@inkeep/open-knowledge 0.27.1-beta.1 → 0.28.0-beta.1
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/THIRD_PARTY_NOTICES.md +24 -9
- package/dist/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +1 -1
- package/dist/awk2-BBAGSFUB-Clvg_OoV.mjs +1 -0
- package/dist/chunk-2TRDZQLB-C2G-sahM.mjs +18 -0
- package/dist/{chunk-UNYNJIFU-HSzsM3a6.mjs → chunk-3BS5SKQH-HZ1-1bfb.mjs} +36 -36
- package/dist/{chunk-YS3AZT3J-DwQ3GyQR.mjs → chunk-3H6UQG3A-DdNaIxPm.mjs} +9 -9
- package/dist/{chunk-XORM457F-CJbQLVgU.mjs → chunk-6Z5SFZXK-C3WlMqq-.mjs} +53 -53
- package/dist/{chunk-YNYSPYQ5-DHter9G3.mjs → chunk-B74TABJS-DlbqoTuk.mjs} +13 -13
- package/dist/{chunk-FEIOJCZD-D6YUa1Xl.mjs → chunk-BGSUD5R5-DQ0_iOyO.mjs} +2 -2
- package/dist/{chunk-F55TLFGB-AEzanSfe.mjs → chunk-DBKNVD4L-BVx-WyDG.mjs} +2 -2
- package/dist/{chunk-BRGMQKJV-DtyxDw61.mjs → chunk-HKLCLINH-DwmCAW4U.mjs} +16 -16
- package/dist/chunk-HL6NGDO2-978327U5.mjs +24 -0
- package/dist/{chunk-LPQPILI2-GOcK96AE.mjs → chunk-K6LIBGJA-DpjaSGfc.mjs} +2 -2
- package/dist/{chunk-BBXLRYSX-OVlWa2B-.mjs → chunk-KRBPSX3W-nYEMVABW.mjs} +2 -2
- package/dist/chunk-KX3P26DQ-Cli1PSKS.mjs +2 -0
- package/dist/{chunk-SYMJJMQ4-DUF5hY-A.mjs → chunk-PXTK5WE2-B17f9YTq.mjs} +1 -1
- package/dist/{chunk-J642UCRS-C1PS8Hwf.mjs → chunk-SNN4IESC-C-P75V1I.mjs} +2 -2
- package/dist/chunk-TP4BZANS-eJW0TOjs.mjs +21 -0
- package/dist/{chunk-YFG2CMIF-DBRGs_rZ.mjs → chunk-V5MWI2OL-CDEVEp7K.mjs} +2 -2
- package/dist/chunk-XKWWSDBF-XuPgN5BP.mjs +37 -0
- package/dist/{chunk-NYQYO467-KfHLMnUW.mjs → chunk-YMMW5UAP-uYgeXT56.mjs} +5 -5
- package/dist/chunk-YULBWSET-BYBVdNmi.mjs +14 -0
- package/dist/{chunk-OL3S66CO-CBdL6pp1.mjs → chunk-ZZO3UDB3-CdVtmXn4.mjs} +2 -2
- package/dist/cli.mjs +7 -7
- package/dist/constants-BnzVSpjR.mjs +2 -0
- package/dist/{dist-CgMyk9vp.mjs → dist-BSd2Ezzl.mjs} +1 -1
- package/dist/{dist-C_yx5tj0.mjs → dist-CPsLcVzP.mjs} +153 -153
- package/dist/expansion-VBDYWVZR-k3W3Rc7R.mjs +1 -0
- package/dist/expr-YYCVMXE3-CHnBeIXW.mjs +1 -0
- package/dist/file-IGDTDPLG-DQaFkvTu.mjs +1 -0
- package/dist/find-DH2ALKQS-6y8KktlA.mjs +1 -0
- package/dist/{flag-coverage-QT4N2Z44-BlPYKPtd.mjs → flag-coverage-6JEX67RU-BqC6mFKB.mjs} +2 -2
- package/dist/grep-2HUTXO5U-Dbnjl3Iq.mjs +1 -0
- package/dist/index.d.mts +30 -1
- package/dist/index.mjs +1 -1
- package/dist/{init-JVcJVxEY.mjs → init-CqjCm8Nv.mjs} +24 -24
- package/dist/init-DNwD_Pli.mjs +1 -0
- package/dist/jq-LYZFFBZB-CSF_TJhe.mjs +1 -0
- package/dist/{js-exec-M6UR76J5-ZESSNIAK.mjs → js-exec-VXN6TZ7U-fCXuAS2-.mjs} +2 -2
- package/dist/loader-B8SvxN0m.mjs +1 -0
- package/dist/{loader-ixEy1_13.mjs → loader-C6DwSh1a.mjs} +2 -2
- package/dist/{preview-Cv6PfUmC.mjs → preview-CPq8NQ67.mjs} +2 -2
- package/dist/preview-wdPR6Env.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-C5aUKw04.js → ActivityModeContent-FXULq3P6.js} +1 -1
- package/dist/public/assets/DocumentContext-AziEfQFy.js +36 -0
- package/dist/public/assets/{EnableSyncConfirmDialog-CM7n_hoC.js → EnableSyncConfirmDialog-D8UuFHxQ.js} +1 -1
- package/dist/public/assets/{GraphPanel-CTza81SW.js → GraphPanel-CHb0qJOI.js} +2 -2
- package/dist/public/assets/{ManagedArtifactProperties-CWVjllTE.js → ManagedArtifactProperties-70ooWd7O.js} +1 -1
- package/dist/public/assets/{McpConsentDialogBody-DEYxioBK.js → McpConsentDialogBody-BKvKmtg_.js} +1 -1
- package/dist/public/assets/PropertyPanel-Cq1sqsH4.js +2 -0
- package/dist/public/assets/SettingsDialogBody-BX4GP2gS.js +7 -0
- package/dist/public/assets/{ShareBranchSwitchDialog-CiPv0nQI.js → ShareBranchSwitchDialog-Clk_4Io5.js} +1 -1
- package/dist/public/assets/{ShareReceiveDialog-Cqyj-wkq.js → ShareReceiveDialog-BDmjkthD.js} +1 -1
- package/dist/public/assets/{ShareReceiveMissDialog-FpCznbtQ.js → ShareReceiveMissDialog-Ds4kHbjr.js} +1 -1
- package/dist/public/assets/{SkillEditorActions-Ccafet7G.js → SkillEditorActions-pVw4b49f.js} +1 -1
- package/dist/public/assets/SourceEditor-DXcSGXCG.js +2 -0
- package/dist/public/assets/{TerminalPanel-EQQLq46y.js → TerminalPanel-Cfp4xEGm.js} +3 -3
- package/dist/public/assets/{auth-state-cache-Bc_I9bTu.js → auth-state-cache-De8QvFee.js} +3 -3
- package/dist/public/assets/{config-provider-CEZVcaXZ.js → config-provider-DY1ejnq-.js} +1 -1
- package/dist/public/assets/{dist-CNSnGZ9C.js → dist-BQeT9ICH.js} +41 -41
- package/dist/public/assets/{doc-hash-DgyRTkQv.js → doc-hash-eLdowlcO.js} +1 -1
- package/dist/public/assets/{documents-events-DnqtZXe7.js → documents-events-DftWTO_p.js} +1 -1
- package/dist/public/assets/{file-tree-adapter-CRZV1_Rs.js → file-tree-adapter-BHXYt6U1.js} +1 -1
- package/dist/public/assets/index-Br8R5akq.js +2003 -0
- package/dist/public/assets/keyboard-shortcuts-C5JAtPtb.js +1 -0
- package/dist/public/assets/{navigation-targets-DYgvWZ49.js → navigation-targets-fzjpgS0d.js} +1 -1
- package/dist/public/assets/{open-managed-artifact-tab-CIoFOyAR.js → open-managed-artifact-tab-BiLs1dgV.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-BDS56-vQ.js → pending-receive-nav-store-eEQMXb1T.js} +1 -1
- package/dist/public/assets/{prop-types-s-LFwB3O.js → prop-types-DVWxeasv.js} +1 -1
- package/dist/public/assets/{receive-store-C29GivX_.js → receive-store-Ckz3u5Dv.js} +1 -1
- package/dist/public/assets/{selection-context-BCk-SXA9.js → selection-context-DaymKQhd.js} +1 -1
- package/dist/public/assets/{skill-actions-jPAfbBub.js → skill-actions-CBRvSwTx.js} +1 -1
- package/dist/public/assets/{skills-api-DuXrVXK8.js → skills-api-c0dJMBt0.js} +1 -1
- package/dist/public/assets/{target-navigation-intent-D1jqbtay.js → target-navigation-intent-DJtJaVBl.js} +1 -1
- package/dist/public/assets/{typing-burst-detector--cTSnkpJ.js → typing-burst-detector-fx0Rb57X.js} +3 -3
- package/dist/public/index.html +21 -21
- package/dist/{python3-AUFTPCU6-B7_jrPM3.mjs → python3-DNGS4G3E-bGzU9nm-.mjs} +2 -2
- package/dist/{repair-launch-json-DjycVQkK.mjs → repair-launch-json-Bx6AIRnT.mjs} +2 -2
- package/dist/repair-mcp-configs-C0PHLK4Q.mjs +2 -0
- package/dist/repair-skills-D5IllzJm.mjs +3 -0
- package/dist/repair-skills-J5Ty5dNP.mjs +1 -0
- package/dist/rg-XNF3R3II-ivb6d3Sm.mjs +1 -0
- package/dist/sed-JAPPVBEU-BvDbOHs0.mjs +1 -0
- package/dist/{sqlite3-56UMWEY3-DNmhrHQv.mjs → sqlite3-TE5AIOTF-DW7pT7NE.mjs} +1 -1
- package/dist/{src-BF8Wntv3.mjs → src-Cvy2rszo.mjs} +3 -3
- package/dist/start-Dp2rloGz.mjs +1 -0
- package/dist/{start-C7JWIgQb.mjs → start-aKZT__Ag.mjs} +2 -2
- package/dist/tar-MZQD7NO4-46pC0DHj.mjs +1 -0
- package/dist/{write-project-skill-GLroKiE7.mjs → write-project-skill-f17OygUR.mjs} +3 -3
- package/dist/xan-UD7JYIL2-DnWVVFeC.mjs +1 -0
- package/dist/xan-view-OW2TB7Z3-DBl8NjSB.mjs +1 -0
- package/dist/yq-OAKYHSXH-CpYttz-E.mjs +1 -0
- package/package.json +1 -1
- package/dist/awk2-POPGKRAI-6Q9HKhoL.mjs +0 -1
- package/dist/chunk-CR5AFCPT-BD_awIEP.mjs +0 -24
- package/dist/chunk-HWBSOZZR-DaPTwPxK.mjs +0 -37
- package/dist/chunk-OARHFVLG-Csb_cJVS.mjs +0 -21
- package/dist/chunk-VLGZJRPG-CHtdu0KZ.mjs +0 -17
- package/dist/chunk-XHM67O4N-2lBQUjKO.mjs +0 -2
- package/dist/chunk-YCFVLTST-CKzPj8PR.mjs +0 -13
- package/dist/constants-KS-9Bzpo.mjs +0 -2
- package/dist/expansion-ENLSRCXJ-C5xjxYTl.mjs +0 -1
- package/dist/expr-5T3UU5KE-DrJUreFq.mjs +0 -1
- package/dist/file-ZIGAJ4YS-D07ChhI1.mjs +0 -1
- package/dist/find-TPUOAIUQ-ZPOxwUwf.mjs +0 -1
- package/dist/grep-3AIAIJVR-Bh6KBg6d.mjs +0 -1
- package/dist/init-rHPP9Y_Z.mjs +0 -1
- package/dist/jq-ODXZBPLY-D3tmTL1R.mjs +0 -1
- package/dist/loader-DdezjzEN.mjs +0 -1
- package/dist/preview-CygJcmSs.mjs +0 -1
- package/dist/public/assets/DocumentContext-cOp7rOof.js +0 -36
- package/dist/public/assets/PropertyPanel-CUfe4JDc.js +0 -2
- package/dist/public/assets/SettingsDialogBody-Bdcmgui3.js +0 -7
- package/dist/public/assets/SourceEditor-BjxKq1og.js +0 -2
- package/dist/public/assets/index-CVsw5c62.js +0 -2003
- package/dist/public/assets/keyboard-shortcuts-DWlSJLXo.js +0 -1
- package/dist/repair-mcp-configs-y4y4K-24.mjs +0 -2
- package/dist/repair-skills-B-VIYM77.mjs +0 -1
- package/dist/repair-skills-DJmyw_aE.mjs +0 -3
- package/dist/rg-FOQSCCX3-ViKChHv5.mjs +0 -1
- package/dist/sed-VFTTATXJ-BfHBQ11q.mjs +0 -1
- package/dist/start-KHoZRBpK.mjs +0 -1
- package/dist/tar-ANUBEFJY-Db9qg5B2.mjs +0 -1
- package/dist/xan-BXDXYEIB-I8yansvE.mjs +0 -1
- package/dist/xan-view-ECQUO7AJ-DJhdCPf3.mjs +0 -1
- package/dist/yq-MJMAR36V-BXyMiYfX.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as __require$2,n as __esmMin,o as __toCommonJS,r as __exportAll,s as __toESM$2,t as __commonJSMin$2}from"./chunk-C94x7I9S.mjs";import{$ as CLIENT_VERSION_HEADER,$a as isValidAttachmentFolderPath,$i as parseSkillTargets,$n as SkillDeleteSuccessSchema,$r as UA_PATTERNS,$t as LocalOpEmbeddingsSetKeyRequestSchema,A as AgentWriteMdRequestSchema,Aa as fnv1aDigest,Ai as formatFileSize,An as SKILL_STATE_VERSION_RE,Ar as SyncConflictsSuccessSchema,At as FolderConfigPutRequestSchema,B as BrokenLinkSchema,Ba as EXECUTABLE_BLOCKLIST_EXTENSIONS,Bn as SeedApplySuccessSchema,Bo as clone,Br as TemplateDeleteSuccessSchema,Bt as INSTALLED_SKILLS_REL,C as AdvisoryWarningSchema,Ca as toWikiLinkSlug,Ci as displayNameFromClientName,Cn as RescueListSuccessSchema,Co as record,Cr as SkillUpdateRequestSchema,Ct as DuplicatePathSuccessSchema,D as AgentPatchSuccessSchema,Da as getSchema,Di as encodeShareUrl,Dn as SKILL_NAME_REGEX,Dr as StreamingProblemEventSchema,Dt as EmbedDetectSuccessSchema,E as AgentPatchRequestSchema,Ea as withFences,Ei as emptySkillState,En as SKILL_CONTENT_ROOT,Eo as unknown,Er as SpawnCursorSuccessSchema,Et as EDITOR_PROJECT_SKILL_ROOT,F as BacklinkCountsSuccessSchema,Fa as DEFAULT_EMBEDDINGS_BASE_URL,Fi as iconFromClientName,Fn as SaveVersionRequestSchema,Fo as parse$1,Fr as SyncTriggerSuccessSchema,Ft as FrontmatterValueSchema,G as CC1DiskAckPayloadSchema,Gi as managedArtifactDocNameFromContentTarget,Gn as ShareConstructUrlRequestSchema,Go as require_dist$1,Gr as TemplatePutSuccessSchema,Gt as LINEAGE_EPOCH_KEY,H as CC1ConfigIgnoreNestedErrorPayloadSchema,Ha as LINKABLE_ASSET_EXTENSIONS,Hi as isOrphanMode,Hn as SeedPlanSuccessSchema,Ho as normalizeParams,Hr as TemplateMoveRequestSchema,Ht as InstallSkillSuccessSchema,I as BacklinksSuccessSchema,Ia as DEFAULT_EMBEDDINGS_MODEL,Ii as instantiateDoc,In as SaveVersionSuccessSchema,Io as parseAsync,Ir as TEMPLATE_IDENTITY_KEY,J as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Ja as addConfigSpanEvent,Ji as parseFrontmatterYaml,Jn as SharePublishOwnersResponseSchema,Jr as TestRescanBacklinksSuccessSchema,Jt as LocalOpAuthHostRequestSchema,K as CC1ServerInfoPayloadSchema,Ka as SANDBOXED_HTML_CSP,Ki as mergeThreeWay,Kn as ShareConstructUrlResponseSchema,Kr as TemplatesListSuccessSchema,Kt as LinkGraphSuccessSchema,L as BranchInfoResponseSchema,La as DEFAULT_LOGS_MAX_BYTES,Li as isBranchNotFoundGitError,Ln as SearchRequestSchema,Lo as safeParse$1,Lr as TEMPLATE_NAME_REGEX,Lt as HistorySuccessSchema,M as AgentWriteRequestSchema,Ma as CONFIG_SCHEMA_MAJOR_PATH,Mi as getHeadingSlug,Mo as meta$1,Mr as SyncResolveConflictSuccessSchema,Mt as ForwardLinksSuccessSchema,N as AgentWriteSuccessSchema,Na as ConfigSchema$1,Ni as getParseHealth,Nn as SUPPORTED_DOC_EXTENSIONS,No as $ZodObject,Nr as SyncStatusSchema,Nt as FrontmatterPatchRequestSchema,O as AgentUndoRequestSchema,Oa as PluginKey,Oi as expandTagToHierarchy,On as SKILL_STATE_REL,Oo as datetime,Or as SuggestLinksSuccessSchema,Ot as EmptyRequestSchema,P as ApiConfigSuccessSchema,Pa as DEFAULT_DEDUP_MODE,Pi as getWikiLinkText,Pn as SYSTEM_DOC_NAME,Po as $ZodType,Pr as SyncTriggerRequestSchema,Pt as FrontmatterPatchSuccessSchema,Q as CC1_CONTRACT_VERSION,Qa as isKnownConfigError,Qi as parseProjectSkillBundleDoc,Qn as ShareTargetStatusResponseSchema,Qr as TrashCleanupSuccessSchema,Qt as LocalOpEmbeddingsMutationSuccessSchema,R as BridgeInvariantViolationError,Ra as DEFAULT_SPANS_MAX_BYTES,Ri as isFrontmatterValueEmpty,Rn as SearchSuccessSchema,Ro as safeParseAsync$1,Rr as TagsForNameSuccessSchema,Rt as HistoryVersionSuccessSchema,Sa as toBridgeInvariantLog,Si as detectFmRegion,Sn as RenamePathSuccessSchema,So as preprocess,Sr as SkillUninstallSuccessSchema,St as DuplicatePathRequestSchema,T as AgentBurstDiffSuccessSchema,Ta as validateDocName,Ti as emptyInstalledSkills,Tn as RollbackSuccessSchema,To as union,Tr as SkillsListSuccessSchema,Tt as EDITOR_PROJECT_CONFIG_PATH,U as CC1ConfigValidationRejectedPayloadSchema,Ua as LOCAL_DIR,Ui as isParseEquivalentBridge,Un as SemanticIndexStatusSchema,Uo as $constructor,Ur as TemplateMoveSuccessSchema,Ut as InstalledAgentsSuccessSchema,V as CC1BranchSwitchedPayloadSchema,Va as INLINE_RENDERABLE_EXTENSIONS,Vi as isManagedArtifactDocName,Vn as SeedListPacksSuccessSchema,Vo as defineLazy,Vr as TemplateGetSuccessSchema,Vt as InstallSkillRequestSchema,W as CC1DerivedViewPayloadSchema,Wa as OK_PROJECT_MARKER,Wi as isValidBranchName,Wn as ServerInfoSuccessSchema,Wr as TemplatePutRequestSchema,Wt as InstalledSkillsSchema,X as CC1_CHANNEL_DISK_ACK,Xa as detectRemovedKeys,Xi as parseInstalledSkills,Xn as SharePublishResponseSchema,Xr as TestResetSuccessSchema,Xt as LocalOpAuthStatusSuccessSchema,Y as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Ya as applyPatchToDocument,Yi as parseGlobalSkillBundleDoc,Yn as SharePublishRequestSchema,Yr as TestRescanFilesSuccessSchema,Yt as LocalOpAuthSetIdentityRequestSchema,Z as CC1_CHANNEL_SERVER_INFO,Za as humanFormat,Zi as parseManagedArtifactName,Zn as ShareTargetStatusRequestSchema,Zr as TrashCleanupRequestSchema,Zt as LocalOpCloneRequestSchema,_ as releaseServerLock,_i as createTagInTextRegex,_n as PageHeadingsSuccessSchema,_o as literal,_r as SkillTargetsGetSuccessSchema,_t as DeadLinksSuccessSchema,a as acquireProcessLock,aa as projectSkillContentDocName,ai as applyPatchToFm,an as MCP_SERVER_NAME,ao as withConfigSpan,ar as SkillInstallRequestSchema,at as CheckoutRequestSchema,ba as stripFrontmatter,bi as defaultScheduler,bn as ProblemDetailsSchema,bo as object$1,br as SkillTargetsSchema,bt as DocumentListSuccessSchema,c as isProcessAlive,ca as renderInventoryFooter,ci as classifyMarkdownHref,cn as MetricsParseHealthSuccessSchema,co as ZodOptional$1,cr as SkillMoveRequestSchema,ct as ClientLogsSuccessSchema,d as markProcessLockDraining,da as resolveInternalHref,di as colorFromSeed,dn as OrphansSuccessSchema,dr as SkillPutSuccessSchema,dt as CreatePageRequestSchema,ea as parseTemplateFile,ei as UploadAssetSuccessSchema,en as LocalOpOkInitRequestSchema,eo as locateIssue,er as SkillFileDeleteSuccessSchema,et as CONFIG_DOC_NAMES,f as markServerLockDraining,fa as resolveSkillBundleWikiTarget,fi as comparePmStructural,fn as PARSE_EQUIVALENCE_TOLERANCE,fo as array,fr as SkillRestoreRequestSchema,ft as CreatePageSuccessSchema,g as releaseProcessLock,ga as sharedExtensions,gi as createCodeFenceTracker,gn as PROTOCOL_VERSION,go as intersection,gr as SkillTargetEditorSchema,gt as DOCUMENT_OPEN_BYTE_LIMIT,h as readServerLock,ha as setToleranceTelemetryHook,hi as createBasenameIndex,hn as PROJECT_SKILL_EDITOR_IDS,ho as discriminatedUnion,hr as SkillStateSchema,ia as projectMergeBoundarySpace,ii as applyIncrementalDiff,in as MANAGED_ARTIFACT_SCOPES,io as validatePatchScopes,ir as SkillGetSuccessSchema,it as CONFIG_DOC_NAME_USER,j as AgentWriteMdSuccessSchema,ja as ASSET_EXTENSIONS,ji as getAgentCanonicalDescriptors,jn as SKILL_TARGETS_REL,jo as describe$1,jr as SyncResolveConflictRequestSchema,jt as FolderConfigPutSuccessSchema,k as AgentUndoSuccessSchema,ka as Fragment,ki as extractFrontmatterTags,kn as SKILL_STATE_TARGETS,ko as toJSONSchema,kr as SyncConflictContentSuccessSchema,kt as FolderConfigGetSuccessSchema,l as isValidLockPid,la as resolveAssetProjectPath,li as classifyWikiLinkTarget,ln as MetricsReconciliationSuccessSchema,lo as _enum,lr as SkillMoveSuccessSchema,lt as CreateFolderRequestSchema,ma as serializeFrontmatterMap,mi as containsXmlTag,mn as PREVIEW_THEME_TOKENS,mo as custom,mr as SkillScopeSchema,n as RUNTIME_VERSION,na as previewEmbedFence,ni as WorkspaceSuccessSchema,nn as MANAGED_ARTIFACT_PREFIX_SKILL,no as normalizeAttachmentFolderPath,nr as SkillFilePutRequestSchema,nt as CONFIG_DOC_NAME_PROJECT,o as acquireServerLock,oa as readFmMap,oi as assertNeverProblemType,on as MarkdownManager,oo as withConfigSpanSync,or as SkillInstallStateSuccessSchema,ot as CheckoutResponseSchema,p as readProcessLock,pa as searchWorkspaceCorpus,pi as composeTemplateFile,pn as PREVIEW_EMBED_STARTERS,po as boolean,pr as SkillRestoreSuccessSchema,q as CC1_CHANNEL_BRANCH_SWITCHED,qa as SANDBOXED_HTML_EXTENSIONS,qi as normalizeBridge,qn as SharePublishNameCheckResponseSchema,qr as TestFlushGitSuccessSchema,qt as LocalOpAuthEmptySuccessSchema,ra as projectFull,ri as applyFastDiff,rn as MANAGED_ARTIFACT_PREFIX_TEMPLATE,ro as toConfigIssue,rr as SkillFilePutSuccessSchema,rt as CONFIG_DOC_NAME_PROJECT_LOCAL,sa as reattachLeadingDocBoundary,si as classifyGitAuthError,sn as MetricsAgentPresenceSuccessSchema,sr as SkillInstallSuccessSchema,st as ClientLogsRequestSchema,t as ProcessLockCollisionError,ta as prependFrontmatter,ti as UploadRequestSchema,tn as LocalOpOkInitResponseSchema,to as mediaKindForSidebarAssetExtension,tr as SkillFileGetSuccessSchema,tt as CONFIG_DOC_NAME_OKIGNORE,un as ORPHAN_MODES,uo as _null,ur as SkillPutRequestSchema,ut as CreateFolderSuccessSchema,v as updateProcessLockPort,va as skillLiveDocName,vi as createWorkspaceSearchCorpus,vn as PagesSuccessSchema,vo as looseObject,vr as SkillTargetsPutRequestSchema,vt as DeletePathRequestSchema,w as AgentActivitySuccessSchema,wa as unwrapFrontmatterFences,wi as emitToleranceFire,wn as RollbackRequestSchema,wo as string,wr as SkillUpdateSuccessSchema,x as AGENT_ICON_COLORS,xa as tagsMatchingPrefix,xi as detectAppliedToleranceClasses,xn as RenamePathRequestSchema,xo as optional,xr as SkillUninstallRequestSchema,xt as DocumentReadSuccessSchema,ya as splitLeadingDocBoundary,yi as createWorkspaceSearchDocument,yn as PrincipalSuccessSchema,yo as number,yr as SkillTargetsPutSuccessSchema,yt as DeletePathSuccessSchema,z as BridgeMergeContentLossError,za as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,zi as isHiddenDocName,zn as SeedApplyRequestSchema,zo as prettifyError,zr as TagsListSuccessSchema,zt as HubsSuccessSchema}from"./server-lock-iLcBw_q0-D_cD26E0.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-BQ4-CT8p.mjs";import{a as esm_default,i as withParentLock,n as createGitInstance,o as simpleGit,r as splitNulSeparatedPaths,s as require_src$15,t as applyGitEnv}from"./git-handle-Bhgrj9qX-DBwQr-02.mjs";import{t as createPatch}from"./libesm-_Wi8iuGI.mjs";import{n as mimes,t as build_default}from"./build-CCNlCFyu.mjs";import{t as require_yazl}from"./yazl-DgCFuIuD.mjs";import{t as b1}from"./chunk-YNYSPYQ5-DHter9G3.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-DigWkxW2.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-D6YUa1Xl.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-2lBQUjKO.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-XKIhMSUi.mjs";import{r as o$1}from"./chunk-CWQS3NFK-DNm_iIwd.mjs";import"./chunk-DXB73IDG-Bx-Ikbnu.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-_0tQyQsf.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-Kbs3GRxW.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-LGuZyK6R.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-BoP5OA93.mjs";import{n as n$1}from"./chunk-3THT3N7L-CBWmNncQ.mjs";import{t as n$2}from"./chunk-44UOCSGV-B6GSHp1s.mjs";import{t as import_websocket_server$1}from"./wrapper-CGw3ogaz.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import{basename,delimiter,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{homedir,hostname,platform,tmpdir}from"node:os";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,readlinkSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,symlinkSync,unlinkSync,writeFileSync}from"node:fs";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";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$2 from"crypto";import*as zlib 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 GIT_AUTHOR_WRITER_PREFIX=`git-author-`;function gitAuthorWriterId(e){return`${GIT_AUTHOR_WRITER_PREFIX}${fnv1aDigest(e.trim().toLowerCase())}`}const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|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 __require$2,n as __esmMin,o as __toCommonJS,r as __exportAll,s as __toESM$2,t as __commonJSMin$2}from"./chunk-C94x7I9S.mjs";import{$ as CLIENT_VERSION_HEADER,$a as isValidAttachmentFolderPath,$i as parseSkillTargets,$n as SkillDeleteSuccessSchema,$r as UA_PATTERNS,$t as LocalOpEmbeddingsSetKeyRequestSchema,A as AgentWriteMdRequestSchema,Aa as fnv1aDigest,Ai as formatFileSize,An as SKILL_STATE_VERSION_RE,Ar as SyncConflictsSuccessSchema,At as FolderConfigPutRequestSchema,B as BrokenLinkSchema,Ba as EXECUTABLE_BLOCKLIST_EXTENSIONS,Bn as SeedApplySuccessSchema,Bo as clone,Br as TemplateDeleteSuccessSchema,Bt as INSTALLED_SKILLS_REL,C as AdvisoryWarningSchema,Ca as toWikiLinkSlug,Ci as displayNameFromClientName,Cn as RescueListSuccessSchema,Co as record,Cr as SkillUpdateRequestSchema,Ct as DuplicatePathSuccessSchema,D as AgentPatchSuccessSchema,Da as getSchema,Di as encodeShareUrl,Dn as SKILL_NAME_REGEX,Dr as StreamingProblemEventSchema,Dt as EmbedDetectSuccessSchema,E as AgentPatchRequestSchema,Ea as withFences,Ei as emptySkillState,En as SKILL_CONTENT_ROOT,Eo as unknown,Er as SpawnCursorSuccessSchema,Et as EDITOR_PROJECT_SKILL_ROOT,F as BacklinkCountsSuccessSchema,Fa as DEFAULT_EMBEDDINGS_BASE_URL,Fi as iconFromClientName,Fn as SaveVersionRequestSchema,Fo as parse$1,Fr as SyncTriggerSuccessSchema,Ft as FrontmatterValueSchema,G as CC1DiskAckPayloadSchema,Gi as managedArtifactDocNameFromContentTarget,Gn as ShareConstructUrlRequestSchema,Go as require_dist$1,Gr as TemplatePutSuccessSchema,Gt as LINEAGE_EPOCH_KEY,H as CC1ConfigIgnoreNestedErrorPayloadSchema,Ha as LINKABLE_ASSET_EXTENSIONS,Hi as isOrphanMode,Hn as SeedPlanSuccessSchema,Ho as normalizeParams,Hr as TemplateMoveRequestSchema,Ht as InstallSkillSuccessSchema,I as BacklinksSuccessSchema,Ia as DEFAULT_EMBEDDINGS_MODEL,Ii as instantiateDoc,In as SaveVersionSuccessSchema,Io as parseAsync,Ir as TEMPLATE_IDENTITY_KEY,J as CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,Ja as addConfigSpanEvent,Ji as parseFrontmatterYaml,Jn as SharePublishOwnersResponseSchema,Jr as TestRescanBacklinksSuccessSchema,Jt as LocalOpAuthHostRequestSchema,K as CC1ServerInfoPayloadSchema,Ka as SANDBOXED_HTML_CSP,Ki as mergeThreeWay,Kn as ShareConstructUrlResponseSchema,Kr as TemplatesListSuccessSchema,Kt as LinkGraphSuccessSchema,L as BranchInfoResponseSchema,La as DEFAULT_LOGS_MAX_BYTES,Li as isBranchNotFoundGitError,Ln as SearchRequestSchema,Lo as safeParse$1,Lr as TEMPLATE_NAME_REGEX,Lt as HistorySuccessSchema,M as AgentWriteRequestSchema,Ma as CONFIG_SCHEMA_MAJOR_PATH,Mi as getHeadingSlug,Mo as meta$1,Mr as SyncResolveConflictSuccessSchema,Mt as ForwardLinksSuccessSchema,N as AgentWriteSuccessSchema,Na as ConfigSchema$1,Ni as getParseHealth,Nn as SUPPORTED_DOC_EXTENSIONS,No as $ZodObject,Nr as SyncStatusSchema,Nt as FrontmatterPatchRequestSchema,O as AgentUndoRequestSchema,Oa as PluginKey,Oi as expandTagToHierarchy,On as SKILL_STATE_REL,Oo as datetime,Or as SuggestLinksSuccessSchema,Ot as EmptyRequestSchema,P as ApiConfigSuccessSchema,Pa as DEFAULT_DEDUP_MODE,Pi as getWikiLinkText,Pn as SYSTEM_DOC_NAME,Po as $ZodType,Pr as SyncTriggerRequestSchema,Pt as FrontmatterPatchSuccessSchema,Q as CC1_CONTRACT_VERSION,Qa as isKnownConfigError,Qi as parseProjectSkillBundleDoc,Qn as ShareTargetStatusResponseSchema,Qr as TrashCleanupSuccessSchema,Qt as LocalOpEmbeddingsMutationSuccessSchema,R as BridgeInvariantViolationError,Ra as DEFAULT_SPANS_MAX_BYTES,Ri as isFrontmatterValueEmpty,Rn as SearchSuccessSchema,Ro as safeParseAsync$1,Rr as TagsForNameSuccessSchema,Rt as HistoryVersionSuccessSchema,Sa as toBridgeInvariantLog,Si as detectFmRegion,Sn as RenamePathSuccessSchema,So as preprocess,Sr as SkillUninstallSuccessSchema,St as DuplicatePathRequestSchema,T as AgentBurstDiffSuccessSchema,Ta as validateDocName,Ti as emptyInstalledSkills,Tn as RollbackSuccessSchema,To as union,Tr as SkillsListSuccessSchema,Tt as EDITOR_PROJECT_CONFIG_PATH,U as CC1ConfigValidationRejectedPayloadSchema,Ua as LOCAL_DIR,Ui as isParseEquivalentBridge,Un as SemanticIndexStatusSchema,Uo as $constructor,Ur as TemplateMoveSuccessSchema,Ut as InstalledAgentsSuccessSchema,V as CC1BranchSwitchedPayloadSchema,Va as INLINE_RENDERABLE_EXTENSIONS,Vi as isManagedArtifactDocName,Vn as SeedListPacksSuccessSchema,Vo as defineLazy,Vr as TemplateGetSuccessSchema,Vt as InstallSkillRequestSchema,W as CC1DerivedViewPayloadSchema,Wa as OK_PROJECT_MARKER,Wi as isValidBranchName,Wn as ServerInfoSuccessSchema,Wr as TemplatePutRequestSchema,Wt as InstalledSkillsSchema,X as CC1_CHANNEL_DISK_ACK,Xa as detectRemovedKeys,Xi as parseInstalledSkills,Xn as SharePublishResponseSchema,Xr as TestResetSuccessSchema,Xt as LocalOpAuthStatusSuccessSchema,Y as CC1_CHANNEL_CONFIG_VALIDATION_REJECTED,Ya as applyPatchToDocument,Yi as parseGlobalSkillBundleDoc,Yn as SharePublishRequestSchema,Yr as TestRescanFilesSuccessSchema,Yt as LocalOpAuthSetIdentityRequestSchema,Z as CC1_CHANNEL_SERVER_INFO,Za as humanFormat,Zi as parseManagedArtifactName,Zn as ShareTargetStatusRequestSchema,Zr as TrashCleanupRequestSchema,Zt as LocalOpCloneRequestSchema,_ as releaseServerLock,_i as createTagInTextRegex,_n as PageHeadingsSuccessSchema,_o as literal,_r as SkillTargetsGetSuccessSchema,_t as DeadLinksSuccessSchema,a as acquireProcessLock,aa as projectSkillContentDocName,ai as applyPatchToFm,an as MCP_SERVER_NAME,ao as withConfigSpan,ar as SkillInstallRequestSchema,at as CheckoutRequestSchema,ba as stripFrontmatter,bi as defaultScheduler,bn as ProblemDetailsSchema,bo as object$1,br as SkillTargetsSchema,bt as DocumentListSuccessSchema,c as isProcessAlive,ca as renderInventoryFooter,ci as classifyMarkdownHref,cn as MetricsParseHealthSuccessSchema,co as ZodOptional$1,cr as SkillMoveRequestSchema,ct as ClientLogsSuccessSchema,d as markProcessLockDraining,da as resolveInternalHref,di as colorFromSeed,dn as OrphansSuccessSchema,dr as SkillPutSuccessSchema,dt as CreatePageRequestSchema,ea as parseTemplateFile,ei as UploadAssetSuccessSchema,en as LocalOpOkInitRequestSchema,eo as locateIssue,er as SkillFileDeleteSuccessSchema,et as CONFIG_DOC_NAMES,f as markServerLockDraining,fa as resolveSkillBundleWikiTarget,fi as comparePmStructural,fn as PARSE_EQUIVALENCE_TOLERANCE,fo as array,fr as SkillRestoreRequestSchema,ft as CreatePageSuccessSchema,g as releaseProcessLock,ga as sharedExtensions,gi as createCodeFenceTracker,gn as PROTOCOL_VERSION,go as intersection,gr as SkillTargetEditorSchema,gt as DOCUMENT_OPEN_BYTE_LIMIT,h as readServerLock,ha as setToleranceTelemetryHook,hi as createBasenameIndex,hn as PROJECT_SKILL_EDITOR_IDS,ho as discriminatedUnion,hr as SkillStateSchema,ia as projectMergeBoundarySpace,ii as applyIncrementalDiff,in as MANAGED_ARTIFACT_SCOPES,io as validatePatchScopes,ir as SkillGetSuccessSchema,it as CONFIG_DOC_NAME_USER,j as AgentWriteMdSuccessSchema,ja as ASSET_EXTENSIONS,ji as getAgentCanonicalDescriptors,jn as SKILL_TARGETS_REL,jo as describe$1,jr as SyncResolveConflictRequestSchema,jt as FolderConfigPutSuccessSchema,k as AgentUndoSuccessSchema,ka as Fragment,ki as extractFrontmatterTags,kn as SKILL_STATE_TARGETS,ko as toJSONSchema,kr as SyncConflictContentSuccessSchema,kt as FolderConfigGetSuccessSchema,l as isValidLockPid,la as resolveAssetProjectPath,li as classifyWikiLinkTarget,ln as MetricsReconciliationSuccessSchema,lo as _enum,lr as SkillMoveSuccessSchema,lt as CreateFolderRequestSchema,ma as serializeFrontmatterMap,mi as containsXmlTag,mn as PREVIEW_THEME_TOKENS,mo as custom,mr as SkillScopeSchema,n as RUNTIME_VERSION,na as previewEmbedFence,ni as WorkspaceSuccessSchema,nn as MANAGED_ARTIFACT_PREFIX_SKILL,no as normalizeAttachmentFolderPath,nr as SkillFilePutRequestSchema,nt as CONFIG_DOC_NAME_PROJECT,o as acquireServerLock,oa as readFmMap,oi as assertNeverProblemType,on as MarkdownManager,oo as withConfigSpanSync,or as SkillInstallStateSuccessSchema,ot as CheckoutResponseSchema,p as readProcessLock,pa as searchWorkspaceCorpus,pi as composeTemplateFile,pn as PREVIEW_EMBED_STARTERS,po as boolean,pr as SkillRestoreSuccessSchema,q as CC1_CHANNEL_BRANCH_SWITCHED,qa as SANDBOXED_HTML_EXTENSIONS,qi as normalizeBridge,qn as SharePublishNameCheckResponseSchema,qr as TestFlushGitSuccessSchema,qt as LocalOpAuthEmptySuccessSchema,ra as projectFull,ri as applyFastDiff,rn as MANAGED_ARTIFACT_PREFIX_TEMPLATE,ro as toConfigIssue,rr as SkillFilePutSuccessSchema,rt as CONFIG_DOC_NAME_PROJECT_LOCAL,sa as reattachLeadingDocBoundary,si as classifyGitAuthError,sn as MetricsAgentPresenceSuccessSchema,sr as SkillInstallSuccessSchema,st as ClientLogsRequestSchema,t as ProcessLockCollisionError,ta as prependFrontmatter,ti as UploadRequestSchema,tn as LocalOpOkInitResponseSchema,to as mediaKindForSidebarAssetExtension,tr as SkillFileGetSuccessSchema,tt as CONFIG_DOC_NAME_OKIGNORE,un as ORPHAN_MODES,uo as _null,ur as SkillPutRequestSchema,ut as CreateFolderSuccessSchema,v as updateProcessLockPort,va as skillLiveDocName,vi as createWorkspaceSearchCorpus,vn as PagesSuccessSchema,vo as looseObject,vr as SkillTargetsPutRequestSchema,vt as DeletePathRequestSchema,w as AgentActivitySuccessSchema,wa as unwrapFrontmatterFences,wi as emitToleranceFire,wn as RollbackRequestSchema,wo as string,wr as SkillUpdateSuccessSchema,x as AGENT_ICON_COLORS,xa as tagsMatchingPrefix,xi as detectAppliedToleranceClasses,xn as RenamePathRequestSchema,xo as optional,xr as SkillUninstallRequestSchema,xt as DocumentReadSuccessSchema,ya as splitLeadingDocBoundary,yi as createWorkspaceSearchDocument,yn as PrincipalSuccessSchema,yo as number,yr as SkillTargetsPutSuccessSchema,yt as DeletePathSuccessSchema,z as BridgeMergeContentLossError,za as DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,zi as isHiddenDocName,zn as SeedApplyRequestSchema,zo as prettifyError,zr as TagsListSuccessSchema,zt as HubsSuccessSchema}from"./server-lock-iLcBw_q0-D_cD26E0.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-BQ4-CT8p.mjs";import{a as esm_default,i as withParentLock,n as createGitInstance,o as simpleGit,r as splitNulSeparatedPaths,s as require_src$15,t as applyGitEnv}from"./git-handle-Bhgrj9qX-DBwQr-02.mjs";import{t as createPatch}from"./libesm-_Wi8iuGI.mjs";import{n as mimes,t as build_default}from"./build-CCNlCFyu.mjs";import{t as require_yazl}from"./yazl-DgCFuIuD.mjs";import{t as I1}from"./chunk-B74TABJS-DlbqoTuk.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-DigWkxW2.mjs";import{A as gt$1,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi$1,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,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-BGSUD5R5-DQ0_iOyO.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-KX3P26DQ-Cli1PSKS.mjs";import{n as l$1,r as o,t as h$2}from"./chunk-R6VWJ2ZL-XKIhMSUi.mjs";import{r as o$1}from"./chunk-CWQS3NFK-DNm_iIwd.mjs";import{t as m$2}from"./chunk-DXB73IDG-Bx-Ikbnu.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-_0tQyQsf.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-Kbs3GRxW.mjs";import{n,r,t as c$2}from"./chunk-OJDRYQWQ-LGuZyK6R.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-BoP5OA93.mjs";import{n as n$1}from"./chunk-3THT3N7L-CBWmNncQ.mjs";import{t as n$2}from"./chunk-44UOCSGV-B6GSHp1s.mjs";import{t as import_websocket_server$1}from"./wrapper-CGw3ogaz.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import{basename,delimiter,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import{URLSearchParams as URLSearchParams$1,fileURLToPath}from"node:url";import{homedir,hostname,platform,tmpdir}from"node:os";import*as I from"node:fs";import{appendFileSync,chmodSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFile,readFileSync,readSync,readdirSync,readlinkSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,symlinkSync,unlinkSync,writeFileSync}from"node:fs";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";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$2 from"crypto";import*as zlib 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 GIT_AUTHOR_WRITER_PREFIX=`git-author-`;function gitAuthorWriterId(e){return`${GIT_AUTHOR_WRITER_PREFIX}${fnv1aDigest(e.trim().toLowerCase())}`}const WRITER_ID_RE=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|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===`producer-guard-loss`){let e=w;return typeof e.construct==`string`?{kind:`producer-guard-loss`,docName:E,size:D,metadata:{construct:e.construct}}: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}if(S===`auto-consolidation`){let e=w;return typeof e.foldedRefs==`number`&&Number.isFinite(e.foldedRefs)&&typeof e.trigger==`string`?{kind:`auto-consolidation`,docName:E,size:D,metadata:{foldedRefs:e.foldedRefs,trigger:e.trigger}}: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 parseOkActor(e){if(!e)return null;for(let t of e.split(`
|
|
4
4
|
`)){let e=t.trim();if(!e.startsWith(OK_ACTOR_PREFIX))continue;let s;try{s=JSON.parse(e.slice(10))}catch{return null}return typeof s!=`object`||!s?null:parseOkActorObject(s)}return null}function parseOkActors(e){if(!e)return[];let t=[];for(let s of e.split(`
|
|
@@ -48,42 +48,42 @@ To resolve the conflict:`,(0,g.getConflictResolutionRecipe)(S,e))),w=E):s.diag.w
|
|
|
48
48
|
missingProperty: ${S},
|
|
49
49
|
depsCount: ${s},
|
|
50
50
|
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$1(),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$2);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
|
|
51
|
-
`;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-B99ElfBo.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-Cqi4_PjZ.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-2Mks7IIT.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-CNZ_hN8P.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-Bl16kSBR.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-CFMuhNvO.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-DGiKr2c0.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-F9g7gQHU.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-VqiK1WcH.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-D9pw6nb9.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-Byit-TLI.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-C_dD-tNl.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-m5fzqroZ.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-BMheCA1U.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-DSAed845.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-knoYRbXD.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-Bof613yN.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-DOG39Ce5.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-3AIAIJVR-Bh6KBg6d.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-3AIAIJVR-Bh6KBg6d.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-3AIAIJVR-Bh6KBg6d.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-FOQSCCX3-ViKChHv5.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-VFTTATXJ-BfHBQ11q.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-POPGKRAI-6Q9HKhoL.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-DqMg1dll.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-CiXMC2Qh.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-CTh1BUfn.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-BDAM8WY8.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-C8EyimeA.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-BDNDgux2.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-4azlKYu4.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-Bs_nMrMg.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-Bx5XDGgK.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-Bp3M0RnL.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-BWFllY1p.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-l9kho9ff.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-DqhMcIGL.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-Bg1ZsVDm.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-BMnXfCXQ.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-BgHEibOy.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-TPUOAIUQ-ZPOxwUwf.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-GWPOMupJ.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-VsUIxZwx.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-BK2c44-E.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-Cq3dzRFU.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-CsaomJHQ.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-CsaomJHQ.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-DxvTrQH3.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-DxvTrQH3.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-BwBOMO5i.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-CdKFilDT.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-B6CZ-ZF1.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-B6CZ-ZF1.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-C4DTv-gF.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-C7Yi9aK0.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-C7Yi9aK0.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-ODXZBPLY-D3tmTL1R.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-bqN_UBX0.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-DSY9AfjL.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-nDqDn5ZQ.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-BgSOeH2N.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-aaC7r4sX.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-CXWA3kJ0.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-BaUQfYSh.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-5T3UU5KE-DrJUreFq.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-pTX2tfQd.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-NRAU83Yg.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-Cfe-w5CY.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-ZIGAJ4YS-D07ChhI1.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-D7XdAo13.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-DCBusWam.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-DfnqWxtA.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-DMDGVNTy.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-_qJ9gN13.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-DhtD1OhF.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-DwpkPMHp.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-BtiMTiZG.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-BtiMTiZG.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-BtiMTiZG.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Ye.push({name:`tar`,load:async()=>(await import(`./tar-ANUBEFJY-Db9qg5B2.mjs`)).tarCommand}),Ye.push({name:`yq`,load:async()=>(await import(`./yq-MJMAR36V-BXyMiYfX.mjs`)).yqCommand}),Ye.push({name:`xan`,load:async()=>(await import(`./xan-BXDXYEIB-I8yansvE.mjs`)).xanCommand}),Ye.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-56UMWEY3-DNmhrHQv.mjs`)).sqlite3Command}));var Zt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Zt.push({name:`python3`,load:async()=>(await import(`./python3-AUFTPCU6-B7_jrPM3.mjs`)).python3Command}),Zt.push({name:`python`,load:async()=>(await import(`./python3-AUFTPCU6-B7_jrPM3.mjs`)).pythonCommand}));var qt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(qt.push({name:`js-exec`,load:async()=>(await import(`./js-exec-M6UR76J5-ZESSNIAK.mjs`)).jsExecCommand}),qt.push({name:`node`,load:async()=>(await import(`./js-exec-M6UR76J5-ZESSNIAK.mjs`)).nodeStubCommand}));var sn=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-ClMENMWY.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-BlPYKPtd.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
|
+
`;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-B99ElfBo.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-Cqi4_PjZ.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-2Mks7IIT.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-CNZ_hN8P.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-Bl16kSBR.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-CFMuhNvO.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-DGiKr2c0.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-F9g7gQHU.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-VqiK1WcH.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-D9pw6nb9.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-Byit-TLI.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-C_dD-tNl.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-m5fzqroZ.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-BMheCA1U.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-DSAed845.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-knoYRbXD.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-Bof613yN.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-DOG39Ce5.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-2HUTXO5U-Dbnjl3Iq.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-2HUTXO5U-Dbnjl3Iq.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-2HUTXO5U-Dbnjl3Iq.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-XNF3R3II-ivb6d3Sm.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-JAPPVBEU-BvDbOHs0.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-BBAGSFUB-Clvg_OoV.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-DqMg1dll.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-CiXMC2Qh.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-CTh1BUfn.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-BDAM8WY8.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-C8EyimeA.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-BDNDgux2.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-4azlKYu4.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-Bs_nMrMg.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-Bx5XDGgK.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-Bp3M0RnL.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-BWFllY1p.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-l9kho9ff.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-DqhMcIGL.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-Bg1ZsVDm.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-BMnXfCXQ.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-BgHEibOy.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-DH2ALKQS-6y8KktlA.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-GWPOMupJ.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-VsUIxZwx.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-BK2c44-E.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-Cq3dzRFU.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-CsaomJHQ.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-CsaomJHQ.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-DxvTrQH3.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-DxvTrQH3.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-BwBOMO5i.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-CdKFilDT.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-B6CZ-ZF1.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-B6CZ-ZF1.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-C4DTv-gF.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-C7Yi9aK0.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-C7Yi9aK0.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-LYZFFBZB-CSF_TJhe.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-bqN_UBX0.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-DSY9AfjL.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-nDqDn5ZQ.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-BgSOeH2N.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-aaC7r4sX.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-CXWA3kJ0.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-BaUQfYSh.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-YYCVMXE3-CHnBeIXW.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-pTX2tfQd.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-NRAU83Yg.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-Cfe-w5CY.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-IGDTDPLG-DQaFkvTu.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-D7XdAo13.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-DCBusWam.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-DfnqWxtA.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-DMDGVNTy.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-_qJ9gN13.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-DhtD1OhF.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-DwpkPMHp.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-BtiMTiZG.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-BtiMTiZG.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-BtiMTiZG.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Ye.push({name:`tar`,load:async()=>(await import(`./tar-MZQD7NO4-46pC0DHj.mjs`)).tarCommand}),Ye.push({name:`yq`,load:async()=>(await import(`./yq-OAKYHSXH-CpYttz-E.mjs`)).yqCommand}),Ye.push({name:`xan`,load:async()=>(await import(`./xan-UD7JYIL2-DnWVVFeC.mjs`)).xanCommand}),Ye.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-TE5AIOTF-DW7pT7NE.mjs`)).sqlite3Command}));var qt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(qt.push({name:`python3`,load:async()=>(await import(`./python3-DNGS4G3E-bGzU9nm-.mjs`)).python3Command}),qt.push({name:`python`,load:async()=>(await import(`./python3-DNGS4G3E-bGzU9nm-.mjs`)).pythonCommand}));var Gt=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(Gt.push({name:`js-exec`,load:async()=>(await import(`./js-exec-VXN6TZ7U-fCXuAS2-.mjs`)).jsExecCommand}),Gt.push({name:`node`,load:async()=>(await import(`./js-exec-VXN6TZ7U-fCXuAS2-.mjs`)).nodeStubCommand}));var on=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-ClMENMWY.mjs`)).curlCommand}],nn=new Map;function Kt(e){return{name:e.name,async execute(t,s){let g=nn.get(e.name);if(g||(g=await _$1.runTrustedAsync(()=>e.load()),nn.set(e.name,g)),s.coverage&&(typeof __BROWSER__>`u`||!__BROWSER__)){let{emitFlagCoverage:g}=await import(`./flag-coverage-6JEX67RU-BqC6mFKB.mjs`);g(s.coverage,e.name,t)}return g.execute(t,s)}}}function an(e){return(e?Ye.filter(t=>e.includes(t.name)):Ye).map(Kt)}function ln(){return on.map(Kt)}function cn(){return qt.map(Kt)}function un(){return Gt.map(Kt)}function fn(e){return`load`in e&&typeof e.load==`function`}function dn(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 ro(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):ro(s)?this.writeFileSync(t,s.content,void 0,{mode:s.mode,mtime:s.mtime}):this.writeFileSync(t,s)}ensureParentDirs(e){let t=p$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=p$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=m$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=m$1(g,e),w=m$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 no(e){let t=e;return typeof t.mkdirSync==`function`&&typeof t.writeFileSync==`function`}function io(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 oo(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 ao(e,t){e.mkdirSync(`/proc/self/fd`,{recursive:!0}),e.writeFileSync(`/proc/version`,`${xi$1}
|
|
52
52
|
`),e.writeFileSync(`/proc/self/exe`,`/bin/bash`),e.writeFileSync(`/proc/self/cmdline`,`bash\0`),e.writeFileSync(`/proc/self/comm`,`bash
|
|
53
|
-
`),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
|
|
53
|
+
`),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 hn(e,t,s={pid:1,ppid:0,uid:1e3,gid:1e3}){no(e)&&(io(e,t),oo(e),ao(e,s))}var lo=[`allexport`,`errexit`,`noglob`,`noclobber`,`noexec`,`nounset`,`pipefail`,`posix`,`verbose`,`xtrace`],co=[`braceexpand`,`hashall`,`interactive-comments`];function Ws(e){let t=[],s=[...co.map(e=>({name:e,enabled:!0})),...lo.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`,Ws(e.state.options))}var uo=[`dotglob`,`expand_aliases`,`extglob`,`failglob`,`globskipdots`,`globstar`,`lastpipe`,`nocaseglob`,`nocasematch`,`nullglob`,`xpg_echo`];function zs(e){let t=[];for(let s of uo)e[s]&&t.push(s);return t.join(`:`)}function Vs(e){e.state.env.set(`BASHOPTS`,zs(e.state.shoptOptions))}var fo=`BASH_ALIAS_`;function pn(e){return e.parts.length===1?e.parts[0].type===`Literal`:!1}function mn(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type===`Literal`?t.value:null}function yn(e,t){return e.env.get(`${fo}${t}`)}function Bs(e,t,s){if(!t.name||!pn(t.name))return t;let g=mn(t.name);if(!g)return t;let S=yn(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=wn(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 gn(t,S);let k=O.statements[0].pipelines[0].commands[0];if(k.type!==`SimpleCommand`)return gn(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(pn(t)){let g=mn(t);if(g&&yn(e,g)){let g={type:`SimpleCommand`,name:t,args:j.args.slice(1),assignments:[],redirections:[]},S=Bs(e,g,s);S!==g&&(j={...j,name:S.name,args:[...S.args]})}}}return j}catch(e){throw s.delete(g),e}}function gn(e,t){let s=t;for(let t of e.args){let e=wn(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 wn(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 vn(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 bn(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 ho=[`tar`,`yq`,`xan`,`sqlite3`,`python3`,`python`];function En(e){return ho.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 js(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
|
|
54
54
|
`);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
|
|
55
|
-
`);s=e}throw new c(s)}async function
|
|
55
|
+
`);s=e}throw new c(s)}async function Us(e,t){let s,g=!1,S=!1,w=0;for(;w<t.length;)if(t[w]===`--`){w++;break}else if(t[w]===`-L`)S=!1,w++;else if(t[w]===`-P`)S=!0,w++;else if(t[w].startsWith(`-`)&&t[w]!==`-`)w++;else break;let E=t.slice(w);if(E.length===0||E[0]===`~`?s=e.state.env.get(`HOME`)||`/`:E[0]===`-`?(s=e.state.previousDir,g=!0):s=E[0],!s.startsWith(`/`)&&!s.startsWith(`./`)&&!s.startsWith(`../`)&&s!==`.`&&s!==`..`){let t=e.state.env.get(`CDPATH`);if(t){let S=t.split(`:`).filter(e=>e);for(let t of S){let S=t.startsWith(`/`)?`${t}/${s}`:`${e.state.cwd}/${t}/${s}`;try{if((await e.fs.stat(S)).isDirectory){s=S,g=!0;break}}catch{}}}}let D=(s.startsWith(`/`)?s:`${e.state.cwd}/${s}`).split(`/`).filter(e=>e&&e!==`.`),O=``;for(let t of D)if(t===`..`)O=O.split(`/`).slice(0,-1).join(`/`)||`/`;else{O=O?`${O}/${t}`:`/${t}`;try{if(!(await e.fs.stat(O)).isDirectory)return A(`bash: cd: ${s}: Not a directory
|
|
56
56
|
`)}catch{return A(`bash: cd: ${s}: No such file or directory
|
|
57
57
|
`)}}let k=O||`/`;if(S)try{k=await e.fs.realpath(k)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=k,e.state.env.set(`PWD`,e.state.cwd),e.state.env.set(`OLDPWD`,e.state.previousDir),z(g?`${k}
|
|
58
|
-
`:``)}function
|
|
59
|
-
`,!1}return e.state.env.has(`${t}_${S}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?gt(e,t).length>0:mt$1(e,t).length>0}async function He(e,t){switch(t.type){case`CondBinary`:{let s=await Pt$1(e,t.left),g=t.right.parts.length>0&&t.right.parts.every(e=>e.type===`SingleQuoted`||e.type===`DoubleQuoted`||e.type===`Escaped`&&t.operator!==`=~`),S;if(S=t.operator===`=~`?g?bt(await Pt$1(e,t.right)):await Sl(e,t.right):
|
|
60
|
-
`,2):
|
|
61
|
-
`,2):_(``,``,1)}if(t.length===3){let s=t[0],g=t[1],S=t[2];if(
|
|
62
|
-
`,2):Q(s.value)}async function
|
|
63
|
-
`)&&!g&&!S){E&&=(t.push(s),s=``,!1);continue}s+=D,E=!0}return E&&t.push(s),t}function
|
|
58
|
+
`:``)}function Hs(e,t){return e.fs.resolvePath(e.state.cwd,t)}var po=[`-e`,`-a`,`-f`,`-d`,`-r`,`-w`,`-x`,`-s`,`-L`,`-h`,`-k`,`-g`,`-u`,`-G`,`-O`,`-b`,`-c`,`-p`,`-S`,`-t`,`-N`];function Yt(e){return po.includes(e)}async function Qt(e,t,s){let g=Hs(e,s);switch(t){case`-e`:case`-a`:return e.fs.exists(g);case`-f`:return await e.fs.exists(g)?(await e.fs.stat(g)).isFile:!1;case`-d`:return await e.fs.exists(g)?(await e.fs.stat(g)).isDirectory:!1;case`-r`:return await e.fs.exists(g)?((await e.fs.stat(g)).mode&256)!=0:!1;case`-w`:return await e.fs.exists(g)?((await e.fs.stat(g)).mode&128)!=0:!1;case`-x`:return await e.fs.exists(g)?((await e.fs.stat(g)).mode&64)!=0:!1;case`-s`:return await e.fs.exists(g)?(await e.fs.stat(g)).size>0:!1;case`-L`:case`-h`:try{return(await e.fs.lstat(g)).isSymbolicLink}catch{return!1}case`-k`:return await e.fs.exists(g)?((await e.fs.stat(g)).mode&512)!=0:!1;case`-g`:return await e.fs.exists(g)?((await e.fs.stat(g)).mode&1024)!=0:!1;case`-u`:return await e.fs.exists(g)?((await e.fs.stat(g)).mode&2048)!=0:!1;case`-G`:case`-O`:return e.fs.exists(g);case`-b`:return!1;case`-c`:return[`/dev/null`,`/dev/zero`,`/dev/random`,`/dev/urandom`,`/dev/tty`,`/dev/stdin`,`/dev/stdout`,`/dev/stderr`].includes(g);case`-p`:return!1;case`-S`:return!1;case`-t`:return!1;case`-N`:return e.fs.exists(g);default:return!1}}var mo=[`-nt`,`-ot`,`-ef`];function Jt(e){return mo.includes(e)}async function es(e,t,s,g){let S=Hs(e,s),w=Hs(e,g);switch(t){case`-nt`:try{let t=await e.fs.stat(S),s=await e.fs.stat(w);return t.mtime>s.mtime}catch{return!1}case`-ot`:try{let t=await e.fs.stat(S),s=await e.fs.stat(w);return t.mtime<s.mtime}catch{return!1}case`-ef`:try{return!await e.fs.exists(S)||!await e.fs.exists(w)?!1:e.fs.resolvePath(e.state.cwd,S)===e.fs.resolvePath(e.state.cwd,w)}catch{return!1}default:return!1}}var yo=new Set([`-eq`,`-ne`,`-lt`,`-le`,`-gt`,`-ge`]);function ts(e){return yo.has(e)}function ss(e,t,s){switch(e){case`-eq`:return t===s;case`-ne`:return t!==s;case`-lt`:return t<s;case`-le`:return t<=s;case`-gt`:return t>s;case`-ge`:return t>=s}}function Pt(e){return e===`=`||e===`==`||e===`!=`}function rs(e,t,s,g=!1,S=!1,w=!1){if(g){let g=ct(t,s,S,w);return e===`!=`?!g:g}if(S){let g=t.toLowerCase()===s.toLowerCase();return e===`!=`?!g:g}let E=t===s;return e===`!=`?!E:E}var go=new Set([`-z`,`-n`]);function ns(e){return go.has(e)}function is(e,t){switch(e){case`-z`:return t===``;case`-n`:return t!==``}}async function os(e,t){let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let t=s[1],g=s[2];if(e.state.associativeArrays?.has(t)){let s=g;return(s.startsWith(`'`)&&s.endsWith(`'`)||s.startsWith(`"`)&&s.endsWith(`"`))&&(s=s.slice(1,-1)),s=s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(t,s)=>e.state.env.get(s)||``),e.state.env.has(`${t}_${s}`)}let S;try{S=await R(e,M(new V,g).expression)}catch{if(/^-?\d+$/.test(g))S=Number.parseInt(g,10);else{let t=e.state.env.get(g);S=t?Number.parseInt(t,10):0}}if(S<0){let s=mt$1(e,t),g=e.state.currentLine;if(s.length===0||(S=Math.max(...s)+1+S,S<0))return e.state.expansionStderr=(e.state.expansionStderr||``)+`bash: line ${g}: ${t}: bad array subscript
|
|
59
|
+
`,!1}return e.state.env.has(`${t}_${S}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?gt$1(e,t).length>0:mt$1(e,t).length>0}async function He(e,t){switch(t.type){case`CondBinary`:{let s=await Pt$1(e,t.left),g=t.right.parts.length>0&&t.right.parts.every(e=>e.type===`SingleQuoted`||e.type===`DoubleQuoted`||e.type===`Escaped`&&t.operator!==`=~`),S;if(S=t.operator===`=~`?g?bt(await Pt$1(e,t.right)):await Sl(e,t.right):Pt(t.operator)&&!g?await bl(e,t.right):await Pt$1(e,t.right),Pt(t.operator)){let w=e.state.shoptOptions.nocasematch;return rs(t.operator,s,S,!g,w,!0)}if(ts(t.operator))return ss(t.operator,await Sn(e,s),await Sn(e,S));if(Jt(t.operator))return es(e,t.operator,s,S);switch(t.operator){case`=~`:try{let t=e.state.shoptOptions.nocasematch,g=I1(Eo(S),t?`i`:``).match(s);if(Ci$1(e,`BASH_REMATCH`),g)for(let t=0;t<g.length;t++)e.state.env.set(`BASH_REMATCH_${t}`,g[t]||``);return g!==null}catch{throw Error(`syntax error in regular expression`)}case`<`:return s<S;case`>`:return s>S;default:return!1}}case`CondUnary`:{let s=await Pt$1(e,t.operand);return Yt(t.operator)?Qt(e,t.operator,s):ns(t.operator)?is(t.operator,s):t.operator===`-v`?await os(e,s):t.operator===`-o`?qs(e,s):!1}case`CondNot`:return e.state.shoptOptions.extglob&&t.operand.type===`CondGroup`&&t.operand.expression.type===`CondWord`?`!(${await Pt$1(e,t.operand.expression.word)})`!=``:!await He(e,t.operand);case`CondAnd`:return await He(e,t.left)?await He(e,t.right):!1;case`CondOr`:return await He(e,t.left)?!0:await He(e,t.right);case`CondGroup`:return await He(e,t.expression);case`CondWord`:return await Pt$1(e,t.word)!==``;default:return!1}}async function At(e,t){if(t.length===0)return _(``,``,1);if(t.length===1)return Q(!!t[0]);if(t.length===2){let s=t[0],g=t[1];return s===`(`?A(`test: '(' without matching ')'
|
|
60
|
+
`,2):Yt(s)?Q(await Qt(e,s,g)):ns(s)?Q(is(s,g)):s===`!`?Q(!g):s===`-v`?Q(await os(e,g)):s===`-o`?Q(qs(e,g)):s===`=`||s===`==`||s===`!=`||s===`<`||s===`>`||s===`-eq`||s===`-ne`||s===`-lt`||s===`-le`||s===`-gt`||s===`-ge`||s===`-nt`||s===`-ot`||s===`-ef`?A(`test: ${s}: unary operator expected
|
|
61
|
+
`,2):_(``,``,1)}if(t.length===3){let s=t[0],g=t[1],S=t[2];if(Pt(g))return Q(rs(g,s,S));if(ts(g)){let e=as(s),t=as(S);return!e.valid||!t.valid?_(``,``,2):Q(ss(g,e.value,t.value))}if(Jt(g))return Q(await es(e,g,s,S));switch(g){case`-a`:return Q(s!==``&&S!==``);case`-o`:return Q(s!==``||S!==``);case`>`:return Q(s>S);case`<`:return Q(s<S)}if(s===`!`){let t=await At(e,[g,S]);return _(``,t.stderr,t.exitCode===0?1:t.exitCode===1?0:t.exitCode)}if(s===`(`&&S===`)`)return Q(g!==``)}if(t.length===4){if(t[0]===`!`){let s=await At(e,t.slice(1));return _(``,s.stderr,s.exitCode===0?1:s.exitCode===1?0:s.exitCode)}if(t[0]===`(`&&t[3]===`)`)return At(e,[t[1],t[2]])}let s=await An(e,t,0);return s.pos<t.length?A(`test: too many arguments
|
|
62
|
+
`,2):Q(s.value)}async function An(e,t,s){return wo(e,t,s)}async function wo(e,t,s){let{value:g,pos:S}=await $n(e,t,s);for(;t[S]===`-o`;){let s=await $n(e,t,S+1);g||=s.value,S=s.pos}return{value:g,pos:S}}async function $n(e,t,s){let{value:g,pos:S}=await Zs(e,t,s);for(;t[S]===`-a`;){let s=await Zs(e,t,S+1);g&&=s.value,S=s.pos}return{value:g,pos:S}}async function Zs(e,t,s){if(t[s]===`!`){let{value:g,pos:S}=await Zs(e,t,s+1);return{value:!g,pos:S}}return vo(e,t,s)}async function vo(e,t,s){let g=t[s];if(g===`(`){let{value:g,pos:S}=await An(e,t,s+1);return{value:g,pos:t[S]===`)`?S+1:S}}let S=t[s+1];if(Pt(S))return{value:rs(S,g,t[s+2]??``),pos:s+3};if(ts(S)){let e=as(g),w=as(t[s+2]??`0`);return!e.valid||!w.valid?{value:!1,pos:s+3}:{value:ss(S,e.value,w.value),pos:s+3}}return Jt(S)?{value:await es(e,S,g,t[s+2]??``),pos:s+3}:Yt(g)?{value:await Qt(e,g,t[s+1]??``),pos:s+2}:ns(g)?{value:is(g,t[s+1]??``),pos:s+2}:g===`-v`?{value:await os(e,t[s+1]??``),pos:s+2}:g===`-o`?{value:qs(e,t[s+1]??``),pos:s+2}:{value:g!==void 0&&g!==``,pos:s+1}}function ct(e,t,s=!1,g=!1){return I1(`^${kn(t,g)}$`,s?`is`:`s`).test(e)}function kn(e,t){let s=``;for(let g=0;g<e.length;g++){let S=e[g];if(t&&(S===`@`||S===`*`||S===`+`||S===`?`||S===`!`)&&g+1<e.length&&e[g+1]===`(`){let w=_n(e,g+1);if(w!==-1){let E=Cn(e.slice(g+2,w)),D=E.map(e=>kn(e,t)),O=D.length>0?D.join(`|`):`(?:)`;if(S===`@`)s+=`(?:${O})`;else if(S===`*`)s+=`(?:${O})*`;else if(S===`+`)s+=`(?:${O})+`;else if(S===`?`)s+=`(?:${O})?`;else if(S===`!`)if(w<e.length-1){let e=E.map(e=>Nn(e,t));if(e.every(e=>e!==null)&&e.every(t=>t===e[0])&&e[0]!==null){let t=e[0];if(t===0)s+=`(?:.+)`;else{let e=[];t>0&&e.push(`.{0,${t-1}}`),e.push(`.{${t+1},}`),e.push(`(?!(?:${O})).{${t}}`),s+=`(?:${e.join(`|`)})`}}else s+=`(?:(?!(?:${O})).)*?`}else s+=`(?!(?:${O})$).*`;g=w;continue}}if(S===`\\`)if(g+1<e.length){let t=e[g+1];/[\\^$.|+(){}[\]*?]/.test(t)?s+=`\\${t}`:s+=t,g++}else s+=`\\\\`;else if(S===`*`)s+=`.*`;else if(S===`?`)s+=`.`;else if(S===`[`){let t=e.indexOf(`]`,g+1);t===-1?s+=`\\[`:(s+=e.slice(g,t+1),g=t)}else /[\\^$.|+(){}]/.test(S)?s+=`\\${S}`:s+=S}return s}function _n(e,t){let s=1,g=t+1;for(;g<e.length&&s>0;){let t=e[g];if(t===`\\`){g+=2;continue}if(t===`(`)s++;else if(t===`)`&&(s--,s===0))return g;g++}return-1}function Cn(e){let t=[],s=``,g=0,S=0;for(;S<e.length;){let w=e[S];if(w===`\\`){s+=w,S+1<e.length?(s+=e[S+1],S+=2):S++;continue}w===`(`?(g++,s+=w):w===`)`?(g--,s+=w):w===`|`&&g===0?(t.push(s),s=``):s+=w,S++}return t.push(s),t}function Nn(e,t){let s=0,g=0;for(;g<e.length;){let S=e[g];if(t&&(S===`@`||S===`*`||S===`+`||S===`?`||S===`!`)&&g+1<e.length&&e[g+1]===`(`){let w=_n(e,g+1);if(w!==-1){if(S===`@`){let S=Cn(e.slice(g+2,w)).map(e=>Nn(e,t));if(S.every(e=>e!==null)&&S.every(e=>e===S[0])){s+=S[0],g=w+1;continue}return null}return null}}if(S===`*`)return null;if(S===`?`){s+=1,g++;continue}if(S===`[`){let t=e.indexOf(`]`,g+1);if(t!==-1){s+=1,g=t+1;continue}s+=1,g++;continue}if(S===`\\`){s+=1,g+=2;continue}s+=1,g++}return s}function qs(e,t){let s=new Map([[`errexit`,()=>e.state.options.errexit===!0],[`nounset`,()=>e.state.options.nounset===!0],[`pipefail`,()=>e.state.options.pipefail===!0],[`xtrace`,()=>e.state.options.xtrace===!0],[`e`,()=>e.state.options.errexit===!0],[`u`,()=>e.state.options.nounset===!0],[`x`,()=>e.state.options.xtrace===!0]]).get(t);return s?s():!1}async function Sn(e,t){if(t=t.trim(),t===``)return 0;if(/^[+-]?(\d+#[a-zA-Z0-9@_]+|0[xX][0-9a-fA-F]+|0[0-7]+|\d+)$/.test(t))return Pn(t);try{return await R(e,M(new V,t).expression)}catch{return Pn(t)}}function bo(e,t){let s=0;for(let g of e){let e;if(g>=`0`&&g<=`9`)e=g.charCodeAt(0)-48;else if(g>=`a`&&g<=`z`)e=g.charCodeAt(0)-97+10;else if(g>=`A`&&g<=`Z`)e=g.charCodeAt(0)-65+36;else if(g===`@`)e=62;else if(g===`_`)e=63;else return NaN;if(e>=t)return NaN;s=s*t+e}return s}function Pn(e){if(e=e.trim(),e===``)return 0;let t=!1;e.startsWith(`-`)?(t=!0,e=e.slice(1)):e.startsWith(`+`)&&(e=e.slice(1));let s,g=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(g){let e=Number.parseInt(g[1],10);s=e>=2&&e<=64?bo(g[2],e):0}else s=/^0[xX][0-9a-fA-F]+$/.test(e)?Number.parseInt(e,16):/^0[0-7]+$/.test(e)?Number.parseInt(e,8):Number.parseInt(e,10);return Number.isNaN(s)&&(s=0),t?-s:s}function as(e){if(e=e.trim(),e===``)return{value:0,valid:!0};let t=!1;if(e.startsWith(`-`)?(t=!0,e=e.slice(1)):e.startsWith(`+`)&&(e=e.slice(1)),!/^\d+$/.test(e))return{value:0,valid:!1};let s=Number.parseInt(e,10);return Number.isNaN(s)?{value:0,valid:!1}:{value:t?-s:s,valid:!0}}function Eo(e){let t=``,s=0;for(;s<e.length;)if(e[s]===`\\`&&s+1<e.length)t+=e[s]+e[s+1],s+=2;else if(e[s]===`[`){let g=$o(e,s);t+=g.converted,s=g.endIndex}else t+=e[s],s++;return t}function $o(e,t){let s=t+1,g=`[`;s<e.length&&(e[s]===`^`||e[s]===`!`)&&(g+=`^`,s++);let S=!1;s<e.length&&e[s]===`]`&&(S=!0,s++);let w=!1;s<e.length&&e[s]===`[`&&s+1<e.length&&e[s+1]!==`:`&&(w=!0,s++);let E=``,D=!1;for(;s<e.length;){let t=e[s];if(t===`]`){D=!0,s++;break}if(t===`[`&&s+1<e.length&&e[s+1]===`:`){let t=e.indexOf(`:]`,s+2);if(t!==-1){let g=e.slice(s+2,t);E+=So(g),s=t+2;continue}}if(t===`[`&&s+1<e.length){let t=e[s+1];if(t===`.`||t===`=`){let g=`${t}]`,S=e.indexOf(g,s+2);if(S!==-1){let t=e.slice(s+2,S);E+=t,s=S+2;continue}}}if(t===`\\`&&s+1<e.length){E+=t+e[s+1],s+=2;continue}E+=t,s++}return D?(S&&(g+=`\\]`),w&&(g+=`\\[`),g+=E,g+=`]`,{converted:g,endIndex:s}):{converted:`\\[`,endIndex:t+1}}function So(e){return new Map([[`alnum`,`a-zA-Z0-9`],[`alpha`,`a-zA-Z`],[`ascii`,`\\x00-\\x7F`],[`blank`,` \\t`],[`cntrl`,`\\x00-\\x1F\\x7F`],[`digit`,`0-9`],[`graph`,`!-~`],[`lower`,`a-z`],[`print`,` -~`],[`punct`,"!-/:-@\\[-`{-~"],[`space`,` \\t\\n\\r\\f\\v`],[`upper`,`A-Z`],[`word`,`a-zA-Z0-9_`],[`xdigit`,`0-9A-Fa-f`]]).get(e)??``}function Oe(e){let t=[],s=``,g=!1,S=!1,w=!1,E=!1;for(let D of e){if(w){s+=D,w=!1,E=!0;continue}if(D===`\\`){w=!0;continue}if(D===`'`&&!S){g||(E=!0),g=!g;continue}if(D===`"`&&!g){S||(E=!0),S=!S;continue}if((D===` `||D===` `||D===`
|
|
63
|
+
`)&&!g&&!S){E&&=(t.push(s),s=``,!1);continue}s+=D,E=!0}return E&&t.push(s),t}function ls(e){let t=[],s=0;for(;s<e.length;){for(;s<e.length&&/\s/.test(e[s]);)s++;if(s>=e.length)break;if(e[s]!==`[`){s++;continue}s++;let g=``;if(e[s]===`'`||e[s]===`"`){let t=e[s];for(s++;s<e.length&&e[s]!==t;)g+=e[s],s++;e[s]===t&&s++}else for(;s<e.length&&e[s]!==`]`&&e[s]!==`=`;)g+=e[s],s++;for(;s<e.length&&e[s]!==`]`;)s++;if(e[s]===`]`&&s++,e[s]!==`=`)continue;s++;let S=``;if(e[s]===`'`||e[s]===`"`){let t=e[s];for(s++;s<e.length&&e[s]!==t;)e[s]===`\\`&&s+1<e.length&&s++,S+=e[s],s++;e[s]===t&&s++}else for(;s<e.length&&!/\s/.test(e[s]);)S+=e[s],s++;t.push([g,S])}return t}function On(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:Oe(t[2])};let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(s)return{name:s[1],isArray:!1,arrayIndex:s[2],value:s[3]};if(e.includes(`=`)){let t=e.indexOf(`=`);return{name:e.slice(0,t),isArray:!1,value:e.slice(t+1)}}return{name:e,isArray:!1}}async function Po(e,t){try{return await R(e,M(new V,t).expression)}catch{let e=parseInt(t,10);return Number.isNaN(e)?0:e}}async function xn(e,t,s={}){let{name:g,isArray:S,arrayElements:w,value:E,arrayIndex:D}=t,{makeReadonly:O=!1,checkReadonly:k=!0}=s;if(k){let t=da$1(e,g);if(t)return t}if(S&&w){for(let t=0;t<w.length;t++)e.state.env.set(`${g}_${t}`,w[t]);e.state.env.set(`${g}__length`,String(w.length))}else if(D!==void 0&&E!==void 0){let t=await Po(e,D);e.state.env.set(`${g}_${t}`,E),t>=parseInt(e.state.env.get(`${g}__length`)??`0`,10)&&e.state.env.set(`${g}__length`,String(t+1))}else E!==void 0&&e.state.env.set(g,E);return O&&pa$1(e,g),null}function Ze(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function ut(e,t){return e.state.localVarDepth?.get(t)}function cs(e,t){e.state.localVarDepth?.delete(t)}function Dn(e,t,s){e.state.localVarStack=e.state.localVarStack||new Map;let g=e.state.localVarStack.get(t)||[];g.push({value:s,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,g)}function us(e,t){let s=e.state.localVarStack?.get(t);if(!(!s||s.length===0))return s.pop()}function Tn(e,t){if(e.state.localVarStack)for(let[s,g]of e.state.localVarStack.entries()){for(;g.length>0&&g[g.length-1].scopeIndex===t;)g.pop();g.length===0&&e.state.localVarStack.delete(s)}}var Gs=new Set([`:`,`.`,`break`,`continue`,`eval`,`exec`,`exit`,`export`,`readonly`,`return`,`set`,`shift`,`trap`,`unset`]);function Rn(e){return Gs.has(e)}var Ks=new Set([`if`,`then`,`else`,`elif`,`fi`,`case`,`esac`,`for`,`select`,`while`,`until`,`do`,`done`,`in`,`function`,`{`,`}`,`time`,`[[`,`]]`,`!`]),ft=new Set(`:,true,false,cd,export,unset,exit,local,set,break,continue,return,eval,shift,getopts,compgen,complete,compopt,pushd,popd,dirs,source,.,read,mapfile,readarray,declare,typeset,readonly,let,command,shopt,exec,test,[,echo,printf,pwd,alias,unalias,type,hash,ulimit,umask,trap,times,wait,kill,jobs,fg,bg,disown,suspend,fc,history,help,enable,builtin,caller`.split(`,`));async function Qe(e,t,s,g){try{if((await e.fs.stat(t)).isDirectory)return`bash: ${s}: Is a directory
|
|
64
64
|
`;if(g.checkNoclobber&&e.state.options.noclobber&&!g.isClobber&&s!==`/dev/null`)return`bash: ${s}: cannot overwrite existing file
|
|
65
|
-
`}catch{}return null}function Fe(e){let t=Math.min(e.length,8192);for(let s=0;s<t;s++)if(e.charCodeAt(s)>127)return`utf8`;return`binary`}function
|
|
66
|
-
`};s.set(g,await Pt$1(e,S.target))}else{let t=await Nl(e,S.target);if(`error`in t)return{targets:s,error:t.error};s.set(g,t.target)}}return{targets:s}}function
|
|
65
|
+
`}catch{}return null}function Fe(e){let t=Math.min(e.length,8192);for(let s=0;s<t;s++)if(e.charCodeAt(s)>127)return`utf8`;return`binary`}function Ao(e){if(!e.startsWith(`__rw__:`))return null;let t=e.slice(7),s=t.indexOf(`:`);if(s===-1)return null;let g=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(g)||g<0)return null;let S=s+1,w=t.slice(S,S+g),E=S+g+1,D=t.slice(E),O=D.indexOf(`:`);if(O===-1)return null;let k=Number.parseInt(D.slice(0,O),10);return Number.isNaN(k)||k<0?null:{path:w,position:k,content:D.slice(O+1)}}async function In(e,t){let s=new Map;for(let g=0;g<t.length;g++){let S=t[g];if(S.target.type!==`HereDoc`)if(S.operator===`>&`||S.operator===`<&`){if(Fs(e,S.target))return{targets:s,error:`bash: $@: ambiguous redirect
|
|
66
|
+
`};s.set(g,await Pt$1(e,S.target))}else{let t=await Nl(e,S.target);if(`error`in t)return{targets:s,error:t.error};s.set(g,t.target)}}return{targets:s}}function ko(e){e.state.nextFd===void 0&&(e.state.nextFd=10);let t=e.state.nextFd,s=e.limits.maxFileDescriptors;if(t>=s)throw Error(`bash: cannot allocate file descriptor: too many open files (max ${s})`);return e.state.nextFd++,t}async function fs(e,t){for(let s of t){if(!s.fdVariable)continue;if(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),(s.operator===`>&`||s.operator===`<&`)&&s.target.type===`Word`&&await Pt$1(e,s.target)===`-`){let t=e.state.env.get(s.fdVariable);if(t!==void 0){let s=Number.parseInt(t,10);Number.isNaN(s)||e.state.fileDescriptors.delete(s)}continue}let t=ko(e);if(e.state.env.set(s.fdVariable,String(t)),s.target.type===`Word`){let g=await Pt$1(e,s.target);if(s.operator===`>&`||s.operator===`<&`){let s=Number.parseInt(g,10);if(!Number.isNaN(s)){let g=e.state.fileDescriptors.get(s);g!==void 0&&(le(e),e.state.fileDescriptors.set(t,g));continue}}if(s.operator===`>`||s.operator===`>>`||s.operator===`>|`||s.operator===`&>`||s.operator===`&>>`){let S=e.fs.resolvePath(e.state.cwd,g);(s.operator===`>`||s.operator===`>|`||s.operator===`&>`)&&await e.fs.writeFile(S,``,`binary`),le(e),e.state.fileDescriptors.set(t,`__file__:${S}`)}else if(s.operator===`<<<`)le(e),e.state.fileDescriptors.set(t,`${g}
|
|
67
67
|
`);else if(s.operator===`<`||s.operator===`<>`)try{let s=e.fs.resolvePath(e.state.cwd,g),S=await e.fs.readFile(s);le(e),e.state.fileDescriptors.set(t,S)}catch{return _(``,`bash: ${g}: No such file or directory
|
|
68
68
|
`,1)}}}return null}async function xe(e,t){for(let s of t){if(s.target.type===`HereDoc`)continue;let t=s.operator===`>&`;if(s.operator!==`>`&&s.operator!==`>|`&&s.operator!==`&>`&&!t)continue;let g;if(t){if(g=await Pt$1(e,s.target),g===`-`||!Number.isNaN(Number.parseInt(g,10))||s.fd!=null)continue}else{let t=await Nl(e,s.target);if(`error`in t)return _(``,t.error,1);g=t.target}let S=e.fs.resolvePath(e.state.cwd,g),w=s.operator===`>|`;if(S.includes(`\0`))return _(``,`bash: ${g}: No such file or directory
|
|
69
69
|
`,1);try{let t=await e.fs.stat(S);if(t.isDirectory)return _(``,`bash: ${g}: Is a directory
|
|
70
70
|
`,1);if(e.state.options.noclobber&&!w&&!t.isDirectory&&g!==`/dev/null`)return _(``,`bash: ${g}: cannot overwrite existing file
|
|
71
71
|
`,1)}catch{}if(g!==`/dev/null`&&g!==`/dev/stdout`&&g!==`/dev/stderr`&&g!==`/dev/full`&&await e.fs.writeFile(S,``,`binary`),g===`/dev/full`)return _(``,`bash: /dev/full: No space left on device
|
|
72
|
-
`,1)}return null}async function G(e,t,s,g){let{stdout:S,stderr:w,exitCode:E}=t,D=t.stdoutEncoding===`binary`?()=>`binary`:e=>Fe(e);for(let t=0;t<s.length;t++){let O=s[t];if(O.target.type===`HereDoc`)continue;let k,j=g?.get(t);if(j!==void 0)k=j;else if(O.operator===`>&`||O.operator===`<&`){if(Fs
|
|
72
|
+
`,1)}return null}async function G(e,t,s,g){let{stdout:S,stderr:w,exitCode:E}=t,D=t.stdoutEncoding===`binary`?()=>`binary`:e=>Fe(e);for(let t=0;t<s.length;t++){let O=s[t];if(O.target.type===`HereDoc`)continue;let k,j=g?.get(t);if(j!==void 0)k=j;else if(O.operator===`>&`||O.operator===`<&`){if(Fs(e,O.target)){w+=`bash: $@: ambiguous redirect
|
|
73
73
|
`,E=1,S=``;continue}k=await Pt$1(e,O.target)}else{let t=await Nl(e,O.target);if(`error`in t){w+=t.error,E=1,S=``;continue}k=t.target}if(!O.fdVariable){if(k.includes(`\0`)){w+=`bash: ${k.replace(/\0/g,``)}: No such file or directory
|
|
74
74
|
`,E=1,S=``;continue}switch(O.operator){case`>`:case`>|`:{let t=O.fd??1,s=O.operator===`>|`;if(t===1){if(k===`/dev/stdout`)break;if(k===`/dev/stderr`){w+=S,S=``;break}if(k===`/dev/full`){w+=`bash: echo: write error: No space left on device
|
|
75
75
|
`,E=1,S=``;break}let t=e.fs.resolvePath(e.state.cwd,k),g=await Qe(e,t,k,{checkNoclobber:!0,isClobber:s});if(g){w+=g,E=1,S=``;break}await e.fs.writeFile(t,S,D(S)),S=``}else if(t===2){if(k===`/dev/stderr`)break;if(k===`/dev/stdout`){S+=w,w=``;break}if(k===`/dev/full`){w+=`bash: echo: write error: No space left on device
|
|
76
76
|
`,E=1;break}if(k===`/dev/null`)w=``;else{let t=e.fs.resolvePath(e.state.cwd,k),g=await Qe(e,t,k,{checkNoclobber:!0,isClobber:s});if(g){w+=g,E=1;break}await e.fs.writeFile(t,w,Fe(w)),w=``}}break}case`>>`:{let t=O.fd??1;if(t===1){if(k===`/dev/stdout`)break;if(k===`/dev/stderr`){w+=S,S=``;break}if(k===`/dev/full`){w+=`bash: echo: write error: No space left on device
|
|
77
77
|
`,E=1,S=``;break}let t=e.fs.resolvePath(e.state.cwd,k),s=await Qe(e,t,k,{});if(s){w+=s,E=1,S=``;break}await e.fs.appendFile(t,S,D(S)),S=``}else if(t===2){if(k===`/dev/stderr`)break;if(k===`/dev/stdout`){S+=w,w=``;break}if(k===`/dev/full`){w+=`bash: echo: write error: No space left on device
|
|
78
78
|
`,E=1;break}let t=e.fs.resolvePath(e.state.cwd,k),s=await Qe(e,t,k,{});if(s){w+=s,E=1;break}await e.fs.appendFile(t,w,Fe(w)),w=``}break}case`>&`:case`<&`:{let t=O.fd??1;if(k===`-`)break;if(k.endsWith(`-`)){let s=k.slice(0,-1),g=Number.parseInt(s,10);if(!Number.isNaN(g)){let s=e.state.fileDescriptors?.get(g);s===void 0?g===1||g===2?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,`__dupout__:${g}`)):g===0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,`__dupin__:${g}`)):g>=3&&(w+=`bash: ${g}: Bad file descriptor
|
|
79
|
-
`,E=1):(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,s),g>=3&&e.state.fileDescriptors?.delete(g))}break}if(k===`2`||k===`&2`)t===1&&(w+=S,S=``);else if(k===`1`||k===`&1`)S+=w,w=``;else{let s=Number.parseInt(k,10);if(Number.isNaN(s)){if(O.operator===`>&`){let s=e.fs.resolvePath(e.state.cwd,k),g=await Qe(e,s,k,{checkNoclobber:!0});if(g){w=g,E=1,S=``;break}if(O.fd==null){let t=S+w;await e.fs.writeFile(s,t,D(t)),S=``,w=``}else t===1?(await e.fs.writeFile(s,S,D(S)),S=``):t===2&&(await e.fs.writeFile(s,w,Fe(w)),w=``)}}else{let g=e.state.fileDescriptors?.get(s);if(g?.startsWith(`__file__:`)){let s=g.slice(9);t===1?(await e.fs.appendFile(s,S,D(S)),S=``):t===2&&(await e.fs.appendFile(s,w,Fe(w)),w=``)}else if(g?.startsWith(`__rw__:`)){let s=
|
|
79
|
+
`,E=1):(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,s),g>=3&&e.state.fileDescriptors?.delete(g))}break}if(k===`2`||k===`&2`)t===1&&(w+=S,S=``);else if(k===`1`||k===`&1`)S+=w,w=``;else{let s=Number.parseInt(k,10);if(Number.isNaN(s)){if(O.operator===`>&`){let s=e.fs.resolvePath(e.state.cwd,k),g=await Qe(e,s,k,{checkNoclobber:!0});if(g){w=g,E=1,S=``;break}if(O.fd==null){let t=S+w;await e.fs.writeFile(s,t,D(t)),S=``,w=``}else t===1?(await e.fs.writeFile(s,S,D(S)),S=``):t===2&&(await e.fs.writeFile(s,w,Fe(w)),w=``)}}else{let g=e.state.fileDescriptors?.get(s);if(g?.startsWith(`__file__:`)){let s=g.slice(9);t===1?(await e.fs.appendFile(s,S,D(S)),S=``):t===2&&(await e.fs.appendFile(s,w,Fe(w)),w=``)}else if(g?.startsWith(`__rw__:`)){let s=Ao(g);s&&(t===1?(await e.fs.appendFile(s.path,S,D(S)),S=``):t===2&&(await e.fs.appendFile(s.path,w,Fe(w)),w=``))}else if(g?.startsWith(`__dupout__:`)){let s=Number.parseInt(g.slice(11),10);if(s!==1)if(s===2)t===1&&(w+=S,S=``);else{let g=e.state.fileDescriptors?.get(s);if(g?.startsWith(`__file__:`)){let s=g.slice(9);t===1?(await e.fs.appendFile(s,S,D(S)),S=``):t===2&&(await e.fs.appendFile(s,w,Fe(w)),w=``)}}}else (g?.startsWith(`__dupin__:`)||s>=3)&&(w+=`bash: ${s}: Bad file descriptor
|
|
80
80
|
`,E=1,S=``)}}break}case`&>`:{if(k===`/dev/full`){w=`bash: echo: write error: No space left on device
|
|
81
81
|
`,E=1,S=``;break}let t=e.fs.resolvePath(e.state.cwd,k),s=await Qe(e,t,k,{checkNoclobber:!0});if(s){w=s,E=1,S=``;break}let g=S+w;await e.fs.writeFile(t,g,D(g)),S=``,w=``;break}case`&>>`:{if(k===`/dev/full`){w=`bash: echo: write error: No space left on device
|
|
82
|
-
`,E=1,S=``;break}let t=e.fs.resolvePath(e.state.cwd,k),s=await Qe(e,t,k,{});if(s){w=s,E=1,S=``;break}let g=S+w;await e.fs.appendFile(t,g,D(g)),S=``,w=``;break}}}}let O=e.state.fileDescriptors?.get(1);if(O){if(O===`__dupout__:2`)w+=S,S=``;else if(O.startsWith(`__file__:`)){let t=O.slice(9);await e.fs.appendFile(t,S,D(S)),S=``}else if(O.startsWith(`__file_append__:`)){let t=O.slice(16);await e.fs.appendFile(t,S,D(S)),S=``}}let k=e.state.fileDescriptors?.get(2);if(k){if(k===`__dupout__:1`)S+=w,w=``;else if(k.startsWith(`__file__:`)){let t=k.slice(9);await e.fs.appendFile(t,w,Fe(w)),w=``}else if(k.startsWith(`__file_append__:`)){let t=k.slice(16);await e.fs.appendFile(t,w,Fe(w)),w=``}}return _(S,w,E)}function
|
|
83
|
-
`);let s={...t,sourceFile:t.sourceFile??e.state.currentSource??`main`};return e.state.functions.set(t.name,s),W}async function
|
|
82
|
+
`,E=1,S=``;break}let t=e.fs.resolvePath(e.state.cwd,k),s=await Qe(e,t,k,{});if(s){w=s,E=1,S=``;break}let g=S+w;await e.fs.appendFile(t,g,D(g)),S=``,w=``;break}}}}let O=e.state.fileDescriptors?.get(1);if(O){if(O===`__dupout__:2`)w+=S,S=``;else if(O.startsWith(`__file__:`)){let t=O.slice(9);await e.fs.appendFile(t,S,D(S)),S=``}else if(O.startsWith(`__file_append__:`)){let t=O.slice(16);await e.fs.appendFile(t,S,D(S)),S=``}}let k=e.state.fileDescriptors?.get(2);if(k){if(k===`__dupout__:1`)S+=w,w=``;else if(k.startsWith(`__file__:`)){let t=k.slice(9);await e.fs.appendFile(t,w,Fe(w)),w=``}else if(k.startsWith(`__file_append__:`)){let t=k.slice(16);await e.fs.appendFile(t,w,Fe(w)),w=``}}return _(S,w,E)}function Ln(e,t){if(e.state.options.posix&&Gs.has(t.name))throw new d(2,``,`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
|
|
83
|
+
`);let s={...t,sourceFile:t.sourceFile??e.state.currentSource??`main`};return e.state.functions.set(t.name,s),W}async function _o(e,t){let s=``;for(let g of t)if((g.operator===`<<`||g.operator===`<<-`)&&g.target.type===`HereDoc`){let t=g.target,S=await Pt$1(e,t.content);t.stripTabs&&(S=S.split(`
|
|
84
84
|
`).map(e=>e.replace(/^\t+/,``)).join(`
|
|
85
85
|
`)),(g.fd??0)===0&&(s=S)}else if(g.operator===`<<<`&&g.target.type===`Word`)s=`${await Pt$1(e,g.target)}
|
|
86
|
-
`;else if(g.operator===`<`&&g.target.type===`Word`){let t=await Pt$1(e,g.target),S=e.fs.resolvePath(e.state.cwd,t);try{s=await e.fs.readFile(S)}catch{}}return s}async function
|
|
86
|
+
`;else if(g.operator===`<`&&g.target.type===`Word`){let t=await Pt$1(e,g.target),S=e.fs.resolvePath(e.state.cwd,t);try{s=await e.fs.readFile(S)}catch{}}return s}async function ds(e,t,s,g=``,S){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,Ne(`${t.name}: maximum recursion depth (${e.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,`recursion`)),e.state.funcNameStack||(e.state.funcNameStack=[]),e.state.callLineStack||(e.state.callLineStack=[]),e.state.sourceStack||(e.state.sourceStack=[]),e.state.funcNameStack.unshift(t.name),e.state.callLineStack.unshift(S??e.state.currentLine),e.state.sourceStack.unshift(t.sourceFile??`main`),e.state.localScopes.push(new Map),e.state.localExportedVars||(e.state.localExportedVars=[]),e.state.localExportedVars.push(new Set);let w=new Map;for(let t=0;t<s.length;t++)w.set(String(t+1),e.state.env.get(String(t+1))),e.state.env.set(String(t+1),s[t]);w.set(`@`,e.state.env.get(`@`)),w.set(`#`,e.state.env.get(`#`)),e.state.env.set(`@`,s.join(` `)),e.state.env.set(`#`,String(s.length));let E=()=>{let t=e.state.localScopes.length-1,s=e.state.localScopes.pop();if(s)for(let[t,g]of s)g===void 0?e.state.env.delete(t):e.state.env.set(t,g);if(Tn(e,t),e.state.fullyUnsetLocals)for(let[s,g]of e.state.fullyUnsetLocals.entries())g===t&&e.state.fullyUnsetLocals.delete(s);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let t=e.state.localExportedVars.pop();if(t)for(let s of t)e.state.exportedVars?.delete(s)}for(let[t,s]of w)s===void 0?e.state.env.delete(t):e.state.env.set(t,s);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--},{targets:D,error:O}=await In(e,t.redirections);if(O)return E(),_(``,O,1);try{let s=await _o(e,t.redirections),S=g||s,w=await e.executeCommand(t.body,S);return E(),G(e,w,t.redirections,D)}catch(s){if(E(),s instanceof i)return G(e,_(s.stdout,s.stderr,s.exitCode),t.redirections,D);throw s}}var Mn=[`!`,`[[`,`]]`,`case`,`do`,`done`,`elif`,`else`,`esac`,`fi`,`for`,`function`,`if`,`in`,`then`,`time`,`until`,`while`,`{`,`}`],Ys=`.,:,[,alias,bg,bind,break,builtin,caller,cd,command,compgen,complete,compopt,continue,declare,dirs,disown,echo,enable,eval,exec,exit,export,false,fc,fg,getopts,hash,help,history,jobs,kill,let,local,logout,mapfile,popd,printf,pushd,pwd,read,readarray,readonly,return,set,shift,shopt,source,suspend,test,times,trap,true,type,typeset,ulimit,umask,unalias,unset,wait`.split(`,`),Co=`autocd.assoc_expand_once.cdable_vars.cdspell.checkhash.checkjobs.checkwinsize.cmdhist.compat31.compat32.compat40.compat41.compat42.compat43.compat44.complete_fullquote.direxpand.dirspell.dotglob.execfail.expand_aliases.extdebug.extglob.extquote.failglob.force_fignore.globasciiranges.globstar.gnu_errfmt.histappend.histreedit.histverify.hostcomplete.huponexit.inherit_errexit.interactive_comments.lastpipe.lithist.localvar_inherit.localvar_unset.login_shell.mailwarn.no_empty_cmd_completion.nocaseglob.nocasematch.nullglob.progcomp.progcomp_alias.promptvars.restricted_shell.shift_verbose.sourcepath.xpg_echo`.split(`.`),No=Ys;async function Qs(e,t){let s=[],g=null,S=``,w=``,E=null,D=!1,O=!1,k=!1,j=null,F=null,L=null,B=[],H=[`alias`,`arrayvar`,`binding`,`builtin`,`command`,`directory`,`disabled`,`enabled`,`export`,`file`,`function`,`group`,`helptopic`,`hostname`,`job`,`keyword`,`running`,`service`,`setopt`,`shopt`,`signal`,`stopped`,`user`,`variable`];for(let e=0;e<t.length;e++){let E=t[e];if(E===`-v`)s.push(`variable`);else if(E===`-e`)s.push(`export`);else if(E===`-f`)s.push(`file`);else if(E===`-d`)s.push(`directory`);else if(E===`-k`)s.push(`keyword`);else if(E===`-A`){if(e++,e>=t.length)return A(`compgen: -A: option requires an argument
|
|
87
87
|
`,2);let g=t[e];if(!H.includes(g))return A(`compgen: ${g}: invalid action name
|
|
88
88
|
`,2);s.push(g)}else if(E===`-W`){if(e++,e>=t.length)return A(`compgen: -W: option requires an argument
|
|
89
89
|
`,2);g=t[e]}else if(E===`-P`){if(e++,e>=t.length)return A(`compgen: -P: option requires an argument
|
|
@@ -94,53 +94,53 @@ To resolve the conflict:`,(0,g.getConflictResolutionRecipe)(S,e))),w=E):s.diag.w
|
|
|
94
94
|
`,2);F=t[e]}else if(E===`-C`){if(e++,e>=t.length)return A(`compgen: -C: option requires an argument
|
|
95
95
|
`,2);L=t[e]}else if(E===`-X`){if(e++,e>=t.length)return A(`compgen: -X: option requires an argument
|
|
96
96
|
`,2);j=t[e]}else if(E===`-G`){if(e++,e>=t.length)return A(`compgen: -G: option requires an argument
|
|
97
|
-
`,2)}else if(E===`--`){B.push(...t.slice(e+1));break}else E.startsWith(`-`)||B.push(E)}E=B[0]??null;let q=[];if(O){let t=await
|
|
97
|
+
`,2)}else if(E===`--`){B.push(...t.slice(e+1));break}else E.startsWith(`-`)||B.push(E)}E=B[0]??null;let q=[];if(O){let t=await Xs(e,E);q.push(...t)}if(k){let t=await Fn(e,E);q.push(...t)}for(let t of s)if(t===`variable`){let t=Oo(e,E);q.push(...t)}else if(t===`export`){let t=xo(e,E);q.push(...t)}else if(t===`function`){let t=Do(e,E);q.push(...t)}else if(t===`builtin`){let e=To(E);q.push(...e)}else if(t===`keyword`){let e=Ro(E);q.push(...e)}else if(t===`alias`){let t=Io(e,E);q.push(...t)}else if(t===`shopt`){let e=Lo(E);q.push(...e)}else if(t===`helptopic`){let e=Fo(E);q.push(...e)}else if(t===`directory`){let t=await Xs(e,E);q.push(...t)}else if(t===`file`){let t=await Fn(e,E);q.push(...t)}else if(t===`user`){let e=Mo(E);q.push(...e)}else if(t===`command`){let t=await Wo(e,E);q.push(...t)}if(g!==null)try{let t=Vo(e,await zo(e,g));for(let e of t)(E===null||e.startsWith(E))&&q.push(e)}catch{return _(``,``,1)}if(D){let t=await Xs(e,E);for(let e of t)q.includes(e)||q.push(e)}let ee=``;if(F!==null){let t=e.state.functions.get(F);if(t){let s=new Map;s.set(`COMP_WORDS__length`,e.state.env.get(`COMP_WORDS__length`)),e.state.env.set(`COMP_WORDS__length`,`0`),s.set(`COMP_CWORD`,e.state.env.get(`COMP_CWORD`)),e.state.env.set(`COMP_CWORD`,`-1`),s.set(`COMP_LINE`,e.state.env.get(`COMP_LINE`)),e.state.env.set(`COMP_LINE`,``),s.set(`COMP_POINT`,e.state.env.get(`COMP_POINT`)),e.state.env.set(`COMP_POINT`,`0`);let g=new Map;for(let t of e.state.env.keys())(t===`COMPREPLY`||t.startsWith(`COMPREPLY_`)||t===`COMPREPLY__length`)&&(g.set(t,e.state.env.get(t)),e.state.env.delete(t));let S=[`compgen`,B[0]??``,``];try{let w=await ds(e,t,S,``);if(w.exitCode!==0)return dt(e,s),dt(e,g),_(``,w.stderr,1);ee=w.stdout;let E=Bo(e);q.push(...E)}catch{return dt(e,s),dt(e,g),_(``,``,1)}dt(e,s),dt(e,g)}}if(L!==null)try{let t=di$1(L),s=await e.executeScript(t);if(s.exitCode!==0)return _(``,s.stderr,s.exitCode);if(s.stdout){let e=s.stdout.split(`
|
|
98
98
|
`);for(let t of e)t.length>0&&q.push(t)}}catch(e){if(e.name===`ParseException`)return A(`compgen: -C: ${e.message}
|
|
99
99
|
`,2);throw e}let J=q;if(j!==null){let e=j.startsWith(`!`),t=e?j.slice(1):j;J=q.filter(s=>{let g=ct(s,t,!1,!0);return e?g:!g})}if(J.length===0&&E!==null)return _(ee,``,1);let Y=J.map(e=>`${S}${e}${w}`).join(`
|
|
100
100
|
`);return z(ee+(Y?`${Y}
|
|
101
|
-
`:``))}function
|
|
102
|
-
`;if(s.length===0)return[t];let g=new Set(s.split(``)),S=[],w=``,E=0;for(;E<t.length;){let e=t[E];if(e===`\\`&&E+1<t.length){let e=t[E+1];w+=e,E+=2}else g.has(e)?(w.length>0&&(S.push(w),w=``),E++):(w+=e,E++)}return w.length>0&&S.push(w),S}function dt(e,t){for(let[s,g]of t)g===void 0?e.state.env.delete(s):e.state.env.set(s,g)}function
|
|
101
|
+
`:``))}function Oo(e,t){let s=new Set;for(let t of e.state.env.keys()){if(t.includes(`_`)&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(t)||t.endsWith(`__length`))continue;let g=t.split(`_`)[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?s.add(t):g&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(g)&&e.state.env.has(`${g}__length`)&&s.add(g)}let g=Array.from(s);return t!==null&&(g=g.filter(e=>e.startsWith(t))),g.sort()}function xo(e,t){let s=e.state.exportedVars??new Set,g=Array.from(s);return t!==null&&(g=g.filter(e=>e.startsWith(t))),g=g.filter(t=>t.includes(`_`)&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(t)||t.endsWith(`__length`)?!1:e.state.env.has(t)),g.sort()}function Do(e,t){let s=Array.from(e.state.functions.keys());return t!==null&&(s=s.filter(e=>e.startsWith(t))),s.sort()}function To(e){let t=[...Ys];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}function Ro(e){let t=[...Mn];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}function Io(e,t){let s=[];for(let t of e.state.env.keys())if(t.startsWith(`BASH_ALIAS_`)){let e=t.slice(11);s.push(e)}let g=s;return t!==null&&(g=g.filter(e=>e.startsWith(t))),g.sort()}function Lo(e){let t=[...Co];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}function Fo(e){let t=[...No];return e!==null&&(t=t.filter(t=>t.startsWith(e))),t.sort()}async function Xs(e,t){let s=[];try{let g=e.state.cwd,S=t??``;if(t){let s=t.lastIndexOf(`/`);if(s!==-1){let w=t.slice(0,s)||`/`;S=t.slice(s+1),g=w.startsWith(`/`)?w:`${e.state.cwd}/${w}`}}let w=await e.fs.readdir(g);for(let E of w){let w=`${g}/${E}`;try{if((await e.fs.stat(w)).isDirectory&&(!S||E.startsWith(S)))if(t?.includes(`/`)){let e=t.lastIndexOf(`/`),g=t.slice(0,e+1);s.push(g+E)}else s.push(E)}catch{}}}catch{}return s.sort()}async function Fn(e,t){let s=[];try{let g=e.state.cwd,S=t??``;if(t){let s=t.lastIndexOf(`/`);if(s!==-1){let w=t.slice(0,s)||`/`;S=t.slice(s+1),g=w.startsWith(`/`)?w:`${e.state.cwd}/${w}`}}let w=await e.fs.readdir(g);for(let e of w)if(!S||e.startsWith(S))if(t?.includes(`/`)){let g=t.lastIndexOf(`/`),S=t.slice(0,g+1);s.push(S+e)}else s.push(e)}catch{}return s.sort()}function Mo(e){return[`root`,`nobody`]}async function Wo(e,t){let s=new Set;for(let e of Ys)s.add(e);for(let t of e.state.functions.keys())s.add(t);for(let t of e.state.env.keys())t.startsWith(`BASH_ALIAS_`)&&s.add(t.slice(11));for(let e of Mn)s.add(e);let g=e.state.env.get(`PATH`)??`/usr/bin:/bin`;for(let t of g.split(`:`))if(t)try{let g=await e.fs.readdir(t);for(let e of g)s.add(e)}catch{}let S=Array.from(s);return t!==null&&(S=S.filter(e=>e.startsWith(t))),S.sort()}async function zo(e,t){return await Pt$1(e,new V().parseWordFromString(t,!1,!1))}function Vo(e,t){let s=e.state.env.get(`IFS`)??`
|
|
102
|
+
`;if(s.length===0)return[t];let g=new Set(s.split(``)),S=[],w=``,E=0;for(;E<t.length;){let e=t[E];if(e===`\\`&&E+1<t.length){let e=t[E+1];w+=e,E+=2}else g.has(e)?(w.length>0&&(S.push(w),w=``),E++):(w+=e,E++)}return w.length>0&&S.push(w),S}function dt(e,t){for(let[s,g]of t)g===void 0?e.state.env.delete(s):e.state.env.set(s,g)}function Bo(e){let t=[];if(e.state.env.get(`COMPREPLY__length`)!==void 0){let s=P(e,`COMPREPLY`);for(let[,e]of s)t.push(e)}else{let s=e.state.env.get(`COMPREPLY`);s!==void 0&&t.push(s)}return t}var jo=[`bashdefault`,`default`,`dirnames`,`filenames`,`noquote`,`nosort`,`nospace`,`plusdirs`];function er(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,g=!1,S=!1,w,E,D,O=[],k=[],j=[];for(let e=0;e<t.length;e++){let F=t[e];if(F===`-p`)s=!0;else if(F===`-r`)g=!0;else if(F===`-D`)S=!0;else if(F===`-W`){if(e++,e>=t.length)return A(`complete: -W: option requires an argument
|
|
103
103
|
`,2);w=t[e]}else if(F===`-F`){if(e++,e>=t.length)return A(`complete: -F: option requires an argument
|
|
104
104
|
`,2);E=t[e]}else if(F===`-o`){if(e++,e>=t.length)return A(`complete: -o: option requires an argument
|
|
105
|
-
`,2);let s=t[e];if(!
|
|
105
|
+
`,2);let s=t[e];if(!jo.includes(s))return A(`complete: ${s}: invalid option name
|
|
106
106
|
`,2);O.push(s)}else if(F===`-A`){if(e++,e>=t.length)return A(`complete: -A: option requires an argument
|
|
107
107
|
`,2);k.push(t[e])}else if(F===`-C`){if(e++,e>=t.length)return A(`complete: -C: option requires an argument
|
|
108
108
|
`,2);D=t[e]}else if(F===`-G`){if(e++,e>=t.length)return A(`complete: -G: option requires an argument
|
|
109
109
|
`,2)}else if(F===`-P`){if(e++,e>=t.length)return A(`complete: -P: option requires an argument
|
|
110
110
|
`,2)}else if(F===`-S`){if(e++,e>=t.length)return A(`complete: -S: option requires an argument
|
|
111
111
|
`,2)}else if(F===`-X`){if(e++,e>=t.length)return A(`complete: -X: option requires an argument
|
|
112
|
-
`,2)}else if(F===`--`){j.push(...t.slice(e+1));break}else F.startsWith(`-`)||j.push(F)}if(g){if(j.length===0)return e.state.completionSpecs.clear(),z(``);for(let t of j)e.state.completionSpecs.delete(t);return z(``)}if(s)return j.length===0?
|
|
113
|
-
`,2);if(S){let t={isDefault:!0};return w!==void 0&&(t.wordlist=w),E!==void 0&&(t.function=E),D!==void 0&&(t.command=D),O.length>0&&(t.options=O),k.length>0&&(t.actions=k),e.state.completionSpecs.set(`__default__`,t),z(``)}for(let t of j){let s=Object.create(null);w!==void 0&&(s.wordlist=w),E!==void 0&&(s.function=E),D!==void 0&&(s.command=D),O.length>0&&(s.options=O),k.length>0&&(s.actions=k),e.state.completionSpecs.set(t,s)}return z(``)}function
|
|
112
|
+
`,2)}else if(F===`--`){j.push(...t.slice(e+1));break}else F.startsWith(`-`)||j.push(F)}if(g){if(j.length===0)return e.state.completionSpecs.clear(),z(``);for(let t of j)e.state.completionSpecs.delete(t);return z(``)}if(s)return j.length===0?Js(e):Js(e,j);if(t.length===0||j.length===0&&!w&&!E&&!D&&O.length===0&&k.length===0&&!S)return Js(e);if(E&&j.length===0&&!S)return A(`complete: -F: option requires a command name
|
|
113
|
+
`,2);if(S){let t={isDefault:!0};return w!==void 0&&(t.wordlist=w),E!==void 0&&(t.function=E),D!==void 0&&(t.command=D),O.length>0&&(t.options=O),k.length>0&&(t.actions=k),e.state.completionSpecs.set(`__default__`,t),z(``)}for(let t of j){let s=Object.create(null);w!==void 0&&(s.wordlist=w),E!==void 0&&(s.function=E),D!==void 0&&(s.command=D),O.length>0&&(s.options=O),k.length>0&&(s.actions=k),e.state.completionSpecs.set(t,s)}return z(``)}function Js(e,t){let s=e.state.completionSpecs;if(!s||s.size===0){if(t&&t.length>0){let e=``;for(let s of t)e+=`complete: ${s}: no completion specification
|
|
114
114
|
`;return _(``,e,1)}return z(``)}let g=[],S=t||Array.from(s.keys());for(let e of S){if(e===`__default__`)continue;let S=s.get(e);if(!S){if(t)return _(g.join(`
|
|
115
115
|
`)+(g.length>0?`
|
|
116
116
|
`:``),`complete: ${e}: no completion specification
|
|
117
117
|
`,1);continue}let w=`complete`;if(S.options)for(let e of S.options)w+=` -o ${e}`;if(S.actions)for(let e of S.actions)w+=` -A ${e}`;S.wordlist!==void 0&&(S.wordlist.includes(` `)||S.wordlist.includes(`'`)?w+=` -W '${S.wordlist}'`:w+=` -W ${S.wordlist}`),S.function!==void 0&&(w+=` -F ${S.function}`),S.isDefault&&(w+=` -D`),w+=` ${e}`,g.push(w)}return g.length===0?z(``):z(`${g.join(`
|
|
118
118
|
`)}
|
|
119
|
-
`)}var
|
|
120
|
-
`,2);let s=t[e];if(!
|
|
119
|
+
`)}var Wn=[`bashdefault`,`default`,`dirnames`,`filenames`,`noquote`,`nosort`,`nospace`,`plusdirs`];function tr(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,g=!1,S=[],w=[],E=[];for(let e=0;e<t.length;e++){let D=t[e];if(D===`-D`)s=!0;else if(D===`-E`)g=!0;else if(D===`-o`){if(e++,e>=t.length)return A(`compopt: -o: option requires an argument
|
|
120
|
+
`,2);let s=t[e];if(!Wn.includes(s))return A(`compopt: ${s}: invalid option name
|
|
121
121
|
`,2);S.push(s)}else if(D===`+o`){if(e++,e>=t.length)return A(`compopt: +o: option requires an argument
|
|
122
|
-
`,2);let s=t[e];if(!
|
|
122
|
+
`,2);let s=t[e];if(!Wn.includes(s))return A(`compopt: ${s}: invalid option name
|
|
123
123
|
`,2);w.push(s)}else if(D===`--`){E.push(...t.slice(e+1));break}else !D.startsWith(`-`)&&!D.startsWith(`+`)&&E.push(D)}if(s){let t=e.state.completionSpecs.get(`__default__`)??{isDefault:!0},s=new Set(t.options??[]);for(let e of S)s.add(e);for(let e of w)s.delete(e);return t.options=s.size>0?Array.from(s):void 0,e.state.completionSpecs.set(`__default__`,t),z(``)}if(g){let t=e.state.completionSpecs.get(`__empty__`)??{},s=new Set(t.options??[]);for(let e of S)s.add(e);for(let e of w)s.delete(e);return t.options=s.size>0?Array.from(s):void 0,e.state.completionSpecs.set(`__empty__`,t),z(``)}if(E.length>0){for(let t of E){let s=e.state.completionSpecs.get(t)??{},g=new Set(s.options??[]);for(let e of S)g.add(e);for(let e of w)g.delete(e);s.options=g.size>0?Array.from(g):void 0,e.state.completionSpecs.set(t,s)}return z(``)}return A(`compopt: not currently executing completion function
|
|
124
|
-
`,1)}function
|
|
124
|
+
`,1)}function sr(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: continue: too many arguments
|
|
125
125
|
`);let s=1;if(t.length>0){let e=Number.parseInt(t[0],10);if(Number.isNaN(e)||e<1)throw new d(1,``,`bash: continue: ${t[0]}: numeric argument required
|
|
126
|
-
`);s=e}throw new a(s)}function X(e,t){let s=e.state.env.get(`HOME`)||`/home/user`;return t.split(`:`).map(e=>e===`~`?s:e===`~root`?`/root`:e.startsWith(`~/`)?s+e.slice(1):e.startsWith(`~root/`)?`/root${e.slice(5)}`:e).join(`:`)}function
|
|
127
|
-
`;else{let g=t.map(t=>`['${t}']=${
|
|
126
|
+
`);s=e}throw new a(s)}function X(e,t){let s=e.state.env.get(`HOME`)||`/home/user`;return t.split(`:`).map(e=>e===`~`?s:e===`~root`?`/root`:e.startsWith(`~/`)?s+e.slice(1):e.startsWith(`~root/`)?`/root${e.slice(5)}`:e).join(`:`)}function rr(e){for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);if(s<32||s===127)return!0}return!1}function nr(e){let t=`$'`;for(let s=0;s<e.length;s++){let g=e[s],S=e.charCodeAt(s);S===7?t+=`\\a`:S===8?t+=`\\b`:S===9?t+=`\\t`:S===10?t+=`\\n`:S===11?t+=`\\v`:S===12?t+=`\\f`:S===13?t+=`\\r`:S===27?t+=`\\e`:S===39?t+=`\\'`:S===92?t+=`\\\\`:S<32||S===127?t+=`\\${S.toString(8).padStart(3,`0`)}`:t+=g}return t+=`'`,t}function hs(e){return rr(e)?nr(e):/^[a-zA-Z0-9_/.:\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function Je(e){return rr(e)?nr(e):`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function ir(e){return rr(e)?nr(e):`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function zn(e,t){let s=``;return e.state.integerVars?.has(t)&&(s+=`i`),e.state.lowercaseVars?.has(t)&&(s+=`l`),W$1(e,t)&&(s+=`n`),e.state.readonlyVars?.has(t)&&(s+=`r`),e.state.uppercaseVars?.has(t)&&(s+=`u`),e.state.exportedVars?.has(t)&&(s+=`x`),s===``?`--`:`-${s}`}function or(e){return e===``?`''`:/[\s'\\]/.test(e)?`'${e.replace(/'/g,`'\\''`)}'`:e}function Vn(e,t){let s=``,g=``,S=!1;for(let w of t){let t=zn(e,w);if(e.state.associativeArrays?.has(w)){let t=gt$1(e,w);if(t.length===0)s+=`declare -A ${w}=()
|
|
127
|
+
`;else{let g=t.map(t=>`['${t}']=${or(e.state.env.get(`${w}_${t}`)??``)}`);s+=`declare -A ${w}=(${g.join(` `)})
|
|
128
128
|
`}continue}let E=mt$1(e,w);if(E.length>0){let t=E.map(t=>`[${t}]=${Je(e.state.env.get(`${w}_${t}`)??``)}`);s+=`declare -a ${w}=(${t.join(` `)})
|
|
129
129
|
`;continue}if(e.state.env.has(`${w}__length`)){s+=`declare -a ${w}=()
|
|
130
|
-
`;continue}let D=e.state.env.get(w);if(D!==void 0)s+=`declare ${t} ${w}=${
|
|
130
|
+
`;continue}let D=e.state.env.get(w);if(D!==void 0)s+=`declare ${t} ${w}=${ir(D)}
|
|
131
131
|
`;else{let E=e.state.declaredVars?.has(w),D=e.state.localVarDepth?.has(w);E||D?s+=`declare ${t} ${w}
|
|
132
132
|
`:(g+=`bash: declare: ${w}: not found
|
|
133
|
-
`,S=!0)}}return _(s,g,S?1:0)}function
|
|
134
|
-
`;else{let g=s.map(s=>`['${s}']=${
|
|
133
|
+
`,S=!0)}}return _(s,g,S?1:0)}function Bn(e,t){let{filterExport:s,filterReadonly:g,filterNameref:S,filterIndexedArray:w,filterAssocArray:E}=t,D=s||g||S||w||E,O=``,k=new Set;for(let t of e.state.env.keys()){if(t.startsWith(`BASH_`))continue;if(t.endsWith(`__length`)){let e=t.slice(0,-8);k.add(e);continue}let s=t.lastIndexOf(`_`);if(s>0){let g=t.slice(0,s),S=t.slice(s+1);if(/^\d+$/.test(S)||e.state.associativeArrays?.has(g)){k.add(g);continue}}k.add(t)}if(e.state.localVarDepth)for(let t of e.state.localVarDepth.keys())k.add(t);if(e.state.associativeArrays)for(let t of e.state.associativeArrays)k.add(t);let j=Array.from(k).sort();for(let t of j){let k=zn(e,t),j=e.state.associativeArrays?.has(t),F=mt$1(e,t),L=!j&&(F.length>0||e.state.env.has(`${t}__length`));if(D&&(E&&!j||w&&!L||s&&!e.state.exportedVars?.has(t)||g&&!e.state.readonlyVars?.has(t)||S&&!W$1(e,t)))continue;if(j){let s=gt$1(e,t);if(s.length===0)O+=`declare -A ${t}=()
|
|
134
|
+
`;else{let g=s.map(s=>`['${s}']=${or(e.state.env.get(`${t}_${s}`)??``)}`);O+=`declare -A ${t}=(${g.join(` `)})
|
|
135
135
|
`}continue}if(F.length>0){let s=F.map(s=>`[${s}]=${Je(e.state.env.get(`${t}_${s}`)??``)}`);O+=`declare -a ${t}=(${s.join(` `)})
|
|
136
136
|
`;continue}if(e.state.env.has(`${t}__length`)){O+=`declare -a ${t}=()
|
|
137
|
-
`;continue}let B=e.state.env.get(t);B!==void 0&&(O+=`declare ${k} ${t}=${
|
|
138
|
-
`)}return z(O)}function
|
|
139
|
-
`;else{let S=s.map(t=>`['${t}']=${
|
|
140
|
-
`}}return z(t)}function
|
|
137
|
+
`;continue}let B=e.state.env.get(t);B!==void 0&&(O+=`declare ${k} ${t}=${ir(B)}
|
|
138
|
+
`)}return z(O)}function jn(e){let t=``,s=Array.from(e.state.associativeArrays??[]).sort();for(let g of s){let s=gt$1(e,g);if(s.length===0)t+=`declare -A ${g}=()
|
|
139
|
+
`;else{let S=s.map(t=>`['${t}']=${or(e.state.env.get(`${g}_${t}`)??``)}`);t+=`declare -A ${g}=(${S.join(` `)})
|
|
140
|
+
`}}return z(t)}function Un(e){let t=``,s=new Set;for(let t of e.state.env.keys()){if(t.startsWith(`BASH_`))continue;if(t.endsWith(`__length`)){let g=t.slice(0,-8);e.state.associativeArrays?.has(g)||s.add(g);continue}let g=t.lastIndexOf(`_`);if(g>0){let S=t.slice(0,g),w=t.slice(g+1);/^\d+$/.test(w)&&(e.state.associativeArrays?.has(S)||s.add(S))}}let g=Array.from(s).sort();for(let s of g){let g=mt$1(e,s);if(g.length===0)t+=`declare -a ${s}=()
|
|
141
141
|
`;else{let S=g.map(t=>`[${t}]=${Je(e.state.env.get(`${s}_${t}`)??``)}`);t+=`declare -a ${s}=(${S.join(` `)})
|
|
142
|
-
`}}return z(t)}function
|
|
143
|
-
`)}return z(t)}function
|
|
142
|
+
`}}return z(t)}function Hn(e){let t=``,s=new Set;for(let t of e.state.env.keys()){if(t.startsWith(`BASH_`))continue;if(t.endsWith(`__length`)){let e=t.slice(0,-8);s.add(e);continue}let g=t.lastIndexOf(`_`);if(g>0){let S=t.slice(0,g),w=t.slice(g+1);if(/^\d+$/.test(w)||e.state.associativeArrays?.has(S)){s.add(S);continue}}s.add(t)}let g=Array.from(s).sort();for(let s of g){if(e.state.associativeArrays?.has(s)||mt$1(e,s).length>0||e.state.env.has(`${s}__length`))continue;let g=e.state.env.get(s);g!==void 0&&(t+=`${s}=${hs(g)}
|
|
143
|
+
`)}return z(t)}function ar(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function kt(e,t){return e.state.integerVars?.has(t)??!1}function lr(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function Uo(e,t){return e.state.lowercaseVars?.has(t)??!1}function cr(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function Ho(e,t){return e.state.uppercaseVars?.has(t)??!1}function ht(e,t,s){return Uo(e,t)?s.toLowerCase():Ho(e,t)?s.toUpperCase():s}async function Zn(e,t){try{let s=await R(e,M(new V,t).expression);return String(s)}catch{return`0`}}function Zo(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let s=t[0],g=s.length;if(e[g]!==`[`)return null;let S=0,w=g+1;for(;g<e.length;g++)if(e[g]===`[`)S++;else if(e[g]===`]`&&(S--,S===0))break;if(S!==0)return null;let E=e.slice(w,g);return g++,e[g]===`=`?(g++,{name:s,indexExpr:E,value:e.slice(g)}):null}async function ur(e,t){let s=!1,g=!1,S=!1,w=!1,E=!1,D=!1,O=!1,k=!1,j=!1,F=!1,L=!1,B=!1,H=!1,q=!1,ee=!1,J=[];for(let e=0;e<t.length;e++){let Y=t[e];if(Y===`-a`)s=!0;else if(Y===`-A`)g=!0;else if(Y===`-r`)S=!0;else if(Y===`-x`)w=!0;else if(Y===`-p`)E=!0;else if(Y===`-n`)D=!0;else if(Y===`+n`)O=!0;else if(Y===`+a`)k=!0;else if(Y===`+x`)j=!0;else if(Y===`--`){J.push(...t.slice(e+1));break}else if(Y.startsWith(`+`)){for(let e of Y.slice(1))if(e===`n`)O=!0;else if(e===`a`)k=!0;else if(e===`x`)j=!0;else if(e!==`r`&&e!==`i`&&!(e===`f`||e===`F`))return _(``,`bash: typeset: +${e}: invalid option
|
|
144
144
|
`,2)}else if(Y===`-i`)F=!0;else if(Y===`-l`)L=!0;else if(Y===`-u`)B=!0;else if(Y===`-f`)H=!0;else if(Y===`-F`)q=!0;else if(Y===`-g`)ee=!0;else if(Y.startsWith(`-`))for(let e of Y.slice(1))if(e===`a`)s=!0;else if(e===`A`)g=!0;else if(e===`r`)S=!0;else if(e===`x`)w=!0;else if(e===`p`)E=!0;else if(e===`n`)D=!0;else if(e===`i`)F=!0;else if(e===`l`)L=!0;else if(e===`u`)B=!0;else if(e===`f`)H=!0;else if(e===`F`)q=!0;else if(e===`g`)ee=!0;else return _(``,`bash: typeset: -${e}: invalid option
|
|
145
145
|
`,2);else J.push(Y)}let Y=e.state.localScopes.length>0&&!ee,te=t=>{if(!Y)return;let s=e.state.localScopes[e.state.localScopes.length-1];s.has(t)||s.set(t,e.state.env.get(t))},ne=t=>{if(!Y)return;let s=e.state.localScopes[e.state.localScopes.length-1];s.has(t)||s.set(t,e.state.env.get(t));let g=`${t}_`;for(let t of e.state.env.keys())t.startsWith(g)&&!t.includes(`__`)&&(s.has(t)||s.set(t,e.state.env.get(t)));let S=`${t}__length`;e.state.env.has(S)&&!s.has(S)&&s.set(S,e.state.env.get(S))},ae=t=>{Y&&Ze(e,t)};if(q){if(J.length===0){let t=Array.from(e.state.functions.keys()).sort(),s=``;for(let e of t)s+=`declare -f ${e}
|
|
146
146
|
`;return z(s)}let t=!0,s=``;for(let g of J)e.state.functions.has(g)?s+=`${g}
|
|
@@ -148,42 +148,42 @@ To resolve the conflict:`,(0,g.getConflictResolutionRecipe)(S,e))),w=E):s.diag.w
|
|
|
148
148
|
{
|
|
149
149
|
# function body
|
|
150
150
|
}
|
|
151
|
-
`;return z(t)}let t=!0;for(let s of J)e.state.functions.has(s)||(t=!1);return _(``,``,t?0:1)}if(E&&J.length>0)return
|
|
151
|
+
`;return z(t)}let t=!0;for(let s of J)e.state.functions.has(s)||(t=!1);return _(``,``,t?0:1)}if(E&&J.length>0)return Vn(e,J);if(E&&J.length===0)return Bn(e,{filterExport:w,filterReadonly:S,filterNameref:D,filterIndexedArray:s,filterAssocArray:g});if(J.length===0&&g&&!E)return jn(e);if(J.length===0&&s&&!E)return Un(e);if(J.length===0&&!E)return Hn(e);let oe=``,se=0;for(let t of J){let E=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(E&&!k){let t=E[1],D=E[2];if(g&&mt$1(e,t).length>0){oe+=`bash: declare: ${t}: cannot convert indexed to associative array
|
|
152
152
|
`,se=1;continue}if((s||!g&&!s)&&e.state.associativeArrays?.has(t)){oe+=`bash: declare: ${t}: cannot convert associative to indexed array
|
|
153
|
-
`,se=1;continue}if(ne(t),g&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(t)),Ci$1(e,t),e.state.env.delete(t),e.state.env.delete(`${t}__length`),g&&D.includes(`[`)){let s=
|
|
153
|
+
`,se=1;continue}if(ne(t),g&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(t)),Ci$1(e,t),e.state.env.delete(t),e.state.env.delete(`${t}__length`),g&&D.includes(`[`)){let s=ls(D);for(let[g,S]of s){let s=X(e,S);e.state.env.set(`${t}_${g}`,s)}}else if(g){let s=Oe(D);for(let g=0;g<s.length;g+=2){let S=s[g],w=g+1<s.length?X(e,s[g+1]):``;e.state.env.set(`${t}_${S}`,w)}}else{let s=Oe(D);if(s.some(e=>/^\[[^\]]+\]=/.test(e))){let g=0;for(let S of s){let s=S.match(/^\[([^\]]+)\]=(.*)$/);if(s){let S=s[1],w=s[2],E=X(e,w),D;if(/^-?\d+$/.test(S))D=Number.parseInt(S,10);else try{D=await R(e,M(new V,S).expression)}catch{D=0}e.state.env.set(`${t}_${D}`,E),g=D+1}else{let s=X(e,S);e.state.env.set(`${t}_${g}`,s),g++}}}else{for(let g=0;g<s.length;g++)e.state.env.set(`${t}_${g}`,s[g]);e.state.env.set(`${t}__length`,String(s.length))}}ae(t),S&&pa$1(e,t),w&&ma$1(e,t);continue}if(O&&(qi$1(e,t.includes(`=`)?t.slice(0,t.indexOf(`=`)):t),!t.includes(`=`))||j&&(ga$1(e,t.includes(`=`)?t.slice(0,t.indexOf(`=`)):t),!t.includes(`=`)))continue;let H=Zo(t);if(H){let{name:t,indexExpr:s,value:g}=H,E=da$1(e,t);if(E)return E;ne(t);let D;try{D=await R(e,M(new V,s).expression)}catch{let e=parseInt(s,10);D=Number.isNaN(e)?0:e}e.state.env.set(`${t}_${D}`,g);let O=parseInt(e.state.env.get(`${t}__length`)??`0`,10);D>=O&&e.state.env.set(`${t}__length`,String(D+1)),ae(t),S&&pa$1(e,t),w&&ma$1(e,t);continue}let q=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(q&&!k){let t=q[1],s=q[2],g=da$1(e,t);if(g)return g;ne(t);let E=Oe(s);if(e.state.associativeArrays?.has(t)){let g=ls(s);for(let[s,S]of g){let g=X(e,S);e.state.env.set(`${t}_${s}`,g)}}else{let s=mt$1(e,t),g=0,S=e.state.env.get(t);s.length===0&&S!==void 0?(e.state.env.set(`${t}_0`,S),e.state.env.delete(t),g=1):s.length>0&&(g=Math.max(...s)+1);for(let s=0;s<E.length;s++)e.state.env.set(`${t}_${g+s}`,X(e,E[s]));let w=g+E.length;e.state.env.set(`${t}__length`,String(w))}ae(t),S&&pa$1(e,t),w&&ma$1(e,t);continue}let ee=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(ee){let t=ee[1],s=X(e,ee[2]),g=da$1(e,t);if(g)return g;te(t),F&&ar(e,t),L&&lr(e,t),B&&cr(e,t);let E=mt$1(e,t).length>0||e.state.associativeArrays?.has(t);if(kt(e,t)){let g=e.state.env.get(t)??`0`,S=parseInt(g,10)||0,w=parseInt(await Zn(e,s),10)||0;s=String(S+w),e.state.env.set(t,s)}else if(E){s=ht(e,t,s);let g=`${t}_0`,S=e.state.env.get(g)??``;e.state.env.set(g,S+s)}else{s=ht(e,t,s);let g=e.state.env.get(t)??``;e.state.env.set(t,g+s)}ae(t),S&&pa$1(e,t),w&&ma$1(e,t),e.state.options.allexport&&!j&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(t));continue}if(t.includes(`=`)){let s=t.indexOf(`=`),g=t.slice(0,s),E=t.slice(s+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(g)){oe+=`bash: typeset: \`${g}': not a valid identifier
|
|
154
154
|
`,se=1;continue}let O=da$1(e,g);if(O)return O;if(te(g),D){if(E!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(E)){oe+=`bash: declare: \`${E}': invalid variable name for name reference
|
|
155
|
-
`,se=1;continue}e.state.env.set(g,E),Vi$1(e,g),E!==``&&us$1(e,E)&&Fi$1(e,g),ae(g),S&&pa$1(e,g),w&&ma$1(e,g);continue}if(F&&
|
|
156
|
-
`,se=1;continue}if(s||g?ne(E):te(E),D){Vi$1(e,E);let t=e.state.env.get(E);t!==void 0&&t!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(t)?Bi$1(e,E):t&&us$1(e,t)&&Fi$1(e,E),ae(E),S&&pa$1(e,E),w&&ma$1(e,E);continue}if(F&&
|
|
157
|
-
`,se=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(E)}let O=Array.from(e.state.env.keys()).some(e=>e.startsWith(`${E}_`)&&!e.startsWith(`${E}__length`));!e.state.env.has(E)&&!O&&(s||g?e.state.env.set(`${E}__length`,`0`):(e.state.declaredVars??=new Set,e.state.declaredVars.add(E))),ae(E),S&&pa$1(e,E),w&&ma$1(e,E)}}return _(``,oe,se)}async function
|
|
158
|
-
`}}return z(t)}for(let t of s){let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(s){let t=s[1],g=s[2],S=da$1(e,t);if(S)return S;let w=Oe(g);if(e.state.associativeArrays?.has(t)){let s=
|
|
155
|
+
`,se=1;continue}e.state.env.set(g,E),Vi$1(e,g),E!==``&&us$1(e,E)&&Fi$1(e,g),ae(g),S&&pa$1(e,g),w&&ma$1(e,g);continue}if(F&&ar(e,g),L&&lr(e,g),B&&cr(e,g),kt(e,g)&&(E=await Zn(e,E)),E=ht(e,g,E),W$1(e,g)){let t=he(e,g);t&&t!==g?e.state.env.set(t,E):e.state.env.set(g,E)}else e.state.env.set(g,E);ae(g),S&&pa$1(e,g),w&&ma$1(e,g),e.state.options.allexport&&!j&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(g))}else{let E=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(E)){oe+=`bash: typeset: \`${E}': not a valid identifier
|
|
156
|
+
`,se=1;continue}if(s||g?ne(E):te(E),D){Vi$1(e,E);let t=e.state.env.get(E);t!==void 0&&t!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(t)?Bi$1(e,E):t&&us$1(e,t)&&Fi$1(e,E),ae(E),S&&pa$1(e,E),w&&ma$1(e,E);continue}if(F&&ar(e,E),L&&lr(e,E),B&&cr(e,E),g){if(mt$1(e,E).length>0){oe+=`bash: declare: ${E}: cannot convert indexed to associative array
|
|
157
|
+
`,se=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(E)}let O=Array.from(e.state.env.keys()).some(e=>e.startsWith(`${E}_`)&&!e.startsWith(`${E}__length`));!e.state.env.has(E)&&!O&&(s||g?e.state.env.set(`${E}__length`,`0`):(e.state.declaredVars??=new Set,e.state.declaredVars.add(E))),ae(E),S&&pa$1(e,E),w&&ma$1(e,E)}}return _(``,oe,se)}async function fr(e,t){let s=[];for(let e=0;e<t.length;e++){let g=t[e];if(g!==`-a`&&g!==`-A`&&g!==`-p`)if(g===`--`){s.push(...t.slice(e+1));break}else g.startsWith(`-`)||s.push(g)}if(s.length===0){let t=``,s=Array.from(e.state.readonlyVars||[]).sort();for(let g of s){let s=e.state.env.get(g);if(s!==void 0){let e=s.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);t+=`declare -r ${g}="${e}"
|
|
158
|
+
`}}return z(t)}for(let t of s){let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(s){let t=s[1],g=s[2],S=da$1(e,t);if(S)return S;let w=Oe(g);if(e.state.associativeArrays?.has(t)){let s=ls(g);for(let[g,S]of s){let s=X(e,S);e.state.env.set(`${t}_${g}`,s)}}else{let s=mt$1(e,t),g=0,S=e.state.env.get(t);s.length===0&&S!==void 0?(e.state.env.set(`${t}_0`,S),e.state.env.delete(t),g=1):s.length>0&&(g=Math.max(...s)+1);for(let s=0;s<w.length;s++)e.state.env.set(`${t}_${g+s}`,X(e,w[s]));let E=g+w.length;e.state.env.set(`${t}__length`,String(E))}pa$1(e,t);continue}let g=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(g){let t=g[1],s=X(e,g[2]),S=da$1(e,t);if(S)return S;let w=e.state.env.get(t)??``;e.state.env.set(t,w+s),pa$1(e,t);continue}let S=On(t);if(S.value===void 0&&!S.isArray){pa$1(e,S.name);continue}let w=await xn(e,S,{makeReadonly:!0});if(w)return w}return W}function dr(e){return e.state.directoryStack??=[],e.state.directoryStack}function _t(e,t){return t&&e===t?`~`:t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function qo(e){let t=e.split(`/`).filter(e=>e&&e!==`.`),s=[];for(let e of t)e===`..`?s.pop():s.push(e);return`/${s.join(`/`)}`}async function hr(e,t){let s=dr(e),g;for(let e=0;e<t.length;e++){let s=t[e];if(s===`--`){if(e+1<t.length){if(g!==void 0)return A(`bash: pushd: too many arguments
|
|
159
159
|
`,2);g=t[e+1],e++}}else{if(s.startsWith(`-`)&&s!==`-`)return A(`bash: pushd: ${s}: invalid option
|
|
160
160
|
`,2);if(g!==void 0)return A(`bash: pushd: too many arguments
|
|
161
161
|
`,2);g=s}}if(g===void 0){if(s.length<2)return A(`bash: pushd: no other directory
|
|
162
|
-
`,1);let e=s[0];s[0]=s[1],s[1]=e,g=s[0]}let S;if(g.startsWith(`/`))S=g;else if(g===`..`){let t=e.state.cwd.split(`/`).filter(e=>e);t.pop(),S=`/${t.join(`/`)}`}else S=g===`.`?e.state.cwd:g.startsWith(`~`)?(e.state.env.get(`HOME`)||`/`)+g.slice(1):`${e.state.cwd}/${g}`;S=
|
|
162
|
+
`,1);let e=s[0];s[0]=s[1],s[1]=e,g=s[0]}let S;if(g.startsWith(`/`))S=g;else if(g===`..`){let t=e.state.cwd.split(`/`).filter(e=>e);t.pop(),S=`/${t.join(`/`)}`}else S=g===`.`?e.state.cwd:g.startsWith(`~`)?(e.state.env.get(`HOME`)||`/`)+g.slice(1):`${e.state.cwd}/${g}`;S=qo(S);try{if(!(await e.fs.stat(S)).isDirectory)return A(`bash: pushd: ${g}: Not a directory
|
|
163
163
|
`,1)}catch{return A(`bash: pushd: ${g}: No such file or directory
|
|
164
|
-
`,1)}s.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=S,e.state.env.set(`PWD`,S),e.state.env.set(`OLDPWD`,e.state.previousDir);let w=e.state.env.get(`HOME`)||``;return z(`${[S,...s].map(e=>
|
|
165
|
-
`)}function
|
|
164
|
+
`,1)}s.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=S,e.state.env.set(`PWD`,S),e.state.env.set(`OLDPWD`,e.state.previousDir);let w=e.state.env.get(`HOME`)||``;return z(`${[S,...s].map(e=>_t(e,w)).join(` `)}
|
|
165
|
+
`)}function pr(e,t){let s=dr(e);for(let e of t)if(e!==`--`)return e.startsWith(`-`)&&e!==`-`?A(`bash: popd: ${e}: invalid option
|
|
166
166
|
`,2):A(`bash: popd: too many arguments
|
|
167
167
|
`,2);if(s.length===0)return A(`bash: popd: directory stack empty
|
|
168
168
|
`,1);let g=s.shift();if(!g)return A(`bash: popd: directory stack empty
|
|
169
|
-
`,1);e.state.previousDir=e.state.cwd,e.state.cwd=g,e.state.env.set(`PWD`,g),e.state.env.set(`OLDPWD`,e.state.previousDir);let S=e.state.env.get(`HOME`)||``;return z(`${[g,...s].map(e=>
|
|
170
|
-
`)}function
|
|
169
|
+
`,1);e.state.previousDir=e.state.cwd,e.state.cwd=g,e.state.env.set(`PWD`,g),e.state.env.set(`OLDPWD`,e.state.previousDir);let S=e.state.env.get(`HOME`)||``;return z(`${[g,...s].map(e=>_t(e,S)).join(` `)}
|
|
170
|
+
`)}function mr(e,t){let s=dr(e),g=!1,S=!1,w=!1,E=!1;for(let e of t)if(e!==`--`)if(e.startsWith(`-`))for(let t of e.slice(1))if(t===`c`)g=!0;else if(t===`l`)S=!0;else if(t===`p`)w=!0;else if(t===`v`)w=!0,E=!0;else return A(`bash: dirs: -${t}: invalid option
|
|
171
171
|
`,2);else return A(`bash: dirs: too many arguments
|
|
172
|
-
`,1);if(g)return e.state.directoryStack=[],W;let D=[e.state.cwd,...s],O=e.state.env.get(`HOME`)||``,k;return E?(k=D.map((e,t)=>` ${t} ${S?e:
|
|
172
|
+
`,1);if(g)return e.state.directoryStack=[],W;let D=[e.state.cwd,...s],O=e.state.env.get(`HOME`)||``,k;return E?(k=D.map((e,t)=>` ${t} ${S?e:_t(e,O)}`).join(`
|
|
173
173
|
`),k+=`
|
|
174
|
-
`):k=w?D.map(e=>S?e:
|
|
174
|
+
`):k=w?D.map(e=>S?e:_t(e,O)).join(`
|
|
175
175
|
`)+`
|
|
176
|
-
`:D.map(e=>S?e:
|
|
177
|
-
`,z(k)}async function
|
|
176
|
+
`:D.map(e=>S?e:_t(e,O)).join(` `)+`
|
|
177
|
+
`,z(k)}async function ps(e,t,s){let g=t;if(g.length>0){let e=g[0];if(e===`--`)g=g.slice(1);else if(e.startsWith(`-`)&&e!==`-`&&e.length>1)return A(`bash: eval: ${e}: invalid option
|
|
178
178
|
eval: usage: eval [arg ...]
|
|
179
179
|
`,2)}if(g.length===0)return W;let S=g.join(` `);if(S.trim()===``)return W;let w=e.state.groupStdin,E=s??e.state.groupStdin;E!==void 0&&(e.state.groupStdin=E);try{let t=di$1(S);return await e.executeScript(t)}catch(e){if(e instanceof c||e instanceof a||e instanceof i||e instanceof d)throw e;if(e.name===`ParseException`)return A(`bash: eval: ${e.message}
|
|
180
|
-
`);throw e}finally{e.state.groupStdin=w}}function
|
|
181
|
-
`,s=2):s=(S%256+256)%256}throw new d(s,``,g)}function
|
|
180
|
+
`);throw e}finally{e.state.groupStdin=w}}function yr(e,t){let s,g=``;if(t.length===0)s=e.state.lastExitCode;else{let e=t[0],S=Number.parseInt(e,10);e===``||Number.isNaN(S)||!/^-?\d+$/.test(e)?(g=`bash: exit: ${e}: numeric argument required
|
|
181
|
+
`,s=2):s=(S%256+256)%256}throw new d(s,``,g)}function gr(e,t){let s=!1,g=[];for(let e of t)e===`-n`?s=!0:e===`-p`||e===`--`||g.push(e);if(g.length===0&&!s){let t=``,s=e.state.exportedVars??new Set,g=Array.from(s).sort();for(let s of g){let g=e.state.env.get(s);if(g!==void 0){let e=g.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);t+=`declare -x ${s}="${e}"
|
|
182
182
|
`}}return z(t)}if(s){for(let t of g){let s,g;if(t.includes(`=`)){let S=t.indexOf(`=`);s=t.slice(0,S),g=X(e,t.slice(S+1)),e.state.env.set(s,g)}else s=t;ga$1(e,s)}return W}let S=``,w=0;for(let t of g){let s,g,E=!1,D=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(D)s=D[1],g=X(e,D[2]),E=!0;else if(t.includes(`=`)){let S=t.indexOf(`=`);s=t.slice(0,S),g=X(e,t.slice(S+1))}else s=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)){S+=`bash: export: \`${t}': not a valid identifier
|
|
183
|
-
`,w=1;continue}if(g!==void 0)if(E){let t=e.state.env.get(s)??``;e.state.env.set(s,t+g)}else e.state.env.set(s,g);else e.state.env.has(s)||e.state.env.set(s,``);ma$1(e,s)}return _(``,S,w)}function
|
|
184
|
-
`);let s=t[0],g=t[1],S=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(g),w=s.startsWith(`:`),E=w?s.slice(1):s,D;if(t.length>2)D=t.slice(2);else{let t=Number.parseInt(e.state.env.get(`#`)||`0`,10);D=[];for(let s=1;s<=t;s++)D.push(e.state.env.get(String(s))||``)}let O=Number.parseInt(e.state.env.get(`OPTIND`)||`1`,10);O<1&&(O=1);let k=Number.parseInt(e.state.env.get(`__GETOPTS_CHARINDEX`)||`0`,10);if(e.state.env.set(`OPTARG`,``),O>D.length)return S||e.state.env.set(g,`?`),e.state.env.set(`OPTIND`,String(D.length+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),{exitCode:S?2:1,stdout:``,stderr:``};let j=D[O-1];if(!j||j===`-`||!j.startsWith(`-`))return S||e.state.env.set(g,`?`),{exitCode:S?2:1,stdout:``,stderr:``};if(j===`--`)return e.state.env.set(`OPTIND`,String(O+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),S||e.state.env.set(g,`?`),{exitCode:S?2:1,stdout:``,stderr:``};let F=k===0?1:k,L=j[F];if(!L)return e.state.env.set(`OPTIND`,String(O+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),
|
|
183
|
+
`,w=1;continue}if(g!==void 0)if(E){let t=e.state.env.get(s)??``;e.state.env.set(s,t+g)}else e.state.env.set(s,g);else e.state.env.has(s)||e.state.env.set(s,``);ma$1(e,s)}return _(``,S,w)}function ms(e,t){if(t.length<2)return A(`bash: getopts: usage: getopts optstring name [arg ...]
|
|
184
|
+
`);let s=t[0],g=t[1],S=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(g),w=s.startsWith(`:`),E=w?s.slice(1):s,D;if(t.length>2)D=t.slice(2);else{let t=Number.parseInt(e.state.env.get(`#`)||`0`,10);D=[];for(let s=1;s<=t;s++)D.push(e.state.env.get(String(s))||``)}let O=Number.parseInt(e.state.env.get(`OPTIND`)||`1`,10);O<1&&(O=1);let k=Number.parseInt(e.state.env.get(`__GETOPTS_CHARINDEX`)||`0`,10);if(e.state.env.set(`OPTARG`,``),O>D.length)return S||e.state.env.set(g,`?`),e.state.env.set(`OPTIND`,String(D.length+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),{exitCode:S?2:1,stdout:``,stderr:``};let j=D[O-1];if(!j||j===`-`||!j.startsWith(`-`))return S||e.state.env.set(g,`?`),{exitCode:S?2:1,stdout:``,stderr:``};if(j===`--`)return e.state.env.set(`OPTIND`,String(O+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),S||e.state.env.set(g,`?`),{exitCode:S?2:1,stdout:``,stderr:``};let F=k===0?1:k,L=j[F];if(!L)return e.state.env.set(`OPTIND`,String(O+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),ms(e,t);let B=E.indexOf(L);if(B===-1){let t=``;return w?e.state.env.set(`OPTARG`,L):t=`bash: illegal option -- ${L}
|
|
185
185
|
`,S||e.state.env.set(g,`?`),F+1<j.length?(e.state.env.set(`__GETOPTS_CHARINDEX`,String(F+1)),e.state.env.set(`OPTIND`,String(O))):(e.state.env.set(`OPTIND`,String(O+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`)),{exitCode:S?2:0,stdout:``,stderr:t}}if(B+1<E.length&&E[B+1]===`:`)if(F+1<j.length)e.state.env.set(`OPTARG`,j.slice(F+1)),e.state.env.set(`OPTIND`,String(O+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`);else{if(O>=D.length){let t=``;return w?(e.state.env.set(`OPTARG`,L),S||e.state.env.set(g,`:`)):(t=`bash: option requires an argument -- ${L}
|
|
186
|
-
`,S||e.state.env.set(g,`?`)),e.state.env.set(`OPTIND`,String(O+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),{exitCode:S?2:0,stdout:``,stderr:t}}e.state.env.set(`OPTARG`,D[O]),e.state.env.set(`OPTIND`,String(O+2)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`)}else F+1<j.length?(e.state.env.set(`__GETOPTS_CHARINDEX`,String(F+1)),e.state.env.set(`OPTIND`,String(O))):(e.state.env.set(`OPTIND`,String(O+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`));return S||e.state.env.set(g,L),{exitCode:S?2:0,stdout:``,stderr:``}}async function
|
|
186
|
+
`,S||e.state.env.set(g,`?`)),e.state.env.set(`OPTIND`,String(O+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`),{exitCode:S?2:0,stdout:``,stderr:t}}e.state.env.set(`OPTARG`,D[O]),e.state.env.set(`OPTIND`,String(O+2)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`)}else F+1<j.length?(e.state.env.set(`__GETOPTS_CHARINDEX`,String(F+1)),e.state.env.set(`OPTIND`,String(O))):(e.state.env.set(`OPTIND`,String(O+1)),e.state.env.set(`__GETOPTS_CHARINDEX`,`0`));return S||e.state.env.set(g,L),{exitCode:S?2:0,stdout:``,stderr:``}}async function wr(e,t){e.state.hashTable||(e.state.hashTable=new Map);let s=!1,g=!1,S=!1,w=!1,E=!1,D=``,O=[],k=0;for(;k<t.length;){let e=t[k];if(e===`--`){k++,O.push(...t.slice(k));break}if(e===`-r`)s=!0,k++;else if(e===`-d`)g=!0,k++;else if(e===`-l`)S=!0,k++;else if(e===`-t`)E=!0,k++;else if(e===`-p`){if(w=!0,k++,k>=t.length)return A(`bash: hash: -p: option requires an argument
|
|
187
187
|
`,1);D=t[k],k++}else if(e.startsWith(`-`)&&e.length>1){for(let t of e.slice(1))if(t===`r`)s=!0;else if(t===`d`)g=!0;else if(t===`l`)S=!0;else if(t===`t`)E=!0;else return A(t===`p`?`bash: hash: -p: option requires an argument
|
|
188
188
|
`:`bash: hash: -${t}: invalid option
|
|
189
189
|
`,1);k++}else O.push(e),k++}if(s)return e.state.hashTable.clear(),W;if(g){if(O.length===0)return A(`bash: hash: -d: option requires an argument
|
|
@@ -199,7 +199,7 @@ eval: usage: eval [arg ...]
|
|
|
199
199
|
`;for(let[,s]of e.state.hashTable)t+=` 1 ${s}
|
|
200
200
|
`}return z(t)}let j=!1,F=``,L=(e.state.env.get(`PATH`)||`/usr/bin:/bin`).split(`:`);for(let t of O){if(t.includes(`/`)){F+=`bash: hash: ${t}: cannot use / in name
|
|
201
201
|
`,j=!0;continue}let s=!1;for(let g of L){if(!g)continue;let S=`${g}/${t}`;if(await e.fs.exists(S)){e.state.hashTable.set(t,S),s=!0;break}}s||(F+=`bash: hash: ${t}: not found
|
|
202
|
-
`,j=!0)}return j?A(F,1):W}var
|
|
202
|
+
`,j=!0)}return j?A(F,1):W}var qn=new Map([[`:`,[`: [arguments]`,`Null command.
|
|
203
203
|
No effect; the command does nothing.
|
|
204
204
|
Exit Status:
|
|
205
205
|
Always succeeds.`]],[`.`,[`. filename [arguments]`,`Execute commands from a file in the current shell.
|
|
@@ -546,33 +546,33 @@ eval: usage: eval [arg ...]
|
|
|
546
546
|
job specification, and reports its termination status.
|
|
547
547
|
Exit Status:
|
|
548
548
|
Returns the status of the last ID; fails if ID is invalid or an invalid
|
|
549
|
-
option is given.`]]]),
|
|
550
|
-
`,2)}S++}else g.push(e),S++}if(g.length===0)return
|
|
551
|
-
`,E=!0;continue}for(let e of t){let t=
|
|
549
|
+
option is given.`]]]),Gn=[...qn.keys()].sort();function vr(e,t){let s=!1,g=[],S=0;for(;S<t.length;){let e=t[S];if(e===`--`){for(S++;S<t.length;)g.push(t[S]),S++;break}if(e.startsWith(`-`)&&e.length>1){for(let t=1;t<e.length;t++){let g=e[t];if(g===`s`)s=!0;else return A(`bash: help: -${g}: invalid option
|
|
550
|
+
`,2)}S++}else g.push(e),S++}if(g.length===0)return Ko();let w=``,E=!1,D=``;for(let e of g){let t=Go(e);if(t.length===0){D+=`bash: help: no help topics match \`${e}'. Try \`help help' or \`man -k ${e}' or \`info ${e}'.
|
|
551
|
+
`,E=!0;continue}for(let e of t){let t=qn.get(e);if(!t)continue;let[g,S]=t;s?w+=`${e}: ${g}
|
|
552
552
|
`:w+=`${e}: ${g}
|
|
553
553
|
${S}
|
|
554
|
-
`}}return{exitCode:E?1:0,stdout:w,stderr:D}}function
|
|
554
|
+
`}}return{exitCode:E?1:0,stdout:w,stderr:D}}function Go(e){let t=I1(`^${e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`).replace(/\?/g,`.`)}$`);return Gn.filter(e=>t.test(e))}function Ko(){let e=[];e.push(`just-bash shell builtins`),e.push("These shell commands are defined internally. Type `help' to see this list."),e.push("Type `help name' to find out more about the function `name'."),e.push(``);let t=36,s=Gn.slice(),g=Math.ceil(s.length/2);for(let t=0;t<g;t++){let S=s[t]||``,w=s[t+g]||``,E=S.padEnd(36);e.push(w?`${E}${w}`:S)}return z(`${e.join(`
|
|
555
555
|
`)}
|
|
556
|
-
`)}function
|
|
557
|
-
`);let s=
|
|
558
|
-
`)}return _(``,``,g===0?1:0)}async function
|
|
556
|
+
`)}function Xo(e){let t=[],s=``,g=0;for(let S of e){for(let e of S)e===`(`?g++:e===`)`&&g--;s?s+=` ${S}`:s=S,g===0&&(t.push(s),s=``)}return s&&t.push(s),t}async function br(e,t){if(t.length===0)return A(`bash: let: expression expected
|
|
557
|
+
`);let s=Xo(t),g=0;for(let t of s)try{let s=di$1(`(( ${t} ))`).statements[0];if(s&&s.pipelines.length>0&&s.pipelines[0].commands.length>0){let t=s.pipelines[0].commands[0];t.type===`ArithmeticCommand`&&(g=await R(e,t.expression.expression))}}catch(e){return A(`bash: let: ${t}: ${e.message}
|
|
558
|
+
`)}return _(``,``,g===0?1:0)}async function Er(e,t){if(e.state.localScopes.length===0)return A(`bash: local: can only be used in a function
|
|
559
559
|
`);let s=e.state.localScopes[e.state.localScopes.length-1],g=``,S=0,w=!1,E=!1,D=[];for(let e of t)if(e===`-n`)w=!0;else if(e===`-a`)E=!0;else if(e!==`-p`)if(e.startsWith(`-`)&&!e.includes(`=`))for(let t of e.slice(1))t===`n`?w=!0:t===`a`&&(E=!0);else D.push(e);if(D.length===0){let t=``,g=Array.from(s.keys()).filter(e=>!e.includes(`_`)||!e.match(/_\d+$/)).filter(e=>!e.includes(`__length`)).sort();for(let s of g){let g=e.state.env.get(s);g!==void 0&&(t+=`${s}=${g}
|
|
560
560
|
`)}return _(t,``,0)}for(let t of D){let D,O,k=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(k){D=k[1];let E=k[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(D)){g+=`bash: local: \`${t}': not a valid identifier
|
|
561
561
|
`,S=1;continue}if(da$1(e,D,`bash`),!s.has(D)){s.set(D,e.state.env.get(D));let t=`${D}_`;for(let g of e.state.env.keys())g.startsWith(t)&&!g.includes(`__`)&&(s.has(g)||s.set(g,e.state.env.get(g)))}let O=`${D}_`;for(let t of e.state.env.keys())t.startsWith(O)&&!t.includes(`__`)&&e.state.env.delete(t);let j=Oe(E);for(let t=0;t<j.length;t++)e.state.env.set(`${D}_${t}`,j[t]);e.state.env.set(`${D}__length`,String(j.length)),Ze(e,D),w&&Vi$1(e,D);continue}let j=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(j){D=j[1];let t=j[2];if(da$1(e,D,`bash`),!s.has(D)){s.set(D,e.state.env.get(D));let t=`${D}_`;for(let g of e.state.env.keys())g.startsWith(t)&&!g.includes(`__`)&&(s.has(g)||s.set(g,e.state.env.get(g)));let g=`${D}__length`;e.state.env.has(g)&&!s.has(g)&&s.set(g,e.state.env.get(g))}let g=Oe(t),S=mt$1(e,D),E=0,O=e.state.env.get(D);S.length===0&&O!==void 0?(e.state.env.set(`${D}_0`,O),e.state.env.delete(D),E=1):S.length>0&&(E=Math.max(...S)+1);for(let t=0;t<g.length;t++)e.state.env.set(`${D}_${E+t}`,X(e,g[t]));let k=E+g.length;e.state.env.set(`${D}__length`,String(k)),Ze(e,D),w&&Vi$1(e,D);continue}let F=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(F){D=F[1];let t=X(e,F[2]);da$1(e,D,`bash`),s.has(D)||s.set(D,e.state.env.get(D));let g=e.state.env.get(D)??``;e.state.env.set(D,g+t),Ze(e,D),w&&Vi$1(e,D);continue}let L=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(L){D=L[1];let t=L[2],g=X(e,L[3]);if(da$1(e,D,`bash`),!s.has(D)){s.set(D,e.state.env.get(D));let t=`${D}_`;for(let g of e.state.env.keys())g.startsWith(t)&&!g.includes(`__`)&&(s.has(g)||s.set(g,e.state.env.get(g)));let g=`${D}__length`;e.state.env.has(g)&&!s.has(g)&&s.set(g,e.state.env.get(g))}let S;try{S=await R(e,M(new V,t).expression)}catch{let e=parseInt(t,10);S=Number.isNaN(e)?0:e}e.state.env.set(`${D}_${S}`,g);let E=parseInt(e.state.env.get(`${D}__length`)??`0`,10);S>=E&&e.state.env.set(`${D}__length`,String(S+1)),Ze(e,D),w&&Vi$1(e,D);continue}if(t.includes(`=`)){let s=t.indexOf(`=`);D=t.slice(0,s),O=X(e,t.slice(s+1))}else D=t;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(D)){g+=`bash: local: \`${t}': not a valid identifier
|
|
562
|
-
`,S=1;continue}let B=s.has(D);if(O!==void 0){let t=e.state.env.get(D);if(e.state.tempEnvBindings){let s=e.state.accessedTempEnvVars?.has(D),g=e.state.mutatedTempEnvVars?.has(D);if(!s&&!g)for(let s=e.state.tempEnvBindings.length-1;s>=0;s--){let g=e.state.tempEnvBindings[s];if(g.has(D)){t=g.get(D);break}}}
|
|
563
|
-
`,S=1;continue}e.state.env.set(D,O),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(D))}else{let t=e.state.tempEnvBindings?.some(e=>e.has(D));!B&&!t&&e.state.env.delete(D)}Ze(e,D),w&&Vi$1(e,D)}return _(``,g,S)}function
|
|
562
|
+
`,S=1;continue}let B=s.has(D);if(O!==void 0){let t=e.state.env.get(D);if(e.state.tempEnvBindings){let s=e.state.accessedTempEnvVars?.has(D),g=e.state.mutatedTempEnvVars?.has(D);if(!s&&!g)for(let s=e.state.tempEnvBindings.length-1;s>=0;s--){let g=e.state.tempEnvBindings[s];if(g.has(D)){t=g.get(D);break}}}Dn(e,D,t)}if(!B){let t=e.state.env.get(D);if(e.state.tempEnvBindings)for(let s=e.state.tempEnvBindings.length-1;s>=0;s--){let g=e.state.tempEnvBindings[s];if(g.has(D)){t=g.get(D);break}}if(s.set(D,t),E){let t=`${D}_`;for(let g of e.state.env.keys())g.startsWith(t)&&!g.includes(`__`)&&(s.has(g)||s.set(g,e.state.env.get(g)));let g=`${D}__length`;e.state.env.has(g)&&!s.has(g)&&s.set(g,e.state.env.get(g))}}if(E&&O===void 0){let t=`${D}_`;for(let s of e.state.env.keys())s.startsWith(t)&&!s.includes(`__`)&&e.state.env.delete(s);e.state.env.set(`${D}__length`,`0`)}else if(O!==void 0){if(da$1(e,D,`bash`),w&&O!==``&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(O)){g+=`bash: local: \`${O}': invalid variable name for name reference
|
|
563
|
+
`,S=1;continue}e.state.env.set(D,O),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(D))}else{let t=e.state.tempEnvBindings?.some(e=>e.has(D));!B&&!t&&e.state.env.delete(D)}Ze(e,D),w&&Vi$1(e,D)}return _(``,g,S)}function $r(e,t,s){let g=`
|
|
564
564
|
`,S=0,w=0,E=0,D=!1,O=`MAPFILE`,k=0;for(;k<t.length;){let e=t[k];e===`-d`&&k+1<t.length?(g=t[k+1]===``?`\0`:t[k+1]||`
|
|
565
565
|
`,k+=2):e===`-n`&&k+1<t.length?(S=Number.parseInt(t[k+1],10)||0,k+=2):e===`-O`&&k+1<t.length?(w=Number.parseInt(t[k+1],10)||0,k+=2):e===`-s`&&k+1<t.length?(E=Number.parseInt(t[k+1],10)||0,k+=2):e===`-t`?(D=!0,k++):e===`-u`||e===`-C`||e===`-c`?k+=2:(e.startsWith(`-`)||(O=e),k++)}let j=s;!j&&e.state.groupStdin!==void 0&&(j=e.state.groupStdin);let F=[],L=j,B=0,H=0,q=e.limits?.maxArrayElements??1e5;for(;L.length>0;){let e=L.indexOf(g);if(e===-1){if(L.length>0){if(H<E)H++;else if(S===0||B<S){if(w+B>=q)return _(``,`mapfile: array element limit exceeded (${q})
|
|
566
566
|
`,1);let e=L,t=e.indexOf(`\0`);t!==-1&&(e=e.substring(0,t)),F.push(e),B++}}break}let t=L.substring(0,e),s=t.indexOf(`\0`);if(s!==-1&&(t=t.substring(0,s)),!D&&g!==`\0`&&(t+=g),L=L.substring(e+g.length),H<E){H++;continue}if(S>0&&B>=S)break;if(w+B>=q)return _(``,`mapfile: array element limit exceeded (${q})
|
|
567
|
-
`,1);F.push(t),B++}w===0&&Ci$1(e,O);for(let t=0;t<F.length;t++)e.state.env.set(`${O}_${w+t}`,F[t]);let ee=parseInt(e.state.env.get(`${O}__length`)||`0`,10),J=w+F.length;return e.state.env.set(`${O}__length`,String(Math.max(ee,J))),e.state.groupStdin!==void 0&&!s&&(e.state.groupStdin=``),_(``,``,0)}function
|
|
568
|
-
`,E=-1,D=-1,O=null,k=-1,j=-1,F=[],L=0,B=!1,H=(e,s)=>{let g=1;for(;g<e.length;){let F=e[g];if(F===`r`)S=!0,g++;else if(F===`s`)g++;else{if(F===`d`)return g+1<e.length?(w=e.substring(g+1),{nextArgIndex:s+1}):s+1<t.length?(w=t[s+1],{nextArgIndex:s+2}):{nextArgIndex:s+1};if(F===`n`){if(g+1<e.length){let t=e.substring(g+1);return E=Number.parseInt(t,10),(Number.isNaN(E)||E<0)&&(B=!0,E=0),{nextArgIndex:s+1}}else if(s+1<t.length)return E=Number.parseInt(t[s+1],10),(Number.isNaN(E)||E<0)&&(B=!0,E=0),{nextArgIndex:s+2};return{nextArgIndex:s+1}}else if(F===`N`){if(g+1<e.length){let t=e.substring(g+1);return D=Number.parseInt(t,10),(Number.isNaN(D)||D<0)&&(B=!0,D=0),{nextArgIndex:s+1}}else if(s+1<t.length)return D=Number.parseInt(t[s+1],10),(Number.isNaN(D)||D<0)&&(B=!0,D=0),{nextArgIndex:s+2};return{nextArgIndex:s+1}}else{if(F===`a`)return g+1<e.length?(O=e.substring(g+1),{nextArgIndex:s+1}):s+1<t.length?(O=t[s+1],{nextArgIndex:s+2}):{nextArgIndex:s+1};if(F===`p`)return g+1<e.length?(e.substring(g+1),{nextArgIndex:s+1}):s+1<t.length?(t[s+1],{nextArgIndex:s+2}):{nextArgIndex:s+1};if(F===`u`){if(g+1<e.length){let t=e.substring(g+1);return k=Number.parseInt(t,10),Number.isNaN(k)||k<0?{nextArgIndex:-2}:{nextArgIndex:s+1}}else if(s+1<t.length)return k=Number.parseInt(t[s+1],10),Number.isNaN(k)||k<0?{nextArgIndex:-2}:{nextArgIndex:s+2};return{nextArgIndex:s+1}}else if(F===`t`){if(g+1<e.length){let t=e.substring(g+1);return j=Number.parseFloat(t),Number.isNaN(j)&&(j=0),{nextArgIndex:s+1}}else if(s+1<t.length)return j=Number.parseFloat(t[s+1]),Number.isNaN(j)&&(j=0),{nextArgIndex:s+2};return{nextArgIndex:s+1}}else if(F===`e`||F===`i`||F===`P`){if(F===`i`&&s+1<t.length)return{nextArgIndex:s+2};g++}else g++}}}return{nextArgIndex:s+1}};for(;L<t.length;){let e=t[L];if(e.startsWith(`-`)&&e.length>1&&e!==`--`){let t=H(e,L);if(t.nextArgIndex===-1)return{stdout:``,stderr:``,exitCode:2};if(t.nextArgIndex===-2)return{stdout:``,stderr:``,exitCode:1};L=t.nextArgIndex}else if(e===`--`)for(L++;L<t.length;)F.push(t[L]),L++;else F.push(e),L++}if(B)return _(``,``,1);if(F.length===0&&O===null&&F.push(`REPLY`),j===0){if(O)Ci$1(e,O);else{for(let t of F)e.state.env.set(t,``);F.length===0&&e.state.env.set(`REPLY`,``)}return _(``,``,0)}if(j<0&&j!==-1)return _(``,``,1);let q=s;k>=0?q=e.state.fileDescriptors&&e.state.fileDescriptors.get(k)||``:!q&&e.state.groupStdin!==void 0&&(q=e.state.groupStdin);let ee=w===``?`\0`:w,J=``,Y=0,te=!0,ne=t=>{if(k>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(k,q.substring(t));else if(g>=0&&e.state.fileDescriptors){let s=e.state.fileDescriptors.get(g);if(s?.startsWith(`__rw__:`)){let S=
|
|
567
|
+
`,1);F.push(t),B++}w===0&&Ci$1(e,O);for(let t=0;t<F.length;t++)e.state.env.set(`${O}_${w+t}`,F[t]);let ee=parseInt(e.state.env.get(`${O}__length`)||`0`,10),J=w+F.length;return e.state.env.set(`${O}__length`,String(Math.max(ee,J))),e.state.groupStdin!==void 0&&!s&&(e.state.groupStdin=``),_(``,``,0)}function Yo(e){if(!e.startsWith(`__rw__:`))return null;let t=e.slice(7),s=t.indexOf(`:`);if(s===-1)return null;let g=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(g)||g<0)return null;let S=s+1,w=t.slice(S,S+g),E=S+g+1,D=t.slice(E),O=D.indexOf(`:`);if(O===-1)return null;let k=Number.parseInt(D.slice(0,O),10);return Number.isNaN(k)||k<0?null:{path:w,position:k,content:D.slice(O+1)}}function Qo(e,t,s){return`__rw__:${e.length}:${e}:${t}:${s}`}function Sr(e,t,s,g=-1){let S=!1,w=`
|
|
568
|
+
`,E=-1,D=-1,O=null,k=-1,j=-1,F=[],L=0,B=!1,H=(e,s)=>{let g=1;for(;g<e.length;){let F=e[g];if(F===`r`)S=!0,g++;else if(F===`s`)g++;else{if(F===`d`)return g+1<e.length?(w=e.substring(g+1),{nextArgIndex:s+1}):s+1<t.length?(w=t[s+1],{nextArgIndex:s+2}):{nextArgIndex:s+1};if(F===`n`){if(g+1<e.length){let t=e.substring(g+1);return E=Number.parseInt(t,10),(Number.isNaN(E)||E<0)&&(B=!0,E=0),{nextArgIndex:s+1}}else if(s+1<t.length)return E=Number.parseInt(t[s+1],10),(Number.isNaN(E)||E<0)&&(B=!0,E=0),{nextArgIndex:s+2};return{nextArgIndex:s+1}}else if(F===`N`){if(g+1<e.length){let t=e.substring(g+1);return D=Number.parseInt(t,10),(Number.isNaN(D)||D<0)&&(B=!0,D=0),{nextArgIndex:s+1}}else if(s+1<t.length)return D=Number.parseInt(t[s+1],10),(Number.isNaN(D)||D<0)&&(B=!0,D=0),{nextArgIndex:s+2};return{nextArgIndex:s+1}}else{if(F===`a`)return g+1<e.length?(O=e.substring(g+1),{nextArgIndex:s+1}):s+1<t.length?(O=t[s+1],{nextArgIndex:s+2}):{nextArgIndex:s+1};if(F===`p`)return g+1<e.length?(e.substring(g+1),{nextArgIndex:s+1}):s+1<t.length?(t[s+1],{nextArgIndex:s+2}):{nextArgIndex:s+1};if(F===`u`){if(g+1<e.length){let t=e.substring(g+1);return k=Number.parseInt(t,10),Number.isNaN(k)||k<0?{nextArgIndex:-2}:{nextArgIndex:s+1}}else if(s+1<t.length)return k=Number.parseInt(t[s+1],10),Number.isNaN(k)||k<0?{nextArgIndex:-2}:{nextArgIndex:s+2};return{nextArgIndex:s+1}}else if(F===`t`){if(g+1<e.length){let t=e.substring(g+1);return j=Number.parseFloat(t),Number.isNaN(j)&&(j=0),{nextArgIndex:s+1}}else if(s+1<t.length)return j=Number.parseFloat(t[s+1]),Number.isNaN(j)&&(j=0),{nextArgIndex:s+2};return{nextArgIndex:s+1}}else if(F===`e`||F===`i`||F===`P`){if(F===`i`&&s+1<t.length)return{nextArgIndex:s+2};g++}else g++}}}return{nextArgIndex:s+1}};for(;L<t.length;){let e=t[L];if(e.startsWith(`-`)&&e.length>1&&e!==`--`){let t=H(e,L);if(t.nextArgIndex===-1)return{stdout:``,stderr:``,exitCode:2};if(t.nextArgIndex===-2)return{stdout:``,stderr:``,exitCode:1};L=t.nextArgIndex}else if(e===`--`)for(L++;L<t.length;)F.push(t[L]),L++;else F.push(e),L++}if(B)return _(``,``,1);if(F.length===0&&O===null&&F.push(`REPLY`),j===0){if(O)Ci$1(e,O);else{for(let t of F)e.state.env.set(t,``);F.length===0&&e.state.env.set(`REPLY`,``)}return _(``,``,0)}if(j<0&&j!==-1)return _(``,``,1);let q=s;k>=0?q=e.state.fileDescriptors&&e.state.fileDescriptors.get(k)||``:!q&&e.state.groupStdin!==void 0&&(q=e.state.groupStdin);let ee=w===``?`\0`:w,J=``,Y=0,te=!0,ne=t=>{if(k>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(k,q.substring(t));else if(g>=0&&e.state.fileDescriptors){let s=e.state.fileDescriptors.get(g);if(s?.startsWith(`__rw__:`)){let S=Yo(s);if(S){let s=S.position+t;e.state.fileDescriptors.set(g,Qo(S.path,s,S.content))}}}else e.state.groupStdin!==void 0&&!s&&(e.state.groupStdin=q.substring(t))};if(D>=0){let t=Math.min(D,q.length);J=q.substring(0,t),Y=t,te=t>=D,ne(Y);let s=F[0]||`REPLY`;e.state.env.set(s,J);for(let t=1;t<F.length;t++)e.state.env.set(F[t],``);return _(``,``,te?0:1)}else if(E>=0){let e=0,t=0,s=!1;for(;t<q.length&&e<E;){let g=q[t];if(g===ee){Y=t+1,s=!0;break}if(!S&&g===`\\`&&t+1<q.length){let s=q[t+1];if(s===ee&&ee===`
|
|
569
569
|
`){t+=2,Y=t;continue}if(s===ee){t+=2,e++,J+=s,Y=t;continue}J+=s,t+=2,e++,Y=t}else J+=g,t++,e++,Y=t}te=e>=E||s,ne(Y)}else{Y=0;let t=0;for(;t<q.length;){let e=q[t];if(e===ee){Y=t+ee.length,te=!0;break}if(!S&&e===`\\`&&t+1<q.length){let s=q[t+1];if(s===`
|
|
570
570
|
`){t+=2;continue}if(s===ee){J+=s,t+=2;continue}J+=e,J+=s,t+=2;continue}J+=e,t++}if(t>=q.length&&(te=!1,Y=t,J.length===0&&q.length===0)){for(let t of F)e.state.env.set(t,``);return O&&Ci$1(e,O),_(``,``,1)}ne(Y)}ee===`
|
|
571
571
|
`&&J.endsWith(`
|
|
572
572
|
`)&&(J=J.slice(0,-1));let ae=e=>S?e:e.replace(/\\(.)/g,`$1`);if(F.length===1&&F[0]===`REPLY`)return e.state.env.set(`REPLY`,ae(J)),_(``,``,te?0:1);let oe=T(e.state.env);if(O){let{words:t}=Wi$1(J,oe,void 0,S),s=e.limits?.maxArrayElements??1e5;if(t.length>s)return _(``,`read: array element limit exceeded (${s})
|
|
573
|
-
`,1);Ci$1(e,O);for(let s=0;s<t.length;s++)e.state.env.set(`${O}_${s}`,ae(t[s]));return _(``,``,te?0:1)}let se=F.length,{words:ce,wordStarts:ue}=Wi$1(J,oe,se,S);for(let t=0;t<F.length;t++){let s=F[t];if(t<F.length-1)e.state.env.set(s,ae(ce[t]??``));else if(t<ue.length){let g=J.substring(ue[t]);g=Ti$1(g,oe,S),g=ae(g),e.state.env.set(s,g)}else e.state.env.set(s,``)}return _(``,``,te?0:1)}function
|
|
573
|
+
`,1);Ci$1(e,O);for(let s=0;s<t.length;s++)e.state.env.set(`${O}_${s}`,ae(t[s]));return _(``,``,te?0:1)}let se=F.length,{words:ce,wordStarts:ue}=Wi$1(J,oe,se,S);for(let t=0;t<F.length;t++){let s=F[t];if(t<F.length-1)e.state.env.set(s,ae(ce[t]??``));else if(t<ue.length){let g=J.substring(ue[t]);g=Ti$1(g,oe,S),g=ae(g),e.state.env.set(s,g)}else e.state.env.set(s,``)}return _(``,``,te?0:1)}function Pr(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return A(`bash: return: can only \`return' from a function or sourced script
|
|
574
574
|
`);let s=e.state.lastExitCode;if(t.length>0){let e=t[0],g=Number.parseInt(e,10);if(e===``||Number.isNaN(g)||!/^-?\d+$/.test(e))return A(`bash: return: ${e}: numeric argument required
|
|
575
|
-
`,2);s=(g%256+256)%256}throw new i(s)}var
|
|
575
|
+
`,2);s=(g%256+256)%256}throw new i(s)}var ys=`set: usage: set [-eux] [+eux] [-o option] [+o option]
|
|
576
576
|
Options:
|
|
577
577
|
-e Exit immediately if a command exits with non-zero status
|
|
578
578
|
+e Disable -e
|
|
@@ -588,56 +588,56 @@ Options:
|
|
|
588
588
|
+o pipefail Disable pipefail
|
|
589
589
|
-o xtrace Same as -x
|
|
590
590
|
+o xtrace Disable xtrace
|
|
591
|
-
`,
|
|
591
|
+
`,Kn=new Map([[`e`,`errexit`],[`u`,`nounset`],[`x`,`xtrace`],[`v`,`verbose`],[`f`,`noglob`],[`C`,`noclobber`],[`a`,`allexport`],[`n`,`noexec`],[`h`,null],[`b`,null],[`m`,null],[`B`,null],[`H`,null],[`P`,null],[`T`,null],[`E`,null],[`p`,null]]),Xn=new Map([[`errexit`,`errexit`],[`pipefail`,`pipefail`],[`nounset`,`nounset`],[`xtrace`,`xtrace`],[`verbose`,`verbose`],[`noclobber`,`noclobber`],[`noglob`,`noglob`],[`allexport`,`allexport`],[`noexec`,`noexec`],[`posix`,`posix`],[`vi`,`vi`],[`emacs`,`emacs`],[`notify`,null],[`monitor`,null],[`braceexpand`,null],[`histexpand`,null],[`physical`,null],[`functrace`,null],[`errtrace`,null],[`privileged`,null],[`hashall`,null],[`ignoreeof`,null],[`interactive-comments`,null],[`keyword`,null],[`onecmd`,null]]),Yn=[`errexit`,`nounset`,`pipefail`,`verbose`,`xtrace`,`posix`,`allexport`,`noclobber`,`noglob`,`noexec`,`vi`,`emacs`],Qn=[`braceexpand`,`errtrace`,`functrace`,`hashall`,`histexpand`,`history`,`ignoreeof`,`interactive-comments`,`keyword`,`monitor`,`nolog`,`notify`,`onecmd`,`physical`,`privileged`];function Jn(e,t,s){t!==null&&(s&&(t===`vi`?e.state.options.emacs=!1:t===`emacs`&&(e.state.options.vi=!1)),e.state.options[t]=s,lt(e))}function Jo(e,t){return t+1<e.length&&!e[t+1].startsWith(`-`)&&!e[t+1].startsWith(`+`)}function ea(e,t){let s=mt$1(e,t);return s.length===0?`${t}=()`:`${t}=(${s.map(s=>`[${s}]=${Je(e.state.env.get(`${t}_${s}`)??``)}`).join(` `)})`}function ta(e){return/^[a-zA-Z0-9_]+$/.test(e)?e:`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function sa(e,t){let s=gt$1(e,t);return s.length===0?`${t}=()`:`${t}=(${s.map(s=>{let g=e.state.env.get(`${t}_${s}`)??``;return`[${ta(s)}]=${Je(g)}`}).join(` `)} )`}function ra(e){let t=new Set,s=e.state.associativeArrays??new Set;for(let g of e.state.env.keys()){let e=g.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(e){let g=e[1];s.has(g)||t.add(g)}}return t}function na(e){return e.state.associativeArrays??new Set}function kr(e,t){if(t.includes(`--help`))return z(ys);if(t.length===0){let t=ra(e),s=na(e),g=e=>{for(let t of s){let s=`${t}_`;if(e!==`${t}__length`&&e.startsWith(s)){if(e.slice(s.length).startsWith(`_length`))continue;return!0}}return!1},S=[];for(let[w,E]of e.state.env){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(w)||t.has(w)||s.has(w))continue;let e=w.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(e&&t.has(e[1]))continue;let D=w.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);D&&t.has(D[1])||g(w)||D&&s.has(D[1])||S.push([w,E])}let w=[];for(let[e,t]of S.sort(([e],[t])=>e<t?-1:e>t?1:0))w.push(`${e}=${hs(t)}`);for(let s of[...t].sort((e,t)=>e<t?-1:e>t?1:0))w.push(ea(e,s));for(let t of[...s].sort((e,t)=>e<t?-1:e>t?1:0))w.push(sa(e,t));return w.sort((e,t)=>{let s=e.split(`=`)[0],g=t.split(`=`)[0];return s<g?-1:s>g?1:0}),z(w.length>0?`${w.join(`
|
|
592
592
|
`)}
|
|
593
|
-
`:``)}let s=0;for(;s<t.length;){let g=t[s];if((g===`-o`||g===`+o`)&&
|
|
594
|
-
${
|
|
593
|
+
`:``)}let s=0;for(;s<t.length;){let g=t[s];if((g===`-o`||g===`+o`)&&Jo(t,s)){let S=t[s+1];if(!Xn.has(S)){let t=`bash: set: ${S}: invalid option name
|
|
594
|
+
${ys}`;if(e.state.options.posix)throw new C(1,``,t);return A(t)}Jn(e,Xn.get(S)??null,g===`-o`),s+=2;continue}if(g===`-o`){let t=Yn.map(t=>`${t.padEnd(16)}${e.state.options[t]?`on`:`off`}`),s=Qn.map(e=>`${e.padEnd(16)}off`);return z(`${[...t,...s].sort().join(`
|
|
595
595
|
`)}
|
|
596
|
-
`)}if(g===`+o`){let t=
|
|
596
|
+
`)}if(g===`+o`){let t=Yn.map(t=>`set ${e.state.options[t]?`-o`:`+o`} ${t}`),s=Qn.map(e=>`set +o ${e}`);return z(`${[...t,...s].sort().join(`
|
|
597
597
|
`)}
|
|
598
|
-
`)}if(g.length>1&&(g[0]===`-`||g[0]===`+`)&&g[1]!==`-`){let t=g[0]===`-`;for(let s=1;s<g.length;s++){let S=g[s];if(!
|
|
599
|
-
${
|
|
600
|
-
${
|
|
598
|
+
`)}if(g.length>1&&(g[0]===`-`||g[0]===`+`)&&g[1]!==`-`){let t=g[0]===`-`;for(let s=1;s<g.length;s++){let S=g[s];if(!Kn.has(S)){let t=`bash: set: ${g[0]}${S}: invalid option
|
|
599
|
+
${ys}`;if(e.state.options.posix)throw new C(1,``,t);return A(t)}Jn(e,Kn.get(S)??null,t)}s++;continue}if(g===`--`)return Ar(e,t.slice(s+1)),W;if(g===`-`){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,lt(e),s+1<t.length)return Ar(e,t.slice(s+1)),W;s++;continue}if(g===`+`){s++;continue}if(g.startsWith(`-`)||g.startsWith(`+`)){let t=`bash: set: ${g}: invalid option
|
|
600
|
+
${ys}`;if(e.state.options.posix)throw new C(1,``,t);return A(t)}return Ar(e,t.slice(s)),W}return W}function Ar(e,t){let s=1;for(;e.state.env.has(String(s));)e.state.env.delete(String(s)),s++;for(let s=0;s<t.length;s++)e.state.env.set(String(s+1),t[s]);e.state.env.set(`#`,String(t.length)),e.state.env.set(`@`,t.join(` `)),e.state.env.set(`*`,t.join(` `))}function _r(e,t){let s=1;if(t.length>0){let g=Number.parseInt(t[0],10);if(Number.isNaN(g)||g<0){let s=`bash: shift: ${t[0]}: numeric argument required
|
|
601
601
|
`;if(e.state.options.posix)throw new C(1,``,s);return A(s)}s=g}let g=Number.parseInt(e.state.env.get(`#`)||`0`,10);if(s>g){let t=`bash: shift: shift count out of range
|
|
602
|
-
`;if(e.state.options.posix)throw new C(1,``,t);return A(t)}if(s===0)return W;let S=[];for(let t=1;t<=g;t++)S.push(e.state.env.get(String(t))||``);let w=S.slice(s);for(let t=1;t<=g;t++)e.state.env.delete(String(t));for(let t=0;t<w.length;t++)e.state.env.set(String(t+1),w[t]);return e.state.env.set(`#`,String(w.length)),e.state.env.set(`@`,w.join(` `)),W}async function
|
|
602
|
+
`;if(e.state.options.posix)throw new C(1,``,t);return A(t)}if(s===0)return W;let S=[];for(let t=1;t<=g;t++)S.push(e.state.env.get(String(t))||``);let w=S.slice(s);for(let t=1;t<=g;t++)e.state.env.delete(String(t));for(let t=0;t<w.length;t++)e.state.env.set(String(t+1),w[t]);return e.state.env.set(`#`,String(w.length)),e.state.env.set(`@`,w.join(` `)),W}async function Cr(e,t){let s=t;if(s.length>0&&s[0]===`--`&&(s=s.slice(1)),s.length===0)return _(``,`bash: source: filename argument required
|
|
603
603
|
`,2);let g=s[0],S=null;if(g.includes(`/`)){let t=e.fs.resolvePath(e.state.cwd,g);try{S=await e.fs.readFile(t)}catch{}}else{let t=(e.state.env.get(`PATH`)||``).split(`:`).filter(e=>e);for(let s of t){let t=e.fs.resolvePath(e.state.cwd,`${s}/${g}`);try{if((await e.fs.stat(t)).isDirectory)continue;S=await e.fs.readFile(t);break}catch{}}if(S===null){let t=e.fs.resolvePath(e.state.cwd,g);try{S=await e.fs.readFile(t)}catch{}}}if(S===null)return A(`bash: ${g}: No such file or directory
|
|
604
604
|
`);let w=new Map;if(s.length>1){for(let t=1;t<=9;t++)w.set(String(t),e.state.env.get(String(t)));w.set(`#`,e.state.env.get(`#`)),w.set(`@`,e.state.env.get(`@`));let t=s.slice(1);e.state.env.set(`#`,String(t.length)),e.state.env.set(`@`,t.join(` `));for(let s=0;s<t.length&&s<9;s++)e.state.env.set(String(s+1),t[s]);for(let s=t.length+1;s<=9;s++)e.state.env.delete(String(s))}let E=e.state.currentSource,D=()=>{if(e.state.sourceDepth--,e.state.currentSource=E,s.length>1)for(let[t,s]of w)s===void 0?e.state.env.delete(t):e.state.env.set(t,s)};if(e.state.sourceDepth++,e.state.sourceDepth>e.limits.maxSourceDepth)throw e.state.sourceDepth--,new b(`source: maximum nesting depth (${e.limits.maxSourceDepth}) exceeded, increase executionLimits.maxSourceDepth`,`recursion`);e.state.currentSource=g;try{let t=di$1(S),s=await e.executeScript(t);return D(),s}catch(e){if(D(),e instanceof d)throw e;if(e instanceof i)return _(e.stdout,e.stderr,e.exitCode);if(e.name===`ParseException`)return A(`bash: ${g}: ${e.message}
|
|
605
|
-
`);throw e}}function
|
|
606
|
-
`,S=1;continue}let k=await
|
|
605
|
+
`);throw e}}function ei(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function ia(e){return e.startsWith(`'`)&&e.endsWith(`'`)||e.startsWith(`"`)&&e.endsWith(`"`)}async function ti(e,t){if(ia(t))return null;try{return await R(e,M(new V,t).expression)}catch{let e=parseInt(t,10);return Number.isNaN(e)?0:e}}function si(e,t){if(e.state.localVarStack?.has(t)){let s=us(e,t);if(s){s.value===void 0?e.state.env.delete(t):e.state.env.set(t,s.value);let g=e.state.localVarStack?.get(t);if(!g||g.length===0)cs(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,s.scopeIndex),Nr(e,t);else{let s=g[g.length-1];e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,s.scopeIndex+1)}return!0}return e.state.env.delete(t),cs(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let s=e.state.localScopes.length-1;s>=0;s--){let g=e.state.localScopes[s];if(g.has(t)){let S=g.get(t);S===void 0?e.state.env.delete(t):e.state.env.set(t,S),g.delete(t);let w=!1;for(let g=s-1;g>=0;g--)if(e.state.localScopes[g].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,g+1),w=!0;break}return w||cs(e,t),!0}}return!1}function Nr(e,t){if(!e.state.tempEnvBindings||e.state.tempEnvBindings.length===0)return!1;for(let s=e.state.tempEnvBindings.length-1;s>=0;s--){let g=e.state.tempEnvBindings[s];if(g.has(t)){let s=g.get(t);return s===void 0?e.state.env.delete(t):e.state.env.set(t,s),g.delete(t),!0}}return!1}async function ri(e,t){if(t.startsWith(`'`)&&t.endsWith(`'`))return t.slice(1,-1);if(t.startsWith(`"`)&&t.endsWith(`"`)){let s=t.slice(1,-1);return Pt$1(e,new V().parseWordFromString(s,!0,!1))}return t.includes(`$`)?Pt$1(e,new V().parseWordFromString(t,!1,!1)):t}async function Or(e,t){let s=`both`,g=``,S=0;for(let w of t){if(w===`-v`){s=`variable`;continue}if(w===`-f`){s=`function`;continue}if(s===`function`){e.state.functions.delete(w);continue}if(s===`variable`){let t=w.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(t){let s=t[1],w=t[2];if(w===`@`||w===`*`){let t=P(e,s);for(let[g]of t)e.state.env.delete(`${s}_${g}`);e.state.env.delete(s);continue}let E=e.state.associativeArrays?.has(s);if(E){let t=await ri(e,w);e.state.env.delete(`${s}_${t}`);continue}let D=be(e,s),O=e.state.declaredVars?.has(s);if((e.state.env.has(s)||O)&&!D&&!E){g+=`bash: unset: ${s}: not an array variable
|
|
606
|
+
`,S=1;continue}let k=await ti(e,w);if(k===null&&D){g+=`bash: unset: ${w}: not a valid identifier
|
|
607
607
|
`,S=1;continue}if(k===null)continue;if(k<0){let t=P(e,s),w=t.length,E=e.state.currentLine;if(w===0){g+=`bash: line ${E}: unset: [${k}]: bad array subscript
|
|
608
608
|
`,S=1;continue}let D=w+k;if(D<0){g+=`bash: line ${E}: unset: [${k}]: bad array subscript
|
|
609
|
-
`,S=1;continue}let O=t[D][0];e.state.env.delete(`${s}_${O}`);continue}e.state.env.delete(`${s}_${k}`);continue}if(!
|
|
609
|
+
`,S=1;continue}let O=t[D][0];e.state.env.delete(`${s}_${O}`);continue}e.state.env.delete(`${s}_${k}`);continue}if(!ei(w)){g+=`bash: unset: \`${w}': not a valid identifier
|
|
610
610
|
`,S=1;continue}let s=w;if(W$1(e,w)){let t=he(e,w);t&&t!==w&&(s=t)}if(wt(e,s)){g+=`bash: unset: ${s}: cannot unset: readonly variable
|
|
611
|
-
`,S=1;continue}let E=ut(e,s);if(E!==void 0&&E!==e.state.callDepth)
|
|
612
|
-
`,S=1;continue}let O=await
|
|
611
|
+
`,S=1;continue}let E=ut(e,s);if(E!==void 0&&E!==e.state.callDepth)si(e,s);else if(e.state.fullyUnsetLocals?.has(s))e.state.env.delete(s);else if(E!==void 0){let t=e.state.accessedTempEnvVars?.has(s),g=e.state.mutatedTempEnvVars?.has(s);if((t||g)&&e.state.localVarStack?.has(s)){let t=us(e,s);t?t.value===void 0?e.state.env.delete(s):e.state.env.set(s,t.value):e.state.env.delete(s)}else e.state.env.delete(s)}else Nr(e,s)||e.state.env.delete(s);e.state.exportedVars?.delete(s);continue}let t=w.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(t){let s=t[1],w=t[2];if(w===`@`||w===`*`){let t=P(e,s);for(let[g]of t)e.state.env.delete(`${s}_${g}`);e.state.env.delete(s);continue}let E=e.state.associativeArrays?.has(s);if(E){let t=await ri(e,w);e.state.env.delete(`${s}_${t}`);continue}let D=be(e,s);if(e.state.env.has(s)&&!D&&!E){g+=`bash: unset: ${s}: not an array variable
|
|
612
|
+
`,S=1;continue}let O=await ti(e,w);if(O===null&&D){g+=`bash: unset: ${w}: not a valid identifier
|
|
613
613
|
`,S=1;continue}if(O===null)continue;if(O<0){let t=P(e,s),w=t.length,E=e.state.currentLine;if(w===0){g+=`bash: line ${E}: unset: [${O}]: bad array subscript
|
|
614
614
|
`,S=1;continue}let D=w+O;if(D<0){g+=`bash: line ${E}: unset: [${O}]: bad array subscript
|
|
615
|
-
`,S=1;continue}let k=t[D][0];e.state.env.delete(`${s}_${k}`);continue}e.state.env.delete(`${s}_${O}`);continue}if(!
|
|
615
|
+
`,S=1;continue}let k=t[D][0];e.state.env.delete(`${s}_${k}`);continue}e.state.env.delete(`${s}_${O}`);continue}if(!ei(w)){g+=`bash: unset: \`${w}': not a valid identifier
|
|
616
616
|
`,S=1;continue}let E=w;if(W$1(e,w)){let t=he(e,w);t&&t!==w&&(E=t)}if(wt(e,E)){g+=`bash: unset: ${E}: cannot unset: readonly variable
|
|
617
|
-
`,S=1;continue}let D=ut(e,E);if(D!==void 0&&D!==e.state.callDepth)
|
|
618
|
-
`}}}O++}else break}for(;O<t.length;)D.push(t[O]),O++;if(E)return
|
|
619
|
-
`};if(D.length===0){if(s||g){let t=[];for(let w of
|
|
617
|
+
`,S=1;continue}let D=ut(e,E);if(D!==void 0&&D!==e.state.callDepth)si(e,E);else if(e.state.fullyUnsetLocals?.has(E))e.state.env.delete(E);else if(D!==void 0){let t=e.state.accessedTempEnvVars?.has(E),s=e.state.mutatedTempEnvVars?.has(E);if((t||s)&&e.state.localVarStack?.has(E)){let t=us(e,E);t?t.value===void 0?e.state.env.delete(E):e.state.env.set(E,t.value):e.state.env.delete(E)}else e.state.env.delete(E)}else Nr(e,E)||e.state.env.delete(E);e.state.exportedVars?.delete(E),e.state.functions.delete(w)}return _(``,g,S)}var xr=[`extglob`,`dotglob`,`nullglob`,`failglob`,`globstar`,`globskipdots`,`nocaseglob`,`nocasematch`,`expand_aliases`,`lastpipe`,`xpg_echo`],oa=`autocd.cdable_vars.cdspell.checkhash.checkjobs.checkwinsize.cmdhist.compat31.compat32.compat40.compat41.compat42.compat43.compat44.complete_fullquote.direxpand.dirspell.execfail.extdebug.extquote.force_fignore.globasciiranges.gnu_errfmt.histappend.histreedit.histverify.hostcomplete.huponexit.inherit_errexit.interactive_comments.lithist.localvar_inherit.localvar_unset.login_shell.mailwarn.no_empty_cmd_completion.progcomp.progcomp_alias.promptvars.restricted_shell.shift_verbose.sourcepath`.split(`.`);function gs(e){return xr.includes(e)}function aa(e){return oa.includes(e)}function ni(e,t){let s=!1,g=!1,S=!1,w=!1,E=!1,D=[],O=0;for(;O<t.length;){let e=t[O];if(e===`--`){O++;break}if(e.startsWith(`-`)&&e.length>1){for(let t=1;t<e.length;t++){let D=e[t];switch(D){case`s`:s=!0;break;case`u`:g=!0;break;case`p`:S=!0;break;case`q`:w=!0;break;case`o`:E=!0;break;default:return{exitCode:2,stdout:``,stderr:`shopt: -${D}: invalid option
|
|
618
|
+
`}}}O++}else break}for(;O<t.length;)D.push(t[O]),O++;if(E)return la(e,D,s,g,S,w);if(s&&g)return{exitCode:1,stdout:``,stderr:`shopt: cannot set and unset shell options simultaneously
|
|
619
|
+
`};if(D.length===0){if(s||g){let t=[];for(let w of xr){let E=e.state.shoptOptions[w];s&&E?t.push(S?`shopt -s ${w}`:`${w} on`):g&&!E&&t.push(S?`shopt -u ${w}`:`${w} off`)}return{exitCode:0,stdout:t.length>0?`${t.join(`
|
|
620
620
|
`)}
|
|
621
|
-
`:``,stderr:``}}let t=[];for(let s of
|
|
621
|
+
`:``,stderr:``}}let t=[];for(let s of xr){let g=e.state.shoptOptions[s];t.push(S?`shopt ${g?`-s`:`-u`} ${s}`:`${s} ${g?`on`:`off`}`)}return{exitCode:0,stdout:`${t.join(`
|
|
622
622
|
`)}
|
|
623
|
-
`,stderr:``}}let k=!1,j=``,F=[];for(let t of D){if(!
|
|
624
|
-
`,k=!0;continue}if(s)
|
|
623
|
+
`,stderr:``}}let k=!1,j=``,F=[];for(let t of D){if(!gs(t)&&!aa(t)){j+=`shopt: ${t}: invalid shell option name
|
|
624
|
+
`,k=!0;continue}if(s)gs(t)&&(e.state.shoptOptions[t]=!0,Vs(e));else if(g)gs(t)&&(e.state.shoptOptions[t]=!1,Vs(e));else if(gs(t)){let s=e.state.shoptOptions[t];w?s||(k=!0):S?(F.push(`shopt ${s?`-s`:`-u`} ${t}`),s||(k=!0)):(F.push(`${t} ${s?`on`:`off`}`),s||(k=!0))}else w?k=!0:S?(F.push(`shopt -u ${t}`),k=!0):(F.push(`${t} off`),k=!0)}return{exitCode:k?1:0,stdout:F.length>0?`${F.join(`
|
|
625
625
|
`)}
|
|
626
|
-
`:``,stderr:j}}function
|
|
626
|
+
`:``,stderr:j}}function la(e,t,s,g,S,w){let E=new Map([[`errexit`,`errexit`],[`pipefail`,`pipefail`],[`nounset`,`nounset`],[`xtrace`,`xtrace`],[`verbose`,`verbose`],[`posix`,`posix`],[`allexport`,`allexport`],[`noclobber`,`noclobber`],[`noglob`,`noglob`],[`noexec`,`noexec`],[`vi`,`vi`],[`emacs`,`emacs`]]),D=[`braceexpand`,`errtrace`,`functrace`,`hashall`,`histexpand`,`history`,`ignoreeof`,`interactive-comments`,`keyword`,`monitor`,`nolog`,`notify`,`onecmd`,`physical`,`privileged`],O=[...E.keys(),...D].sort();if(t.length===0){let t=[];for(let w of O){let O=D.includes(w),k=E.get(w),j=O||!k?!1:e.state.options[k];s&&!j||g&&j||t.push(S?`set ${j?`-o`:`+o`} ${w}`:`${w} ${j?`on`:`off`}`)}return{exitCode:0,stdout:t.length>0?`${t.join(`
|
|
627
627
|
`)}
|
|
628
628
|
`:``,stderr:``}}let k=!1,j=``,F=[];for(let O of t){let t=E.has(O),L=D.includes(O);if(!t&&!L){j+=`shopt: ${O}: invalid option name
|
|
629
629
|
`,k=!0;continue}if(L){s||g||(w?k=!0:S?(F.push(`set +o ${O}`),k=!0):(F.push(`${O} off`),k=!0));continue}let B=E.get(O);if(B)if(s)B===`vi`?e.state.options.emacs=!1:B===`emacs`&&(e.state.options.vi=!1),e.state.options[B]=!0,lt(e);else if(g)e.state.options[B]=!1,lt(e);else{let t=e.state.options[B];w?t||(k=!0):S?(F.push(`set ${t?`-o`:`+o`} ${O}`),t||(k=!0)):(F.push(`${O} ${t?`on`:`off`}`),t||(k=!0))}}return{exitCode:k?1:0,stdout:F.length>0?`${F.join(`
|
|
630
630
|
`)}
|
|
631
|
-
`:``,stderr:j}}async function
|
|
631
|
+
`:``,stderr:j}}async function ii(e,t,s){if(t.includes(`/`)){let s=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(s))return{error:`not_found`,path:s};let g=s.split(`/`).pop()||t,S=e.commands.get(g);try{let t=await e.fs.stat(s);return t.isDirectory?{error:`permission_denied`,path:s}:S?{cmd:S,path:s}:t.mode&73?{script:!0,path:s}:{error:`permission_denied`,path:s}}catch{return{error:`not_found`,path:s}}}if(!s&&e.state.hashTable){let s=e.state.hashTable.get(t);if(s)if(await e.fs.exists(s)){let g=e.commands.get(t);if(g)return{cmd:g,path:s};try{let t=await e.fs.stat(s);if(!t.isDirectory&&t.mode&73)return{script:!0,path:s}}catch{}}else e.state.hashTable.delete(t)}let g=(s??e.state.env.get(`PATH`)??`/usr/bin:/bin`).split(`:`);for(let s of g){if(!s)continue;let g=`${s.startsWith(`/`)?s:e.fs.resolvePath(e.state.cwd,s)}/${t}`;if(await e.fs.exists(g))try{let S=await e.fs.stat(g);if(S.isDirectory)continue;let w=(S.mode&73)!=0,E=e.commands.get(t),D=s===`/bin`||s===`/usr/bin`;if(E&&D)return{cmd:E,path:g};if(w&&(E&&!D||!E))return{script:!0,path:g}}catch{}}if(!await e.fs.exists(`/usr/bin`)){let s=e.commands.get(t);if(s)return{cmd:s,path:`/usr/bin/${t}`}}return null}async function ws(e,t){let s=[];if(t.includes(`/`)){let g=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(g))try{let S=await e.fs.stat(g);S.isDirectory||S.mode&73&&s.push(t)}catch{}return s}let g=(e.state.env.get(`PATH`)||`/usr/bin:/bin`).split(`:`);for(let S of g){if(!S)continue;let g=`${S.startsWith(`/`)?S:e.fs.resolvePath(e.state.cwd,S)}/${t}`;if(await e.fs.exists(g)){try{if((await e.fs.stat(g)).isDirectory)continue}catch{continue}s.push(S.startsWith(`/`)?g:`${S}/${t}`)}}return s}function ca(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function K(e,t,s,g){return((...S)=>{a$1(t,s,`${g} call`);let w=e(...S);return ca(w)?w.then(e=>(a$1(t,s,`${g} post-await`),e),e=>{throw a$1(t,s,`${g} post-await`),e}):(a$1(t,s,`${g} return`),w)})}function ua(e,t,s){let g={readFile:K(e.readFile.bind(e),t,s,`fs.readFile`),readFileBuffer:K(e.readFileBuffer.bind(e),t,s,`fs.readFileBuffer`),writeFile:K(e.writeFile.bind(e),t,s,`fs.writeFile`),appendFile:K(e.appendFile.bind(e),t,s,`fs.appendFile`),exists:K(e.exists.bind(e),t,s,`fs.exists`),stat:K(e.stat.bind(e),t,s,`fs.stat`),mkdir:K(e.mkdir.bind(e),t,s,`fs.mkdir`),readdir:K(e.readdir.bind(e),t,s,`fs.readdir`),rm:K(e.rm.bind(e),t,s,`fs.rm`),cp:K(e.cp.bind(e),t,s,`fs.cp`),mv:K(e.mv.bind(e),t,s,`fs.mv`),resolvePath:K(e.resolvePath.bind(e),t,s,`fs.resolvePath`),getAllPaths:K(e.getAllPaths.bind(e),t,s,`fs.getAllPaths`),chmod:K(e.chmod.bind(e),t,s,`fs.chmod`),symlink:K(e.symlink.bind(e),t,s,`fs.symlink`),link:K(e.link.bind(e),t,s,`fs.link`),readlink:K(e.readlink.bind(e),t,s,`fs.readlink`),lstat:K(e.lstat.bind(e),t,s,`fs.lstat`),realpath:K(e.realpath.bind(e),t,s,`fs.realpath`),utimes:K(e.utimes.bind(e),t,s,`fs.utimes`)};return e.readdirWithFileTypes&&(g.readdirWithFileTypes=K(e.readdirWithFileTypes.bind(e),t,s,`fs.readdirWithFileTypes`)),g}function oi(e,t){if(!e.requireDefenseContext)return e;let s=`command:${t}`,g={...e,fs:ua(e.fs,e.requireDefenseContext,s)};return e.exec&&(g.exec=K(e.exec,e.requireDefenseContext,s,`exec`)),e.fetch&&(g.fetch=K(e.fetch,e.requireDefenseContext,s,`fetch`)),e.sleep&&(g.sleep=K(e.sleep,e.requireDefenseContext,s,`sleep`)),e.getRegisteredCommands&&(g.getRegisteredCommands=K(e.getRegisteredCommands,e.requireDefenseContext,s,`getRegisteredCommands`)),g}async function ui(e,t,s,g){let S=!1,w=!1,E=!1,D=!1,O=!1,k=[];for(let e of t)if(e.startsWith(`-`)&&e.length>1)for(let t of e.slice(1))t===`t`?S=!0:t===`p`?w=!0:t===`P`?E=!0:t===`a`?D=!0:t===`f`&&(O=!0);else k.push(e);let j=``,F=``,L=0,B=!1,H=!1;for(let t of k){let k=!1;if(E){if(D){let e=await g(t);if(e.length>0){for(let t of e)j+=`${t}
|
|
632
632
|
`;B=!0,k=!0}}else{let e=await s(t);e&&(j+=`${e}
|
|
633
633
|
`,B=!0,k=!0)}k||(H=!0);continue}let L=!O&&e.state.functions.has(t);if(D&&L){if(!w)if(S)j+=`function
|
|
634
|
-
`;else{let s=e.state.functions.get(t),g=s?
|
|
634
|
+
`;else{let s=e.state.functions.get(t),g=s?ai(t,s):`${t} is a function
|
|
635
635
|
`;j+=g}k=!0}let q=e.state.env.get(`BASH_ALIAS_${t}`);if(!(q!==void 0&&(D||!k)&&(w||(S?j+=`alias
|
|
636
636
|
`:j+=`${t} is aliased to \`${q}'
|
|
637
|
-
`),k=!0,!D)||
|
|
637
|
+
`),k=!0,!D)||Ks.has(t)&&(D||!k)&&(w||(S?j+=`keyword
|
|
638
638
|
`:j+=`${t} is a shell keyword
|
|
639
639
|
`),k=!0,!D))){if(!D&&L&&!k){if(!w)if(S)j+=`function
|
|
640
|
-
`;else{let s=e.state.functions.get(t),g=s?
|
|
640
|
+
`;else{let s=e.state.functions.get(t),g=s?ai(t,s):`${t} is a function
|
|
641
641
|
`;j+=g}k=!0;continue}if(!(ft.has(t)&&(D||!k)&&(w||(S?j+=`builtin
|
|
642
642
|
`:j+=`${t} is a shell builtin
|
|
643
643
|
`),k=!0,!D))){if(D){let e=await g(t);for(let s of e)w?j+=`${s}
|
|
@@ -647,14 +647,14 @@ ${ms}`;if(e.state.options.posix)throw new C(1,``,t);return A(t)}return $r(e,t.sl
|
|
|
647
647
|
`:S?j+=`file
|
|
648
648
|
`:j+=`${t} is ${e}
|
|
649
649
|
`,B=!0,k=!0)}if(!k&&(H=!0,!S&&!w)){let s=!0;if(t.includes(`/`)){let g=e.fs.resolvePath(e.state.cwd,t);await e.fs.exists(g)&&(s=!1)}s&&(F+=`bash: type: ${t}: not found
|
|
650
|
-
`)}}}}return L=w?H&&!B?1:0:H?1:0,_(j,F,L)}function
|
|
650
|
+
`)}}}}return L=w?H&&!B?1:0:H?1:0,_(j,F,L)}function ai(e,t){let s;return s=t.body.type===`Group`?t.body.body.map(e=>Ct(e)).join(`; `):Ct(t.body),`${e} is a function
|
|
651
651
|
${e} ()
|
|
652
652
|
{
|
|
653
653
|
${s}
|
|
654
654
|
}
|
|
655
|
-
`}function
|
|
655
|
+
`}function Ct(e){if(Array.isArray(e))return e.map(e=>Ct(e)).join(`; `);if(e.type===`Statement`){let t=[];for(let s=0;s<e.pipelines.length;s++){let g=e.pipelines[s];t.push(fa(g)),e.operators[s]&&t.push(e.operators[s])}return t.join(` `)}if(e.type===`SimpleCommand`){let t=e,s=[];t.name&&s.push(li(t.name));for(let e of t.args)s.push(li(e));return s.join(` `)}return e.type===`Group`?`{ ${e.body.map(e=>Ct(e)).join(`; `)}; }`:`...`}function fa(e){let t=e.commands.map(e=>Ct(e));return(e.negated?`! `:``)+t.join(` | `)}function li(e){let t=``;for(let s of e.parts)s.type===`Literal`?t+=s.value:s.type===`DoubleQuoted`?t+=`"${s.parts.map(e=>ci(e)).join(``)}"`:s.type===`SingleQuoted`?t+=`'${s.value}'`:t+=ci(s);return t}function ci(e){let t=e;return t.type===`Literal`?t.value??``:t.type===`Variable`?`$${t.name}`:``}async function fi(e,t,s,g){let S=``,w=``,E=0;for(let s of t){if(!s){E=1;continue}let t=e.state.env.get(`BASH_ALIAS_${s}`);if(t!==void 0)g?S+=`${s} is an alias for "${t}"
|
|
656
656
|
`:S+=`alias ${s}='${t}'
|
|
657
|
-
`;else if(
|
|
657
|
+
`;else if(Ks.has(s))g?S+=`${s} is a shell keyword
|
|
658
658
|
`:S+=`${s}
|
|
659
659
|
`;else if(ft.has(s))g?S+=`${s} is a shell builtin
|
|
660
660
|
`:S+=`${s}
|
|
@@ -666,104 +666,104 @@ ${e} ()
|
|
|
666
666
|
`),E=1)}else if(e.commands.has(s)){let t=(e.state.env.get(`PATH`)??`/usr/bin:/bin`).split(`:`),w=null;for(let g of t){if(!g)continue;let t=`${g}/${s}`;try{let s=await e.fs.stat(t);if(!s.isDirectory&&s.mode&73){w=t;break}}catch{}}w||=`/usr/bin/${s}`,g?S+=`${s} is ${w}
|
|
667
667
|
`:S+=`${w}
|
|
668
668
|
`}else g&&(w+=`${s}: not found
|
|
669
|
-
`),E=1}return _(S,w,E)}async function
|
|
670
|
-
`,2);e=s.slice(0,-1)}return
|
|
671
|
-
`);let[,...E]=S;return g(w,E,[],s,!0,!1,-1)}async function
|
|
669
|
+
`),E=1}return _(S,w,E)}async function di(e,t){if(t.includes(`/`)){let s=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(s)){try{let t=await e.fs.stat(s);if(t.isDirectory||!(t.mode&73))return null}catch{return null}return t}return null}let s=(e.state.env.get(`PATH`)??`/usr/bin:/bin`).split(`:`);for(let g of s){if(!g)continue;let s=`${g.startsWith(`/`)?g:e.fs.resolvePath(e.state.cwd,g)}/${t}`;if(await e.fs.exists(s)){try{if((await e.fs.stat(s)).isDirectory)continue}catch{continue}return`${g}/${t}`}}if(e.commands.has(t)){for(let e of s)if(e===`/usr/bin`||e===`/bin`)return`${e}/${t}`;return`/usr/bin/${t}`}return null}async function hi(e,t,s,g,S,w,E,D){let{ctx:O,runCommand:k}=e;if(O.coverage&&ft.has(t)&&O.coverage.hit(`bash:builtin:${t}`),t===`export`)return gr(O,s);if(t===`unset`)return Or(O,s);if(t===`exit`)return yr(O,s);if(t===`local`)return Er(O,s);if(t===`set`)return kr(O,s);if(t===`break`)return js(O,s);if(t===`continue`)return sr(O,s);if(t===`return`)return Pr(O,s);if(t===`eval`&&O.state.options.posix)return ps(O,s,S);if(t===`shift`)return _r(O,s);if(t===`getopts`)return ms(O,s);if(t===`compgen`)return Qs(O,s);if(t===`complete`)return er(O,s);if(t===`compopt`)return tr(O,s);if(t===`pushd`)return await hr(O,s);if(t===`popd`)return pr(O,s);if(t===`dirs`)return mr(O,s);if(t===`source`||t===`.`)return Cr(O,s);if(t===`read`)return Sr(O,s,S,D);if(t===`mapfile`||t===`readarray`)return $r(O,s,S);if(t===`declare`||t===`typeset`)return ur(O,s);if(t===`readonly`)return fr(O,s);if(!w){let e=O.state.functions.get(t);if(e)return ds(O,e,s,S)}if(t===`eval`)return ps(O,s,S);if(t===`cd`)return await Us(O,s);if(t===`:`||t===`true`)return W;if(t===`false`)return Q(!1);if(t===`let`)return br(O,s);if(t===`command`)return da(e,s,S);if(t===`builtin`)return ha(e,s,S);if(t===`shopt`)return ni(O,s);if(t===`exec`){if(s.length===0)return W;let[e,...t]=s;return k(e,t,[],S,!1,!1,-1)}if(t===`wait`)return W;if(t===`type`)return await ui(O,s,e=>di(O,e),e=>ws(O,e));if(t===`hash`)return wr(O,s);if(t===`help`)return vr(O,s);if(t===`[`||t===`test`){let e=s;if(t===`[`){if(s[s.length-1]!==`]`)return A(`[: missing \`]'
|
|
670
|
+
`,2);e=s.slice(0,-1)}return At(O,e)}return null}async function da(e,t,s){let{ctx:g,runCommand:S}=e;if(t.length===0)return W;let w=!1,E=!1,D=!1,O=t;for(;O.length>0&&O[0].startsWith(`-`);){let e=O[0];if(e===`--`){O=O.slice(1);break}for(let t of e.slice(1))t===`p`?w=!0:t===`V`?E=!0:t===`v`&&(D=!0);O=O.slice(1)}if(O.length===0)return W;if(D||E)return await fi(g,O,D,E);let[k,...j]=O;return S(k,j,[],s,!0,w,-1)}async function ha(e,t,s){let{runCommand:g}=e;if(t.length===0)return W;let S=t;if(S[0]===`--`&&(S=S.slice(1),S.length===0))return W;let w=S[0];if(!ft.has(w))return A(`bash: builtin: ${w}: not a shell builtin
|
|
671
|
+
`);let[,...E]=S;return g(w,E,[],s,!0,!1,-1)}async function pi(e,t,s,g,S){let{ctx:w,buildExportedEnv:E,executeUserScript:D}=e,O=await ii(w,t,S?`/usr/bin:/bin`:void 0);if(!O)return En(t)?A(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
|
|
672
672
|
`,127):A(`bash: ${t}: command not found
|
|
673
673
|
`,127);if(`error`in O)return O.error===`permission_denied`?A(`bash: ${t}: Permission denied
|
|
674
674
|
`,126):A(`bash: ${t}: No such file or directory
|
|
675
|
-
`,127);if(`script`in O)return t.includes(`/`)||(w.state.hashTable||(w.state.hashTable=new Map),w.state.hashTable.set(t,O.path)),await D(O.path,s,g);let{cmd:k,path:j}=O;t.includes(`/`)||(w.state.hashTable||(w.state.hashTable=new Map),w.state.hashTable.set(t,j));let F=g||w.state.groupStdin||``,L=E(),B=
|
|
676
|
-
`)}}async function
|
|
677
|
-
`,exitCode:1}}async function
|
|
678
|
-
`,exitCode:1}}return{stdout:S,stderr:w,exitCode:E}}async function
|
|
679
|
-
`);let D=[];if(t.words===null)D=(e.state.env.get(`@`)||``).split(` `).filter(Boolean);else if(t.words.length===0)D=[];else try{for(let s of t.words){let t=await wl(e,s);D.push(...t.values)}}catch(e){if(e instanceof h)return{stdout:``,stderr:e.stderr,exitCode:1};throw e}e.state.loopDepth++;try{for(let s of D){E++,E>e.limits.maxLoopIterations&&Ne(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,g,S),e.state.env.set(t.variable,s);try{for(let s of t.body){let t=await e.executeStatement(s);g+=t.stdout,S+=t.stderr,w=t.exitCode}}catch(s){let w=
|
|
675
|
+
`,127);if(`script`in O)return t.includes(`/`)||(w.state.hashTable||(w.state.hashTable=new Map),w.state.hashTable.set(t,O.path)),await D(O.path,s,g);let{cmd:k,path:j}=O;t.includes(`/`)||(w.state.hashTable||(w.state.hashTable=new Map),w.state.hashTable.set(t,j));let F=g||w.state.groupStdin||``,L=E(),B=oi({fs:w.fs,cwd:w.state.cwd,env:w.state.env,exportedEnv:L,stdin:F,limits:w.limits,exec:w.execFn,fetch:w.fetch,getRegisteredCommands:()=>Array.from(w.commands.keys()),sleep:w.sleep,trace:w.trace,fileDescriptors:w.state.fileDescriptors,xpgEcho:w.state.shoptOptions.xpg_echo,coverage:w.coverage,signal:w.state.signal,requireDefenseContext:w.requireDefenseContext,jsBootstrapCode:w.jsBootstrapCode},t);try{let e=()=>x$1(w.requireDefenseContext,`command`,`${t} execution`,()=>k.execute(s,B));return k.trusted?await _$1.runTrustedAsync(()=>e()):await e()}catch(e){if(e instanceof b||e instanceof d$2)throw e;return A(`${t}: ${n$1(n$2(e))}
|
|
676
|
+
`)}}async function Dr(e,t){let s=e.state.inCondition;e.state.inCondition=!0;let g=``,S=``,w=0;try{for(let s of t){let t=await e.executeStatement(s);g+=t.stdout,S+=t.stderr,w=t.exitCode}}finally{e.state.inCondition=s}return{stdout:g,stderr:S,exitCode:w}}function Nt(e,t,s,g){if(e instanceof c)return t+=e.stdout,s+=e.stderr,e.levels>1&&g>1?(e.levels--,e.stdout=t,e.stderr=s,{action:`rethrow`,stdout:t,stderr:s,error:e}):{action:`break`,stdout:t,stderr:s};if(e instanceof a)return t+=e.stdout,s+=e.stderr,e.levels>1&&g>1?(e.levels--,e.stdout=t,e.stderr=s,{action:`rethrow`,stdout:t,stderr:s,error:e}):{action:`continue`,stdout:t,stderr:s};if(e instanceof i||e instanceof u||e instanceof d||e instanceof b)return e.prependOutput(t,s),{action:`rethrow`,stdout:t,stderr:s,error:e};let S=n$2(e);return{action:`error`,stdout:t,stderr:`${s}${S}
|
|
677
|
+
`,exitCode:1}}async function vs(e,t,s=``,g=``){let S=s,w=g,E=0;try{for(let s of t){let t=await e.executeStatement(s);S+=t.stdout,w+=t.stderr,E=t.exitCode}}catch(e){if(v(e)||e instanceof u||e instanceof d||e instanceof b||e instanceof f)throw e.prependOutput(S,w),e;return{stdout:S,stderr:`${w}${n$2(e)}
|
|
678
|
+
`,exitCode:1}}return{stdout:S,stderr:w,exitCode:E}}async function mi(e,t){let s=``,g=``;for(let S of t.clauses){let t=await Dr(e,S.condition);if(s+=t.stdout,g+=t.stderr,t.exitCode===0)return vs(e,S.body,s,g)}return t.elseBody?vs(e,t.elseBody,s,g):_(s,g,0)}async function yi(e,t){let s=await xe(e,t.redirections);if(s)return s;let g=``,S=``,w=0,E=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return A(`bash: \`${t.variable}': not a valid identifier
|
|
679
|
+
`);let D=[];if(t.words===null)D=(e.state.env.get(`@`)||``).split(` `).filter(Boolean);else if(t.words.length===0)D=[];else try{for(let s of t.words){let t=await wl(e,s);D.push(...t.values)}}catch(e){if(e instanceof h)return{stdout:``,stderr:e.stderr,exitCode:1};throw e}e.state.loopDepth++;try{for(let s of D){E++,E>e.limits.maxLoopIterations&&Ne(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,g,S),e.state.env.set(t.variable,s);try{for(let s of t.body){let t=await e.executeStatement(s);g+=t.stdout,S+=t.stderr,w=t.exitCode}}catch(s){let w=Nt(s,g,S,e.state.loopDepth);if(g=w.stdout,S=w.stderr,w.action===`break`)break;if(w.action===`continue`)continue;if(w.action===`error`)return G(e,_(g,S,w.exitCode??1),t.redirections);throw w.error}}}finally{e.state.loopDepth--}return G(e,_(g,S,w),t.redirections)}async function gi(e,t){let s=await xe(e,t.redirections);if(s)return s;let g=t.line;g!==void 0&&(e.state.currentLine=g);let S=``,w=``,E=0,D=0;t.init&&await R(e,t.init.expression),e.state.loopDepth++;try{for(;D++,D>e.limits.maxLoopIterations&&Ne(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,S,w),!(t.condition&&(g!==void 0&&(e.state.currentLine=g),await R(e,t.condition.expression)===0));){try{for(let s of t.body){let t=await e.executeStatement(s);S+=t.stdout,w+=t.stderr,E=t.exitCode}}catch(s){let g=Nt(s,S,w,e.state.loopDepth);if(S=g.stdout,w=g.stderr,g.action===`break`)break;if(g.action===`continue`){t.update&&await R(e,t.update.expression);continue}if(g.action===`error`)return G(e,_(S,w,g.exitCode??1),t.redirections);throw g.error}t.update&&await R(e,t.update.expression)}}finally{e.state.loopDepth--}return G(e,_(S,w,E),t.redirections)}async function wi(e,t,s=``){let g=``,S=``,w=0,E=0,D=s;for(let s of t.redirections)if((s.operator===`<<`||s.operator===`<<-`)&&s.target.type===`HereDoc`){let t=s.target,g=await Pt$1(e,t.content);t.stripTabs&&(g=g.split(`
|
|
680
680
|
`).map(e=>e.replace(/^\t+/,``)).join(`
|
|
681
681
|
`)),D=g}else if(s.operator===`<<<`&&s.target.type===`Word`)D=`${await Pt$1(e,s.target)}
|
|
682
682
|
`;else if(s.operator===`<`&&s.target.type===`Word`)try{let t=await Pt$1(e,s.target),g=e.fs.resolvePath(e.state.cwd,t);D=await e.fs.readFile(g)}catch{return A(`bash: ${await Pt$1(e,s.target)}: No such file or directory
|
|
683
|
-
`)}let O=e.state.groupStdin;D&&(e.state.groupStdin=D),e.state.loopDepth++;try{for(;;){E++,E>e.limits.maxLoopIterations&&Ne(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,g,S);let s=0,D=!1,O=!1,k=e.state.inCondition;e.state.inCondition=!0;try{for(let w of t.condition){let t=await e.executeStatement(w);g+=t.stdout,S+=t.stderr,s=t.exitCode}}catch(t){if(t instanceof c){if(g+=t.stdout,S+=t.stderr,t.levels>1&&e.state.loopDepth>1)throw t.levels--,t.stdout=g,t.stderr=S,e.state.inCondition=k,t;D=!0}else if(t instanceof a){if(g+=t.stdout,S+=t.stderr,t.levels>1&&e.state.loopDepth>1)throw t.levels--,t.stdout=g,t.stderr=S,e.state.inCondition=k,t;O=!0}else throw e.state.inCondition=k,t}finally{e.state.inCondition=k}if(D)break;if(!O){if(s!==0)break;try{for(let s of t.body){let t=await e.executeStatement(s);g+=t.stdout,S+=t.stderr,w=t.exitCode}}catch(t){let s=
|
|
684
|
-
`,t
|
|
683
|
+
`)}let O=e.state.groupStdin;D&&(e.state.groupStdin=D),e.state.loopDepth++;try{for(;;){E++,E>e.limits.maxLoopIterations&&Ne(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,g,S);let s=0,D=!1,O=!1,k=e.state.inCondition;e.state.inCondition=!0;try{for(let w of t.condition){let t=await e.executeStatement(w);g+=t.stdout,S+=t.stderr,s=t.exitCode}}catch(t){if(t instanceof c){if(g+=t.stdout,S+=t.stderr,t.levels>1&&e.state.loopDepth>1)throw t.levels--,t.stdout=g,t.stderr=S,e.state.inCondition=k,t;D=!0}else if(t instanceof a){if(g+=t.stdout,S+=t.stderr,t.levels>1&&e.state.loopDepth>1)throw t.levels--,t.stdout=g,t.stderr=S,e.state.inCondition=k,t;O=!0}else throw e.state.inCondition=k,t}finally{e.state.inCondition=k}if(D)break;if(!O){if(s!==0)break;try{for(let s of t.body){let t=await e.executeStatement(s);g+=t.stdout,S+=t.stderr,w=t.exitCode}}catch(t){let s=Nt(t,g,S,e.state.loopDepth);if(g=s.stdout,S=s.stderr,s.action===`break`)break;if(s.action===`continue`)continue;if(s.action===`error`)return _(g,S,s.exitCode??1);throw s.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=O}return _(g,S,w)}async function vi(e,t){let s=``,g=``,S=0,w=0;e.state.loopDepth++;try{for(;;){w++,w>e.limits.maxLoopIterations&&Ne(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,`iterations`,s,g);let E=await Dr(e,t.condition);if(s+=E.stdout,g+=E.stderr,E.exitCode===0)break;try{for(let w of t.body){let t=await e.executeStatement(w);s+=t.stdout,g+=t.stderr,S=t.exitCode}}catch(t){let S=Nt(t,s,g,e.state.loopDepth);if(s=S.stdout,g=S.stderr,S.action===`break`)break;if(S.action===`continue`)continue;if(S.action===`error`)return _(s,g,S.exitCode??1);throw S.error}}}finally{e.state.loopDepth--}return _(s,g,S)}async function bi(e,t){let s=await xe(e,t.redirections);if(s)return s;let g=``,S=``,w=0,E=await Pt$1(e,t.word),D=!1;for(let s=0;s<t.items.length;s++){let O=t.items[s],k=D;if(!D)for(let t of O.patterns){let s=await Pt$1(e,t);Al(t)&&(s=X$1(s));let g=e.state.shoptOptions.nocasematch,S=e.state.shoptOptions.extglob;if(ct(E,s,g,S)){k=!0;break}}if(k){let t=await vs(e,O.body,g,S);if(g=t.stdout,S=t.stderr,w=t.exitCode,O.terminator===`;;`)break;D=O.terminator===`;&`}else D=!1}return G(e,_(g,S,w),t.redirections)}function Tr(e,t){if(e.parts.length!==1)return!1;let s=e.parts[0];return s.type===`Literal`?t.includes(s.value):!1}function Ei(e){if(!e.startsWith(`__rw__:`))return null;let t=e.slice(7),s=t.indexOf(`:`);if(s===-1)return null;let g=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(g)||g<0)return null;let S=s+1,w=t.slice(S,S+g),E=S+g+1,D=t.slice(E),O=D.indexOf(`:`);if(O===-1)return null;let k=Number.parseInt(D.slice(0,O),10);return Number.isNaN(k)||k<0?null:{path:w,position:k,content:D.slice(O+1)}}var $i=`+ `;async function Si(e){let t=e.state.env.get(`PS4`);if(t===void 0)return $i;if(t===``)return``;try{return await Pt$1(e,new V().parseWordFromString(t,!1,!1))}catch{return e.state.expansionStderr=`${e.state.expansionStderr||``}bash: ${t}: bad substitution
|
|
684
|
+
`,t||$i}}function pa(e){return e.map(e=>ma(e)).join(` `)}function ma(e){if(e===``)return`''`;if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let t=/[\x00-\x1f\x7f]/.test(e),s=e.includes(`
|
|
685
685
|
`),g=e.includes(` `),S=e.includes(`\\`),w=e.includes(`'`);if(t||s||g||S){let t=``;for(let s of e){let e=s.charCodeAt(0);s===`
|
|
686
|
-
`?t+=`\\n`:s===` `?t+=`\\t`:s===`\\`?t+=`\\\\`:s===`'`?t+=`'`:s===`"`?t+=`"`:e<32||e===127?e<256?t+=`\\x${e.toString(16).padStart(2,`0`)}`:t+=`\\u${e.toString(16).padStart(4,`0`)}`:t+=s}return`$'${t}'`}return w?`"${e.replace(/([\\$`"])/g,`\\$1`)}"`:`'${e}'`}async function
|
|
687
|
-
`:``}async function
|
|
688
|
-
`:``}async function
|
|
686
|
+
`?t+=`\\n`:s===` `?t+=`\\t`:s===`\\`?t+=`\\\\`:s===`'`?t+=`'`:s===`"`?t+=`"`:e<32||e===127?e<256?t+=`\\x${e.toString(16).padStart(2,`0`)}`:t+=`\\u${e.toString(16).padStart(4,`0`)}`:t+=s}return`$'${t}'`}return w?`"${e.replace(/([\\$`"])/g,`\\$1`)}"`:`'${e}'`}async function Pi(e,t,s){return e.state.options.xtrace?`${await Si(e)}${pa([t,...s])}
|
|
687
|
+
`:``}async function Ai(e,t,s){return e.state.options.xtrace?`${await Si(e)}${t}=${s}
|
|
688
|
+
`:``}async function ki(e,t,s){let g=t.timed?o$1():0,S=``,w=W,E=0,D=[],O=``,k=t.commands.length>1,j=e.state.lastArg;for(let g=0;g<t.commands.length;g++){let j=t.commands[g],F=g===t.commands.length-1,L=g===0;k&&(e.state.lastArg=``,L||(e.state.groupStdin=void 0));let B=k&&(!F||!e.state.shoptOptions.lastpipe)?new Map(e.state.env):null,H;try{H=await s(j,S)}catch(s){if(s instanceof l)H={stdout:s.stdout,stderr:s.stderr,exitCode:1};else if(s instanceof d&&t.commands.length>1)H={stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode};else if(s instanceof u&&t.commands.length>1)H={stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode};else throw B&&(e.state.env=B),s}B&&(e.state.env=B),D.push(H.exitCode),H.exitCode!==0&&(E=H.exitCode),F?w=H:(t.pipeStderr?.[g]??!1?S=H.stderr+H.stdout:(S=H.stdout,O+=H.stderr),w={stdout:``,stderr:``,exitCode:H.exitCode})}if(O&&(w={...w,stderr:O+w.stderr}),t.commands.length>1||t.commands.length===1&&t.commands[0].type===`SimpleCommand`){for(let t of e.state.env.keys())t.startsWith(`PIPESTATUS_`)&&e.state.env.delete(t);for(let t=0;t<D.length;t++)e.state.env.set(`PIPESTATUS_${t}`,String(D[t]));e.state.env.set(`PIPESTATUS__length`,String(D.length))}if(e.state.options.pipefail&&E!==0&&(w={...w,exitCode:E}),t.negated&&(w={...w,exitCode:w.exitCode===0?1:0}),t.timed){let e=(o$1()-g)/1e3,s=Math.floor(e/60),S=e%60,E;E=t.timePosix?`real ${e.toFixed(2)}
|
|
689
689
|
user 0.00
|
|
690
690
|
sys 0.00
|
|
691
691
|
`:`
|
|
692
692
|
real ${`${s}m${S.toFixed(3)}s`}
|
|
693
693
|
user 0m0.000s
|
|
694
694
|
sys 0m0.000s
|
|
695
|
-
`,w={...w,stderr:w.stderr+E}}return k&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=j),w}async function
|
|
696
|
-
`,1)};let D=w.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(D){let w=await
|
|
695
|
+
`,w={...w,stderr:w.stderr+E}}return k&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=j),w}async function _i(e,t){let s=new Map,g=``;for(let S of t.assignments){let w=S.name;if(S.array){let E=await ya(e,t,w,S.array,S.append,s);if(E.error)return{continueToNext:!1,xtraceOutput:g,tempAssignments:s,error:E.error};if(g+=E.xtraceOutput,E.continueToNext)continue}let E=S.value?await Pt$1(e,S.value):``;if(w.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:g,tempAssignments:s,error:_(``,`bash: ${w}: bad array subscript
|
|
696
|
+
`,1)};let D=w.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(D){let w=await Ea(e,t,D[1],D[2],E,S.append,s);if(w.error)return{continueToNext:!1,xtraceOutput:g,tempAssignments:s,error:w.error};if(w.continueToNext)continue}let O=await Sa(e,t,w,E,S.append,s);if(O.error)return{continueToNext:!1,xtraceOutput:g,tempAssignments:s,error:O.error};g+=O.xtraceOutput,O.continueToNext}return{continueToNext:!1,xtraceOutput:g,tempAssignments:s}}async function ya(e,t,s,g,S,w){let E=``;if(/\[.+\]$/.test(s))return{continueToNext:!1,xtraceOutput:``,error:_(``,`bash: ${s}: cannot assign list to array member
|
|
697
697
|
`,1)};if(W$1(e,s)){let t=Se(e,s);if(t===void 0||t===``)throw new d(1,``,``);let g=he(e,s);if(g&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(g))return{continueToNext:!1,xtraceOutput:``,error:_(``,`bash: ${s}: cannot assign list to array member
|
|
698
698
|
`,1)}}if(wt(e,s)){if(t.name)return E+=`bash: ${s}: readonly variable
|
|
699
|
-
`,{continueToNext:!0,xtraceOutput:E};let g=da$1(e,s);if(g)return{continueToNext:!1,xtraceOutput:``,error:g}}let D=e.state.associativeArrays?.has(s),O=
|
|
700
|
-
`)}async function
|
|
701
|
-
`,1)};D=t}}if(wt(e,D)){if(t.name)return{continueToNext:!0,xtraceOutput:``};let s=da$1(e,D);if(s)return{continueToNext:!1,xtraceOutput:``,error:s}}let O=e.state.associativeArrays?.has(D),k;if(O)k=await
|
|
699
|
+
`,{continueToNext:!0,xtraceOutput:E};let g=da$1(e,s);if(g)return{continueToNext:!1,xtraceOutput:``,error:g}}let D=e.state.associativeArrays?.has(s),O=ga(g),k=()=>{let t=`${s}_`;for(let s of e.state.env.keys())s.startsWith(t)&&!s.includes(`__`)&&e.state.env.delete(s);e.state.env.delete(s)};if(D&&O?await wa(e,t,s,g,S,k,e=>{E+=e}):O?await va(e,s,g,S,k):await ba(e,s,g,S,k),t.name){w.set(s,e.state.env.get(s));let t=`(${g.map(e=>En$1(e)).join(` `)})`;e.state.env.set(s,t)}return{continueToNext:!0,xtraceOutput:E}}function ga(e){return e.some(e=>{if(e.parts.length>=2){let t=e.parts[0],s=e.parts[1];if(t.type!==`Glob`||!t.pattern.startsWith(`[`))return!1;if(t.pattern===`[`&&(s.type===`DoubleQuoted`||s.type===`SingleQuoted`)){if(e.parts.length<3)return!1;let t=e.parts[2];return t.type===`Literal`?t.value.startsWith(`]=`)||t.value.startsWith(`]+=`):!1}return s.type===`Literal`?s.value.startsWith(`]`)?s.value.startsWith(`]=`)||s.value.startsWith(`]+=`):t.pattern.endsWith(`]`)?s.value.startsWith(`=`)||s.value.startsWith(`+=`):!1:!1}return!1})}async function wa(e,t,s,g,S,w,E){let D=[];for(let t of g){let s=Oi$1(t);if(s){let{key:t,valueParts:g,append:S}=s,w;w=g.length>0?await Pt$1(e,{type:`Word`,parts:g}):``,w=X(e,w),D.push({type:`keyed`,key:t,value:w,append:S})}else{let s=await Pt$1(e,t);D.push({type:`invalid`,expandedValue:s})}}S||w();for(let g of D)if(g.type===`keyed`)if(g.append){let t=e.state.env.get(`${s}_${g.key}`)??``;e.state.env.set(`${s}_${g.key}`,t+g.value)}else e.state.env.set(`${s}_${g.key}`,g.value);else E(`bash: line ${t.line??e.state.currentLine??1}: ${s}: ${g.expandedValue}: must use subscript when assigning associative array
|
|
700
|
+
`)}async function va(e,t,s,g,S){let w=[];for(let t of s){let s=Oi$1(t);if(s){let{key:t,valueParts:g,append:S}=s,E;E=g.length>0?await Pt$1(e,{type:`Word`,parts:g}):``,E=X(e,E),w.push({type:`keyed`,indexExpr:t,value:E,append:S})}else{let s=await wl(e,t);w.push({type:`non-keyed`,values:s.values})}}g||S();let E=0;for(let s of w)if(s.type===`keyed`){let g;try{g=await R(e,M(new V,s.indexExpr).expression,!1)}catch{if(/^-?\d+$/.test(s.indexExpr))g=Number.parseInt(s.indexExpr,10);else{let t=e.state.env.get(s.indexExpr);g=t?Number.parseInt(t,10):0,Number.isNaN(g)&&(g=0)}}if(s.append){let S=e.state.env.get(`${t}_${g}`)??``;e.state.env.set(`${t}_${g}`,S+s.value)}else e.state.env.set(`${t}_${g}`,s.value);E=g+1}else for(let g of s.values)e.state.env.set(`${t}_${E++}`,g)}async function ba(e,t,s,g,S){let w=[];for(let t of s){let s=await wl(e,t);w.push(...s.values)}let E=0;if(g){let s=P(e,t);if(s.length>0)E=Math.max(...s.map(([e])=>typeof e==`number`?e:0))+1;else{let s=e.state.env.get(t);s!==void 0&&(e.state.env.set(`${t}_0`,s),e.state.env.delete(t),E=1)}}else S();for(let s=0;s<w.length;s++)e.state.env.set(`${t}_${E+s}`,w[s]);g||e.state.env.set(`${t}__length`,String(w.length))}async function Ea(e,t,s,g,S,w,E){let D=s;if(W$1(e,s)){let t=he(e,s);if(t&&t!==s){if(t.includes(`[`))return{continueToNext:!1,xtraceOutput:``,error:_(``,`bash: \`${t}': not a valid identifier
|
|
701
|
+
`,1)};D=t}}if(wt(e,D)){if(t.name)return{continueToNext:!0,xtraceOutput:``};let s=da$1(e,D);if(s)return{continueToNext:!1,xtraceOutput:``,error:s}}let O=e.state.associativeArrays?.has(D),k;if(O)k=await Ci(e,D,g);else{let t=await $a(e,D,g);if(t.error)return{continueToNext:!1,xtraceOutput:``,error:t.error};k=`${D}_${t.index}`}let j=w?(e.state.env.get(k)||``)+S:S;if(t.name)E.set(k,e.state.env.get(k)),e.state.env.set(k,j);else{let t=ut(e,D);if(t!==void 0&&t===e.state.callDepth&&e.state.localScopes.length>0){let t=e.state.localScopes[e.state.localScopes.length-1];t.has(k)||t.set(k,e.state.env.get(k))}e.state.env.set(k,j)}return{continueToNext:!0,xtraceOutput:``}}async function Ci(e,t,s){let g;if(s.startsWith(`'`)&&s.endsWith(`'`))g=s.slice(1,-1);else if(s.startsWith(`"`)&&s.endsWith(`"`)){let t=s.slice(1,-1);g=await Pt$1(e,new V().parseWordFromString(t,!0,!1))}else g=s.includes(`$`)?await Pt$1(e,new V().parseWordFromString(s,!1,!1)):s;return`${t}_${g}`}async function $a(e,t,s){let g=s;s.startsWith(`"`)&&s.endsWith(`"`)&&s.length>=2&&(g=s.slice(1,-1));let S;if(/^-?\d+$/.test(g))S=Number.parseInt(g,10);else{try{S=await R(e,M(new V,g).expression,!1)}catch(t){if(t instanceof p){let g=`bash: line ${e.state.currentLine}: ${s}: ${t.message}
|
|
702
702
|
`;if(t.fatal)throw new d(1,``,g);return{index:0,error:_(``,g,1)}}let g=e.state.env.get(s);S=g?Number.parseInt(g,10):0}Number.isNaN(S)&&(S=0)}if(S<0){let g=P(e,t);if(g.length===0){let g=e.state.currentLine;return{index:0,error:_(``,`bash: line ${g}: ${t}[${s}]: bad array subscript
|
|
703
703
|
`,1)}}if(S=Math.max(...g.map(([e])=>typeof e==`number`?e:0))+1+S,S<0){let g=e.state.currentLine;return{index:0,error:_(``,`bash: line ${g}: ${t}[${s}]: bad array subscript
|
|
704
|
-
`,1)}}}return{index:S}}async function
|
|
704
|
+
`,1)}}}return{index:S}}async function Sa(e,t,s,g,S,w){let E=``,D=s,O=null;if(W$1(e,s)){let t=zi$1(e,s,g);if(t===void 0)return{continueToNext:!1,xtraceOutput:``,error:_(``,`bash: ${s}: circular name reference
|
|
705
705
|
`,1)};if(t===null)return{continueToNext:!0,xtraceOutput:``};D=t;let S=D.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);S&&(O={arrayName:S[1],subscriptExpr:S[2]},D=S[1])}if(wt(e,D)){if(t.name)return E+=`bash: ${D}: readonly variable
|
|
706
|
-
`,{continueToNext:!0,xtraceOutput:E};let s=da$1(e,D);if(s)return{continueToNext:!1,xtraceOutput:``,error:s}}let k;if(
|
|
707
|
-
`,1),t.redirections)}return ae(),G(e,_(Y,te,ne),t.redirections)}async function
|
|
706
|
+
`,{continueToNext:!0,xtraceOutput:E};let s=da$1(e,D);if(s)return{continueToNext:!1,xtraceOutput:``,error:s}}let k;if(kt(e,D))try{let t=new V;if(S){let s=M(t,`(${e.state.env.get(D)||`0`}) + (${g})`);k=String(await R(e,s.expression))}else{let s=M(t,g);k=String(await R(e,s.expression))}}catch{k=`0`}else{let{isArray:t}=await import(`./expansion-VBDYWVZR-k3W3Rc7R.mjs`),s=t(e,D)?`${D}_0`:D;k=S?(e.state.env.get(s)||``)+g:g}k=ht(e,D,k),E+=await Ai(e,D,k);let j=D;if(O)j=await Pa(e,O);else{let{isArray:t}=await import(`./expansion-VBDYWVZR-k3W3Rc7R.mjs`);t(e,D)&&(j=`${D}_0`)}return t.name?(w.set(j,e.state.env.get(j)),e.state.env.set(j,k)):(e.state.env.set(j,k),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(D)),e.state.tempEnvBindings?.some(e=>e.has(D))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(D))),{continueToNext:!1,xtraceOutput:E}}async function Pa(e,t){let{arrayName:s,subscriptExpr:g}=t;if(e.state.associativeArrays?.has(s))return Ci(e,s,g);let S;if(/^-?\d+$/.test(g))S=Number.parseInt(g,10);else{try{S=await R(e,M(new V,g).expression,!1)}catch{let t=e.state.env.get(g);S=t?Number.parseInt(t,10):0}Number.isNaN(S)&&(S=0)}if(S<0){let t=P(e,s);t.length>0&&(S=Math.max(...t.map(e=>e[0]))+1+S)}return`${s}_${S}`}async function Ni(e,t,s,g){let S=await xe(e,t.redirections);if(S)return S;let w=new Map(e.state.env),E=e.state.cwd,D={...e.state.options},O=new Map(e.state.functions),k=e.state.localScopes,j=e.state.localVarStack,F=e.state.localVarDepth,L=e.state.fullyUnsetLocals;if(e.state.localScopes=k.map(e=>new Map(e)),j){e.state.localVarStack=new Map;for(let[t,s]of j.entries())e.state.localVarStack.set(t,s.map(e=>({...e})))}F&&(e.state.localVarDepth=new Map(F)),L&&(e.state.fullyUnsetLocals=new Map(L));let B=e.state.loopDepth,H=e.state.parentHasLoopContext;e.state.parentHasLoopContext=B>0,e.state.loopDepth=0;let q=e.state.lastArg,ee=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let J=e.state.groupStdin;s&&(e.state.groupStdin=s);let Y=``,te=``,ne=0,ae=()=>{e.state.env=w,e.state.cwd=E,e.state.options=D,e.state.functions=O,e.state.localScopes=k,e.state.localVarStack=j,e.state.localVarDepth=F,e.state.fullyUnsetLocals=L,e.state.loopDepth=B,e.state.parentHasLoopContext=H,e.state.groupStdin=J,e.state.bashPid=ee,e.state.lastArg=q};try{for(let e of t.body){let t=await g(e);Y+=t.stdout,te+=t.stderr,ne=t.exitCode}}catch(s){if(ae(),s instanceof b)throw s;return s instanceof f||s instanceof c||s instanceof a?(Y+=s.stdout,te+=s.stderr,G(e,_(Y,te,0),t.redirections)):s instanceof d||s instanceof i?(Y+=s.stdout,te+=s.stderr,G(e,_(Y,te,s.exitCode),t.redirections)):s instanceof u?G(e,_(Y+s.stdout,te+s.stderr,s.exitCode),t.redirections):G(e,_(Y,`${te}${n$2(s)}
|
|
707
|
+
`,1),t.redirections)}return ae(),G(e,_(Y,te,ne),t.redirections)}async function Oi(e,t,s,g){let S=``,w=``,E=0,D=await fs(e,t.redirections);if(D)return D;let O=s;for(let s of t.redirections)if((s.operator===`<<`||s.operator===`<<-`)&&s.target.type===`HereDoc`){let t=s.target,g=await Pt$1(e,t.content);t.stripTabs&&(g=g.split(`
|
|
708
708
|
`).map(e=>e.replace(/^\t+/,``)).join(`
|
|
709
709
|
`));let S=s.fd??0;S===0?O=g:(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),le(e),e.state.fileDescriptors.set(S,g))}else if(s.operator===`<<<`&&s.target.type===`Word`)O=`${await Pt$1(e,s.target)}
|
|
710
710
|
`;else if(s.operator===`<`&&s.target.type===`Word`)try{let t=await Pt$1(e,s.target),g=e.fs.resolvePath(e.state.cwd,t);O=await e.fs.readFile(g)}catch{return _(``,`bash: ${await Pt$1(e,s.target)}: No such file or directory
|
|
711
711
|
`,1)}let k=e.state.groupStdin;O&&(e.state.groupStdin=O);try{for(let e of t.body){let t=await g(e);S+=t.stdout,w+=t.stderr,E=t.exitCode}}catch(t){if(e.state.groupStdin=k,t instanceof b)throw t;if(v(t)||t instanceof u||t instanceof d)throw t.prependOutput(S,w),t;return _(S,`${w}${n$2(t)}
|
|
712
|
-
`,1)}return e.state.groupStdin=k,G(e,_(S,w,E),t.redirections)}async function
|
|
712
|
+
`,1)}return e.state.groupStdin=k,G(e,_(S,w,E),t.redirections)}async function xi(e,t,s,g,S){let w;try{w=await e.fs.readFile(t)}catch{return A(`bash: ${t}: No such file or directory
|
|
713
713
|
`,127)}if(w.startsWith(`#!`)){let e=w.indexOf(`
|
|
714
714
|
`);e!==-1&&(w=w.slice(e+1))}let E=new Map(e.state.env),D=e.state.cwd,O={...e.state.options},k=e.state.loopDepth,j=e.state.parentHasLoopContext,F=e.state.lastArg,L=e.state.bashPid,B=e.state.groupStdin,H=e.state.currentSource;e.state.parentHasLoopContext=k>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++,g&&(e.state.groupStdin=g),e.state.currentSource=t,e.state.env.set(`0`,t),e.state.env.set(`#`,String(s.length)),e.state.env.set(`@`,s.join(` `)),e.state.env.set(`*`,s.join(` `));for(let t=0;t<s.length&&t<9;t++)e.state.env.set(String(t+1),s[t]);for(let t=s.length+1;t<=9;t++)e.state.env.delete(String(t));let q=()=>{e.state.env=E,e.state.cwd=D,e.state.options=O,e.state.loopDepth=k,e.state.parentHasLoopContext=j,e.state.lastArg=F,e.state.bashPid=L,e.state.groupStdin=B,e.state.currentSource=H};try{let e=await S(new V().parse(w));return q(),e}catch(e){if(q(),e instanceof d||e instanceof b)throw e;if(e.name===`ParseException`)return A(`bash: ${t}: ${e.message}
|
|
715
|
-
`);throw e}}var
|
|
716
|
-
`);let g=0,S=-1,w=!1;for(let E=0;E<e.pipelines.length;E++){let D=e.pipelines[E],O=E>0?e.operators[E-1]:null;if(O===`&&`&&g!==0||O===`||`&&g===0)continue;let k=await this.executePipeline(D);t+=k.stdout,s+=k.stderr,g=k.exitCode,S=E,w=D.negated,this.ctx.state.lastExitCode=g,this.ctx.state.env.set(`?`,String(g))}let E=S<e.pipelines.length-1,D=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=E||w||D,this.ctx.state.options.errexit&&g!==0&&S===e.pipelines.length-1&&!w&&!this.ctx.state.inCondition&&!D)throw new u(g,t,s);return _(t,s,g)}async executePipeline(e){return
|
|
715
|
+
`);throw e}}var Ot=class{ctx;constructor(e,t){this.ctx={state:t,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep,trace:e.trace,coverage:e.coverage,requireDefenseContext:e.requireDefenseContext??!1,jsBootstrapCode:e.jsBootstrapCode}}assertDefenseContext(e){if(!this.ctx.requireDefenseContext||_$1.isInSandboxedContext())return;let t=`interpreter ${e} attempted outside defense context`;throw new d$2(t,{timestamp:Date.now(),type:`missing_defense_context`,message:t,path:`DefenseInDepthBox.context`,stack:Error().stack,executionId:_$1.getCurrentExecutionId()})}buildExportedEnv(){let e=this.ctx.state.exportedVars,t=this.ctx.state.tempExportedVars,s=new Set;if(e)for(let t of e)s.add(t);if(t)for(let e of t)s.add(e);if(s.size===0)return Object.create(null);let g=Object.create(null);for(let e of s){let t=this.ctx.state.env.get(e);t!==void 0&&(g[e]=t)}return g}async executeScript(e){this.assertDefenseContext(`execution`);let t=``,s=``,g=0,S=this.ctx.limits.maxOutputSize,w=(e,g)=>{t.length+s.length+e.length+g.length>S&&Ne(`total output size exceeded (>${S} bytes), increase executionLimits.maxOutputSize`,`output_size`),t+=e,s+=g};for(let S of e.statements)try{let e=await this.executeStatement(S);w(e.stdout,e.stderr),g=e.exitCode,this.ctx.state.lastExitCode=g,this.ctx.state.env.set(`?`,String(g))}catch(e){if(e instanceof d)throw e.prependOutput(t,s),e;if(e instanceof C)return w(e.stdout,e.stderr),g=e.exitCode,this.ctx.state.lastExitCode=g,this.ctx.state.env.set(`?`,String(g)),{stdout:t,stderr:s,exitCode:g,env:r(this.ctx.state.env)};if(e instanceof b)throw e;if(e instanceof u)return w(e.stdout,e.stderr),g=e.exitCode,this.ctx.state.lastExitCode=g,this.ctx.state.env.set(`?`,String(g)),{stdout:t,stderr:s,exitCode:g,env:r(this.ctx.state.env)};if(e instanceof x||e instanceof l)return w(e.stdout,e.stderr),g=1,this.ctx.state.lastExitCode=g,this.ctx.state.env.set(`?`,String(g)),{stdout:t,stderr:s,exitCode:g,env:r(this.ctx.state.env)};if(e instanceof p){w(e.stdout,e.stderr),g=1,this.ctx.state.lastExitCode=g,this.ctx.state.env.set(`?`,String(g));continue}if(e instanceof m){w(e.stdout,e.stderr),g=1,this.ctx.state.lastExitCode=g,this.ctx.state.env.set(`?`,String(g));continue}if(e instanceof c||e instanceof a){if(this.ctx.state.loopDepth>0)throw e.prependOutput(t,s),e;w(e.stdout,e.stderr);continue}throw e instanceof i&&e.prependOutput(t,s),e}return{stdout:t,stderr:s,exitCode:g,env:r(this.ctx.state.env)}}async executeUserScript(e,t,s=``){return xi(this.ctx,e,t,s,e=>this.executeScript(e))}async executeStatement(e){if(this.assertDefenseContext(`statement`),this.ctx.state.signal?.aborted)throw new $$1;if(this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&Ne(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,`commands`),e.deferredError)throw new G$1(e.deferredError.message,e.line??1,1);if(this.ctx.state.options.noexec)return W;this.ctx.state.errexitSafe=!1;let t=``,s=``;this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&e.sourceText&&(s+=`${e.sourceText}
|
|
716
|
+
`);let g=0,S=-1,w=!1;for(let E=0;E<e.pipelines.length;E++){let D=e.pipelines[E],O=E>0?e.operators[E-1]:null;if(O===`&&`&&g!==0||O===`||`&&g===0)continue;let k=await this.executePipeline(D);t+=k.stdout,s+=k.stderr,g=k.exitCode,S=E,w=D.negated,this.ctx.state.lastExitCode=g,this.ctx.state.env.set(`?`,String(g))}let E=S<e.pipelines.length-1,D=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=E||w||D,this.ctx.state.options.errexit&&g!==0&&S===e.pipelines.length-1&&!w&&!this.ctx.state.inCondition&&!D)throw new u(g,t,s);return _(t,s,g)}async executePipeline(e){return ki(this.ctx,e,(e,t)=>this.executeCommand(e,t))}async executeCommand(e,t){switch(this.assertDefenseContext(`command`),this.ctx.coverage?.hit(`bash:cmd:${e.type}`),e.type){case`SimpleCommand`:return this.executeSimpleCommand(e,t);case`If`:return mi(this.ctx,e);case`For`:return yi(this.ctx,e);case`CStyleFor`:return gi(this.ctx,e);case`While`:return wi(this.ctx,e,t);case`Until`:return vi(this.ctx,e);case`Case`:return bi(this.ctx,e);case`Subshell`:return this.executeSubshell(e,t);case`Group`:return this.executeGroup(e,t);case`FunctionDef`:return Ln(this.ctx,e);case`ArithmeticCommand`:return this.executeArithmeticCommand(e);case`ConditionalCommand`:return this.executeConditionalCommand(e);default:return W}}async executeSimpleCommand(e,t){try{return await this.executeSimpleCommandInner(e,t)}catch(e){if(e instanceof h)return A(e.stderr);throw e}}async executeSimpleCommandInner(e,t){if(e.line!==void 0&&(this.ctx.state.currentLine=e.line),this.ctx.state.shoptOptions.expand_aliases&&e.name){let t=e,s=100;for(;s>0;){let e=this.expandAlias(t);if(e===t)break;t=e,s--}this.aliasExpansionStack.clear(),t!==e&&(e=t)}this.ctx.state.expansionStderr=``;let s=await _i(this.ctx,e);if(s.error)return s.error;let g=s.tempAssignments,S=s.xtraceOutput;if(!e.name){if(e.redirections.length>0){let t=await xe(this.ctx,e.redirections);if(t)return t;let s=_(``,S,0);return G(this.ctx,s,e.redirections)}this.ctx.state.lastArg=``;let t=(this.ctx.state.expansionStderr||``)+S;return this.ctx.state.expansionStderr=``,_(``,t,this.ctx.state.lastExitCode)}let w=e.name&&Tr(e.name,[`local`,`declare`,`typeset`,`export`,`readonly`]),E=Array.from(g.keys());if(E.length>0&&!w){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let e of E)this.ctx.state.tempExportedVars.add(e)}let D=await fs(this.ctx,e.redirections);if(D){for(let[e,t]of g)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t);return D}let O=-1;for(let s of e.redirections){if((s.operator===`<<`||s.operator===`<<-`)&&s.target.type===`HereDoc`){let e=s.target,g=await Pt$1(this.ctx,e.content);e.stripTabs&&(g=g.split(`
|
|
717
717
|
`).map(e=>e.replace(/^\t+/,``)).join(`
|
|
718
718
|
`));let S=s.fd??0;S===0?t=g:(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),le(this.ctx),this.ctx.state.fileDescriptors.set(S,g));continue}if(s.operator===`<<<`&&s.target.type===`Word`){t=`${await Pt$1(this.ctx,s.target)}
|
|
719
719
|
`;continue}if(s.operator===`<`&&s.target.type===`Word`)try{let e=await Pt$1(this.ctx,s.target),g=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);t=await this.ctx.fs.readFile(g)}catch{let e=await Pt$1(this.ctx,s.target);for(let[e,t]of g)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t);return A(`bash: ${e}: No such file or directory
|
|
720
|
-
`)}if(s.operator===`<&`&&s.target.type===`Word`){let e=await Pt$1(this.ctx,s.target),g=Number.parseInt(e,10);if(!Number.isNaN(g)&&this.ctx.state.fileDescriptors){let e=this.ctx.state.fileDescriptors.get(g);if(e!==void 0)if(e.startsWith(`__rw__:`)){let s=
|
|
720
|
+
`)}if(s.operator===`<&`&&s.target.type===`Word`){let e=await Pt$1(this.ctx,s.target),g=Number.parseInt(e,10);if(!Number.isNaN(g)&&this.ctx.state.fileDescriptors){let e=this.ctx.state.fileDescriptors.get(g);if(e!==void 0)if(e.startsWith(`__rw__:`)){let s=Ei(e);s&&(t=s.content.slice(s.position),O=g)}else e.startsWith(`__file__:`)||e.startsWith(`__file_append__:`)||(t=e)}}}let k=await Pt$1(this.ctx,e.name),j=[],F=[];if(Tr(e.name,[`local`,`declare`,`typeset`,`export`,`readonly`])&&(k===`local`||k===`declare`||k===`typeset`||k===`export`||k===`readonly`))for(let t of e.args){let e=await vn(this.ctx,t);if(e)j.push(e),F.push(!0);else{let e=await bn(this.ctx,t);if(e!==null)j.push(e),F.push(!0);else{let e=await wl(this.ctx,t);for(let t of e.values)j.push(t),F.push(e.quoted)}}}else for(let t of e.args){let e=await wl(this.ctx,t);for(let t of e.values)j.push(t),F.push(e.quoted)}if(!k){if(e.name.parts.every(e=>e.type===`CommandSubstitution`||e.type===`ParameterExpansion`||e.type===`ArithmeticExpansion`)){if(j.length>0){let e=j.shift();return F.shift(),await this.runCommand(e,j,F,t,!1,!1,O)}return _(``,``,this.ctx.state.lastExitCode)}return A(`bash: : command not found
|
|
721
721
|
`,127)}if(k===`exec`&&(j.length===0||j[0]===`--`)){for(let t of e.redirections){if(t.target.type===`HereDoc`||t.fdVariable)continue;let e=await Pt$1(this.ctx,t.target),s=t.fd??(t.operator===`<`||t.operator===`<>`?0:1);switch(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),t.operator){case`>`:case`>|`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);await this.ctx.fs.writeFile(t,``,`utf8`),le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__file__:${t}`);break}case`>>`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__file_append__:${t}`);break}case`<`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);try{let e=await this.ctx.fs.readFile(t);le(this.ctx),this.ctx.state.fileDescriptors.set(s,e)}catch{return A(`bash: ${e}: No such file or directory
|
|
722
|
-
`)}break}case`<>`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);try{let e=await this.ctx.fs.readFile(t);le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__rw__:${t.length}:${t}:0:${e}`)}catch{await this.ctx.fs.writeFile(t,``,`utf8`),le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__rw__:${t.length}:${t}:0:`)}break}case`>&`:if(e===`-`)this.ctx.state.fileDescriptors.delete(s);else if(e.endsWith(`-`)){let t=e.slice(0,-1),g=Number.parseInt(t,10);if(!Number.isNaN(g)){let e=this.ctx.state.fileDescriptors.get(g);e===void 0?this.ctx.state.fileDescriptors.set(s,`__dupout__:${g}`):this.ctx.state.fileDescriptors.set(s,e),this.ctx.state.fileDescriptors.delete(g)}}else{let t=Number.parseInt(e,10);Number.isNaN(t)||(le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__dupout__:${t}`))}break;case`<&`:if(e===`-`)this.ctx.state.fileDescriptors.delete(s);else if(e.endsWith(`-`)){let t=e.slice(0,-1),g=Number.parseInt(t,10);if(!Number.isNaN(g)){let e=this.ctx.state.fileDescriptors.get(g);e===void 0?this.ctx.state.fileDescriptors.set(s,`__dupin__:${g}`):this.ctx.state.fileDescriptors.set(s,e),this.ctx.state.fileDescriptors.delete(g)}}else{let t=Number.parseInt(e,10);Number.isNaN(t)||(le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__dupin__:${t}`))}break}}for(let[e,t]of g)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t);if(this.ctx.state.tempExportedVars)for(let e of g.keys())this.ctx.state.tempExportedVars.delete(e);return W}if(this.ctx.state.extraArgs){j.push(...this.ctx.state.extraArgs);for(let e=0;e<this.ctx.state.extraArgs.length;e++)F.push(!0);this.ctx.state.extraArgs=void 0}let L=await
|
|
722
|
+
`)}break}case`<>`:{let t=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);try{let e=await this.ctx.fs.readFile(t);le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__rw__:${t.length}:${t}:0:${e}`)}catch{await this.ctx.fs.writeFile(t,``,`utf8`),le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__rw__:${t.length}:${t}:0:`)}break}case`>&`:if(e===`-`)this.ctx.state.fileDescriptors.delete(s);else if(e.endsWith(`-`)){let t=e.slice(0,-1),g=Number.parseInt(t,10);if(!Number.isNaN(g)){let e=this.ctx.state.fileDescriptors.get(g);e===void 0?this.ctx.state.fileDescriptors.set(s,`__dupout__:${g}`):this.ctx.state.fileDescriptors.set(s,e),this.ctx.state.fileDescriptors.delete(g)}}else{let t=Number.parseInt(e,10);Number.isNaN(t)||(le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__dupout__:${t}`))}break;case`<&`:if(e===`-`)this.ctx.state.fileDescriptors.delete(s);else if(e.endsWith(`-`)){let t=e.slice(0,-1),g=Number.parseInt(t,10);if(!Number.isNaN(g)){let e=this.ctx.state.fileDescriptors.get(g);e===void 0?this.ctx.state.fileDescriptors.set(s,`__dupin__:${g}`):this.ctx.state.fileDescriptors.set(s,e),this.ctx.state.fileDescriptors.delete(g)}}else{let t=Number.parseInt(e,10);Number.isNaN(t)||(le(this.ctx),this.ctx.state.fileDescriptors.set(s,`__dupin__:${t}`))}break}}for(let[e,t]of g)t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t);if(this.ctx.state.tempExportedVars)for(let e of g.keys())this.ctx.state.tempExportedVars.delete(e);return W}if(this.ctx.state.extraArgs){j.push(...this.ctx.state.extraArgs);for(let e=0;e<this.ctx.state.extraArgs.length;e++)F.push(!0);this.ctx.state.extraArgs=void 0}let L=await Pi(this.ctx,k,j);g.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(g)));let B,H=null;try{B=await this.runCommand(k,j,F,t,!1,!1,O)}catch(e){if(e instanceof c||e instanceof a)H=e,B=W;else throw e}let q=S+L;if(q&&(B={...B,stderr:q+B.stderr}),B=await G(this.ctx,B,e.redirections),H)throw H;if(j.length>0){let e=j[j.length-1];if((k===`declare`||k===`local`||k===`typeset`)&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(e)){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);t&&(e=t[1])}this.ctx.state.lastArg=e}else this.ctx.state.lastArg=k;let ee=Rn(k)&&k!==`unset`&&k!==`eval`;if(!this.ctx.state.options.posix||!ee)for(let[e,t]of g)this.ctx.state.fullyUnsetLocals?.has(e)||(t===void 0?this.ctx.state.env.delete(e):this.ctx.state.env.set(e,t));if(this.ctx.state.tempExportedVars)for(let e of g.keys())this.ctx.state.tempExportedVars.delete(e);return g.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop(),this.ctx.state.expansionStderr&&(B={...B,stderr:this.ctx.state.expansionStderr+B.stderr},this.ctx.state.expansionStderr=``),B}async runCommand(e,t,s,g,S=!1,w=!1,E=-1){let D={ctx:this.ctx,runCommand:(e,t,s,g,S,w,E)=>this.runCommand(e,t,s,g,S,w,E),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(e,t,s)=>this.executeUserScript(e,t,s)},O=await hi(D,e,t,s,g,S,w,E);return O===null?pi(D,e,t,g,w):O}aliasExpansionStack=new Set;expandAlias(e){return Bs(this.ctx.state,e,this.aliasExpansionStack)}async findCommandInPath(e){return ws(this.ctx,e)}async executeSubshell(e,t=``){return Ni(this.ctx,e,t,e=>this.executeStatement(e))}async executeGroup(e,t=``){return Oi(this.ctx,e,t,e=>this.executeStatement(e))}async executeArithmeticCommand(e){e.line!==void 0&&(this.ctx.state.currentLine=e.line);let t=await xe(this.ctx,e.redirections);if(t)return t;try{let t=Q(await R(this.ctx,e.expression.expression)!==0);return this.ctx.state.expansionStderr&&(t={...t,stderr:this.ctx.state.expansionStderr+t.stderr},this.ctx.state.expansionStderr=``),G(this.ctx,t,e.redirections)}catch(t){let s=A(`bash: arithmetic expression: ${t.message}
|
|
723
723
|
`);return G(this.ctx,s,e.redirections)}}async executeConditionalCommand(e){e.line!==void 0&&(this.ctx.state.currentLine=e.line);let t=await xe(this.ctx,e.redirections);if(t)return t;try{let t=Q(await He(this.ctx,e.expression));return this.ctx.state.expansionStderr&&(t={...t,stderr:this.ctx.state.expansionStderr+t.stderr},this.ctx.state.expansionStderr=``),G(this.ctx,t,e.redirections)}catch(t){let s=t instanceof p?1:2,g=A(`bash: conditional expression: ${t.message}
|
|
724
|
-
`,s);return G(this.ctx,g,e.redirections)}}},re={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxSubstitutionDepth:50,maxBraceExpansionResults:1e4,maxOutputSize:10485760,maxFileDescriptors:1024,maxSourceDepth:100};function
|
|
724
|
+
`,s);return G(this.ctx,g,e.redirections)}}},re={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxSubstitutionDepth:50,maxBraceExpansionResults:1e4,maxOutputSize:10485760,maxFileDescriptors:1024,maxSourceDepth:100};function Di(e){return e?{maxCallDepth:e.maxCallDepth??re.maxCallDepth,maxCommandCount:e.maxCommandCount??re.maxCommandCount,maxLoopIterations:e.maxLoopIterations??re.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??re.maxAwkIterations,maxSedIterations:e.maxSedIterations??re.maxSedIterations,maxJqIterations:e.maxJqIterations??re.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??re.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??re.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??re.maxJsTimeoutMs,maxGlobOperations:e.maxGlobOperations??re.maxGlobOperations,maxStringLength:e.maxStringLength??re.maxStringLength,maxArrayElements:e.maxArrayElements??re.maxArrayElements,maxHeredocSize:e.maxHeredocSize??re.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??re.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??re.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??re.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??re.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??re.maxSourceDepth}:{...re}}function Rr(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function Aa(e){let t=Rr(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function Ti(e){if(e.includes(`\\`))return!0;let t=e.toLowerCase();return t.includes(`%2f`)||t.includes(`%5c`)}function ka(e,t){return t===`/`||t===``?!0:t.endsWith(`/`)?e.startsWith(t):e===t||e.startsWith(`${t}/`)}function Ir(e,t){let s=Rr(e);if(!s)return!1;let g=Aa(t);return!g||s.origin!==g.origin||g.pathPrefix!==`/`&&g.pathPrefix!==``&&Ti(s.pathname)?!1:ka(s.pathname,g.pathPrefix)}function Ri(e){return typeof e==`string`?e:e.url}function Ii(e,t){return!t||t.length===0?!1:t.some(t=>Ir(e,Ri(t)))}function Lr(e){let t=_a(e);if(t===`localhost`||t.endsWith(`.localhost`))return!0;let s=Li(t);if(s)return bs(s);let g=Na(t);return g?Oa(g):!1}function _a(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function Ca(e){if(!e)return null;let t=10,s=e;if(s.startsWith(`0x`)||s.startsWith(`0X`)?(t=16,s=s.slice(2)):s.length>1&&s.startsWith(`0`)&&(t=8),!s||t===16&&!/^[0-9a-fA-F]+$/.test(s)||t===10&&!/^\d+$/.test(s)||t===8&&!/^[0-7]+$/.test(s))return null;let g=Number.parseInt(s,t);return!Number.isFinite(g)||g<0?null:g}function Li(e){let t=e.split(`.`);if(t.length===0||t.length>4)return null;let s=t.map(e=>Ca(e));if(s.some(e=>e===null))return null;let g=s;if(t.length===1){let e=g[0];return e>4294967295?null:[e>>>24&255,e>>>16&255,e>>>8&255,e&255]}if(t.length===2){let[e,t]=g;return e>255||t>16777215?null:[e,t>>>16&255,t>>>8&255,t&255]}if(t.length===3){let[e,t,s]=g;return e>255||t>255||s>65535?null:[e,t,s>>>8&255,s&255]}let[S,w,E,D]=g;return S>255||w>255||E>255||D>255?null:[S,w,E,D]}function Na(e){let t=e,s=null;if(t.includes(`.`)){let e=t.lastIndexOf(`:`);if(e<0)return null;let g=Li(t.slice(e+1));if(!g)return null;s=g,t=t.slice(0,e)}let g=t.includes(`::`)?t.split(`::`).length-1:0;if(g>1)return null;let[S,w]=t.split(`::`),E=S?S.split(`:`).filter(Boolean):[],D=w?w.split(`:`).filter(Boolean):[],O=e=>/^[0-9a-f]{1,4}$/i.test(e)?Number.parseInt(e,16):null,k=E.map(O),j=D.map(O);if(k.some(e=>e===null)||j.some(e=>e===null))return null;let F=s?2:0,L=k.length+j.length+F,B=0;if(g===1){if(B=8-L,B<0)return null}else if(L!==8)return null;let H=[...k,...Array(B).fill(0),...j];return s&&(H.push(s[0]<<8|s[1]),H.push(s[2]<<8|s[3])),H.length===8?H:null}function bs(e){let[t,s]=e;return t===127||t===10||t===172&&s>=16&&s<=31||t===192&&s===168||t===169&&s===254||t===0||t===100&&s>=64&&s<=127||t===198&&(s===18||s===19)||t===192&&s===0&&e[2]===0||t===192&&s===0&&e[2]===2||t===198&&s===51&&e[2]===100||t===203&&s===0&&e[2]===113||t>=240}function Oa(e){return e.every(e=>e===0)||e.slice(0,7).every(e=>e===0)&&e[7]===1||(e[0]&65472)==65152||(e[0]&65024)==64512?!0:e[0]===0&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===65535?bs([e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255]):e[0]===8193&&e[1]===3512?!0:e[0]===100&&e[1]===65435&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===0?bs([e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255]):e[0]===100&&e[1]===65435&&e[2]===1?!0:e[0]===8194?bs([e[1]>>>8&255,e[1]&255,e[2]>>>8&255,e[2]&255]):!1}function Fi(e){let t=[];for(let s of e){if(typeof s!=`string`&&(typeof s!=`object`||!s||!(`url`in s)||typeof s.url!=`string`)){t.push(`Invalid allow-list entry: must be a string URL or an object with a "url" string property`);continue}let e=Ri(s);if(!Rr(e)){t.push(`Invalid URL in allow-list: "${e}" - must be a valid URL with scheme and host (e.g., "https://example.com")`);continue}let g=new URL(e);if(g.protocol!==`http:`&&g.protocol!==`https:`){t.push(`Only http and https URLs are allowed in allow-list: "${e}"`);continue}if(!g.hostname){t.push(`Allow-list entry must include a hostname: "${e}"`);continue}if(g.pathname!==`/`&&g.pathname!==``&&Ti(g.pathname)){t.push(`Allow-list entry contains ambiguous path separators: "${e}"`);continue}(g.search||g.hash)&&t.push(`Query strings and fragments are ignored in allow-list entries: "${e}"`)}return t}var xa=typeof __BROWSER__<`u`&&__BROWSER__,pt=null,Es=null,Mi=!1;function Da(){if(pt===null&&!xa)try{let e=m$2(`node:async_hooks`);Es=m$2(`node:dns`),pt=new e.AsyncLocalStorage}catch{}}function Ta(){if(Mi||(Da(),!pt||!Es))return;Mi=!0;let e=pt,t=Es.lookup;function s(...s){let g=s[0],S=e.getStore();if(typeof g!=`string`||!S||S.hostname.toLowerCase()!==g.toLowerCase())return t.apply(this,s);let w={},E;if(s.length===2)E=s[1];else if(s.length>=3){let e=s[1];typeof e==`number`?w={family:e}:e&&typeof e==`object`&&(w=e),E=s[2]}if(typeof E!=`function`)return t.apply(this,s);let D=E;if(w.family!==void 0&&w.family!==0&&w.family!==S.family){let e=Error(`ENOTFOUND ${g}`);e.code=`ENOTFOUND`,e.errno=-3008,e.syscall=`getaddrinfo`,e.hostname=g,process.nextTick(()=>D(e));return}process.nextTick(()=>{w.all?D(null,[{address:S.address,family:S.family}]):D(null,S.address,S.family)})}Object.defineProperty(Es,`lookup`,{value:s,writable:!0,configurable:!0})}function Wi(e,t){return Ta(),pt?pt.run(e,t):t()}var Ae=class extends Error{constructor(e,t){super(`Network access denied: ${t??`URL not in allow-list`}: ${e}`),this.name=`NetworkAccessDeniedError`}},mt=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name=`TooManyRedirectsError`}},yt=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name=`RedirectNotAllowedError`}},$s=class extends Error{constructor(e,t){super(`HTTP method '${e}' not allowed. Allowed methods: ${t.join(`, `)}`),this.name=`MethodNotAllowedError`}},gt=class extends Error{constructor(e){super(`Response body too large (max: ${e} bytes)`),this.name=`ResponseTooLargeError`}};function Ia(e){return new Promise((t,s)=>{lookup(e,{all:!0},(e,g)=>{e?s(e):t(g)})})}var La=20,Fa=3e4,Ma=10485760,Wa=[`GET`,`HEAD`],za=new Set([`GET`,`HEAD`,`OPTIONS`]),Va=new Set([301,302,303,307,308]);function Fr(e){let t=e.allowedUrlPrefixes??[];if(!e.dangerouslyAllowFullInternetAccess){let e=Fi(t);if(e.length>0)throw Error(`Invalid network allow-list:
|
|
725
725
|
${e.join(`
|
|
726
|
-
`)}`)}let s=[];for(let e of t)typeof e==`object`&&e.transform&&e.transform.length>0&&s.push(e);function g(e){if(s.length===0)return null;let t=null;for(let g of s)if(
|
|
727
|
-
`)}function
|
|
728
|
-
${S}${s.delimiter}`}return e.operator===`<<<`?`${t}<<< ${ie(e.target)}`:e.operator===`&>`||e.operator===`&>>`?`${e.operator} ${ie(e.target)}`:`${t}${e.operator} ${ie(e.target)}`}function ke(e){return e.length===0?``:` ${e.map(
|
|
729
|
-
`)}function
|
|
726
|
+
`)}`)}let s=[];for(let e of t)typeof e==`object`&&e.transform&&e.transform.length>0&&s.push(e);function g(e){if(s.length===0)return null;let t=null;for(let g of s)if(Ir(e,g.url)&&g.transform){t||=new Headers;for(let e of g.transform)for(let[s,g]of Object.entries(e.headers))t.set(s,g)}return t}let S=e.maxRedirects??La,w=e.timeoutMs??Fa,E=e.maxResponseSize??Ma,D=e.dangerouslyAllowFullInternetAccess?[`GET`,`HEAD`,`POST`,`PUT`,`DELETE`,`PATCH`,`OPTIONS`]:e.allowedMethods??Wa,O=e.denyPrivateRanges??(typeof process<`u`&&process.env?.NODE_ENV===`production`),k=e._dnsResolve??Ia;async function j(s){if(!e.dangerouslyAllowFullInternetAccess&&!Ii(s,t))throw new Ae(s);if(O)try{let e=new URL(s);if(Lr(e.hostname))throw new Ae(s,`private/loopback IP address blocked`);let t=e.hostname;if(/[a-zA-Z]/.test(t))try{let e=await k(t);for(let{address:t}of e)if(Lr(t))throw new Ae(s,`hostname resolves to private/loopback IP address`);let g=e[0];if(g)return{hostname:t,address:g.address,family:g.family===6?6:4}}catch(e){if(e instanceof Ae)throw e;let t=e?.code;if(!(t===`ENOTFOUND`||t===`ENODATA`))throw new Ae(s,`DNS resolution failed for private IP check`)}}catch(e){if(e instanceof Ae)throw e}return null}function F(t){if(e.dangerouslyAllowFullInternetAccess)return;let s=t.toUpperCase();if(!D.includes(s))throw new $s(s,D)}async function L(e,t={}){let s=t.method?.toUpperCase()??`GET`,D=await j(e);F(s);let O=e,k=0,L=t.followRedirects??!0,B=t.timeoutMs===void 0?w:Math.min(t.timeoutMs,w);for(;;){let e=new AbortController,w=b$1(()=>e.abort(),B);try{let w=await _$1.runTrustedAsync(()=>{let S=g(O),w={method:s,headers:Ba(t.headers,S),signal:e.signal,redirect:`manual`};return t.body&&!za.has(s)&&(w.body=t.body),D?Wi(D,()=>fetch(O,w)):fetch(O,w)});if(Va.has(w.status)&&L){let e=w.headers.get(`location`);if(!e)return await zi(w,O,E);let t=new URL(e,O).href;try{D=await j(t)}catch{throw new yt(t)}if(k++,k>S)throw new mt(S);O=t;continue}return await zi(w,O,E)}finally{u$1(w)}}}return L}function Ba(e,t){if(!e&&!t)return;if(!t)return e;let s=(e instanceof Headers,new Headers(e));for(let[e,g]of t)s.set(e,g);return s}async function zi(e,t,s){let g=Object.create(null);if(e.headers.forEach((e,t)=>{g[t.toLowerCase()]=e}),s>0){let t=e.headers.get(`content-length`);if(t){let e=parseInt(t,10);if(!Number.isNaN(e)&&e>s)throw new gt(s)}}let S;if(s>0&&e.body){let t=e.body.getReader(),g=[],w=0;for(;;){let{done:e,value:S}=await t.read();if(e)break;if(S){if(w+=S.byteLength,w>s)throw t.cancel(),new gt(s);g.push(S)}}S=new Uint8Array(w);let E=0;for(let e of g)S.set(e,E),E+=e.byteLength}else{let t=await e.arrayBuffer();if(s>0&&t.byteLength>s)throw new gt(s);S=new Uint8Array(t)}return{status:e.status,statusText:e.statusText,headers:g,body:S,url:t}}function xt(e){return tt(e)}function tt(e){return e.statements.map(Vi).join(`
|
|
727
|
+
`)}function Vi(e){let t=[];for(let s=0;s<e.pipelines.length;s++)t.push(ja(e.pipelines[s])),s<e.operators.length&&t.push(e.operators[s]);let s=t.join(` `);return e.background&&(s+=` &`),s}function ja(e){let t=[];e.timed&&t.push(e.timePosix?`time -p`:`time`),e.negated&&t.push(`!`);let s=[];for(let t=0;t<e.commands.length;t++)if(s.push(Bi(e.commands[t])),t<e.commands.length-1){let g=e.pipeStderr?.[t];s.push(g?`|&`:`|`)}return(t.length>0?`${t.join(` `)} `:``)+s.join(` `)}function Bi(e){switch(e.type){case`SimpleCommand`:return Ua(e);case`If`:return Ja(e);case`For`:return el(e);case`CStyleFor`:return tl(e);case`While`:return sl(e);case`Until`:return rl(e);case`Case`:return nl(e);case`Subshell`:return ol(e);case`Group`:return al(e);case`ArithmeticCommand`:return ll(e);case`ConditionalCommand`:return cl(e);case`FunctionDef`:return ul(e);default:throw Error(`Unsupported command type: ${e.type}`)}}function Ua(e){let t=[];for(let s of e.assignments)t.push(Ha(s));e.name&&t.push(ie(e.name));for(let s of e.args)t.push(ie(s));for(let s of e.redirections)t.push(Hi(s));return t.join(` `)}function Ha(e){let t=e.append?`+=`:`=`;if(e.array){let s=e.array.map(ie).join(` `);return`${e.name}${t}(${s})`}return e.value?`${e.name}${t}${ie(e.value)}`:`${e.name}${t}`}function ie(e){return e.parts.map(e=>Ss(e,!1)).join(``)}function qe(e){return e.parts.map(e=>Ss(e,!0)).join(``)}function Ss(e,t){switch(e.type){case`Literal`:return t?qa(e.value):Za(e.value);case`SingleQuoted`:return`'${e.value}'`;case`DoubleQuoted`:return`"${e.parts.map(e=>Ss(e,!0)).join(``)}"`;case`Escaped`:return`\\${e.value}`;case`ParameterExpansion`:return ji(e);case`CommandSubstitution`:return e.legacy?`\`${tt(e.body)}\``:`$(${tt(e.body)})`;case`ArithmeticExpansion`:return`$((${Z(e.expression.expression)}))`;case`ProcessSubstitution`:return e.direction===`input`?`<(${tt(e.body)})`:`>(${tt(e.body)})`;case`BraceExpansion`:return Ya(e);case`TildeExpansion`:return e.user===null?`~`:`~${e.user}`;case`Glob`:return e.pattern;default:throw Error(`Unsupported word part type: ${e.type}`)}}function Za(e){return e.replace(/[\s\\'"`!|&;()<>{}[\]*?~#]/g,`\\$&`)}function qa(e){return e.replace(/[$`"\\]/g,`\\$&`)}function Ga(e,t){return e.parts.map(e=>Ka(e,t)).join(``)}function Ka(e,t){switch(e.type){case`Literal`:return t?e.value:e.value.replace(/[$`]/g,`\\$&`);case`Escaped`:return`\\${e.value}`;case`ParameterExpansion`:return ji(e);case`CommandSubstitution`:return e.legacy?`\`${tt(e.body)}\``:`$(${tt(e.body)})`;case`ArithmeticExpansion`:return`$((${Z(e.expression.expression)}))`;default:return Ss(e,!1)}}function ji(e){return e.operation?`\${${Ui(e.parameter,e.operation)}}`:Xa(e.parameter)?`\${${e.parameter}}`:`$${e.parameter}`}function Xa(e){return!(/^[?#@*$!\-0-9]$/.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))}function Ui(e,t){switch(t.type){case`Length`:return`#${e}`;case`LengthSliceError`:return`#${e}:`;case`BadSubstitution`:return t.text;case`DefaultValue`:return`${e}${t.checkEmpty?`:`:``}-${qe(t.word)}`;case`AssignDefault`:return`${e}${t.checkEmpty?`:`:``}=${qe(t.word)}`;case`ErrorIfUnset`:return`${e}${t.checkEmpty?`:`:``}?${t.word?qe(t.word):``}`;case`UseAlternative`:return`${e}${t.checkEmpty?`:`:``}+${qe(t.word)}`;case`Substring`:{let s=Z(t.offset.expression);return t.length?`${e}:${s}:${Z(t.length.expression)}`:`${e}:${s}`}case`PatternRemoval`:{let s=t.side===`prefix`?`#`:`%`;return`${e}${t.greedy?`${s}${s}`:s}${qe(t.pattern)}`}case`PatternReplacement`:{let s=`/`;t.all?s=`//`:t.anchor===`start`?s=`/#`:t.anchor===`end`&&(s=`/%`);let g=t.replacement?`/${qe(t.replacement)}`:``;return`${e}${s}${qe(t.pattern)}${g}`}case`CaseModification`:{let s=t.direction===`upper`?`^`:`,`;return`${e}${t.all?`${s}${s}`:s}${t.pattern?qe(t.pattern):``}`}case`Transform`:return`${e}@${t.operator}`;case`Indirection`:return t.innerOp?`!${Ui(e,t.innerOp)}`:`!${e}`;case`ArrayKeys`:return`!${t.array}[${t.star?`*`:`@`}]`;case`VarNamePrefix`:return`!${t.prefix}${t.star?`*`:`@`}`;default:throw Error(`Unsupported parameter operation type: ${t.type}`)}}function Ya(e){return`{${e.items.map(Qa).join(`,`)}}`}function Qa(e){if(e.type===`Word`)return ie(e.word);let t=e.startStr??String(e.start),s=e.endStr??String(e.end);return e.step===void 0?`${t}..${s}`:`${t}..${s}..${e.step}`}function Hi(e){let t=e.fdVariable?`{${e.fdVariable}}`:e.fd===null?``:String(e.fd);if(e.operator===`<<`||e.operator===`<<-`){let s=e.target,g=s.quoted?`'${s.delimiter}'`:s.delimiter,S=Ga(s.content,s.quoted);return`${t}${e.operator}${g}
|
|
728
|
+
${S}${s.delimiter}`}return e.operator===`<<<`?`${t}<<< ${ie(e.target)}`:e.operator===`&>`||e.operator===`&>>`?`${e.operator} ${ie(e.target)}`:`${t}${e.operator} ${ie(e.target)}`}function ke(e){return e.length===0?``:` ${e.map(Hi).join(` `)}`}function Ee(e){return e.map(Vi).join(`
|
|
729
|
+
`)}function Ja(e){let t=[];for(let s=0;s<e.clauses.length;s++){let g=e.clauses[s],S=s===0?`if`:`elif`;t.push(`${S} ${Ee(g.condition)}; then
|
|
730
730
|
${Ee(g.body)}`)}return e.elseBody&&t.push(`else
|
|
731
731
|
${Ee(e.elseBody)}`),`${t.join(`
|
|
732
732
|
`)}
|
|
733
|
-
fi${ke(e.redirections)}`}function
|
|
733
|
+
fi${ke(e.redirections)}`}function el(e){let t;if(e.words===null)t=`for ${e.variable}`;else{let s=e.words.map(ie).join(` `);t=`for ${e.variable} in ${s}`}return`${t}; do
|
|
734
734
|
${Ee(e.body)}
|
|
735
|
-
done${ke(e.redirections)}`}function
|
|
735
|
+
done${ke(e.redirections)}`}function tl(e){return`for ((${e.init?Z(e.init.expression):``}; ${e.condition?Z(e.condition.expression):``}; ${e.update?Z(e.update.expression):``})); do
|
|
736
736
|
${Ee(e.body)}
|
|
737
|
-
done${ke(e.redirections)}`}function
|
|
737
|
+
done${ke(e.redirections)}`}function sl(e){return`while ${Ee(e.condition)}; do
|
|
738
738
|
${Ee(e.body)}
|
|
739
|
-
done${ke(e.redirections)}`}function
|
|
739
|
+
done${ke(e.redirections)}`}function rl(e){return`until ${Ee(e.condition)}; do
|
|
740
740
|
${Ee(e.body)}
|
|
741
|
-
done${ke(e.redirections)}`}function
|
|
741
|
+
done${ke(e.redirections)}`}function nl(e){let t=e.items.map(il).join(`
|
|
742
742
|
`);return`case ${ie(e.word)} in
|
|
743
743
|
${t}
|
|
744
|
-
esac${ke(e.redirections)}`}function
|
|
744
|
+
esac${ke(e.redirections)}`}function il(e){let t=e.patterns.map(ie).join(` | `),s=Ee(e.body);return s?`${t})
|
|
745
745
|
${s}
|
|
746
746
|
${e.terminator}`:`${t})
|
|
747
|
-
${e.terminator}`}function
|
|
748
|
-
`],[`OSTYPE`,`linux-gnu`],[`MACHTYPE`,`x86_64-pc-linux-gnu`],[`HOSTTYPE`,`x86_64`],[`HOSTNAME`,`localhost`],[`PWD`,s],[`OLDPWD`,s],[`OPTIND`,`1`],...Object.entries(e.env??{})]);if(this.limits=
|
|
747
|
+
${e.terminator}`}function ol(e){return`(${Ee(e.body)})${ke(e.redirections)}`}function al(e){return`{ ${Ee(e.body)}; }${ke(e.redirections)}`}function ll(e){return`((${Z(e.expression.expression)}))${ke(e.redirections)}`}function cl(e){return`[[ ${et(e.expression)} ]]${ke(e.redirections)}`}function ul(e){let t=Bi(e.body);return`${e.name}() ${t}${ke(e.redirections)}`}function Z(e){switch(e.type){case`ArithNumber`:return String(e.value);case`ArithVariable`:return e.hasDollarPrefix?`$${e.name}`:e.name;case`ArithSpecialVar`:return`$${e.name}`;case`ArithBinary`:return`${Z(e.left)} ${e.operator} ${Z(e.right)}`;case`ArithUnary`:return e.prefix?`${e.operator}${Z(e.operand)}`:`${Z(e.operand)}${e.operator}`;case`ArithTernary`:return`${Z(e.condition)} ? ${Z(e.consequent)} : ${Z(e.alternate)}`;case`ArithAssignment`:return`${e.subscript?`${e.variable}[${Z(e.subscript)}]`:e.stringKey===void 0?e.variable:`${e.variable}[${e.stringKey}]`} ${e.operator} ${Z(e.value)}`;case`ArithDynamicAssignment`:return`${e.subscript?`${Z(e.target)}[${Z(e.subscript)}]`:Z(e.target)} ${e.operator} ${Z(e.value)}`;case`ArithDynamicElement`:return`${Z(e.nameExpr)}[${Z(e.subscript)}]`;case`ArithGroup`:return`(${Z(e.expression)})`;case`ArithNested`:return`$((${Z(e.expression)}))`;case`ArithCommandSubst`:return`$(${e.command})`;case`ArithBracedExpansion`:return`\${${e.content}}`;case`ArithArrayElement`:return e.stringKey===void 0?e.index?`${e.array}[${Z(e.index)}]`:e.array:`${e.array}[${e.stringKey}]`;case`ArithDynamicBase`:return`\${${e.baseExpr}}#${e.value}`;case`ArithDynamicNumber`:return`\${${e.prefix}}${e.suffix}`;case`ArithConcat`:return e.parts.map(Z).join(``);case`ArithDoubleSubscript`:return`${e.array}[${Z(e.index)}]`;case`ArithNumberSubscript`:return`${e.number}[${e.errorToken}]`;case`ArithSyntaxError`:return e.errorToken;case`ArithSingleQuote`:return`'${e.content}'`;default:throw Error(`Unsupported arithmetic expression type: ${e.type}`)}}function et(e){switch(e.type){case`CondBinary`:return`${ie(e.left)} ${e.operator} ${ie(e.right)}`;case`CondUnary`:return`${e.operator} ${ie(e.operand)}`;case`CondNot`:return`! ${et(e.operand)}`;case`CondAnd`:return`${et(e.left)} && ${et(e.right)}`;case`CondOr`:return`${et(e.left)} || ${et(e.right)}`;case`CondGroup`:return`( ${et(e.expression)} )`;case`CondWord`:return ie(e.word);default:throw Error(`Unsupported conditional expression type: ${e.type}`)}}var Dt=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;transformPlugins=[];state;constructor(e={}){let t=e.fs??new Le(e.files);this.fs=t,this.useDefaultLayout=!e.cwd&&!e.files;let s=e.cwd||(this.useDefaultLayout?`/home/user`:`/`),g=new Map([[`HOME`,this.useDefaultLayout?`/home/user`:`/`],[`PATH`,`/usr/bin:/bin`],[`IFS`,`
|
|
748
|
+
`],[`OSTYPE`,`linux-gnu`],[`MACHTYPE`,`x86_64-pc-linux-gnu`],[`HOSTTYPE`,`x86_64`],[`HOSTNAME`,`localhost`],[`PWD`,s],[`OLDPWD`,s],[`OPTIND`,`1`],...Object.entries(e.env??{})]);if(this.limits=Di({...e.executionLimits,...e.maxCallDepth!==void 0&&{maxCallDepth:e.maxCallDepth},...e.maxCommandCount!==void 0&&{maxCommandCount:e.maxCommandCount},...e.maxLoopIterations!==void 0&&{maxLoopIterations:e.maxLoopIterations}}),e.fetch?this.secureFetch=e.fetch:e.network&&(this.secureFetch=Fr(e.network)),this.sleepFn=e.sleep,this.traceFn=e.trace,this.logger=e.logger,this.defenseInDepthConfig=e.defenseInDepth??!0,this.coverageWriter=e.coverage,this.state={env:g,cwd:s,previousDir:`/home/user`,functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:``,startTime:Date.now(),lastBackgroundPid:0,virtualPid:e.processInfo?.pid??1,virtualPpid:e.processInfo?.ppid??0,virtualUid:e.processInfo?.uid??1e3,virtualGid:e.processInfo?.gid??1e3,bashPid:e.processInfo?.pid??1,nextVirtualPid:(e.processInfo?.pid??1)+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set([`HOME`,`PATH`,`PWD`,`OLDPWD`,...Object.keys(e.env||{})]),readonlyVars:new Set([`SHELLOPTS`,`BASHOPTS`]),hashTable:new Map},this.state.env.set(`SHELLOPTS`,Ws(this.state.options)),this.state.env.set(`BASHOPTS`,zs(this.state.shoptOptions)),hn(t,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),s!==`/`&&t instanceof Le)try{t.mkdirSync(s,{recursive:!0})}catch{}for(let t of an(e.commands))this.registerCommand(t);if(e.fetch||e.network)for(let e of ln())this.registerCommand(e);if(e.python)for(let e of cn())this.registerCommand(e);if(e.javascript){for(let e of un())this.registerCommand(e);let t=typeof e.javascript==`object`?e.javascript:Object.create(null);t.bootstrap&&(this.jsBootstrapCode=t.bootstrap)}if(e.customCommands)for(let t of e.customCommands)fn(t)?this.registerCommand(dn(t)):this.registerCommand({...t,trusted:t.trusted??!0})}registerCommand(e){this.commands.set(e.name,e);let t=this.fs;if(typeof t.writeFileSync==`function`){let s=`#!/bin/bash
|
|
749
749
|
# Built-in command: ${e.name}
|
|
750
|
-
`;try{t.writeFileSync(`/bin/${e.name}`,s)}catch{}try{t.writeFileSync(`/usr/bin/${e.name}`,s)}catch{}}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug(`stdout`,{output:e.stdout}),e.stderr&&this.logger.info(`stderr`,{output:e.stderr}),this.logger.info(`exit`,{exitCode:e.exitCode})),e.stdout=
|
|
751
|
-
`,exitCode:1,env:n(this.state.env,t?.env)};if(!e.trim())return{stdout:``,stderr:``,exitCode:0,env:n(this.state.env,t?.env)};this.logger?.info(`exec`,{command:e});let s=t?.cwd??this.state.cwd,g,S=s;if(t?.cwd)if(t.env&&`PWD`in t.env)g=t.env.PWD;else if(t?.env&&!(`PWD`in t.env))try{g=await this.fs.realpath(s),S=g}catch{g=s}else g=s;let w=t?.replaceEnv?new Map:new Map(this.state.env);if(t?.env)for(let[e,s]of Object.entries(t.env))w.set(e,s);g!==void 0&&w.set(`PWD`,g);let E={...this.state,env:w,cwd:S,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:t?.stdin,signal:t?.signal,extraArgs:t?.args},D=e;t?.rawScript||(D=
|
|
750
|
+
`;try{t.writeFileSync(`/bin/${e.name}`,s)}catch{}try{t.writeFileSync(`/usr/bin/${e.name}`,s)}catch{}}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug(`stdout`,{output:e.stdout}),e.stderr&&this.logger.info(`stderr`,{output:e.stderr}),this.logger.info(`exit`,{exitCode:e.exitCode})),e.stdout=qi(e.stdout),e.stderr=qi(e.stderr),e}async exec(e,t){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:``,stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
|
|
751
|
+
`,exitCode:1,env:n(this.state.env,t?.env)};if(!e.trim())return{stdout:``,stderr:``,exitCode:0,env:n(this.state.env,t?.env)};this.logger?.info(`exec`,{command:e});let s=t?.cwd??this.state.cwd,g,S=s;if(t?.cwd)if(t.env&&`PWD`in t.env)g=t.env.PWD;else if(t?.env&&!(`PWD`in t.env))try{g=await this.fs.realpath(s),S=g}catch{g=s}else g=s;let w=t?.replaceEnv?new Map:new Map(this.state.env);if(t?.env)for(let[e,s]of Object.entries(t.env))w.set(e,s);g!==void 0&&w.set(`PWD`,g);let E={...this.state,env:w,cwd:S,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:t?.stdin,signal:t?.signal,extraArgs:t?.args},D=e;t?.rawScript||(D=Zi(e));let O=this.defenseInDepthConfig?_$1.getInstance(this.defenseInDepthConfig):null,k=O?.activate();try{let e=async()=>{let e=di$1(D,{maxHeredocSize:this.limits.maxHeredocSize}),t;if(this.transformPlugins.length>0){let s=Object.create(null);for(let t of this.transformPlugins){let g=t.transform({ast:e,metadata:s});e=g.ast,g.metadata&&(s=c$2(s,g.metadata))}t=s}let s=await new Ot({fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:O?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode},E).executeScript(e);return t&&(s.metadata=t),this.logResult(s)};return k?await k.run(e):await e()}catch(e){if(e instanceof d||e instanceof C)return this.logResult({stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,env:n(this.state.env,t?.env)});if(e instanceof p)return this.logResult({stdout:e.stdout,stderr:e.stderr,exitCode:1,env:n(this.state.env,t?.env)});if(e instanceof $$1)return this.logResult({stdout:e.stdout,stderr:e.stderr,exitCode:124,env:n(this.state.env,t?.env)});if(e instanceof b)return this.logResult({stdout:e.stdout,stderr:n$1(e.stderr),exitCode:b.EXIT_CODE,env:n(this.state.env,t?.env)});if(e instanceof d$2)return this.logResult({stdout:``,stderr:`bash: security violation: ${n$1(e.message)}
|
|
752
752
|
`,exitCode:1,env:n(this.state.env,t?.env)});if(e.name===`ParseException`)return this.logResult({stdout:``,stderr:`bash: syntax error: ${n$1(e.message)}
|
|
753
753
|
`,exitCode:2,env:n(this.state.env,t?.env)});if(e instanceof pe)return this.logResult({stdout:``,stderr:`bash: ${n$1(e.message)}
|
|
754
754
|
`,exitCode:2,env:n(this.state.env,t?.env)});if(e instanceof RangeError)return this.logResult({stdout:``,stderr:`bash: ${n$1(e.message)}
|
|
755
|
-
`,exitCode:1,env:n(this.state.env,t?.env)});throw e}finally{k?.deactivate()}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,t){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),t)}getCwd(){return this.state.cwd}getEnv(){return r(this.state.env)}registerTransformPlugin(e){this.transformPlugins.push(e)}transform(e){let t=di$1(
|
|
755
|
+
`,exitCode:1,env:n(this.state.env,t?.env)});throw e}finally{k?.deactivate()}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,t){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),t)}getCwd(){return this.state.cwd}getEnv(){return r(this.state.env)}registerTransformPlugin(e){this.transformPlugins.push(e)}transform(e){let t=di$1(Zi(e),{maxHeredocSize:this.limits.maxHeredocSize}),s=Object.create(null);for(let e of this.transformPlugins){let g=e.transform({ast:t,metadata:s});t=g.ast,g.metadata&&(s=c$2(s,g.metadata))}return{script:xt(t),ast:t,metadata:s}}};function Zi(e){let t=e.split(`
|
|
756
756
|
`),s=[],g=[];for(let e=0;e<t.length;e++){let S=t[e];if(g.length>0){let e=g[g.length-1];if((e.stripTabs?S.replace(/^\t+/,``):S)===e.delimiter){s.push(S.trimStart()),g.pop();continue}s.push(S);continue}let w=S.trimStart();s.push(w);for(let e of w.matchAll(/<<(-?)\s*(['"]?)([\w-]+)\2/g)){let t=e[1]===`-`,s=e[3];g.push({delimiter:s,stripTabs:t})}}return s.join(`
|
|
757
|
-
`)}var rl=new TextDecoder(`utf-8`,{fatal:!0});function Bi(e){if(!e)return e;let t=!1;for(let s=0;s<e.length;s++){let g=e.charCodeAt(s);if(g>255)return e;g>127&&(t=!0)}if(!t)return e;let s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);try{return rl.decode(s)}catch{return e}}var ol=[`EACCES`,`escaping sandbox`,`EFBIG`],Ss=class{root;canonicalRoot;maxFileReadSize;allowSymlinks;constructor(e){this.root=U.resolve(e.root),this.maxFileReadSize=e.maxFileReadSize??10485760,this.allowSymlinks=e.allowSymlinks??!1,$$2(this.root,`ReadWriteFs`),this.canonicalRoot=I.realpathSync(this.root)}resolveAndValidate(e,t){let s=this.allowSymlinks?f$1(e,this.canonicalRoot):P$1(e,this.root,this.canonicalRoot);if(s===null)throw Error(`EACCES: permission denied, '${t}' resolves outside sandbox`);return s}validateParent(e,t){let s=U.dirname(e),g=this.resolveAndValidate(s,t);return U.join(g,U.basename(e))}toRealPath(e){let t=c$1(e),s=U.join(this.root,t);return U.resolve(s)}async readFile(e,t){return h$2(await this.readFileBuffer(e),l$1(t))}async readFileBuffer(e){h$1(e,`open`);let t=this.toRealPath(e),s=this.resolveAndValidate(t,e);try{let t=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,g=await I.promises.open(s,t);try{if(this.maxFileReadSize>0){let t=await g.stat();if(t.size>this.maxFileReadSize)throw Error(`EFBIG: file too large, read '${e}' (${t.size} bytes, max ${this.maxFileReadSize})`)}let t=await g.readFile();return new Uint8Array(t)}finally{await g.close()}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(s.code===`EISDIR`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(s.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`open`)}}async writeFile(e,t,s){h$1(e,`write`);let g=this.toRealPath(e),S=this.resolveAndValidate(g,e),w=o(t,l$1(s)),E=U.dirname(S);try{await I.promises.mkdir(E,{recursive:!0}),S=this.resolveAndValidate(g,e);let t=this.allowSymlinks?0:I.constants.O_NOFOLLOW,s=I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_TRUNC|t,D=await I.promises.open(S,s,438);try{await D.writeFile(w)}finally{await D.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`write`)}}async appendFile(e,t,s){h$1(e,`append`);let g=this.toRealPath(e),S=this.resolveAndValidate(g,e),w=o(t,l$1(s)),E=U.dirname(S);try{await I.promises.mkdir(E,{recursive:!0}),S=this.resolveAndValidate(g,e);let t=this.allowSymlinks?0:I.constants.O_NOFOLLOW,s=I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_APPEND|t,D=await I.promises.open(S,s,438);try{await D.writeFile(w)}finally{await D.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`append`)}}async exists(e){if(e.includes(`\0`))return!1;let t=this.toRealPath(e);try{let s=this.resolveAndValidate(t,e);return await I.promises.access(s),!0}catch{return!1}}async stat(e){h$1(e,`stat`);let t=this.toRealPath(e),s=this.resolveAndValidate(t,e);try{let t=await I.promises.lstat(s);if(!this.allowSymlinks&&t.isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return{isFile:t.isFile(),isDirectory:t.isDirectory(),isSymbolicLink:t.isSymbolicLink(),mode:t.mode,size:t.size,mtime:t.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, stat '${e}'`);this.sanitizeError(t,e,`stat`)}}async lstat(e){h$1(e,`lstat`);let t=this.toRealPath(e),s=this.validateParent(t,e);try{let e=await I.promises.lstat(s);return{isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink(),mode:e.mode,size:e.size,mtime:e.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);this.sanitizeError(t,e,`lstat`)}}async mkdir(e,t){h$1(e,`mkdir`);let s=this.toRealPath(e),g=this.resolveAndValidate(s,e);try{await I.promises.mkdir(g,{recursive:t?.recursive})}catch(t){let s=t;if(s.code===`EEXIST`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.sanitizeError(t,e,`mkdir`)}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){h$1(e,`scandir`);let t=this.toRealPath(e),s=this.resolveAndValidate(t,e);try{if(!this.allowSymlinks&&(await I.promises.lstat(s)).isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return(await I.promises.readdir(s,{withFileTypes:!0})).map(e=>({name:e.name,isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink()})).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(s.code===`ENOTDIR`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);this.sanitizeError(t,e,`scandir`)}}async rm(e,t){h$1(e,`rm`);let s=this.toRealPath(e),g=this.resolveAndValidate(s,e);try{await I.promises.rm(g,{recursive:t?.recursive??!1,force:t?.force??!1})}catch(s){let g=s;if(g.code===`ENOENT`&&!t?.force)throw Error(`ENOENT: no such file or directory, rm '${e}'`);if(g.code===`ENOTEMPTY`)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);this.sanitizeError(s,e,`rm`)}}async cp(e,t,s){h$1(e,`cp`),h$1(t,`cp`);let g=this.toRealPath(e),S=this.toRealPath(t),w=this.resolveAndValidate(g,e),E=this.resolveAndValidate(S,t);try{await I.promises.cp(w,E,{recursive:s?.recursive??!1,filter:async e=>{try{if(I.lstatSync(e).isSymbolicLink()){let t=await I.promises.realpath(e).catch(()=>null);return t===null?!1:d$1(t,this.canonicalRoot)}return!0}catch(e){return e.code===`ENOENT`}}})}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(s.code===`EISDIR`)throw Error(`EISDIR: is a directory, cp '${e}'`);this.sanitizeError(t,e,`cp`)}}async mv(e,t){h$1(e,`mv`),h$1(t,`mv`);let s=this.toRealPath(e),g=this.toRealPath(t),S=this.validateParent(s,e),w=this.validateParent(g,t);try{if((await I.promises.lstat(S)).isSymbolicLink()){let s=await I.promises.readlink(S),g=U.resolve(U.dirname(w),s);if(!d$1(await I.promises.realpath(g).catch(()=>g),this.canonicalRoot))throw Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlink escaping sandbox`)}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(s.message?.includes(`EACCES`)||s.message?.includes(`escaping sandbox`))throw t}let E=U.dirname(w);try{await I.promises.mkdir(E,{recursive:!0})}catch(e){this.sanitizeError(e,t,`mv`)}try{await I.promises.rename(S,w)}catch(s){let g=s;if(g.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(g.code===`EXDEV`){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0});return}this.sanitizeError(s,e,`mv`)}try{if(I.lstatSync(w).isDirectory()&&this.findEscapingSymlinks(w).length>0)throw await I.promises.rename(w,S),Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlinks escaping sandbox`)}catch(e){if(e.message?.includes(`EACCES`)||e.message?.includes(`escaping sandbox`))throw e}}resolvePath(e,t){return y(e,t)}getAllPaths(){let e=[];return this.scanDir(`/`,e),e}sanitizeError(e,t,s){N(e,t,s,ol)}findEscapingSymlinks(e){let t=[];try{let s=I.readdirSync(e);for(let g of s){let s=U.join(e,g);try{let g=I.lstatSync(s);if(g.isSymbolicLink()){let g=I.readlinkSync(s),S=U.resolve(e,g),w;try{w=I.realpathSync(S)}catch{w=S}d$1(w,this.canonicalRoot)||t.push(s)}else g.isDirectory()&&t.push(...this.findEscapingSymlinks(s))}catch{}}}catch{}return t}scanDir(e,t){let s=this.toRealPath(e),g;try{g=this.resolveAndValidate(s,e)}catch{return}try{let s=I.readdirSync(g);for(let S of s){let s=e===`/`?`/${S}`:`${e}/${S}`;t.push(s);let w=U.join(g,S);I.lstatSync(w).isDirectory()&&this.scanDir(s,t)}}catch{}}async chmod(e,t){h$1(e,`chmod`);let s=this.toRealPath(e),g=this.resolveAndValidate(s,e);try{let e=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,s=await I.promises.open(g,e);try{await s.chmod(t)}finally{await s.close()}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);if(s.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`chmod`)}}async symlink(e,t){if(!this.allowSymlinks)throw Error(`EPERM: operation not permitted, symlink '${t}'`);h$1(t,`symlink`);let s=this.toRealPath(t),g=this.validateParent(s,t),S=c$1(t),w=c$1(U.dirname(S)),E=e.startsWith(`/`)?c$1(e):c$1(w===`/`?`/${e}`:`${w}/${e}`),D=U.join(this.canonicalRoot,E),O=U.dirname(g),k=e.startsWith(`/`)?D:U.relative(O,D)||`.`;try{await I.promises.symlink(k,g)}catch(e){if(e.code===`EEXIST`)throw Error(`EEXIST: file already exists, symlink '${t}'`);this.sanitizeError(e,t,`symlink`)}}async link(e,t){h$1(e,`link`),h$1(t,`link`);let s=this.toRealPath(e),g=this.toRealPath(t),S=this.resolveAndValidate(s,e),w=this.resolveAndValidate(g,t);try{await I.promises.link(S,w)}catch(s){let g=s;if(g.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(g.code===`EEXIST`)throw Error(`EEXIST: file already exists, link '${t}'`);if(g.code===`EPERM`)throw Error(`EPERM: operation not permitted, link '${e}'`);this.sanitizeError(s,e,`link`)}}async readlink(e){h$1(e,`readlink`);let t=this.toRealPath(e),s=this.validateParent(t,e);try{let t=await I.promises.readlink(s),g=c$1(e),S=U.dirname(g),w=U.isAbsolute(t)?t:U.resolve(U.dirname(s),t),E=await I.promises.realpath(w).catch(()=>w);if(d$1(E,this.canonicalRoot)){let e=E.slice(this.canonicalRoot.length)||`/`;return S===`/`?e.startsWith(`/`)?e.slice(1)||`.`:e:U.relative(S,e)}return U.basename(t)}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(s.code===`EINVAL`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);this.sanitizeError(t,e,`readlink`)}}async realpath(e){h$1(e,`realpath`);let t=this.toRealPath(e);try{this.resolveAndValidate(t,e)}catch{throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}let s;try{s=await I.promises.realpath(t)}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, realpath '${e}'`);if(s.code===`ELOOP`)throw Error(`ELOOP: too many levels of symbolic links, realpath '${e}'`);this.sanitizeError(t,e,`realpath`)}if(d$1(s,this.canonicalRoot))return s.slice(this.canonicalRoot.length)||`/`;throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}async utimes(e,t,s){h$1(e,`utimes`);let g=this.toRealPath(e),S=this.resolveAndValidate(g,e);try{let e=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,g=await I.promises.open(S,e);try{await g.utimes(t,s)}finally{await g.close()}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);if(s.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`utimes`)}}},require_quote=__commonJSMin$2(((e,t)=>{t.exports=function(e){return e.map(function(e){return e===``?`''`:e&&typeof e==`object`?e.op.replace(/(.)/g,`\\$1`):/["\s\\]/.test(e)&&!/'/.test(e)?`'`+e.replace(/(['])/g,`\\$1`)+`'`:/["'\s]/.test(e)?`"`+e.replace(/(["\\$`!])/g,`\\$1`)+`"`:String(e).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,`$1\\$2`)}).join(` `)}})),require_parse=__commonJSMin$2(((e,t)=>{for(var s=`(?:`+[`\\|\\|`,`\\&\\&`,`;;`,`\\|\\&`,`\\<\\(`,`\\<\\<\\<`,`>>`,`>\\&`,`<\\&`,`[&;()|<>]`].join(`|`)+`)`,g=RegExp(`^`+s+`$`),S=`|&;()<> \\t`,w=`"((\\\\"|[^"])*?)"`,E=`'((\\\\'|[^'])*?)'`,D=/^#$/,O=`'`,k=`"`,j=`$`,F=``,L=4294967296,B=0;B<4;B++)F+=(L*Math.random()).toString(16);var H=RegExp(`^`+F);function q(e,t){for(var s=t.lastIndex,g=[],S;S=t.exec(e);)g.push(S),t.lastIndex===S.index&&(t.lastIndex+=1);return t.lastIndex=s,g}function ee(e,t,s){var g=typeof e==`function`?e(s):e[s];return g===void 0&&s!=``?g=``:g===void 0&&(g=`$`),typeof g==`object`?t+F+JSON.stringify(g)+F:t+g}function J(e,t,F){F||={};var L=F.escape||`\\`,B=`(\\`+L+`['"`+S+`]|[^\\s'"`+S+`])+`,H=q(e,new RegExp([`(`+s+`)`,`(`+B+`|`+w+`|`+E+`)+`].join(`|`),`g`));if(H.length===0)return[];t||={};var J=!1;return H.map(function(s){var S=s[0];if(!S||J)return;if(g.test(S))return{op:S};var w=!1,E=!1,F=``,B=!1,H;function q(){H+=1;var e,s,g=S.charAt(H);if(g===`{`){if(H+=1,S.charAt(H)===`}`)throw Error(`Bad substitution: `+S.slice(H-2,H+1));if(e=S.indexOf(`}`,H),e<0)throw Error(`Bad substitution: `+S.slice(H));s=S.slice(H,e),H=e}else if(/[*@#?$!_-]/.test(g))s=g,H+=1;else{var w=S.slice(H);e=w.match(/[^\w\d_]/),e?(s=w.slice(0,e.index),H+=e.index-1):(s=w,H=S.length)}return ee(t,``,s)}for(H=0;H<S.length;H++){var Y=S.charAt(H);if(B||=!w&&(Y===`*`||Y===`?`),E)F+=Y,E=!1;else if(w)Y===w?w=!1:w==O?F+=Y:Y===L?(H+=1,Y=S.charAt(H),Y===k||Y===L||Y===j?F+=Y:F+=L+Y):Y===j?F+=q():F+=Y;else if(Y===k||Y===O)w=Y;else if(g.test(Y))return{op:S};else if(D.test(Y)){J=!0;var te={comment:e.slice(s.index+H+1)};return F.length?[F,te]:[te]}else Y===L?E=!0:Y===j?F+=q():F+=Y}return B?{op:`glob`,pattern:F}:F}).reduce(function(e,t){return t===void 0?e:e.concat(t)},[])}t.exports=function(e,t,s){var g=J(e,t,s);return typeof t==`function`?g.reduce(function(e,t){if(typeof t==`object`)return e.concat(t);var s=t.split(RegExp(`(`+F+`.*?`+F+`)`,`g`));return s.length===1?e.concat(s[0]):e.concat(s.filter(Boolean).map(function(e){return H.test(e)?JSON.parse(e.split(F)[1]):e}))},[]):g}})),require_shell_quote=__commonJSMin$2((e=>{e.quote=require_quote(),e.parse=require_parse()}));const floor$1=Math.floor,min$1=(e,t)=>e<t?e:t,max$1=(e,t)=>e>t?e:t;Number.isNaN;const BIT8$1=128,BIT18$1=1<<17,BIT19$1=1<<18,BIT20$1=1<<19,BIT21$1=1<<20,BIT22$1=1<<21,BIT23$1=1<<22,BIT24$1=1<<23,BIT25$1=1<<24,BIT26$1=1<<25,BIT27$1=1<<26,BIT28$1=1<<27,BIT29$1=1<<28,BIT30$1=1<<29,BIT31$1=1<<30,BITS7$1=127;BIT18$1-1,BIT19$1-1,BIT20$1-1,BIT21$1-1,BIT22$1-1,BIT23$1-1,BIT24$1-1,BIT25$1-1,BIT26$1-1,BIT27$1-1,BIT28$1-1,BIT29$1-1,BIT30$1-1,BIT31$1-1;const MAX_SAFE_INTEGER$1=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const fromCharCode$1=String.fromCharCode;String.fromCodePoint,fromCharCode$1(65535);const _encodeUtf8Polyfill$1=e=>{let t=unescape(encodeURIComponent(e)),s=t.length,g=new Uint8Array(s);for(let e=0;e<s;e++)g[e]=t.codePointAt(e);return g},utf8TextEncoder$1=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native$1=e=>utf8TextEncoder$1.encode(e),encodeUtf8$1=utf8TextEncoder$1?_encodeUtf8Native$1:_encodeUtf8Polyfill$1;let utf8TextDecoder$1=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder$1&&utf8TextDecoder$1.decode(new Uint8Array).length===1&&(utf8TextDecoder$1=null);const write$1=(e,t)=>{let s=e.cbuf.length;e.cpos===s&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(s*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeVarUint$1=(e,t)=>{for(;t>BITS7$1;)write$1(e,BIT8$1|BITS7$1&t),t=floor$1(t/128);write$1(e,BITS7$1&t)},_strBuffer$1=new Uint8Array(3e4),_maxStrBSize$1=_strBuffer$1.length/3,_writeVarStringNative$1=(e,t)=>{if(t.length<_maxStrBSize$1){let s=utf8TextEncoder$1.encodeInto(t,_strBuffer$1).written||0;writeVarUint$1(e,s);for(let t=0;t<s;t++)write$1(e,_strBuffer$1[t])}else writeVarUint8Array$1(e,encodeUtf8$1(t))},_writeVarStringPolyfill$1=(e,t)=>{let s=unescape(encodeURIComponent(t)),g=s.length;writeVarUint$1(e,g);for(let t=0;t<g;t++)write$1(e,s.codePointAt(t))},writeVarString$1=utf8TextEncoder$1&&utf8TextEncoder$1.encodeInto?_writeVarStringNative$1:_writeVarStringPolyfill$1,writeUint8Array$1=(e,t)=>{let s=e.cbuf.length,g=e.cpos,S=min$1(s-g,t.length),w=t.length-S;e.cbuf.set(t.subarray(0,S),g),e.cpos+=S,w>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max$1(s*2,w)),e.cbuf.set(t.subarray(S)),e.cpos=w)},writeVarUint8Array$1=(e,t)=>{writeVarUint$1(e,t.byteLength),writeUint8Array$1(e,t)},create$3=e=>Error(e),errorUnexpectedEndOfArray$1=create$3(`Unexpected end of array`),errorIntegerOutOfRange$1=create$3(`Integer out of Range`);let AuthMessageType=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const writePermissionDenied=(e,t)=>{writeVarUint$1(e,AuthMessageType.PermissionDenied),writeVarString$1(e,t)},writeAuthenticated=(e,t)=>{writeVarUint$1(e,AuthMessageType.Authenticated),writeVarString$1(e,t)},writeTokenSyncRequest=e=>{writeVarUint$1(e,AuthMessageType.Token)},ResetConnection={code:4205,reason:`Reset Connection`},Unauthorized={code:4401,reason:`Unauthorized`},Forbidden={code:4403,reason:`Forbidden`},ConnectionTimeout={code:4408,reason:`Connection Timeout`},awarenessStatesToArray=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var SkipFurtherHooksError=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let WsReadyStates=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});const E_CANCELED=Error(`request for lock canceled`);var __awaiter$2=function(e,t,s,g){function S(e){return e instanceof s?e:new s(function(t){t(e)})}return new(s||=Promise)(function(s,w){function E(e){try{O(g.next(e))}catch(e){w(e)}}function D(e){try{O(g.throw(e))}catch(e){w(e)}}function O(e){e.done?s(e.value):S(e.value).then(E,D)}O((g=g.apply(e,t||[])).next())})},Semaphore=class{constructor(e,t=E_CANCELED){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((s,g)=>{let S={resolve:s,reject:g,weight:e,priority:t},w=findIndexFromEnd(this._queue,e=>t<=e.priority);w===-1&&e<=this._value?this._dispatchItem(S):this._queue.splice(w+1,0,S)})}runExclusive(e){return __awaiter$2(this,arguments,void 0,function*(e,t=1,s=0){let[g,S]=yield this.acquire(t,s);try{return yield e(g)}finally{S()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(s=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),insertSorted(this._weightedWaiters[e-1],{resolve:s,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let s=this._weightedWaiters[t-1];if(!s)continue;let g=s.findIndex(t=>t.priority<=e);(g===-1?s:s.splice(0,g)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function insertSorted(e,t){let s=findIndexFromEnd(e,e=>t.priority<=e.priority);e.splice(s+1,0,t)}function findIndexFromEnd(e,t){for(let s=e.length-1;s>=0;s--)if(t(e[s]))return s;return-1}var __awaiter$1=function(e,t,s,g){function S(e){return e instanceof s?e:new s(function(t){t(e)})}return new(s||=Promise)(function(s,w){function E(e){try{O(g.next(e))}catch(e){w(e)}}function D(e){try{O(g.throw(e))}catch(e){w(e)}}function O(e){e.done?s(e.value):S(e.value).then(E,D)}O((g=g.apply(e,t||[])).next())})},Mutex=class{constructor(e){this._semaphore=new Semaphore(1,e)}acquire(){return __awaiter$1(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};let FORCE_COLOR,NODE_DISABLE_COLORS,NO_COLOR,TERM,isTTY=!0;typeof process<`u`&&({FORCE_COLOR,NODE_DISABLE_COLORS,NO_COLOR,TERM}=process.env||{},isTTY=process.stdout&&process.stdout.isTTY);const $={enabled:!NODE_DISABLE_COLORS&&NO_COLOR==null&&TERM!==`dumb`&&(FORCE_COLOR!=null&&FORCE_COLOR!==`0`||isTTY),reset:init(0,0),bold:init(1,22),dim:init(2,22),italic:init(3,23),underline:init(4,24),inverse:init(7,27),hidden:init(8,28),strikethrough:init(9,29),black:init(30,39),red:init(31,39),green:init(32,39),yellow:init(33,39),blue:init(34,39),magenta:init(35,39),cyan:init(36,39),white:init(37,39),gray:init(90,39),grey:init(90,39),bgBlack:init(40,49),bgRed:init(41,49),bgGreen:init(42,49),bgYellow:init(43,49),bgBlue:init(44,49),bgMagenta:init(45,49),bgCyan:init(46,49),bgWhite:init(47,49)};function run(e,t){let s=0,g,S=``,w=``;for(;s<e.length;s++)g=e[s],S+=g.open,w+=g.close,~t.indexOf(g.close)&&(t=t.replace(g.rgx,g.close+g.open));return S+t+w}function chain(e,t){let s={has:e,keys:t};return s.reset=$.reset.bind(s),s.bold=$.bold.bind(s),s.dim=$.dim.bind(s),s.italic=$.italic.bind(s),s.underline=$.underline.bind(s),s.inverse=$.inverse.bind(s),s.hidden=$.hidden.bind(s),s.strikethrough=$.strikethrough.bind(s),s.black=$.black.bind(s),s.red=$.red.bind(s),s.green=$.green.bind(s),s.yellow=$.yellow.bind(s),s.blue=$.blue.bind(s),s.magenta=$.magenta.bind(s),s.cyan=$.cyan.bind(s),s.white=$.white.bind(s),s.gray=$.gray.bind(s),s.grey=$.grey.bind(s),s.bgBlack=$.bgBlack.bind(s),s.bgRed=$.bgRed.bind(s),s.bgGreen=$.bgGreen.bind(s),s.bgYellow=$.bgYellow.bind(s),s.bgBlue=$.bgBlue.bind(s),s.bgMagenta=$.bgMagenta.bind(s),s.bgCyan=$.bgCyan.bind(s),s.bgWhite=$.bgWhite.bind(s),s}function init(e,t){let s={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(s)),t===void 0?this:$.enabled?run(this.keys,t+``):t+``):t===void 0?chain([e],[s]):$.enabled?run([s],t+``):t+``}}const BIT8=128,BIT18=1<<17,BIT19=1<<18,BIT20=1<<19,BIT21=1<<20,BIT22=1<<21,BIT23=1<<22,BIT24=1<<23,BIT25=1<<24,BIT26=1<<25,BIT27=1<<26,BIT28=1<<27,BIT29=1<<28,BIT30=1<<29,BIT31=1<<30,BITS7=127;BIT18-1,BIT19-1,BIT20-1,BIT21-1,BIT22-1,BIT23-1,BIT24-1,BIT25-1,BIT26-1,BIT27-1,BIT28-1,BIT29-1,BIT30-1,BIT31-1;const floor=Math.floor,min=(e,t)=>e<t?e:t,max=(e,t)=>e>t?e:t;Number.isNaN;const MAX_SAFE_INTEGER=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const create$2=()=>new Set,from=Array.from;Array.isArray;const fromCharCode=String.fromCharCode;String.fromCodePoint,fromCharCode(65535);const _encodeUtf8Polyfill=e=>{let t=unescape(encodeURIComponent(e)),s=t.length,g=new Uint8Array(s);for(let e=0;e<s;e++)g[e]=t.codePointAt(e);return g},utf8TextEncoder=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native=e=>utf8TextEncoder.encode(e),encodeUtf8=utf8TextEncoder?_encodeUtf8Native:_encodeUtf8Polyfill;let utf8TextDecoder=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder&&utf8TextDecoder.decode(new Uint8Array).length===1&&(utf8TextDecoder=null);const create$1=e=>Error(e);var Encoder=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const createEncoder=()=>new Encoder,length=e=>{let t=e.cpos;for(let s=0;s<e.bufs.length;s++)t+=e.bufs[s].length;return t},toUint8Array=e=>{let t=new Uint8Array(length(e)),s=0;for(let g=0;g<e.bufs.length;g++){let S=e.bufs[g];t.set(S,s),s+=S.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),s),t},write=(e,t)=>{let s=e.cbuf.length;e.cpos===s&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(s*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeVarUint=(e,t)=>{for(;t>BITS7;)write(e,BIT8|BITS7&t),t=floor(t/128);write(e,BITS7&t)},_strBuffer=new Uint8Array(3e4),_maxStrBSize=_strBuffer.length/3,_writeVarStringNative=(e,t)=>{if(t.length<_maxStrBSize){let s=utf8TextEncoder.encodeInto(t,_strBuffer).written||0;writeVarUint(e,s);for(let t=0;t<s;t++)write(e,_strBuffer[t])}else writeVarUint8Array(e,encodeUtf8(t))},_writeVarStringPolyfill=(e,t)=>{let s=unescape(encodeURIComponent(t)),g=s.length;writeVarUint(e,g);for(let t=0;t<g;t++)write(e,s.codePointAt(t))},writeVarString=utf8TextEncoder&&utf8TextEncoder.encodeInto?_writeVarStringNative:_writeVarStringPolyfill,writeUint8Array=(e,t)=>{let s=e.cbuf.length,g=e.cpos,S=min(s-g,t.length),w=t.length-S;e.cbuf.set(t.subarray(0,S),g),e.cpos+=S,w>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max(s*2,w)),e.cbuf.set(t.subarray(S)),e.cpos=w)},writeVarUint8Array=(e,t)=>{writeVarUint(e,t.byteLength),writeUint8Array(e,t)},errorUnexpectedEndOfArray=create$1(`Unexpected end of array`),errorIntegerOutOfRange=create$1(`Integer out of Range`);var Decoder=class{constructor(e){this.arr=e,this.pos=0}};const createDecoder=e=>new Decoder(e),hasContent=e=>e.pos!==e.arr.length,readUint8Array=(e,t)=>{let s=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,s},readVarUint8Array=e=>readUint8Array(e,readVarUint(e)),readUint8=e=>e.arr[e.pos++],readVarUint=e=>{let t=0,s=1,g=e.arr.length;for(;e.pos<g;){let g=e.arr[e.pos++];if(t+=(g&BITS7)*s,s*=128,g<BIT8)return t;if(t>MAX_SAFE_INTEGER)throw errorIntegerOutOfRange}throw errorUnexpectedEndOfArray},_readVarStringPolyfill=e=>{let t=readVarUint(e);if(t===0)return``;{let s=String.fromCodePoint(readUint8(e));if(--t<100)for(;t--;)s+=String.fromCodePoint(readUint8(e));else for(;t>0;){let g=t<1e4?t:1e4,S=e.arr.subarray(e.pos,e.pos+g);e.pos+=g,s+=String.fromCodePoint.apply(null,S),t-=g}return decodeURIComponent(escape(s))}},_readVarStringNative=e=>utf8TextDecoder.decode(readVarUint8Array(e)),readVarString=utf8TextDecoder?_readVarStringNative:_readVarStringPolyfill;var IncomingMessage=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=createDecoder(e)}get encoder(){return this.encoderInternal||=createEncoder(),this.encoderInternal}readVarUint8Array(){return readVarUint8Array(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=readVarUint8Array(this.decoder);return this.decoder.pos=e,t}readVarUint(){return readVarUint(this.decoder)}readVarString(){return readVarString(this.decoder)}toUint8Array(){return toUint8Array(this.encoder)}writeVarUint(e){writeVarUint(this.encoder,e)}writeVarString(e){writeVarString(this.encoder,e)}get length(){return length(this.encoder)}};const getUnixTime=Date.now,create=()=>new Map,setIfUndefined=(e,t,s)=>{let g=e.get(t);return g===void 0&&e.set(t,g=s()),g};var Observable=class{constructor(){this._observers=create()}on(e,t){setIfUndefined(this._observers,e,create$2).add(t)}once(e,t){let s=(...g)=>{this.off(e,s),t(...g)};this.on(e,s)}off(e,t){let s=this._observers.get(e);s!==void 0&&(s.delete(t),s.size===0&&this._observers.delete(e))}emit(e,t){return from((this._observers.get(e)||create()).values()).forEach(e=>e(...t))}destroy(){this._observers=create()}};const EqualityTraitSymbol=Symbol(`Equality`),keys=Object.keys,size=e=>keys(e).length,hasProperty=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),equalityDeep=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[EqualityTraitSymbol]!=null)return e[EqualityTraitSymbol](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let s=0;s<e.length;s++)if(e[s]!==t[s])return!1;break;case Set:if(e.size!==t.size)return!1;for(let s of e)if(!t.has(s))return!1;break;case Map:if(e.size!==t.size)return!1;for(let s of e.keys())if(!t.has(s)||!equalityDeep(e.get(s),t.get(s)))return!1;break;case void 0:case Object:if(size(e)!==size(t))return!1;for(let s in e)if(!hasProperty(e,s)||!equalityDeep(e[s],t[s]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!equalityDeep(e[s],t[s]))return!1;break;default:return!1}return!0},outdatedTimeout=3e4;var Awareness=class extends Observable{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=getUnixTime();this.getLocalState()!==null&&outdatedTimeout/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((s,g)=>{g!==this.clientID&&outdatedTimeout<=e-s.lastUpdated&&this.states.has(g)&&t.push(g)}),t.length>0&&removeAwarenessStates(this,t,`timeout`)},floor(outdatedTimeout/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,s=this.meta.get(t),g=s===void 0?0:s.clock+1,S=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:g,lastUpdated:getUnixTime()});let w=[],E=[],D=[],O=[];e===null?O.push(t):S==null?e!=null&&w.push(t):(E.push(t),equalityDeep(S,e)||D.push(t)),(w.length>0||D.length>0||O.length>0)&&this.emit(`change`,[{added:w,updated:D,removed:O},`local`]),this.emit(`update`,[{added:w,updated:E,removed:O},`local`])}setLocalStateField(e,t){let s=this.getLocalState();s!==null&&this.setLocalState({...s,[e]:t})}getStates(){return this.states}};const removeAwarenessStates=(e,t,s)=>{let g=[];for(let s=0;s<t.length;s++){let S=t[s];if(e.states.has(S)){if(e.states.delete(S),S===e.clientID){let t=e.meta.get(S);e.meta.set(S,{clock:t.clock+1,lastUpdated:getUnixTime()})}g.push(S)}}g.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:g},s]),e.emit(`update`,[{added:[],updated:[],removed:g},s]))},encodeAwarenessUpdate=(e,t,s=e.states)=>{let g=t.length,S=createEncoder();writeVarUint(S,g);for(let w=0;w<g;w++){let g=t[w],E=s.get(g)||null,D=e.meta.get(g).clock;writeVarUint(S,g),writeVarUint(S,D),writeVarString(S,JSON.stringify(E))}return toUint8Array(S)},applyAwarenessUpdate=(e,t,s)=>{let g=createDecoder(t),S=getUnixTime(),w=[],E=[],D=[],O=[],k=readVarUint(g);for(let t=0;t<k;t++){let t=readVarUint(g),s=readVarUint(g),k=JSON.parse(readVarString(g)),j=e.meta.get(t),F=e.states.get(t),L=j===void 0?0:j.clock;(L<s||L===s&&k===null&&e.states.has(t))&&(k===null?t===e.clientID&&e.getLocalState()!=null?s++:e.states.delete(t):e.states.set(t,k),e.meta.set(t,{clock:s,lastUpdated:S}),j===void 0&&k!==null?w.push(t):j!==void 0&&k===null?O.push(t):k!==null&&(equalityDeep(k,F)||D.push(t),E.push(t)))}(w.length>0||D.length>0||O.length>0)&&e.emit(`change`,[{added:w,updated:D,removed:O},s]),(w.length>0||E.length>0||O.length>0)&&e.emit(`update`,[{added:w,updated:E,removed:O},s])},messageYjsSyncStep1=0,messageYjsSyncStep2=1,messageYjsUpdate=2,writeSyncStep1=(e,t)=>{writeVarUint(e,messageYjsSyncStep1),writeVarUint8Array(e,encodeStateVector(t))},writeSyncStep2=(e,t,s)=>{writeVarUint(e,messageYjsSyncStep2),writeVarUint8Array(e,encodeStateAsUpdate(t,s))},readSyncStep1=(e,t,s)=>writeSyncStep2(t,s,readVarUint8Array(e)),readSyncStep2=(e,t,s,g)=>{try{applyUpdate(t,readVarUint8Array(e),s)}catch(e){g?.(e),console.error(`Caught error while handling a Yjs update`,e)}},writeUpdate=(e,t)=>{writeVarUint(e,messageYjsUpdate),writeVarUint8Array(e,t)},readUpdate=readSyncStep2;function isTransactionOrigin(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function shouldSkipStoreHooks(e){if(!isTransactionOrigin(e))return!1;switch(e.source){case`connection`:return!1;case`redis`:return!0;case`local`:return e.skipStoreHooks??!1}}let MessageType=function(e){return e[e.Unknown=-1]=`Unknown`,e[e.Sync=0]=`Sync`,e[e.Awareness=1]=`Awareness`,e[e.Auth=2]=`Auth`,e[e.QueryAwareness=3]=`QueryAwareness`,e[e.SyncReply=4]=`SyncReply`,e[e.Stateless=5]=`Stateless`,e[e.BroadcastStateless=6]=`BroadcastStateless`,e[e.CLOSE=7]=`CLOSE`,e[e.SyncStatus=8]=`SyncStatus`,e[e.Ping=9]=`Ping`,e[e.Pong=10]=`Pong`,e}({});var OutgoingMessage=class{constructor(e){this.encoder=createEncoder(),writeVarString(this.encoder,e)}createSyncMessage(){return this.type=MessageType.Sync,writeVarUint(this.encoder,MessageType.Sync),this}createSyncReplyMessage(){return this.type=MessageType.SyncReply,writeVarUint(this.encoder,MessageType.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=MessageType.Awareness,this.category=`Update`;let s=encodeAwarenessUpdate(e,t||Array.from(e.getStates().keys()));return writeVarUint(this.encoder,MessageType.Awareness),writeVarUint8Array(this.encoder,s),this}writeQueryAwareness(){return this.type=MessageType.QueryAwareness,this.category=`Update`,writeVarUint(this.encoder,MessageType.QueryAwareness),this}writeTokenSyncRequest(){return this.type=MessageType.Auth,this.category=`TokenSync`,writeVarUint(this.encoder,MessageType.Auth),writeTokenSyncRequest(this.encoder),this}writeAuthenticated(e){return this.type=MessageType.Auth,this.category=`Authenticated`,writeVarUint(this.encoder,MessageType.Auth),writeAuthenticated(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=MessageType.Auth,this.category=`PermissionDenied`,writeVarUint(this.encoder,MessageType.Auth),writePermissionDenied(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,writeSyncStep1(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,writeUpdate(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,writeVarUint(this.encoder,MessageType.Stateless),writeVarString(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,writeVarUint(this.encoder,MessageType.BroadcastStateless),writeVarString(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,writeVarUint(this.encoder,MessageType.SyncStatus),writeVarUint(this.encoder,e?1:0),this}writeCloseMessage(e){return this.type=MessageType.CLOSE,writeVarUint(this.encoder,MessageType.CLOSE),writeVarString(this.encoder,e),this}toUint8Array(){return toUint8Array(this.encoder)}},MessageReceiver=class{constructor(e,t){this.message=e,this.defaultTransactionOrigin=t}async apply(e,t,s){let{message:g}=this,S=g.readVarUint(),w=g.length;switch(S){case MessageType.Sync:case MessageType.SyncReply:g.writeVarUint(MessageType.Sync),await this.readSyncMessage(g,e,t,s,S!==MessageType.SyncReply),g.length>w+1&&(s?s(g.toUint8Array()):t&&t.send(g.toUint8Array()));break;case MessageType.Awareness:applyAwarenessUpdate(e.awareness,g.readVarUint8Array(),t??null);break;case MessageType.QueryAwareness:this.applyQueryAwarenessMessage(e,t,s);break;case MessageType.Stateless:t?.callbacks.statelessCallback({connection:t,documentName:e.name,document:e,payload:readVarString(g.decoder)});break;case MessageType.BroadcastStateless:{let t=g.readVarString();e.getConnections().forEach(e=>{e.sendStateless(t)});break}case MessageType.CLOSE:t?.close({code:1e3,reason:`provider_initiated`});break;case MessageType.Auth:if(g.readVarUint()===AuthMessageType.Token){t?.callbacks.onTokenSyncCallback({token:g.readVarString()});break}console.error(`Received an authentication message on a connection that is already fully authenticated. Probably your provider has been destroyed + recreated really fast.`);break;default:console.error(`Unable to handle message of type ${S}: no handler defined! Are your provider/server versions aligned?`)}}async readSyncMessage(e,t,s,g,S=!0){let w=e.readVarUint(),E=s?.messageAddress??t.name;switch(s&&await s.callbacks.beforeSync(s,{type:w,payload:e.peekVarUint8Array()}),w){case messageYjsSyncStep1:if(readSyncStep1(e.decoder,e.encoder,t),g&&S)g(new OutgoingMessage(E).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(s){let e=new OutgoingMessage(E).createSyncMessage().writeFirstSyncStepFor(t);s.send(e.toUint8Array())}break;case messageYjsSyncStep2:if(s?.readOnly){if(snapshotContainsUpdate(snapshot(t),readVarUint8Array(e.decoder))){let e=new OutgoingMessage(E).writeSyncStatus(!0);s.send(e.toUint8Array())}else{let e=new OutgoingMessage(E).writeSyncStatus(!1);s.send(e.toUint8Array())}break}readSyncStep2(e.decoder,t,s?{source:`connection`,connection:s}:this.defaultTransactionOrigin??{source:`local`}),s&&s.send(new OutgoingMessage(E).writeSyncStatus(!0).toUint8Array());break;case messageYjsUpdate:if(s?.readOnly){s.send(new OutgoingMessage(E).writeSyncStatus(!1).toUint8Array());break}readUpdate(e.decoder,t,s?{source:`connection`,connection:s}:this.defaultTransactionOrigin??{source:`local`}),s&&s.send(new OutgoingMessage(E).writeSyncStatus(!0).toUint8Array());break;default:throw Error(`Received a message with an unknown type: ${w}`)}return w}applyQueryAwarenessMessage(e,t,s){let g=new OutgoingMessage(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);s&&s(g.toUint8Array())}},Connection=class{get messageAddress(){return this.sessionId?`${this.document.name}\0${this.sessionId}`:this.document.name}constructor(e,t,s,g,S,w=!1,E,D){this.callbacks={onClose:[(e,t)=>{}],beforeHandleMessage:(e,t)=>Promise.resolve(),beforeSync:(e,t)=>Promise.resolve(),statelessCallback:e=>Promise.resolve(),onTokenSyncCallback:e=>Promise.resolve()},this.messageQueue=[],this.processingPromise=Promise.resolve(),this.webSocket=e,this.context=S,this.document=s,this.request=t,this.socketId=g,this.readOnly=w,this.sessionId=E??null,this.providerVersion=D??null,this.document.addConnection(this),this.sendCurrentAwareness()}onClose(e){return this.callbacks.onClose.push(e),this}onStatelessCallback(e){return this.callbacks.statelessCallback=e,this}beforeHandleMessage(e){return this.callbacks.beforeHandleMessage=e,this}beforeSync(e){return this.callbacks.beforeSync=e,this}onTokenSyncCallback(e){return this.callbacks.onTokenSyncCallback=e,this}waitForPendingMessages(){return this.processingPromise}send(e){if(this.webSocket.readyState===WsReadyStates.Closing||this.webSocket.readyState===WsReadyStates.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new OutgoingMessage(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new OutgoingMessage(this.messageAddress).writeTokenSyncRequest();this.send(e.toUint8Array())}close(e){if(this.document.hasConnection(this)){this.document.removeConnection(this),this.callbacks.onClose.forEach(t=>t(this.document,e));let t=new OutgoingMessage(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new OutgoingMessage(this.messageAddress).createAwarenessUpdateMessage(this.document.awareness);this.send(e.toUint8Array())}handleMessage(e){this.messageQueue.push(e),this.messageQueue.length===1&&(this.processingPromise=this.processMessages())}async processMessages(){for(;this.messageQueue.length>0;){let e=this.messageQueue.at(0),t=new IncomingMessage(e),s=t.readVarString(),g=s.indexOf(`\0`),S=g===-1?s:s.substring(0,g);if(S!==this.document.name){this.messageQueue.shift();continue}t.writeVarString(this.messageAddress);try{await this.callbacks.beforeHandleMessage(this,e),await new MessageReceiver(t).apply(this.document,this)}catch(e){console.error(`closing connection ${this.socketId} (while handling ${S}) because of exception`,e),this.close({code:`code`in e&&typeof e.code==`number`?e.code:ResetConnection.code,reason:`reason`in e?e.reason:ResetConnection.reason})}this.messageQueue.shift()}}},Document=class extends Doc{constructor(e,t){super(t),this.callbacks={onUpdate:(e,t,s)=>{},beforeBroadcastStateless:(e,t)=>{}},this.connections=new Map,this.directConnectionsCount=0,this.isDestroyed=!1,this.saveMutex=new Mutex,this.lastChangeTime=0,this.name=e,this.awareness=new Awareness(this),this.awareness.setLocalState(null),this.awareness.on(`update`,this.handleAwarenessUpdate.bind(this)),this.on(`update`,this.handleUpdate.bind(this)),this.isLoading=!0}isEmpty(e){return!this.get(e)._start&&!this.get(e)._map.size}merge(e){return(Array.isArray(e)?e:[e]).forEach(e=>{applyUpdate(this,encodeStateAsUpdate(e))}),this}onUpdate(e){return this.callbacks.onUpdate=e,this}beforeBroadcastStateless(e){return this.callbacks.beforeBroadcastStateless=e,this}addConnection(e){return this.connections.set(e,{clients:new Set}),this}hasConnection(e){return this.connections.has(e)}removeConnection(e){let t=this.connections.get(e);return t&&removeAwarenessStates(this.awareness,Array.from(t.clients),null),this.connections.delete(e),this}addDirectConnection(){return this.directConnectionsCount+=1,this}removeDirectConnection(){return this.directConnectionsCount>0&&--this.directConnectionsCount,this}getConnectionsCount(){return this.connections.size+this.directConnectionsCount}getConnections(){return Array.from(this.connections.keys())}getClients(e){let t=this.connections.get(e);return t?.clients===void 0?new Set:t.clients}hasAwarenessStates(){return this.awareness.getStates().size>0}applyAwarenessUpdate(e,t){return applyAwarenessUpdate(this.awareness,t,e),this}handleAwarenessUpdate({added:e,updated:t,removed:s},g){let S=e.concat(t,s);if(g!==null){let t=this.connections.get(g);t&&(e.forEach(e=>t.clients.add(e)),s.forEach(e=>t.clients.delete(e)))}for(let e of this.getConnections()){let t=new OutgoingMessage(e.messageAddress).createAwarenessUpdateMessage(this.awareness,S);e.send(t.toUint8Array())}return this}handleUpdate(e,t){this.callbacks.onUpdate(this,t,e);for(let t of this.getConnections()){let s=new OutgoingMessage(t.messageAddress).createSyncMessage().writeUpdate(e);t.send(s.toUint8Array())}return this}broadcastStateless(e,t){this.callbacks.beforeBroadcastStateless(this,e),(t?this.getConnections().filter(t):this.getConnections()).forEach(t=>{t.sendStateless(e)})}destroy(){super.destroy(),this.isDestroyed=!0}},version=`4.0.0-rc.1`;function getParameters(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var ClientConnection=class{constructor(e,t,s,g,S,w={}){this.websocket=e,this.request=t,this.documentProvider=s,this.hooks=g,this.opts=S,this.defaultContext=w,this.documentConnections={},this.incomingMessageQueue={},this.documentConnectionsEstablished=new Set,this.hookPayloads={},this.callbacks={onClose:[(e,t)=>{}]},this.socketId=crypto$1.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(ConnectionTimeout)},this.setUpNewConnection=async(e,t,s)=>{let g=this.hookPayloads[e],S=await this.documentProvider.createDocument(t,g.request,g.socketId,g.connectionConfig,g.context),w=this.createConnection(this.websocket,S,g,s,g.providerVersion);if(w.onClose((t,s)=>{delete this.hookPayloads[e],delete this.documentConnections[e],delete this.incomingMessageQueue[e],this.documentConnectionsEstablished.delete(e)}),w.onTokenSyncCallback(async e=>{try{return await this.hooks(`onTokenSync`,{...g,...e,document:S,connection:w,documentName:t},e=>{g.context={...g.context,...e}})}catch(e){console.error(e);let t={...Unauthorized,...e};w.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=w,this.websocket.readyState===WsReadyStates.Closing||this.websocket.readyState===WsReadyStates.Closed){this.close();return}this.incomingMessageQueue[e]?.forEach(e=>{w.handleMessage(e)}),await this.hooks(`connected`,{...g,documentName:t,context:g.context,connection:w})},this.handleQueueingMessage=async(e,t,s)=>{try{let g=new IncomingMessage(e);if(readVarString(g.decoder),!(readVarUint(g.decoder)===MessageType.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),readVarUint(g.decoder);let S=readVarString(g.decoder),w=null;hasContent(g.decoder)&&(w=readVarString(g.decoder));let E=t.indexOf(`\0`),D=E===-1?null:t.substring(E+1),O=t;try{let e=this.hookPayloads[t];e.providerVersion=w,await this.hooks(`onConnect`,{...e,documentName:s},t=>{e.context={...e.context,...t}}),await this.hooks(`onAuthenticate`,{token:S,...e,documentName:s},t=>{e.context={...e.context,...t}}),e.connectionConfig.isAuthenticated=!0;let g=new OutgoingMessage(O).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(g.toUint8Array()),await this.setUpNewConnection(t,s,D)}catch(e){let s=e||Forbidden,g=new OutgoingMessage(O).writePermissionDenied(s.reason??`permission-denied`);this.websocket.send(g.toUint8Array()),this.documentConnectionsEstablished.delete(t),delete this.hookPayloads[t],delete this.incomingMessageQueue[t]}}catch(e){console.error(e),this.websocket.close(ResetConnection.code,ResetConnection.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=readVarString(new IncomingMessage(e).decoder),s=t.indexOf(`\0`),g=s===-1?t:t.substring(0,s),S=this.documentConnections[t]??this.documentConnections[g];if(S){S.handleMessage(e);return}if(this.incomingMessageQueue[t]===void 0){if(this.incomingMessageQueue[t]=[],this.hookPayloads[t])throw Error(`first message, but hookPayloads exists`);this.hookPayloads[t]={instance:this.documentProvider,request:this.request,connectionConfig:{readOnly:!1,isAuthenticated:!1},requestHeaders:this.request.headers,requestParameters:getParameters(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,g)}catch(e){console.error(e),this.websocket.close(Unauthorized.code,Unauthorized.reason)}},this.timeout=S.timeout,this.pingInterval=setInterval(this.check,this.timeout)}handleClose(e){this.close(e),clearInterval(this.pingInterval)}close(e){Object.values(this.documentConnections).forEach(t=>t.close(e))}onClose(e){return this.callbacks.onClose.push(e),this}createConnection(e,t,s,g,S){let w=new Connection(e,s.request,t,s.socketId,s.context,s.connectionConfig.readOnly,g,S);return w.onClose(async(e,t)=>{await w.waitForPendingMessages();let g={instance:this.documentProvider,clientsCount:e.getConnectionsCount(),context:s.context,document:e,socketId:s.socketId,documentName:e.name,requestHeaders:s.request.headers,requestParameters:getParameters(s.request)};await this.hooks(`onDisconnect`,g),this.callbacks.onClose.forEach(t=>t(e,g))}),w.onStatelessCallback(async e=>{try{return await this.hooks(`onStateless`,e)}catch(e){if(e?.message)throw e}}),w.beforeHandleMessage((e,g)=>{let S={instance:this.documentProvider,clientsCount:t.getConnectionsCount(),context:s.context,document:t,socketId:s.socketId,connection:e,documentName:t.name,requestHeaders:s.request.headers,requestParameters:getParameters(s.request),update:g};return this.hooks(`beforeHandleMessage`,S)}),w.beforeSync((e,g)=>{let S={clientsCount:t.getConnectionsCount(),context:s.context,document:t,documentName:t.name,connection:e,type:g.type,payload:g.payload};return this.hooks(`beforeSync`,S)}),w}},DirectConnection=class{constructor(e,t,s){this.document=null,this.document=e,this.instance=t,this.context=s??{},this.document.addDirectConnection()}async transact(e){if(!this.document)throw Error(`direct connection closed`);this.document.transact(t=>{e(this.document)},{source:`local`,context:this.context})}async disconnect(){this.document&&=(this.document?.removeDirectConnection(),await this.instance.storeDocumentHooks(this.document,{clientsCount:this.document.getConnectionsCount(),lastContext:this.context,lastTransactionOrigin:{source:`local`,context:this.context},document:this.document,documentName:this.document.name,instance:this.instance},!0),this.document.getConnectionsCount()===0&&!this.document.saveMutex.isLocked()&&(await this.instance.hooks(`onDisconnect`,{instance:this.instance,clientsCount:this.document.getConnectionsCount(),context:this.context,document:this.document,socketId:`server`,documentName:this.document.name,requestHeaders:new Headers,requestParameters:new URLSearchParams$1}),await this.instance.unloadDocument(this.document)),null)}};const useDebounce=()=>{let e=new Map,t=new Map;return{debounce:async(s,g,S,w)=>{let E=e.get(s),D=E?.start||Date.now(),O=async()=>{t.has(s)&&await t.get(s),e.delete(s);let S=g();t.set(s,S);let w=await S;return t.delete(s),w};if(E?.timeout&&clearTimeout(E.timeout),S===0||Date.now()-D>=w)return O();e.set(s,{start:D,timeout:setTimeout(O,S),func:O})},isDebounced:t=>e.has(t),isCurrentlyExecuting:e=>t.has(e),executeNow:t=>{let s=e.get(t);if(s)return clearTimeout(s.timeout),s.func()}}},defaultConfiguration={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var Hocuspocus=class{constructor(e){this.configuration={...defaultConfiguration,extensions:[],onConfigure:()=>new Promise(e=>e(null)),onListen:()=>new Promise(e=>e(null)),onUpgrade:()=>new Promise(e=>e(null)),onConnect:()=>new Promise(e=>e(null)),connected:()=>new Promise(e=>e(null)),beforeHandleMessage:()=>new Promise(e=>e(null)),beforeSync:()=>new Promise(e=>e(null)),beforeBroadcastStateless:()=>new Promise(e=>e(null)),onStateless:()=>new Promise(e=>e(null)),onChange:()=>new Promise(e=>e(null)),onCreateDocument:()=>new Promise(e=>e(null)),onLoadDocument:()=>new Promise(e=>e(null)),onStoreDocument:()=>new Promise(e=>e(null)),afterStoreDocument:()=>new Promise(e=>e(null)),onAwarenessUpdate:()=>new Promise(e=>e(null)),onRequest:()=>new Promise(e=>e(null)),onDisconnect:()=>new Promise(e=>e(null)),onDestroy:()=>new Promise(e=>e(null))},this.loadingDocuments=new Map,this.unloadingDocuments=new Map,this.documents=new Map,this.debouncer=useDebounce(),e&&this.configure(e)}configure(e){return this.configuration={...this.configuration,...e},this.configuration.extensions.sort((e,t)=>{let s=e.priority===void 0?100:e.priority,g=t.priority===void 0?100:t.priority;return s>g?-1:s<g?1:0}),this.configuration.extensions.push({onConfigure:this.configuration.onConfigure,onListen:this.configuration.onListen,onUpgrade:this.configuration.onUpgrade,onConnect:this.configuration.onConnect,connected:this.configuration.connected,onAuthenticate:this.configuration.onAuthenticate,onTokenSync:this.configuration.onTokenSync,onLoadDocument:this.configuration.onLoadDocument,afterLoadDocument:this.configuration.afterLoadDocument,beforeHandleMessage:this.configuration.beforeHandleMessage,beforeBroadcastStateless:this.configuration.beforeBroadcastStateless,beforeSync:this.configuration.beforeSync,onStateless:this.configuration.onStateless,onChange:this.configuration.onChange,onStoreDocument:this.configuration.onStoreDocument,afterStoreDocument:this.configuration.afterStoreDocument,onAwarenessUpdate:this.configuration.onAwarenessUpdate,onRequest:this.configuration.onRequest,beforeUnloadDocument:this.configuration.beforeUnloadDocument,afterUnloadDocument:this.configuration.afterUnloadDocument,onDisconnect:this.configuration.onDisconnect,onDestroy:this.configuration.onDestroy}),this.hooks(`onConfigure`,{configuration:this.configuration,version,instance:this}),this}getDocumentsCount(){return this.documents.size}getConnectionsCount(){let e=new Set,t=Array.from(this.documents.values()).reduce((t,s)=>(s.getConnections().forEach(({socketId:t})=>{e.add(t)}),t+s.directConnectionsCount),0);return e.size+t}flushPendingStores(){this.documents.forEach(e=>{let t=`onStoreDocument-${e.name}`;!e.isLoading&&this.debouncer.isDebounced(t)&&this.debouncer.executeNow(t)})}closeConnections(e){this.documents.forEach(t=>{e&&t.name!==e||t.connections.forEach((e,t)=>{t.close(ResetConnection)})})}handleConnection(e,t,s={}){let g=new ClientConnection(e,t,this,this.hooks.bind(this),{timeout:this.configuration.timeout},s);return g.onClose((e,t)=>{e.getConnectionsCount()>0||(!e.isLoading&&this.debouncer.isDebounced(`onStoreDocument-${e.name}`)?this.configuration.unloadImmediately&&this.debouncer.executeNow(`onStoreDocument-${e.name}`):this.unloadDocument(e))}),g}handleDocumentUpdate(e,t,s){let g=isTransactionOrigin(t)&&t.source===`connection`?t.connection:void 0,S=g?.request,w=isTransactionOrigin(t)?t.source===`connection`?t.connection.context:t.source===`local`?t.context??{}:{}:{},E={instance:this,clientsCount:e.getConnectionsCount(),document:e,documentName:e.name,requestHeaders:S?.headers??new Headers,requestParameters:getParameters(S),socketId:g?.socketId??``,update:s,transactionOrigin:t,connection:g,context:w};if(this.hooks(`onChange`,E),shouldSkipStoreHooks(t))return;let D={instance:this,clientsCount:e.getConnectionsCount(),document:e,lastContext:w,lastTransactionOrigin:t,documentName:e.name};this.storeDocumentHooks(e,D)}async createDocument(e,t,s,g,S){if(!e.trim())throw Error(`Document name must not be empty`);let w=this.loadingDocuments.get(e);if(w)return w;let E=this.documents.get(e);if(E)return Promise.resolve(E);let D=this.loadDocument(e,t,s,g,S);this.loadingDocuments.set(e,D);try{let t=await D;return this.documents.set(e,t),this.loadingDocuments.delete(e),t}catch(t){throw this.loadingDocuments.delete(e),t}}async loadDocument(e,t,s,g,S){let w=t.headers,E=getParameters(t),D=S??{},O=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:w,requestParameters:E,connectionConfig:g,context:D,socketId:s,instance:this}),k=new Document(e,{...this.configuration.yDocOptions,...O}),j={instance:this,context:D,connectionConfig:g,document:k,documentName:e,socketId:s,requestHeaders:w,requestParameters:E};try{await this.hooks(`onLoadDocument`,j,e=>{e instanceof Doc?applyUpdate(k,encodeStateAsUpdate(e)):e instanceof Uint8Array&&applyUpdate(k,e)})}catch(t){throw this.closeConnections(e),this.unloadDocument(k),t}return k.isLoading=!1,k.onUpdate((e,t,s)=>{e.lastChangeTime=Date.now(),this.handleDocumentUpdate(e,t,s)}),await this.hooks(`afterLoadDocument`,j),k.beforeBroadcastStateless((e,t)=>{let s={document:e,documentName:e.name,payload:t};this.hooks(`beforeBroadcastStateless`,s)}),k.awareness.on(`update`,(t,s)=>{this.hooks(`onAwarenessUpdate`,{document:k,documentName:e,instance:this,...t,transactionOrigin:s,connection:isTransactionOrigin(s)&&s.source===`connection`?s.connection:void 0,awareness:k.awareness,states:awarenessStatesToArray(k.awareness.getStates())})}),k}storeDocumentHooks(e,t,s){let g=`onStoreDocument-${e.name}`;return this.debouncer.debounce(g,async()=>{try{await e.saveMutex.runExclusive(async()=>{await this.hooks(`onStoreDocument`,t),await this.hooks(`afterStoreDocument`,t)})}catch(t){if(t instanceof SkipFurtherHooksError){setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0);return}console.error(`Caught error during storeDocumentHooks. Document stays in memory to avoid data loss`,t);return}setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0)},s?0:this.configuration.debounce,this.configuration.maxDebounce)}hooks(e,t,s=null){let{extensions:g}=this.configuration,S=Promise.resolve();return g.filter(t=>typeof t[e]==`function`).forEach(g=>{S=S.then(()=>g[e]?.(t)).catch(t=>{throw t?.message&&console.error(`[${e}]`,t.message),t}),s&&(S=S.then((...e)=>s(...e)))}),S}shouldUnloadDocument(e){return(this.debouncer.isDebounced(`onStoreDocument-${e.name}`)||this.debouncer.isCurrentlyExecuting(`onStoreDocument-${e.name}`)||e.saveMutex.isLocked())===!1&&e.getConnectionsCount()===0}async unloadDocument(e){let t=e.name;if(!this.shouldUnloadDocument(e)||!this.documents.has(t))return;if(this.unloadingDocuments.has(t))return this.unloadingDocuments.get(t);let s=(async()=>{try{await this.hooks(`beforeUnloadDocument`,{instance:this,documentName:t,document:e})}catch{return}this.shouldUnloadDocument(e)&&(this.documents.delete(t),e.destroy(),await this.hooks(`afterUnloadDocument`,{instance:this,documentName:t}))})();this.unloadingDocuments.set(t,Promise.resolve(s)),await s,this.unloadingDocuments.delete(t)}async openDirectConnection(e,t){return new DirectConnection(await this.createDocument(e,new Request(`http://localhost`),crypto$1.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},__create$1=Object.create,__defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__getOwnPropNames$1=Object.getOwnPropertyNames,__getProtoOf$1=Object.getPrototypeOf,__hasOwnProp$1=Object.prototype.hasOwnProperty,__commonJSMin$1=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),__copyProps$1=(e,t,s,g)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var S=__getOwnPropNames$1(t),w=0,E=S.length,D;w<E;w++)D=S[w],!__hasOwnProp$1.call(e,D)&&D!==s&&__defProp$1(e,D,{get:(e=>t[e]).bind(null,D),enumerable:!(g=__getOwnPropDesc$1(t,D))||g.enumerable});return e},__toESM$1=(e,t,s)=>(s=e==null?{}:__create$1(__getProtoOf$1(e)),__copyProps$1(t||!e||!e.__esModule?__defProp$1(s,`default`,{value:e,enumerable:!0}):s,e)),__require$1=createRequire(import.meta.url),require_constants$2=__commonJSMin$1(((e,t)=>{let s=[`nodebuffer`,`arraybuffer`,`fragments`],g=typeof Blob<`u`;g&&s.push(`blob`),t.exports={BINARY_TYPES:s,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:g,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),require_buffer_util=__commonJSMin$1(((e,t)=>{let{EMPTY_BUFFER:s}=require_constants$2(),g=Buffer[Symbol.species];function S(e,t){if(e.length===0)return s;if(e.length===1)return e[0];let S=Buffer.allocUnsafe(t),w=0;for(let t=0;t<e.length;t++){let s=e[t];S.set(s,w),w+=s.length}return w<t?new g(S.buffer,S.byteOffset,w):S}function w(e,t,s,g,S){for(let w=0;w<S;w++)s[g+w]=e[w]^t[w&3]}function E(e,t){for(let s=0;s<e.length;s++)e[s]^=t[s&3]}function D(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function O(e){if(O.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new g(e):ArrayBuffer.isView(e)?t=new g(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),O.readOnly=!1),t}if(t.exports={concat:S,mask:w,toArrayBuffer:D,toBuffer:O,unmask:E},!process.env.WS_NO_BUFFER_UTIL)try{let e=__require$1(`bufferutil`);t.exports.mask=function(t,s,g,S,E){E<48?w(t,s,g,S,E):e.mask(t,s,g,S,E)},t.exports.unmask=function(t,s){t.length<32?E(t,s):e.unmask(t,s)}}catch{}})),require_limiter=__commonJSMin$1(((e,t)=>{let s=Symbol(`kDone`),g=Symbol(`kRun`);t.exports=class{constructor(e){this[s]=()=>{this.pending--,this[g]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[g]()}[g](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[s])}}}})),require_permessage_deflate=__commonJSMin$1(((e,t)=>{let s=__require$1(`zlib`),g=require_buffer_util(),S=require_limiter(),{kStatusCode:w}=require_constants$2(),E=Buffer[Symbol.species],D=Buffer.from([0,0,255,255]),O=Symbol(`permessage-deflate`),k=Symbol(`total-length`),j=Symbol(`callback`),F=Symbol(`buffers`),L=Symbol(`error`),B;t.exports=class{constructor(e,t,s){this._maxPayload=s|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,B||=new S(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[j];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,s=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!s)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(s.server_no_context_takeover=!0),t.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(s.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?s.client_max_window_bits=t.clientMaxWindowBits:(s.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let s=e[t];if(s.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(s=s[0],t===`client_max_window_bits`){if(s!==!0){let e=+s;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${s}`)}else if(t===`server_max_window_bits`){let e=+s;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(s!==!0)throw TypeError(`Invalid value for parameter "${t}": ${s}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=s})}),e}decompress(e,t,s){B.add(g=>{this._decompress(e,t,(e,t)=>{g(),s(e,t)})})}compress(e,t,s){B.add(g=>{this._compress(e,t,(e,t)=>{g(),s(e,t)})})}_decompress(e,t,S){let w=this._isServer?`client`:`server`;if(!this._inflate){let e=`${w}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:s.Z_DEFAULT_WINDOWBITS;this._inflate=s.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[O]=this,this._inflate[k]=0,this._inflate[F]=[],this._inflate.on(`error`,ee),this._inflate.on(`data`,q)}this._inflate[j]=S,this._inflate.write(e),t&&this._inflate.write(D),this._inflate.flush(()=>{let e=this._inflate[L];if(e){this._inflate.close(),this._inflate=null,S(e);return}let s=g.concat(this._inflate[F],this._inflate[k]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[k]=0,this._inflate[F]=[],t&&this.params[`${w}_no_context_takeover`]&&this._inflate.reset()),S(null,s)})}_compress(e,t,S){let w=this._isServer?`server`:`client`;if(!this._deflate){let e=`${w}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:s.Z_DEFAULT_WINDOWBITS;this._deflate=s.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[k]=0,this._deflate[F]=[],this._deflate.on(`data`,H)}this._deflate[j]=S,this._deflate.write(e),this._deflate.flush(s.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=g.concat(this._deflate[F],this._deflate[k]);t&&(e=new E(e.buffer,e.byteOffset,e.length-4)),this._deflate[j]=null,this._deflate[k]=0,this._deflate[F]=[],t&&this.params[`${w}_no_context_takeover`]&&this._deflate.reset(),S(null,e)})}};function H(e){this[F].push(e),this[k]+=e.length}function q(e){if(this[k]+=e.length,this[O]._maxPayload<1||this[k]<=this[O]._maxPayload){this[F].push(e);return}this[L]=RangeError(`Max payload size exceeded`),this[L].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[L][w]=1009,this.removeListener(`data`,q),this.reset()}function ee(e){if(this[O]._inflate=null,this[L]){this[j](this[L]);return}e[w]=1007,this[j](e)}})),require_validation=__commonJSMin$1(((e,t)=>{let{isUtf8:s}=__require$1(`buffer`),{hasBlob:g}=require_constants$2(),S=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function w(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function E(e){let t=e.length,s=0;for(;s<t;)if(!(e[s]&128))s++;else if((e[s]&224)==192){if(s+1===t||(e[s+1]&192)!=128||(e[s]&254)==192)return!1;s+=2}else if((e[s]&240)==224){if(s+2>=t||(e[s+1]&192)!=128||(e[s+2]&192)!=128||e[s]===224&&(e[s+1]&224)==128||e[s]===237&&(e[s+1]&224)==160)return!1;s+=3}else if((e[s]&248)==240){if(s+3>=t||(e[s+1]&192)!=128||(e[s+2]&192)!=128||(e[s+3]&192)!=128||e[s]===240&&(e[s+1]&240)==128||e[s]===244&&e[s+1]>143||e[s]>244)return!1;s+=4}else return!1;return!0}function D(e){return g&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:D,isValidStatusCode:w,isValidUTF8:E,tokenChars:S},s)t.exports.isValidUTF8=function(e){return e.length<24?E(e):s(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=__require$1(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?E(t):e(t)}}catch{}})),require_receiver=__commonJSMin$1(((e,t)=>{let{Writable:s}=__require$1(`stream`),g=require_permessage_deflate(),{BINARY_TYPES:S,EMPTY_BUFFER:w,kStatusCode:E,kWebSocket:D}=require_constants$2(),{concat:O,toArrayBuffer:k,unmask:j}=require_buffer_util(),{isValidStatusCode:F,isValidUTF8:L}=require_validation(),B=Buffer[Symbol.species],H=0,q=1,ee=2,J=3,Y=4,te=5,ne=6;t.exports=class extends s{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||S[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[D]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,s){if(this._opcode===8&&this._state==0)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new B(t.buffer,t.byteOffset+e,t.length-e),new B(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let s=this._buffers[0],g=t.length-e;e>=s.length?t.set(this._buffers.shift(),g):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),g),this._buffers[0]=new B(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let s=(t[0]&64)==64;if(s&&!this._extensions[g.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(s){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(s){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),s=t.readUInt32BE(0);if(s>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=s*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=w;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&j(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[g.extensionName].decompress(e,this._fin,(e,s)=>{if(e)return t(e);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(s)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let g;g=this._binaryType===`nodebuffer`?O(s,t):this._binaryType===`arraybuffer`?k(O(s,t)):this._binaryType===`blob`?new Blob(s):s,this._allowSynchronousEvents?(this.emit(`message`,g,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,g,!0),this._state=0,this.startLoop(e)}))}else{let g=O(s,t);if(!this._skipUTF8Validation&&!L(g)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,g,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,g,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,w),this.end();else{let s=e.readUInt16BE(0);if(!F(s)){t(this.createError(RangeError,`invalid status code ${s}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let g=new B(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!L(g)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,s,g),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,s,g,S){this._loop=!1,this._errored=!0;let w=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(w,this.createError),w.code=S,w[E]=g,w}}})),require_sender=__commonJSMin$1(((e,t)=>{let{Duplex:s}=__require$1(`stream`),{randomFillSync:g}=__require$1(`crypto`),S=require_permessage_deflate(),{EMPTY_BUFFER:w,kWebSocket:E,NOOP:D}=require_constants$2(),{isBlob:O,isValidStatusCode:k}=require_validation(),{mask:j,toBuffer:F}=require_buffer_util(),L=Symbol(`kByteLength`),B=Buffer.alloc(4),H=8*1024,q,ee=H,J=0,Y=1,te=2;t.exports=class e{constructor(e,t,s){this._extensions=t||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=D,this[E]=void 0}static frame(e,t){let s,S=!1,w=2,E=!1;t.mask&&(s=t.maskBuffer||B,t.generateMask?t.generateMask(s):(ee===H&&(q===void 0&&(q=Buffer.alloc(H)),g(q,0,H),ee=0),s[0]=q[ee++],s[1]=q[ee++],s[2]=q[ee++],s[3]=q[ee++]),E=(s[0]|s[1]|s[2]|s[3])===0,w=6);let D;typeof e==`string`?(!t.mask||E)&&t[L]!==void 0?D=t[L]:(e=Buffer.from(e),D=e.length):(D=e.length,S=t.mask&&t.readOnly&&!E);let O=D;D>=65536?(w+=8,O=127):D>125&&(w+=2,O=126);let k=Buffer.allocUnsafe(S?D+w:w);return k[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(k[0]|=64),k[1]=O,O===126?k.writeUInt16BE(D,2):O===127&&(k[2]=k[3]=0,k.writeUIntBE(D,4,6)),!t.mask||(k[1]|=128,k[w-4]=s[0],k[w-3]=s[1],k[w-2]=s[2],k[w-1]=s[3],E)?[k,e]:S?(j(e,s,k,w,D),[k]):(j(e,s,e,0,D),[k,e])}close(t,s,g,S){let E;if(t===void 0)E=w;else if(typeof t!=`number`||!k(t))throw TypeError(`First argument must be a valid error code number`);else if(s===void 0||!s.length)E=Buffer.allocUnsafe(2),E.writeUInt16BE(t,0);else{let e=Buffer.byteLength(s);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);E=Buffer.allocUnsafe(2+e),E.writeUInt16BE(t,0),typeof s==`string`?E.write(s,2):E.set(s,2)}let D={[L]:E.length,fin:!0,generateMask:this._generateMask,mask:g,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(E,D),S):this.enqueue([this.dispatch,E,!1,D,S])}ping(t,s,g){let S,w;if(typeof t==`string`?(S=Buffer.byteLength(t),w=!1):O(t)?(S=t.size,w=!1):(t=F(t),S=t.length,w=F.readOnly),S>125)throw RangeError(`The data size must not be greater than 125 bytes`);let E={[L]:S,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:9,readOnly:w,rsv1:!1};O(t)?this._state===0?this.getBlobData(t,!1,E,g):this.enqueue([this.getBlobData,t,!1,E,g]):this._state===0?this.sendFrame(e.frame(t,E),g):this.enqueue([this.dispatch,t,!1,E,g])}pong(t,s,g){let S,w;if(typeof t==`string`?(S=Buffer.byteLength(t),w=!1):O(t)?(S=t.size,w=!1):(t=F(t),S=t.length,w=F.readOnly),S>125)throw RangeError(`The data size must not be greater than 125 bytes`);let E={[L]:S,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:10,readOnly:w,rsv1:!1};O(t)?this._state===0?this.getBlobData(t,!1,E,g):this.enqueue([this.getBlobData,t,!1,E,g]):this._state===0?this.sendFrame(e.frame(t,E),g):this.enqueue([this.dispatch,t,!1,E,g])}send(e,t,s){let g=this._extensions[S.extensionName],w=t.binary?2:1,E=t.compress,D,k;typeof e==`string`?(D=Buffer.byteLength(e),k=!1):O(e)?(D=e.size,k=!1):(e=F(e),D=e.length,k=F.readOnly),this._firstFragment?(this._firstFragment=!1,E&&g&&g.params[g._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(E=D>=g._threshold),this._compress=E):(E=!1,w=0),t.fin&&(this._firstFragment=!0);let j={[L]:D,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:w,readOnly:k,rsv1:E};O(e)?this._state===0?this.getBlobData(e,this._compress,j,s):this.enqueue([this.getBlobData,e,this._compress,j,s]):this._state===0?this.dispatch(e,this._compress,j,s):this.enqueue([this.dispatch,e,this._compress,j,s])}getBlobData(t,s,g,S){this._bufferedBytes+=g[L],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(ne,this,e,S);return}this._bufferedBytes-=g[L];let w=F(t);s?this.dispatch(w,s,g,S):(this._state=0,this.sendFrame(e.frame(w,g),S),this.dequeue())}).catch(e=>{process.nextTick(ae,this,e,S)})}dispatch(t,s,g,w){if(!s){this.sendFrame(e.frame(t,g),w);return}let E=this._extensions[S.extensionName];this._bufferedBytes+=g[L],this._state=1,E.compress(t,g.fin,(t,s)=>{if(this._socket.destroyed){ne(this,Error(`The socket was closed while data was being compressed`),w);return}this._bufferedBytes-=g[L],this._state=0,g.readOnly=!1,this.sendFrame(e.frame(s,g),w),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][L],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][L],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function ne(e,t,s){typeof s==`function`&&s(t);for(let s=0;s<e._queue.length;s++){let g=e._queue[s],S=g[g.length-1];typeof S==`function`&&S(t)}}function ae(e,t,s){ne(e,t,s),e.onerror(t)}})),require_event_target=__commonJSMin$1(((e,t)=>{let{kForOnEventAttribute:s,kListener:g}=require_constants$2(),S=Symbol(`kCode`),w=Symbol(`kData`),E=Symbol(`kError`),D=Symbol(`kMessage`),O=Symbol(`kReason`),k=Symbol(`kTarget`),j=Symbol(`kType`),F=Symbol(`kWasClean`);var L=class{constructor(e){this[k]=null,this[j]=e}get target(){return this[k]}get type(){return this[j]}};Object.defineProperty(L.prototype,`target`,{enumerable:!0}),Object.defineProperty(L.prototype,`type`,{enumerable:!0});var B=class extends L{constructor(e,t={}){super(e),this[S]=t.code===void 0?0:t.code,this[O]=t.reason===void 0?``:t.reason,this[F]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[S]}get reason(){return this[O]}get wasClean(){return this[F]}};Object.defineProperty(B.prototype,`code`,{enumerable:!0}),Object.defineProperty(B.prototype,`reason`,{enumerable:!0}),Object.defineProperty(B.prototype,`wasClean`,{enumerable:!0});var H=class extends L{constructor(e,t={}){super(e),this[E]=t.error===void 0?null:t.error,this[D]=t.message===void 0?``:t.message}get error(){return this[E]}get message(){return this[D]}};Object.defineProperty(H.prototype,`error`,{enumerable:!0}),Object.defineProperty(H.prototype,`message`,{enumerable:!0});var q=class extends L{constructor(e,t={}){super(e),this[w]=t.data===void 0?null:t.data}get data(){return this[w]}};Object.defineProperty(q.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:B,ErrorEvent:H,Event:L,EventTarget:{addEventListener(e,t,S={}){for(let w of this.listeners(e))if(!S[s]&&w[g]===t&&!w[s])return;let w;if(e===`message`)w=function(e,s){let g=new q(`message`,{data:s?e:e.toString()});g[k]=this,ee(t,this,g)};else if(e===`close`)w=function(e,s){let g=new B(`close`,{code:e,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});g[k]=this,ee(t,this,g)};else if(e===`error`)w=function(e){let s=new H(`error`,{error:e,message:e.message});s[k]=this,ee(t,this,s)};else if(e===`open`)w=function(){let e=new L(`open`);e[k]=this,ee(t,this,e)};else return;w[s]=!!S[s],w[g]=t,S.once?this.once(e,w):this.on(e,w)},removeEventListener(e,t){for(let S of this.listeners(e))if(S[g]===t&&!S[s]){this.removeListener(e,S);break}}},MessageEvent:q};function ee(e,t,s){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,s):e.call(t,s)}})),require_extension=__commonJSMin$1(((e,t)=>{let{tokenChars:s}=require_validation();function g(e,t,s){e[t]===void 0?e[t]=[s]:e[t].push(s)}function S(e){let t=Object.create(null),S=Object.create(null),w=!1,E=!1,D=!1,O,k,j=-1,F=-1,L=-1,B=0;for(;B<e.length;B++)if(F=e.charCodeAt(B),O===void 0)if(L===-1&&s[F]===1)j===-1&&(j=B);else if(B!==0&&(F===32||F===9))L===-1&&j!==-1&&(L=B);else if(F===59||F===44){if(j===-1)throw SyntaxError(`Unexpected character at index ${B}`);L===-1&&(L=B);let s=e.slice(j,L);F===44?(g(t,s,S),S=Object.create(null)):O=s,j=L=-1}else throw SyntaxError(`Unexpected character at index ${B}`);else if(k===void 0)if(L===-1&&s[F]===1)j===-1&&(j=B);else if(F===32||F===9)L===-1&&j!==-1&&(L=B);else if(F===59||F===44){if(j===-1)throw SyntaxError(`Unexpected character at index ${B}`);L===-1&&(L=B),g(S,e.slice(j,L),!0),F===44&&(g(t,O,S),S=Object.create(null),O=void 0),j=L=-1}else if(F===61&&j!==-1&&L===-1)k=e.slice(j,B),j=L=-1;else throw SyntaxError(`Unexpected character at index ${B}`);else if(E){if(s[F]!==1)throw SyntaxError(`Unexpected character at index ${B}`);j===-1?j=B:w||=!0,E=!1}else if(D)if(s[F]===1)j===-1&&(j=B);else if(F===34&&j!==-1)D=!1,L=B;else if(F===92)E=!0;else throw SyntaxError(`Unexpected character at index ${B}`);else if(F===34&&e.charCodeAt(B-1)===61)D=!0;else if(L===-1&&s[F]===1)j===-1&&(j=B);else if(j!==-1&&(F===32||F===9))L===-1&&(L=B);else if(F===59||F===44){if(j===-1)throw SyntaxError(`Unexpected character at index ${B}`);L===-1&&(L=B);let s=e.slice(j,L);w&&=(s=s.replace(/\\/g,``),!1),g(S,k,s),F===44&&(g(t,O,S),S=Object.create(null),O=void 0),k=void 0,j=L=-1}else throw SyntaxError(`Unexpected character at index ${B}`);if(j===-1||D||F===32||F===9)throw SyntaxError(`Unexpected end of input`);L===-1&&(L=B);let H=e.slice(j,L);return O===void 0?g(t,H,S):(k===void 0?g(S,H,!0):w?g(S,k,H.replace(/\\/g,``)):g(S,k,H),g(t,O,S)),t}function w(e){return Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>[t].concat(Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:w,parse:S}})),require_websocket=__commonJSMin$1(((e,t)=>{let s=__require$1(`events`),g=__require$1(`https`),S=__require$1(`http`),w=__require$1(`net`),E=__require$1(`tls`),{randomBytes:D,createHash:O}=__require$1(`crypto`),{Duplex:k,Readable:j}=__require$1(`stream`),{URL:F}=__require$1(`url`),L=require_permessage_deflate(),B=require_receiver(),H=require_sender(),{isBlob:q}=require_validation(),{BINARY_TYPES:ee,CLOSE_TIMEOUT:J,EMPTY_BUFFER:Y,GUID:te,kForOnEventAttribute:ne,kListener:ae,kStatusCode:oe,kWebSocket:se,NOOP:ce}=require_constants$2(),{EventTarget:{addEventListener:ue,removeEventListener:de}}=require_event_target(),{format:fe,parse:me}=require_extension(),{toBuffer:ge}=require_buffer_util(),_e=Symbol(`kAborted`),ve=[8,13],ye=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],Ce=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var we=class e extends s{constructor(t,s,g){super(),this._binaryType=ee[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Y,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=g.autoPong,this._closeTimeout=g.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,s===void 0?s=[]:Array.isArray(s)||(typeof s==`object`&&s?(g=s,s=[]):s=[s]),Te(this,t,s,g))}get binaryType(){return this._binaryType}set binaryType(e){ee.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,s,g){let S=new B({allowSynchronousEvents:g.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:g.maxPayload,skipUTF8Validation:g.skipUTF8Validation}),w=new H(t,this._extensions,g.generateMask);this._receiver=S,this._sender=w,this._socket=t,S[se]=this,w[se]=this,t[se]=this,S.on(`conclude`,Re),S.on(`drain`,ze),S.on(`error`,Be),S.on(`message`,Ue),S.on(`ping`,We),S.on(`pong`,Ge),w.onerror=Xe,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),s.length>0&&t.unshift(s),t.on(`close`,nt),t.on(`data`,rt),t.on(`end`,it),t.on(`error`,at),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[L.extensionName]&&this._extensions[L.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,s){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Pe(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,s,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),$e(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,s,g){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(g=t,t=s=void 0):typeof s==`function`&&(g=s,s=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){Ie(this,t,g);return}s===void 0&&(s=!this._isServer),this._sender.ping(t||Y,s,g)}pong(t,s,g){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(g=t,t=s=void 0):typeof s==`function`&&(g=s,s=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){Ie(this,t,g);return}s===void 0&&(s=!this._isServer),this._sender.pong(t||Y,s,g)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,s,g){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof s==`function`&&(g=s,s={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){Ie(this,t,g);return}let S={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...s};this._extensions[L.extensionName]||(S.compress=!1),this._sender.send(t||Y,S,g)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Pe(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(we,`CONNECTING`,{enumerable:!0,value:ye.indexOf(`CONNECTING`)}),Object.defineProperty(we.prototype,`CONNECTING`,{enumerable:!0,value:ye.indexOf(`CONNECTING`)}),Object.defineProperty(we,`OPEN`,{enumerable:!0,value:ye.indexOf(`OPEN`)}),Object.defineProperty(we.prototype,`OPEN`,{enumerable:!0,value:ye.indexOf(`OPEN`)}),Object.defineProperty(we,`CLOSING`,{enumerable:!0,value:ye.indexOf(`CLOSING`)}),Object.defineProperty(we.prototype,`CLOSING`,{enumerable:!0,value:ye.indexOf(`CLOSING`)}),Object.defineProperty(we,`CLOSED`,{enumerable:!0,value:ye.indexOf(`CLOSED`)}),Object.defineProperty(we.prototype,`CLOSED`,{enumerable:!0,value:ye.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(we.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(we.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[ne])return t[ae];return null},set(t){for(let t of this.listeners(e))if(t[ne]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[ne]:!0})}})}),we.prototype.addEventListener=ue,we.prototype.removeEventListener=de,t.exports=we;function Te(e,t,s,w){let E={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:J,protocolVersion:ve[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...w,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=E.autoPong,e._closeTimeout=E.closeTimeout,!ve.includes(E.protocolVersion))throw RangeError(`Unsupported protocol version: ${E.protocolVersion} (supported versions: ${ve.join(`, `)})`);let k;if(t instanceof F)k=t;else try{k=new F(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}k.protocol===`http:`?k.protocol=`ws:`:k.protocol===`https:`&&(k.protocol=`wss:`),e._url=k.href;let j=k.protocol===`wss:`,B=k.protocol===`ws+unix:`,H;if(k.protocol!==`ws:`&&!j&&!B?H=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:B&&!k.pathname?H=`The URL's pathname is empty`:k.hash&&(H=`The URL contains a fragment identifier`),H){let t=SyntaxError(H);if(e._redirects===0)throw t;De(e,t);return}let q=j?443:80,ee=D(16).toString(`base64`),Y=j?g.request:S.request,ne=new Set,ae;if(E.createConnection=E.createConnection||(j?Me:je),E.defaultPort=E.defaultPort||q,E.port=k.port||q,E.host=k.hostname.startsWith(`[`)?k.hostname.slice(1,-1):k.hostname,E.headers={...E.headers,"Sec-WebSocket-Version":E.protocolVersion,"Sec-WebSocket-Key":ee,Connection:`Upgrade`,Upgrade:`websocket`},E.path=k.pathname+k.search,E.timeout=E.handshakeTimeout,E.perMessageDeflate&&(ae=new L(E.perMessageDeflate===!0?{}:E.perMessageDeflate,!1,E.maxPayload),E.headers[`Sec-WebSocket-Extensions`]=fe({[L.extensionName]:ae.offer()})),s.length){for(let e of s){if(typeof e!=`string`||!Ce.test(e)||ne.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);ne.add(e)}E.headers[`Sec-WebSocket-Protocol`]=s.join(`,`)}if(E.origin&&(E.protocolVersion<13?E.headers[`Sec-WebSocket-Origin`]=E.origin:E.headers.Origin=E.origin),(k.username||k.password)&&(E.auth=`${k.username}:${k.password}`),B){let e=E.path.split(`:`);E.socketPath=e[0],E.path=e[1]}let oe;if(E.followRedirects){if(e._redirects===0){e._originalIpc=B,e._originalSecure=j,e._originalHostOrSocketPath=B?E.socketPath:k.host;let t=w&&w.headers;if(w={...w,headers:{}},t)for(let[e,s]of Object.entries(t))w.headers[e.toLowerCase()]=s}else if(e.listenerCount(`redirect`)===0){let t=B?e._originalIpc?E.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:k.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!j)&&(delete E.headers.authorization,delete E.headers.cookie,t||delete E.headers.host,E.auth=void 0)}E.auth&&!w.headers.authorization&&(w.headers.authorization=`Basic `+Buffer.from(E.auth).toString(`base64`)),oe=e._req=Y(E),e._redirects&&e.emit(`redirect`,e.url,oe)}else oe=e._req=Y(E);E.timeout&&oe.on(`timeout`,()=>{Pe(e,oe,`Opening handshake has timed out`)}),oe.on(`error`,t=>{oe===null||oe[_e]||(oe=e._req=null,De(e,t))}),oe.on(`response`,g=>{let S=g.headers.location,D=g.statusCode;if(S&&E.followRedirects&&D>=300&&D<400){if(++e._redirects>E.maxRedirects){Pe(e,oe,`Maximum redirects exceeded`);return}oe.abort();let g;try{g=new F(S,t)}catch{De(e,SyntaxError(`Invalid URL: ${S}`));return}Te(e,g,s,w)}else e.emit(`unexpected-response`,oe,g)||Pe(e,oe,`Unexpected server response: ${g.statusCode}`)}),oe.on(`upgrade`,(t,s,g)=>{if(e.emit(`upgrade`,t),e.readyState!==we.CONNECTING)return;oe=e._req=null;let S=t.headers.upgrade;if(S===void 0||S.toLowerCase()!==`websocket`){Pe(e,s,`Invalid Upgrade header`);return}let w=O(`sha1`).update(ee+te).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==w){Pe(e,s,`Invalid Sec-WebSocket-Accept header`);return}let D=t.headers[`sec-websocket-protocol`],k;if(D===void 0?ne.size&&(k=`Server sent no subprotocol`):ne.size?ne.has(D)||(k=`Server sent an invalid subprotocol`):k=`Server sent a subprotocol but none was requested`,k){Pe(e,s,k);return}D&&(e._protocol=D);let j=t.headers[`sec-websocket-extensions`];if(j!==void 0){if(!ae){Pe(e,s,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=me(j)}catch{Pe(e,s,`Invalid Sec-WebSocket-Extensions header`);return}let g=Object.keys(t);if(g.length!==1||g[0]!==L.extensionName){Pe(e,s,`Server indicated an extension that was not requested`);return}try{ae.accept(t[L.extensionName])}catch{Pe(e,s,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[L.extensionName]=ae}e.setSocket(s,g,{allowSynchronousEvents:E.allowSynchronousEvents,generateMask:E.generateMask,maxPayload:E.maxPayload,skipUTF8Validation:E.skipUTF8Validation})}),E.finishRequest?E.finishRequest(oe,e):oe.end()}function De(e,t){e._readyState=we.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function je(e){return e.path=e.socketPath,w.connect(e)}function Me(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=w.isIP(e.host)?``:e.host),E.connect(e)}function Pe(e,t,s){e._readyState=we.CLOSING;let g=Error(s);Error.captureStackTrace(g,Pe),t.setHeader?(t[_e]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(De,e,g)):(t.destroy(g),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function Ie(e,t,s){if(t){let s=q(t)?t.size:ge(t).length;e._socket?e._sender._bufferedBytes+=s:e._bufferedAmount+=s}if(s){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${ye[e.readyState]})`);process.nextTick(s,t)}}function Re(e,t){let s=this[se];s._closeFrameReceived=!0,s._closeMessage=t,s._closeCode=e,s._socket[se]!==void 0&&(s._socket.removeListener(`data`,rt),process.nextTick(Ke,s._socket),e===1005?s.close():s.close(e,t))}function ze(){let e=this[se];e.isPaused||e._socket.resume()}function Be(e){let t=this[se];t._socket[se]!==void 0&&(t._socket.removeListener(`data`,rt),process.nextTick(Ke,t._socket),t.close(e[oe])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function Ve(){this[se].emitClose()}function Ue(e,t){this[se].emit(`message`,e,t)}function We(e){let t=this[se];t._autoPong&&t.pong(e,!this._isServer,ce),t.emit(`ping`,e)}function Ge(e){this[se].emit(`pong`,e)}function Ke(e){e.resume()}function Xe(e){let t=this[se];t.readyState!==we.CLOSED&&(t.readyState===we.OPEN&&(t._readyState=we.CLOSING,$e(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function $e(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function nt(){let e=this[se];if(this.removeListener(`close`,nt),this.removeListener(`data`,rt),this.removeListener(`end`,it),e._readyState=we.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[se]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,Ve),e._receiver.on(`finish`,Ve))}function rt(e){this[se]._receiver.write(e)||this.pause()}function it(){let e=this[se];e._readyState=we.CLOSING,e._receiver.end(),this.end()}function at(){let e=this[se];this.removeListener(`error`,at),this.on(`error`,ce),e&&(e._readyState=we.CLOSING,this.destroy())}})),require_stream=__commonJSMin$1(((e,t)=>{require_websocket();let{Duplex:s}=__require$1(`stream`);function g(e){e.emit(`close`)}function S(){!this.destroyed&&this._writableState.finished&&this.destroy()}function w(e){this.removeListener(`error`,w),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function E(e,t){let E=!0,D=new s({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,s){let g=!s&&D._readableState.objectMode?t.toString():t;D.push(g)||e.pause()}),e.once(`error`,function(e){D.destroyed||(E=!1,D.destroy(e))}),e.once(`close`,function(){D.destroyed||D.push(null)}),D._destroy=function(t,s){if(e.readyState===e.CLOSED){s(t),process.nextTick(g,D);return}let S=!1;e.once(`error`,function(e){S=!0,s(e)}),e.once(`close`,function(){S||s(t),process.nextTick(g,D)}),E&&e.terminate()},D._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){D._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),D._readableState.endEmitted&&D.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},D._read=function(){e.isPaused&&e.resume()},D._write=function(t,s,g){if(e.readyState===e.CONNECTING){e.once(`open`,function(){D._write(t,s,g)});return}e.send(t,g)},D.on(`end`,S),D.on(`error`,w),D}t.exports=E})),require_subprotocol=__commonJSMin$1(((e,t)=>{let{tokenChars:s}=require_validation();function g(e){let t=new Set,g=-1,S=-1,w=0;for(;w<e.length;w++){let E=e.charCodeAt(w);if(S===-1&&s[E]===1)g===-1&&(g=w);else if(w!==0&&(E===32||E===9))S===-1&&g!==-1&&(S=w);else if(E===44){if(g===-1)throw SyntaxError(`Unexpected character at index ${w}`);S===-1&&(S=w);let s=e.slice(g,S);if(t.has(s))throw SyntaxError(`The "${s}" subprotocol is duplicated`);t.add(s),g=S=-1}else throw SyntaxError(`Unexpected character at index ${w}`)}if(g===-1||S!==-1)throw SyntaxError(`Unexpected end of input`);let E=e.slice(g,w);if(t.has(E))throw SyntaxError(`The "${E}" subprotocol is duplicated`);return t.add(E),t}t.exports={parse:g}})),require_websocket_server=__commonJSMin$1(((e,t)=>{let s=__require$1(`events`),g=__require$1(`http`),{Duplex:S}=__require$1(`stream`),{createHash:w}=__require$1(`crypto`),E=require_extension(),D=require_permessage_deflate(),O=require_subprotocol(),k=require_websocket(),{CLOSE_TIMEOUT:j,GUID:F,kWebSocket:L}=require_constants$2(),B=/^[+/0-9A-Za-z]{22}==$/,H=0,q=1,ee=2;t.exports=class extends s{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:j,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:k,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=g.createServer((e,t)=>{let s=g.STATUS_CODES[426];t.writeHead(426,{"Content-Length":s.length,"Content-Type":`text/plain`}),t.end(s)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=J(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,s,g)=>{this.handleUpgrade(t,s,g,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(Y,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(Y,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{Y(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,s,g){t.on(`error`,te);let S=e.headers[`sec-websocket-key`],w=e.headers.upgrade,k=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){ae(this,e,t,405,`Invalid HTTP method`);return}if(w===void 0||w.toLowerCase()!==`websocket`){ae(this,e,t,400,`Invalid Upgrade header`);return}if(S===void 0||!B.test(S)){ae(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(k!==13&&k!==8){ae(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){ne(t,400);return}let j=e.headers[`sec-websocket-protocol`],F=new Set;if(j!==void 0)try{F=O.parse(j)}catch{ae(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let L=e.headers[`sec-websocket-extensions`],H={};if(this.options.perMessageDeflate&&L!==void 0){let s=new D(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=E.parse(L);e[D.extensionName]&&(s.accept(e[D.extensionName]),H[D.extensionName]=s)}catch{ae(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let w={origin:e.headers[`${k===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(w,(w,E,D,O)=>{if(!w)return ne(t,E||401,D,O);this.completeUpgrade(H,S,F,e,t,s,g)});return}if(!this.options.verifyClient(w))return ne(t,401)}this.completeUpgrade(H,S,F,e,t,s,g)}completeUpgrade(e,t,s,g,S,O,k){if(!S.readable||!S.writable)return S.destroy();if(S[L])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return ne(S,503);let j=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${w(`sha1`).update(t+F).digest(`base64`)}`],B=new this.options.WebSocket(null,void 0,this.options);if(s.size){let e=this.options.handleProtocols?this.options.handleProtocols(s,g):s.values().next().value;e&&(j.push(`Sec-WebSocket-Protocol: ${e}`),B._protocol=e)}if(e[D.extensionName]){let t=e[D.extensionName].params,s=E.format({[D.extensionName]:[t]});j.push(`Sec-WebSocket-Extensions: ${s}`),B._extensions=e}this.emit(`headers`,j,g),S.write(j.concat(`\r
|
|
757
|
+
`)}var fl=new TextDecoder(`utf-8`,{fatal:!0});function qi(e){if(!e)return e;let t=!1;for(let s=0;s<e.length;s++){let g=e.charCodeAt(s);if(g>255)return e;g>127&&(t=!0)}if(!t)return e;let s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);try{return fl.decode(s)}catch{return e}}var pl=[`EACCES`,`escaping sandbox`,`EFBIG`],As=class{root;canonicalRoot;maxFileReadSize;allowSymlinks;constructor(e){this.root=U.resolve(e.root),this.maxFileReadSize=e.maxFileReadSize??10485760,this.allowSymlinks=e.allowSymlinks??!1,$$2(this.root,`ReadWriteFs`),this.canonicalRoot=I.realpathSync(this.root)}resolveAndValidate(e,t){let s=this.allowSymlinks?f$1(e,this.canonicalRoot):P$1(e,this.root,this.canonicalRoot);if(s===null)throw Error(`EACCES: permission denied, '${t}' resolves outside sandbox`);return s}validateParent(e,t){let s=U.dirname(e),g=this.resolveAndValidate(s,t);return U.join(g,U.basename(e))}toRealPath(e){let t=c$1(e),s=U.join(this.root,t);return U.resolve(s)}async readFile(e,t){return h$2(await this.readFileBuffer(e),l$1(t))}async readFileBuffer(e){h$1(e,`open`);let t=this.toRealPath(e),s=this.resolveAndValidate(t,e);try{let t=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,g=await I.promises.open(s,t);try{if(this.maxFileReadSize>0){let t=await g.stat();if(t.size>this.maxFileReadSize)throw Error(`EFBIG: file too large, read '${e}' (${t.size} bytes, max ${this.maxFileReadSize})`)}let t=await g.readFile();return new Uint8Array(t)}finally{await g.close()}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(s.code===`EISDIR`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(s.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`open`)}}async writeFile(e,t,s){h$1(e,`write`);let g=this.toRealPath(e),S=this.resolveAndValidate(g,e),w=o(t,l$1(s)),E=U.dirname(S);try{await I.promises.mkdir(E,{recursive:!0}),S=this.resolveAndValidate(g,e);let t=this.allowSymlinks?0:I.constants.O_NOFOLLOW,s=I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_TRUNC|t,D=await I.promises.open(S,s,438);try{await D.writeFile(w)}finally{await D.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`write`)}}async appendFile(e,t,s){h$1(e,`append`);let g=this.toRealPath(e),S=this.resolveAndValidate(g,e),w=o(t,l$1(s)),E=U.dirname(S);try{await I.promises.mkdir(E,{recursive:!0}),S=this.resolveAndValidate(g,e);let t=this.allowSymlinks?0:I.constants.O_NOFOLLOW,s=I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_APPEND|t,D=await I.promises.open(S,s,438);try{await D.writeFile(w)}finally{await D.close()}}catch(t){if(t.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`append`)}}async exists(e){if(e.includes(`\0`))return!1;let t=this.toRealPath(e);try{let s=this.resolveAndValidate(t,e);return await I.promises.access(s),!0}catch{return!1}}async stat(e){h$1(e,`stat`);let t=this.toRealPath(e),s=this.resolveAndValidate(t,e);try{let t=await I.promises.lstat(s);if(!this.allowSymlinks&&t.isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return{isFile:t.isFile(),isDirectory:t.isDirectory(),isSymbolicLink:t.isSymbolicLink(),mode:t.mode,size:t.size,mtime:t.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, stat '${e}'`);this.sanitizeError(t,e,`stat`)}}async lstat(e){h$1(e,`lstat`);let t=this.toRealPath(e),s=this.validateParent(t,e);try{let e=await I.promises.lstat(s);return{isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink(),mode:e.mode,size:e.size,mtime:e.mtime}}catch(t){if(t.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);this.sanitizeError(t,e,`lstat`)}}async mkdir(e,t){h$1(e,`mkdir`);let s=this.toRealPath(e),g=this.resolveAndValidate(s,e);try{await I.promises.mkdir(g,{recursive:t?.recursive})}catch(t){let s=t;if(s.code===`EEXIST`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.sanitizeError(t,e,`mkdir`)}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){h$1(e,`scandir`);let t=this.toRealPath(e),s=this.resolveAndValidate(t,e);try{if(!this.allowSymlinks&&(await I.promises.lstat(s)).isSymbolicLink())throw Error(`EACCES: permission denied, '${e}' is a symlink`);return(await I.promises.readdir(s,{withFileTypes:!0})).map(e=>({name:e.name,isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink()})).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(s.code===`ENOTDIR`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);this.sanitizeError(t,e,`scandir`)}}async rm(e,t){h$1(e,`rm`);let s=this.toRealPath(e),g=this.resolveAndValidate(s,e);try{await I.promises.rm(g,{recursive:t?.recursive??!1,force:t?.force??!1})}catch(s){let g=s;if(g.code===`ENOENT`&&!t?.force)throw Error(`ENOENT: no such file or directory, rm '${e}'`);if(g.code===`ENOTEMPTY`)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);this.sanitizeError(s,e,`rm`)}}async cp(e,t,s){h$1(e,`cp`),h$1(t,`cp`);let g=this.toRealPath(e),S=this.toRealPath(t),w=this.resolveAndValidate(g,e),E=this.resolveAndValidate(S,t);try{await I.promises.cp(w,E,{recursive:s?.recursive??!1,filter:async e=>{try{if(I.lstatSync(e).isSymbolicLink()){let t=await I.promises.realpath(e).catch(()=>null);return t===null?!1:d$1(t,this.canonicalRoot)}return!0}catch(e){return e.code===`ENOENT`}}})}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(s.code===`EISDIR`)throw Error(`EISDIR: is a directory, cp '${e}'`);this.sanitizeError(t,e,`cp`)}}async mv(e,t){h$1(e,`mv`),h$1(t,`mv`);let s=this.toRealPath(e),g=this.toRealPath(t),S=this.validateParent(s,e),w=this.validateParent(g,t);try{if((await I.promises.lstat(S)).isSymbolicLink()){let s=await I.promises.readlink(S),g=U.resolve(U.dirname(w),s);if(!d$1(await I.promises.realpath(g).catch(()=>g),this.canonicalRoot))throw Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlink escaping sandbox`)}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(s.message?.includes(`EACCES`)||s.message?.includes(`escaping sandbox`))throw t}let E=U.dirname(w);try{await I.promises.mkdir(E,{recursive:!0})}catch(e){this.sanitizeError(e,t,`mv`)}try{await I.promises.rename(S,w)}catch(s){let g=s;if(g.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, mv '${e}'`);if(g.code===`EXDEV`){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0});return}this.sanitizeError(s,e,`mv`)}try{if(I.lstatSync(w).isDirectory()&&this.findEscapingSymlinks(w).length>0)throw await I.promises.rename(w,S),Error(`EACCES: permission denied, mv '${e}' -> '${t}' would create symlinks escaping sandbox`)}catch(e){if(e.message?.includes(`EACCES`)||e.message?.includes(`escaping sandbox`))throw e}}resolvePath(e,t){return y(e,t)}getAllPaths(){let e=[];return this.scanDir(`/`,e),e}sanitizeError(e,t,s){N(e,t,s,pl)}findEscapingSymlinks(e){let t=[];try{let s=I.readdirSync(e);for(let g of s){let s=U.join(e,g);try{let g=I.lstatSync(s);if(g.isSymbolicLink()){let g=I.readlinkSync(s),S=U.resolve(e,g),w;try{w=I.realpathSync(S)}catch{w=S}d$1(w,this.canonicalRoot)||t.push(s)}else g.isDirectory()&&t.push(...this.findEscapingSymlinks(s))}catch{}}}catch{}return t}scanDir(e,t){let s=this.toRealPath(e),g;try{g=this.resolveAndValidate(s,e)}catch{return}try{let s=I.readdirSync(g);for(let S of s){let s=e===`/`?`/${S}`:`${e}/${S}`;t.push(s);let w=U.join(g,S);I.lstatSync(w).isDirectory()&&this.scanDir(s,t)}}catch{}}async chmod(e,t){h$1(e,`chmod`);let s=this.toRealPath(e),g=this.resolveAndValidate(s,e);try{let e=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,s=await I.promises.open(g,e);try{await s.chmod(t)}finally{await s.close()}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);if(s.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`chmod`)}}async symlink(e,t){if(!this.allowSymlinks)throw Error(`EPERM: operation not permitted, symlink '${t}'`);h$1(t,`symlink`);let s=this.toRealPath(t),g=this.validateParent(s,t),S=c$1(t),w=c$1(U.dirname(S)),E=e.startsWith(`/`)?c$1(e):c$1(w===`/`?`/${e}`:`${w}/${e}`),D=U.join(this.canonicalRoot,E),O=U.dirname(g),k=e.startsWith(`/`)?D:U.relative(O,D)||`.`;try{await I.promises.symlink(k,g)}catch(e){if(e.code===`EEXIST`)throw Error(`EEXIST: file already exists, symlink '${t}'`);this.sanitizeError(e,t,`symlink`)}}async link(e,t){h$1(e,`link`),h$1(t,`link`);let s=this.toRealPath(e),g=this.toRealPath(t),S=this.resolveAndValidate(s,e),w=this.resolveAndValidate(g,t);try{await I.promises.link(S,w)}catch(s){let g=s;if(g.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(g.code===`EEXIST`)throw Error(`EEXIST: file already exists, link '${t}'`);if(g.code===`EPERM`)throw Error(`EPERM: operation not permitted, link '${e}'`);this.sanitizeError(s,e,`link`)}}async readlink(e){h$1(e,`readlink`);let t=this.toRealPath(e),s=this.validateParent(t,e);try{let t=await I.promises.readlink(s),g=c$1(e),S=U.dirname(g),w=U.isAbsolute(t)?t:U.resolve(U.dirname(s),t),E=await I.promises.realpath(w).catch(()=>w);if(d$1(E,this.canonicalRoot)){let e=E.slice(this.canonicalRoot.length)||`/`;return S===`/`?e.startsWith(`/`)?e.slice(1)||`.`:e:U.relative(S,e)}return U.basename(t)}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(s.code===`EINVAL`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);this.sanitizeError(t,e,`readlink`)}}async realpath(e){h$1(e,`realpath`);let t=this.toRealPath(e);try{this.resolveAndValidate(t,e)}catch{throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}let s;try{s=await I.promises.realpath(t)}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, realpath '${e}'`);if(s.code===`ELOOP`)throw Error(`ELOOP: too many levels of symbolic links, realpath '${e}'`);this.sanitizeError(t,e,`realpath`)}if(d$1(s,this.canonicalRoot))return s.slice(this.canonicalRoot.length)||`/`;throw Error(`ENOENT: no such file or directory, realpath '${e}'`)}async utimes(e,t,s){h$1(e,`utimes`);let g=this.toRealPath(e),S=this.resolveAndValidate(g,e);try{let e=this.allowSymlinks?I.constants.O_RDONLY:I.constants.O_RDONLY|I.constants.O_NOFOLLOW,g=await I.promises.open(S,e);try{await g.utimes(t,s)}finally{await g.close()}}catch(t){let s=t;if(s.code===`ENOENT`)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);if(s.code===`ELOOP`)throw Error(`EACCES: permission denied, '${e}' is a symlink`);this.sanitizeError(t,e,`utimes`)}}},require_quote=__commonJSMin$2(((e,t)=>{t.exports=function(e){return e.map(function(e){return e===``?`''`:e&&typeof e==`object`?e.op.replace(/(.)/g,`\\$1`):/["\s\\]/.test(e)&&!/'/.test(e)?`'`+e.replace(/(['])/g,`\\$1`)+`'`:/["'\s]/.test(e)?`"`+e.replace(/(["\\$`!])/g,`\\$1`)+`"`:String(e).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,`$1\\$2`)}).join(` `)}})),require_parse=__commonJSMin$2(((e,t)=>{for(var s=`(?:`+[`\\|\\|`,`\\&\\&`,`;;`,`\\|\\&`,`\\<\\(`,`\\<\\<\\<`,`>>`,`>\\&`,`<\\&`,`[&;()|<>]`].join(`|`)+`)`,g=RegExp(`^`+s+`$`),S=`|&;()<> \\t`,w=`"((\\\\"|[^"])*?)"`,E=`'((\\\\'|[^'])*?)'`,D=/^#$/,O=`'`,k=`"`,j=`$`,F=``,L=4294967296,B=0;B<4;B++)F+=(L*Math.random()).toString(16);var H=RegExp(`^`+F);function q(e,t){for(var s=t.lastIndex,g=[],S;S=t.exec(e);)g.push(S),t.lastIndex===S.index&&(t.lastIndex+=1);return t.lastIndex=s,g}function ee(e,t,s){var g=typeof e==`function`?e(s):e[s];return g===void 0&&s!=``?g=``:g===void 0&&(g=`$`),typeof g==`object`?t+F+JSON.stringify(g)+F:t+g}function J(e,t,F){F||={};var L=F.escape||`\\`,B=`(\\`+L+`['"`+S+`]|[^\\s'"`+S+`])+`,H=q(e,new RegExp([`(`+s+`)`,`(`+B+`|`+w+`|`+E+`)+`].join(`|`),`g`));if(H.length===0)return[];t||={};var J=!1;return H.map(function(s){var S=s[0];if(!S||J)return;if(g.test(S))return{op:S};var w=!1,E=!1,F=``,B=!1,H;function q(){H+=1;var e,s,g=S.charAt(H);if(g===`{`){if(H+=1,S.charAt(H)===`}`)throw Error(`Bad substitution: `+S.slice(H-2,H+1));if(e=S.indexOf(`}`,H),e<0)throw Error(`Bad substitution: `+S.slice(H));s=S.slice(H,e),H=e}else if(/[*@#?$!_-]/.test(g))s=g,H+=1;else{var w=S.slice(H);e=w.match(/[^\w\d_]/),e?(s=w.slice(0,e.index),H+=e.index-1):(s=w,H=S.length)}return ee(t,``,s)}for(H=0;H<S.length;H++){var Y=S.charAt(H);if(B||=!w&&(Y===`*`||Y===`?`),E)F+=Y,E=!1;else if(w)Y===w?w=!1:w==O?F+=Y:Y===L?(H+=1,Y=S.charAt(H),Y===k||Y===L||Y===j?F+=Y:F+=L+Y):Y===j?F+=q():F+=Y;else if(Y===k||Y===O)w=Y;else if(g.test(Y))return{op:S};else if(D.test(Y)){J=!0;var te={comment:e.slice(s.index+H+1)};return F.length?[F,te]:[te]}else Y===L?E=!0:Y===j?F+=q():F+=Y}return B?{op:`glob`,pattern:F}:F}).reduce(function(e,t){return t===void 0?e:e.concat(t)},[])}t.exports=function(e,t,s){var g=J(e,t,s);return typeof t==`function`?g.reduce(function(e,t){if(typeof t==`object`)return e.concat(t);var s=t.split(RegExp(`(`+F+`.*?`+F+`)`,`g`));return s.length===1?e.concat(s[0]):e.concat(s.filter(Boolean).map(function(e){return H.test(e)?JSON.parse(e.split(F)[1]):e}))},[]):g}})),require_shell_quote=__commonJSMin$2((e=>{e.quote=require_quote(),e.parse=require_parse()}));const floor$1=Math.floor,min$1=(e,t)=>e<t?e:t,max$1=(e,t)=>e>t?e:t;Number.isNaN;const BIT8$1=128,BIT18$1=1<<17,BIT19$1=1<<18,BIT20$1=1<<19,BIT21$1=1<<20,BIT22$1=1<<21,BIT23$1=1<<22,BIT24$1=1<<23,BIT25$1=1<<24,BIT26$1=1<<25,BIT27$1=1<<26,BIT28$1=1<<27,BIT29$1=1<<28,BIT30$1=1<<29,BIT31$1=1<<30,BITS7$1=127;BIT18$1-1,BIT19$1-1,BIT20$1-1,BIT21$1-1,BIT22$1-1,BIT23$1-1,BIT24$1-1,BIT25$1-1,BIT26$1-1,BIT27$1-1,BIT28$1-1,BIT29$1-1,BIT30$1-1,BIT31$1-1;const MAX_SAFE_INTEGER$1=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const fromCharCode$1=String.fromCharCode;String.fromCodePoint,fromCharCode$1(65535);const _encodeUtf8Polyfill$1=e=>{let t=unescape(encodeURIComponent(e)),s=t.length,g=new Uint8Array(s);for(let e=0;e<s;e++)g[e]=t.codePointAt(e);return g},utf8TextEncoder$1=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native$1=e=>utf8TextEncoder$1.encode(e),encodeUtf8$1=utf8TextEncoder$1?_encodeUtf8Native$1:_encodeUtf8Polyfill$1;let utf8TextDecoder$1=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder$1&&utf8TextDecoder$1.decode(new Uint8Array).length===1&&(utf8TextDecoder$1=null);const write$1=(e,t)=>{let s=e.cbuf.length;e.cpos===s&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(s*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeVarUint$1=(e,t)=>{for(;t>BITS7$1;)write$1(e,BIT8$1|BITS7$1&t),t=floor$1(t/128);write$1(e,BITS7$1&t)},_strBuffer$1=new Uint8Array(3e4),_maxStrBSize$1=_strBuffer$1.length/3,_writeVarStringNative$1=(e,t)=>{if(t.length<_maxStrBSize$1){let s=utf8TextEncoder$1.encodeInto(t,_strBuffer$1).written||0;writeVarUint$1(e,s);for(let t=0;t<s;t++)write$1(e,_strBuffer$1[t])}else writeVarUint8Array$1(e,encodeUtf8$1(t))},_writeVarStringPolyfill$1=(e,t)=>{let s=unescape(encodeURIComponent(t)),g=s.length;writeVarUint$1(e,g);for(let t=0;t<g;t++)write$1(e,s.codePointAt(t))},writeVarString$1=utf8TextEncoder$1&&utf8TextEncoder$1.encodeInto?_writeVarStringNative$1:_writeVarStringPolyfill$1,writeUint8Array$1=(e,t)=>{let s=e.cbuf.length,g=e.cpos,S=min$1(s-g,t.length),w=t.length-S;e.cbuf.set(t.subarray(0,S),g),e.cpos+=S,w>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max$1(s*2,w)),e.cbuf.set(t.subarray(S)),e.cpos=w)},writeVarUint8Array$1=(e,t)=>{writeVarUint$1(e,t.byteLength),writeUint8Array$1(e,t)},create$3=e=>Error(e),errorUnexpectedEndOfArray$1=create$3(`Unexpected end of array`),errorIntegerOutOfRange$1=create$3(`Integer out of Range`);let AuthMessageType=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const writePermissionDenied=(e,t)=>{writeVarUint$1(e,AuthMessageType.PermissionDenied),writeVarString$1(e,t)},writeAuthenticated=(e,t)=>{writeVarUint$1(e,AuthMessageType.Authenticated),writeVarString$1(e,t)},writeTokenSyncRequest=e=>{writeVarUint$1(e,AuthMessageType.Token)},ResetConnection={code:4205,reason:`Reset Connection`},Unauthorized={code:4401,reason:`Unauthorized`},Forbidden={code:4403,reason:`Forbidden`},ConnectionTimeout={code:4408,reason:`Connection Timeout`},awarenessStatesToArray=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var SkipFurtherHooksError=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let WsReadyStates=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});const E_CANCELED=Error(`request for lock canceled`);var __awaiter$2=function(e,t,s,g){function S(e){return e instanceof s?e:new s(function(t){t(e)})}return new(s||=Promise)(function(s,w){function E(e){try{O(g.next(e))}catch(e){w(e)}}function D(e){try{O(g.throw(e))}catch(e){w(e)}}function O(e){e.done?s(e.value):S(e.value).then(E,D)}O((g=g.apply(e,t||[])).next())})},Semaphore=class{constructor(e,t=E_CANCELED){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((s,g)=>{let S={resolve:s,reject:g,weight:e,priority:t},w=findIndexFromEnd(this._queue,e=>t<=e.priority);w===-1&&e<=this._value?this._dispatchItem(S):this._queue.splice(w+1,0,S)})}runExclusive(e){return __awaiter$2(this,arguments,void 0,function*(e,t=1,s=0){let[g,S]=yield this.acquire(t,s);try{return yield e(g)}finally{S()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(s=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),insertSorted(this._weightedWaiters[e-1],{resolve:s,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let s=this._weightedWaiters[t-1];if(!s)continue;let g=s.findIndex(t=>t.priority<=e);(g===-1?s:s.splice(0,g)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function insertSorted(e,t){let s=findIndexFromEnd(e,e=>t.priority<=e.priority);e.splice(s+1,0,t)}function findIndexFromEnd(e,t){for(let s=e.length-1;s>=0;s--)if(t(e[s]))return s;return-1}var __awaiter$1=function(e,t,s,g){function S(e){return e instanceof s?e:new s(function(t){t(e)})}return new(s||=Promise)(function(s,w){function E(e){try{O(g.next(e))}catch(e){w(e)}}function D(e){try{O(g.throw(e))}catch(e){w(e)}}function O(e){e.done?s(e.value):S(e.value).then(E,D)}O((g=g.apply(e,t||[])).next())})},Mutex=class{constructor(e){this._semaphore=new Semaphore(1,e)}acquire(){return __awaiter$1(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};let FORCE_COLOR,NODE_DISABLE_COLORS,NO_COLOR,TERM,isTTY=!0;typeof process<`u`&&({FORCE_COLOR,NODE_DISABLE_COLORS,NO_COLOR,TERM}=process.env||{},isTTY=process.stdout&&process.stdout.isTTY);const $={enabled:!NODE_DISABLE_COLORS&&NO_COLOR==null&&TERM!==`dumb`&&(FORCE_COLOR!=null&&FORCE_COLOR!==`0`||isTTY),reset:init(0,0),bold:init(1,22),dim:init(2,22),italic:init(3,23),underline:init(4,24),inverse:init(7,27),hidden:init(8,28),strikethrough:init(9,29),black:init(30,39),red:init(31,39),green:init(32,39),yellow:init(33,39),blue:init(34,39),magenta:init(35,39),cyan:init(36,39),white:init(37,39),gray:init(90,39),grey:init(90,39),bgBlack:init(40,49),bgRed:init(41,49),bgGreen:init(42,49),bgYellow:init(43,49),bgBlue:init(44,49),bgMagenta:init(45,49),bgCyan:init(46,49),bgWhite:init(47,49)};function run(e,t){let s=0,g,S=``,w=``;for(;s<e.length;s++)g=e[s],S+=g.open,w+=g.close,~t.indexOf(g.close)&&(t=t.replace(g.rgx,g.close+g.open));return S+t+w}function chain(e,t){let s={has:e,keys:t};return s.reset=$.reset.bind(s),s.bold=$.bold.bind(s),s.dim=$.dim.bind(s),s.italic=$.italic.bind(s),s.underline=$.underline.bind(s),s.inverse=$.inverse.bind(s),s.hidden=$.hidden.bind(s),s.strikethrough=$.strikethrough.bind(s),s.black=$.black.bind(s),s.red=$.red.bind(s),s.green=$.green.bind(s),s.yellow=$.yellow.bind(s),s.blue=$.blue.bind(s),s.magenta=$.magenta.bind(s),s.cyan=$.cyan.bind(s),s.white=$.white.bind(s),s.gray=$.gray.bind(s),s.grey=$.grey.bind(s),s.bgBlack=$.bgBlack.bind(s),s.bgRed=$.bgRed.bind(s),s.bgGreen=$.bgGreen.bind(s),s.bgYellow=$.bgYellow.bind(s),s.bgBlue=$.bgBlue.bind(s),s.bgMagenta=$.bgMagenta.bind(s),s.bgCyan=$.bgCyan.bind(s),s.bgWhite=$.bgWhite.bind(s),s}function init(e,t){let s={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(s)),t===void 0?this:$.enabled?run(this.keys,t+``):t+``):t===void 0?chain([e],[s]):$.enabled?run([s],t+``):t+``}}const BIT8=128,BIT18=1<<17,BIT19=1<<18,BIT20=1<<19,BIT21=1<<20,BIT22=1<<21,BIT23=1<<22,BIT24=1<<23,BIT25=1<<24,BIT26=1<<25,BIT27=1<<26,BIT28=1<<27,BIT29=1<<28,BIT30=1<<29,BIT31=1<<30,BITS7=127;BIT18-1,BIT19-1,BIT20-1,BIT21-1,BIT22-1,BIT23-1,BIT24-1,BIT25-1,BIT26-1,BIT27-1,BIT28-1,BIT29-1,BIT30-1,BIT31-1;const floor=Math.floor,min=(e,t)=>e<t?e:t,max=(e,t)=>e>t?e:t;Number.isNaN;const MAX_SAFE_INTEGER=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const create$2=()=>new Set,from=Array.from;Array.isArray;const fromCharCode=String.fromCharCode;String.fromCodePoint,fromCharCode(65535);const _encodeUtf8Polyfill=e=>{let t=unescape(encodeURIComponent(e)),s=t.length,g=new Uint8Array(s);for(let e=0;e<s;e++)g[e]=t.codePointAt(e);return g},utf8TextEncoder=typeof TextEncoder<`u`?new TextEncoder:null,_encodeUtf8Native=e=>utf8TextEncoder.encode(e),encodeUtf8=utf8TextEncoder?_encodeUtf8Native:_encodeUtf8Polyfill;let utf8TextDecoder=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});utf8TextDecoder&&utf8TextDecoder.decode(new Uint8Array).length===1&&(utf8TextDecoder=null);const create$1=e=>Error(e);var Encoder=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const createEncoder=()=>new Encoder,length=e=>{let t=e.cpos;for(let s=0;s<e.bufs.length;s++)t+=e.bufs[s].length;return t},toUint8Array=e=>{let t=new Uint8Array(length(e)),s=0;for(let g=0;g<e.bufs.length;g++){let S=e.bufs[g];t.set(S,s),s+=S.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),s),t},write=(e,t)=>{let s=e.cbuf.length;e.cpos===s&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(s*2),e.cpos=0),e.cbuf[e.cpos++]=t},writeVarUint=(e,t)=>{for(;t>BITS7;)write(e,BIT8|BITS7&t),t=floor(t/128);write(e,BITS7&t)},_strBuffer=new Uint8Array(3e4),_maxStrBSize=_strBuffer.length/3,_writeVarStringNative=(e,t)=>{if(t.length<_maxStrBSize){let s=utf8TextEncoder.encodeInto(t,_strBuffer).written||0;writeVarUint(e,s);for(let t=0;t<s;t++)write(e,_strBuffer[t])}else writeVarUint8Array(e,encodeUtf8(t))},_writeVarStringPolyfill=(e,t)=>{let s=unescape(encodeURIComponent(t)),g=s.length;writeVarUint(e,g);for(let t=0;t<g;t++)write(e,s.codePointAt(t))},writeVarString=utf8TextEncoder&&utf8TextEncoder.encodeInto?_writeVarStringNative:_writeVarStringPolyfill,writeUint8Array=(e,t)=>{let s=e.cbuf.length,g=e.cpos,S=min(s-g,t.length),w=t.length-S;e.cbuf.set(t.subarray(0,S),g),e.cpos+=S,w>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(max(s*2,w)),e.cbuf.set(t.subarray(S)),e.cpos=w)},writeVarUint8Array=(e,t)=>{writeVarUint(e,t.byteLength),writeUint8Array(e,t)},errorUnexpectedEndOfArray=create$1(`Unexpected end of array`),errorIntegerOutOfRange=create$1(`Integer out of Range`);var Decoder=class{constructor(e){this.arr=e,this.pos=0}};const createDecoder=e=>new Decoder(e),hasContent=e=>e.pos!==e.arr.length,readUint8Array=(e,t)=>{let s=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,s},readVarUint8Array=e=>readUint8Array(e,readVarUint(e)),readUint8=e=>e.arr[e.pos++],readVarUint=e=>{let t=0,s=1,g=e.arr.length;for(;e.pos<g;){let g=e.arr[e.pos++];if(t+=(g&BITS7)*s,s*=128,g<BIT8)return t;if(t>MAX_SAFE_INTEGER)throw errorIntegerOutOfRange}throw errorUnexpectedEndOfArray},_readVarStringPolyfill=e=>{let t=readVarUint(e);if(t===0)return``;{let s=String.fromCodePoint(readUint8(e));if(--t<100)for(;t--;)s+=String.fromCodePoint(readUint8(e));else for(;t>0;){let g=t<1e4?t:1e4,S=e.arr.subarray(e.pos,e.pos+g);e.pos+=g,s+=String.fromCodePoint.apply(null,S),t-=g}return decodeURIComponent(escape(s))}},_readVarStringNative=e=>utf8TextDecoder.decode(readVarUint8Array(e)),readVarString=utf8TextDecoder?_readVarStringNative:_readVarStringPolyfill;var IncomingMessage=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=createDecoder(e)}get encoder(){return this.encoderInternal||=createEncoder(),this.encoderInternal}readVarUint8Array(){return readVarUint8Array(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=readVarUint8Array(this.decoder);return this.decoder.pos=e,t}readVarUint(){return readVarUint(this.decoder)}readVarString(){return readVarString(this.decoder)}toUint8Array(){return toUint8Array(this.encoder)}writeVarUint(e){writeVarUint(this.encoder,e)}writeVarString(e){writeVarString(this.encoder,e)}get length(){return length(this.encoder)}};const getUnixTime=Date.now,create=()=>new Map,setIfUndefined=(e,t,s)=>{let g=e.get(t);return g===void 0&&e.set(t,g=s()),g};var Observable=class{constructor(){this._observers=create()}on(e,t){setIfUndefined(this._observers,e,create$2).add(t)}once(e,t){let s=(...g)=>{this.off(e,s),t(...g)};this.on(e,s)}off(e,t){let s=this._observers.get(e);s!==void 0&&(s.delete(t),s.size===0&&this._observers.delete(e))}emit(e,t){return from((this._observers.get(e)||create()).values()).forEach(e=>e(...t))}destroy(){this._observers=create()}};const EqualityTraitSymbol=Symbol(`Equality`),keys=Object.keys,size=e=>keys(e).length,hasProperty=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),equalityDeep=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[EqualityTraitSymbol]!=null)return e[EqualityTraitSymbol](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let s=0;s<e.length;s++)if(e[s]!==t[s])return!1;break;case Set:if(e.size!==t.size)return!1;for(let s of e)if(!t.has(s))return!1;break;case Map:if(e.size!==t.size)return!1;for(let s of e.keys())if(!t.has(s)||!equalityDeep(e.get(s),t.get(s)))return!1;break;case void 0:case Object:if(size(e)!==size(t))return!1;for(let s in e)if(!hasProperty(e,s)||!equalityDeep(e[s],t[s]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!equalityDeep(e[s],t[s]))return!1;break;default:return!1}return!0},outdatedTimeout=3e4;var Awareness=class extends Observable{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=getUnixTime();this.getLocalState()!==null&&outdatedTimeout/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((s,g)=>{g!==this.clientID&&outdatedTimeout<=e-s.lastUpdated&&this.states.has(g)&&t.push(g)}),t.length>0&&removeAwarenessStates(this,t,`timeout`)},floor(outdatedTimeout/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,s=this.meta.get(t),g=s===void 0?0:s.clock+1,S=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:g,lastUpdated:getUnixTime()});let w=[],E=[],D=[],O=[];e===null?O.push(t):S==null?e!=null&&w.push(t):(E.push(t),equalityDeep(S,e)||D.push(t)),(w.length>0||D.length>0||O.length>0)&&this.emit(`change`,[{added:w,updated:D,removed:O},`local`]),this.emit(`update`,[{added:w,updated:E,removed:O},`local`])}setLocalStateField(e,t){let s=this.getLocalState();s!==null&&this.setLocalState({...s,[e]:t})}getStates(){return this.states}};const removeAwarenessStates=(e,t,s)=>{let g=[];for(let s=0;s<t.length;s++){let S=t[s];if(e.states.has(S)){if(e.states.delete(S),S===e.clientID){let t=e.meta.get(S);e.meta.set(S,{clock:t.clock+1,lastUpdated:getUnixTime()})}g.push(S)}}g.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:g},s]),e.emit(`update`,[{added:[],updated:[],removed:g},s]))},encodeAwarenessUpdate=(e,t,s=e.states)=>{let g=t.length,S=createEncoder();writeVarUint(S,g);for(let w=0;w<g;w++){let g=t[w],E=s.get(g)||null,D=e.meta.get(g).clock;writeVarUint(S,g),writeVarUint(S,D),writeVarString(S,JSON.stringify(E))}return toUint8Array(S)},applyAwarenessUpdate=(e,t,s)=>{let g=createDecoder(t),S=getUnixTime(),w=[],E=[],D=[],O=[],k=readVarUint(g);for(let t=0;t<k;t++){let t=readVarUint(g),s=readVarUint(g),k=JSON.parse(readVarString(g)),j=e.meta.get(t),F=e.states.get(t),L=j===void 0?0:j.clock;(L<s||L===s&&k===null&&e.states.has(t))&&(k===null?t===e.clientID&&e.getLocalState()!=null?s++:e.states.delete(t):e.states.set(t,k),e.meta.set(t,{clock:s,lastUpdated:S}),j===void 0&&k!==null?w.push(t):j!==void 0&&k===null?O.push(t):k!==null&&(equalityDeep(k,F)||D.push(t),E.push(t)))}(w.length>0||D.length>0||O.length>0)&&e.emit(`change`,[{added:w,updated:D,removed:O},s]),(w.length>0||E.length>0||O.length>0)&&e.emit(`update`,[{added:w,updated:E,removed:O},s])},messageYjsSyncStep1=0,messageYjsSyncStep2=1,messageYjsUpdate=2,writeSyncStep1=(e,t)=>{writeVarUint(e,messageYjsSyncStep1),writeVarUint8Array(e,encodeStateVector(t))},writeSyncStep2=(e,t,s)=>{writeVarUint(e,messageYjsSyncStep2),writeVarUint8Array(e,encodeStateAsUpdate(t,s))},readSyncStep1=(e,t,s)=>writeSyncStep2(t,s,readVarUint8Array(e)),readSyncStep2=(e,t,s,g)=>{try{applyUpdate(t,readVarUint8Array(e),s)}catch(e){g?.(e),console.error(`Caught error while handling a Yjs update`,e)}},writeUpdate=(e,t)=>{writeVarUint(e,messageYjsUpdate),writeVarUint8Array(e,t)},readUpdate=readSyncStep2;function isTransactionOrigin(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function shouldSkipStoreHooks(e){if(!isTransactionOrigin(e))return!1;switch(e.source){case`connection`:return!1;case`redis`:return!0;case`local`:return e.skipStoreHooks??!1}}let MessageType=function(e){return e[e.Unknown=-1]=`Unknown`,e[e.Sync=0]=`Sync`,e[e.Awareness=1]=`Awareness`,e[e.Auth=2]=`Auth`,e[e.QueryAwareness=3]=`QueryAwareness`,e[e.SyncReply=4]=`SyncReply`,e[e.Stateless=5]=`Stateless`,e[e.BroadcastStateless=6]=`BroadcastStateless`,e[e.CLOSE=7]=`CLOSE`,e[e.SyncStatus=8]=`SyncStatus`,e[e.Ping=9]=`Ping`,e[e.Pong=10]=`Pong`,e}({});var OutgoingMessage=class{constructor(e){this.encoder=createEncoder(),writeVarString(this.encoder,e)}createSyncMessage(){return this.type=MessageType.Sync,writeVarUint(this.encoder,MessageType.Sync),this}createSyncReplyMessage(){return this.type=MessageType.SyncReply,writeVarUint(this.encoder,MessageType.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=MessageType.Awareness,this.category=`Update`;let s=encodeAwarenessUpdate(e,t||Array.from(e.getStates().keys()));return writeVarUint(this.encoder,MessageType.Awareness),writeVarUint8Array(this.encoder,s),this}writeQueryAwareness(){return this.type=MessageType.QueryAwareness,this.category=`Update`,writeVarUint(this.encoder,MessageType.QueryAwareness),this}writeTokenSyncRequest(){return this.type=MessageType.Auth,this.category=`TokenSync`,writeVarUint(this.encoder,MessageType.Auth),writeTokenSyncRequest(this.encoder),this}writeAuthenticated(e){return this.type=MessageType.Auth,this.category=`Authenticated`,writeVarUint(this.encoder,MessageType.Auth),writeAuthenticated(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=MessageType.Auth,this.category=`PermissionDenied`,writeVarUint(this.encoder,MessageType.Auth),writePermissionDenied(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,writeSyncStep1(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,writeUpdate(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,writeVarUint(this.encoder,MessageType.Stateless),writeVarString(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,writeVarUint(this.encoder,MessageType.BroadcastStateless),writeVarString(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,writeVarUint(this.encoder,MessageType.SyncStatus),writeVarUint(this.encoder,e?1:0),this}writeCloseMessage(e){return this.type=MessageType.CLOSE,writeVarUint(this.encoder,MessageType.CLOSE),writeVarString(this.encoder,e),this}toUint8Array(){return toUint8Array(this.encoder)}},MessageReceiver=class{constructor(e,t){this.message=e,this.defaultTransactionOrigin=t}async apply(e,t,s){let{message:g}=this,S=g.readVarUint(),w=g.length;switch(S){case MessageType.Sync:case MessageType.SyncReply:g.writeVarUint(MessageType.Sync),await this.readSyncMessage(g,e,t,s,S!==MessageType.SyncReply),g.length>w+1&&(s?s(g.toUint8Array()):t&&t.send(g.toUint8Array()));break;case MessageType.Awareness:applyAwarenessUpdate(e.awareness,g.readVarUint8Array(),t??null);break;case MessageType.QueryAwareness:this.applyQueryAwarenessMessage(e,t,s);break;case MessageType.Stateless:t?.callbacks.statelessCallback({connection:t,documentName:e.name,document:e,payload:readVarString(g.decoder)});break;case MessageType.BroadcastStateless:{let t=g.readVarString();e.getConnections().forEach(e=>{e.sendStateless(t)});break}case MessageType.CLOSE:t?.close({code:1e3,reason:`provider_initiated`});break;case MessageType.Auth:if(g.readVarUint()===AuthMessageType.Token){t?.callbacks.onTokenSyncCallback({token:g.readVarString()});break}console.error(`Received an authentication message on a connection that is already fully authenticated. Probably your provider has been destroyed + recreated really fast.`);break;default:console.error(`Unable to handle message of type ${S}: no handler defined! Are your provider/server versions aligned?`)}}async readSyncMessage(e,t,s,g,S=!0){let w=e.readVarUint(),E=s?.messageAddress??t.name;switch(s&&await s.callbacks.beforeSync(s,{type:w,payload:e.peekVarUint8Array()}),w){case messageYjsSyncStep1:if(readSyncStep1(e.decoder,e.encoder,t),g&&S)g(new OutgoingMessage(E).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(s){let e=new OutgoingMessage(E).createSyncMessage().writeFirstSyncStepFor(t);s.send(e.toUint8Array())}break;case messageYjsSyncStep2:if(s?.readOnly){if(snapshotContainsUpdate(snapshot(t),readVarUint8Array(e.decoder))){let e=new OutgoingMessage(E).writeSyncStatus(!0);s.send(e.toUint8Array())}else{let e=new OutgoingMessage(E).writeSyncStatus(!1);s.send(e.toUint8Array())}break}readSyncStep2(e.decoder,t,s?{source:`connection`,connection:s}:this.defaultTransactionOrigin??{source:`local`}),s&&s.send(new OutgoingMessage(E).writeSyncStatus(!0).toUint8Array());break;case messageYjsUpdate:if(s?.readOnly){s.send(new OutgoingMessage(E).writeSyncStatus(!1).toUint8Array());break}readUpdate(e.decoder,t,s?{source:`connection`,connection:s}:this.defaultTransactionOrigin??{source:`local`}),s&&s.send(new OutgoingMessage(E).writeSyncStatus(!0).toUint8Array());break;default:throw Error(`Received a message with an unknown type: ${w}`)}return w}applyQueryAwarenessMessage(e,t,s){let g=new OutgoingMessage(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);s&&s(g.toUint8Array())}},Connection=class{get messageAddress(){return this.sessionId?`${this.document.name}\0${this.sessionId}`:this.document.name}constructor(e,t,s,g,S,w=!1,E,D){this.callbacks={onClose:[(e,t)=>{}],beforeHandleMessage:(e,t)=>Promise.resolve(),beforeSync:(e,t)=>Promise.resolve(),statelessCallback:e=>Promise.resolve(),onTokenSyncCallback:e=>Promise.resolve()},this.messageQueue=[],this.processingPromise=Promise.resolve(),this.webSocket=e,this.context=S,this.document=s,this.request=t,this.socketId=g,this.readOnly=w,this.sessionId=E??null,this.providerVersion=D??null,this.document.addConnection(this),this.sendCurrentAwareness()}onClose(e){return this.callbacks.onClose.push(e),this}onStatelessCallback(e){return this.callbacks.statelessCallback=e,this}beforeHandleMessage(e){return this.callbacks.beforeHandleMessage=e,this}beforeSync(e){return this.callbacks.beforeSync=e,this}onTokenSyncCallback(e){return this.callbacks.onTokenSyncCallback=e,this}waitForPendingMessages(){return this.processingPromise}send(e){if(this.webSocket.readyState===WsReadyStates.Closing||this.webSocket.readyState===WsReadyStates.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new OutgoingMessage(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new OutgoingMessage(this.messageAddress).writeTokenSyncRequest();this.send(e.toUint8Array())}close(e){if(this.document.hasConnection(this)){this.document.removeConnection(this),this.callbacks.onClose.forEach(t=>t(this.document,e));let t=new OutgoingMessage(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new OutgoingMessage(this.messageAddress).createAwarenessUpdateMessage(this.document.awareness);this.send(e.toUint8Array())}handleMessage(e){this.messageQueue.push(e),this.messageQueue.length===1&&(this.processingPromise=this.processMessages())}async processMessages(){for(;this.messageQueue.length>0;){let e=this.messageQueue.at(0),t=new IncomingMessage(e),s=t.readVarString(),g=s.indexOf(`\0`),S=g===-1?s:s.substring(0,g);if(S!==this.document.name){this.messageQueue.shift();continue}t.writeVarString(this.messageAddress);try{await this.callbacks.beforeHandleMessage(this,e),await new MessageReceiver(t).apply(this.document,this)}catch(e){console.error(`closing connection ${this.socketId} (while handling ${S}) because of exception`,e),this.close({code:`code`in e&&typeof e.code==`number`?e.code:ResetConnection.code,reason:`reason`in e?e.reason:ResetConnection.reason})}this.messageQueue.shift()}}},Document=class extends Doc{constructor(e,t){super(t),this.callbacks={onUpdate:(e,t,s)=>{},beforeBroadcastStateless:(e,t)=>{}},this.connections=new Map,this.directConnectionsCount=0,this.isDestroyed=!1,this.saveMutex=new Mutex,this.lastChangeTime=0,this.name=e,this.awareness=new Awareness(this),this.awareness.setLocalState(null),this.awareness.on(`update`,this.handleAwarenessUpdate.bind(this)),this.on(`update`,this.handleUpdate.bind(this)),this.isLoading=!0}isEmpty(e){return!this.get(e)._start&&!this.get(e)._map.size}merge(e){return(Array.isArray(e)?e:[e]).forEach(e=>{applyUpdate(this,encodeStateAsUpdate(e))}),this}onUpdate(e){return this.callbacks.onUpdate=e,this}beforeBroadcastStateless(e){return this.callbacks.beforeBroadcastStateless=e,this}addConnection(e){return this.connections.set(e,{clients:new Set}),this}hasConnection(e){return this.connections.has(e)}removeConnection(e){let t=this.connections.get(e);return t&&removeAwarenessStates(this.awareness,Array.from(t.clients),null),this.connections.delete(e),this}addDirectConnection(){return this.directConnectionsCount+=1,this}removeDirectConnection(){return this.directConnectionsCount>0&&--this.directConnectionsCount,this}getConnectionsCount(){return this.connections.size+this.directConnectionsCount}getConnections(){return Array.from(this.connections.keys())}getClients(e){let t=this.connections.get(e);return t?.clients===void 0?new Set:t.clients}hasAwarenessStates(){return this.awareness.getStates().size>0}applyAwarenessUpdate(e,t){return applyAwarenessUpdate(this.awareness,t,e),this}handleAwarenessUpdate({added:e,updated:t,removed:s},g){let S=e.concat(t,s);if(g!==null){let t=this.connections.get(g);t&&(e.forEach(e=>t.clients.add(e)),s.forEach(e=>t.clients.delete(e)))}for(let e of this.getConnections()){let t=new OutgoingMessage(e.messageAddress).createAwarenessUpdateMessage(this.awareness,S);e.send(t.toUint8Array())}return this}handleUpdate(e,t){this.callbacks.onUpdate(this,t,e);for(let t of this.getConnections()){let s=new OutgoingMessage(t.messageAddress).createSyncMessage().writeUpdate(e);t.send(s.toUint8Array())}return this}broadcastStateless(e,t){this.callbacks.beforeBroadcastStateless(this,e),(t?this.getConnections().filter(t):this.getConnections()).forEach(t=>{t.sendStateless(e)})}destroy(){super.destroy(),this.isDestroyed=!0}},version=`4.0.0-rc.1`;function getParameters(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var ClientConnection=class{constructor(e,t,s,g,S,w={}){this.websocket=e,this.request=t,this.documentProvider=s,this.hooks=g,this.opts=S,this.defaultContext=w,this.documentConnections={},this.incomingMessageQueue={},this.documentConnectionsEstablished=new Set,this.hookPayloads={},this.callbacks={onClose:[(e,t)=>{}]},this.socketId=crypto$1.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(ConnectionTimeout)},this.setUpNewConnection=async(e,t,s)=>{let g=this.hookPayloads[e],S=await this.documentProvider.createDocument(t,g.request,g.socketId,g.connectionConfig,g.context),w=this.createConnection(this.websocket,S,g,s,g.providerVersion);if(w.onClose((t,s)=>{delete this.hookPayloads[e],delete this.documentConnections[e],delete this.incomingMessageQueue[e],this.documentConnectionsEstablished.delete(e)}),w.onTokenSyncCallback(async e=>{try{return await this.hooks(`onTokenSync`,{...g,...e,document:S,connection:w,documentName:t},e=>{g.context={...g.context,...e}})}catch(e){console.error(e);let t={...Unauthorized,...e};w.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=w,this.websocket.readyState===WsReadyStates.Closing||this.websocket.readyState===WsReadyStates.Closed){this.close();return}this.incomingMessageQueue[e]?.forEach(e=>{w.handleMessage(e)}),await this.hooks(`connected`,{...g,documentName:t,context:g.context,connection:w})},this.handleQueueingMessage=async(e,t,s)=>{try{let g=new IncomingMessage(e);if(readVarString(g.decoder),!(readVarUint(g.decoder)===MessageType.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),readVarUint(g.decoder);let S=readVarString(g.decoder),w=null;hasContent(g.decoder)&&(w=readVarString(g.decoder));let E=t.indexOf(`\0`),D=E===-1?null:t.substring(E+1),O=t;try{let e=this.hookPayloads[t];e.providerVersion=w,await this.hooks(`onConnect`,{...e,documentName:s},t=>{e.context={...e.context,...t}}),await this.hooks(`onAuthenticate`,{token:S,...e,documentName:s},t=>{e.context={...e.context,...t}}),e.connectionConfig.isAuthenticated=!0;let g=new OutgoingMessage(O).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(g.toUint8Array()),await this.setUpNewConnection(t,s,D)}catch(e){let s=e||Forbidden,g=new OutgoingMessage(O).writePermissionDenied(s.reason??`permission-denied`);this.websocket.send(g.toUint8Array()),this.documentConnectionsEstablished.delete(t),delete this.hookPayloads[t],delete this.incomingMessageQueue[t]}}catch(e){console.error(e),this.websocket.close(ResetConnection.code,ResetConnection.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=readVarString(new IncomingMessage(e).decoder),s=t.indexOf(`\0`),g=s===-1?t:t.substring(0,s),S=this.documentConnections[t]??this.documentConnections[g];if(S){S.handleMessage(e);return}if(this.incomingMessageQueue[t]===void 0){if(this.incomingMessageQueue[t]=[],this.hookPayloads[t])throw Error(`first message, but hookPayloads exists`);this.hookPayloads[t]={instance:this.documentProvider,request:this.request,connectionConfig:{readOnly:!1,isAuthenticated:!1},requestHeaders:this.request.headers,requestParameters:getParameters(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,g)}catch(e){console.error(e),this.websocket.close(Unauthorized.code,Unauthorized.reason)}},this.timeout=S.timeout,this.pingInterval=setInterval(this.check,this.timeout)}handleClose(e){this.close(e),clearInterval(this.pingInterval)}close(e){Object.values(this.documentConnections).forEach(t=>t.close(e))}onClose(e){return this.callbacks.onClose.push(e),this}createConnection(e,t,s,g,S){let w=new Connection(e,s.request,t,s.socketId,s.context,s.connectionConfig.readOnly,g,S);return w.onClose(async(e,t)=>{await w.waitForPendingMessages();let g={instance:this.documentProvider,clientsCount:e.getConnectionsCount(),context:s.context,document:e,socketId:s.socketId,documentName:e.name,requestHeaders:s.request.headers,requestParameters:getParameters(s.request)};await this.hooks(`onDisconnect`,g),this.callbacks.onClose.forEach(t=>t(e,g))}),w.onStatelessCallback(async e=>{try{return await this.hooks(`onStateless`,e)}catch(e){if(e?.message)throw e}}),w.beforeHandleMessage((e,g)=>{let S={instance:this.documentProvider,clientsCount:t.getConnectionsCount(),context:s.context,document:t,socketId:s.socketId,connection:e,documentName:t.name,requestHeaders:s.request.headers,requestParameters:getParameters(s.request),update:g};return this.hooks(`beforeHandleMessage`,S)}),w.beforeSync((e,g)=>{let S={clientsCount:t.getConnectionsCount(),context:s.context,document:t,documentName:t.name,connection:e,type:g.type,payload:g.payload};return this.hooks(`beforeSync`,S)}),w}},DirectConnection=class{constructor(e,t,s){this.document=null,this.document=e,this.instance=t,this.context=s??{},this.document.addDirectConnection()}async transact(e){if(!this.document)throw Error(`direct connection closed`);this.document.transact(t=>{e(this.document)},{source:`local`,context:this.context})}async disconnect(){this.document&&=(this.document?.removeDirectConnection(),await this.instance.storeDocumentHooks(this.document,{clientsCount:this.document.getConnectionsCount(),lastContext:this.context,lastTransactionOrigin:{source:`local`,context:this.context},document:this.document,documentName:this.document.name,instance:this.instance},!0),this.document.getConnectionsCount()===0&&!this.document.saveMutex.isLocked()&&(await this.instance.hooks(`onDisconnect`,{instance:this.instance,clientsCount:this.document.getConnectionsCount(),context:this.context,document:this.document,socketId:`server`,documentName:this.document.name,requestHeaders:new Headers,requestParameters:new URLSearchParams$1}),await this.instance.unloadDocument(this.document)),null)}};const useDebounce=()=>{let e=new Map,t=new Map;return{debounce:async(s,g,S,w)=>{let E=e.get(s),D=E?.start||Date.now(),O=async()=>{t.has(s)&&await t.get(s),e.delete(s);let S=g();t.set(s,S);let w=await S;return t.delete(s),w};if(E?.timeout&&clearTimeout(E.timeout),S===0||Date.now()-D>=w)return O();e.set(s,{start:D,timeout:setTimeout(O,S),func:O})},isDebounced:t=>e.has(t),isCurrentlyExecuting:e=>t.has(e),executeNow:t=>{let s=e.get(t);if(s)return clearTimeout(s.timeout),s.func()}}},defaultConfiguration={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var Hocuspocus=class{constructor(e){this.configuration={...defaultConfiguration,extensions:[],onConfigure:()=>new Promise(e=>e(null)),onListen:()=>new Promise(e=>e(null)),onUpgrade:()=>new Promise(e=>e(null)),onConnect:()=>new Promise(e=>e(null)),connected:()=>new Promise(e=>e(null)),beforeHandleMessage:()=>new Promise(e=>e(null)),beforeSync:()=>new Promise(e=>e(null)),beforeBroadcastStateless:()=>new Promise(e=>e(null)),onStateless:()=>new Promise(e=>e(null)),onChange:()=>new Promise(e=>e(null)),onCreateDocument:()=>new Promise(e=>e(null)),onLoadDocument:()=>new Promise(e=>e(null)),onStoreDocument:()=>new Promise(e=>e(null)),afterStoreDocument:()=>new Promise(e=>e(null)),onAwarenessUpdate:()=>new Promise(e=>e(null)),onRequest:()=>new Promise(e=>e(null)),onDisconnect:()=>new Promise(e=>e(null)),onDestroy:()=>new Promise(e=>e(null))},this.loadingDocuments=new Map,this.unloadingDocuments=new Map,this.documents=new Map,this.debouncer=useDebounce(),e&&this.configure(e)}configure(e){return this.configuration={...this.configuration,...e},this.configuration.extensions.sort((e,t)=>{let s=e.priority===void 0?100:e.priority,g=t.priority===void 0?100:t.priority;return s>g?-1:s<g?1:0}),this.configuration.extensions.push({onConfigure:this.configuration.onConfigure,onListen:this.configuration.onListen,onUpgrade:this.configuration.onUpgrade,onConnect:this.configuration.onConnect,connected:this.configuration.connected,onAuthenticate:this.configuration.onAuthenticate,onTokenSync:this.configuration.onTokenSync,onLoadDocument:this.configuration.onLoadDocument,afterLoadDocument:this.configuration.afterLoadDocument,beforeHandleMessage:this.configuration.beforeHandleMessage,beforeBroadcastStateless:this.configuration.beforeBroadcastStateless,beforeSync:this.configuration.beforeSync,onStateless:this.configuration.onStateless,onChange:this.configuration.onChange,onStoreDocument:this.configuration.onStoreDocument,afterStoreDocument:this.configuration.afterStoreDocument,onAwarenessUpdate:this.configuration.onAwarenessUpdate,onRequest:this.configuration.onRequest,beforeUnloadDocument:this.configuration.beforeUnloadDocument,afterUnloadDocument:this.configuration.afterUnloadDocument,onDisconnect:this.configuration.onDisconnect,onDestroy:this.configuration.onDestroy}),this.hooks(`onConfigure`,{configuration:this.configuration,version,instance:this}),this}getDocumentsCount(){return this.documents.size}getConnectionsCount(){let e=new Set,t=Array.from(this.documents.values()).reduce((t,s)=>(s.getConnections().forEach(({socketId:t})=>{e.add(t)}),t+s.directConnectionsCount),0);return e.size+t}flushPendingStores(){this.documents.forEach(e=>{let t=`onStoreDocument-${e.name}`;!e.isLoading&&this.debouncer.isDebounced(t)&&this.debouncer.executeNow(t)})}closeConnections(e){this.documents.forEach(t=>{e&&t.name!==e||t.connections.forEach((e,t)=>{t.close(ResetConnection)})})}handleConnection(e,t,s={}){let g=new ClientConnection(e,t,this,this.hooks.bind(this),{timeout:this.configuration.timeout},s);return g.onClose((e,t)=>{e.getConnectionsCount()>0||(!e.isLoading&&this.debouncer.isDebounced(`onStoreDocument-${e.name}`)?this.configuration.unloadImmediately&&this.debouncer.executeNow(`onStoreDocument-${e.name}`):this.unloadDocument(e))}),g}handleDocumentUpdate(e,t,s){let g=isTransactionOrigin(t)&&t.source===`connection`?t.connection:void 0,S=g?.request,w=isTransactionOrigin(t)?t.source===`connection`?t.connection.context:t.source===`local`?t.context??{}:{}:{},E={instance:this,clientsCount:e.getConnectionsCount(),document:e,documentName:e.name,requestHeaders:S?.headers??new Headers,requestParameters:getParameters(S),socketId:g?.socketId??``,update:s,transactionOrigin:t,connection:g,context:w};if(this.hooks(`onChange`,E),shouldSkipStoreHooks(t))return;let D={instance:this,clientsCount:e.getConnectionsCount(),document:e,lastContext:w,lastTransactionOrigin:t,documentName:e.name};this.storeDocumentHooks(e,D)}async createDocument(e,t,s,g,S){if(!e.trim())throw Error(`Document name must not be empty`);let w=this.loadingDocuments.get(e);if(w)return w;let E=this.documents.get(e);if(E)return Promise.resolve(E);let D=this.loadDocument(e,t,s,g,S);this.loadingDocuments.set(e,D);try{let t=await D;return this.documents.set(e,t),this.loadingDocuments.delete(e),t}catch(t){throw this.loadingDocuments.delete(e),t}}async loadDocument(e,t,s,g,S){let w=t.headers,E=getParameters(t),D=S??{},O=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:w,requestParameters:E,connectionConfig:g,context:D,socketId:s,instance:this}),k=new Document(e,{...this.configuration.yDocOptions,...O}),j={instance:this,context:D,connectionConfig:g,document:k,documentName:e,socketId:s,requestHeaders:w,requestParameters:E};try{await this.hooks(`onLoadDocument`,j,e=>{e instanceof Doc?applyUpdate(k,encodeStateAsUpdate(e)):e instanceof Uint8Array&&applyUpdate(k,e)})}catch(t){throw this.closeConnections(e),this.unloadDocument(k),t}return k.isLoading=!1,k.onUpdate((e,t,s)=>{e.lastChangeTime=Date.now(),this.handleDocumentUpdate(e,t,s)}),await this.hooks(`afterLoadDocument`,j),k.beforeBroadcastStateless((e,t)=>{let s={document:e,documentName:e.name,payload:t};this.hooks(`beforeBroadcastStateless`,s)}),k.awareness.on(`update`,(t,s)=>{this.hooks(`onAwarenessUpdate`,{document:k,documentName:e,instance:this,...t,transactionOrigin:s,connection:isTransactionOrigin(s)&&s.source===`connection`?s.connection:void 0,awareness:k.awareness,states:awarenessStatesToArray(k.awareness.getStates())})}),k}storeDocumentHooks(e,t,s){let g=`onStoreDocument-${e.name}`;return this.debouncer.debounce(g,async()=>{try{await e.saveMutex.runExclusive(async()=>{await this.hooks(`onStoreDocument`,t),await this.hooks(`afterStoreDocument`,t)})}catch(t){if(t instanceof SkipFurtherHooksError){setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0);return}console.error(`Caught error during storeDocumentHooks. Document stays in memory to avoid data loss`,t);return}setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0)},s?0:this.configuration.debounce,this.configuration.maxDebounce)}hooks(e,t,s=null){let{extensions:g}=this.configuration,S=Promise.resolve();return g.filter(t=>typeof t[e]==`function`).forEach(g=>{S=S.then(()=>g[e]?.(t)).catch(t=>{throw t?.message&&console.error(`[${e}]`,t.message),t}),s&&(S=S.then((...e)=>s(...e)))}),S}shouldUnloadDocument(e){return(this.debouncer.isDebounced(`onStoreDocument-${e.name}`)||this.debouncer.isCurrentlyExecuting(`onStoreDocument-${e.name}`)||e.saveMutex.isLocked())===!1&&e.getConnectionsCount()===0}async unloadDocument(e){let t=e.name;if(!this.shouldUnloadDocument(e)||!this.documents.has(t))return;if(this.unloadingDocuments.has(t))return this.unloadingDocuments.get(t);let s=(async()=>{try{await this.hooks(`beforeUnloadDocument`,{instance:this,documentName:t,document:e})}catch{return}this.shouldUnloadDocument(e)&&(this.documents.delete(t),e.destroy(),await this.hooks(`afterUnloadDocument`,{instance:this,documentName:t}))})();this.unloadingDocuments.set(t,Promise.resolve(s)),await s,this.unloadingDocuments.delete(t)}async openDirectConnection(e,t){return new DirectConnection(await this.createDocument(e,new Request(`http://localhost`),crypto$1.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},__create$1=Object.create,__defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__getOwnPropNames$1=Object.getOwnPropertyNames,__getProtoOf$1=Object.getPrototypeOf,__hasOwnProp$1=Object.prototype.hasOwnProperty,__commonJSMin$1=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),__copyProps$1=(e,t,s,g)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var S=__getOwnPropNames$1(t),w=0,E=S.length,D;w<E;w++)D=S[w],!__hasOwnProp$1.call(e,D)&&D!==s&&__defProp$1(e,D,{get:(e=>t[e]).bind(null,D),enumerable:!(g=__getOwnPropDesc$1(t,D))||g.enumerable});return e},__toESM$1=(e,t,s)=>(s=e==null?{}:__create$1(__getProtoOf$1(e)),__copyProps$1(t||!e||!e.__esModule?__defProp$1(s,`default`,{value:e,enumerable:!0}):s,e)),__require$1=createRequire(import.meta.url),require_constants$2=__commonJSMin$1(((e,t)=>{let s=[`nodebuffer`,`arraybuffer`,`fragments`],g=typeof Blob<`u`;g&&s.push(`blob`),t.exports={BINARY_TYPES:s,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:g,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),require_buffer_util=__commonJSMin$1(((e,t)=>{let{EMPTY_BUFFER:s}=require_constants$2(),g=Buffer[Symbol.species];function S(e,t){if(e.length===0)return s;if(e.length===1)return e[0];let S=Buffer.allocUnsafe(t),w=0;for(let t=0;t<e.length;t++){let s=e[t];S.set(s,w),w+=s.length}return w<t?new g(S.buffer,S.byteOffset,w):S}function w(e,t,s,g,S){for(let w=0;w<S;w++)s[g+w]=e[w]^t[w&3]}function E(e,t){for(let s=0;s<e.length;s++)e[s]^=t[s&3]}function D(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function O(e){if(O.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new g(e):ArrayBuffer.isView(e)?t=new g(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),O.readOnly=!1),t}if(t.exports={concat:S,mask:w,toArrayBuffer:D,toBuffer:O,unmask:E},!process.env.WS_NO_BUFFER_UTIL)try{let e=__require$1(`bufferutil`);t.exports.mask=function(t,s,g,S,E){E<48?w(t,s,g,S,E):e.mask(t,s,g,S,E)},t.exports.unmask=function(t,s){t.length<32?E(t,s):e.unmask(t,s)}}catch{}})),require_limiter=__commonJSMin$1(((e,t)=>{let s=Symbol(`kDone`),g=Symbol(`kRun`);t.exports=class{constructor(e){this[s]=()=>{this.pending--,this[g]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[g]()}[g](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[s])}}}})),require_permessage_deflate=__commonJSMin$1(((e,t)=>{let s=__require$1(`zlib`),g=require_buffer_util(),S=require_limiter(),{kStatusCode:w}=require_constants$2(),E=Buffer[Symbol.species],D=Buffer.from([0,0,255,255]),O=Symbol(`permessage-deflate`),k=Symbol(`total-length`),j=Symbol(`callback`),F=Symbol(`buffers`),L=Symbol(`error`),B;t.exports=class{constructor(e,t,s){this._maxPayload=s|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,B||=new S(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[j];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,s=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!s)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(s.server_no_context_takeover=!0),t.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(s.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?s.client_max_window_bits=t.clientMaxWindowBits:(s.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let s=e[t];if(s.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(s=s[0],t===`client_max_window_bits`){if(s!==!0){let e=+s;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${s}`)}else if(t===`server_max_window_bits`){let e=+s;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(s!==!0)throw TypeError(`Invalid value for parameter "${t}": ${s}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=s})}),e}decompress(e,t,s){B.add(g=>{this._decompress(e,t,(e,t)=>{g(),s(e,t)})})}compress(e,t,s){B.add(g=>{this._compress(e,t,(e,t)=>{g(),s(e,t)})})}_decompress(e,t,S){let w=this._isServer?`client`:`server`;if(!this._inflate){let e=`${w}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:s.Z_DEFAULT_WINDOWBITS;this._inflate=s.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[O]=this,this._inflate[k]=0,this._inflate[F]=[],this._inflate.on(`error`,ee),this._inflate.on(`data`,q)}this._inflate[j]=S,this._inflate.write(e),t&&this._inflate.write(D),this._inflate.flush(()=>{let e=this._inflate[L];if(e){this._inflate.close(),this._inflate=null,S(e);return}let s=g.concat(this._inflate[F],this._inflate[k]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[k]=0,this._inflate[F]=[],t&&this.params[`${w}_no_context_takeover`]&&this._inflate.reset()),S(null,s)})}_compress(e,t,S){let w=this._isServer?`server`:`client`;if(!this._deflate){let e=`${w}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:s.Z_DEFAULT_WINDOWBITS;this._deflate=s.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[k]=0,this._deflate[F]=[],this._deflate.on(`data`,H)}this._deflate[j]=S,this._deflate.write(e),this._deflate.flush(s.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=g.concat(this._deflate[F],this._deflate[k]);t&&(e=new E(e.buffer,e.byteOffset,e.length-4)),this._deflate[j]=null,this._deflate[k]=0,this._deflate[F]=[],t&&this.params[`${w}_no_context_takeover`]&&this._deflate.reset(),S(null,e)})}};function H(e){this[F].push(e),this[k]+=e.length}function q(e){if(this[k]+=e.length,this[O]._maxPayload<1||this[k]<=this[O]._maxPayload){this[F].push(e);return}this[L]=RangeError(`Max payload size exceeded`),this[L].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[L][w]=1009,this.removeListener(`data`,q),this.reset()}function ee(e){if(this[O]._inflate=null,this[L]){this[j](this[L]);return}e[w]=1007,this[j](e)}})),require_validation=__commonJSMin$1(((e,t)=>{let{isUtf8:s}=__require$1(`buffer`),{hasBlob:g}=require_constants$2(),S=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function w(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function E(e){let t=e.length,s=0;for(;s<t;)if(!(e[s]&128))s++;else if((e[s]&224)==192){if(s+1===t||(e[s+1]&192)!=128||(e[s]&254)==192)return!1;s+=2}else if((e[s]&240)==224){if(s+2>=t||(e[s+1]&192)!=128||(e[s+2]&192)!=128||e[s]===224&&(e[s+1]&224)==128||e[s]===237&&(e[s+1]&224)==160)return!1;s+=3}else if((e[s]&248)==240){if(s+3>=t||(e[s+1]&192)!=128||(e[s+2]&192)!=128||(e[s+3]&192)!=128||e[s]===240&&(e[s+1]&240)==128||e[s]===244&&e[s+1]>143||e[s]>244)return!1;s+=4}else return!1;return!0}function D(e){return g&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:D,isValidStatusCode:w,isValidUTF8:E,tokenChars:S},s)t.exports.isValidUTF8=function(e){return e.length<24?E(e):s(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=__require$1(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?E(t):e(t)}}catch{}})),require_receiver=__commonJSMin$1(((e,t)=>{let{Writable:s}=__require$1(`stream`),g=require_permessage_deflate(),{BINARY_TYPES:S,EMPTY_BUFFER:w,kStatusCode:E,kWebSocket:D}=require_constants$2(),{concat:O,toArrayBuffer:k,unmask:j}=require_buffer_util(),{isValidStatusCode:F,isValidUTF8:L}=require_validation(),B=Buffer[Symbol.species],H=0,q=1,ee=2,J=3,Y=4,te=5,ne=6;t.exports=class extends s{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||S[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[D]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,s){if(this._opcode===8&&this._state==0)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new B(t.buffer,t.byteOffset+e,t.length-e),new B(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let s=this._buffers[0],g=t.length-e;e>=s.length?t.set(this._buffers.shift(),g):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),g),this._buffers[0]=new B(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let s=(t[0]&64)==64;if(s&&!this._extensions[g.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(s){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(s){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),s=t.readUInt32BE(0);if(s>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=s*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=w;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&j(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[g.extensionName].decompress(e,this._fin,(e,s)=>{if(e)return t(e);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(s)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let g;g=this._binaryType===`nodebuffer`?O(s,t):this._binaryType===`arraybuffer`?k(O(s,t)):this._binaryType===`blob`?new Blob(s):s,this._allowSynchronousEvents?(this.emit(`message`,g,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,g,!0),this._state=0,this.startLoop(e)}))}else{let g=O(s,t);if(!this._skipUTF8Validation&&!L(g)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,g,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,g,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,w),this.end();else{let s=e.readUInt16BE(0);if(!F(s)){t(this.createError(RangeError,`invalid status code ${s}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let g=new B(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!L(g)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,s,g),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,s,g,S){this._loop=!1,this._errored=!0;let w=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(w,this.createError),w.code=S,w[E]=g,w}}})),require_sender=__commonJSMin$1(((e,t)=>{let{Duplex:s}=__require$1(`stream`),{randomFillSync:g}=__require$1(`crypto`),S=require_permessage_deflate(),{EMPTY_BUFFER:w,kWebSocket:E,NOOP:D}=require_constants$2(),{isBlob:O,isValidStatusCode:k}=require_validation(),{mask:j,toBuffer:F}=require_buffer_util(),L=Symbol(`kByteLength`),B=Buffer.alloc(4),H=8*1024,q,ee=H,J=0,Y=1,te=2;t.exports=class e{constructor(e,t,s){this._extensions=t||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=D,this[E]=void 0}static frame(e,t){let s,S=!1,w=2,E=!1;t.mask&&(s=t.maskBuffer||B,t.generateMask?t.generateMask(s):(ee===H&&(q===void 0&&(q=Buffer.alloc(H)),g(q,0,H),ee=0),s[0]=q[ee++],s[1]=q[ee++],s[2]=q[ee++],s[3]=q[ee++]),E=(s[0]|s[1]|s[2]|s[3])===0,w=6);let D;typeof e==`string`?(!t.mask||E)&&t[L]!==void 0?D=t[L]:(e=Buffer.from(e),D=e.length):(D=e.length,S=t.mask&&t.readOnly&&!E);let O=D;D>=65536?(w+=8,O=127):D>125&&(w+=2,O=126);let k=Buffer.allocUnsafe(S?D+w:w);return k[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(k[0]|=64),k[1]=O,O===126?k.writeUInt16BE(D,2):O===127&&(k[2]=k[3]=0,k.writeUIntBE(D,4,6)),!t.mask||(k[1]|=128,k[w-4]=s[0],k[w-3]=s[1],k[w-2]=s[2],k[w-1]=s[3],E)?[k,e]:S?(j(e,s,k,w,D),[k]):(j(e,s,e,0,D),[k,e])}close(t,s,g,S){let E;if(t===void 0)E=w;else if(typeof t!=`number`||!k(t))throw TypeError(`First argument must be a valid error code number`);else if(s===void 0||!s.length)E=Buffer.allocUnsafe(2),E.writeUInt16BE(t,0);else{let e=Buffer.byteLength(s);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);E=Buffer.allocUnsafe(2+e),E.writeUInt16BE(t,0),typeof s==`string`?E.write(s,2):E.set(s,2)}let D={[L]:E.length,fin:!0,generateMask:this._generateMask,mask:g,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(E,D),S):this.enqueue([this.dispatch,E,!1,D,S])}ping(t,s,g){let S,w;if(typeof t==`string`?(S=Buffer.byteLength(t),w=!1):O(t)?(S=t.size,w=!1):(t=F(t),S=t.length,w=F.readOnly),S>125)throw RangeError(`The data size must not be greater than 125 bytes`);let E={[L]:S,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:9,readOnly:w,rsv1:!1};O(t)?this._state===0?this.getBlobData(t,!1,E,g):this.enqueue([this.getBlobData,t,!1,E,g]):this._state===0?this.sendFrame(e.frame(t,E),g):this.enqueue([this.dispatch,t,!1,E,g])}pong(t,s,g){let S,w;if(typeof t==`string`?(S=Buffer.byteLength(t),w=!1):O(t)?(S=t.size,w=!1):(t=F(t),S=t.length,w=F.readOnly),S>125)throw RangeError(`The data size must not be greater than 125 bytes`);let E={[L]:S,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:10,readOnly:w,rsv1:!1};O(t)?this._state===0?this.getBlobData(t,!1,E,g):this.enqueue([this.getBlobData,t,!1,E,g]):this._state===0?this.sendFrame(e.frame(t,E),g):this.enqueue([this.dispatch,t,!1,E,g])}send(e,t,s){let g=this._extensions[S.extensionName],w=t.binary?2:1,E=t.compress,D,k;typeof e==`string`?(D=Buffer.byteLength(e),k=!1):O(e)?(D=e.size,k=!1):(e=F(e),D=e.length,k=F.readOnly),this._firstFragment?(this._firstFragment=!1,E&&g&&g.params[g._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(E=D>=g._threshold),this._compress=E):(E=!1,w=0),t.fin&&(this._firstFragment=!0);let j={[L]:D,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:w,readOnly:k,rsv1:E};O(e)?this._state===0?this.getBlobData(e,this._compress,j,s):this.enqueue([this.getBlobData,e,this._compress,j,s]):this._state===0?this.dispatch(e,this._compress,j,s):this.enqueue([this.dispatch,e,this._compress,j,s])}getBlobData(t,s,g,S){this._bufferedBytes+=g[L],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(ne,this,e,S);return}this._bufferedBytes-=g[L];let w=F(t);s?this.dispatch(w,s,g,S):(this._state=0,this.sendFrame(e.frame(w,g),S),this.dequeue())}).catch(e=>{process.nextTick(ae,this,e,S)})}dispatch(t,s,g,w){if(!s){this.sendFrame(e.frame(t,g),w);return}let E=this._extensions[S.extensionName];this._bufferedBytes+=g[L],this._state=1,E.compress(t,g.fin,(t,s)=>{if(this._socket.destroyed){ne(this,Error(`The socket was closed while data was being compressed`),w);return}this._bufferedBytes-=g[L],this._state=0,g.readOnly=!1,this.sendFrame(e.frame(s,g),w),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][L],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][L],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function ne(e,t,s){typeof s==`function`&&s(t);for(let s=0;s<e._queue.length;s++){let g=e._queue[s],S=g[g.length-1];typeof S==`function`&&S(t)}}function ae(e,t,s){ne(e,t,s),e.onerror(t)}})),require_event_target=__commonJSMin$1(((e,t)=>{let{kForOnEventAttribute:s,kListener:g}=require_constants$2(),S=Symbol(`kCode`),w=Symbol(`kData`),E=Symbol(`kError`),D=Symbol(`kMessage`),O=Symbol(`kReason`),k=Symbol(`kTarget`),j=Symbol(`kType`),F=Symbol(`kWasClean`);var L=class{constructor(e){this[k]=null,this[j]=e}get target(){return this[k]}get type(){return this[j]}};Object.defineProperty(L.prototype,`target`,{enumerable:!0}),Object.defineProperty(L.prototype,`type`,{enumerable:!0});var B=class extends L{constructor(e,t={}){super(e),this[S]=t.code===void 0?0:t.code,this[O]=t.reason===void 0?``:t.reason,this[F]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[S]}get reason(){return this[O]}get wasClean(){return this[F]}};Object.defineProperty(B.prototype,`code`,{enumerable:!0}),Object.defineProperty(B.prototype,`reason`,{enumerable:!0}),Object.defineProperty(B.prototype,`wasClean`,{enumerable:!0});var H=class extends L{constructor(e,t={}){super(e),this[E]=t.error===void 0?null:t.error,this[D]=t.message===void 0?``:t.message}get error(){return this[E]}get message(){return this[D]}};Object.defineProperty(H.prototype,`error`,{enumerable:!0}),Object.defineProperty(H.prototype,`message`,{enumerable:!0});var q=class extends L{constructor(e,t={}){super(e),this[w]=t.data===void 0?null:t.data}get data(){return this[w]}};Object.defineProperty(q.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:B,ErrorEvent:H,Event:L,EventTarget:{addEventListener(e,t,S={}){for(let w of this.listeners(e))if(!S[s]&&w[g]===t&&!w[s])return;let w;if(e===`message`)w=function(e,s){let g=new q(`message`,{data:s?e:e.toString()});g[k]=this,ee(t,this,g)};else if(e===`close`)w=function(e,s){let g=new B(`close`,{code:e,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});g[k]=this,ee(t,this,g)};else if(e===`error`)w=function(e){let s=new H(`error`,{error:e,message:e.message});s[k]=this,ee(t,this,s)};else if(e===`open`)w=function(){let e=new L(`open`);e[k]=this,ee(t,this,e)};else return;w[s]=!!S[s],w[g]=t,S.once?this.once(e,w):this.on(e,w)},removeEventListener(e,t){for(let S of this.listeners(e))if(S[g]===t&&!S[s]){this.removeListener(e,S);break}}},MessageEvent:q};function ee(e,t,s){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,s):e.call(t,s)}})),require_extension=__commonJSMin$1(((e,t)=>{let{tokenChars:s}=require_validation();function g(e,t,s){e[t]===void 0?e[t]=[s]:e[t].push(s)}function S(e){let t=Object.create(null),S=Object.create(null),w=!1,E=!1,D=!1,O,k,j=-1,F=-1,L=-1,B=0;for(;B<e.length;B++)if(F=e.charCodeAt(B),O===void 0)if(L===-1&&s[F]===1)j===-1&&(j=B);else if(B!==0&&(F===32||F===9))L===-1&&j!==-1&&(L=B);else if(F===59||F===44){if(j===-1)throw SyntaxError(`Unexpected character at index ${B}`);L===-1&&(L=B);let s=e.slice(j,L);F===44?(g(t,s,S),S=Object.create(null)):O=s,j=L=-1}else throw SyntaxError(`Unexpected character at index ${B}`);else if(k===void 0)if(L===-1&&s[F]===1)j===-1&&(j=B);else if(F===32||F===9)L===-1&&j!==-1&&(L=B);else if(F===59||F===44){if(j===-1)throw SyntaxError(`Unexpected character at index ${B}`);L===-1&&(L=B),g(S,e.slice(j,L),!0),F===44&&(g(t,O,S),S=Object.create(null),O=void 0),j=L=-1}else if(F===61&&j!==-1&&L===-1)k=e.slice(j,B),j=L=-1;else throw SyntaxError(`Unexpected character at index ${B}`);else if(E){if(s[F]!==1)throw SyntaxError(`Unexpected character at index ${B}`);j===-1?j=B:w||=!0,E=!1}else if(D)if(s[F]===1)j===-1&&(j=B);else if(F===34&&j!==-1)D=!1,L=B;else if(F===92)E=!0;else throw SyntaxError(`Unexpected character at index ${B}`);else if(F===34&&e.charCodeAt(B-1)===61)D=!0;else if(L===-1&&s[F]===1)j===-1&&(j=B);else if(j!==-1&&(F===32||F===9))L===-1&&(L=B);else if(F===59||F===44){if(j===-1)throw SyntaxError(`Unexpected character at index ${B}`);L===-1&&(L=B);let s=e.slice(j,L);w&&=(s=s.replace(/\\/g,``),!1),g(S,k,s),F===44&&(g(t,O,S),S=Object.create(null),O=void 0),k=void 0,j=L=-1}else throw SyntaxError(`Unexpected character at index ${B}`);if(j===-1||D||F===32||F===9)throw SyntaxError(`Unexpected end of input`);L===-1&&(L=B);let H=e.slice(j,L);return O===void 0?g(t,H,S):(k===void 0?g(S,H,!0):w?g(S,k,H.replace(/\\/g,``)):g(S,k,H),g(t,O,S)),t}function w(e){return Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>[t].concat(Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:w,parse:S}})),require_websocket=__commonJSMin$1(((e,t)=>{let s=__require$1(`events`),g=__require$1(`https`),S=__require$1(`http`),w=__require$1(`net`),E=__require$1(`tls`),{randomBytes:D,createHash:O}=__require$1(`crypto`),{Duplex:k,Readable:j}=__require$1(`stream`),{URL:F}=__require$1(`url`),L=require_permessage_deflate(),B=require_receiver(),H=require_sender(),{isBlob:q}=require_validation(),{BINARY_TYPES:ee,CLOSE_TIMEOUT:J,EMPTY_BUFFER:Y,GUID:te,kForOnEventAttribute:ne,kListener:ae,kStatusCode:oe,kWebSocket:se,NOOP:ce}=require_constants$2(),{EventTarget:{addEventListener:ue,removeEventListener:de}}=require_event_target(),{format:fe,parse:me}=require_extension(),{toBuffer:ge}=require_buffer_util(),_e=Symbol(`kAborted`),ve=[8,13],ye=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],Ce=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var we=class e extends s{constructor(t,s,g){super(),this._binaryType=ee[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Y,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=g.autoPong,this._closeTimeout=g.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,s===void 0?s=[]:Array.isArray(s)||(typeof s==`object`&&s?(g=s,s=[]):s=[s]),Te(this,t,s,g))}get binaryType(){return this._binaryType}set binaryType(e){ee.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,s,g){let S=new B({allowSynchronousEvents:g.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:g.maxPayload,skipUTF8Validation:g.skipUTF8Validation}),w=new H(t,this._extensions,g.generateMask);this._receiver=S,this._sender=w,this._socket=t,S[se]=this,w[se]=this,t[se]=this,S.on(`conclude`,Re),S.on(`drain`,ze),S.on(`error`,Be),S.on(`message`,Ue),S.on(`ping`,We),S.on(`pong`,Ge),w.onerror=Xe,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),s.length>0&&t.unshift(s),t.on(`close`,nt),t.on(`data`,rt),t.on(`end`,it),t.on(`error`,at),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[L.extensionName]&&this._extensions[L.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,s){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Pe(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,s,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),$e(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,s,g){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(g=t,t=s=void 0):typeof s==`function`&&(g=s,s=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){Ie(this,t,g);return}s===void 0&&(s=!this._isServer),this._sender.ping(t||Y,s,g)}pong(t,s,g){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(g=t,t=s=void 0):typeof s==`function`&&(g=s,s=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){Ie(this,t,g);return}s===void 0&&(s=!this._isServer),this._sender.pong(t||Y,s,g)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,s,g){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof s==`function`&&(g=s,s={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){Ie(this,t,g);return}let S={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...s};this._extensions[L.extensionName]||(S.compress=!1),this._sender.send(t||Y,S,g)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Pe(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(we,`CONNECTING`,{enumerable:!0,value:ye.indexOf(`CONNECTING`)}),Object.defineProperty(we.prototype,`CONNECTING`,{enumerable:!0,value:ye.indexOf(`CONNECTING`)}),Object.defineProperty(we,`OPEN`,{enumerable:!0,value:ye.indexOf(`OPEN`)}),Object.defineProperty(we.prototype,`OPEN`,{enumerable:!0,value:ye.indexOf(`OPEN`)}),Object.defineProperty(we,`CLOSING`,{enumerable:!0,value:ye.indexOf(`CLOSING`)}),Object.defineProperty(we.prototype,`CLOSING`,{enumerable:!0,value:ye.indexOf(`CLOSING`)}),Object.defineProperty(we,`CLOSED`,{enumerable:!0,value:ye.indexOf(`CLOSED`)}),Object.defineProperty(we.prototype,`CLOSED`,{enumerable:!0,value:ye.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(we.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(we.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[ne])return t[ae];return null},set(t){for(let t of this.listeners(e))if(t[ne]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[ne]:!0})}})}),we.prototype.addEventListener=ue,we.prototype.removeEventListener=de,t.exports=we;function Te(e,t,s,w){let E={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:J,protocolVersion:ve[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...w,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=E.autoPong,e._closeTimeout=E.closeTimeout,!ve.includes(E.protocolVersion))throw RangeError(`Unsupported protocol version: ${E.protocolVersion} (supported versions: ${ve.join(`, `)})`);let k;if(t instanceof F)k=t;else try{k=new F(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}k.protocol===`http:`?k.protocol=`ws:`:k.protocol===`https:`&&(k.protocol=`wss:`),e._url=k.href;let j=k.protocol===`wss:`,B=k.protocol===`ws+unix:`,H;if(k.protocol!==`ws:`&&!j&&!B?H=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:B&&!k.pathname?H=`The URL's pathname is empty`:k.hash&&(H=`The URL contains a fragment identifier`),H){let t=SyntaxError(H);if(e._redirects===0)throw t;De(e,t);return}let q=j?443:80,ee=D(16).toString(`base64`),Y=j?g.request:S.request,ne=new Set,ae;if(E.createConnection=E.createConnection||(j?Me:je),E.defaultPort=E.defaultPort||q,E.port=k.port||q,E.host=k.hostname.startsWith(`[`)?k.hostname.slice(1,-1):k.hostname,E.headers={...E.headers,"Sec-WebSocket-Version":E.protocolVersion,"Sec-WebSocket-Key":ee,Connection:`Upgrade`,Upgrade:`websocket`},E.path=k.pathname+k.search,E.timeout=E.handshakeTimeout,E.perMessageDeflate&&(ae=new L(E.perMessageDeflate===!0?{}:E.perMessageDeflate,!1,E.maxPayload),E.headers[`Sec-WebSocket-Extensions`]=fe({[L.extensionName]:ae.offer()})),s.length){for(let e of s){if(typeof e!=`string`||!Ce.test(e)||ne.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);ne.add(e)}E.headers[`Sec-WebSocket-Protocol`]=s.join(`,`)}if(E.origin&&(E.protocolVersion<13?E.headers[`Sec-WebSocket-Origin`]=E.origin:E.headers.Origin=E.origin),(k.username||k.password)&&(E.auth=`${k.username}:${k.password}`),B){let e=E.path.split(`:`);E.socketPath=e[0],E.path=e[1]}let oe;if(E.followRedirects){if(e._redirects===0){e._originalIpc=B,e._originalSecure=j,e._originalHostOrSocketPath=B?E.socketPath:k.host;let t=w&&w.headers;if(w={...w,headers:{}},t)for(let[e,s]of Object.entries(t))w.headers[e.toLowerCase()]=s}else if(e.listenerCount(`redirect`)===0){let t=B?e._originalIpc?E.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:k.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!j)&&(delete E.headers.authorization,delete E.headers.cookie,t||delete E.headers.host,E.auth=void 0)}E.auth&&!w.headers.authorization&&(w.headers.authorization=`Basic `+Buffer.from(E.auth).toString(`base64`)),oe=e._req=Y(E),e._redirects&&e.emit(`redirect`,e.url,oe)}else oe=e._req=Y(E);E.timeout&&oe.on(`timeout`,()=>{Pe(e,oe,`Opening handshake has timed out`)}),oe.on(`error`,t=>{oe===null||oe[_e]||(oe=e._req=null,De(e,t))}),oe.on(`response`,g=>{let S=g.headers.location,D=g.statusCode;if(S&&E.followRedirects&&D>=300&&D<400){if(++e._redirects>E.maxRedirects){Pe(e,oe,`Maximum redirects exceeded`);return}oe.abort();let g;try{g=new F(S,t)}catch{De(e,SyntaxError(`Invalid URL: ${S}`));return}Te(e,g,s,w)}else e.emit(`unexpected-response`,oe,g)||Pe(e,oe,`Unexpected server response: ${g.statusCode}`)}),oe.on(`upgrade`,(t,s,g)=>{if(e.emit(`upgrade`,t),e.readyState!==we.CONNECTING)return;oe=e._req=null;let S=t.headers.upgrade;if(S===void 0||S.toLowerCase()!==`websocket`){Pe(e,s,`Invalid Upgrade header`);return}let w=O(`sha1`).update(ee+te).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==w){Pe(e,s,`Invalid Sec-WebSocket-Accept header`);return}let D=t.headers[`sec-websocket-protocol`],k;if(D===void 0?ne.size&&(k=`Server sent no subprotocol`):ne.size?ne.has(D)||(k=`Server sent an invalid subprotocol`):k=`Server sent a subprotocol but none was requested`,k){Pe(e,s,k);return}D&&(e._protocol=D);let j=t.headers[`sec-websocket-extensions`];if(j!==void 0){if(!ae){Pe(e,s,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=me(j)}catch{Pe(e,s,`Invalid Sec-WebSocket-Extensions header`);return}let g=Object.keys(t);if(g.length!==1||g[0]!==L.extensionName){Pe(e,s,`Server indicated an extension that was not requested`);return}try{ae.accept(t[L.extensionName])}catch{Pe(e,s,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[L.extensionName]=ae}e.setSocket(s,g,{allowSynchronousEvents:E.allowSynchronousEvents,generateMask:E.generateMask,maxPayload:E.maxPayload,skipUTF8Validation:E.skipUTF8Validation})}),E.finishRequest?E.finishRequest(oe,e):oe.end()}function De(e,t){e._readyState=we.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function je(e){return e.path=e.socketPath,w.connect(e)}function Me(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=w.isIP(e.host)?``:e.host),E.connect(e)}function Pe(e,t,s){e._readyState=we.CLOSING;let g=Error(s);Error.captureStackTrace(g,Pe),t.setHeader?(t[_e]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(De,e,g)):(t.destroy(g),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function Ie(e,t,s){if(t){let s=q(t)?t.size:ge(t).length;e._socket?e._sender._bufferedBytes+=s:e._bufferedAmount+=s}if(s){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${ye[e.readyState]})`);process.nextTick(s,t)}}function Re(e,t){let s=this[se];s._closeFrameReceived=!0,s._closeMessage=t,s._closeCode=e,s._socket[se]!==void 0&&(s._socket.removeListener(`data`,rt),process.nextTick(Ke,s._socket),e===1005?s.close():s.close(e,t))}function ze(){let e=this[se];e.isPaused||e._socket.resume()}function Be(e){let t=this[se];t._socket[se]!==void 0&&(t._socket.removeListener(`data`,rt),process.nextTick(Ke,t._socket),t.close(e[oe])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function Ve(){this[se].emitClose()}function Ue(e,t){this[se].emit(`message`,e,t)}function We(e){let t=this[se];t._autoPong&&t.pong(e,!this._isServer,ce),t.emit(`ping`,e)}function Ge(e){this[se].emit(`pong`,e)}function Ke(e){e.resume()}function Xe(e){let t=this[se];t.readyState!==we.CLOSED&&(t.readyState===we.OPEN&&(t._readyState=we.CLOSING,$e(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function $e(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function nt(){let e=this[se];if(this.removeListener(`close`,nt),this.removeListener(`data`,rt),this.removeListener(`end`,it),e._readyState=we.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[se]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,Ve),e._receiver.on(`finish`,Ve))}function rt(e){this[se]._receiver.write(e)||this.pause()}function it(){let e=this[se];e._readyState=we.CLOSING,e._receiver.end(),this.end()}function at(){let e=this[se];this.removeListener(`error`,at),this.on(`error`,ce),e&&(e._readyState=we.CLOSING,this.destroy())}})),require_stream=__commonJSMin$1(((e,t)=>{require_websocket();let{Duplex:s}=__require$1(`stream`);function g(e){e.emit(`close`)}function S(){!this.destroyed&&this._writableState.finished&&this.destroy()}function w(e){this.removeListener(`error`,w),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function E(e,t){let E=!0,D=new s({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,s){let g=!s&&D._readableState.objectMode?t.toString():t;D.push(g)||e.pause()}),e.once(`error`,function(e){D.destroyed||(E=!1,D.destroy(e))}),e.once(`close`,function(){D.destroyed||D.push(null)}),D._destroy=function(t,s){if(e.readyState===e.CLOSED){s(t),process.nextTick(g,D);return}let S=!1;e.once(`error`,function(e){S=!0,s(e)}),e.once(`close`,function(){S||s(t),process.nextTick(g,D)}),E&&e.terminate()},D._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){D._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),D._readableState.endEmitted&&D.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},D._read=function(){e.isPaused&&e.resume()},D._write=function(t,s,g){if(e.readyState===e.CONNECTING){e.once(`open`,function(){D._write(t,s,g)});return}e.send(t,g)},D.on(`end`,S),D.on(`error`,w),D}t.exports=E})),require_subprotocol=__commonJSMin$1(((e,t)=>{let{tokenChars:s}=require_validation();function g(e){let t=new Set,g=-1,S=-1,w=0;for(;w<e.length;w++){let E=e.charCodeAt(w);if(S===-1&&s[E]===1)g===-1&&(g=w);else if(w!==0&&(E===32||E===9))S===-1&&g!==-1&&(S=w);else if(E===44){if(g===-1)throw SyntaxError(`Unexpected character at index ${w}`);S===-1&&(S=w);let s=e.slice(g,S);if(t.has(s))throw SyntaxError(`The "${s}" subprotocol is duplicated`);t.add(s),g=S=-1}else throw SyntaxError(`Unexpected character at index ${w}`)}if(g===-1||S!==-1)throw SyntaxError(`Unexpected end of input`);let E=e.slice(g,w);if(t.has(E))throw SyntaxError(`The "${E}" subprotocol is duplicated`);return t.add(E),t}t.exports={parse:g}})),require_websocket_server=__commonJSMin$1(((e,t)=>{let s=__require$1(`events`),g=__require$1(`http`),{Duplex:S}=__require$1(`stream`),{createHash:w}=__require$1(`crypto`),E=require_extension(),D=require_permessage_deflate(),O=require_subprotocol(),k=require_websocket(),{CLOSE_TIMEOUT:j,GUID:F,kWebSocket:L}=require_constants$2(),B=/^[+/0-9A-Za-z]{22}==$/,H=0,q=1,ee=2;t.exports=class extends s{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:j,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:k,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=g.createServer((e,t)=>{let s=g.STATUS_CODES[426];t.writeHead(426,{"Content-Length":s.length,"Content-Type":`text/plain`}),t.end(s)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=J(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,s,g)=>{this.handleUpgrade(t,s,g,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(Y,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(Y,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{Y(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,s,g){t.on(`error`,te);let S=e.headers[`sec-websocket-key`],w=e.headers.upgrade,k=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){ae(this,e,t,405,`Invalid HTTP method`);return}if(w===void 0||w.toLowerCase()!==`websocket`){ae(this,e,t,400,`Invalid Upgrade header`);return}if(S===void 0||!B.test(S)){ae(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(k!==13&&k!==8){ae(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){ne(t,400);return}let j=e.headers[`sec-websocket-protocol`],F=new Set;if(j!==void 0)try{F=O.parse(j)}catch{ae(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let L=e.headers[`sec-websocket-extensions`],H={};if(this.options.perMessageDeflate&&L!==void 0){let s=new D(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=E.parse(L);e[D.extensionName]&&(s.accept(e[D.extensionName]),H[D.extensionName]=s)}catch{ae(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let w={origin:e.headers[`${k===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(w,(w,E,D,O)=>{if(!w)return ne(t,E||401,D,O);this.completeUpgrade(H,S,F,e,t,s,g)});return}if(!this.options.verifyClient(w))return ne(t,401)}this.completeUpgrade(H,S,F,e,t,s,g)}completeUpgrade(e,t,s,g,S,O,k){if(!S.readable||!S.writable)return S.destroy();if(S[L])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return ne(S,503);let j=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${w(`sha1`).update(t+F).digest(`base64`)}`],B=new this.options.WebSocket(null,void 0,this.options);if(s.size){let e=this.options.handleProtocols?this.options.handleProtocols(s,g):s.values().next().value;e&&(j.push(`Sec-WebSocket-Protocol: ${e}`),B._protocol=e)}if(e[D.extensionName]){let t=e[D.extensionName].params,s=E.format({[D.extensionName]:[t]});j.push(`Sec-WebSocket-Extensions: ${s}`),B._extensions=e}this.emit(`headers`,j,g),S.write(j.concat(`\r
|
|
758
758
|
`).join(`\r
|
|
759
759
|
`)),S.removeListener(`error`,te),B.setSocket(S,O,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(B),B.on(`close`,()=>{this.clients.delete(B),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Y,this)})),k(B,g)}};function J(e,t){for(let s of Object.keys(t))e.on(s,t[s]);return function(){for(let s of Object.keys(t))e.removeListener(s,t[s])}}function Y(e){e._state=2,e.emit(`close`)}function te(){this.destroy()}function ne(e,t,s,S){s||=g.STATUS_CODES[t],S={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(s),...S},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${g.STATUS_CODES[t]}\r\n`+Object.keys(S).map(e=>`${e}: ${S[e]}`).join(`\r
|
|
760
760
|
`)+`\r
|
|
761
761
|
\r
|
|
762
762
|
`+s)}function ae(e,t,s,g,S,w){if(e.listenerCount(`wsClientError`)){let g=Error(S);Error.captureStackTrace(g,ae),e.emit(`wsClientError`,g,s,t)}else ne(s,g,S,w)}}));require_stream(),require_receiver(),require_sender(),require_websocket();var import_websocket_server=__toESM$1(require_websocket_server(),1),require_ignore=__commonJSMin$2(((e,t)=>{function s(e){return Array.isArray(e)?e:[e]}let g=``,S=` `,w=`\\`,E=/^\s+$/,D=/(?:[^\\]|^)\\$/,O=/^\\!/,k=/^\\#/,j=/\r?\n/g,F=/^\.*\/|^\.+$/,L=`/`,B=`node-ignore`;typeof Symbol<`u`&&(B=Symbol.for(`node-ignore`));let H=B,q=(e,t,s)=>Object.defineProperty(e,t,{value:s}),ee=/([0-z])-([0-z])/g,J=()=>!1,Y=e=>e.replace(ee,(e,t,s)=>t.charCodeAt(0)<=s.charCodeAt(0)?e:``),te=e=>{let{length:t}=e;return e.slice(0,t-t%2)},ne=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,s)=>t+(s.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:s}=t;return t.slice(0,s-s%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,s)=>t+6<s.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,s)=>t+s.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,s,g,S)=>t===`\\`?`\\[${s}${te(g)}${S}`:S===`]`&&g.length%2==0?`[${Y(s)}${g}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`]],ae=Object.create(null),oe=(e,t)=>{let s=ae[e];return s||(s=ne.reduce((t,[s,g])=>t.replace(s,g.bind(e)),e),ae[e]=s),t?new RegExp(s,`i`):new RegExp(s)},se=e=>typeof e==`string`,ce=e=>e&&se(e)&&!E.test(e)&&!D.test(e)&&e.indexOf(`#`)!==0,ue=e=>e.split(j);var de=class{constructor(e,t,s,g){this.origin=e,this.pattern=t,this.negative=s,this.regex=g}};let fe=(e,t)=>{let s=e,g=!1;e.indexOf(`!`)===0&&(g=!0,e=e.substr(1)),e=e.replace(O,`!`).replace(k,`#`);let S=oe(e,t);return new de(s,e,g,S)},me=(e,t)=>{throw new t(e)},ge=(e,t,s)=>se(e)?e?ge.isNotRelative(e)?s(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:s(`path must not be empty`,TypeError):s(`path must be a string, but got \`${t}\``,TypeError),_e=e=>F.test(e);ge.isNotRelative=_e,ge.convert=e=>e;var ve=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:s=!1}={}){q(this,H,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=s,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[H]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(ce(e)){let t=fe(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,s(se(e)?ue(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let s=!1,g=!1;return this._rules.forEach(S=>{let{negative:w}=S;g===w&&s!==g||w&&!s&&!g&&!t||S.regex.test(e)&&(s=!w,g=w)}),{ignored:s,unignored:g}}_test(e,t,s,g){let S=e&&ge.convert(e);return ge(S,e,this._allowRelativePaths?J:me),this._t(S,t,s,g)}_t(e,t,s,g){if(e in t)return t[e];if(g||=e.split(`/`),g.pop(),!g.length)return t[e]=this._testOne(e,s);let S=this._t(g.join(`/`)+`/`,t,s,g);return t[e]=S.ignored?S:this._testOne(e,s)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return s(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let ye=e=>new ve(e);if(ye.isPathValid=e=>ge(e&&ge.convert(e),e,J),ye.default=ye,t.exports=ye,typeof process<`u`&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform===`win32`)){ge.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;ge.isNotRelative=t=>e.test(t)||_e(t)}}));init_esm$2();var import_src=require_src$14(),import_src$1=require_src$10(),import_src$2=require_src$9(),import_src$3=require_src$4(),import_src$4=require_src$3(),import_src$5=require_src$2(),import_src$6=require_src$1(),import_src$7=require_src();init_esm$1();var import_lib=__toESM$2(require_lib(),1),import_yazl=__toESM$2(require_yazl(),1),import_shell_quote=__toESM$2(require_shell_quote(),1),import_ignore=__toESM$2(require_ignore(),1),__create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__commonJSMin=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),__copyProps=(e,t,s,g)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var S=__getOwnPropNames(t),w=0,E=S.length,D;w<E;w++)D=S[w],!__hasOwnProp.call(e,D)&&D!==s&&__defProp(e,D,{get:(e=>t[e]).bind(null,D),enumerable:!(g=__getOwnPropDesc(t,D))||g.enumerable});return e},__toESM=(e,t,s)=>(s=e==null?{}:__create(__getProtoOf(e)),__copyProps(t||!e||!e.__esModule?__defProp(s,`default`,{value:e,enumerable:!0}):s,e)),__require=createRequire(import.meta.url);const MAX_LEN=128;function sanitizeGitIdentity(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,MAX_LEN)}const AGENT_ID_RE=/^[a-zA-Z0-9_-]+$/,AGENT_ID_MAX_LEN=64;function validateAgentId(e){return typeof e!=`string`||e.length===0||e.length>64||!AGENT_ID_RE.test(e)?null:e}function toBroadcasterKey(e){return e.startsWith(`agent-`)?e:`agent-${e}`}function isPresenceEligibleAgentId(e){return!e.startsWith(`principal-`)}function resolveAgentType(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)||t.startsWith(`local-agent-mode-`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function parseAgentBodyFields(e){let t=validateAgentId(typeof e.agentId==`string`?e.agentId:null)??void 0;return{rawAgentId:t,writerId:t===void 0?void 0:toBroadcasterKey(t),displayName:typeof e.agentName==`string`?sanitizeGitIdentity(e.agentName):`Claude`,clientName:typeof e.clientName==`string`?sanitizeGitIdentity(e.clientName):void 0,clientVersion:typeof e.clientVersion==`string`?sanitizeGitIdentity(e.clientVersion):void 0,label:typeof e.label==`string`?sanitizeGitIdentity(e.label):void 0,colorSeed:typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):void 0}}var require_err_helpers=__commonJSMin(((e,t)=>{let s=e=>e&&typeof e.message==`string`,g=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return s(t)?t:void 0}else return s(t)?t:void 0},S=(e,t)=>{if(!s(e))return``;let w=e.stack||``;if(t.has(e))return w+`
|
|
763
763
|
causes have become circular...`;let E=g(e);return E?(t.add(e),w+`
|
|
764
|
-
caused by: `+S(E,t)):w},w=e=>S(e,new Set),E=(e,t,S)=>{if(!s(e))return``;let w=S?``:e.message||``;if(t.has(e))return w+`: ...`;let D=g(e);if(D){t.add(e);let s=typeof e.cause==`function`;return w+(s?``:`: `)+E(D,t,s)}else return w};t.exports={isErrorLike:s,getErrorCause:g,stackWithCauses:w,messageWithCauses:e=>E(e,new Set)}})),require_err_proto=__commonJSMin(((e,t)=>{let s=Symbol(`circular-ref-tag`),g=Symbol(`pino-raw-err-ref`),S=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[g]},set:function(e){this[g]=e}}});Object.defineProperty(S,g,{writable:!0,value:{}}),t.exports={pinoErrProto:S,pinoErrorSymbols:{seen:s,rawSymbol:g}}})),require_err=__commonJSMin(((e,t)=>{t.exports=k;let{messageWithCauses:s,stackWithCauses:g,isErrorLike:S}=require_err_helpers(),{pinoErrProto:w,pinoErrorSymbols:E}=require_err_proto(),{seen:D}=E,{toString:O}=Object.prototype;function k(e){if(!S(e))return e;e[D]=void 0;let t=Object.create(w);t.type=O.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=s(e),t.stack=g(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>k(e)));for(let s in e)if(t[s]===void 0){let g=e[s];S(g)?s!==`cause`&&!Object.prototype.hasOwnProperty.call(g,D)&&(t[s]=k(g)):t[s]=g}return delete e[D],t.raw=e,t}})),require_err_with_cause=__commonJSMin(((e,t)=>{t.exports=D;let{isErrorLike:s}=require_err_helpers(),{pinoErrProto:g,pinoErrorSymbols:S}=require_err_proto(),{seen:w}=S,{toString:E}=Object.prototype;function D(e){if(!s(e))return e;e[w]=void 0;let t=Object.create(g);t.type=E.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>D(e))),s(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,w)&&(t.cause=D(e.cause));for(let g in e)if(t[g]===void 0){let S=e[g];s(S)?Object.prototype.hasOwnProperty.call(S,w)||(t[g]=D(S)):t[g]=S}return delete e[w],t.raw=e,t}})),require_req=__commonJSMin(((e,t)=>{t.exports={mapHttpRequest:w,reqSerializer:S};let s=Symbol(`pino-raw-req-ref`),g=Object.create({},{id:{enumerable:!0,writable:!0,value:``},method:{enumerable:!0,writable:!0,value:``},url:{enumerable:!0,writable:!0,value:``},query:{enumerable:!0,writable:!0,value:``},params:{enumerable:!0,writable:!0,value:``},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:``},remotePort:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[s]},set:function(e){this[s]=e}}});Object.defineProperty(g,s,{writable:!0,value:{}});function S(e){let t=e.info||e.socket,s=Object.create(g);if(s.id=typeof e.id==`function`?e.id():e.id||(e.info?e.info.id:void 0),s.method=e.method,e.originalUrl)s.url=e.originalUrl;else{let t=e.path;s.url=typeof t==`string`?t:e.url?e.url.path||e.url:void 0}return e.query&&(s.query=e.query),e.params&&(s.params=e.params),s.headers=e.headers,s.remoteAddress=t&&t.remoteAddress,s.remotePort=t&&t.remotePort,s.raw=e.raw||e,s}function w(e){return{req:S(e)}}})),require_res=__commonJSMin(((e,t)=>{t.exports={mapHttpResponse:w,resSerializer:S};let s=Symbol(`pino-raw-res-ref`),g=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[s]},set:function(e){this[s]=e}}});Object.defineProperty(g,s,{writable:!0,value:{}});function S(e){let t=Object.create(g);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function w(e){return{res:S(e)}}})),require_pino_std_serializers=__commonJSMin(((e,t)=>{let s=require_err(),g=require_err_with_cause(),S=require_req(),w=require_res();t.exports={err:s,errWithCause:g,mapHttpRequest:S.mapHttpRequest,mapHttpResponse:w.mapHttpResponse,req:S.reqSerializer,res:w.resSerializer,wrapErrorSerializer:function(e){return e===s?e:function(t){return e(s(t))}},wrapRequestSerializer:function(e){return e===S.reqSerializer?e:function(t){return e(S.reqSerializer(t))}},wrapResponseSerializer:function(e){return e===w.resSerializer?e:function(t){return e(w.resSerializer(t))}}}})),require_caller=__commonJSMin(((e,t)=>{function s(e,t){return t}t.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=s;let t=Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let g=t.slice(2),S=[];for(let e of g)e&&S.push(e.getFileName());return S}})),require_redact=__commonJSMin(((e,t)=>{function s(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array){let t=[];for(let g=0;g<e.length;g++)t[g]=s(e[g]);return t}if(typeof e==`object`){let t=Object.create(Object.getPrototypeOf(e));for(let g in e)Object.prototype.hasOwnProperty.call(e,g)&&(t[g]=s(e[g]));return t}return e}function g(e){let t=[],s=``,g=!1,S=!1,w=``;for(let E=0;E<e.length;E++){let D=e[E];!g&&D===`.`?s&&=(t.push(s),``):D===`[`?(s&&=(t.push(s),``),g=!0):D===`]`&&g?(t.push(s),s=``,g=!1,S=!1):(D===`"`||D===`'`)&&g?S?D===w?(S=!1,w=``):s+=D:(S=!0,w=D):s+=D}return s&&t.push(s),t}function S(e,t,s){let g=e;for(let e=0;e<t.length-1;e++){let s=t[e];if(typeof g!=`object`||!g||!(s in g)||typeof g[s]!=`object`||g[s]===null)return!1;g=g[s]}let S=t[t.length-1];if(S===`*`){if(Array.isArray(g))for(let e=0;e<g.length;e++)g[e]=s;else if(typeof g==`object`&&g)for(let e in g)Object.prototype.hasOwnProperty.call(g,e)&&(g[e]=s)}else typeof g==`object`&&g&&S in g&&Object.prototype.hasOwnProperty.call(g,S)&&(g[S]=s);return!0}function w(e,t){let s=e;for(let e=0;e<t.length-1;e++){let g=t[e];if(typeof s!=`object`||!s||!(g in s)||typeof s[g]!=`object`||s[g]===null)return!1;s=s[g]}let g=t[t.length-1];if(g===`*`){if(Array.isArray(s))for(let e=0;e<s.length;e++)s[e]=void 0;else if(typeof s==`object`&&s)for(let e in s)Object.prototype.hasOwnProperty.call(s,e)&&delete s[e]}else typeof s==`object`&&s&&g in s&&Object.prototype.hasOwnProperty.call(s,g)&&delete s[g];return!0}let E=Symbol(`PATH_NOT_FOUND`);function D(e,t){let s=e;for(let e of t){if(typeof s!=`object`||!s||!s||!(e in s))return E;s=s[e]}return s}function O(e,t){let s=e;for(let e of t){if(typeof s!=`object`||!s||!s)return;s=s[e]}return s}function k(e,t,s,O=!1){for(let k of t){let t=g(k);if(t.includes(`*`))j(e,t,s,k,O);else if(O)w(e,t);else{let g=D(e,t);if(g===E)continue;S(e,t,typeof s==`function`?s(g,t):s)}}}function j(e,t,s,g,S=!1){let w=t.indexOf(`*`);if(w===t.length-1){let g=t.slice(0,-1),w=e;for(let e of g){if(typeof w!=`object`||!w||!w)return;w=w[e]}if(Array.isArray(w))if(S)for(let e=0;e<w.length;e++)w[e]=void 0;else for(let e=0;e<w.length;e++){let t=[...g,e.toString()],S=typeof s==`function`?s(w[e],t):s;w[e]=S}else if(typeof w==`object`&&w)if(S){let e=[];for(let t in w)Object.prototype.hasOwnProperty.call(w,t)&&e.push(t);for(let t of e)delete w[t]}else for(let e in w){let t=[...g,e],S=typeof s==`function`?s(w[e],t):s;w[e]=S}}else F(e,t,s,w,g,S)}function F(e,t,s,g,E,D=!1){let k=t.slice(0,g),F=t.slice(g+1),L=[];function B(e,t){if(t===k.length){if(Array.isArray(e))for(let s=0;s<e.length;s++)L[t]=s.toString(),B(e[s],t+1);else if(typeof e==`object`&&e)for(let s in e)L[t]=s,B(e[s],t+1)}else if(t<k.length){let s=k[t];e&&typeof e==`object`&&e&&s in e&&(L[t]=s,B(e[s],t+1))}else F.includes(`*`)?j(e,F,typeof s==`function`?(e,g)=>s(e,[...L.slice(0,t),...g]):s,E,D):D?w(e,F):S(e,F,typeof s==`function`?s(O(e,F),[...L.slice(0,t),...F]):s)}if(k.length===0)B(e,0);else{let t=e;for(let e=0;e<k.length;e++){let s=k[e];if(typeof t!=`object`||!t||!t)return;t=t[s],L[e]=s}t!=null&&B(t,k.length)}}function L(e){if(e.length===0)return null;let t=new Map;for(let s of e){let e=g(s),S=t;for(let t=0;t<e.length;t++){let s=e[t];S.has(s)||S.set(s,new Map),S=S.get(s)}}return t}function B(e,t){if(!t)return e;function s(e,t,g=0){if(!t||t.size===0||typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let g=[];for(let S=0;S<e.length;S++){let w=S.toString();t.has(w)||t.has(`*`)?g[S]=s(e[S],t.get(w)||t.get(`*`)):g[S]=e[S]}return g}let S=Object.create(Object.getPrototypeOf(e));for(let g in e)Object.prototype.hasOwnProperty.call(e,g)&&(t.has(g)||t.has(`*`)?S[g]=s(e[g],t.get(g)||t.get(`*`)):S[g]=e[g]);return S}return s(e,t)}function H(e){if(typeof e!=`string`)throw Error(`Paths must be (non-empty) strings`);if(e===``)throw Error(`Invalid redaction path ()`);if(e.includes(`..`)||e.includes(`,`))throw Error(`Invalid redaction path (${e})`);let t=0,s=!1,g=``;for(let S=0;S<e.length;S++){let w=e[S];if((w===`"`||w===`'`)&&t>0)s?w===g&&(s=!1,g=``):(s=!0,g=w);else if(w===`[`&&!s)t++;else if(w===`]`&&!s&&(t--,t<0))throw Error(`Invalid redaction path (${e})`)}if(t!==0)throw Error(`Invalid redaction path (${e})`)}function q(e){if(!Array.isArray(e))throw TypeError(`paths must be an array`);for(let t of e)H(t)}function ee(e={}){let{paths:t=[],censor:g=`[REDACTED]`,serialize:S=JSON.stringify,strict:w=!0,remove:E=!1}=e;q(t);let D=L(t);return function(e){if(w&&(typeof e!=`object`||!e)&&(typeof e!=`object`||!e))return S?S(e):e;let O=B(e,D),j=e,F=g;return typeof g==`function`&&(F=g),k(O,t,F,E),S===!1?(O.restore=function(){return s(j)},O):typeof S==`function`?S(O):JSON.stringify(O)}}t.exports=ee})),require_symbols=__commonJSMin(((e,t)=>{let s=Symbol(`pino.setLevel`),g=Symbol(`pino.getLevel`),S=Symbol(`pino.levelVal`),w=Symbol(`pino.levelComp`),E=Symbol(`pino.useLevelLabels`),D=Symbol(`pino.useOnlyCustomLevels`),O=Symbol(`pino.mixin`),k=Symbol(`pino.lsCache`),j=Symbol(`pino.chindings`),F=Symbol(`pino.asJson`),L=Symbol(`pino.write`),B=Symbol(`pino.redactFmt`),H=Symbol(`pino.time`),q=Symbol(`pino.timeSliceIndex`),ee=Symbol(`pino.stream`),J=Symbol(`pino.stringify`),Y=Symbol(`pino.stringifySafe`),te=Symbol(`pino.stringifiers`),ne=Symbol(`pino.end`),ae=Symbol(`pino.formatOpts`),oe=Symbol(`pino.messageKey`),se=Symbol(`pino.errorKey`),ce=Symbol(`pino.nestedKey`),ue=Symbol(`pino.nestedKeyStr`),de=Symbol(`pino.mixinMergeStrategy`),fe=Symbol(`pino.msgPrefix`),me=Symbol(`pino.wildcardFirst`),ge=Symbol.for(`pino.serializers`),_e=Symbol.for(`pino.formatters`),ve=Symbol.for(`pino.hooks`);t.exports={setLevelSym:s,getLevelSym:g,levelValSym:S,levelCompSym:w,useLevelLabelsSym:E,mixinSym:O,lsCacheSym:k,chindingsSym:j,asJsonSym:F,writeSym:L,serializersSym:ge,redactFmtSym:B,timeSym:H,timeSliceIndexSym:q,streamSym:ee,stringifySym:J,stringifySafeSym:Y,stringifiersSym:te,endSym:ne,formatOptsSym:ae,messageKeySym:oe,errorKeySym:se,nestedKeySym:ce,wildcardFirstSym:me,needsMetadataGsym:Symbol.for(`pino.metadata`),useOnlyCustomLevelsSym:D,formattersSym:_e,hooksSym:ve,nestedKeyStrSym:ue,mixinMergeStrategySym:de,msgPrefixSym:fe}})),require_redaction=__commonJSMin(((e,t)=>{let s=require_redact(),{redactFmtSym:g,wildcardFirstSym:S}=require_symbols(),w=/[^.[\]]+|\[([^[\]]*?)\]/g,E=`[Redacted]`,D=!1;function O(e,t){let{paths:E,censor:D,remove:O}=k(e),j=E.reduce((e,t)=>{w.lastIndex=0;let s=w.exec(t),g=w.exec(t),E=s[1]===void 0?s[0]:s[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,`$1`);if(E===`*`&&(E=S),g===null)return e[E]=null,e;if(e[E]===null)return e;let{index:D}=g,O=`${t.substr(D,t.length-1)}`;return e[E]=e[E]||[],E!==S&&e[E].length===0&&e[E].push(...e[S]||[]),E===S&&Object.keys(e).forEach(function(t){e[t]&&e[t].push(O)}),e[E].push(O),e},{}),F={[g]:s({paths:E,censor:D,serialize:t,strict:!1,remove:O})},L=(...e)=>t(typeof D==`function`?D(...e):D);return[...Object.keys(j),...Object.getOwnPropertySymbols(j)].reduce((e,g)=>{if(j[g]===null)e[g]=e=>L(e,[g]);else{let S=typeof D==`function`?(e,t)=>D(e,[g,...t]):D;e[g]=s({paths:j[g],censor:S,serialize:t,strict:!1,remove:O})}return e},F)}function k(e){if(Array.isArray(e))return e={paths:e,censor:E},e;let{paths:t,censor:s=E,remove:g}=e;if(Array.isArray(t)===!1)throw Error(`pino – redact must contain an array of strings`);return g===!0&&(s=void 0),{paths:t,censor:s,remove:g}}t.exports=O})),require_time=__commonJSMin(((e,t)=>{let s=()=>``,g=()=>`,"time":${Date.now()}`,S=()=>`,"time":${Math.round(Date.now()/1e3)}`,w=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,E=1000000n,D=1000000000n,O=BigInt(Date.now())*1000000n,k=process.hrtime.bigint();t.exports={nullTime:s,epochTime:g,unixTime:S,isoTime:w,isoTimeNano:()=>{let e=O+(process.hrtime.bigint()-k),t=e/D,s=e%D,g=Number(t*1000n+s/1000000n),S=new Date(g);return`,"time":"${S.getUTCFullYear()}-${(S.getUTCMonth()+1).toString().padStart(2,`0`)}-${S.getUTCDate().toString().padStart(2,`0`)}T${S.getUTCHours().toString().padStart(2,`0`)}:${S.getUTCMinutes().toString().padStart(2,`0`)}:${S.getUTCSeconds().toString().padStart(2,`0`)}.${s.toString().padStart(9,`0`)}Z"`}}})),require_quick_format_unescaped=__commonJSMin(((e,t)=>{function s(e){try{return JSON.stringify(e)}catch{return`"[Circular]"`}}t.exports=g;function g(e,t,g){var S=g&&g.stringify||s,w=1;if(typeof e==`object`&&e){var E=t.length+w;if(E===1)return e;var D=Array(E);D[0]=S(e);for(var O=1;O<E;O++)D[O]=S(t[O]);return D.join(` `)}if(typeof e!=`string`)return e;var k=t.length;if(k===0)return e;for(var j=``,F=1-w,L=-1,B=e&&e.length||0,H=0;H<B;){if(e.charCodeAt(H)===37&&H+1<B){switch(L=L>-1?L:0,e.charCodeAt(H+1)){case 100:case 102:if(F>=k||t[F]==null)break;L<H&&(j+=e.slice(L,H)),j+=Number(t[F]),L=H+2,H++;break;case 105:if(F>=k||t[F]==null)break;L<H&&(j+=e.slice(L,H)),j+=Math.floor(Number(t[F])),L=H+2,H++;break;case 79:case 111:case 106:if(F>=k||t[F]===void 0)break;L<H&&(j+=e.slice(L,H));var q=typeof t[F];if(q===`string`){j+=`'`+t[F]+`'`,L=H+2,H++;break}if(q===`function`){j+=t[F].name||`<anonymous>`,L=H+2,H++;break}j+=S(t[F]),L=H+2,H++;break;case 115:if(F>=k)break;L<H&&(j+=e.slice(L,H)),j+=String(t[F]),L=H+2,H++;break;case 37:L<H&&(j+=e.slice(L,H)),j+=`%`,L=H+2,H++,F--;break}++F}++H}return L===-1?e:(L<B&&(j+=e.slice(L)),j)}})),require_atomic_sleep=__commonJSMin(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function s(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=s}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),require_sonic_boom=__commonJSMin(((e,t)=>{let s=__require(`fs`),g=__require(`events`),S=__require(`util`).inherits,w=__require(`path`),E=require_atomic_sleep(),D=__require(`assert`),O=100,k=Buffer.allocUnsafe(0),j=16*1024,F=`buffer`,L=`utf8`,[B,H]=(process.versions.node||`0.0`).split(`.`).map(Number),q=B>=22&&H>=7;function ee(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function g(s,g){if(s){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,s)}):t.emit(`error`,s);return}let S=t._reopening;t.fd=g,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():S&&process.nextTick(()=>t.emit(`drain`)))}let S=t.append?`a`:`w`,E=t.mode;if(t.sync)try{t.mkdir&&s.mkdirSync(w.dirname(e),{recursive:!0}),g(null,s.openSync(e,S,E))}catch(e){throw g(e),e}else t.mkdir?s.mkdir(w.dirname(e),{recursive:!0},t=>{if(t)return g(t);s.open(e,S,E,g)}):s.open(e,S,E,g)}function J(e){if(!(this instanceof J))return new J(e);let{fd:t,dest:g,minLength:S,maxLength:w,maxWrite:D,periodicFlush:O,sync:j,append:B=!0,mkdir:H,retryEAGAIN:q,fsync:ne,contentMode:se,mode:ve}=e||{};t||=g,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(S||0,16387),this.file=null,this.destroyed=!1,this.minLength=S||0,this.maxLength=w||0,this.maxWrite=D||16384,this._periodicFlush=O||0,this._periodicFlushTimer=void 0,this.sync=j||!1,this.writable=!0,this._fsync=ne||!1,this.append=B||!1,this.mode=ve,this.retryEAGAIN=q||(()=>!0),this.mkdir=H||!1;let ye,Ce;if(se===F)this._writingBuf=k,this.write=oe,this.flush=ue,this.flushSync=fe,this._actualWrite=ge,ye=()=>s.writeSync(this.fd,this._writingBuf),Ce=()=>s.write(this.fd,this._writingBuf,this.release);else if(se===void 0||se===L)this._writingBuf=``,this.write=ae,this.flush=ce,this.flushSync=de,this._actualWrite=me,ye=()=>Buffer.isBuffer(this._writingBuf)?s.writeSync(this.fd,this._writingBuf):s.writeSync(this.fd,this._writingBuf,`utf8`),Ce=()=>Buffer.isBuffer(this._writingBuf)?s.write(this.fd,this._writingBuf,this.release):s.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${L}" and "${F}", but passed ${se}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)ee(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{E(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(Ce,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let g=Y(this._writingBuf,this._len,t);if(this._len=g.len,this._writingBuf=g.writingBuf,this._writingBuf.length){if(!this.sync){Ce();return}try{do{let e=ye(),t=Y(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&s.fsyncSync(this.fd);let S=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):S>this.minLength?this._actualWrite():this._ending?S>0?this._actualWrite():(this._writing=!1,_e(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(te,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Y(e,t,s){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-s,0),e=e.subarray(s),{writingBuf:e,len:t}}function te(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}S(J,g);function ne(e,t){return e.length===0?k:e.length===1?e[0]:Buffer.concat(e,t)}function ae(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),s=this._len+t,g=this._bufs;return this.maxLength&&s>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(g.length===0||Buffer.byteLength(g[g.length-1])+t>this.maxWrite?g.push(e):g[g.length-1]+=e,this._len=s,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function oe(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,s=this._bufs,g=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(s.length===0||g[g.length-1]+e.length>this.maxWrite?(s.push([e]),g.push(e.length)):(s[s.length-1].push(e),g[g.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function se(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{s.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,g)},g=s=>{this._flushPending=!1,e(s),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,g)}function ce(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&se.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function ue(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&se.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}J.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&s.close(t,e=>{if(e)return this.emit(`error`,e)})}),ee(this.file,this)},J.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():_e(this)))};function de(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?s.writeSync(this.fd,e):s.writeSync(this.fd,e,`utf8`),g=Y(e,this._len,t);e=g.writingBuf,this._len=g.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;E(100)}}try{s.fsyncSync(this.fd)}catch{}}function fe(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=k);let e=k;for(;this._bufs.length||e.length;){e.length<=0&&(e=ne(this._bufs[0],this._lens[0]));try{let t=s.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;E(100)}}}J.prototype.destroy=function(){this.destroyed||_e(this)};function me(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?s.writeSync(this.fd,this._writingBuf):s.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else s.write(this.fd,this._writingBuf,e)}function ge(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:ne(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,s.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else q&&(this._writingBuf=Buffer.from(this._writingBuf)),s.write(this.fd,this._writingBuf,e)}function _e(e){if(e.fd===-1){e.once(`ready`,_e.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],D(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{s.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?s.close(e.fd,g):g()}function g(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}J.SonicBoom=J,J.default=J,t.exports=J})),require_on_exit_leak_free=__commonJSMin(((e,t)=>{let s={exit:[],beforeExit:[]},g={exit:O,beforeExit:k},S;function w(){S===void 0&&(S=new FinalizationRegistry(F))}function E(e){s[e].length>0||process.on(e,g[e])}function D(e){s[e].length>0||(process.removeListener(e,g[e]),s.exit.length===0&&s.beforeExit.length===0&&(S=void 0))}function O(){j(`exit`)}function k(){j(`beforeExit`)}function j(e){for(let t of s[e]){let s=t.deref(),g=t.fn;s!==void 0&&g(s,e)}s[e]=[]}function F(e){for(let t of[`exit`,`beforeExit`]){let g=s[t].indexOf(e);s[t].splice(g,g+1),D(t)}}function L(e,t,g){if(t===void 0)throw Error(`the object can't be undefined`);E(e);let D=new WeakRef(t);D.fn=g,w(),S.register(t,D),s[e].push(D)}function B(e,t){L(`exit`,e,t)}function H(e,t){L(`beforeExit`,e,t)}function q(e){if(S!==void 0){S.unregister(e);for(let t of[`exit`,`beforeExit`])s[t]=s[t].filter(t=>{let s=t.deref();return s&&s!==e}),D(t)}}t.exports={register:B,registerBeforeExit:H,unregister:q}})),require_package=__commonJSMin(((e,t)=>{t.exports={name:`thread-stream`,version:`4.0.0`,description:`A streaming way to send data to a Node.js Worker Thread`,main:`index.js`,types:`index.d.ts`,engines:{node:`>=20`},dependencies:{"real-require":`^0.2.0`},devDependencies:{"@types/node":`^22.0.0`,"@yao-pkg/pkg":`^6.0.0`,borp:`^0.21.0`,desm:`^1.3.0`,eslint:`^9.39.1`,fastbench:`^1.0.1`,husky:`^9.0.6`,neostandard:`^0.12.2`,"pino-elasticsearch":`^8.0.0`,"sonic-boom":`^4.0.1`,"ts-node":`^10.8.0`,typescript:`~5.7.3`},scripts:{build:`tsc --noEmit`,lint:`eslint`,test:`npm run lint && npm run build && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:ci":`npm run lint && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:yarn":`npm run transpile && borp --pattern 'test/*.test.js'`,transpile:`sh ./test/ts/transpile.sh`,prepare:`husky install`},repository:{type:`git`,url:`git+https://github.com/mcollina/thread-stream.git`},keywords:[`worker`,`thread`,`threads`,`stream`],author:`Matteo Collina <hello@matteocollina.com>`,license:`MIT`,bugs:{url:`https://github.com/mcollina/thread-stream/issues`},homepage:`https://github.com/mcollina/thread-stream#readme`}})),require_wait=__commonJSMin(((e,t)=>{let s=1e4;function g(e,t,g,S,w){let E=S===1/0?1/0:Date.now()+S,D=()=>{let S=Atomics.load(e,t);if(S===g){w(null,`ok`);return}if(E!==1/0&&Date.now()>E){w(null,`timed-out`);return}let O=E===1/0?s:Math.min(s,Math.max(1,E-Date.now())),k=Atomics.waitAsync(e,t,S,O);k.async?k.value.then(D):setImmediate(D)};D()}function S(e,t,g,S,w){let E=S===1/0?1/0:Date.now()+S,D=()=>{if(Atomics.load(e,t)!==g){w(null,`ok`);return}if(E!==1/0&&Date.now()>E){w(null,`timed-out`);return}let S=E===1/0?s:Math.min(s,Math.max(1,E-Date.now())),O=Atomics.waitAsync(e,t,g,S);O.async?O.value.then(D):setImmediate(D)};D()}t.exports={wait:g,waitDiff:S}})),require_indexes=__commonJSMin(((e,t)=>{t.exports={WRITE_INDEX:4,READ_INDEX:8}})),require_thread_stream=__commonJSMin(((e,t)=>{let{version:s}=require_package(),{EventEmitter:g}=__require(`events`),{Worker:S}=__require(`worker_threads`),{join:w}=__require(`path`),{pathToFileURL:E}=__require(`url`),{wait:D}=require_wait(),{WRITE_INDEX:O,READ_INDEX:k}=require_indexes(),j=__require(`buffer`),F=__require(`assert`),L=Symbol(`kImpl`),B=j.constants.MAX_STRING_LENGTH;var H=class{constructor(e){this._value=e}deref(){return this._value}},q=class{register(){}unregister(){}};let ee=process.env.NODE_V8_COVERAGE?q:global.FinalizationRegistry||q,J=process.env.NODE_V8_COVERAGE?H:global.WeakRef||H,Y=new ee(e=>{e.exited||e.terminate()});function te(e,t){let{filename:g,workerData:D}=t,O=new S((`__bundlerPathsOverrides`in globalThis?globalThis.__bundlerPathsOverrides:{})[`thread-stream-worker`]||w(__dirname,`lib`,`worker.js`),{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:g.indexOf(`file://`)===0?g:E(g).href,dataBuf:e[L].dataBuf,stateBuf:e[L].stateBuf,workerData:{$context:{threadStreamVersion:s},...D}}});return O.stream=new H(e),O.on(`message`,oe),O.on(`exit`,se),Y.register(e,O),O}function ne(e){F(!e[L].sync),e[L].needDrain&&(e[L].needDrain=!1,e.emit(`drain`))}function ae(e){let t=Atomics.load(e[L].state,O),s=e[L].data.length-t;if(s>0){if(e[L].buf.length===0){e[L].flushing=!1,e[L].ending?me(e):e[L].needDrain&&process.nextTick(ne,e);return}let t=e[L].buf.slice(0,s),g=Buffer.byteLength(t);g<=s?(e[L].buf=e[L].buf.slice(s),fe(e,t,ae.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[L].state,k,0),Atomics.store(e[L].state,O,0),Atomics.notify(e[L].state,k);g>e[L].data.length;)s/=2,t=e[L].buf.slice(0,s),g=Buffer.byteLength(t);e[L].buf=e[L].buf.slice(s),fe(e,t,ae.bind(null,e))}})}else if(s===0){if(t===0&&e[L].buf.length===0)return;e.flush(()=>{Atomics.store(e[L].state,k,0),Atomics.store(e[L].state,O,0),Atomics.notify(e[L].state,k),ae(e)})}else de(e,Error(`overwritten`))}function oe(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case`READY`:this.stream=new J(t),t.flush(()=>{t[L].ready=!0,t.emit(`ready`)});break;case`ERROR`:de(t,e.err);break;case`EVENT`:Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case`WARNING`:process.emitWarning(e.err);break;default:de(t,Error(`this should not happen: `+e.code))}}function se(e){let t=this.stream.deref();t!==void 0&&(Y.unregister(t),t.worker.exited=!0,t.worker.off(`exit`,se),de(t,e===0?null:Error(`the worker thread exited`)))}var ce=class extends g{constructor(e={}){if(super(),e.bufferSize<4)throw Error(`bufferSize must at least fit a 4-byte utf-8 char`);this[L]={},this[L].stateBuf=new SharedArrayBuffer(128),this[L].state=new Int32Array(this[L].stateBuf),this[L].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[L].data=Buffer.from(this[L].dataBuf),this[L].sync=e.sync||!1,this[L].ending=!1,this[L].ended=!1,this[L].needDrain=!1,this[L].destroyed=!1,this[L].flushing=!1,this[L].ready=!1,this[L].finished=!1,this[L].errored=null,this[L].closed=!1,this[L].buf=``,this.worker=te(this,e),this.on(`message`,(e,t)=>{this.worker.postMessage(e,t)})}write(e){if(this[L].destroyed)return ue(this,Error(`the worker has exited`)),!1;if(this[L].ending)return ue(this,Error(`the worker is ending`)),!1;if(this[L].flushing&&this[L].buf.length+e.length>=B)try{ge(this),this[L].flushing=!0}catch(e){return de(this,e),!1}if(this[L].buf+=e,this[L].sync)try{return ge(this),!0}catch(e){return de(this,e),!1}return this[L].flushing||(this[L].flushing=!0,setImmediate(ae,this)),this[L].needDrain=this[L].data.length-this[L].buf.length-Atomics.load(this[L].state,O)<=0,!this[L].needDrain}end(){this[L].destroyed||(this[L].ending=!0,me(this))}flush(e){if(this[L].destroyed){typeof e==`function`&&process.nextTick(e,Error(`the worker has exited`));return}let t=Atomics.load(this[L].state,O);D(this[L].state,k,t,1/0,(t,s)=>{if(t){de(this,t),process.nextTick(e,t);return}if(s===`not-equal`){this.flush(e);return}process.nextTick(e)})}flushSync(){this[L].destroyed||(ge(this),_e(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[L].ready}get destroyed(){return this[L].destroyed}get closed(){return this[L].closed}get writable(){return!this[L].destroyed&&!this[L].ending}get writableEnded(){return this[L].ending}get writableFinished(){return this[L].finished}get writableNeedDrain(){return this[L].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[L].errored}};function ue(e,t){setImmediate(()=>{e.emit(`error`,t)})}function de(e,t){e[L].destroyed||(e[L].destroyed=!0,t&&(e[L].errored=t,ue(e,t)),e.worker.exited?setImmediate(()=>{e[L].closed=!0,e.emit(`close`)}):e.worker.terminate().catch(()=>{}).then(()=>{e[L].closed=!0,e.emit(`close`)}))}function fe(e,t,s){let g=Atomics.load(e[L].state,O),S=Buffer.byteLength(t);return e[L].data.write(t,g),Atomics.store(e[L].state,O,g+S),Atomics.notify(e[L].state,O),s(),!0}function me(e){if(!(e[L].ended||!e[L].ending||e[L].flushing)){e[L].ended=!0;try{e.flushSync();let t=Atomics.load(e[L].state,k);Atomics.store(e[L].state,O,-1),Atomics.notify(e[L].state,O);let s=0;for(;t!==-1;){if(Atomics.wait(e[L].state,k,t,1e3),t=Atomics.load(e[L].state,k),t===-2){de(e,Error(`end() failed`));return}if(++s===10){de(e,Error(`end() took too long (10s)`));return}}process.nextTick(()=>{e[L].finished=!0,e.emit(`finish`)})}catch(t){de(e,t)}}}function ge(e){let t=()=>{e[L].ending?me(e):e[L].needDrain&&process.nextTick(ne,e)};for(e[L].flushing=!1;e[L].buf.length!==0;){let s=Atomics.load(e[L].state,O),g=e[L].data.length-s;if(g===0){_e(e),Atomics.store(e[L].state,k,0),Atomics.store(e[L].state,O,0),Atomics.notify(e[L].state,k);continue}else if(g<0)throw Error(`overwritten`);let S=e[L].buf.slice(0,g),w=Buffer.byteLength(S);if(w<=g)e[L].buf=e[L].buf.slice(g),fe(e,S,t);else{for(_e(e),Atomics.store(e[L].state,k,0),Atomics.store(e[L].state,O,0),Atomics.notify(e[L].state,k);w>e[L].buf.length;)g/=2,S=e[L].buf.slice(0,g),w=Buffer.byteLength(S);e[L].buf=e[L].buf.slice(g),fe(e,S,t)}}}function _e(e){if(e[L].flushing)throw Error(`unable to flush while flushing`);let t=Atomics.load(e[L].state,O),s=0;for(;;){let g=Atomics.load(e[L].state,k);if(g===-2)throw Error(`_flushSync failed`);if(g!==t)Atomics.wait(e[L].state,k,g,1e3);else break;if(++s===10)throw Error(`_flushSync took too long (10s)`)}}t.exports=ce})),require_transport=__commonJSMin(((e,t)=>{let{createRequire:s}=__require(`module`),{existsSync:g}=__require(`node:fs`),S=require_caller(),{join:w,isAbsolute:E,sep:D}=__require(`node:path`),{fileURLToPath:O}=__require(`node:url`),k=require_atomic_sleep(),j=require_on_exit_leak_free(),F=require_thread_stream();function L(e){j.register(e,Y),j.registerBeforeExit(e,te),e.on(`close`,function(){j.unregister(e)})}function B(){let e=process.execArgv;for(let t=0;t<e.length;t++){let s=e[t];if(s===`--import`||s===`--require`||s===`-r`||s.startsWith(`--import=`)||s.startsWith(`--require=`)||s.startsWith(`-r=`))return!0}return!1}function H(e){let t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!t)return e;let s=[],g=!1;for(let e=0;e<t.length;e++){let S=t[e];if(S===`--require`||S===`-r`||S===`--import`){let w=t[e+1];if(w&&q(w)){g=!0,e++;continue}s.push(S),w&&(s.push(w),e++);continue}if((S.startsWith(`--require=`)||S.startsWith(`-r=`)||S.startsWith(`--import=`))&&q(S.slice(S.indexOf(`=`)+1))){g=!0;continue}s.push(S)}return g?s.join(` `):e}function q(e){let t=ee(e);if(!t)return!1;let s=t;if(s.startsWith(`file://`))try{s=O(s)}catch{return!1}return E(s)&&!g(s)}function ee(e){let t=e[0],s=e[e.length-1];return t===`"`&&s===`"`||t===`'`&&s===`'`?e.slice(1,-1):e}function J(e,t,s,g,S){if(!s.execArgv&&B()&&__require.main===void 0&&(s={...s,execArgv:[]}),!s.env&&process.env.NODE_OPTIONS){let e=H(process.env.NODE_OPTIONS);e!==process.env.NODE_OPTIONS&&(s={...s,env:{...process.env,NODE_OPTIONS:e}})}s={...s,name:S};let w=new F({filename:e,workerData:t,workerOpts:s,sync:g});w.on(`ready`,E),w.on(`close`,function(){process.removeListener(`exit`,D)}),process.on(`exit`,D);function E(){process.removeListener(`exit`,D),w.unref(),s.autoEnd!==!1&&L(w)}function D(){w.closed||(w.flushSync(),k(100),w.end())}return w}function Y(e){e.ref(),e.flushSync(),e.end(),e.once(`close`,function(){e.unref()})}function te(e){e.flushSync()}function ne(e){let{pipeline:t,targets:g,levels:O,dedupe:k,worker:j={},caller:F=S(),sync:L=!1}=e,B={...e.options},H=typeof F==`string`?[F]:F,q=typeof globalThis==`object`&&Object.prototype.hasOwnProperty.call(globalThis,`__bundlerPathsOverrides`)&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==`object`?globalThis.__bundlerPathsOverrides:Object.create(null),ee=e.target;if(ee&&g)throw Error(`only one of target or targets can be specified`);g?(ee=q[`pino-worker`]||w(__dirname,`worker.js`),B.targets=g.filter(e=>e.target).map(e=>({...e,target:te(e.target)})),B.pipelines=g.filter(e=>e.pipeline).map(e=>e.pipeline.map(t=>({...t,level:e.level,target:te(t.target)})))):t&&(ee=q[`pino-worker`]||w(__dirname,`worker.js`),B.pipelines=[t.map(e=>({...e,target:te(e.target)}))]),O&&(B.levels=O),k&&(B.dedupe=k),B.pinoWillSendConfig=!0;let Y=g||t?`pino.transport`:ee;return J(te(ee),B,j,L,Y);function te(e){if(e=q[e]||e,E(e)||e.indexOf(`file://`)===0)return e;if(e===`pino/file`)return w(__dirname,`..`,`file.js`);let t;for(let g of H)try{t=s(g===`node:repl`?process.cwd()+D:g).resolve(e);break}catch{continue}if(!t)throw Error(`unable to determine transport target for "${e}"`);return t}}t.exports=ne})),require_tools=__commonJSMin(((e,t)=>{let s=__require(`node:diagnostics_channel`),g=require_quick_format_unescaped(),{mapHttpRequest:S,mapHttpResponse:w}=require_pino_std_serializers(),E=require_sonic_boom(),D=require_on_exit_leak_free(),{lsCacheSym:O,chindingsSym:k,writeSym:j,serializersSym:F,formatOptsSym:L,endSym:B,stringifiersSym:H,stringifySym:q,stringifySafeSym:ee,wildcardFirstSym:J,nestedKeySym:Y,formattersSym:te,messageKeySym:ne,errorKeySym:ae,nestedKeyStrSym:oe,msgPrefixSym:se}=require_symbols(),{isMainThread:ce}=__require(`worker_threads`),ue=require_transport(),[de]=process.versions.node.split(`.`).map(e=>Number(e)),fe=s.tracingChannel(`pino_asJson`),me=de>=25?e=>JSON.stringify(e):ve;function ge(){}function _e(e,t){if(!t)return s;return function(...g){t.call(this,g,s,e)};function s(t,...s){if(typeof t==`object`){let E=t;t!==null&&(t.method&&t.headers&&t.socket?t=S(t):typeof t.setHeader==`function`&&(t=w(t)));let D;E===null&&s.length===0?D=[null]:(E=s.shift(),D=s),typeof this[se]==`string`&&E!=null&&(E=this[se]+E),this[j](t,g(E,D,this[L]),e)}else{let S=t===void 0?s.shift():t;typeof this[se]==`string`&&S!=null&&(S=this[se]+S),this[j](null,g(S,s,this[L]),e)}}}function ve(e){let t=``,s=0,g=!1,S=255,w=e.length;if(w>100)return JSON.stringify(e);for(var E=0;E<w&&S>=32;E++)S=e.charCodeAt(E),(S===34||S===92)&&(t+=e.slice(s,E)+`\\`,s=E,g=!0);return g?t+=e.slice(s):t=e,S<32?JSON.stringify(e):`"`+t+`"`}function ye(e,t,s,g){if(fe.hasSubscribers===!1)return Ce.call(this,e,t,s,g);let S={instance:this,arguments};return fe.traceSync(Ce,S,this,e,t,s,g)}function Ce(e,t,s,g){let S=this[q],w=this[ee],E=this[H],D=this[B],j=this[k],L=this[F],se=this[te],ce=this[ne],ue=this[ae],de=this[O][s]+g;de+=j;let fe;se.log&&(e=se.log(e));let ge=E[J],_e=``;for(let t in e)if(fe=e[t],Object.prototype.hasOwnProperty.call(e,t)&&fe!==void 0){L[t]?fe=L[t](fe):t===ue&&L.err&&(fe=L.err(fe));let e=E[t]||ge;switch(typeof fe){case`undefined`:case`function`:continue;case`number`:Number.isFinite(fe)===!1&&(fe=null);case`boolean`:e&&(fe=e(fe));break;case`string`:fe=(e||me)(fe);break;default:fe=(e||S)(fe,w)}if(fe===void 0)continue;let s=me(t);_e+=`,`+s+`:`+fe}let ve=``;if(t!==void 0){fe=L[ce]?L[ce](t):t;let e=E[ce]||ge;switch(typeof fe){case`function`:break;case`number`:Number.isFinite(fe)===!1&&(fe=null);case`boolean`:e&&(fe=e(fe)),ve=`,"`+ce+`":`+fe;break;case`string`:fe=(e||me)(fe),ve=`,"`+ce+`":`+fe;break;default:fe=(e||S)(fe,w),ve=`,"`+ce+`":`+fe}}return this[Y]&&_e?de+this[oe]+_e.slice(1)+`}`+ve+D:de+_e+ve+D}function we(e,t){let s,g=e[k],S=e[q],w=e[ee],E=e[H],D=E[J],O=e[F],j=e[te].bindings;t=j(t);for(let e in t)if(s=t[e],((e.length<5||e!==`level`&&e!==`serializers`&&e!==`formatters`&&e!==`customLevels`)&&t.hasOwnProperty(e)&&s!==void 0)===!0){if(s=O[e]?O[e](s):s,s=(E[e]||D||S)(s,w),s===void 0)continue;g+=`,"`+e+`":`+s}return g}function Te(e){return e.write!==e.constructor.prototype.write}function De(e){let t=new E(e);return t.on(`error`,s),!e.sync&&ce&&(D.register(t,je),t.on(`close`,function(){D.unregister(t)})),t;function s(e){if(e.code===`EPIPE`){t.write=ge,t.end=ge,t.flushSync=ge,t.destroy=ge;return}t.removeListener(`error`,s),t.emit(`error`,e)}}function je(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function Me(e){return function(t,s,g={},S){if(typeof g==`string`)S=De({dest:g}),g={};else if(typeof S==`string`){if(g&&g.transport)throw Error(`only one of option.transport or stream can be specified`);S=De({dest:S})}else if(g instanceof E||g.writable||g._writableState)S=g,g={};else if(g.transport){if(g.transport instanceof E||g.transport.writable||g.transport._writableState)throw Error(`option.transport do not allow stream, please pass to option directly. e.g. pino(transport)`);if(g.transport.targets&&g.transport.targets.length&&g.formatters&&typeof g.formatters.level==`function`)throw Error(`option.transport.targets do not allow custom level formatters`);let e;g.customLevels&&(e=g.useOnlyCustomLevels?g.customLevels:Object.assign({},g.levels,g.customLevels)),S=ue({caller:s,...g.transport,levels:e})}if(g=Object.assign({},e,g),g.serializers=Object.assign({},e.serializers,g.serializers),g.formatters=Object.assign({},e.formatters,g.formatters),g.prettyPrint)throw Error(`prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)`);let{enabled:w,onChild:D}=g;return w===!1&&(g.level=`silent`),D||(g.onChild=ge),S||=Te(process.stdout)?process.stdout:De({fd:process.stdout.fd||1}),{opts:g,stream:S}}}function Pe(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[ee])(e)}catch{return`"[unable to serialize, circular reference is too complex to analyze]"`}}}function Ie(e,t,s){return{level:e,bindings:t,log:s}}function Re(e){let t=Number(e);return typeof e==`string`&&Number.isFinite(t)?t:e===void 0?1:e}t.exports={noop:ge,buildSafeSonicBoom:De,asChindings:we,asJson:ye,genLog:_e,createArgsNormalizer:Me,stringify:Pe,buildFormatters:Ie,normalizeDestFileDescriptor:Re}})),require_constants$1=__commonJSMin(((e,t)=>{t.exports={DEFAULT_LEVELS:{trace:10,debug:20,info:30,warn:40,error:50,fatal:60},SORTING_ORDER:{ASC:`ASC`,DESC:`DESC`}}})),require_levels=__commonJSMin(((e,t)=>{let{lsCacheSym:s,levelValSym:g,useOnlyCustomLevelsSym:S,streamSym:w,formattersSym:E,hooksSym:D,levelCompSym:O}=require_symbols(),{noop:k,genLog:j}=require_tools(),{DEFAULT_LEVELS:F,SORTING_ORDER:L}=require_constants$1(),B={fatal:e=>{let t=j(F.fatal,e);return function(...e){let s=this[w];if(t.call(this,...e),typeof s.flushSync==`function`)try{s.flushSync()}catch{}}},error:e=>j(F.error,e),warn:e=>j(F.warn,e),info:e=>j(F.info,e),debug:e=>j(F.debug,e),trace:e=>j(F.trace,e)},H=Object.keys(F).reduce((e,t)=>(e[F[t]]=t,e),{}),q=Object.keys(H).reduce((e,t)=>(e[t]=`{"level":`+Number(t),e),{});function ee(e){let t=e[E].level,{labels:g}=e.levels,S={};for(let e in g){let s=t(g[e],Number(e));S[e]=JSON.stringify(s).slice(0,-1)}return e[s]=S,e}function J(e,t){if(t)return!1;switch(e){case`fatal`:case`error`:case`warn`:case`info`:case`debug`:case`trace`:return!0;default:return!1}}function Y(e){let{labels:t,values:s}=this.levels;if(typeof e==`number`){if(t[e]===void 0)throw Error(`unknown level value`+e);e=t[e]}if(s[e]===void 0)throw Error(`unknown level `+e);let w=this[g],E=this[g]=s[e],F=this[S],L=this[O],H=this[D].logMethod;for(let e in s){if(L(s[e],E)===!1){this[e]=k;continue}this[e]=J(e,F)?B[e](H):j(s[e],H)}this.emit(`level-change`,e,E,t[w],w,this)}function te(e){let{levels:t,levelVal:s}=this;return t&&t.labels?t.labels[s]:``}function ne(e){let{values:t}=this.levels,s=t[e];return s!==void 0&&this[O](s,this[g])}function ae(e,t,s){return e===L.DESC?t<=s:t>=s}function oe(e){return typeof e==`string`?ae.bind(null,e):e}function se(e=null,t=!1){let s=e?Object.keys(e).reduce((t,s)=>(t[e[s]]=s,t),{}):null;return{labels:Object.assign(Object.create(Object.prototype,{Infinity:{value:`silent`}}),t?null:H,s),values:Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:F,e)}}function ce(e,t,s){if(typeof e==`number`){if(![].concat(Object.keys(t||{}).map(e=>t[e]),s?[]:Object.keys(H).map(e=>+e),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}if(!(e in Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),s?null:F,t)))throw Error(`default level:${e} must be included in custom levels`)}function ue(e,t){let{labels:s,values:g}=e;for(let e in t){if(e in g)throw Error(`levels cannot be overridden`);if(t[e]in s)throw Error(`pre-existing level values cannot be used for new levels`)}}function de(e){if(typeof e!=`function`&&!(typeof e==`string`&&Object.values(L).includes(e)))throw Error(`Levels comparison should be one of "ASC", "DESC" or "function" type`)}t.exports={initialLsCache:q,genLsCache:ee,levelMethods:B,getLevel:te,setLevel:Y,isLevelEnabled:ne,mappings:se,assertNoLevelCollisions:ue,assertDefaultLevelFound:ce,genLevelComparison:oe,assertLevelComparison:de}})),require_meta=__commonJSMin(((e,t)=>{t.exports={version:`10.3.1`}})),require_proto=__commonJSMin(((e,t)=>{let{EventEmitter:s}=__require(`node:events`),{lsCacheSym:g,levelValSym:S,setLevelSym:w,getLevelSym:E,chindingsSym:D,mixinSym:O,asJsonSym:k,writeSym:j,mixinMergeStrategySym:F,timeSym:L,timeSliceIndexSym:B,streamSym:H,serializersSym:q,formattersSym:ee,errorKeySym:J,messageKeySym:Y,useOnlyCustomLevelsSym:te,needsMetadataGsym:ne,redactFmtSym:ae,stringifySym:oe,formatOptsSym:se,stringifiersSym:ce,msgPrefixSym:ue,hooksSym:de}=require_symbols(),{getLevel:fe,setLevel:me,isLevelEnabled:ge,mappings:_e,initialLsCache:ve,genLsCache:ye,assertNoLevelCollisions:Ce}=require_levels(),{asChindings:we,asJson:Te,buildFormatters:De,stringify:je,noop:Me}=require_tools(),{version:Pe}=require_meta(),Ie=require_redaction(),Re={constructor:class{},child:Be,bindings:Ve,setBindings:Ue,flush:Ke,isLevelEnabled:ge,version:Pe,get level(){return this[E]()},set level(e){this[w](e)},get levelVal(){return this[S]},set levelVal(e){throw Error(`levelVal is read-only`)},get msgPrefix(){return this[ue]},get[Symbol.toStringTag](){return`Pino`},[g]:ve,[j]:Ge,[k]:Te,[E]:fe,[w]:me};Object.setPrototypeOf(Re,s.prototype),t.exports=function(){return Object.create(Re)};let ze=e=>e;function Be(e,t){if(!e)throw Error(`missing bindings for child Pino`);let s=this[q],g=this[ee],S=Object.create(this);if(t==null)return S[ee].bindings!==ze&&(S[ee]=De(g.level,ze,g.log)),S[D]=we(S,e),this.onChild!==Me&&this.onChild(S),S;if(t.hasOwnProperty(`serializers`)===!0){S[q]=Object.create(null);for(let e in s)S[q][e]=s[e];let e=Object.getOwnPropertySymbols(s);for(var E=0;E<e.length;E++){let t=e[E];S[q][t]=s[t]}for(let e in t.serializers)S[q][e]=t.serializers[e];let g=Object.getOwnPropertySymbols(t.serializers);for(var O=0;O<g.length;O++){let e=g[O];S[q][e]=t.serializers[e]}}else S[q]=s;if(t.hasOwnProperty(`formatters`)){let{level:e,bindings:s,log:w}=t.formatters;S[ee]=De(e||g.level,s||ze,w||g.log)}else S[ee]=De(g.level,ze,g.log);if(t.hasOwnProperty(`customLevels`)===!0&&(Ce(this.levels,t.customLevels),S.levels=_e(t.customLevels,S[te]),ye(S)),typeof t.redact==`object`&&t.redact!==null||Array.isArray(t.redact)){S.redact=t.redact;let e=Ie(S.redact,je),s={stringify:e[ae]};S[oe]=je,S[ce]=e,S[se]=s}if(typeof t.msgPrefix==`string`&&(S[ue]=(this[ue]||``)+t.msgPrefix),S[D]=we(S,e),t.level!==void 0&&t.level!==this.level||t.hasOwnProperty(`customLevels`)){let e=t.level||this.level;S[w](e)}return this.onChild(S),S}function Ve(){let e=`{${this[D].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function Ue(e){this[D]=we(this,e)}function We(e,t){return Object.assign(t,e)}function Ge(e,t,s){let g=this[L](),S=this[O],w=this[J],E=this[Y],D=this[F]||We,j,q=this[de].streamWrite;e==null?j={}:e instanceof Error?(j={[w]:e},t===void 0&&(t=e.message)):(j=e,t===void 0&&e[E]===void 0&&e[w]&&(t=e[w].message)),S&&(j=D(j,S(j,s,this)));let ee=this[k](j,t,s,g),te=this[H];te[ne]===!0&&(te.lastLevel=s,te.lastObj=j,te.lastMsg=t,te.lastTime=g.slice(this[B]),te.lastLogger=this),te.write(q?q(ee):ee)}function Ke(e){if(e!=null&&typeof e!=`function`)throw Error(`callback must be a function`);let t=this[H];typeof t.flush==`function`?t.flush(e||Me):e&&e()}})),require_safe_stable_stringify=__commonJSMin(((e,t)=>{let{hasOwnProperty:s}=Object.prototype,g=J();g.configure=J,g.stringify=g,g.default=g,e.stringify=g,e.configure=J,t.exports=g;let S=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function w(e){return e.length<5e3&&!S.test(e)?`"${e}"`:JSON.stringify(e)}function E(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){let s=e[t],g=t;for(;g!==0&&e[g-1]>s;)e[g]=e[g-1],g--;e[g]=s}return e}let D=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function O(e){return D.call(e)!==void 0&&e.length!==0}function k(e,t,s){e.length<s&&(s=e.length);let g=t===`,`?``:` `,S=`"0":${g}${e[0]}`;for(let w=1;w<s;w++)S+=`${t}"${w}":${g}${e[w]}`;return S}function j(e){if(s.call(e,`circularValue`)){let t=e.circularValue;if(typeof t==`string`)return`"${t}"`;if(t==null)return t;if(t===Error||t===TypeError)return{toString(){throw TypeError(`Converting circular structure to JSON`)}};throw TypeError(`The "circularValue" argument must be of type string or the value null or undefined`)}return`"[Circular]"`}function F(e){let t;if(s.call(e,`deterministic`)&&(t=e.deterministic,typeof t!=`boolean`&&typeof t!=`function`))throw TypeError(`The "deterministic" argument must be of type boolean or comparator function`);return t===void 0?!0:t}function L(e,t){let g;if(s.call(e,t)&&(g=e[t],typeof g!=`boolean`))throw TypeError(`The "${t}" argument must be of type boolean`);return g===void 0?!0:g}function B(e,t){let g;if(s.call(e,t)){if(g=e[t],typeof g!=`number`)throw TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(g))throw TypeError(`The "${t}" argument must be an integer`);if(g<1)throw RangeError(`The "${t}" argument must be >= 1`)}return g===void 0?1/0:g}function H(e){return e===1?`1 item`:`${e} items`}function q(e){let t=new Set;for(let s of e)(typeof s==`string`||typeof s==`number`)&&t.add(String(s));return t}function ee(e){if(s.call(e,`strict`)){let t=e.strict;if(typeof t!=`boolean`)throw TypeError(`The "strict" argument must be of type boolean`);if(t)return e=>{let t=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!=`function`&&(t+=` (${e.toString()})`),Error(t)}}}function J(e){e={...e};let t=ee(e);t&&(e.bigint===void 0&&(e.bigint=!1),`circularValue`in e||(e.circularValue=Error));let s=j(e),g=L(e,`bigint`),S=F(e),D=typeof S==`function`?S:void 0,J=B(e,`maximumDepth`),Y=B(e,`maximumBreadth`);function te(e,k,j,F,L,B){let q=k[e];switch(typeof q==`object`&&q&&typeof q.toJSON==`function`&&(q=q.toJSON(e)),q=F.call(k,e,q),typeof q){case`string`:return w(q);case`object`:{if(q===null)return`null`;if(j.indexOf(q)!==-1)return s;let e=``,t=`,`,g=B;if(Array.isArray(q)){if(q.length===0)return`[]`;if(J<j.length+1)return`"[Array]"`;j.push(q),L!==``&&(B+=L,e+=`\n${B}`,t=`,\n${B}`);let s=Math.min(q.length,Y),S=0;for(;S<s-1;S++){let s=te(String(S),q,j,F,L,B);e+=s===void 0?`null`:s,e+=t}let w=te(String(S),q,j,F,L,B);if(e+=w===void 0?`null`:w,q.length-1>Y){let s=q.length-Y-1;e+=`${t}"... ${H(s)} not stringified"`}return L!==``&&(e+=`\n${g}`),j.pop(),`[${e}]`}let k=Object.keys(q),ee=k.length;if(ee===0)return`{}`;if(J<j.length+1)return`"[Object]"`;let ne=``,ae=``;L!==``&&(B+=L,t=`,\n${B}`,ne=` `);let oe=Math.min(ee,Y);S&&!O(q)&&(k=E(k,D)),j.push(q);for(let s=0;s<oe;s++){let g=k[s],S=te(g,q,j,F,L,B);S!==void 0&&(e+=`${ae}${w(g)}:${ne}${S}`,ae=t)}if(ee>Y){let s=ee-Y;e+=`${ae}"...":${ne}"${H(s)} not stringified"`,ae=t}return L!==``&&ae.length>1&&(e=`\n${B}${e}\n${g}`),j.pop(),`{${e}}`}case`number`:return isFinite(q)?String(q):t?t(q):`null`;case`boolean`:return q===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(g)return String(q);default:return t?t(q):void 0}}function ne(e,S,E,D,O,k){switch(typeof S==`object`&&S&&typeof S.toJSON==`function`&&(S=S.toJSON(e)),typeof S){case`string`:return w(S);case`object`:{if(S===null)return`null`;if(E.indexOf(S)!==-1)return s;let e=k,t=``,g=`,`;if(Array.isArray(S)){if(S.length===0)return`[]`;if(J<E.length+1)return`"[Array]"`;E.push(S),O!==``&&(k+=O,t+=`\n${k}`,g=`,\n${k}`);let s=Math.min(S.length,Y),w=0;for(;w<s-1;w++){let e=ne(String(w),S[w],E,D,O,k);t+=e===void 0?`null`:e,t+=g}let j=ne(String(w),S[w],E,D,O,k);if(t+=j===void 0?`null`:j,S.length-1>Y){let e=S.length-Y-1;t+=`${g}"... ${H(e)} not stringified"`}return O!==``&&(t+=`\n${e}`),E.pop(),`[${t}]`}E.push(S);let j=``;O!==``&&(k+=O,g=`,\n${k}`,j=` `);let F=``;for(let e of D){let s=ne(e,S[e],E,D,O,k);s!==void 0&&(t+=`${F}${w(e)}:${j}${s}`,F=g)}return O!==``&&F.length>1&&(t=`\n${k}${t}\n${e}`),E.pop(),`{${t}}`}case`number`:return isFinite(S)?String(S):t?t(S):`null`;case`boolean`:return S===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(g)return String(S);default:return t?t(S):void 0}}function ae(e,j,F,L,B){switch(typeof j){case`string`:return w(j);case`object`:{if(j===null)return`null`;if(typeof j.toJSON==`function`){if(j=j.toJSON(e),typeof j!=`object`)return ae(e,j,F,L,B);if(j===null)return`null`}if(F.indexOf(j)!==-1)return s;let t=B;if(Array.isArray(j)){if(j.length===0)return`[]`;if(J<F.length+1)return`"[Array]"`;F.push(j),B+=L;let e=`\n${B}`,s=`,\n${B}`,g=Math.min(j.length,Y),S=0;for(;S<g-1;S++){let t=ae(String(S),j[S],F,L,B);e+=t===void 0?`null`:t,e+=s}let w=ae(String(S),j[S],F,L,B);if(e+=w===void 0?`null`:w,j.length-1>Y){let t=j.length-Y-1;e+=`${s}"... ${H(t)} not stringified"`}return e+=`\n${t}`,F.pop(),`[${e}]`}let g=Object.keys(j),q=g.length;if(q===0)return`{}`;if(J<F.length+1)return`"[Object]"`;B+=L;let ee=`,\n${B}`,te=``,ne=``,oe=Math.min(q,Y);O(j)&&(te+=k(j,ee,Y),g=g.slice(j.length),oe-=j.length,ne=ee),S&&(g=E(g,D)),F.push(j);for(let e=0;e<oe;e++){let t=g[e],s=ae(t,j[t],F,L,B);s!==void 0&&(te+=`${ne}${w(t)}: ${s}`,ne=ee)}if(q>Y){let e=q-Y;te+=`${ne}"...": "${H(e)} not stringified"`,ne=ee}return ne!==``&&(te=`\n${B}${te}\n${t}`),F.pop(),`{${te}}`}case`number`:return isFinite(j)?String(j):t?t(j):`null`;case`boolean`:return j===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(g)return String(j);default:return t?t(j):void 0}}function oe(e,j,F){switch(typeof j){case`string`:return w(j);case`object`:{if(j===null)return`null`;if(typeof j.toJSON==`function`){if(j=j.toJSON(e),typeof j!=`object`)return oe(e,j,F);if(j===null)return`null`}if(F.indexOf(j)!==-1)return s;let t=``,g=j.length!==void 0;if(g&&Array.isArray(j)){if(j.length===0)return`[]`;if(J<F.length+1)return`"[Array]"`;F.push(j);let e=Math.min(j.length,Y),s=0;for(;s<e-1;s++){let e=oe(String(s),j[s],F);t+=e===void 0?`null`:e,t+=`,`}let g=oe(String(s),j[s],F);if(t+=g===void 0?`null`:g,j.length-1>Y){let e=j.length-Y-1;t+=`,"... ${H(e)} not stringified"`}return F.pop(),`[${t}]`}let L=Object.keys(j),B=L.length;if(B===0)return`{}`;if(J<F.length+1)return`"[Object]"`;let q=``,ee=Math.min(B,Y);g&&O(j)&&(t+=k(j,`,`,Y),L=L.slice(j.length),ee-=j.length,q=`,`),S&&(L=E(L,D)),F.push(j);for(let e=0;e<ee;e++){let s=L[e],g=oe(s,j[s],F);g!==void 0&&(t+=`${q}${w(s)}:${g}`,q=`,`)}if(B>Y){let e=B-Y;t+=`${q}"...":"${H(e)} not stringified"`}return F.pop(),`{${t}}`}case`number`:return isFinite(j)?String(j):t?t(j):`null`;case`boolean`:return j===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(g)return String(j);default:return t?t(j):void 0}}function se(e,t,s){if(arguments.length>1){let g=``;if(typeof s==`number`?g=` `.repeat(Math.min(s,10)):typeof s==`string`&&(g=s.slice(0,10)),t!=null){if(typeof t==`function`)return te(``,{"":e},[],t,g,``);if(Array.isArray(t))return ne(``,e,[],q(t),g,``)}if(g.length!==0)return ae(``,e,[],g,``)}return oe(``,e,[])}return se}})),require_multistream=__commonJSMin(((e,t)=>{let s=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:g}=require_constants$1(),S=g.info;function w(e,t){e||=[],t||={dedupe:!1};let w=Object.create(g);w.silent=1/0,t.levels&&typeof t.levels==`object`&&Object.keys(t.levels).forEach(e=>{w[e]=t.levels[e]});let j={write:F,add:H,remove:q,emit:L,flushSync:B,end:ee,minLevel:0,lastId:0,streams:[],clone:J,[s]:!0,streamLevels:w};return Array.isArray(e)?e.forEach(H,j):H.call(j,e),e=null,j;function F(e){let g,S=this.lastLevel,{streams:w}=this,E=0,j;for(let F=D(w.length,t.dedupe);k(F,w.length,t.dedupe);F=O(F,t.dedupe))if(g=w[F],g.level<=S){if(E!==0&&E!==g.level)break;if(j=g.stream,j[s]){let{lastTime:e,lastMsg:t,lastObj:s,lastLogger:g}=this;j.lastLevel=S,j.lastTime=e,j.lastMsg=t,j.lastObj=s,j.lastLogger=g}j.write(e),t.dedupe&&(E=g.level)}else if(!t.dedupe)break}function L(...e){for(let{stream:t}of this.streams)typeof t.emit==`function`&&t.emit(...e)}function B(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync()}function H(e){if(!e)return j;let t=typeof e.write==`function`||e.stream,s=e.write?e:e.stream;if(!t)throw Error(`stream object needs to implement either StreamEntry or DestinationStream interface`);let{streams:g,streamLevels:w}=this,D;D=typeof e.levelVal==`number`?e.levelVal:typeof e.level==`string`?w[e.level]:typeof e.level==`number`?e.level:S;let O={stream:s,level:D,levelVal:void 0,id:++j.lastId};return g.unshift(O),g.sort(E),this.minLevel=g[0].level,j}function q(e){let{streams:t}=this,s=t.findIndex(t=>t.id===e);return s>=0&&(t.splice(s,1),t.sort(E),this.minLevel=t.length>0?t[0].level:-1),j}function ee(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync(),e.end()}function J(e){let t=Array(this.streams.length);for(let s=0;s<t.length;s++)t[s]={level:e,stream:this.streams[s].stream};return{write:F,add:H,remove:q,minLevel:e,streams:t,clone:J,emit:L,flushSync:B,[s]:!0}}}function E(e,t){return e.level-t.level}function D(e,t){return t?e-1:0}function O(e,t){return t?e-1:e+1}function k(e,t,s){return s?e>=0:e<t}t.exports=w})),require_pino=__commonJSMin(((e,t)=>{let s=__require(`node:os`),g=require_pino_std_serializers(),S=require_caller(),w=require_redaction(),E=require_time(),D=require_proto(),O=require_symbols(),{configure:k}=require_safe_stable_stringify(),{assertDefaultLevelFound:j,mappings:F,genLsCache:L,genLevelComparison:B,assertLevelComparison:H}=require_levels(),{DEFAULT_LEVELS:q,SORTING_ORDER:ee}=require_constants$1(),{createArgsNormalizer:J,asChindings:Y,buildSafeSonicBoom:te,buildFormatters:ne,stringify:ae,normalizeDestFileDescriptor:oe,noop:se}=require_tools(),{version:ce}=require_meta(),{chindingsSym:ue,redactFmtSym:de,serializersSym:fe,timeSym:me,timeSliceIndexSym:ge,streamSym:_e,stringifySym:ve,stringifySafeSym:ye,stringifiersSym:Ce,setLevelSym:we,endSym:Te,formatOptsSym:De,messageKeySym:je,errorKeySym:Me,nestedKeySym:Pe,mixinSym:Ie,levelCompSym:Re,useOnlyCustomLevelsSym:ze,formattersSym:Be,hooksSym:Ve,nestedKeyStrSym:Ue,mixinMergeStrategySym:We,msgPrefixSym:Ge}=O,{epochTime:Ke,nullTime:Xe}=E,{pid:$e}=process,nt=s.hostname(),rt=g.err,it=J({level:`info`,levelComparison:ee.ASC,levels:q,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:$e,hostname:nt},serializers:Object.assign(Object.create(null),{err:rt}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:Ke,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),at=Object.assign(Object.create(null),g);function st(...e){let t={},{opts:s,stream:g}=it(t,S(),...e);s.level&&typeof s.level==`string`&&q[s.level.toLowerCase()]!==void 0&&(s.level=s.level.toLowerCase());let{redact:E,crlf:O,serializers:ee,timestamp:J,messageKey:te,errorKey:oe,nestedKey:ce,base:$e,name:nt,level:rt,customLevels:at,levelComparison:st,mixin:vt,mixinMergeStrategy:Tt,useOnlyCustomLevels:Et,formatters:Dt,hooks:jt,depthLimit:Mt,edgeLimit:Ft,onChild:It,msgPrefix:Lt}=s,Rt=k({maximumDepth:Mt,maximumBreadth:Ft}),zt=ne(Dt.level,Dt.bindings,Dt.log),Bt=ae.bind({[ye]:Rt}),Vt=E?w(E,Bt):{},Ht=E?{stringify:Vt[de]}:{stringify:Bt},Ut=`}`+(O?`\r
|
|
764
|
+
caused by: `+S(E,t)):w},w=e=>S(e,new Set),E=(e,t,S)=>{if(!s(e))return``;let w=S?``:e.message||``;if(t.has(e))return w+`: ...`;let D=g(e);if(D){t.add(e);let s=typeof e.cause==`function`;return w+(s?``:`: `)+E(D,t,s)}else return w};t.exports={isErrorLike:s,getErrorCause:g,stackWithCauses:w,messageWithCauses:e=>E(e,new Set)}})),require_err_proto=__commonJSMin(((e,t)=>{let s=Symbol(`circular-ref-tag`),g=Symbol(`pino-raw-err-ref`),S=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[g]},set:function(e){this[g]=e}}});Object.defineProperty(S,g,{writable:!0,value:{}}),t.exports={pinoErrProto:S,pinoErrorSymbols:{seen:s,rawSymbol:g}}})),require_err=__commonJSMin(((e,t)=>{t.exports=k;let{messageWithCauses:s,stackWithCauses:g,isErrorLike:S}=require_err_helpers(),{pinoErrProto:w,pinoErrorSymbols:E}=require_err_proto(),{seen:D}=E,{toString:O}=Object.prototype;function k(e){if(!S(e))return e;e[D]=void 0;let t=Object.create(w);t.type=O.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=s(e),t.stack=g(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>k(e)));for(let s in e)if(t[s]===void 0){let g=e[s];S(g)?s!==`cause`&&!Object.prototype.hasOwnProperty.call(g,D)&&(t[s]=k(g)):t[s]=g}return delete e[D],t.raw=e,t}})),require_err_with_cause=__commonJSMin(((e,t)=>{t.exports=D;let{isErrorLike:s}=require_err_helpers(),{pinoErrProto:g,pinoErrorSymbols:S}=require_err_proto(),{seen:w}=S,{toString:E}=Object.prototype;function D(e){if(!s(e))return e;e[w]=void 0;let t=Object.create(g);t.type=E.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>D(e))),s(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,w)&&(t.cause=D(e.cause));for(let g in e)if(t[g]===void 0){let S=e[g];s(S)?Object.prototype.hasOwnProperty.call(S,w)||(t[g]=D(S)):t[g]=S}return delete e[w],t.raw=e,t}})),require_req=__commonJSMin(((e,t)=>{t.exports={mapHttpRequest:w,reqSerializer:S};let s=Symbol(`pino-raw-req-ref`),g=Object.create({},{id:{enumerable:!0,writable:!0,value:``},method:{enumerable:!0,writable:!0,value:``},url:{enumerable:!0,writable:!0,value:``},query:{enumerable:!0,writable:!0,value:``},params:{enumerable:!0,writable:!0,value:``},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:``},remotePort:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[s]},set:function(e){this[s]=e}}});Object.defineProperty(g,s,{writable:!0,value:{}});function S(e){let t=e.info||e.socket,s=Object.create(g);if(s.id=typeof e.id==`function`?e.id():e.id||(e.info?e.info.id:void 0),s.method=e.method,e.originalUrl)s.url=e.originalUrl;else{let t=e.path;s.url=typeof t==`string`?t:e.url?e.url.path||e.url:void 0}return e.query&&(s.query=e.query),e.params&&(s.params=e.params),s.headers=e.headers,s.remoteAddress=t&&t.remoteAddress,s.remotePort=t&&t.remotePort,s.raw=e.raw||e,s}function w(e){return{req:S(e)}}})),require_res=__commonJSMin(((e,t)=>{t.exports={mapHttpResponse:w,resSerializer:S};let s=Symbol(`pino-raw-res-ref`),g=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[s]},set:function(e){this[s]=e}}});Object.defineProperty(g,s,{writable:!0,value:{}});function S(e){let t=Object.create(g);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function w(e){return{res:S(e)}}})),require_pino_std_serializers=__commonJSMin(((e,t)=>{let s=require_err(),g=require_err_with_cause(),S=require_req(),w=require_res();t.exports={err:s,errWithCause:g,mapHttpRequest:S.mapHttpRequest,mapHttpResponse:w.mapHttpResponse,req:S.reqSerializer,res:w.resSerializer,wrapErrorSerializer:function(e){return e===s?e:function(t){return e(s(t))}},wrapRequestSerializer:function(e){return e===S.reqSerializer?e:function(t){return e(S.reqSerializer(t))}},wrapResponseSerializer:function(e){return e===w.resSerializer?e:function(t){return e(w.resSerializer(t))}}}})),require_caller=__commonJSMin(((e,t)=>{function s(e,t){return t}t.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=s;let t=Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let g=t.slice(2),S=[];for(let e of g)e&&S.push(e.getFileName());return S}})),require_redact=__commonJSMin(((e,t)=>{function s(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array){let t=[];for(let g=0;g<e.length;g++)t[g]=s(e[g]);return t}if(typeof e==`object`){let t=Object.create(Object.getPrototypeOf(e));for(let g in e)Object.prototype.hasOwnProperty.call(e,g)&&(t[g]=s(e[g]));return t}return e}function g(e){let t=[],s=``,g=!1,S=!1,w=``;for(let E=0;E<e.length;E++){let D=e[E];!g&&D===`.`?s&&=(t.push(s),``):D===`[`?(s&&=(t.push(s),``),g=!0):D===`]`&&g?(t.push(s),s=``,g=!1,S=!1):(D===`"`||D===`'`)&&g?S?D===w?(S=!1,w=``):s+=D:(S=!0,w=D):s+=D}return s&&t.push(s),t}function S(e,t,s){let g=e;for(let e=0;e<t.length-1;e++){let s=t[e];if(typeof g!=`object`||!g||!(s in g)||typeof g[s]!=`object`||g[s]===null)return!1;g=g[s]}let S=t[t.length-1];if(S===`*`){if(Array.isArray(g))for(let e=0;e<g.length;e++)g[e]=s;else if(typeof g==`object`&&g)for(let e in g)Object.prototype.hasOwnProperty.call(g,e)&&(g[e]=s)}else typeof g==`object`&&g&&S in g&&Object.prototype.hasOwnProperty.call(g,S)&&(g[S]=s);return!0}function w(e,t){let s=e;for(let e=0;e<t.length-1;e++){let g=t[e];if(typeof s!=`object`||!s||!(g in s)||typeof s[g]!=`object`||s[g]===null)return!1;s=s[g]}let g=t[t.length-1];if(g===`*`){if(Array.isArray(s))for(let e=0;e<s.length;e++)s[e]=void 0;else if(typeof s==`object`&&s)for(let e in s)Object.prototype.hasOwnProperty.call(s,e)&&delete s[e]}else typeof s==`object`&&s&&g in s&&Object.prototype.hasOwnProperty.call(s,g)&&delete s[g];return!0}let E=Symbol(`PATH_NOT_FOUND`);function D(e,t){let s=e;for(let e of t){if(typeof s!=`object`||!s||!s||!(e in s))return E;s=s[e]}return s}function O(e,t){let s=e;for(let e of t){if(typeof s!=`object`||!s||!s)return;s=s[e]}return s}function k(e,t,s,O=!1){for(let k of t){let t=g(k);if(t.includes(`*`))j(e,t,s,k,O);else if(O)w(e,t);else{let g=D(e,t);if(g===E)continue;S(e,t,typeof s==`function`?s(g,t):s)}}}function j(e,t,s,g,S=!1){let w=t.indexOf(`*`);if(w===t.length-1){let g=t.slice(0,-1),w=e;for(let e of g){if(typeof w!=`object`||!w||!w)return;w=w[e]}if(Array.isArray(w))if(S)for(let e=0;e<w.length;e++)w[e]=void 0;else for(let e=0;e<w.length;e++){let t=[...g,e.toString()],S=typeof s==`function`?s(w[e],t):s;w[e]=S}else if(typeof w==`object`&&w)if(S){let e=[];for(let t in w)Object.prototype.hasOwnProperty.call(w,t)&&e.push(t);for(let t of e)delete w[t]}else for(let e in w){let t=[...g,e],S=typeof s==`function`?s(w[e],t):s;w[e]=S}}else F(e,t,s,w,g,S)}function F(e,t,s,g,E,D=!1){let k=t.slice(0,g),F=t.slice(g+1),L=[];function B(e,t){if(t===k.length){if(Array.isArray(e))for(let s=0;s<e.length;s++)L[t]=s.toString(),B(e[s],t+1);else if(typeof e==`object`&&e)for(let s in e)L[t]=s,B(e[s],t+1)}else if(t<k.length){let s=k[t];e&&typeof e==`object`&&e&&s in e&&(L[t]=s,B(e[s],t+1))}else F.includes(`*`)?j(e,F,typeof s==`function`?(e,g)=>s(e,[...L.slice(0,t),...g]):s,E,D):D?w(e,F):S(e,F,typeof s==`function`?s(O(e,F),[...L.slice(0,t),...F]):s)}if(k.length===0)B(e,0);else{let t=e;for(let e=0;e<k.length;e++){let s=k[e];if(typeof t!=`object`||!t||!t)return;t=t[s],L[e]=s}t!=null&&B(t,k.length)}}function L(e){if(e.length===0)return null;let t=new Map;for(let s of e){let e=g(s),S=t;for(let t=0;t<e.length;t++){let s=e[t];S.has(s)||S.set(s,new Map),S=S.get(s)}}return t}function B(e,t){if(!t)return e;function s(e,t,g=0){if(!t||t.size===0||typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let g=[];for(let S=0;S<e.length;S++){let w=S.toString();t.has(w)||t.has(`*`)?g[S]=s(e[S],t.get(w)||t.get(`*`)):g[S]=e[S]}return g}let S=Object.create(Object.getPrototypeOf(e));for(let g in e)Object.prototype.hasOwnProperty.call(e,g)&&(t.has(g)||t.has(`*`)?S[g]=s(e[g],t.get(g)||t.get(`*`)):S[g]=e[g]);return S}return s(e,t)}function H(e){if(typeof e!=`string`)throw Error(`Paths must be (non-empty) strings`);if(e===``)throw Error(`Invalid redaction path ()`);if(e.includes(`..`)||e.includes(`,`))throw Error(`Invalid redaction path (${e})`);let t=0,s=!1,g=``;for(let S=0;S<e.length;S++){let w=e[S];if((w===`"`||w===`'`)&&t>0)s?w===g&&(s=!1,g=``):(s=!0,g=w);else if(w===`[`&&!s)t++;else if(w===`]`&&!s&&(t--,t<0))throw Error(`Invalid redaction path (${e})`)}if(t!==0)throw Error(`Invalid redaction path (${e})`)}function q(e){if(!Array.isArray(e))throw TypeError(`paths must be an array`);for(let t of e)H(t)}function ee(e={}){let{paths:t=[],censor:g=`[REDACTED]`,serialize:S=JSON.stringify,strict:w=!0,remove:E=!1}=e;q(t);let D=L(t);return function(e){if(w&&(typeof e!=`object`||!e)&&(typeof e!=`object`||!e))return S?S(e):e;let O=B(e,D),j=e,F=g;return typeof g==`function`&&(F=g),k(O,t,F,E),S===!1?(O.restore=function(){return s(j)},O):typeof S==`function`?S(O):JSON.stringify(O)}}t.exports=ee})),require_symbols=__commonJSMin(((e,t)=>{let s=Symbol(`pino.setLevel`),g=Symbol(`pino.getLevel`),S=Symbol(`pino.levelVal`),w=Symbol(`pino.levelComp`),E=Symbol(`pino.useLevelLabels`),D=Symbol(`pino.useOnlyCustomLevels`),O=Symbol(`pino.mixin`),k=Symbol(`pino.lsCache`),j=Symbol(`pino.chindings`),F=Symbol(`pino.asJson`),L=Symbol(`pino.write`),B=Symbol(`pino.redactFmt`),H=Symbol(`pino.time`),q=Symbol(`pino.timeSliceIndex`),ee=Symbol(`pino.stream`),J=Symbol(`pino.stringify`),Y=Symbol(`pino.stringifySafe`),te=Symbol(`pino.stringifiers`),ne=Symbol(`pino.end`),ae=Symbol(`pino.formatOpts`),oe=Symbol(`pino.messageKey`),se=Symbol(`pino.errorKey`),ce=Symbol(`pino.nestedKey`),ue=Symbol(`pino.nestedKeyStr`),de=Symbol(`pino.mixinMergeStrategy`),fe=Symbol(`pino.msgPrefix`),me=Symbol(`pino.wildcardFirst`),ge=Symbol.for(`pino.serializers`),_e=Symbol.for(`pino.formatters`),ve=Symbol.for(`pino.hooks`);t.exports={setLevelSym:s,getLevelSym:g,levelValSym:S,levelCompSym:w,useLevelLabelsSym:E,mixinSym:O,lsCacheSym:k,chindingsSym:j,asJsonSym:F,writeSym:L,serializersSym:ge,redactFmtSym:B,timeSym:H,timeSliceIndexSym:q,streamSym:ee,stringifySym:J,stringifySafeSym:Y,stringifiersSym:te,endSym:ne,formatOptsSym:ae,messageKeySym:oe,errorKeySym:se,nestedKeySym:ce,wildcardFirstSym:me,needsMetadataGsym:Symbol.for(`pino.metadata`),useOnlyCustomLevelsSym:D,formattersSym:_e,hooksSym:ve,nestedKeyStrSym:ue,mixinMergeStrategySym:de,msgPrefixSym:fe}})),require_redaction=__commonJSMin(((e,t)=>{let s=require_redact(),{redactFmtSym:g,wildcardFirstSym:S}=require_symbols(),w=/[^.[\]]+|\[([^[\]]*?)\]/g,E=`[Redacted]`,D=!1;function O(e,t){let{paths:E,censor:D,remove:O}=k(e),j=E.reduce((e,t)=>{w.lastIndex=0;let s=w.exec(t),g=w.exec(t),E=s[1]===void 0?s[0]:s[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,`$1`);if(E===`*`&&(E=S),g===null)return e[E]=null,e;if(e[E]===null)return e;let{index:D}=g,O=`${t.substr(D,t.length-1)}`;return e[E]=e[E]||[],E!==S&&e[E].length===0&&e[E].push(...e[S]||[]),E===S&&Object.keys(e).forEach(function(t){e[t]&&e[t].push(O)}),e[E].push(O),e},{}),F={[g]:s({paths:E,censor:D,serialize:t,strict:!1,remove:O})},L=(...e)=>t(typeof D==`function`?D(...e):D);return[...Object.keys(j),...Object.getOwnPropertySymbols(j)].reduce((e,g)=>{if(j[g]===null)e[g]=e=>L(e,[g]);else{let S=typeof D==`function`?(e,t)=>D(e,[g,...t]):D;e[g]=s({paths:j[g],censor:S,serialize:t,strict:!1,remove:O})}return e},F)}function k(e){if(Array.isArray(e))return e={paths:e,censor:E},e;let{paths:t,censor:s=E,remove:g}=e;if(Array.isArray(t)===!1)throw Error(`pino – redact must contain an array of strings`);return g===!0&&(s=void 0),{paths:t,censor:s,remove:g}}t.exports=O})),require_time=__commonJSMin(((e,t)=>{let s=()=>``,g=()=>`,"time":${Date.now()}`,S=()=>`,"time":${Math.round(Date.now()/1e3)}`,w=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,E=1000000n,D=1000000000n,O=BigInt(Date.now())*1000000n,k=process.hrtime.bigint();t.exports={nullTime:s,epochTime:g,unixTime:S,isoTime:w,isoTimeNano:()=>{let e=O+(process.hrtime.bigint()-k),t=e/D,s=e%D,g=Number(t*1000n+s/1000000n),S=new Date(g);return`,"time":"${S.getUTCFullYear()}-${(S.getUTCMonth()+1).toString().padStart(2,`0`)}-${S.getUTCDate().toString().padStart(2,`0`)}T${S.getUTCHours().toString().padStart(2,`0`)}:${S.getUTCMinutes().toString().padStart(2,`0`)}:${S.getUTCSeconds().toString().padStart(2,`0`)}.${s.toString().padStart(9,`0`)}Z"`}}})),require_quick_format_unescaped=__commonJSMin(((e,t)=>{function s(e){try{return JSON.stringify(e)}catch{return`"[Circular]"`}}t.exports=g;function g(e,t,g){var S=g&&g.stringify||s,w=1;if(typeof e==`object`&&e){var E=t.length+w;if(E===1)return e;var D=Array(E);D[0]=S(e);for(var O=1;O<E;O++)D[O]=S(t[O]);return D.join(` `)}if(typeof e!=`string`)return e;var k=t.length;if(k===0)return e;for(var j=``,F=1-w,L=-1,B=e&&e.length||0,H=0;H<B;){if(e.charCodeAt(H)===37&&H+1<B){switch(L=L>-1?L:0,e.charCodeAt(H+1)){case 100:case 102:if(F>=k||t[F]==null)break;L<H&&(j+=e.slice(L,H)),j+=Number(t[F]),L=H+2,H++;break;case 105:if(F>=k||t[F]==null)break;L<H&&(j+=e.slice(L,H)),j+=Math.floor(Number(t[F])),L=H+2,H++;break;case 79:case 111:case 106:if(F>=k||t[F]===void 0)break;L<H&&(j+=e.slice(L,H));var q=typeof t[F];if(q===`string`){j+=`'`+t[F]+`'`,L=H+2,H++;break}if(q===`function`){j+=t[F].name||`<anonymous>`,L=H+2,H++;break}j+=S(t[F]),L=H+2,H++;break;case 115:if(F>=k)break;L<H&&(j+=e.slice(L,H)),j+=String(t[F]),L=H+2,H++;break;case 37:L<H&&(j+=e.slice(L,H)),j+=`%`,L=H+2,H++,F--;break}++F}++H}return L===-1?e:(L<B&&(j+=e.slice(L)),j)}})),require_atomic_sleep=__commonJSMin(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function s(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=s}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),require_sonic_boom=__commonJSMin(((e,t)=>{let s=__require(`fs`),g=__require(`events`),S=__require(`util`).inherits,w=__require(`path`),E=require_atomic_sleep(),D=__require(`assert`),O=100,k=Buffer.allocUnsafe(0),j=16*1024,F=`buffer`,L=`utf8`,[B,H]=(process.versions.node||`0.0`).split(`.`).map(Number),q=B>=22&&H>=7;function ee(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function g(s,g){if(s){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,s)}):t.emit(`error`,s);return}let S=t._reopening;t.fd=g,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():S&&process.nextTick(()=>t.emit(`drain`)))}let S=t.append?`a`:`w`,E=t.mode;if(t.sync)try{t.mkdir&&s.mkdirSync(w.dirname(e),{recursive:!0}),g(null,s.openSync(e,S,E))}catch(e){throw g(e),e}else t.mkdir?s.mkdir(w.dirname(e),{recursive:!0},t=>{if(t)return g(t);s.open(e,S,E,g)}):s.open(e,S,E,g)}function J(e){if(!(this instanceof J))return new J(e);let{fd:t,dest:g,minLength:S,maxLength:w,maxWrite:D,periodicFlush:O,sync:j,append:B=!0,mkdir:H,retryEAGAIN:q,fsync:ne,contentMode:se,mode:ve}=e||{};t||=g,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(S||0,16387),this.file=null,this.destroyed=!1,this.minLength=S||0,this.maxLength=w||0,this.maxWrite=D||16384,this._periodicFlush=O||0,this._periodicFlushTimer=void 0,this.sync=j||!1,this.writable=!0,this._fsync=ne||!1,this.append=B||!1,this.mode=ve,this.retryEAGAIN=q||(()=>!0),this.mkdir=H||!1;let ye,Ce;if(se===F)this._writingBuf=k,this.write=oe,this.flush=ue,this.flushSync=fe,this._actualWrite=ge,ye=()=>s.writeSync(this.fd,this._writingBuf),Ce=()=>s.write(this.fd,this._writingBuf,this.release);else if(se===void 0||se===L)this._writingBuf=``,this.write=ae,this.flush=ce,this.flushSync=de,this._actualWrite=me,ye=()=>Buffer.isBuffer(this._writingBuf)?s.writeSync(this.fd,this._writingBuf):s.writeSync(this.fd,this._writingBuf,`utf8`),Ce=()=>Buffer.isBuffer(this._writingBuf)?s.write(this.fd,this._writingBuf,this.release):s.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${L}" and "${F}", but passed ${se}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)ee(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{E(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(Ce,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let g=Y(this._writingBuf,this._len,t);if(this._len=g.len,this._writingBuf=g.writingBuf,this._writingBuf.length){if(!this.sync){Ce();return}try{do{let e=ye(),t=Y(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&s.fsyncSync(this.fd);let S=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):S>this.minLength?this._actualWrite():this._ending?S>0?this._actualWrite():(this._writing=!1,_e(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(te,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Y(e,t,s){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-s,0),e=e.subarray(s),{writingBuf:e,len:t}}function te(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}S(J,g);function ne(e,t){return e.length===0?k:e.length===1?e[0]:Buffer.concat(e,t)}function ae(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),s=this._len+t,g=this._bufs;return this.maxLength&&s>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(g.length===0||Buffer.byteLength(g[g.length-1])+t>this.maxWrite?g.push(e):g[g.length-1]+=e,this._len=s,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function oe(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,s=this._bufs,g=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(s.length===0||g[g.length-1]+e.length>this.maxWrite?(s.push([e]),g.push(e.length)):(s[s.length-1].push(e),g[g.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function se(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{s.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,g)},g=s=>{this._flushPending=!1,e(s),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,g)}function ce(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&se.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function ue(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&se.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}J.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&s.close(t,e=>{if(e)return this.emit(`error`,e)})}),ee(this.file,this)},J.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():_e(this)))};function de(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?s.writeSync(this.fd,e):s.writeSync(this.fd,e,`utf8`),g=Y(e,this._len,t);e=g.writingBuf,this._len=g.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;E(100)}}try{s.fsyncSync(this.fd)}catch{}}function fe(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=k);let e=k;for(;this._bufs.length||e.length;){e.length<=0&&(e=ne(this._bufs[0],this._lens[0]));try{let t=s.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;E(100)}}}J.prototype.destroy=function(){this.destroyed||_e(this)};function me(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?s.writeSync(this.fd,this._writingBuf):s.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else s.write(this.fd,this._writingBuf,e)}function ge(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:ne(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,s.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else q&&(this._writingBuf=Buffer.from(this._writingBuf)),s.write(this.fd,this._writingBuf,e)}function _e(e){if(e.fd===-1){e.once(`ready`,_e.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],D(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{s.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?s.close(e.fd,g):g()}function g(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}J.SonicBoom=J,J.default=J,t.exports=J})),require_on_exit_leak_free=__commonJSMin(((e,t)=>{let s={exit:[],beforeExit:[]},g={exit:O,beforeExit:k},S;function w(){S===void 0&&(S=new FinalizationRegistry(F))}function E(e){s[e].length>0||process.on(e,g[e])}function D(e){s[e].length>0||(process.removeListener(e,g[e]),s.exit.length===0&&s.beforeExit.length===0&&(S=void 0))}function O(){j(`exit`)}function k(){j(`beforeExit`)}function j(e){for(let t of s[e]){let s=t.deref(),g=t.fn;s!==void 0&&g(s,e)}s[e]=[]}function F(e){for(let t of[`exit`,`beforeExit`]){let g=s[t].indexOf(e);s[t].splice(g,g+1),D(t)}}function L(e,t,g){if(t===void 0)throw Error(`the object can't be undefined`);E(e);let D=new WeakRef(t);D.fn=g,w(),S.register(t,D),s[e].push(D)}function B(e,t){L(`exit`,e,t)}function H(e,t){L(`beforeExit`,e,t)}function q(e){if(S!==void 0){S.unregister(e);for(let t of[`exit`,`beforeExit`])s[t]=s[t].filter(t=>{let s=t.deref();return s&&s!==e}),D(t)}}t.exports={register:B,registerBeforeExit:H,unregister:q}})),require_package=__commonJSMin(((e,t)=>{t.exports={name:`thread-stream`,version:`4.0.0`,description:`A streaming way to send data to a Node.js Worker Thread`,main:`index.js`,types:`index.d.ts`,engines:{node:`>=20`},dependencies:{"real-require":`^0.2.0`},devDependencies:{"@types/node":`^22.0.0`,"@yao-pkg/pkg":`^6.0.0`,borp:`^0.21.0`,desm:`^1.3.0`,eslint:`^9.39.1`,fastbench:`^1.0.1`,husky:`^9.0.6`,neostandard:`^0.12.2`,"pino-elasticsearch":`^8.0.0`,"sonic-boom":`^4.0.1`,"ts-node":`^10.8.0`,typescript:`~5.7.3`},scripts:{build:`tsc --noEmit`,lint:`eslint`,test:`npm run lint && npm run build && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:ci":`npm run lint && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:yarn":`npm run transpile && borp --pattern 'test/*.test.js'`,transpile:`sh ./test/ts/transpile.sh`,prepare:`husky install`},repository:{type:`git`,url:`git+https://github.com/mcollina/thread-stream.git`},keywords:[`worker`,`thread`,`threads`,`stream`],author:`Matteo Collina <hello@matteocollina.com>`,license:`MIT`,bugs:{url:`https://github.com/mcollina/thread-stream/issues`},homepage:`https://github.com/mcollina/thread-stream#readme`}})),require_wait=__commonJSMin(((e,t)=>{let s=1e4;function g(e,t,g,S,w){let E=S===1/0?1/0:Date.now()+S,D=()=>{let S=Atomics.load(e,t);if(S===g){w(null,`ok`);return}if(E!==1/0&&Date.now()>E){w(null,`timed-out`);return}let O=E===1/0?s:Math.min(s,Math.max(1,E-Date.now())),k=Atomics.waitAsync(e,t,S,O);k.async?k.value.then(D):setImmediate(D)};D()}function S(e,t,g,S,w){let E=S===1/0?1/0:Date.now()+S,D=()=>{if(Atomics.load(e,t)!==g){w(null,`ok`);return}if(E!==1/0&&Date.now()>E){w(null,`timed-out`);return}let S=E===1/0?s:Math.min(s,Math.max(1,E-Date.now())),O=Atomics.waitAsync(e,t,g,S);O.async?O.value.then(D):setImmediate(D)};D()}t.exports={wait:g,waitDiff:S}})),require_indexes=__commonJSMin(((e,t)=>{t.exports={WRITE_INDEX:4,READ_INDEX:8}})),require_thread_stream=__commonJSMin(((e,t)=>{let{version:s}=require_package(),{EventEmitter:g}=__require(`events`),{Worker:S}=__require(`worker_threads`),{join:w}=__require(`path`),{pathToFileURL:E}=__require(`url`),{wait:D}=require_wait(),{WRITE_INDEX:O,READ_INDEX:k}=require_indexes(),j=__require(`buffer`),F=__require(`assert`),L=Symbol(`kImpl`),B=j.constants.MAX_STRING_LENGTH;var H=class{constructor(e){this._value=e}deref(){return this._value}},q=class{register(){}unregister(){}};let ee=process.env.NODE_V8_COVERAGE?q:global.FinalizationRegistry||q,J=process.env.NODE_V8_COVERAGE?H:global.WeakRef||H,Y=new ee(e=>{e.exited||e.terminate()});function te(e,t){let{filename:g,workerData:D}=t,O=new S((`__bundlerPathsOverrides`in globalThis?globalThis.__bundlerPathsOverrides:{})[`thread-stream-worker`]||w(__dirname,`lib`,`worker.js`),{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:g.indexOf(`file://`)===0?g:E(g).href,dataBuf:e[L].dataBuf,stateBuf:e[L].stateBuf,workerData:{$context:{threadStreamVersion:s},...D}}});return O.stream=new H(e),O.on(`message`,oe),O.on(`exit`,se),Y.register(e,O),O}function ne(e){F(!e[L].sync),e[L].needDrain&&(e[L].needDrain=!1,e.emit(`drain`))}function ae(e){let t=Atomics.load(e[L].state,O),s=e[L].data.length-t;if(s>0){if(e[L].buf.length===0){e[L].flushing=!1,e[L].ending?me(e):e[L].needDrain&&process.nextTick(ne,e);return}let t=e[L].buf.slice(0,s),g=Buffer.byteLength(t);g<=s?(e[L].buf=e[L].buf.slice(s),fe(e,t,ae.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[L].state,k,0),Atomics.store(e[L].state,O,0),Atomics.notify(e[L].state,k);g>e[L].data.length;)s/=2,t=e[L].buf.slice(0,s),g=Buffer.byteLength(t);e[L].buf=e[L].buf.slice(s),fe(e,t,ae.bind(null,e))}})}else if(s===0){if(t===0&&e[L].buf.length===0)return;e.flush(()=>{Atomics.store(e[L].state,k,0),Atomics.store(e[L].state,O,0),Atomics.notify(e[L].state,k),ae(e)})}else de(e,Error(`overwritten`))}function oe(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case`READY`:this.stream=new J(t),t.flush(()=>{t[L].ready=!0,t.emit(`ready`)});break;case`ERROR`:de(t,e.err);break;case`EVENT`:Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case`WARNING`:process.emitWarning(e.err);break;default:de(t,Error(`this should not happen: `+e.code))}}function se(e){let t=this.stream.deref();t!==void 0&&(Y.unregister(t),t.worker.exited=!0,t.worker.off(`exit`,se),de(t,e===0?null:Error(`the worker thread exited`)))}var ce=class extends g{constructor(e={}){if(super(),e.bufferSize<4)throw Error(`bufferSize must at least fit a 4-byte utf-8 char`);this[L]={},this[L].stateBuf=new SharedArrayBuffer(128),this[L].state=new Int32Array(this[L].stateBuf),this[L].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[L].data=Buffer.from(this[L].dataBuf),this[L].sync=e.sync||!1,this[L].ending=!1,this[L].ended=!1,this[L].needDrain=!1,this[L].destroyed=!1,this[L].flushing=!1,this[L].ready=!1,this[L].finished=!1,this[L].errored=null,this[L].closed=!1,this[L].buf=``,this.worker=te(this,e),this.on(`message`,(e,t)=>{this.worker.postMessage(e,t)})}write(e){if(this[L].destroyed)return ue(this,Error(`the worker has exited`)),!1;if(this[L].ending)return ue(this,Error(`the worker is ending`)),!1;if(this[L].flushing&&this[L].buf.length+e.length>=B)try{ge(this),this[L].flushing=!0}catch(e){return de(this,e),!1}if(this[L].buf+=e,this[L].sync)try{return ge(this),!0}catch(e){return de(this,e),!1}return this[L].flushing||(this[L].flushing=!0,setImmediate(ae,this)),this[L].needDrain=this[L].data.length-this[L].buf.length-Atomics.load(this[L].state,O)<=0,!this[L].needDrain}end(){this[L].destroyed||(this[L].ending=!0,me(this))}flush(e){if(this[L].destroyed){typeof e==`function`&&process.nextTick(e,Error(`the worker has exited`));return}let t=Atomics.load(this[L].state,O);D(this[L].state,k,t,1/0,(t,s)=>{if(t){de(this,t),process.nextTick(e,t);return}if(s===`not-equal`){this.flush(e);return}process.nextTick(e)})}flushSync(){this[L].destroyed||(ge(this),_e(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[L].ready}get destroyed(){return this[L].destroyed}get closed(){return this[L].closed}get writable(){return!this[L].destroyed&&!this[L].ending}get writableEnded(){return this[L].ending}get writableFinished(){return this[L].finished}get writableNeedDrain(){return this[L].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[L].errored}};function ue(e,t){setImmediate(()=>{e.emit(`error`,t)})}function de(e,t){e[L].destroyed||(e[L].destroyed=!0,t&&(e[L].errored=t,ue(e,t)),e.worker.exited?setImmediate(()=>{e[L].closed=!0,e.emit(`close`)}):e.worker.terminate().catch(()=>{}).then(()=>{e[L].closed=!0,e.emit(`close`)}))}function fe(e,t,s){let g=Atomics.load(e[L].state,O),S=Buffer.byteLength(t);return e[L].data.write(t,g),Atomics.store(e[L].state,O,g+S),Atomics.notify(e[L].state,O),s(),!0}function me(e){if(!(e[L].ended||!e[L].ending||e[L].flushing)){e[L].ended=!0;try{e.flushSync();let t=Atomics.load(e[L].state,k);Atomics.store(e[L].state,O,-1),Atomics.notify(e[L].state,O);let s=0;for(;t!==-1;){if(Atomics.wait(e[L].state,k,t,1e3),t=Atomics.load(e[L].state,k),t===-2){de(e,Error(`end() failed`));return}if(++s===10){de(e,Error(`end() took too long (10s)`));return}}process.nextTick(()=>{e[L].finished=!0,e.emit(`finish`)})}catch(t){de(e,t)}}}function ge(e){let t=()=>{e[L].ending?me(e):e[L].needDrain&&process.nextTick(ne,e)};for(e[L].flushing=!1;e[L].buf.length!==0;){let s=Atomics.load(e[L].state,O),g=e[L].data.length-s;if(g===0){_e(e),Atomics.store(e[L].state,k,0),Atomics.store(e[L].state,O,0),Atomics.notify(e[L].state,k);continue}else if(g<0)throw Error(`overwritten`);let S=e[L].buf.slice(0,g),w=Buffer.byteLength(S);if(w<=g)e[L].buf=e[L].buf.slice(g),fe(e,S,t);else{for(_e(e),Atomics.store(e[L].state,k,0),Atomics.store(e[L].state,O,0),Atomics.notify(e[L].state,k);w>e[L].buf.length;)g/=2,S=e[L].buf.slice(0,g),w=Buffer.byteLength(S);e[L].buf=e[L].buf.slice(g),fe(e,S,t)}}}function _e(e){if(e[L].flushing)throw Error(`unable to flush while flushing`);let t=Atomics.load(e[L].state,O),s=0;for(;;){let g=Atomics.load(e[L].state,k);if(g===-2)throw Error(`_flushSync failed`);if(g!==t)Atomics.wait(e[L].state,k,g,1e3);else break;if(++s===10)throw Error(`_flushSync took too long (10s)`)}}t.exports=ce})),require_transport=__commonJSMin(((e,t)=>{let{createRequire:s}=__require(`module`),{existsSync:g}=__require(`node:fs`),S=require_caller(),{join:w,isAbsolute:E,sep:D}=__require(`node:path`),{fileURLToPath:O}=__require(`node:url`),k=require_atomic_sleep(),j=require_on_exit_leak_free(),F=require_thread_stream();function L(e){j.register(e,Y),j.registerBeforeExit(e,te),e.on(`close`,function(){j.unregister(e)})}function B(){let e=process.execArgv;for(let t=0;t<e.length;t++){let s=e[t];if(s===`--import`||s===`--require`||s===`-r`||s.startsWith(`--import=`)||s.startsWith(`--require=`)||s.startsWith(`-r=`))return!0}return!1}function H(e){let t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!t)return e;let s=[],g=!1;for(let e=0;e<t.length;e++){let S=t[e];if(S===`--require`||S===`-r`||S===`--import`){let w=t[e+1];if(w&&q(w)){g=!0,e++;continue}s.push(S),w&&(s.push(w),e++);continue}if((S.startsWith(`--require=`)||S.startsWith(`-r=`)||S.startsWith(`--import=`))&&q(S.slice(S.indexOf(`=`)+1))){g=!0;continue}s.push(S)}return g?s.join(` `):e}function q(e){let t=ee(e);if(!t)return!1;let s=t;if(s.startsWith(`file://`))try{s=O(s)}catch{return!1}return E(s)&&!g(s)}function ee(e){let t=e[0],s=e[e.length-1];return t===`"`&&s===`"`||t===`'`&&s===`'`?e.slice(1,-1):e}function J(e,t,s,g,S){if(!s.execArgv&&B()&&__require.main===void 0&&(s={...s,execArgv:[]}),!s.env&&process.env.NODE_OPTIONS){let e=H(process.env.NODE_OPTIONS);e!==process.env.NODE_OPTIONS&&(s={...s,env:{...process.env,NODE_OPTIONS:e}})}s={...s,name:S};let w=new F({filename:e,workerData:t,workerOpts:s,sync:g});w.on(`ready`,E),w.on(`close`,function(){process.removeListener(`exit`,D)}),process.on(`exit`,D);function E(){process.removeListener(`exit`,D),w.unref(),s.autoEnd!==!1&&L(w)}function D(){w.closed||(w.flushSync(),k(100),w.end())}return w}function Y(e){e.ref(),e.flushSync(),e.end(),e.once(`close`,function(){e.unref()})}function te(e){e.flushSync()}function ne(e){let{pipeline:t,targets:g,levels:O,dedupe:k,worker:j={},caller:F=S(),sync:L=!1}=e,B={...e.options},H=typeof F==`string`?[F]:F,q=typeof globalThis==`object`&&Object.prototype.hasOwnProperty.call(globalThis,`__bundlerPathsOverrides`)&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==`object`?globalThis.__bundlerPathsOverrides:Object.create(null),ee=e.target;if(ee&&g)throw Error(`only one of target or targets can be specified`);g?(ee=q[`pino-worker`]||w(__dirname,`worker.js`),B.targets=g.filter(e=>e.target).map(e=>({...e,target:te(e.target)})),B.pipelines=g.filter(e=>e.pipeline).map(e=>e.pipeline.map(t=>({...t,level:e.level,target:te(t.target)})))):t&&(ee=q[`pino-worker`]||w(__dirname,`worker.js`),B.pipelines=[t.map(e=>({...e,target:te(e.target)}))]),O&&(B.levels=O),k&&(B.dedupe=k),B.pinoWillSendConfig=!0;let Y=g||t?`pino.transport`:ee;return J(te(ee),B,j,L,Y);function te(e){if(e=q[e]||e,E(e)||e.indexOf(`file://`)===0)return e;if(e===`pino/file`)return w(__dirname,`..`,`file.js`);let t;for(let g of H)try{t=s(g===`node:repl`?process.cwd()+D:g).resolve(e);break}catch{continue}if(!t)throw Error(`unable to determine transport target for "${e}"`);return t}}t.exports=ne})),require_tools=__commonJSMin(((e,t)=>{let s=__require(`node:diagnostics_channel`),g=require_quick_format_unescaped(),{mapHttpRequest:S,mapHttpResponse:w}=require_pino_std_serializers(),E=require_sonic_boom(),D=require_on_exit_leak_free(),{lsCacheSym:O,chindingsSym:k,writeSym:j,serializersSym:F,formatOptsSym:L,endSym:B,stringifiersSym:H,stringifySym:q,stringifySafeSym:ee,wildcardFirstSym:J,nestedKeySym:Y,formattersSym:te,messageKeySym:ne,errorKeySym:ae,nestedKeyStrSym:oe,msgPrefixSym:se}=require_symbols(),{isMainThread:ce}=__require(`worker_threads`),ue=require_transport(),[de]=process.versions.node.split(`.`).map(e=>Number(e)),fe=s.tracingChannel(`pino_asJson`),me=de>=25?e=>JSON.stringify(e):ve;function ge(){}function _e(e,t){if(!t)return s;return function(...g){t.call(this,g,s,e)};function s(t,...s){if(typeof t==`object`){let E=t;t!==null&&(t.method&&t.headers&&t.socket?t=S(t):typeof t.setHeader==`function`&&(t=w(t)));let D;E===null&&s.length===0?D=[null]:(E=s.shift(),D=s),typeof this[se]==`string`&&E!=null&&(E=this[se]+E),this[j](t,g(E,D,this[L]),e)}else{let S=t===void 0?s.shift():t;typeof this[se]==`string`&&S!=null&&(S=this[se]+S),this[j](null,g(S,s,this[L]),e)}}}function ve(e){let t=``,s=0,g=!1,S=255,w=e.length;if(w>100)return JSON.stringify(e);for(var E=0;E<w&&S>=32;E++)S=e.charCodeAt(E),(S===34||S===92)&&(t+=e.slice(s,E)+`\\`,s=E,g=!0);return g?t+=e.slice(s):t=e,S<32?JSON.stringify(e):`"`+t+`"`}function ye(e,t,s,g){if(fe.hasSubscribers===!1)return Ce.call(this,e,t,s,g);let S={instance:this,arguments};return fe.traceSync(Ce,S,this,e,t,s,g)}function Ce(e,t,s,g){let S=this[q],w=this[ee],E=this[H],D=this[B],j=this[k],L=this[F],se=this[te],ce=this[ne],ue=this[ae],de=this[O][s]+g;de+=j;let fe;se.log&&(e=se.log(e));let ge=E[J],_e=``;for(let t in e)if(fe=e[t],Object.prototype.hasOwnProperty.call(e,t)&&fe!==void 0){L[t]?fe=L[t](fe):t===ue&&L.err&&(fe=L.err(fe));let e=E[t]||ge;switch(typeof fe){case`undefined`:case`function`:continue;case`number`:Number.isFinite(fe)===!1&&(fe=null);case`boolean`:e&&(fe=e(fe));break;case`string`:fe=(e||me)(fe);break;default:fe=(e||S)(fe,w)}if(fe===void 0)continue;let s=me(t);_e+=`,`+s+`:`+fe}let ve=``;if(t!==void 0){fe=L[ce]?L[ce](t):t;let e=E[ce]||ge;switch(typeof fe){case`function`:break;case`number`:Number.isFinite(fe)===!1&&(fe=null);case`boolean`:e&&(fe=e(fe)),ve=`,"`+ce+`":`+fe;break;case`string`:fe=(e||me)(fe),ve=`,"`+ce+`":`+fe;break;default:fe=(e||S)(fe,w),ve=`,"`+ce+`":`+fe}}return this[Y]&&_e?de+this[oe]+_e.slice(1)+`}`+ve+D:de+_e+ve+D}function we(e,t){let s,g=e[k],S=e[q],w=e[ee],E=e[H],D=E[J],O=e[F],j=e[te].bindings;t=j(t);for(let e in t)if(s=t[e],((e.length<5||e!==`level`&&e!==`serializers`&&e!==`formatters`&&e!==`customLevels`)&&t.hasOwnProperty(e)&&s!==void 0)===!0){if(s=O[e]?O[e](s):s,s=(E[e]||D||S)(s,w),s===void 0)continue;g+=`,"`+e+`":`+s}return g}function Te(e){return e.write!==e.constructor.prototype.write}function De(e){let t=new E(e);return t.on(`error`,s),!e.sync&&ce&&(D.register(t,je),t.on(`close`,function(){D.unregister(t)})),t;function s(e){if(e.code===`EPIPE`){t.write=ge,t.end=ge,t.flushSync=ge,t.destroy=ge;return}t.removeListener(`error`,s),t.emit(`error`,e)}}function je(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function Me(e){return function(t,s,g={},S){if(typeof g==`string`)S=De({dest:g}),g={};else if(typeof S==`string`){if(g&&g.transport)throw Error(`only one of option.transport or stream can be specified`);S=De({dest:S})}else if(g instanceof E||g.writable||g._writableState)S=g,g={};else if(g.transport){if(g.transport instanceof E||g.transport.writable||g.transport._writableState)throw Error(`option.transport do not allow stream, please pass to option directly. e.g. pino(transport)`);if(g.transport.targets&&g.transport.targets.length&&g.formatters&&typeof g.formatters.level==`function`)throw Error(`option.transport.targets do not allow custom level formatters`);let e;g.customLevels&&(e=g.useOnlyCustomLevels?g.customLevels:Object.assign({},g.levels,g.customLevels)),S=ue({caller:s,...g.transport,levels:e})}if(g=Object.assign({},e,g),g.serializers=Object.assign({},e.serializers,g.serializers),g.formatters=Object.assign({},e.formatters,g.formatters),g.prettyPrint)throw Error(`prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)`);let{enabled:w,onChild:D}=g;return w===!1&&(g.level=`silent`),D||(g.onChild=ge),S||=Te(process.stdout)?process.stdout:De({fd:process.stdout.fd||1}),{opts:g,stream:S}}}function Pe(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[ee])(e)}catch{return`"[unable to serialize, circular reference is too complex to analyze]"`}}}function Ie(e,t,s){return{level:e,bindings:t,log:s}}function Re(e){let t=Number(e);return typeof e==`string`&&Number.isFinite(t)?t:e===void 0?1:e}t.exports={noop:ge,buildSafeSonicBoom:De,asChindings:we,asJson:ye,genLog:_e,createArgsNormalizer:Me,stringify:Pe,buildFormatters:Ie,normalizeDestFileDescriptor:Re}})),require_constants$1=__commonJSMin(((e,t)=>{t.exports={DEFAULT_LEVELS:{trace:10,debug:20,info:30,warn:40,error:50,fatal:60},SORTING_ORDER:{ASC:`ASC`,DESC:`DESC`}}})),require_levels=__commonJSMin(((e,t)=>{let{lsCacheSym:s,levelValSym:g,useOnlyCustomLevelsSym:S,streamSym:w,formattersSym:E,hooksSym:D,levelCompSym:O}=require_symbols(),{noop:k,genLog:j}=require_tools(),{DEFAULT_LEVELS:F,SORTING_ORDER:L}=require_constants$1(),B={fatal:e=>{let t=j(F.fatal,e);return function(...e){let s=this[w];if(t.call(this,...e),typeof s.flushSync==`function`)try{s.flushSync()}catch{}}},error:e=>j(F.error,e),warn:e=>j(F.warn,e),info:e=>j(F.info,e),debug:e=>j(F.debug,e),trace:e=>j(F.trace,e)},H=Object.keys(F).reduce((e,t)=>(e[F[t]]=t,e),{}),q=Object.keys(H).reduce((e,t)=>(e[t]=`{"level":`+Number(t),e),{});function ee(e){let t=e[E].level,{labels:g}=e.levels,S={};for(let e in g){let s=t(g[e],Number(e));S[e]=JSON.stringify(s).slice(0,-1)}return e[s]=S,e}function J(e,t){if(t)return!1;switch(e){case`fatal`:case`error`:case`warn`:case`info`:case`debug`:case`trace`:return!0;default:return!1}}function Y(e){let{labels:t,values:s}=this.levels;if(typeof e==`number`){if(t[e]===void 0)throw Error(`unknown level value`+e);e=t[e]}if(s[e]===void 0)throw Error(`unknown level `+e);let w=this[g],E=this[g]=s[e],F=this[S],L=this[O],H=this[D].logMethod;for(let e in s){if(L(s[e],E)===!1){this[e]=k;continue}this[e]=J(e,F)?B[e](H):j(s[e],H)}this.emit(`level-change`,e,E,t[w],w,this)}function te(e){let{levels:t,levelVal:s}=this;return t&&t.labels?t.labels[s]:``}function ne(e){let{values:t}=this.levels,s=t[e];return s!==void 0&&this[O](s,this[g])}function ae(e,t,s){return e===L.DESC?t<=s:t>=s}function oe(e){return typeof e==`string`?ae.bind(null,e):e}function se(e=null,t=!1){let s=e?Object.keys(e).reduce((t,s)=>(t[e[s]]=s,t),{}):null;return{labels:Object.assign(Object.create(Object.prototype,{Infinity:{value:`silent`}}),t?null:H,s),values:Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:F,e)}}function ce(e,t,s){if(typeof e==`number`){if(![].concat(Object.keys(t||{}).map(e=>t[e]),s?[]:Object.keys(H).map(e=>+e),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}if(!(e in Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),s?null:F,t)))throw Error(`default level:${e} must be included in custom levels`)}function ue(e,t){let{labels:s,values:g}=e;for(let e in t){if(e in g)throw Error(`levels cannot be overridden`);if(t[e]in s)throw Error(`pre-existing level values cannot be used for new levels`)}}function de(e){if(typeof e!=`function`&&!(typeof e==`string`&&Object.values(L).includes(e)))throw Error(`Levels comparison should be one of "ASC", "DESC" or "function" type`)}t.exports={initialLsCache:q,genLsCache:ee,levelMethods:B,getLevel:te,setLevel:Y,isLevelEnabled:ne,mappings:se,assertNoLevelCollisions:ue,assertDefaultLevelFound:ce,genLevelComparison:oe,assertLevelComparison:de}})),require_meta=__commonJSMin(((e,t)=>{t.exports={version:`10.3.1`}})),require_proto=__commonJSMin(((e,t)=>{let{EventEmitter:s}=__require(`node:events`),{lsCacheSym:g,levelValSym:S,setLevelSym:w,getLevelSym:E,chindingsSym:D,mixinSym:O,asJsonSym:k,writeSym:j,mixinMergeStrategySym:F,timeSym:L,timeSliceIndexSym:B,streamSym:H,serializersSym:q,formattersSym:ee,errorKeySym:J,messageKeySym:Y,useOnlyCustomLevelsSym:te,needsMetadataGsym:ne,redactFmtSym:ae,stringifySym:oe,formatOptsSym:se,stringifiersSym:ce,msgPrefixSym:ue,hooksSym:de}=require_symbols(),{getLevel:fe,setLevel:me,isLevelEnabled:ge,mappings:_e,initialLsCache:ve,genLsCache:ye,assertNoLevelCollisions:Ce}=require_levels(),{asChindings:we,asJson:Te,buildFormatters:De,stringify:je,noop:Me}=require_tools(),{version:Pe}=require_meta(),Ie=require_redaction(),Re={constructor:class{},child:Be,bindings:Ve,setBindings:Ue,flush:Ke,isLevelEnabled:ge,version:Pe,get level(){return this[E]()},set level(e){this[w](e)},get levelVal(){return this[S]},set levelVal(e){throw Error(`levelVal is read-only`)},get msgPrefix(){return this[ue]},get[Symbol.toStringTag](){return`Pino`},[g]:ve,[j]:Ge,[k]:Te,[E]:fe,[w]:me};Object.setPrototypeOf(Re,s.prototype),t.exports=function(){return Object.create(Re)};let ze=e=>e;function Be(e,t){if(!e)throw Error(`missing bindings for child Pino`);let s=this[q],g=this[ee],S=Object.create(this);if(t==null)return S[ee].bindings!==ze&&(S[ee]=De(g.level,ze,g.log)),S[D]=we(S,e),this.onChild!==Me&&this.onChild(S),S;if(t.hasOwnProperty(`serializers`)===!0){S[q]=Object.create(null);for(let e in s)S[q][e]=s[e];let e=Object.getOwnPropertySymbols(s);for(var E=0;E<e.length;E++){let t=e[E];S[q][t]=s[t]}for(let e in t.serializers)S[q][e]=t.serializers[e];let g=Object.getOwnPropertySymbols(t.serializers);for(var O=0;O<g.length;O++){let e=g[O];S[q][e]=t.serializers[e]}}else S[q]=s;if(t.hasOwnProperty(`formatters`)){let{level:e,bindings:s,log:w}=t.formatters;S[ee]=De(e||g.level,s||ze,w||g.log)}else S[ee]=De(g.level,ze,g.log);if(t.hasOwnProperty(`customLevels`)===!0&&(Ce(this.levels,t.customLevels),S.levels=_e(t.customLevels,S[te]),ye(S)),typeof t.redact==`object`&&t.redact!==null||Array.isArray(t.redact)){S.redact=t.redact;let e=Ie(S.redact,je),s={stringify:e[ae]};S[oe]=je,S[ce]=e,S[se]=s}if(typeof t.msgPrefix==`string`&&(S[ue]=(this[ue]||``)+t.msgPrefix),S[D]=we(S,e),t.level!==void 0&&t.level!==this.level||t.hasOwnProperty(`customLevels`)){let e=t.level||this.level;S[w](e)}return this.onChild(S),S}function Ve(){let e=`{${this[D].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function Ue(e){this[D]=we(this,e)}function We(e,t){return Object.assign(t,e)}function Ge(e,t,s){let g=this[L](),S=this[O],w=this[J],E=this[Y],D=this[F]||We,j,q=this[de].streamWrite;e==null?j={}:e instanceof Error?(j={[w]:e},t===void 0&&(t=e.message)):(j=e,t===void 0&&e[E]===void 0&&e[w]&&(t=e[w].message)),S&&(j=D(j,S(j,s,this)));let ee=this[k](j,t,s,g),te=this[H];te[ne]===!0&&(te.lastLevel=s,te.lastObj=j,te.lastMsg=t,te.lastTime=g.slice(this[B]),te.lastLogger=this),te.write(q?q(ee):ee)}function Ke(e){if(e!=null&&typeof e!=`function`)throw Error(`callback must be a function`);let t=this[H];typeof t.flush==`function`?t.flush(e||Me):e&&e()}})),require_safe_stable_stringify=__commonJSMin(((e,t)=>{let{hasOwnProperty:s}=Object.prototype,g=J();g.configure=J,g.stringify=g,g.default=g,e.stringify=g,e.configure=J,t.exports=g;let S=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function w(e){return e.length<5e3&&!S.test(e)?`"${e}"`:JSON.stringify(e)}function E(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){let s=e[t],g=t;for(;g!==0&&e[g-1]>s;)e[g]=e[g-1],g--;e[g]=s}return e}let D=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function O(e){return D.call(e)!==void 0&&e.length!==0}function k(e,t,s){e.length<s&&(s=e.length);let g=t===`,`?``:` `,S=`"0":${g}${e[0]}`;for(let w=1;w<s;w++)S+=`${t}"${w}":${g}${e[w]}`;return S}function j(e){if(s.call(e,`circularValue`)){let t=e.circularValue;if(typeof t==`string`)return`"${t}"`;if(t==null)return t;if(t===Error||t===TypeError)return{toString(){throw TypeError(`Converting circular structure to JSON`)}};throw TypeError(`The "circularValue" argument must be of type string or the value null or undefined`)}return`"[Circular]"`}function F(e){let t;if(s.call(e,`deterministic`)&&(t=e.deterministic,typeof t!=`boolean`&&typeof t!=`function`))throw TypeError(`The "deterministic" argument must be of type boolean or comparator function`);return t===void 0?!0:t}function L(e,t){let g;if(s.call(e,t)&&(g=e[t],typeof g!=`boolean`))throw TypeError(`The "${t}" argument must be of type boolean`);return g===void 0?!0:g}function B(e,t){let g;if(s.call(e,t)){if(g=e[t],typeof g!=`number`)throw TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(g))throw TypeError(`The "${t}" argument must be an integer`);if(g<1)throw RangeError(`The "${t}" argument must be >= 1`)}return g===void 0?1/0:g}function H(e){return e===1?`1 item`:`${e} items`}function q(e){let t=new Set;for(let s of e)(typeof s==`string`||typeof s==`number`)&&t.add(String(s));return t}function ee(e){if(s.call(e,`strict`)){let t=e.strict;if(typeof t!=`boolean`)throw TypeError(`The "strict" argument must be of type boolean`);if(t)return e=>{let t=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!=`function`&&(t+=` (${e.toString()})`),Error(t)}}}function J(e){e={...e};let t=ee(e);t&&(e.bigint===void 0&&(e.bigint=!1),`circularValue`in e||(e.circularValue=Error));let s=j(e),g=L(e,`bigint`),S=F(e),D=typeof S==`function`?S:void 0,J=B(e,`maximumDepth`),Y=B(e,`maximumBreadth`);function te(e,k,j,F,L,B){let q=k[e];switch(typeof q==`object`&&q&&typeof q.toJSON==`function`&&(q=q.toJSON(e)),q=F.call(k,e,q),typeof q){case`string`:return w(q);case`object`:{if(q===null)return`null`;if(j.indexOf(q)!==-1)return s;let e=``,t=`,`,g=B;if(Array.isArray(q)){if(q.length===0)return`[]`;if(J<j.length+1)return`"[Array]"`;j.push(q),L!==``&&(B+=L,e+=`\n${B}`,t=`,\n${B}`);let s=Math.min(q.length,Y),S=0;for(;S<s-1;S++){let s=te(String(S),q,j,F,L,B);e+=s===void 0?`null`:s,e+=t}let w=te(String(S),q,j,F,L,B);if(e+=w===void 0?`null`:w,q.length-1>Y){let s=q.length-Y-1;e+=`${t}"... ${H(s)} not stringified"`}return L!==``&&(e+=`\n${g}`),j.pop(),`[${e}]`}let k=Object.keys(q),ee=k.length;if(ee===0)return`{}`;if(J<j.length+1)return`"[Object]"`;let ne=``,ae=``;L!==``&&(B+=L,t=`,\n${B}`,ne=` `);let oe=Math.min(ee,Y);S&&!O(q)&&(k=E(k,D)),j.push(q);for(let s=0;s<oe;s++){let g=k[s],S=te(g,q,j,F,L,B);S!==void 0&&(e+=`${ae}${w(g)}:${ne}${S}`,ae=t)}if(ee>Y){let s=ee-Y;e+=`${ae}"...":${ne}"${H(s)} not stringified"`,ae=t}return L!==``&&ae.length>1&&(e=`\n${B}${e}\n${g}`),j.pop(),`{${e}}`}case`number`:return isFinite(q)?String(q):t?t(q):`null`;case`boolean`:return q===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(g)return String(q);default:return t?t(q):void 0}}function ne(e,S,E,D,O,k){switch(typeof S==`object`&&S&&typeof S.toJSON==`function`&&(S=S.toJSON(e)),typeof S){case`string`:return w(S);case`object`:{if(S===null)return`null`;if(E.indexOf(S)!==-1)return s;let e=k,t=``,g=`,`;if(Array.isArray(S)){if(S.length===0)return`[]`;if(J<E.length+1)return`"[Array]"`;E.push(S),O!==``&&(k+=O,t+=`\n${k}`,g=`,\n${k}`);let s=Math.min(S.length,Y),w=0;for(;w<s-1;w++){let e=ne(String(w),S[w],E,D,O,k);t+=e===void 0?`null`:e,t+=g}let j=ne(String(w),S[w],E,D,O,k);if(t+=j===void 0?`null`:j,S.length-1>Y){let e=S.length-Y-1;t+=`${g}"... ${H(e)} not stringified"`}return O!==``&&(t+=`\n${e}`),E.pop(),`[${t}]`}E.push(S);let j=``;O!==``&&(k+=O,g=`,\n${k}`,j=` `);let F=``;for(let e of D){let s=ne(e,S[e],E,D,O,k);s!==void 0&&(t+=`${F}${w(e)}:${j}${s}`,F=g)}return O!==``&&F.length>1&&(t=`\n${k}${t}\n${e}`),E.pop(),`{${t}}`}case`number`:return isFinite(S)?String(S):t?t(S):`null`;case`boolean`:return S===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(g)return String(S);default:return t?t(S):void 0}}function ae(e,j,F,L,B){switch(typeof j){case`string`:return w(j);case`object`:{if(j===null)return`null`;if(typeof j.toJSON==`function`){if(j=j.toJSON(e),typeof j!=`object`)return ae(e,j,F,L,B);if(j===null)return`null`}if(F.indexOf(j)!==-1)return s;let t=B;if(Array.isArray(j)){if(j.length===0)return`[]`;if(J<F.length+1)return`"[Array]"`;F.push(j),B+=L;let e=`\n${B}`,s=`,\n${B}`,g=Math.min(j.length,Y),S=0;for(;S<g-1;S++){let t=ae(String(S),j[S],F,L,B);e+=t===void 0?`null`:t,e+=s}let w=ae(String(S),j[S],F,L,B);if(e+=w===void 0?`null`:w,j.length-1>Y){let t=j.length-Y-1;e+=`${s}"... ${H(t)} not stringified"`}return e+=`\n${t}`,F.pop(),`[${e}]`}let g=Object.keys(j),q=g.length;if(q===0)return`{}`;if(J<F.length+1)return`"[Object]"`;B+=L;let ee=`,\n${B}`,te=``,ne=``,oe=Math.min(q,Y);O(j)&&(te+=k(j,ee,Y),g=g.slice(j.length),oe-=j.length,ne=ee),S&&(g=E(g,D)),F.push(j);for(let e=0;e<oe;e++){let t=g[e],s=ae(t,j[t],F,L,B);s!==void 0&&(te+=`${ne}${w(t)}: ${s}`,ne=ee)}if(q>Y){let e=q-Y;te+=`${ne}"...": "${H(e)} not stringified"`,ne=ee}return ne!==``&&(te=`\n${B}${te}\n${t}`),F.pop(),`{${te}}`}case`number`:return isFinite(j)?String(j):t?t(j):`null`;case`boolean`:return j===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(g)return String(j);default:return t?t(j):void 0}}function oe(e,j,F){switch(typeof j){case`string`:return w(j);case`object`:{if(j===null)return`null`;if(typeof j.toJSON==`function`){if(j=j.toJSON(e),typeof j!=`object`)return oe(e,j,F);if(j===null)return`null`}if(F.indexOf(j)!==-1)return s;let t=``,g=j.length!==void 0;if(g&&Array.isArray(j)){if(j.length===0)return`[]`;if(J<F.length+1)return`"[Array]"`;F.push(j);let e=Math.min(j.length,Y),s=0;for(;s<e-1;s++){let e=oe(String(s),j[s],F);t+=e===void 0?`null`:e,t+=`,`}let g=oe(String(s),j[s],F);if(t+=g===void 0?`null`:g,j.length-1>Y){let e=j.length-Y-1;t+=`,"... ${H(e)} not stringified"`}return F.pop(),`[${t}]`}let L=Object.keys(j),B=L.length;if(B===0)return`{}`;if(J<F.length+1)return`"[Object]"`;let q=``,ee=Math.min(B,Y);g&&O(j)&&(t+=k(j,`,`,Y),L=L.slice(j.length),ee-=j.length,q=`,`),S&&(L=E(L,D)),F.push(j);for(let e=0;e<ee;e++){let s=L[e],g=oe(s,j[s],F);g!==void 0&&(t+=`${q}${w(s)}:${g}`,q=`,`)}if(B>Y){let e=B-Y;t+=`${q}"...":"${H(e)} not stringified"`}return F.pop(),`{${t}}`}case`number`:return isFinite(j)?String(j):t?t(j):`null`;case`boolean`:return j===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(g)return String(j);default:return t?t(j):void 0}}function se(e,t,s){if(arguments.length>1){let g=``;if(typeof s==`number`?g=` `.repeat(Math.min(s,10)):typeof s==`string`&&(g=s.slice(0,10)),t!=null){if(typeof t==`function`)return te(``,{"":e},[],t,g,``);if(Array.isArray(t))return ne(``,e,[],q(t),g,``)}if(g.length!==0)return ae(``,e,[],g,``)}return oe(``,e,[])}return se}})),require_multistream=__commonJSMin(((e,t)=>{let s=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:g}=require_constants$1(),S=g.info;function w(e,t){e||=[],t||={dedupe:!1};let w=Object.create(g);w.silent=1/0,t.levels&&typeof t.levels==`object`&&Object.keys(t.levels).forEach(e=>{w[e]=t.levels[e]});let j={write:F,add:H,remove:q,emit:L,flushSync:B,end:ee,minLevel:0,lastId:0,streams:[],clone:J,[s]:!0,streamLevels:w};return Array.isArray(e)?e.forEach(H,j):H.call(j,e),e=null,j;function F(e){let g,S=this.lastLevel,{streams:w}=this,E=0,j;for(let F=D(w.length,t.dedupe);k(F,w.length,t.dedupe);F=O(F,t.dedupe))if(g=w[F],g.level<=S){if(E!==0&&E!==g.level)break;if(j=g.stream,j[s]){let{lastTime:e,lastMsg:t,lastObj:s,lastLogger:g}=this;j.lastLevel=S,j.lastTime=e,j.lastMsg=t,j.lastObj=s,j.lastLogger=g}j.write(e),t.dedupe&&(E=g.level)}else if(!t.dedupe)break}function L(...e){for(let{stream:t}of this.streams)typeof t.emit==`function`&&t.emit(...e)}function B(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync()}function H(e){if(!e)return j;let t=typeof e.write==`function`||e.stream,s=e.write?e:e.stream;if(!t)throw Error(`stream object needs to implement either StreamEntry or DestinationStream interface`);let{streams:g,streamLevels:w}=this,D;D=typeof e.levelVal==`number`?e.levelVal:typeof e.level==`string`?w[e.level]:typeof e.level==`number`?e.level:S;let O={stream:s,level:D,levelVal:void 0,id:++j.lastId};return g.unshift(O),g.sort(E),this.minLevel=g[0].level,j}function q(e){let{streams:t}=this,s=t.findIndex(t=>t.id===e);return s>=0&&(t.splice(s,1),t.sort(E),this.minLevel=t.length>0?t[0].level:-1),j}function ee(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync(),e.end()}function J(e){let t=Array(this.streams.length);for(let s=0;s<t.length;s++)t[s]={level:e,stream:this.streams[s].stream};return{write:F,add:H,remove:q,minLevel:e,streams:t,clone:J,emit:L,flushSync:B,[s]:!0}}}function E(e,t){return e.level-t.level}function D(e,t){return t?e-1:0}function O(e,t){return t?e-1:e+1}function k(e,t,s){return s?e>=0:e<t}t.exports=w})),require_pino=__commonJSMin(((e,t)=>{let s=__require(`node:os`),g=require_pino_std_serializers(),S=require_caller(),w=require_redaction(),E=require_time(),D=require_proto(),O=require_symbols(),{configure:k}=require_safe_stable_stringify(),{assertDefaultLevelFound:j,mappings:F,genLsCache:L,genLevelComparison:B,assertLevelComparison:H}=require_levels(),{DEFAULT_LEVELS:q,SORTING_ORDER:ee}=require_constants$1(),{createArgsNormalizer:J,asChindings:Y,buildSafeSonicBoom:te,buildFormatters:ne,stringify:ae,normalizeDestFileDescriptor:oe,noop:se}=require_tools(),{version:ce}=require_meta(),{chindingsSym:ue,redactFmtSym:de,serializersSym:fe,timeSym:me,timeSliceIndexSym:ge,streamSym:_e,stringifySym:ve,stringifySafeSym:ye,stringifiersSym:Ce,setLevelSym:we,endSym:Te,formatOptsSym:De,messageKeySym:je,errorKeySym:Me,nestedKeySym:Pe,mixinSym:Ie,levelCompSym:Re,useOnlyCustomLevelsSym:ze,formattersSym:Be,hooksSym:Ve,nestedKeyStrSym:Ue,mixinMergeStrategySym:We,msgPrefixSym:Ge}=O,{epochTime:Ke,nullTime:Xe}=E,{pid:$e}=process,nt=s.hostname(),rt=g.err,it=J({level:`info`,levelComparison:ee.ASC,levels:q,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:$e,hostname:nt},serializers:Object.assign(Object.create(null),{err:rt}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:Ke,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),at=Object.assign(Object.create(null),g);function st(...e){let t={},{opts:s,stream:g}=it(t,S(),...e);s.level&&typeof s.level==`string`&&q[s.level.toLowerCase()]!==void 0&&(s.level=s.level.toLowerCase());let{redact:E,crlf:O,serializers:ee,timestamp:J,messageKey:te,errorKey:oe,nestedKey:ce,base:$e,name:nt,level:rt,customLevels:at,levelComparison:st,mixin:vt,mixinMergeStrategy:St,useOnlyCustomLevels:Tt,formatters:Et,hooks:jt,depthLimit:Mt,edgeLimit:Ft,onChild:It,msgPrefix:Lt}=s,Rt=k({maximumDepth:Mt,maximumBreadth:Ft}),zt=ne(Et.level,Et.bindings,Et.log),Bt=ae.bind({[ye]:Rt}),Vt=E?w(E,Bt):{},Ht=E?{stringify:Vt[de]}:{stringify:Bt},Ut=`}`+(O?`\r
|
|
765
765
|
`:`
|
|
766
|
-
`),Wt=Y.bind(null,{[ue]:``,[fe]:ee,[Ce]:Vt,[ve]:ae,[ye]:Rt,[Be]:zt}),Kt=``;$e!==null&&(Kt=Wt(nt===void 0?$e:Object.assign({},$e,{name:nt})));let $t=J instanceof Function?J:J?Ke:Xe,en=$t().indexOf(`:`)+1;if(Et&&!at)throw Error(`customLevels is required if useOnlyCustomLevels is set true`);if(vt&&typeof vt!=`function`)throw Error(`Unknown mixin type "${typeof vt}" - expected "function"`);if(Lt&&typeof Lt!=`string`)throw Error(`Unknown msgPrefix type "${typeof Lt}" - expected "string"`);j(rt,at,Et);let jr=F(at,Et);typeof g.emit==`function`&&g.emit(`message`,{code:`PINO_CONFIG`,config:{levels:jr,messageKey:te,errorKey:oe}}),H(st);let Mr=B(st);return Object.assign(t,{levels:jr,[Re]:Mr,[ze]:Et,[_e]:g,[me]:$t,[ge]:en,[ve]:ae,[ye]:Rt,[Ce]:Vt,[Te]:Ut,[De]:Ht,[je]:te,[Me]:oe,[Pe]:ce,[Ue]:ce?`,${JSON.stringify(ce)}:{`:``,[fe]:ee,[Ie]:vt,[We]:Tt,[ue]:Kt,[Be]:zt,[Ve]:jt,silent:se,onChild:It,[Ge]:Lt}),Object.setPrototypeOf(t,D()),L(t),t[we](rt),t}t.exports=st,t.exports.destination=(e=process.stdout.fd)=>typeof e==`object`?(e.dest=oe(e.dest||process.stdout.fd),te(e)):te({dest:oe(e),minLength:0}),t.exports.transport=require_transport(),t.exports.multistream=require_multistream(),t.exports.levels=F(),t.exports.stdSerializers=at,t.exports.stdTimeFunctions=Object.assign({},E),t.exports.symbols=O,t.exports.version=ce,t.exports.default=st,t.exports.pino=st})),require_colorette=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t=__require(`tty`);function s(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(s){if(s!==`default`){var g=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,g.get?g:{enumerable:!0,get:function(){return e[s]}})}}),t.default=e,Object.freeze(t)}var g=s(t);let{env:S={},argv:w=[],platform:E=``}=typeof process>`u`?{}:process,D=`NO_COLOR`in S||w.includes(`--no-color`),O=`FORCE_COLOR`in S||w.includes(`--color`),k=E===`win32`,j=S.TERM===`dumb`,F=g&&g.isatty&&g.isatty(1)&&S.TERM&&!j,L=`CI`in S&&(`GITHUB_ACTIONS`in S||`GITLAB_CI`in S||`CIRCLECI`in S),B=!D&&(O||k&&!j||F||L),H=(e,t,s,g,S=t.substring(0,e)+g,w=t.substring(e+s.length),E=w.indexOf(s))=>S+(E<0?w:H(E,w,s,g)),q=(e,t,s,g,S)=>e<0?s+t+g:s+H(e,t,g,S)+g,ee=(e,t,s=e,g=e.length+1)=>S=>S||!(S===``||S===void 0)?q((``+S).indexOf(t,g),S,e,t,s):``,J=(e,t,s)=>ee(`\x1b[${e}m`,`\x1b[${t}m`,s),Y={reset:J(0,0),bold:J(1,22,`\x1B[22m\x1B[1m`),dim:J(2,22,`\x1B[22m\x1B[2m`),italic:J(3,23),underline:J(4,24),inverse:J(7,27),hidden:J(8,28),strikethrough:J(9,29),black:J(30,39),red:J(31,39),green:J(32,39),yellow:J(33,39),blue:J(34,39),magenta:J(35,39),cyan:J(36,39),white:J(37,39),gray:J(90,39),bgBlack:J(40,49),bgRed:J(41,49),bgGreen:J(42,49),bgYellow:J(43,49),bgBlue:J(44,49),bgMagenta:J(45,49),bgCyan:J(46,49),bgWhite:J(47,49),blackBright:J(90,39),redBright:J(91,39),greenBright:J(92,39),yellowBright:J(93,39),blueBright:J(94,39),magentaBright:J(95,39),cyanBright:J(96,39),whiteBright:J(97,39),bgBlackBright:J(100,49),bgRedBright:J(101,49),bgGreenBright:J(102,49),bgYellowBright:J(103,49),bgBlueBright:J(104,49),bgMagentaBright:J(105,49),bgCyanBright:J(106,49),bgWhiteBright:J(107,49)},te=({useColor:e=B}={})=>e?Y:Object.keys(Y).reduce((e,t)=>({...e,[t]:String}),{}),{reset:ne,bold:ae,dim:oe,italic:se,underline:ce,inverse:ue,hidden:de,strikethrough:fe,black:me,red:ge,green:_e,yellow:ve,blue:ye,magenta:Ce,cyan:we,white:Te,gray:De,bgBlack:je,bgRed:Me,bgGreen:Pe,bgYellow:Ie,bgBlue:Re,bgMagenta:ze,bgCyan:Be,bgWhite:Ve,blackBright:Ue,redBright:We,greenBright:Ge,yellowBright:Ke,blueBright:Xe,magentaBright:$e,cyanBright:nt,whiteBright:rt,bgBlackBright:it,bgRedBright:at,bgGreenBright:st,bgYellowBright:vt,bgBlueBright:Tt,bgMagentaBright:Et,bgCyanBright:Dt,bgWhiteBright:jt}=te();e.bgBlack=je,e.bgBlackBright=it,e.bgBlue=Re,e.bgBlueBright=Tt,e.bgCyan=Be,e.bgCyanBright=Dt,e.bgGreen=Pe,e.bgGreenBright=st,e.bgMagenta=ze,e.bgMagentaBright=Et,e.bgRed=Me,e.bgRedBright=at,e.bgWhite=Ve,e.bgWhiteBright=jt,e.bgYellow=Ie,e.bgYellowBright=vt,e.black=me,e.blackBright=Ue,e.blue=ye,e.blueBright=Xe,e.bold=ae,e.createColors=te,e.cyan=we,e.cyanBright=nt,e.dim=oe,e.gray=De,e.green=_e,e.greenBright=Ge,e.hidden=de,e.inverse=ue,e.isColorSupported=B,e.italic=se,e.magenta=Ce,e.magentaBright=$e,e.red=ge,e.redBright=We,e.reset=ne,e.strikethrough=fe,e.underline=ce,e.white=Te,e.whiteBright=rt,e.yellow=ve,e.yellowBright=Ke})),require_wrappy=__commonJSMin(((e,t)=>{t.exports=s;function s(e,t){if(e&&t)return s(e)(t);if(typeof e!=`function`)throw TypeError(`need wrapper function`);return Object.keys(e).forEach(function(t){g[t]=e[t]}),g;function g(){for(var t=Array(arguments.length),s=0;s<t.length;s++)t[s]=arguments[s];var g=e.apply(this,t),S=t[t.length-1];return typeof g==`function`&&g!==S&&Object.keys(S).forEach(function(e){g[e]=S[e]}),g}}})),require_once=__commonJSMin(((e,t)=>{var s=require_wrappy();t.exports=s(g),t.exports.strict=s(S),g.proto=g(function(){Object.defineProperty(Function.prototype,`once`,{value:function(){return g(this)},configurable:!0}),Object.defineProperty(Function.prototype,`onceStrict`,{value:function(){return S(this)},configurable:!0})});function g(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function S(e){var t=function(){if(t.called)throw Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)};return t.onceError=(e.name||"Function wrapped with `once`")+` shouldn't be called more than once`,t.called=!1,t}})),require_end_of_stream=__commonJSMin(((e,t)=>{var s=require_once(),g=function(){},S=global.Bare?queueMicrotask:process.nextTick.bind(process),w=function(e){return e.setHeader&&typeof e.abort==`function`},E=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},D=function(e,t,O){if(typeof t==`function`)return D(e,null,t);t||={},O=s(O||g);var k=e._writableState,j=e._readableState,F=t.readable||t.readable!==!1&&e.readable,L=t.writable||t.writable!==!1&&e.writable,B=!1,H=function(){e.writable||q()},q=function(){L=!1,F||O.call(e)},ee=function(){F=!1,L||O.call(e)},J=function(t){O.call(e,t?Error(`exited with error code: `+t):null)},Y=function(t){O.call(e,t)},te=function(){S(ne)},ne=function(){if(!B&&(F&&!(j&&j.ended&&!j.destroyed)||L&&!(k&&k.ended&&!k.destroyed)))return O.call(e,Error(`premature close`))},ae=function(){e.req.on(`finish`,q)};return w(e)?(e.on(`complete`,q),e.on(`abort`,te),e.req?ae():e.on(`request`,ae)):L&&!k&&(e.on(`end`,H),e.on(`close`,H)),E(e)&&e.on(`exit`,J),e.on(`end`,ee),e.on(`finish`,q),t.error!==!1&&e.on(`error`,Y),e.on(`close`,te),function(){B=!0,e.removeListener(`complete`,q),e.removeListener(`abort`,te),e.removeListener(`request`,ae),e.req&&e.req.removeListener(`finish`,q),e.removeListener(`end`,H),e.removeListener(`close`,H),e.removeListener(`finish`,q),e.removeListener(`exit`,J),e.removeListener(`end`,ee),e.removeListener(`error`,Y),e.removeListener(`close`,te)}};t.exports=D})),require_pump=__commonJSMin(((e,t)=>{var s=require_once(),g=require_end_of_stream(),S;try{S=__require(`fs`)}catch{}var w=function(){},E=typeof process>`u`?!1:/^v?\.0/.test(process.version),D=function(e){return typeof e==`function`},O=function(e){return!E||!S?!1:(e instanceof(S.ReadStream||w)||e instanceof(S.WriteStream||w))&&D(e.close)},k=function(e){return e.setHeader&&D(e.abort)},j=function(e,t,S,E){E=s(E);var j=!1;e.on(`close`,function(){j=!0}),g(e,{readable:t,writable:S},function(e){if(e)return E(e);j=!0,E()});var F=!1;return function(t){if(!j&&!F){if(F=!0,O(e))return e.close(w);if(k(e))return e.abort();if(D(e.destroy))return e.destroy();E(t||Error(`stream was destroyed`))}}},F=function(e){e()},L=function(e,t){return e.pipe(t)};t.exports=function(){var e=Array.prototype.slice.call(arguments),t=D(e[e.length-1]||w)&&e.pop()||w;if(Array.isArray(e[0])&&(e=e[0]),e.length<2)throw Error(`pump requires two streams per minimum`);var s,g=e.map(function(S,w){var E=w<e.length-1;return j(S,E,w>0,function(e){s||=e,e&&g.forEach(F),!E&&(g.forEach(F),t(s))})});return e.reduce(L)}})),require_split2=__commonJSMin(((e,t)=>{let{Transform:s}=__require(`stream`),{StringDecoder:g}=__require(`string_decoder`),S=Symbol(`last`),w=Symbol(`decoder`);function E(e,t,s){let g;if(this.overflow){if(g=this[w].write(e).split(this.matcher),g.length===1)return s();g.shift(),this.overflow=!1}else this[S]+=this[w].write(e),g=this[S].split(this.matcher);this[S]=g.pop();for(let e=0;e<g.length;e++)try{O(this,this.mapper(g[e]))}catch(e){return s(e)}if(this.overflow=this[S].length>this.maxLength,this.overflow&&!this.skipOverflow){s(Error(`maximum buffer reached`));return}s()}function D(e){if(this[S]+=this[w].end(),this[S])try{O(this,this.mapper(this[S]))}catch(t){return e(t)}e()}function O(e,t){t!==void 0&&e.push(t)}function k(e){return e}function j(e,t,O){switch(e||=/\r?\n/,t||=k,O||={},arguments.length){case 1:typeof e==`function`?(t=e,e=/\r?\n/):typeof e==`object`&&!(e instanceof RegExp)&&!e[Symbol.split]&&(O=e,e=/\r?\n/);break;case 2:typeof e==`function`?(O=t,t=e,e=/\r?\n/):typeof t==`object`&&(O=t,t=k)}O=Object.assign({},O),O.autoDestroy=!0,O.transform=E,O.flush=D,O.readableObjectMode=!0;let j=new s(O);return j[S]=``,j[w]=new g(`utf8`),j.matcher=e,j.mapper=t,j.maxLength=O.maxLength,j.skipOverflow=O.skipOverflow||!1,j.overflow=!1,j._destroy=function(e,t){this._writableState.errorEmitted=!1,t(e)},j}t.exports=j})),require_pino_abstract_transport=__commonJSMin(((e,t)=>{let s=Symbol.for(`pino.metadata`),g=require_split2(),{Duplex:S}=__require(`stream`),{parentPort:w,workerData:E}=__require(`worker_threads`);function D(){let e,t,s=new Promise((s,g)=>{e=s,t=g});return s.resolve=e,s.reject=t,s}t.exports=function(e,t={}){let k=t.expectPinoConfig===!0&&E?.workerData?.pinoWillSendConfig===!0,j=t.parse===`lines`,F=typeof t.parseLine==`function`?t.parseLine:JSON.parse,L=t.close||O,B=g(function(e){let t;try{t=F(e)}catch(t){this.emit(`unknown`,e,t);return}if(t===null){this.emit(`unknown`,e,`Null value ignored`);return}return typeof t!=`object`&&(t={data:t,time:Date.now()}),B[s]&&(B.lastTime=t.time,B.lastLevel=t.level,B.lastObj=t),j?e:t},{autoDestroy:!0});if(B._destroy=function(e,t){let s=L(e,t);s&&typeof s.then==`function`&&s.then(t,t)},t.expectPinoConfig===!0&&E?.workerData?.pinoWillSendConfig!==!0&&setImmediate(()=>{B.emit(`error`,Error(`This transport is not compatible with the current version of pino. Please upgrade pino to the latest version.`))}),t.metadata!==!1&&(B[s]=!0,B.lastTime=0,B.lastLevel=0,B.lastObj=null),k){let e={},t=D();return w.on(`message`,function s(g){g.code===`PINO_CONFIG`&&(e=g.config,t.resolve(),w.off(`message`,s))}),Object.defineProperties(B,{levels:{get(){return e.levels}},messageKey:{get(){return e.messageKey}},errorKey:{get(){return e.errorKey}}}),t.then(H)}return H();function H(){let s=e(B);if(s&&typeof s.catch==`function`)s.catch(e=>{B.destroy(e)}),s=null;else if(t.enablePipelining&&s)return S.from({writable:B,readable:s});return B}};function O(e,t){process.nextTick(t,e)}})),require_constants=__commonJSMin(((e,t)=>{t.exports={DATE_FORMAT:`yyyy-mm-dd HH:MM:ss.l o`,DATE_FORMAT_SIMPLE:`HH:MM:ss.l`,ERROR_LIKE_KEYS:[`err`,`error`],MESSAGE_KEY:`msg`,LEVEL_KEY:`level`,LEVEL_LABEL:`levelLabel`,TIMESTAMP_KEY:`time`,LEVELS:{default:`USERLVL`,60:`FATAL`,50:`ERROR`,40:`WARN`,30:`INFO`,20:`DEBUG`,10:`TRACE`},LEVEL_NAMES:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},LOGGER_KEYS:[`pid`,`hostname`,`name`,`level`,`time`,`timestamp`,`caller`]}})),require_get_level_label_data=__commonJSMin(((e,t)=>{t.exports=S;let{LEVELS:s,LEVEL_NAMES:g}=require_constants();function S(e,t,S){let w=e?t||s:Object.assign({},s,t),E=e?S||g:Object.assign({},g,S);return function(e){let t=`default`;return t=Number.isInteger(+e)?Object.prototype.hasOwnProperty.call(w,e)?e:t:Object.prototype.hasOwnProperty.call(E,e.toLowerCase())?E[e.toLowerCase()]:t,[w[t],t]}}})),require_colors=__commonJSMin(((e,t)=>{let s=e=>e,g={default:s,60:s,50:s,40:s,30:s,20:s,10:s,message:s,greyMessage:s,property:s},{createColors:S}=require_colorette(),w=require_get_level_label_data(),E=S({useColor:!0}),{white:D,bgRed:O,red:k,yellow:j,green:F,blue:L,gray:B,cyan:H,magenta:q}=E,ee={default:D,60:O,50:k,40:j,30:F,20:L,10:B,message:H,greyMessage:B,property:q};function J(e){return e.reduce(function(e,[t,s]){return e[t]=typeof E[s]==`function`?E[s]:D,e},{default:D,message:H,greyMessage:B,property:q})}function Y(e){return function(t,s,{customLevels:g,customLevelNames:S}={}){let[E,D]=w(e,g,S)(t);return Object.prototype.hasOwnProperty.call(s,D)?s[D](E):s.default(E)}}function te(e){let t=Y(e),s=function(e,s){return t(e,g,s)};return s.message=g.message,s.greyMessage=g.greyMessage,s.property=g.property,s.colors=S({useColor:!1}),s}function ne(e){let t=Y(e),s=function(e,s){return t(e,ee,s)};return s.message=ee.message,s.property=ee.property,s.greyMessage=ee.greyMessage,s.colors=E,s}function ae(e,t){let s=J(e),g=t?s:Object.assign({},ee,s),S=Y(t),w=function(e,t){return S(e,g,t)};return w.colors=E,w.message=w.message||g.message,w.property=w.property||g.property,w.greyMessage=w.greyMessage||g.greyMessage,w}t.exports=function(e=!1,t,s){return e&&t!==void 0?ae(t,s):e?ne(s):te(s)}})),require_noop=__commonJSMin(((e,t)=>{t.exports=function(){}})),require_build_safe_sonic_boom=__commonJSMin(((e,t)=>{t.exports=w;let{isMainThread:s}=__require(`node:worker_threads`),g=require_sonic_boom(),S=require_noop();function w(e){let t=new g(e);return t.on(`error`,w),!e.sync&&s&&E(t),t;function w(e){if(e.code===`EPIPE`){t.write=S,t.end=S,t.flushSync=S,t.destroy=S;return}t.removeListener(`error`,w)}}function E(e){if(global.WeakRef&&global.WeakMap&&global.FinalizationRegistry){let t=require_on_exit_leak_free();t.register(e,D),e.on(`close`,function(){t.unregister(e)})}}function D(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}})),require_is_valid_date=__commonJSMin(((e,t)=>{t.exports=s;function s(e){return e instanceof Date&&!Number.isNaN(e.getTime())}})),require_create_date=__commonJSMin(((e,t)=>{t.exports=g;let s=require_is_valid_date();function g(e){let t=new Date(e);return s(t)||(t=new Date(+e)),t}})),require_split_property_key=__commonJSMin(((e,t)=>{t.exports=s;function s(e){let t=[],s=!1,g=``;for(let S=0;S<e.length;S++){let w=e.charAt(S);if(w===`\\`){s=!0;continue}if(s){s=!1,g+=w;continue}if(w===`.`){t.push(g),g=``;continue}g+=w}return g.length&&t.push(g),t}})),require_get_property_value=__commonJSMin(((e,t)=>{t.exports=g;let s=require_split_property_key();function g(e,t){let g=Array.isArray(t)?t:s(t);for(let t of g){if(!Object.prototype.hasOwnProperty.call(e,t))return;e=e[t]}return e}})),require_delete_log_property=__commonJSMin(((e,t)=>{t.exports=S;let s=require_get_property_value(),g=require_split_property_key();function S(e,t){let S=g(t),w=S.pop();e=s(e,S),typeof e==`object`&&e&&Object.prototype.hasOwnProperty.call(e,w)&&delete e[w]}})),require_cjs=__commonJSMin((e=>{let t=Function.prototype.toString,s=Object.prototype.toString;function g(e){if(!e)return Object.create(null);let s=e.constructor;if(s===Object)return e===Object.prototype?{}:Object.create(e);if(s&&~t.call(s).indexOf(`[native code]`))try{return new s}catch{}return Object.create(e)}function S(e){let t=e[Symbol.toStringTag];if(t)return t;let g=s.call(e);return g.substring(8,g.length-1)}let{hasOwnProperty:w,propertyIsEnumerable:E}=Object.prototype;function D(e,t,s,g){let S=Object.getOwnPropertyDescriptor(e,s)||{configurable:!0,enumerable:!0,value:e[s],writable:!0},w=S.get||S.set?S:{configurable:S.configurable,enumerable:S.enumerable,value:g.copier(S.value,g),writable:S.writable};try{Object.defineProperty(t,s,w)}catch{t[s]=w.get?w.get():w.value}}function O(e,t,s){let g=Object.getOwnPropertyNames(e);for(let S=0;S<g.length;++S)D(e,t,g[S],s);let S=Object.getOwnPropertySymbols(e);for(let g=0;g<S.length;++g)D(e,t,S[g],s);return t}function k(e,t){let s=new t.Constructor;t.cache.set(e,s);for(let g=0;g<e.length;++g)s[g]=t.copier(e[g],t);return s}function j(e,t){let s=new t.Constructor;return t.cache.set(e,s),O(e,s,t)}function F(e,t){return e.slice(0)}function L(e,t){return e.slice(0,e.size,e.type)}function B(e,t){return new t.Constructor(F(e.buffer))}function H(e,t){return new t.Constructor(e.getTime())}function q(e,t){let s=new t.Constructor;return t.cache.set(e,s),e.forEach((e,g)=>{s.set(g,t.copier(e,t))}),s}function ee(e,t){return O(e,q(e,t),t)}function J(e,t){let s=g(t.prototype);t.cache.set(e,s);for(let g in e)w.call(e,g)&&(s[g]=t.copier(e[g],t));let S=Object.getOwnPropertySymbols(e);for(let g=0;g<S.length;++g){let w=S[g];E.call(e,w)&&(s[w]=t.copier(e[w],t))}return s}function Y(e,t){let s=g(t.prototype);return t.cache.set(e,s),O(e,s,t)}function te(e,t){return new t.Constructor(e.valueOf())}function ne(e,t){let s=new t.Constructor(e.source,e.flags);return s.lastIndex=e.lastIndex,s}function ae(e,t){return e}function oe(e,t){let s=new t.Constructor;return t.cache.set(e,s),e.forEach(e=>{s.add(t.copier(e,t))}),s}function se(e,t){return O(e,oe(e,t),t)}function ce(){return new WeakMap}function ue({createCache:e,methods:t,strict:s}){let g={array:s?j:k,arrayBuffer:F,asyncGenerator:ae,blob:L,dataView:B,date:H,error:ae,generator:ae,map:s?ee:q,object:s?Y:J,regExp:ne,set:s?se:oe},S=t?Object.assign(g,t):g,w=de(S),E=e||ce;if(!w.Object||!w.Array)throw Error(`An object and array copier must be provided.`);return{createCache:E,copiers:w,methods:S,strict:!!s}}function de(e){return{Arguments:e.object,Array:e.array,ArrayBuffer:e.arrayBuffer,AsyncGenerator:e.asyncGenerator,Blob:e.blob,Boolean:te,DataView:e.dataView,Date:e.date,Error:e.error,Float32Array:e.arrayBuffer,Float64Array:e.arrayBuffer,Generator:e.generator,Int8Array:e.arrayBuffer,Int16Array:e.arrayBuffer,Int32Array:e.arrayBuffer,Map:e.map,Number:te,Object:e.object,Promise:ae,RegExp:e.regExp,Set:e.set,String:te,WeakMap:ae,WeakSet:ae,Uint8Array:e.arrayBuffer,Uint8ClampedArray:e.arrayBuffer,Uint16Array:e.arrayBuffer,Uint32Array:e.arrayBuffer,Uint64Array:e.arrayBuffer}}function fe(e={}){let{createCache:t,copiers:s}=ue(e),{Array:g,Object:w}=s;function E(e,t){if(t.prototype=t.Constructor=void 0,!e||typeof e!=`object`)return e;if(t.cache.has(e))return t.cache.get(e);if(t.prototype=Object.getPrototypeOf(e),t.Constructor=t.prototype&&t.prototype.constructor,!t.Constructor||t.Constructor===Object)return w(e,t);if(Array.isArray(e))return g(e,t);let E=s[S(e)];return E?E(e,t):typeof e.then==`function`?e:w(e,t)}return function(e){return E(e,{Constructor:void 0,cache:t(),copier:E,prototype:void 0})}}let me=fe({strict:!0});e.copy=fe(),e.copyStrict=me,e.createCopier=fe})),require_filter_log=__commonJSMin(((e,t)=>{t.exports=w;let{createCopier:s}=require_cjs(),g=s({}),S=require_delete_log_property();function w({log:e,context:t}){let{ignoreKeys:s,includeKeys:w}=t,E=g(e);if(w){let e={};return w.forEach(t=>{e[t]=E[t]}),e}return s.forEach(e=>{S(E,e)}),E}})),require_dateformat=__commonJSMin(((e,t)=>{function s(e){"@babel/helpers - typeof";return s=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},s(e)}(function(g){var S=arguments,w=function(){var e=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,t=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,s=/[^-+\dA-Z]/g;return function(g,F,L,B){if(S.length===1&&j(g)===`string`&&!/\d/.test(g)&&(F=g,g=void 0),g=g||g===0?g:new Date,g instanceof Date||(g=new Date(g)),isNaN(g))throw TypeError(`Invalid date`);F=String(w.masks[F]||F||w.masks.default);var H=F.slice(0,4);(H===`UTC:`||H===`GMT:`)&&(F=F.slice(4),L=!0,H===`GMT:`&&(B=!0));var q=function(){return L?`getUTC`:`get`},ee=function(){return g[q()+`Date`]()},J=function(){return g[q()+`Day`]()},Y=function(){return g[q()+`Month`]()},te=function(){return g[q()+`FullYear`]()},ne=function(){return g[q()+`Hours`]()},ae=function(){return g[q()+`Minutes`]()},oe=function(){return g[q()+`Seconds`]()},se=function(){return g[q()+`Milliseconds`]()},ce=function(){return L?0:g.getTimezoneOffset()},ue=function(){return O(g)},de=function(){return k(g)},fe={d:function(){return ee()},dd:function(){return E(ee())},ddd:function(){return w.i18n.dayNames[J()]},DDD:function(){return D({y:te(),m:Y(),d:ee(),_:q(),dayName:w.i18n.dayNames[J()],short:!0})},dddd:function(){return w.i18n.dayNames[J()+7]},DDDD:function(){return D({y:te(),m:Y(),d:ee(),_:q(),dayName:w.i18n.dayNames[J()+7]})},m:function(){return Y()+1},mm:function(){return E(Y()+1)},mmm:function(){return w.i18n.monthNames[Y()]},mmmm:function(){return w.i18n.monthNames[Y()+12]},yy:function(){return String(te()).slice(2)},yyyy:function(){return E(te(),4)},h:function(){return ne()%12||12},hh:function(){return E(ne()%12||12)},H:function(){return ne()},HH:function(){return E(ne())},M:function(){return ae()},MM:function(){return E(ae())},s:function(){return oe()},ss:function(){return E(oe())},l:function(){return E(se(),3)},L:function(){return E(Math.floor(se()/10))},t:function(){return ne()<12?w.i18n.timeNames[0]:w.i18n.timeNames[1]},tt:function(){return ne()<12?w.i18n.timeNames[2]:w.i18n.timeNames[3]},T:function(){return ne()<12?w.i18n.timeNames[4]:w.i18n.timeNames[5]},TT:function(){return ne()<12?w.i18n.timeNames[6]:w.i18n.timeNames[7]},Z:function(){return B?`GMT`:L?`UTC`:(String(g).match(t)||[``]).pop().replace(s,``).replace(/GMT\+0000/g,`UTC`)},o:function(){return(ce()>0?`-`:`+`)+E(Math.floor(Math.abs(ce())/60)*100+Math.abs(ce())%60,4)},p:function(){return(ce()>0?`-`:`+`)+E(Math.floor(Math.abs(ce())/60),2)+`:`+E(Math.floor(Math.abs(ce())%60),2)},S:function(){return[`th`,`st`,`nd`,`rd`][ee()%10>3?0:(ee()%100-ee()%10!=10)*ee()%10]},W:function(){return ue()},WW:function(){return E(ue())},N:function(){return de()}};return F.replace(e,function(e){return e in fe?fe[e]():e.slice(1,e.length-1)})}}();w.masks={default:`ddd mmm dd yyyy HH:MM:ss`,shortDate:`m/d/yy`,paddedShortDate:`mm/dd/yyyy`,mediumDate:`mmm d, yyyy`,longDate:`mmmm d, yyyy`,fullDate:`dddd, mmmm d, yyyy`,shortTime:`h:MM TT`,mediumTime:`h:MM:ss TT`,longTime:`h:MM:ss TT Z`,isoDate:`yyyy-mm-dd`,isoTime:`HH:MM:ss`,isoDateTime:`yyyy-mm-dd'T'HH:MM:sso`,isoUtcDateTime:`UTC:yyyy-mm-dd'T'HH:MM:ss'Z'`,expiresHeaderFormat:`ddd, dd mmm yyyy HH:MM:ss Z`},w.i18n={dayNames:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],monthNames:[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`,`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],timeNames:[`a`,`p`,`am`,`pm`,`A`,`P`,`AM`,`PM`]};var E=function(e,t){for(e=String(e),t||=2;e.length<t;)e=`0`+e;return e},D=function(e){var t=e.y,s=e.m,g=e.d,S=e._,w=e.dayName,E=e.short,D=E===void 0?!1:E,O=new Date,k=new Date;k.setDate(k[S+`Date`]()-1);var j=new Date;return j.setDate(j[S+`Date`]()+1),function(){return O[S+`FullYear`]()}()===t&&function(){return O[S+`Month`]()}()===s&&function(){return O[S+`Date`]()}()===g?D?`Tdy`:`Today`:function(){return k[S+`FullYear`]()}()===t&&function(){return k[S+`Month`]()}()===s&&function(){return k[S+`Date`]()}()===g?D?`Ysd`:`Yesterday`:function(){return j[S+`FullYear`]()}()===t&&function(){return j[S+`Month`]()}()===s&&function(){return j[S+`Date`]()}()===g?D?`Tmw`:`Tomorrow`:w},O=function(e){var t=new Date(e.getFullYear(),e.getMonth(),e.getDate());t.setDate(t.getDate()-(t.getDay()+6)%7+3);var s=new Date(t.getFullYear(),0,4);s.setDate(s.getDate()-(s.getDay()+6)%7+3);var g=t.getTimezoneOffset()-s.getTimezoneOffset();t.setHours(t.getHours()-g);var S=(t-s)/(864e5*7);return 1+Math.floor(S)},k=function(e){var t=e.getDay();return t===0&&(t=7),t},j=function(e){return e===null?`null`:e===void 0?`undefined`:s(e)===`object`?Array.isArray(e)?`array`:{}.toString.call(e).slice(8,-1).toLowerCase():s(e)};typeof define==`function`&&define.amd?define(function(){return w}):(e===void 0?`undefined`:s(e))===`object`?t.exports=w:g.dateFormat=w})(void 0)})),require_format_time=__commonJSMin(((e,t)=>{t.exports=D;let{DATE_FORMAT:s,DATE_FORMAT_SIMPLE:g}=require_constants(),S=require_dateformat(),w=require_create_date(),E=require_is_valid_date();function D(e,t=!1){if(t===!1)return e;let D=w(e);if(!E(D))return e;if(t===!0)return S(D,g);let O=t.toUpperCase();if(O===`SYS:STANDARD`)return S(D,s);let k=O.substr(0,4);return k===`SYS:`||k===`UTC:`?k===`UTC:`?S(D,t):S(D,t.slice(4)):S(D,`UTC:${t}`)}})),require_handle_custom_levels_names_opts=__commonJSMin(((e,t)=>{t.exports=s;function s(e){return e?typeof e==`string`?e.split(`,`).reduce((e,t,s)=>{let[g,S=s]=t.split(`:`);return e[g.toLowerCase()]=S,e},{}):Object.prototype.toString.call(e)===`[object Object]`?Object.keys(e).reduce((t,s)=>(t[s.toLowerCase()]=e[s],t),{}):{}:{}}})),require_handle_custom_levels_opts=__commonJSMin(((e,t)=>{t.exports=s;function s(e){return e?typeof e==`string`?e.split(`,`).reduce((e,t,s)=>{let[g,S=s]=t.split(`:`);return e[S]=g.toUpperCase(),e},{default:`USERLVL`}):Object.prototype.toString.call(e)===`[object Object]`?Object.keys(e).reduce((t,s)=>(t[e[s]]=s.toUpperCase(),t),{default:`USERLVL`}):{}:{}}})),require_interpret_conditionals=__commonJSMin(((e,t)=>{t.exports=g;let s=require_get_property_value();function g(e,t){return e=e.replace(/{if (.*?)}(.*?){end}/g,g),e=e.replace(/{if (.*?)}/g,``),e=e.replace(/{end}/g,``),e.replace(/\s+/g,` `).trim();function g(e,g,S){let w=s(t,g);return w&&S.includes(g)?S.replace(RegExp(`{`+g+`}`,`g`),w):``}}})),require_is_object=__commonJSMin(((e,t)=>{t.exports=s;function s(e){return Object.prototype.toString.apply(e)===`[object Object]`}})),require_join_lines_with_indentation=__commonJSMin(((e,t)=>{t.exports=s;function s({input:e,ident:t=` `,eol:s=`
|
|
766
|
+
`),Wt=Y.bind(null,{[ue]:``,[fe]:ee,[Ce]:Vt,[ve]:ae,[ye]:Rt,[Be]:zt}),Xt=``;$e!==null&&(Xt=Wt(nt===void 0?$e:Object.assign({},$e,{name:nt})));let Zt=J instanceof Function?J:J?Ke:Xe,$t=Zt().indexOf(`:`)+1;if(Tt&&!at)throw Error(`customLevels is required if useOnlyCustomLevels is set true`);if(vt&&typeof vt!=`function`)throw Error(`Unknown mixin type "${typeof vt}" - expected "function"`);if(Lt&&typeof Lt!=`string`)throw Error(`Unknown msgPrefix type "${typeof Lt}" - expected "string"`);j(rt,at,Tt);let en=F(at,Tt);typeof g.emit==`function`&&g.emit(`message`,{code:`PINO_CONFIG`,config:{levels:en,messageKey:te,errorKey:oe}}),H(st);let tn=B(st);return Object.assign(t,{levels:en,[Re]:tn,[ze]:Tt,[_e]:g,[me]:Zt,[ge]:$t,[ve]:ae,[ye]:Rt,[Ce]:Vt,[Te]:Ut,[De]:Ht,[je]:te,[Me]:oe,[Pe]:ce,[Ue]:ce?`,${JSON.stringify(ce)}:{`:``,[fe]:ee,[Ie]:vt,[We]:St,[ue]:Xt,[Be]:zt,[Ve]:jt,silent:se,onChild:It,[Ge]:Lt}),Object.setPrototypeOf(t,D()),L(t),t[we](rt),t}t.exports=st,t.exports.destination=(e=process.stdout.fd)=>typeof e==`object`?(e.dest=oe(e.dest||process.stdout.fd),te(e)):te({dest:oe(e),minLength:0}),t.exports.transport=require_transport(),t.exports.multistream=require_multistream(),t.exports.levels=F(),t.exports.stdSerializers=at,t.exports.stdTimeFunctions=Object.assign({},E),t.exports.symbols=O,t.exports.version=ce,t.exports.default=st,t.exports.pino=st})),require_colorette=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t=__require(`tty`);function s(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(s){if(s!==`default`){var g=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,g.get?g:{enumerable:!0,get:function(){return e[s]}})}}),t.default=e,Object.freeze(t)}var g=s(t);let{env:S={},argv:w=[],platform:E=``}=typeof process>`u`?{}:process,D=`NO_COLOR`in S||w.includes(`--no-color`),O=`FORCE_COLOR`in S||w.includes(`--color`),k=E===`win32`,j=S.TERM===`dumb`,F=g&&g.isatty&&g.isatty(1)&&S.TERM&&!j,L=`CI`in S&&(`GITHUB_ACTIONS`in S||`GITLAB_CI`in S||`CIRCLECI`in S),B=!D&&(O||k&&!j||F||L),H=(e,t,s,g,S=t.substring(0,e)+g,w=t.substring(e+s.length),E=w.indexOf(s))=>S+(E<0?w:H(E,w,s,g)),q=(e,t,s,g,S)=>e<0?s+t+g:s+H(e,t,g,S)+g,ee=(e,t,s=e,g=e.length+1)=>S=>S||!(S===``||S===void 0)?q((``+S).indexOf(t,g),S,e,t,s):``,J=(e,t,s)=>ee(`\x1b[${e}m`,`\x1b[${t}m`,s),Y={reset:J(0,0),bold:J(1,22,`\x1B[22m\x1B[1m`),dim:J(2,22,`\x1B[22m\x1B[2m`),italic:J(3,23),underline:J(4,24),inverse:J(7,27),hidden:J(8,28),strikethrough:J(9,29),black:J(30,39),red:J(31,39),green:J(32,39),yellow:J(33,39),blue:J(34,39),magenta:J(35,39),cyan:J(36,39),white:J(37,39),gray:J(90,39),bgBlack:J(40,49),bgRed:J(41,49),bgGreen:J(42,49),bgYellow:J(43,49),bgBlue:J(44,49),bgMagenta:J(45,49),bgCyan:J(46,49),bgWhite:J(47,49),blackBright:J(90,39),redBright:J(91,39),greenBright:J(92,39),yellowBright:J(93,39),blueBright:J(94,39),magentaBright:J(95,39),cyanBright:J(96,39),whiteBright:J(97,39),bgBlackBright:J(100,49),bgRedBright:J(101,49),bgGreenBright:J(102,49),bgYellowBright:J(103,49),bgBlueBright:J(104,49),bgMagentaBright:J(105,49),bgCyanBright:J(106,49),bgWhiteBright:J(107,49)},te=({useColor:e=B}={})=>e?Y:Object.keys(Y).reduce((e,t)=>({...e,[t]:String}),{}),{reset:ne,bold:ae,dim:oe,italic:se,underline:ce,inverse:ue,hidden:de,strikethrough:fe,black:me,red:ge,green:_e,yellow:ve,blue:ye,magenta:Ce,cyan:we,white:Te,gray:De,bgBlack:je,bgRed:Me,bgGreen:Pe,bgYellow:Ie,bgBlue:Re,bgMagenta:ze,bgCyan:Be,bgWhite:Ve,blackBright:Ue,redBright:We,greenBright:Ge,yellowBright:Ke,blueBright:Xe,magentaBright:$e,cyanBright:nt,whiteBright:rt,bgBlackBright:it,bgRedBright:at,bgGreenBright:st,bgYellowBright:vt,bgBlueBright:St,bgMagentaBright:Tt,bgCyanBright:Et,bgWhiteBright:jt}=te();e.bgBlack=je,e.bgBlackBright=it,e.bgBlue=Re,e.bgBlueBright=St,e.bgCyan=Be,e.bgCyanBright=Et,e.bgGreen=Pe,e.bgGreenBright=st,e.bgMagenta=ze,e.bgMagentaBright=Tt,e.bgRed=Me,e.bgRedBright=at,e.bgWhite=Ve,e.bgWhiteBright=jt,e.bgYellow=Ie,e.bgYellowBright=vt,e.black=me,e.blackBright=Ue,e.blue=ye,e.blueBright=Xe,e.bold=ae,e.createColors=te,e.cyan=we,e.cyanBright=nt,e.dim=oe,e.gray=De,e.green=_e,e.greenBright=Ge,e.hidden=de,e.inverse=ue,e.isColorSupported=B,e.italic=se,e.magenta=Ce,e.magentaBright=$e,e.red=ge,e.redBright=We,e.reset=ne,e.strikethrough=fe,e.underline=ce,e.white=Te,e.whiteBright=rt,e.yellow=ve,e.yellowBright=Ke})),require_wrappy=__commonJSMin(((e,t)=>{t.exports=s;function s(e,t){if(e&&t)return s(e)(t);if(typeof e!=`function`)throw TypeError(`need wrapper function`);return Object.keys(e).forEach(function(t){g[t]=e[t]}),g;function g(){for(var t=Array(arguments.length),s=0;s<t.length;s++)t[s]=arguments[s];var g=e.apply(this,t),S=t[t.length-1];return typeof g==`function`&&g!==S&&Object.keys(S).forEach(function(e){g[e]=S[e]}),g}}})),require_once=__commonJSMin(((e,t)=>{var s=require_wrappy();t.exports=s(g),t.exports.strict=s(S),g.proto=g(function(){Object.defineProperty(Function.prototype,`once`,{value:function(){return g(this)},configurable:!0}),Object.defineProperty(Function.prototype,`onceStrict`,{value:function(){return S(this)},configurable:!0})});function g(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function S(e){var t=function(){if(t.called)throw Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)};return t.onceError=(e.name||"Function wrapped with `once`")+` shouldn't be called more than once`,t.called=!1,t}})),require_end_of_stream=__commonJSMin(((e,t)=>{var s=require_once(),g=function(){},S=global.Bare?queueMicrotask:process.nextTick.bind(process),w=function(e){return e.setHeader&&typeof e.abort==`function`},E=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},D=function(e,t,O){if(typeof t==`function`)return D(e,null,t);t||={},O=s(O||g);var k=e._writableState,j=e._readableState,F=t.readable||t.readable!==!1&&e.readable,L=t.writable||t.writable!==!1&&e.writable,B=!1,H=function(){e.writable||q()},q=function(){L=!1,F||O.call(e)},ee=function(){F=!1,L||O.call(e)},J=function(t){O.call(e,t?Error(`exited with error code: `+t):null)},Y=function(t){O.call(e,t)},te=function(){S(ne)},ne=function(){if(!B&&(F&&!(j&&j.ended&&!j.destroyed)||L&&!(k&&k.ended&&!k.destroyed)))return O.call(e,Error(`premature close`))},ae=function(){e.req.on(`finish`,q)};return w(e)?(e.on(`complete`,q),e.on(`abort`,te),e.req?ae():e.on(`request`,ae)):L&&!k&&(e.on(`end`,H),e.on(`close`,H)),E(e)&&e.on(`exit`,J),e.on(`end`,ee),e.on(`finish`,q),t.error!==!1&&e.on(`error`,Y),e.on(`close`,te),function(){B=!0,e.removeListener(`complete`,q),e.removeListener(`abort`,te),e.removeListener(`request`,ae),e.req&&e.req.removeListener(`finish`,q),e.removeListener(`end`,H),e.removeListener(`close`,H),e.removeListener(`finish`,q),e.removeListener(`exit`,J),e.removeListener(`end`,ee),e.removeListener(`error`,Y),e.removeListener(`close`,te)}};t.exports=D})),require_pump=__commonJSMin(((e,t)=>{var s=require_once(),g=require_end_of_stream(),S;try{S=__require(`fs`)}catch{}var w=function(){},E=typeof process>`u`?!1:/^v?\.0/.test(process.version),D=function(e){return typeof e==`function`},O=function(e){return!E||!S?!1:(e instanceof(S.ReadStream||w)||e instanceof(S.WriteStream||w))&&D(e.close)},k=function(e){return e.setHeader&&D(e.abort)},j=function(e,t,S,E){E=s(E);var j=!1;e.on(`close`,function(){j=!0}),g(e,{readable:t,writable:S},function(e){if(e)return E(e);j=!0,E()});var F=!1;return function(t){if(!j&&!F){if(F=!0,O(e))return e.close(w);if(k(e))return e.abort();if(D(e.destroy))return e.destroy();E(t||Error(`stream was destroyed`))}}},F=function(e){e()},L=function(e,t){return e.pipe(t)};t.exports=function(){var e=Array.prototype.slice.call(arguments),t=D(e[e.length-1]||w)&&e.pop()||w;if(Array.isArray(e[0])&&(e=e[0]),e.length<2)throw Error(`pump requires two streams per minimum`);var s,g=e.map(function(S,w){var E=w<e.length-1;return j(S,E,w>0,function(e){s||=e,e&&g.forEach(F),!E&&(g.forEach(F),t(s))})});return e.reduce(L)}})),require_split2=__commonJSMin(((e,t)=>{let{Transform:s}=__require(`stream`),{StringDecoder:g}=__require(`string_decoder`),S=Symbol(`last`),w=Symbol(`decoder`);function E(e,t,s){let g;if(this.overflow){if(g=this[w].write(e).split(this.matcher),g.length===1)return s();g.shift(),this.overflow=!1}else this[S]+=this[w].write(e),g=this[S].split(this.matcher);this[S]=g.pop();for(let e=0;e<g.length;e++)try{O(this,this.mapper(g[e]))}catch(e){return s(e)}if(this.overflow=this[S].length>this.maxLength,this.overflow&&!this.skipOverflow){s(Error(`maximum buffer reached`));return}s()}function D(e){if(this[S]+=this[w].end(),this[S])try{O(this,this.mapper(this[S]))}catch(t){return e(t)}e()}function O(e,t){t!==void 0&&e.push(t)}function k(e){return e}function j(e,t,O){switch(e||=/\r?\n/,t||=k,O||={},arguments.length){case 1:typeof e==`function`?(t=e,e=/\r?\n/):typeof e==`object`&&!(e instanceof RegExp)&&!e[Symbol.split]&&(O=e,e=/\r?\n/);break;case 2:typeof e==`function`?(O=t,t=e,e=/\r?\n/):typeof t==`object`&&(O=t,t=k)}O=Object.assign({},O),O.autoDestroy=!0,O.transform=E,O.flush=D,O.readableObjectMode=!0;let j=new s(O);return j[S]=``,j[w]=new g(`utf8`),j.matcher=e,j.mapper=t,j.maxLength=O.maxLength,j.skipOverflow=O.skipOverflow||!1,j.overflow=!1,j._destroy=function(e,t){this._writableState.errorEmitted=!1,t(e)},j}t.exports=j})),require_pino_abstract_transport=__commonJSMin(((e,t)=>{let s=Symbol.for(`pino.metadata`),g=require_split2(),{Duplex:S}=__require(`stream`),{parentPort:w,workerData:E}=__require(`worker_threads`);function D(){let e,t,s=new Promise((s,g)=>{e=s,t=g});return s.resolve=e,s.reject=t,s}t.exports=function(e,t={}){let k=t.expectPinoConfig===!0&&E?.workerData?.pinoWillSendConfig===!0,j=t.parse===`lines`,F=typeof t.parseLine==`function`?t.parseLine:JSON.parse,L=t.close||O,B=g(function(e){let t;try{t=F(e)}catch(t){this.emit(`unknown`,e,t);return}if(t===null){this.emit(`unknown`,e,`Null value ignored`);return}return typeof t!=`object`&&(t={data:t,time:Date.now()}),B[s]&&(B.lastTime=t.time,B.lastLevel=t.level,B.lastObj=t),j?e:t},{autoDestroy:!0});if(B._destroy=function(e,t){let s=L(e,t);s&&typeof s.then==`function`&&s.then(t,t)},t.expectPinoConfig===!0&&E?.workerData?.pinoWillSendConfig!==!0&&setImmediate(()=>{B.emit(`error`,Error(`This transport is not compatible with the current version of pino. Please upgrade pino to the latest version.`))}),t.metadata!==!1&&(B[s]=!0,B.lastTime=0,B.lastLevel=0,B.lastObj=null),k){let e={},t=D();return w.on(`message`,function s(g){g.code===`PINO_CONFIG`&&(e=g.config,t.resolve(),w.off(`message`,s))}),Object.defineProperties(B,{levels:{get(){return e.levels}},messageKey:{get(){return e.messageKey}},errorKey:{get(){return e.errorKey}}}),t.then(H)}return H();function H(){let s=e(B);if(s&&typeof s.catch==`function`)s.catch(e=>{B.destroy(e)}),s=null;else if(t.enablePipelining&&s)return S.from({writable:B,readable:s});return B}};function O(e,t){process.nextTick(t,e)}})),require_constants=__commonJSMin(((e,t)=>{t.exports={DATE_FORMAT:`yyyy-mm-dd HH:MM:ss.l o`,DATE_FORMAT_SIMPLE:`HH:MM:ss.l`,ERROR_LIKE_KEYS:[`err`,`error`],MESSAGE_KEY:`msg`,LEVEL_KEY:`level`,LEVEL_LABEL:`levelLabel`,TIMESTAMP_KEY:`time`,LEVELS:{default:`USERLVL`,60:`FATAL`,50:`ERROR`,40:`WARN`,30:`INFO`,20:`DEBUG`,10:`TRACE`},LEVEL_NAMES:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},LOGGER_KEYS:[`pid`,`hostname`,`name`,`level`,`time`,`timestamp`,`caller`]}})),require_get_level_label_data=__commonJSMin(((e,t)=>{t.exports=S;let{LEVELS:s,LEVEL_NAMES:g}=require_constants();function S(e,t,S){let w=e?t||s:Object.assign({},s,t),E=e?S||g:Object.assign({},g,S);return function(e){let t=`default`;return t=Number.isInteger(+e)?Object.prototype.hasOwnProperty.call(w,e)?e:t:Object.prototype.hasOwnProperty.call(E,e.toLowerCase())?E[e.toLowerCase()]:t,[w[t],t]}}})),require_colors=__commonJSMin(((e,t)=>{let s=e=>e,g={default:s,60:s,50:s,40:s,30:s,20:s,10:s,message:s,greyMessage:s,property:s},{createColors:S}=require_colorette(),w=require_get_level_label_data(),E=S({useColor:!0}),{white:D,bgRed:O,red:k,yellow:j,green:F,blue:L,gray:B,cyan:H,magenta:q}=E,ee={default:D,60:O,50:k,40:j,30:F,20:L,10:B,message:H,greyMessage:B,property:q};function J(e){return e.reduce(function(e,[t,s]){return e[t]=typeof E[s]==`function`?E[s]:D,e},{default:D,message:H,greyMessage:B,property:q})}function Y(e){return function(t,s,{customLevels:g,customLevelNames:S}={}){let[E,D]=w(e,g,S)(t);return Object.prototype.hasOwnProperty.call(s,D)?s[D](E):s.default(E)}}function te(e){let t=Y(e),s=function(e,s){return t(e,g,s)};return s.message=g.message,s.greyMessage=g.greyMessage,s.property=g.property,s.colors=S({useColor:!1}),s}function ne(e){let t=Y(e),s=function(e,s){return t(e,ee,s)};return s.message=ee.message,s.property=ee.property,s.greyMessage=ee.greyMessage,s.colors=E,s}function ae(e,t){let s=J(e),g=t?s:Object.assign({},ee,s),S=Y(t),w=function(e,t){return S(e,g,t)};return w.colors=E,w.message=w.message||g.message,w.property=w.property||g.property,w.greyMessage=w.greyMessage||g.greyMessage,w}t.exports=function(e=!1,t,s){return e&&t!==void 0?ae(t,s):e?ne(s):te(s)}})),require_noop=__commonJSMin(((e,t)=>{t.exports=function(){}})),require_build_safe_sonic_boom=__commonJSMin(((e,t)=>{t.exports=w;let{isMainThread:s}=__require(`node:worker_threads`),g=require_sonic_boom(),S=require_noop();function w(e){let t=new g(e);return t.on(`error`,w),!e.sync&&s&&E(t),t;function w(e){if(e.code===`EPIPE`){t.write=S,t.end=S,t.flushSync=S,t.destroy=S;return}t.removeListener(`error`,w)}}function E(e){if(global.WeakRef&&global.WeakMap&&global.FinalizationRegistry){let t=require_on_exit_leak_free();t.register(e,D),e.on(`close`,function(){t.unregister(e)})}}function D(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}})),require_is_valid_date=__commonJSMin(((e,t)=>{t.exports=s;function s(e){return e instanceof Date&&!Number.isNaN(e.getTime())}})),require_create_date=__commonJSMin(((e,t)=>{t.exports=g;let s=require_is_valid_date();function g(e){let t=new Date(e);return s(t)||(t=new Date(+e)),t}})),require_split_property_key=__commonJSMin(((e,t)=>{t.exports=s;function s(e){let t=[],s=!1,g=``;for(let S=0;S<e.length;S++){let w=e.charAt(S);if(w===`\\`){s=!0;continue}if(s){s=!1,g+=w;continue}if(w===`.`){t.push(g),g=``;continue}g+=w}return g.length&&t.push(g),t}})),require_get_property_value=__commonJSMin(((e,t)=>{t.exports=g;let s=require_split_property_key();function g(e,t){let g=Array.isArray(t)?t:s(t);for(let t of g){if(!Object.prototype.hasOwnProperty.call(e,t))return;e=e[t]}return e}})),require_delete_log_property=__commonJSMin(((e,t)=>{t.exports=S;let s=require_get_property_value(),g=require_split_property_key();function S(e,t){let S=g(t),w=S.pop();e=s(e,S),typeof e==`object`&&e&&Object.prototype.hasOwnProperty.call(e,w)&&delete e[w]}})),require_cjs=__commonJSMin((e=>{let t=Function.prototype.toString,s=Object.prototype.toString;function g(e){if(!e)return Object.create(null);let s=e.constructor;if(s===Object)return e===Object.prototype?{}:Object.create(e);if(s&&~t.call(s).indexOf(`[native code]`))try{return new s}catch{}return Object.create(e)}function S(e){let t=e[Symbol.toStringTag];if(t)return t;let g=s.call(e);return g.substring(8,g.length-1)}let{hasOwnProperty:w,propertyIsEnumerable:E}=Object.prototype;function D(e,t,s,g){let S=Object.getOwnPropertyDescriptor(e,s)||{configurable:!0,enumerable:!0,value:e[s],writable:!0},w=S.get||S.set?S:{configurable:S.configurable,enumerable:S.enumerable,value:g.copier(S.value,g),writable:S.writable};try{Object.defineProperty(t,s,w)}catch{t[s]=w.get?w.get():w.value}}function O(e,t,s){let g=Object.getOwnPropertyNames(e);for(let S=0;S<g.length;++S)D(e,t,g[S],s);let S=Object.getOwnPropertySymbols(e);for(let g=0;g<S.length;++g)D(e,t,S[g],s);return t}function k(e,t){let s=new t.Constructor;t.cache.set(e,s);for(let g=0;g<e.length;++g)s[g]=t.copier(e[g],t);return s}function j(e,t){let s=new t.Constructor;return t.cache.set(e,s),O(e,s,t)}function F(e,t){return e.slice(0)}function L(e,t){return e.slice(0,e.size,e.type)}function B(e,t){return new t.Constructor(F(e.buffer))}function H(e,t){return new t.Constructor(e.getTime())}function q(e,t){let s=new t.Constructor;return t.cache.set(e,s),e.forEach((e,g)=>{s.set(g,t.copier(e,t))}),s}function ee(e,t){return O(e,q(e,t),t)}function J(e,t){let s=g(t.prototype);t.cache.set(e,s);for(let g in e)w.call(e,g)&&(s[g]=t.copier(e[g],t));let S=Object.getOwnPropertySymbols(e);for(let g=0;g<S.length;++g){let w=S[g];E.call(e,w)&&(s[w]=t.copier(e[w],t))}return s}function Y(e,t){let s=g(t.prototype);return t.cache.set(e,s),O(e,s,t)}function te(e,t){return new t.Constructor(e.valueOf())}function ne(e,t){let s=new t.Constructor(e.source,e.flags);return s.lastIndex=e.lastIndex,s}function ae(e,t){return e}function oe(e,t){let s=new t.Constructor;return t.cache.set(e,s),e.forEach(e=>{s.add(t.copier(e,t))}),s}function se(e,t){return O(e,oe(e,t),t)}function ce(){return new WeakMap}function ue({createCache:e,methods:t,strict:s}){let g={array:s?j:k,arrayBuffer:F,asyncGenerator:ae,blob:L,dataView:B,date:H,error:ae,generator:ae,map:s?ee:q,object:s?Y:J,regExp:ne,set:s?se:oe},S=t?Object.assign(g,t):g,w=de(S),E=e||ce;if(!w.Object||!w.Array)throw Error(`An object and array copier must be provided.`);return{createCache:E,copiers:w,methods:S,strict:!!s}}function de(e){return{Arguments:e.object,Array:e.array,ArrayBuffer:e.arrayBuffer,AsyncGenerator:e.asyncGenerator,Blob:e.blob,Boolean:te,DataView:e.dataView,Date:e.date,Error:e.error,Float32Array:e.arrayBuffer,Float64Array:e.arrayBuffer,Generator:e.generator,Int8Array:e.arrayBuffer,Int16Array:e.arrayBuffer,Int32Array:e.arrayBuffer,Map:e.map,Number:te,Object:e.object,Promise:ae,RegExp:e.regExp,Set:e.set,String:te,WeakMap:ae,WeakSet:ae,Uint8Array:e.arrayBuffer,Uint8ClampedArray:e.arrayBuffer,Uint16Array:e.arrayBuffer,Uint32Array:e.arrayBuffer,Uint64Array:e.arrayBuffer}}function fe(e={}){let{createCache:t,copiers:s}=ue(e),{Array:g,Object:w}=s;function E(e,t){if(t.prototype=t.Constructor=void 0,!e||typeof e!=`object`)return e;if(t.cache.has(e))return t.cache.get(e);if(t.prototype=Object.getPrototypeOf(e),t.Constructor=t.prototype&&t.prototype.constructor,!t.Constructor||t.Constructor===Object)return w(e,t);if(Array.isArray(e))return g(e,t);let E=s[S(e)];return E?E(e,t):typeof e.then==`function`?e:w(e,t)}return function(e){return E(e,{Constructor:void 0,cache:t(),copier:E,prototype:void 0})}}let me=fe({strict:!0});e.copy=fe(),e.copyStrict=me,e.createCopier=fe})),require_filter_log=__commonJSMin(((e,t)=>{t.exports=w;let{createCopier:s}=require_cjs(),g=s({}),S=require_delete_log_property();function w({log:e,context:t}){let{ignoreKeys:s,includeKeys:w}=t,E=g(e);if(w){let e={};return w.forEach(t=>{e[t]=E[t]}),e}return s.forEach(e=>{S(E,e)}),E}})),require_dateformat=__commonJSMin(((e,t)=>{function s(e){"@babel/helpers - typeof";return s=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},s(e)}(function(g){var S=arguments,w=function(){var e=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,t=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,s=/[^-+\dA-Z]/g;return function(g,F,L,B){if(S.length===1&&j(g)===`string`&&!/\d/.test(g)&&(F=g,g=void 0),g=g||g===0?g:new Date,g instanceof Date||(g=new Date(g)),isNaN(g))throw TypeError(`Invalid date`);F=String(w.masks[F]||F||w.masks.default);var H=F.slice(0,4);(H===`UTC:`||H===`GMT:`)&&(F=F.slice(4),L=!0,H===`GMT:`&&(B=!0));var q=function(){return L?`getUTC`:`get`},ee=function(){return g[q()+`Date`]()},J=function(){return g[q()+`Day`]()},Y=function(){return g[q()+`Month`]()},te=function(){return g[q()+`FullYear`]()},ne=function(){return g[q()+`Hours`]()},ae=function(){return g[q()+`Minutes`]()},oe=function(){return g[q()+`Seconds`]()},se=function(){return g[q()+`Milliseconds`]()},ce=function(){return L?0:g.getTimezoneOffset()},ue=function(){return O(g)},de=function(){return k(g)},fe={d:function(){return ee()},dd:function(){return E(ee())},ddd:function(){return w.i18n.dayNames[J()]},DDD:function(){return D({y:te(),m:Y(),d:ee(),_:q(),dayName:w.i18n.dayNames[J()],short:!0})},dddd:function(){return w.i18n.dayNames[J()+7]},DDDD:function(){return D({y:te(),m:Y(),d:ee(),_:q(),dayName:w.i18n.dayNames[J()+7]})},m:function(){return Y()+1},mm:function(){return E(Y()+1)},mmm:function(){return w.i18n.monthNames[Y()]},mmmm:function(){return w.i18n.monthNames[Y()+12]},yy:function(){return String(te()).slice(2)},yyyy:function(){return E(te(),4)},h:function(){return ne()%12||12},hh:function(){return E(ne()%12||12)},H:function(){return ne()},HH:function(){return E(ne())},M:function(){return ae()},MM:function(){return E(ae())},s:function(){return oe()},ss:function(){return E(oe())},l:function(){return E(se(),3)},L:function(){return E(Math.floor(se()/10))},t:function(){return ne()<12?w.i18n.timeNames[0]:w.i18n.timeNames[1]},tt:function(){return ne()<12?w.i18n.timeNames[2]:w.i18n.timeNames[3]},T:function(){return ne()<12?w.i18n.timeNames[4]:w.i18n.timeNames[5]},TT:function(){return ne()<12?w.i18n.timeNames[6]:w.i18n.timeNames[7]},Z:function(){return B?`GMT`:L?`UTC`:(String(g).match(t)||[``]).pop().replace(s,``).replace(/GMT\+0000/g,`UTC`)},o:function(){return(ce()>0?`-`:`+`)+E(Math.floor(Math.abs(ce())/60)*100+Math.abs(ce())%60,4)},p:function(){return(ce()>0?`-`:`+`)+E(Math.floor(Math.abs(ce())/60),2)+`:`+E(Math.floor(Math.abs(ce())%60),2)},S:function(){return[`th`,`st`,`nd`,`rd`][ee()%10>3?0:(ee()%100-ee()%10!=10)*ee()%10]},W:function(){return ue()},WW:function(){return E(ue())},N:function(){return de()}};return F.replace(e,function(e){return e in fe?fe[e]():e.slice(1,e.length-1)})}}();w.masks={default:`ddd mmm dd yyyy HH:MM:ss`,shortDate:`m/d/yy`,paddedShortDate:`mm/dd/yyyy`,mediumDate:`mmm d, yyyy`,longDate:`mmmm d, yyyy`,fullDate:`dddd, mmmm d, yyyy`,shortTime:`h:MM TT`,mediumTime:`h:MM:ss TT`,longTime:`h:MM:ss TT Z`,isoDate:`yyyy-mm-dd`,isoTime:`HH:MM:ss`,isoDateTime:`yyyy-mm-dd'T'HH:MM:sso`,isoUtcDateTime:`UTC:yyyy-mm-dd'T'HH:MM:ss'Z'`,expiresHeaderFormat:`ddd, dd mmm yyyy HH:MM:ss Z`},w.i18n={dayNames:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],monthNames:[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`,`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],timeNames:[`a`,`p`,`am`,`pm`,`A`,`P`,`AM`,`PM`]};var E=function(e,t){for(e=String(e),t||=2;e.length<t;)e=`0`+e;return e},D=function(e){var t=e.y,s=e.m,g=e.d,S=e._,w=e.dayName,E=e.short,D=E===void 0?!1:E,O=new Date,k=new Date;k.setDate(k[S+`Date`]()-1);var j=new Date;return j.setDate(j[S+`Date`]()+1),function(){return O[S+`FullYear`]()}()===t&&function(){return O[S+`Month`]()}()===s&&function(){return O[S+`Date`]()}()===g?D?`Tdy`:`Today`:function(){return k[S+`FullYear`]()}()===t&&function(){return k[S+`Month`]()}()===s&&function(){return k[S+`Date`]()}()===g?D?`Ysd`:`Yesterday`:function(){return j[S+`FullYear`]()}()===t&&function(){return j[S+`Month`]()}()===s&&function(){return j[S+`Date`]()}()===g?D?`Tmw`:`Tomorrow`:w},O=function(e){var t=new Date(e.getFullYear(),e.getMonth(),e.getDate());t.setDate(t.getDate()-(t.getDay()+6)%7+3);var s=new Date(t.getFullYear(),0,4);s.setDate(s.getDate()-(s.getDay()+6)%7+3);var g=t.getTimezoneOffset()-s.getTimezoneOffset();t.setHours(t.getHours()-g);var S=(t-s)/(864e5*7);return 1+Math.floor(S)},k=function(e){var t=e.getDay();return t===0&&(t=7),t},j=function(e){return e===null?`null`:e===void 0?`undefined`:s(e)===`object`?Array.isArray(e)?`array`:{}.toString.call(e).slice(8,-1).toLowerCase():s(e)};typeof define==`function`&&define.amd?define(function(){return w}):(e===void 0?`undefined`:s(e))===`object`?t.exports=w:g.dateFormat=w})(void 0)})),require_format_time=__commonJSMin(((e,t)=>{t.exports=D;let{DATE_FORMAT:s,DATE_FORMAT_SIMPLE:g}=require_constants(),S=require_dateformat(),w=require_create_date(),E=require_is_valid_date();function D(e,t=!1){if(t===!1)return e;let D=w(e);if(!E(D))return e;if(t===!0)return S(D,g);let O=t.toUpperCase();if(O===`SYS:STANDARD`)return S(D,s);let k=O.substr(0,4);return k===`SYS:`||k===`UTC:`?k===`UTC:`?S(D,t):S(D,t.slice(4)):S(D,`UTC:${t}`)}})),require_handle_custom_levels_names_opts=__commonJSMin(((e,t)=>{t.exports=s;function s(e){return e?typeof e==`string`?e.split(`,`).reduce((e,t,s)=>{let[g,S=s]=t.split(`:`);return e[g.toLowerCase()]=S,e},{}):Object.prototype.toString.call(e)===`[object Object]`?Object.keys(e).reduce((t,s)=>(t[s.toLowerCase()]=e[s],t),{}):{}:{}}})),require_handle_custom_levels_opts=__commonJSMin(((e,t)=>{t.exports=s;function s(e){return e?typeof e==`string`?e.split(`,`).reduce((e,t,s)=>{let[g,S=s]=t.split(`:`);return e[S]=g.toUpperCase(),e},{default:`USERLVL`}):Object.prototype.toString.call(e)===`[object Object]`?Object.keys(e).reduce((t,s)=>(t[e[s]]=s.toUpperCase(),t),{default:`USERLVL`}):{}:{}}})),require_interpret_conditionals=__commonJSMin(((e,t)=>{t.exports=g;let s=require_get_property_value();function g(e,t){return e=e.replace(/{if (.*?)}(.*?){end}/g,g),e=e.replace(/{if (.*?)}/g,``),e=e.replace(/{end}/g,``),e.replace(/\s+/g,` `).trim();function g(e,g,S){let w=s(t,g);return w&&S.includes(g)?S.replace(RegExp(`{`+g+`}`,`g`),w):``}}})),require_is_object=__commonJSMin(((e,t)=>{t.exports=s;function s(e){return Object.prototype.toString.apply(e)===`[object Object]`}})),require_join_lines_with_indentation=__commonJSMin(((e,t)=>{t.exports=s;function s({input:e,ident:t=` `,eol:s=`
|
|
767
767
|
`}){let g=e.split(/\r?\n/);for(let e=1;e<g.length;e+=1)g[e]=t+g[e];return g.join(s)}})),require_parse_factory_options=__commonJSMin(((e,t)=>{t.exports=D;let{LEVEL_NAMES:s}=require_constants(),g=require_colors(),S=require_handle_custom_levels_opts(),w=require_handle_custom_levels_names_opts(),E=require_get_level_label_data();function D(e){let t=e.crlf?`\r
|
|
768
768
|
`:`
|
|
769
769
|
`,D=` `,{customPrettifiers:O,errorLikeObjectKeys:k,hideObject:j,levelFirst:F,levelKey:L,levelLabel:B,messageFormat:H,messageKey:q,minimumLevel:ee,singleLine:J,timestampKey:Y,translateTime:te}=e,ne=e.errorProps.split(`,`),ae=typeof e.useOnlyCustomProps==`boolean`?e.useOnlyCustomProps:e.useOnlyCustomProps===`true`,oe=S(e.customLevels),se=w(e.customLevels),ce=E(ae,oe,se),ue;if(e.customColors)if(typeof e.customColors==`string`)ue=e.customColors.split(`,`).reduce((t,g)=>{let[S,w]=g.split(`:`),E=(ae?e.customLevels:se[S]!==void 0)?se[S]:s[S],D=E===void 0?S:E;return t.push([D,w]),t},[]);else if(typeof e.customColors==`object`)ue=Object.keys(e.customColors).reduce((t,g)=>{let[S,w]=[g,e.customColors[g]],E=(ae?e.customLevels:se[S]!==void 0)?se[S]:s[S],D=E===void 0?S:E;return t.push([D,w]),t},[]);else throw Error(`options.customColors must be of type string or object.`);let de={customLevels:oe,customLevelNames:se};ae===!0&&!e.customLevels&&(de.customLevels=void 0,de.customLevelNames=void 0);let fe=e.include===void 0?void 0:new Set(e.include.split(`,`)),me=!fe&&e.ignore?new Set(e.ignore.split(`,`)):void 0,ge=g(e.colorize,ue,ae),_e=e.colorizeObjects?ge:g(!1,[],!1);return{EOL:t,IDENT:` `,colorizer:ge,customColors:ue,customLevelNames:se,customLevels:oe,customPrettifiers:O,customProperties:de,errorLikeObjectKeys:k,errorProps:ne,getLevelLabelData:ce,hideObject:j,ignoreKeys:me,includeKeys:fe,levelFirst:F,levelKey:L,levelLabel:B,messageFormat:H,messageKey:q,minimumLevel:ee,objectColorizer:_e,singleLine:J,timestampKey:Y,translateTime:te,useOnlyCustomProps:ae}}})),require_fast_safe_stringify=__commonJSMin(((e,t)=>{t.exports=D,D.default=D,D.stable=F,D.stableStringify=F;var s=`[...]`,g=`[Circular]`,S=[],w=[];function E(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function D(e,t,s,g){g===void 0&&(g=E()),k(e,``,0,[],void 0,0,g);var D;try{D=w.length===0?JSON.stringify(e,t,s):JSON.stringify(e,B(t),s)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;S.length!==0;){var O=S.pop();O.length===4?Object.defineProperty(O[0],O[1],O[3]):O[0][O[1]]=O[2]}}return D}function O(e,t,s,g){var E=Object.getOwnPropertyDescriptor(g,s);E.get===void 0?(g[s]=e,S.push([g,s,t])):E.configurable?(Object.defineProperty(g,s,{value:e}),S.push([g,s,t,E])):w.push([t,s,e])}function k(e,t,S,w,E,D,j){D+=1;var F;if(typeof e==`object`&&e){for(F=0;F<w.length;F++)if(w[F]===e){O(g,e,t,E);return}if(j.depthLimit!==void 0&&D>j.depthLimit){O(s,e,t,E);return}if(j.edgesLimit!==void 0&&S+1>j.edgesLimit){O(s,e,t,E);return}if(w.push(e),Array.isArray(e))for(F=0;F<e.length;F++)k(e[F],F,F,w,e,D,j);else{var L=Object.keys(e);for(F=0;F<L.length;F++){var B=L[F];k(e[B],B,F,w,e,D,j)}}w.pop()}}function j(e,t){return e<t?-1:e>t?1:0}function F(e,t,s,g){g===void 0&&(g=E());var D=L(e,``,0,[],void 0,0,g)||e,O;try{O=w.length===0?JSON.stringify(D,t,s):JSON.stringify(D,B(t),s)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;S.length!==0;){var k=S.pop();k.length===4?Object.defineProperty(k[0],k[1],k[3]):k[0][k[1]]=k[2]}}return O}function L(e,t,w,E,D,k,F){k+=1;var B;if(typeof e==`object`&&e){for(B=0;B<E.length;B++)if(E[B]===e){O(g,e,t,D);return}try{if(typeof e.toJSON==`function`)return}catch{return}if(F.depthLimit!==void 0&&k>F.depthLimit){O(s,e,t,D);return}if(F.edgesLimit!==void 0&&w+1>F.edgesLimit){O(s,e,t,D);return}if(E.push(e),Array.isArray(e))for(B=0;B<e.length;B++)L(e[B],B,B,E,e,k,F);else{var H={},q=Object.keys(e).sort(j);for(B=0;B<q.length;B++){var ee=q[B];L(e[ee],ee,B,E,e,k,F),H[ee]=e[ee]}if(D!==void 0)S.push([D,t,e]),D[t]=H;else return H}E.pop()}}function B(e){return e=e===void 0?function(e,t){return t}:e,function(t,s){if(w.length>0)for(var g=0;g<w.length;g++){var S=w[g];if(S[1]===t&&S[0]===s){s=S[2],w.splice(g,1);break}}return e.call(this,t,s)}}})),require_prettify_error=__commonJSMin(((e,t)=>{t.exports=g;let s=require_join_lines_with_indentation();function g({keyName:e,lines:t,eol:g,ident:S}){let w=``,E=`${S}${e}: ${s({input:t,ident:S,eol:g})}${g}`.split(g);for(let e=0;e<E.length;e+=1){e!==0&&(w+=g);let t=E[e];if(/^\s*"stack"/.test(t)){let e=/^(\s*"stack":)\s*(".*"),?$/.exec(t);if(e&&e.length===3){let s=/^\s*/.exec(t)[0].length+4,S=` `.repeat(s),E=e[2];w+=e[1]+g+S+JSON.parse(E).replace(/\n/g,g+S)}else w+=t}else w+=t}return w}})),require_prettify_object=__commonJSMin(((e,t)=>{t.exports=E;let{LOGGER_KEYS:s}=require_constants(),g=require_fast_safe_stringify(),S=require_join_lines_with_indentation(),w=require_prettify_error();function E({log:e,excludeLoggerKeys:t=!0,skipKeys:E=[],context:D}){let{EOL:O,IDENT:k,customPrettifiers:j,errorLikeObjectKeys:F,objectColorizer:L,singleLine:B,colorizer:H}=D,q=[].concat(E);t===!0&&Array.prototype.push.apply(q,s);let ee=``,{plain:J,errors:Y}=Object.entries(e).reduce(({plain:t,errors:s},[g,S])=>{if(q.includes(g)===!1){let w=typeof j[g]==`function`?j[g](S,g,e,{colors:H.colors}):S;F.includes(g)?s[g]=w:t[g]=w}return{plain:t,errors:s}},{plain:{},errors:{}});return B?(Object.keys(J).length>0&&(ee+=L.greyMessage(g(J))),ee+=O,ee=ee.replace(/\\\\/gi,`\\`)):Object.entries(J).forEach(([e,t])=>{let s=typeof j[e]==`function`?t:g(t,null,2);if(s===void 0)return;s=s.replace(/\\\\/gi,`\\`);let w=S({input:s,ident:k,eol:O});ee+=`${k}${L.property(e)}:${w.startsWith(O)?``:` `}${w}${O}`}),Object.entries(Y).forEach(([e,t])=>{let s=typeof j[e]==`function`?t:g(t,null,2);s!==void 0&&(ee+=w({keyName:e,lines:s,eol:O,ident:k}))}),ee}})),require_prettify_error_log=__commonJSMin(((e,t)=>{t.exports=E;let{LOGGER_KEYS:s}=require_constants(),g=require_is_object(),S=require_join_lines_with_indentation(),w=require_prettify_object();function E({log:e,context:t}){let{EOL:E,IDENT:D,errorProps:O,messageKey:k}=t,j=e.stack,F=`${D}${S({input:j,ident:D,eol:E})}${E}`;if(O.length>0){let S=s.concat(k,`type`,`stack`),j;j=O[0]===`*`?Object.keys(e).filter(e=>S.includes(e)===!1):O.filter(e=>S.includes(e)===!1);for(let s=0;s<j.length;s+=1){let S=j[s];if(S in e){if(g(e[S])){let s=w({log:e[S],excludeLoggerKeys:!1,context:{...t,IDENT:D+D}});F=`${F}${D}${S}: {${E}${s}${D}}${E}`;continue}F=`${F}${D}${S}: ${e[S]}${E}`}}}return F}})),require_prettify_level=__commonJSMin(((e,t)=>{t.exports=g;let s=require_get_property_value();function g({log:e,context:t}){let{colorizer:g,customLevels:S,customLevelNames:w,levelKey:E,getLevelLabelData:D}=t,O=t.customPrettifiers?.level,k=s(e,E);if(k===void 0)return;let j=g(k,{customLevels:S,customLevelNames:w});if(O){let[t]=D(k);return O(k,E,e,{label:t,labelColorized:j,colors:g.colors})}return j}})),require_prettify_message=__commonJSMin(((e,t)=>{t.exports=w;let{LEVELS:s}=require_constants(),g=require_get_property_value(),S=require_interpret_conditionals();function w({log:e,context:t}){let{colorizer:w,customLevels:E,levelKey:D,levelLabel:O,messageFormat:k,messageKey:j,useOnlyCustomProps:F}=t;if(k&&typeof k==`string`){let t=S(k,e),j=String(t).replace(/{([^{}]+)}/g,function(t,S){let w;if(S===O&&(w=g(e,D))!==void 0)return(F?E===void 0:E[w]===void 0)?s[w]:E[w];let k=g(e,S);return k===void 0?``:k});return w.message(j)}if(k&&typeof k==`function`){let t=k(e,j,O,{colors:w.colors});return w.message(t)}if(j in e&&!(typeof e[j]!=`string`&&typeof e[j]!=`number`&&typeof e[j]!=`boolean`))return w.message(e[j])}})),require_prettify_metadata=__commonJSMin(((e,t)=>{t.exports=s;function s({log:e,context:t}){let{customPrettifiers:s,colorizer:g}=t,S=``;if(e.name||e.pid||e.hostname){if(S+=`(`,e.name&&(S+=s.name?s.name(e.name,`name`,e,{colors:g.colors}):e.name),e.pid){let t=s.pid?s.pid(e.pid,`pid`,e,{colors:g.colors}):e.pid;e.name&&e.pid?S+=`/`+t:S+=t}if(e.hostname){let t=s.hostname?s.hostname(e.hostname,`hostname`,e,{colors:g.colors}):e.hostname;S+=`${S===`(`?`on`:` on`} ${t}`}S+=`)`}if(e.caller){let t=s.caller?s.caller(e.caller,`caller`,e,{colors:g.colors}):e.caller;S+=`${S===``?``:` `}<${t}>`}if(S!==``)return S}})),require_prettify_time=__commonJSMin(((e,t)=>{t.exports=g;let s=require_format_time();function g({log:e,context:t}){let{timestampKey:g,translateTime:S}=t,w=t.customPrettifiers?.time,E=null;if(g in e?E=e[g]:`timestamp`in e&&(E=e.timestamp),E===null)return;let D=S?s(E,S):E;return w?w(D):`[${D}]`}})),require_utils=__commonJSMin(((e,t)=>{t.exports={buildSafeSonicBoom:require_build_safe_sonic_boom(),createDate:require_create_date(),deleteLogProperty:require_delete_log_property(),filterLog:require_filter_log(),formatTime:require_format_time(),getPropertyValue:require_get_property_value(),handleCustomLevelsNamesOpts:require_handle_custom_levels_names_opts(),handleCustomLevelsOpts:require_handle_custom_levels_opts(),interpretConditionals:require_interpret_conditionals(),isObject:require_is_object(),isValidDate:require_is_valid_date(),joinLinesWithIndentation:require_join_lines_with_indentation(),noop:require_noop(),parseFactoryOptions:require_parse_factory_options(),prettifyErrorLog:require_prettify_error_log(),prettifyError:require_prettify_error(),prettifyLevel:require_prettify_level(),prettifyMessage:require_prettify_message(),prettifyMetadata:require_prettify_metadata(),prettifyObject:require_prettify_object(),prettifyTime:require_prettify_time(),splitPropertyKey:require_split_property_key(),getLevelLabelData:require_get_level_label_data()}})),require_secure_json_parse=__commonJSMin(((e,t)=>{let s=typeof Buffer<`u`,g=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,S=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function w(e,t,w){w==null&&typeof t==`object`&&t&&(w=t,t=void 0),s&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let D=JSON.parse(e,t);if(typeof D!=`object`||!D)return D;let O=w&&w.protoAction||`error`,k=w&&w.constructorAction||`error`;if(O===`ignore`&&k===`ignore`)return D;if(O!==`ignore`&&k!==`ignore`){if(g.test(e)===!1&&S.test(e)===!1)return D}else if(O!==`ignore`&&k===`ignore`){if(g.test(e)===!1)return D}else if(S.test(e)===!1)return D;return E(D,{protoAction:O,constructorAction:k,safe:w&&w.safe})}function E(e,{protoAction:t=`error`,constructorAction:s=`error`,safe:g}={}){let S=[e];for(;S.length;){let e=S;S=[];for(let w of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(w,`__proto__`)){if(g===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete w.__proto__}if(s!==`ignore`&&Object.prototype.hasOwnProperty.call(w,`constructor`)&&w.constructor!==null&&typeof w.constructor==`object`&&Object.prototype.hasOwnProperty.call(w.constructor,`prototype`)){if(g===!0)return null;if(s===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete w.constructor}for(let e in w){let t=w[e];t&&typeof t==`object`&&S.push(t)}}}return e}function D(e,t,s){let{stackTraceLimit:g}=Error;Error.stackTraceLimit=0;try{return w(e,t,s)}finally{Error.stackTraceLimit=g}}function O(e,t){let{stackTraceLimit:s}=Error;Error.stackTraceLimit=0;try{return w(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=s}}t.exports=D,t.exports.default=D,t.exports.parse=D,t.exports.safeParse=O,t.exports.scan=E})),require_pretty=__commonJSMin(((e,t)=>{t.exports=q;let s=require_secure_json_parse(),g=require_is_object(),S=require_prettify_error_log(),w=require_prettify_level(),E=require_prettify_message(),D=require_prettify_metadata(),O=require_prettify_object(),k=require_prettify_time(),j=require_filter_log(),{LEVELS:F,LEVEL_KEY:L,LEVEL_NAMES:B}=require_constants(),H=e=>{try{return{value:s.parse(e,{protoAction:`remove`})}}catch(e){return{err:e}}};function q(e){let t;if(g(e))t=e;else{let s=H(e);if(s.err||!g(s.value))return e+this.EOL;t=s.value}if(this.minimumLevel){let e;e=this.useOnlyCustomProps?this.customLevels:this.customLevelNames[this.minimumLevel]!==void 0;let s;if(s=e?this.customLevelNames[this.minimumLevel]:B[this.minimumLevel],s||=typeof this.minimumLevel==`string`?B[this.minimumLevel]:B[F[this.minimumLevel].toLowerCase()],t[this.levelKey===void 0?L:this.levelKey]<s)return}let s=E({log:t,context:this.context});(this.ignoreKeys||this.includeKeys)&&(t=j({log:t,context:this.context}));let q=w({log:t,context:{...this.context,...this.context.customProperties}}),ee=D({log:t,context:this.context}),J=k({log:t,context:this.context}),Y=``;if(this.levelFirst&&q&&(Y=`${q}`),J&&Y===``?Y=`${J}`:J&&(Y=`${Y} ${J}`),!this.levelFirst&&q&&(Y=Y.length>0?`${Y} ${q}`:q),ee&&(Y=Y.length>0?`${Y} ${ee}:`:ee),Y.endsWith(`:`)===!1&&Y!==``&&(Y+=`:`),s!==void 0&&(Y=Y.length>0?`${Y} ${s}`:s),Y.length>0&&!this.singleLine&&(Y+=this.EOL),t.type===`Error`&&typeof t.stack==`string`){let e=S({log:t,context:this.context});this.singleLine&&(Y+=this.EOL),Y+=e}else if(this.hideObject===!1){let e=[this.messageKey,this.levelKey,this.timestampKey].map(e=>e.replaceAll(/\\/g,``)).filter(e=>typeof t[e]==`string`||typeof t[e]==`number`||typeof t[e]==`boolean`),s=O({log:t,skipKeys:e,context:this.context});this.singleLine&&!/^\s$/.test(s)&&(Y+=` `),Y+=s}return Y}})),require_pino_pretty=__commonJSMin(((e,t)=>{let{isColorSupported:s}=require_colorette(),g=require_pump(),{Transform:S}=__require(`node:stream`),w=require_pino_abstract_transport(),E=require_colors(),{ERROR_LIKE_KEYS:D,LEVEL_KEY:O,LEVEL_LABEL:k,MESSAGE_KEY:j,TIMESTAMP_KEY:F}=require_constants(),{buildSafeSonicBoom:L,parseFactoryOptions:B}=require_utils(),H=require_pretty(),q={colorize:s,colorizeObjects:!0,crlf:!1,customColors:null,customLevels:null,customPrettifiers:{},errorLikeObjectKeys:D,errorProps:``,hideObject:!1,ignore:`hostname`,include:void 0,levelFirst:!1,levelKey:O,levelLabel:k,messageFormat:null,messageKey:j,minimumLevel:void 0,outputStream:process.stdout,singleLine:!1,timestampKey:F,translateTime:!0,useOnlyCustomProps:!0};function ee(e){let t=B(Object.assign({},q,e));return H.bind({...t,context:t})}function J(e={}){let t=ee(e),s;return w(function(w){w.on(`message`,function s(g){!g||g.code!==`PINO_CONFIG`||(Object.assign(e,{messageKey:g.config.messageKey,errorLikeObjectKeys:Array.from(new Set([...e.errorLikeObjectKeys||D,g.config.errorKey])),customLevels:g.config.levels.values}),t=ee(e),w.off(`message`,s))});let E=new S({objectMode:!0,autoDestroy:!0,transform(e,s,g){g(null,t(e))}});return s=typeof e.destination==`object`&&typeof e.destination.write==`function`?e.destination:L({dest:e.destination||1,append:e.append,mkdir:e.mkdir,sync:e.sync}),w.on(`unknown`,function(e){s.write(e+`
|
|
@@ -1941,11 +1941,11 @@ Change history for this knowledge base, newest entry first. Add a dated entry (\
|
|
|
1941
1941
|
`).filter(Boolean);ce.push(...e)}catch{}if(ce.length===0&&se.length===0&&de.length===0)return EMPTY;let fe=[...se,...de],me=[];if(fe.length>0){let t=parseGitLogOutput(await oe.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,...fe)).map(e=>({...e,type:`checkpoint`}));if(ne&&(t=await filterEntriesByChain(e,t,O,S,ee,ae,Y)),ue&&se.length>0&&de.length>0){let e=new Set(se),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);me=[...s,...g.filter(e=>new Date(e.timestamp).getTime()<S)]}else me=t}let ge=[...ce];for(let e of fe)ge.push(e);let _e=[];if(ge.length>0&&(_e=parseGitLogOutput(await oe.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,`-n`,String(D),...ge,...ne?[`--`,ne]:[])),_e.length>=D&&(k=!0),J))for(let t=0;t<O.length-1;t++){let s=O[t];if(s.renameCommit!==null)try{let t=await buildSeeds(e,s.renameCommit,S,Y);if(t.length===0)continue;let g=ee(s.path),w=parseGitLogOutput(await logSeededReachable(e,[`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,`-n`,String(D)],t,g));w.length>=D&&(k=!0),_e=[..._e,...w]}catch(e){console.warn(`[timeline] predecessor walk failed for step ${t} (${s.path}); skipping:`,e)}}let ve=[...me,..._e],ye=new Set,Ce=[];for(let e of ve)ye.has(e.sha)||(ye.add(e.sha),Ce.push(e));let we=Ce;Ce.length>0&&O.length>0&&(we=filterEntriesByOkActorDocs(Ce,O,await Promise.all(O.map(async t=>{if(t.renameCommit===null)return null;let s=await buildSeeds(e,t.renameCommit,S,Y);return s.length===0?new Set:buildAncestorShaSet(e,s,S,ae)})))),we.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let Te=we;Te=Te.filter(e=>e.type!==`park`),H||(Te=Te.filter(e=>e.checkpoint?.kind!==`auto-consolidation`)),F.length>0&&(Te=Te.filter(e=>F.includes(e.type))),L.length>0&&(Te=Te.filter(e=>matchesAuthor(e,L))),B.length>0&&(Te=Te.filter(e=>!matchesAuthor(e,B)));let De=Te.length,je=Te.slice(E,E+w),Me=je.map(({rawBody:e,...t})=>t);return j(ge.length,Ce.length),{entries:Me,total:De,hasMore:k&&je.length>0||E+w<De}}catch(e){return console.warn(`[timeline] getDocumentHistory failed, returning empty result:`,e),j(0,0,!0),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(`
|
|
1942
1942
|
`).filter(Boolean);e.push(...s)}catch{}if(e.length===0)return EMPTY;let t=historyWalkCap(E,w),s=parseGitLogOutput(await j.raw(`log`,`--full-history`,`--author-date-order`,`--format=${GIT_LOG_FORMAT}`,`-n`,String(t),...e,`--`,k)),g=s.length>=t,D=O?`${O}/.ok/`:`.ok/`,F=new Set,L=[];for(let e of s){if(F.has(e.sha)||!isFolderArtifactSubject(e.message)||!e.contributors.some(e=>e.docs.some(e=>e.startsWith(D))))continue;F.add(e.sha);let{rawBody:t,...s}=e;L.push(s)}let B=L.length,H=L.slice(E,E+w);return{entries:H,total:B,hasMore:g&&H.length>0||E+w<B}}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}let _searchCorpusTruncatedCounter=null;function searchCorpusTruncatedCounter(){return _searchCorpusTruncatedCounter||=getMeter().createCounter(`ok.search.corpus_truncated_total`,{description:`Count of search-corpus rebuilds where the name-only file tier hit OK_SEARCH_MAX_ENTRIES and dropped deepest-tail paths. One increment per truncated build; non-truncated builds do not increment.`}),_searchCorpusTruncatedCounter}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$7=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=managedArtifactTimelinePaths(e);if(g.managed&&g.versioned)return{path:s?`${s}/${g.filePath}`:g.filePath};let S=getDocExtension(e);return{path:s?`${s}/${e}${S}`:`${e}${S}`}}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,L=!1,B=(e,t)=>{if(!w){if(w=!0,j)try{unlinkSync(j)}catch{}g(t instanceof UploadWriteError?t:new UploadWriteError(e,t))}},H=classifyUploadErrno;S.on(`field`,(e,t)=>{e===`parentDocName`&&(O=t),e===`placement`&&(k=t)}),S.on(`file`,(e,g,S)=>{L=!0,E=S.filename||`upload`,D=S.mimeType||``;let q;try{q=mintTempUploadPath(t)}catch(e){B(H(e),e),g.resume();return}j=q;let ee=new HashingPassThrough;pipeline(g,ee,createWriteStream(q)).then(()=>{w||(w=!0,s({filename:E,mimeType:D,parentDocName:O,placement:k,tempPath:q,sha:ee.digest(),byteLength:ee.byteLength()}))}).catch(e=>{F=e,B(H(e),e)})}),S.on(`error`,e=>{B(`urn:ok:error:malformed-upload`,e)}),S.on(`close`,()=>{w||F||L||(w=!0,s({filename:``,mimeType:``,parentDocName:O,placement:k,tempPath:``,sha:``,byteLength:0}))}),e.on(`close`,()=>{w||F||e.complete||B(`urn:ok:error:malformed-upload`,Error(`client disconnected`))}),e.pipe(S)})}function safeSubdir(e,t){let s=resolve(e,t);if(!isWithinDir(s,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}const DEFAULT_SEARCH_MAX_ENTRIES=5e4;function getSearchMaxEntries(){let e=process.env.OK_SEARCH_MAX_ENTRIES;if(e===void 0)return DEFAULT_SEARCH_MAX_ENTRIES;let t=Number(e);return Number.isInteger(t)&&t>0?t:DEFAULT_SEARCH_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,maxEntries:S,signal:w}=e,E=e.maxDepth??1/0;showAllWalkInvocations+=1;let D=0,O=!1,k=!1,j=e=>g?e===g||e.startsWith(`${g}/`):!0,F;try{F=await realpath(t)}catch{F=t}let L=e=>isWithinDir(e,F),B=async(e,t,g)=>{let S=new Map;for(let t of e){if(!t.isFile()&&!t.isSymbolicLink()||!isSupportedDocFile(t.name))continue;let e=stripDocExtension(g?`${g}/${t.name}`:t.name);S.set(e,(S.get(e)??0)+1)}let w=new Set([...S].filter(([,e])=>e>1).map(([e])=>e));if(w.size===0)return new Map;let E=new Map;for(let S of e){if(!S.isFile()&&!S.isSymbolicLink()||!isSupportedDocFile(S.name))continue;let e=g?`${g}/${S.name}`:S.name,D=stripDocExtension(e);if(w.has(D)&&!s.isExcluded(e,{bypassFilters:!0})&&j(e)){if(S.isSymbolicLink()){let e=join(t,S.name),s;try{s=await realpath(e)}catch{continue}if(!L(s))continue;let g;try{g=await stat$1(s)}catch{continue}if(!g.isFile())continue}else try{await stat$1(join(t,S.name))}catch{continue}E.set(D,(E.get(D)??0)+1)}}return E},H=(e,t)=>{let s=stripDocExtension(e);return(t.get(s)??0)>1?e:s};async function q(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(!L(await realpath(join(e,S.name))))continue}catch(t){console.warn(`[document-list][showAll] probe realpath failed for ${e}/${S.name}:`,t);continue}return!0}if(S.isFile()&&!s.isExcluded(g,{bypassFilters:!0}))return!0}return!1}async function*ee(e,g,F){let ee=[{absDir:e,relDir:g,depth:F}];for(let e=0;e<ee.length;e++){if(w?.aborted){k=!0;return}let{absDir:g,relDir:F,depth:J}=ee[e],Y;try{Y=await readdir(g,{withFileTypes:!0})}catch(e){console.warn(`[document-list][showAll] readdir failed for ${g}:`,e);continue}let te=await B(Y,g,F);for(let e of Y){if(w?.aborted){k=!0;return}if(D>=S){O=!0;return}let B=F?`${F}/${e.name}`:e.name;if(e.isDirectory()){if(s.isDirExcluded(B,{bypassFilters:!0}))continue;let t=join(g,e.name),S;try{S=await realpath(t)}catch(e){console.warn(`[document-list][showAll] realpath failed for ${t}:`,e);continue}if(!L(S)){console.warn(`[document-list][showAll] refusing symlink-escape ${t} -> ${S}`);continue}if(j(B)){let e=null;try{e=await stat$1(t)}catch(e){console.warn(`[document-list][showAll] stat failed for ${t}:`,e)}D+=1;let s=J>=E?await q(t,B):void 0;yield{kind:`folder`,path:B,size:0,modified:e?e.mtime.toISOString():``,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null,...s===void 0?{}:{hasChildren:s}}}J<E&&ee.push({absDir:t,relDir:B,depth:J+1});continue}if(e.isSymbolicLink()){let S=join(g,e.name),w;try{w=await realpath(S)}catch(e){console.warn(`[document-list][showAll] symlink realpath failed for ${S}:`,e);continue}if(!L(w)){console.warn(`[document-list][showAll] refusing symlink-escape ${S} -> ${w}`);continue}let E;try{E=await stat$1(w)}catch(e){console.warn(`[document-list][showAll] symlink target stat failed for ${S}:`,e);continue}let O=toPosix(relative(t,w));if(E.isDirectory()){if(s.isDirExcluded(B,{bypassFilters:!0})||!j(B))continue;D+=1,yield{kind:`folder`,path:B,size:0,modified:E.mtime.toISOString(),docExt:`.md`,isSymlink:!0,canonicalDocName:O,targetPath:O,hasChildren:await q(w,B)};continue}if(!E.isFile()||s.isExcluded(B,{bypassFilters:!0})||!j(B))continue;if(D+=1,isSupportedDocFile(e.name))yield{kind:`document`,docName:H(B,te),docExt:extname(e.name),size:E.size,modified:E.mtime.toISOString(),isSymlink:!0,canonicalDocName:O.replace(/\.(md|mdx)$/i,``),targetPath:O};else{let t=synthesizeShowAllAssetExt(e.name);yield{kind:`asset`,docName:B,docExt:t,path:B,assetExt:t,mediaKind:mediaKindForSidebarAssetExtension(t),referencedBy:[],size:E.size,modified:E.mtime.toISOString(),isSymlink:!0,canonicalDocName:null,targetPath:O}}continue}if(!e.isFile()||s.isExcluded(B,{bypassFilters:!0})||!j(B))continue;let Y=null;try{Y=await stat$1(join(g,e.name))}catch(t){console.warn(`[document-list][showAll] stat failed for ${g}/${e.name}:`,t);continue}if(isSupportedDocFile(e.name)){let t=H(B,te),s=extname(e.name);D+=1,yield{kind:`document`,docName:t,docExt:s,size:Y.size,modified:Y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null};continue}let ne=synthesizeShowAllAssetExt(e.name),ae=mediaKindForSidebarAssetExtension(ne);D+=1,yield{kind:`asset`,docName:B,docExt:ne,path:B,assetExt:ne,mediaKind:ae,referencedBy:[],size:Y.size,modified:Y.mtime.toISOString(),isSymlink:!1,canonicalDocName:null,targetPath:null}}}}return yield*ee(g?join(t,g):t,g??``,1),k&&(showAllWalkAborts+=1),{truncated:O}}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`?docNameToRelativePath(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 isSupportedDocFile(t)?existsSync(resolve(e,t)):SUPPORTED_DOC_EXTENSIONS.some(s=>existsSync(resolve(e,`${t}${s}`)))}function hasSameStemDocumentSibling(e,t){if(!isSupportedDocFile(t))return!1;let s=stripDocExtension(t),g=extname(t).toLowerCase();return SUPPORTED_DOC_EXTENSIONS.some(t=>t.toLowerCase()===g?!1:existsSync(resolve(e,`${s}${t}`)))}function docNameForFileOperationPath(e,t){let s=stripDocExtension(t);return isSupportedDocFile(t)&&hasSameStemDocumentSibling(e,t)?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(t,s){for(let w of readdirSync(t,{withFileTypes:!0})){let E=resolve(t,w.name),D=s?`${s}/${w.name}`:w.name;if(w.isDirectory()){S(E,D);continue}!w.isFile()||!isSupportedDocFile(D)||g.push({docName:docNameForFileOperationPath(e,D),fullPath:E,content:readFileSync(E,`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);if(isSupportedDocFile(t)){let e=stripDocExtension(t);for(let t of SUPPORTED_DOC_EXTENSIONS){let g=resolve(s,`${e}${t}`);g!==s&&!g.startsWith(`${s}${sep}`)||existsSync(g)&®isterDocExtension(e,t)}let g=resolve(s,t);g!==s&&g.startsWith(`${s}${sep}`)&&existsSync(g)&®isterDocExtension(e,extname(t));return}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 writeFileIfContentDiffers(e,t){(existsSync(e)?readFileSync(e,`utf-8`):null)!==t&&tracedWriteFileSync(e,t,`utf-8`)}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{body:t}=stripFrontmatter(e),s=[],g=new Map,S=createCodeFenceTracker();for(let e of t.split(`
|
|
1943
1943
|
`)){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 applyDiskEventToLiveAllFilesIndex(e,t){let s=t();s instanceof Map&&updateFileIndex(e,s)}function createApiExtension(e){let{hocuspocus:t,sessionManager:s,contentDir:g,serverInstanceId:S,getFileIndex:w,getAttachmentFolderPath:E,getAllFilesIndex:D=w,mutateFileIndex:O=e=>applyDiskEventToLiveAllFilesIndex(e,D),getFileIndexGeneration:k,getFolderIndex:j,onReferencedAssetsCacheInvalidator:F,getAliasMap:L,getFolderAliasIndex:B,rescanFiles:H,enableTestRoutes:q=!1,shadowRef:ee,flushGitCommit:J,flushContributors:Y,takeStoreFailure:te,takeStoreDivergence:ne,markAgentWriteStore:ae,getCurrentBranch:oe,getDiskAckSVs:se,contentRoot:ce,backlinkIndex:ue,tagIndex:de,signalChannel:fe,agentFocusBroadcaster:me,agentPresenceBroadcaster:ge,onAgentWrite:_e,getSyncEngine:ve,localOpCliArgs:ye=[`open-knowledge`],projectDir:Ce,getPrincipal:we,homeDirOverride:Te,contentFilter:De,installedAgentsProbe:je,forceUnloadDocument:Me,ready:Pe,recentlyRemovedDocs:Ie,serializeDoc:Re,evictManagedArtifactLkg:ze,semanticSearch:Be,getSemanticSimilarityFloor:Ve,embeddingsSecretsFile:Ue,ephemeral:We=!1}=e,Ge=createConcurrencyGuard(),Ke=new Map,Xe=createSingleFlight(),$e=null;function nt(){let e=j?.();return e instanceof Map?e:null}function rt(e){let t=nt();if(t)try{upsertFolderIndexEntry(t,g,e,statSync(e),e)}catch(t){console.warn(`[api-extension] folder index stat failed for ${e}:`,t)}}function it(e){let t=e.split(`/`).filter(Boolean);for(let e=1;e<=t.length;e+=1)rt(resolve(g,t.slice(0,e).join(`/`)))}function at(e){let t=nt();t&&removeFolderIndexEntries(t,e)}function st(e,t){let s=nt();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)&&rt(e);return}for(let[e,t]of S)s.set(e,{...t,modified:new Date().toISOString(),canonicalPath:resolve(g,e)})}function vt(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
|
|
1944
|
-
`)}function Tt(){$e=null}F?.(Tt);let Et=createInstalledAgentsProbe({probe:je??createOsProbe(process.platform)});function Dt(e){if(isManagedArtifactDocName(e))try{return managedArtifactAbsPath(e,{projectDir:Ce??g,homedirOverride:Te})}catch{return null}if(!isSafeDocName(e))return null;let t=resolve(g),s=resolve(t,docNameToRelativePath(e));return isWithinDir(s,t)?s:null}function jt(e){let t=Dt(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Mt(e,t){return t.has(e)?jt(e):e}let Ft={cluster:void 0,category:void 0,tags:void 0};function It(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;if(Array.isArray(e.tags)){let t=e.tags.filter(e=>typeof e==`string`);g=t.length>0?t:void 0}else typeof e.tags==`string`&&e.tags&&(g=[e.tags]);return{cluster:t,category:s,tags:g}}}}catch{}try{let t=Dt(e);if(!t||!existsSync(t))return Ft;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):Ft}catch{return Ft}}function Lt(e,t){return t.has(e)?It(e):Ft}function Rt(e){if(ue)try{if(ue.getBacklinks(e).length>0)return;let t=performance.now(),s=findHubCandidates(e,w()),g=performance.now()-t;return g>5&&log$7.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 zt(e){return L?.().get(e)??e}function Bt(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function Vt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function Ht(e,s){let g=`onStoreDocument-${e}`;(t.debouncer.isDebounced(g)?t.debouncer.executeNow(g):Promise.resolve()).then(()=>J?.()).catch(e=>{log$7.warn({err:e},`[${s}] post-write flush failed`)})}async function Ut(e){let s=`onStoreDocument-${e}`;t.debouncer.isDebounced(s)&&(ae?.(e),await t.debouncer.executeNow(s));let g=te?.(e)??null;return g?{kind:`failure`,failure:g}:ne?.(e)?{kind:`divergence`}:null}function Wt(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 Kt(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 $t(e){if(e.reconciled)return{kind:`disk-edit-reconciled`,intendedBytes:e.baseBytes,actualBytes:e.diskBytes,byteDelta:e.diskBytes-e.baseBytes,...e.mergeOutcome?{mergeOutcome:e.mergeOutcome}:{},hint:e.mergeOutcome===`merged`?'An out-of-band edit was three-way merged into this document before your edit was applied on top; the merge may have interleaved content blocks. Re-read it (e.g. `exec("cat <path>")`) and review the combined result carefully before continuing.':'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 en(e){if(!De)return!1;let t=docNameToRelativePath(e);return De.isExcluded(t)}function jr(){let e=new Set;for(let[t,s]of w()){e.add(t);for(let t of s.aliases)e.add(t)}try{for(let t of[`project`,`global`]){let s=resolve(t===`global`?nu:g,`.ok`,`skills`);for(let g of lu(s,t).skills)e.add(`${MANAGED_ARTIFACT_PREFIX_SKILL}${t}/${g.name}`)}for(let t of resolveProjectTemplates(resolve(g)).templates)e.add(iu(t.source_folder,t.name))}catch(e){log$7.warn({err:e},`[collectAdmittedDocNames] managed-artifact enumeration failed`)}for(let t of ue?.getIndexedDocNames()??[])e.has(t)||en(t)||e.add(t);return e}let Mr=e=>existsSync(resolve(g,e));function Fr(e,t){en(e)||O?.({kind:w().has(e)?`update`:`create`,path:resolveContentEntryPath(g,`file`,e),docName:e,content:t})}function Ir(){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 Lr=Ir(),zr=e=>e.endsWith(`.`)?e:`${e}.`;function Br(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:zr(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:zr(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:zr(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:zr(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:zr(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:zr(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:zr(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 Vr(e,g){let S=new Map;for(let s of e){let e=t.documents.get(s);e&&S.set(s,e.getText(`source`).toString())}for(let s of e){let e=t.documents.get(s);e&&e.getMap(`lifecycle`).set(`status`,g)}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),ze?.(s),e&&(t.closeConnections(s),await(Me??t.unloadDocument.bind(t))(e))}return S}function Hr(e,t){for(let{fromDocName:s,toDocName:S}of e){let e=safeContentPath(S,g),w=t.get(s);typeof w==`string`&&writeFileIfContentDiffers(e,w);let E=typeof w==`string`?w:existsSync(e)?readFileSync(e,`utf-8`):null;typeof E==`string`&®isterWrite(e,contentHash(E))}}function Ur(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 Wr(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 Gr(e,t){let s=resolveContentEntryPath(g,`file`,e);tracedMkdirSync(dirname(s),{recursive:!0}),writeFileIfContentDiffers(s,t),registerWrite(s,contentHash(t)),setReconciledBase(e,t),O?.({kind:`update`,path:s,docName:e,content:t})}function Kr(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=Jr(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 qr(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 Jr(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=qr(w.markdown,s,S);return{markdown:E.markdown,rewrites:E.markdown===e?0:w.rewrites+E.rewrites}}function Yr(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=qr(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function Xr(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=Wr(g);if(typeof s!=`string`)continue;let S=qr(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function Zr(e){let s=ve?.(),g=new Set(s?s.getConflicts().map(e=>e.file):[]);for(let s of e){let e=t.documents.get(s),S=docNameToRelativePath(s),w=e!==void 0&&isDocInConflict(e),E=g.has(S);if(w||E)throw new DocInConflictError({file:S})}}function Qr(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?Yr(S.docName,s):S;e.rewrites!==0&&(Gr(S.docName,e.markdown),ue?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function ji(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 Hi(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(De?.isDirExcluded(E))continue;s(w);continue}if(!S.isFile()||!isSupportedDocFile(E)||De?.isExcluded(E))continue;let D=docNameForFileOperationPath(g,E);registerDocExtension(stripDocExtension(E),extname(E)),t.push(D)}}return s(e),t.sort((e,t)=>e.localeCompare(t)),t}function Ui(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(De?.isDirExcluded(O))continue;w(D);continue}!E.isFile()||isSupportedDocFile(O)||De?.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 Gi(e,t){return Lr(async()=>withSpan(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async s=>{if(!ue)throw new BacklinkIndexRequiredError;let S=extname(t)?t:`${t}${extname(e)}`;if(isReservedProjectStatePath(e)||isReservedProjectStatePath(S))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.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=Xr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),Zr(O.map(e=>e.docName)),await renameTrackedPathInGit(Ce,w,E)||renamePathOnDisk(w,E);let k=Qr(O,D);return ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist asset rename cache for ${e} -> ${S}:`,t)}),fe?.(`files`),k.length>0&&(fe?.(`backlinks`),fe?.(`graph`)),k.sort((e,t)=>e.docName.localeCompare(t.docName)),s.setAttribute(`rename.rewrite_count`,k.length),{renamedAssets:D,rewrittenDocs:k}}))}async function Ki(e,s){return Lr(async()=>withSpan(`rename.executeDocumentToFileRewrites`,{attributes:{"rename.kind":`asset`,"rename.transition":`document-to-file`}},async S=>{if(!ue)throw new BacklinkIndexRequiredError;if(!isSupportedDocFile(e)||isSupportedDocFile(s))throw new ManagedRenameInvalidRequestError(`Document-to-file rename requires a markdown source and non-markdown destination.`);let w=stripDocExtension(e);if(isSystemDoc(w)||isConfigDoc(w))throw new ManagedRenameReservedPathError(`Reserved document names cannot be renamed.`);if(isReservedProjectStatePath(e)||isReservedProjectStatePath(s))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(s))throw new ManagedRenameInvalidRequestError(`Destination file is excluded by the project content config.`);let E=resolveContentEntryPath(g,`folder`,e),D=resolveContentEntryPath(g,`folder`,s);if(E===D)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,s))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(E))throw new ManagedRenameSourceNotFoundError(`file`);if(existsSync(D))throw new ManagedRenameDestinationExistsError;if(!statSync(E).isFile())throw new ManagedRenameSourceTypeMismatchError(`file`,`Source path is not a document file.`);let k=ve?.(),j=new Set(k?k.getConflicts().map(e=>e.file):[]),F=t.documents.get(w);if(F!==void 0&&isDocInConflict(F)||j.has(e))throw new DocInConflictError({file:e});let L=[{fromPath:e,toPath:s}],B=Xr(L).filter(e=>e.docName!==w);S.setAttribute(`rename.rewrite_candidates`,B.length),Zr(B.map(e=>e.docName)),reconcileDiskBeforeAgentWrite(t,w,g),Ie&&!isSystemDoc(w)&&!isConfigDoc(w)&&Ie.setDeleted(w);let H=(await Vr([w],`renamed`)).get(w),q=typeof H==`string`?H:readFileSync(E,`utf-8`),ee=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[{from:w,to:w}],snapshots:[{docName:w,content:q}],cleanupPaths:[s]}),J=[];return await withManagedRenameRecovery(Ce??g,ee,async()=>{writeFileIfContentDiffers(E,q),registerWrite(E,contentHash(q)),await renameTrackedPathInGit(Ce,E,D)||renamePathOnDisk(E,D),ue.deleteDocument(w),forgetDocExtension(w),O?.({kind:`delete`,path:E,docName:w});let t=statSync(D);O?.({kind:`file-create`,path:D,relativePath:s,size:t.size,modifiedTs:t.mtimeMs,inode:t.ino}),J=Qr(B,L),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist document-to-file rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),J.length>0&&(fe?.(`backlinks`),fe?.(`graph`))}),J.sort((e,t)=>e.docName.localeCompare(t.docName)),S.setAttribute(`rename.rewrite_count`,J.length),{renamedAssets:L,rewrittenDocs:J}}))}async function Yi(e,s,S,E){return Lr(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":S}},async D=>{if(!ue)throw new BacklinkIndexRequiredError;let k=resolveContentEntryPath(g,S,e),j=resolveContentEntryPath(g,S,s);if(k===j)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!existsSync(k))throw new ManagedRenameSourceNotFoundError(S);if(existsSync(j)&&!isCaseOnlySelfCollision(k,j))throw new ManagedRenameDestinationExistsError;let F=statSync(k);if(S===`file`&&!F.isFile()||S===`folder`&&!F.isDirectory())throw new ManagedRenameSourceTypeMismatchError(S);let L=S===`folder`?Ui(k,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[docNameForFileOperationPath(g,e)]:Hi(k)).map(t=>({from:t,to:S===`file`?docNameForFileOperationPath(g,s):remapDocNameForRename(t,S,e,s)}));if(D.setAttribute(`rename.affected_docs`,B.length),B.length===0){let t=Xr(L);Zr(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(Ce,k,j)||renamePathOnDisk(k,j),st(e,s),fe?.(`files`)),g.push(...Qr(t,L)),g.length>0&&(ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`backlinks`),fe?.(`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})),J=new Set;for(let{from:e}of B)for(let t of ue.getBacklinks(e))H.has(t.source)||J.add(t.source);let Y=[...J].sort((e,t)=>e.localeCompare(t)),te=new Map,ne=new Set,ae=new Set,se=[];for(let e of[...H.keys(),...Y]){if(te.has(e))continue;if(!H.has(e)&&!existsSync(resolveContentEntryPath(g,`file`,e))){se.push(e);continue}reconcileDiskBeforeAgentWrite(t,e,g);let s=Wr(e);typeof s==`string`?(te.set(e,s),H.has(e)||ne.add(e)):H.has(e)||se.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)??Wr(t);typeof e==`string`&&Jr(e,t,H.get(t)??t,H,L).rewrites!==0&&(te.has(t)||te.set(t,e),ae.add(t),H.has(t)||ne.add(t))}}Zr(ae);for(let{from:e}of B)if(typeof te.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ce=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[...B],snapshots:Ur([...te.keys()],te)}),de=[],me=[...ne].sort((e,t)=>e.localeCompare(t));return await withManagedRenameRecovery(Ce??g,ce,async()=>{for(let e of se)ue.deleteDocument(e);for(let e of me){let s=t.documents.get(e)?Kr(e,H,L):Jr(te.get(e)??``,e,e,H,L);s.rewrites>0&&(Gr(e,s.markdown),de.push({docName:e,rewrites:s.rewrites})),ue.updateDocumentFromMarkdown(e,s.markdown)}if(Ie)for(let{from:e,to:t}of B)isSystemDoc(e)||isConfigDoc(e)||(Ie.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let w=resolveContentEntryPath(g,S,e),D=resolveContentEntryPath(g,S,s);await renameTrackedPathInGit(Ce,w,D)||renamePathOnDisk(w,D),S===`folder`&&st(e,s);let k=await Vr([...H.keys()],`renamed`);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(ee?.current){let e=ee.current,t=B.filter(({from:e,to:t})=>stripDocExtension(e)!==stripDocExtension(t));t.length>0&&withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":S}},s=>{let g=randomUUID(),w=new Date().toISOString(),D=oe?.()??`main`,O=getOrLoadRenameLogIndex(e.gitDir),k=E?.actor?{writerId:E.actor.writerId,displayName:E.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},j=0;for(let{from:s,to:F}of t){let t={v:1,from:s,to:F,at:w,commitSha:``,branch:D,groupId:g,kind:S,actor:k};appendRenameLogEntry(e.gitDir,t,O,e),j+=1,E?.actor?recordContributor(F,E.actor.writerId,E.actor.displayName,E.actor.colorSeed,formatRenameSubject(s,F),E.actor.actorMetadata,void 0,[{from:s,to:F}]):recordContributor(F,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(s,F),void 0,void 0,[{from:s,to:F}])}s.setAttribute(`rename.entries_appended`,j)})}let j=S===`file`&&isSupportedDocFile(s)?extname(s):null;for(let{from:e,to:t}of B){let s=isSupportedDocFile(e)?extname(e):getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,j??s)}let F=[...B].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of F){let s=resolveContentEntryPath(g,`file`,e),S=resolveContentEntryPath(g,`file`,t),w=Jr(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Hr([{fromDocName:e,toDocName:t}],new Map([[e,w.markdown]])),setReconciledBase(t,w.markdown),O?.({kind:`rename`,oldPath:s,newPath:S,oldDocName:e,newDocName:t,content:w.markdown}),ue.renameDocument(e,t,w.markdown),w.rewrites>0&&de.push({docName:t,rewrites:w.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`)}),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),fe?.(`backlinks`),fe?.(`graph`),de.sort((e,t)=>e.docName.localeCompare(t.docName)),D.setAttribute(`rename.rewrite_count`,de.length),{renamed:q,renamedAssets:L,rewrittenDocs:de}}))}function Xi(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 Zi(e){return{principalId:we?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function ka(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 _s(e){return{value:e.value}}function xs(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function Cs(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=ka(S),E=g||!w.response?w.response:_s(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(),xs(S,!g);for(let{docName:e}of s)Ht(e,`rename-path`);return E}case`principal`:{let t=ka(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)}xs(e.summary,!1);for(let{docName:e}of s)Ht(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 Ts(e,t,s){let g=t.replace(/\/$/,``),S=g===``?``:`${g}/`;return e===`template`?`${S}.ok/templates/${s}`:e===`skill`?`${S}.ok/skills/${s}`:e===`folder-frontmatter`?`${S}.ok/frontmatter`:g===``?`.`:g}function Ds(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=ka(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Os(e){if(Y)try{await Y()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let ks=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Xi(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}=ka(H);try{let t=iconFromClientName(F),s=AGENT_ICON_COLORS[t]??colorFromSeed(j??O);ge?.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,Zi({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),xs(H)}finally{ge?.touchMode(O,`idle`)}let ae=await Ut(D);if(ae?.kind===`failure`){Wt(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){Kt(w,`agent-write`);return}Ht(D,`agent-write`),_e?.();let oe=$t(ee);successResponse(w,200,AgentWriteSuccessSchema,{timestamp:J,...te?{summary:te}:{},...oe?{warning:oe,warnings:[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$7.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`}),As=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=zt(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=Xi(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}=ka(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);ge?.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,Zi({clientName:L,clientVersion:B,label:H}),J),incrementAgentWriteCalls(),xs(q)}finally{ge?.touchMode(k,`idle`)}let oe=await Ut(O);if(oe?.kind===`failure`){Wt(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){Kt(w,`agent-write-md`);return}Ht(O,`agent-write-md`),me?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),_e?.();let se=Rt(O),ce=Y.dc.document.getText(`source`).toString();Fr(O,ce);let ue=await validateMermaidFences(ce,O),de=jr();de.add(O);let fe=computeBrokenOutboundLinks(ce,O,de,Mr),ve=Bt(O),ye=Vt();ye===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let Ce=$t(te),we=ae===void 0?void 0:toContentDivergenceWarning(ae),Te=[...we?[we]:[],...Ce?[Ce]:[],...ue??[]];successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ne,subscriberCount:ve,systemSubscriberCount:ye,...se?{hints:se}:{},...ee?{summary:ee}:{},...we?{warning:we}:Ce?{warning:Ce}:{},...Te.length>0?{warnings:Te}:{},brokenLinks:fe},{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$7.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`}),Ns=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Xi(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}=ka(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,se=!1,ce=!1,ue=[];try{let e=iconFromClientName(F),t=AGENT_ICON_COLORS[e]??colorFromSeed(j??O);ge?.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))ue.push(e);if(s.nextFenced!==e){let g=e===``&&t!==``&&!t.startsWith(`
|
|
1944
|
+
`)}function St(){$e=null}F?.(St);let Tt=createInstalledAgentsProbe({probe:je??createOsProbe(process.platform)});function Et(e){if(isManagedArtifactDocName(e))try{return managedArtifactAbsPath(e,{projectDir:Ce??g,homedirOverride:Te})}catch{return null}if(!isSafeDocName(e))return null;let t=resolve(g),s=resolve(t,docNameToRelativePath(e));return isWithinDir(s,t)?s:null}function jt(e){let t=Et(e);if(!t||!existsSync(t))return e;try{return extractPageTitle(readFileSync(t,`utf-8`),e)}catch{return e}}function Mt(e,t){return t.has(e)?jt(e):e}let Ft={cluster:void 0,category:void 0,tags:void 0};function It(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;if(Array.isArray(e.tags)){let t=e.tags.filter(e=>typeof e==`string`);g=t.length>0?t:void 0}else typeof e.tags==`string`&&e.tags&&(g=[e.tags]);return{cluster:t,category:s,tags:g}}}}catch{}try{let t=Et(e);if(!t||!existsSync(t))return Ft;let{frontmatter:s}=stripFrontmatter(readFileSync(t,`utf-8`));return s?parseFrontmatterMetadata(s):Ft}catch{return Ft}}function Lt(e,t){return t.has(e)?It(e):Ft}function Rt(e){if(ue)try{if(ue.getBacklinks(e).length>0)return;let t=performance.now(),s=findHubCandidates(e,w()),g=performance.now()-t;return g>5&&log$7.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 zt(e){return L?.().get(e)??e}function Bt(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function Vt(){try{return t.documents.get(`__system__`)?.connections.size??0}catch{return 0}}function Ht(e,s){let g=`onStoreDocument-${e}`;(t.debouncer.isDebounced(g)?t.debouncer.executeNow(g):Promise.resolve()).then(()=>J?.()).catch(e=>{log$7.warn({err:e},`[${s}] post-write flush failed`)})}async function Ut(e){let s=`onStoreDocument-${e}`;t.debouncer.isDebounced(s)&&(ae?.(e),await t.debouncer.executeNow(s));let g=te?.(e)??null;return g?{kind:`failure`,failure:g}:ne?.(e)?{kind:`divergence`}:null}function Wt(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 Xt(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 Zt(e){if(e.reconciled)return{kind:`disk-edit-reconciled`,intendedBytes:e.baseBytes,actualBytes:e.diskBytes,byteDelta:e.diskBytes-e.baseBytes,...e.mergeOutcome?{mergeOutcome:e.mergeOutcome}:{},hint:e.mergeOutcome===`merged`?'An out-of-band edit was three-way merged into this document before your edit was applied on top; the merge may have interleaved content blocks. Re-read it (e.g. `exec("cat <path>")`) and review the combined result carefully before continuing.':'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 $t(e){if(!De)return!1;let t=docNameToRelativePath(e);return De.isExcluded(t)}function en(){let e=new Set;for(let[t,s]of w()){e.add(t);for(let t of s.aliases)e.add(t)}try{for(let t of[`project`,`global`]){let s=resolve(t===`global`?cu:g,`.ok`,`skills`);for(let g of hu(s,t).skills)e.add(`${MANAGED_ARTIFACT_PREFIX_SKILL}${t}/${g.name}`)}for(let t of resolveProjectTemplates(resolve(g)).templates)e.add(uu(t.source_folder,t.name))}catch(e){log$7.warn({err:e},`[collectAdmittedDocNames] managed-artifact enumeration failed`)}for(let t of ue?.getIndexedDocNames()??[])e.has(t)||$t(t)||e.add(t);return e}let tn=e=>existsSync(resolve(g,e));function rn(e,t){$t(e)||O?.({kind:w().has(e)?`update`:`create`,path:resolveContentEntryPath(g,`file`,e),docName:e,content:t})}function sn(){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 jr=sn(),Mr=e=>e.endsWith(`.`)?e:`${e}.`;function zr(e){return e instanceof Error?e instanceof ManagedRenameSourceNotFoundError?{status:404,type:`urn:ok:error:doc-not-found`,error:Mr(e.message)}:e instanceof ManagedRenameDestinationExistsError?{status:409,type:`urn:ok:error:doc-already-exists`,error:Mr(e.message)}:e instanceof ManagedRenameSourceTypeMismatchError||e instanceof ManagedRenameInvalidRequestError?{status:400,type:`urn:ok:error:invalid-request`,error:Mr(e.message)}:e instanceof ManagedRenameReservedPathError?{status:400,type:`urn:ok:error:reserved-doc-name`,error:Mr(e.message)}:e instanceof ManagedRenameMissingDocumentError||e instanceof ManagedRenameSnapshotMissingError?{status:404,type:`urn:ok:error:doc-not-found`,error:Mr(e.message)}:e instanceof SymlinkEscapeError?{status:400,type:`urn:ok:error:path-escape`,error:Mr(e.message)}:e instanceof BacklinkIndexRequiredError?{status:503,type:`urn:ok:error:backlink-index-not-configured`,error:Mr(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 Br(e,g){let S=new Map;for(let s of e){let e=t.documents.get(s);e&&S.set(s,e.getText(`source`).toString())}for(let s of e){let e=t.documents.get(s);e&&e.getMap(`lifecycle`).set(`status`,g)}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),ze?.(s),e&&(t.closeConnections(s),await(Me??t.unloadDocument.bind(t))(e))}return S}function Vr(e,t){for(let{fromDocName:s,toDocName:S}of e){let e=safeContentPath(S,g),w=t.get(s);typeof w==`string`&&writeFileIfContentDiffers(e,w);let E=typeof w==`string`?w:existsSync(e)?readFileSync(e,`utf-8`):null;typeof E==`string`&®isterWrite(e,contentHash(E))}}function Hr(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 Ur(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 Wr(e,t){let s=resolveContentEntryPath(g,`file`,e);tracedMkdirSync(dirname(s),{recursive:!0}),writeFileIfContentDiffers(s,t),registerWrite(s,contentHash(t)),setReconciledBase(e,t),O?.({kind:`update`,path:s,docName:e,content:t})}function Gr(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=qr(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 Kr(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 qr(e,t,s,g,S){let w=applyRenameMap(e,t,g),E=Kr(w.markdown,s,S);return{markdown:E.markdown,rewrites:E.markdown===e?0:w.rewrites+E.rewrites}}function Jr(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=Kr(g.getText(`source`).toString(),e,s),S.rewrites!==0&&composeAndWriteRawBody(g,S.markdown,`managed-rename`,!1)},MANAGED_RENAME_ORIGIN),S}function Yr(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=Ur(g);if(typeof s!=`string`)continue;let S=Kr(s,g,e);S.rewrites!==0&&t.push({docName:g,markdown:S.markdown,rewrites:S.rewrites})}return t}function Xr(e){let s=ve?.(),g=new Set(s?s.getConflicts().map(e=>e.file):[]);for(let s of e){let e=t.documents.get(s),S=docNameToRelativePath(s),w=e!==void 0&&isDocInConflict(e),E=g.has(S);if(w||E)throw new DocInConflictError({file:S})}}function Zr(e,s){let g=[];for(let S of e){let e=t.documents.get(S.docName)?Jr(S.docName,s):S;e.rewrites!==0&&(Wr(S.docName,e.markdown),ue?.updateDocumentFromMarkdown(S.docName,e.markdown),g.push({docName:S.docName,rewrites:e.rewrites}))}return g}function Qr(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 Gi(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(De?.isDirExcluded(E))continue;s(w);continue}if(!S.isFile()||!isSupportedDocFile(E)||De?.isExcluded(E))continue;let D=docNameForFileOperationPath(g,E);registerDocExtension(stripDocExtension(E),extname(E)),t.push(D)}}return s(e),t.sort((e,t)=>e.localeCompare(t)),t}function Ki(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(De?.isDirExcluded(O))continue;w(D);continue}!E.isFile()||isSupportedDocFile(O)||De?.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 Ji(e,t){return jr(async()=>withSpan(`rename.executeAssetRewrites`,{attributes:{"rename.kind":`asset`}},async s=>{if(!ue)throw new BacklinkIndexRequiredError;let S=extname(t)?t:`${t}${extname(e)}`;if(isReservedProjectStatePath(e)||isReservedProjectStatePath(S))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.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=Yr(D);s.setAttribute(`rename.rewrite_candidates`,O.length),Xr(O.map(e=>e.docName)),await renameTrackedPathInGit(Ce,w,E)||renamePathOnDisk(w,E);let k=Zr(O,D);return ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist asset rename cache for ${e} -> ${S}:`,t)}),fe?.(`files`),k.length>0&&(fe?.(`backlinks`),fe?.(`graph`)),k.sort((e,t)=>e.docName.localeCompare(t.docName)),s.setAttribute(`rename.rewrite_count`,k.length),{renamedAssets:D,rewrittenDocs:k}}))}async function Yi(e,s){return jr(async()=>withSpan(`rename.executeDocumentToFileRewrites`,{attributes:{"rename.kind":`asset`,"rename.transition":`document-to-file`}},async S=>{if(!ue)throw new BacklinkIndexRequiredError;if(!isSupportedDocFile(e)||isSupportedDocFile(s))throw new ManagedRenameInvalidRequestError(`Document-to-file rename requires a markdown source and non-markdown destination.`);let w=stripDocExtension(e);if(isSystemDoc(w)||isConfigDoc(w))throw new ManagedRenameReservedPathError(`Reserved document names cannot be renamed.`);if(isReservedProjectStatePath(e)||isReservedProjectStatePath(s))throw new ManagedRenameReservedPathError(`.ok and .git are reserved directories.`);if(De?.isPathIgnored(s))throw new ManagedRenameInvalidRequestError(`Destination file is excluded by the project content config.`);let E=resolveContentEntryPath(g,`folder`,e),D=resolveContentEntryPath(g,`folder`,s);if(E===D)return{renamedAssets:[],rewrittenDocs:[]};if(stringsDifferOnlyByCase(e,s))throw new ManagedRenameInvalidRequestError(`Case-only renames are not supported.`);if(!existsSync(E))throw new ManagedRenameSourceNotFoundError(`file`);if(existsSync(D))throw new ManagedRenameDestinationExistsError;if(!statSync(E).isFile())throw new ManagedRenameSourceTypeMismatchError(`file`,`Source path is not a document file.`);let k=ve?.(),j=new Set(k?k.getConflicts().map(e=>e.file):[]),F=t.documents.get(w);if(F!==void 0&&isDocInConflict(F)||j.has(e))throw new DocInConflictError({file:e});let L=[{fromPath:e,toPath:s}],B=Yr(L).filter(e=>e.docName!==w);S.setAttribute(`rename.rewrite_candidates`,B.length),Xr(B.map(e=>e.docName)),reconcileDiskBeforeAgentWrite(t,w,g),Ie&&!isSystemDoc(w)&&!isConfigDoc(w)&&Ie.setDeleted(w);let H=(await Br([w],`renamed`)).get(w),q=typeof H==`string`?H:readFileSync(E,`utf-8`),ee=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[{from:w,to:w}],snapshots:[{docName:w,content:q}],cleanupPaths:[s]}),J=[];return await withManagedRenameRecovery(Ce??g,ee,async()=>{writeFileIfContentDiffers(E,q),registerWrite(E,contentHash(q)),await renameTrackedPathInGit(Ce,E,D)||renamePathOnDisk(E,D),ue.deleteDocument(w),forgetDocExtension(w),O?.({kind:`delete`,path:E,docName:w});let t=statSync(D);O?.({kind:`file-create`,path:D,relativePath:s,size:t.size,modifiedTs:t.mtimeMs,inode:t.ino}),J=Zr(B,L),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist document-to-file rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),J.length>0&&(fe?.(`backlinks`),fe?.(`graph`))}),J.sort((e,t)=>e.docName.localeCompare(t.docName)),S.setAttribute(`rename.rewrite_count`,J.length),{renamedAssets:L,rewrittenDocs:J}}))}async function Xi(e,s,S,E){return jr(async()=>withSpan(`rename.executeRewrites`,{attributes:{"rename.kind":S}},async D=>{if(!ue)throw new BacklinkIndexRequiredError;let k=resolveContentEntryPath(g,S,e),j=resolveContentEntryPath(g,S,s);if(k===j)return{renamed:[],renamedAssets:[],rewrittenDocs:[]};if(!existsSync(k))throw new ManagedRenameSourceNotFoundError(S);if(existsSync(j)&&!isCaseOnlySelfCollision(k,j))throw new ManagedRenameDestinationExistsError;let F=statSync(k);if(S===`file`&&!F.isFile()||S===`folder`&&!F.isDirectory())throw new ManagedRenameSourceTypeMismatchError(S);let L=S===`folder`?Ki(k,e,s):[];D.setAttribute(`rename.affected_assets`,L.length);let B=(S===`file`?[docNameForFileOperationPath(g,e)]:Gi(k)).map(t=>({from:t,to:S===`file`?docNameForFileOperationPath(g,s):remapDocNameForRename(t,S,e,s)}));if(D.setAttribute(`rename.affected_docs`,B.length),B.length===0){let t=Yr(L);Xr(t.map(e=>e.docName));let g=[];return S===`folder`&&(await renameTrackedPathInGit(Ce,k,j)||renamePathOnDisk(k,j),st(e,s),fe?.(`files`)),g.push(...Zr(t,L)),g.length>0&&(ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`backlinks`),fe?.(`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})),J=new Set;for(let{from:e}of B)for(let t of ue.getBacklinks(e))H.has(t.source)||J.add(t.source);let Y=[...J].sort((e,t)=>e.localeCompare(t)),te=new Map,ne=new Set,ae=new Set,se=[];for(let e of[...H.keys(),...Y]){if(te.has(e))continue;if(!H.has(e)&&!existsSync(resolveContentEntryPath(g,`file`,e))){se.push(e);continue}reconcileDiskBeforeAgentWrite(t,e,g);let s=Ur(e);typeof s==`string`?(te.set(e,s),H.has(e)||ne.add(e)):H.has(e)||se.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)??Ur(t);typeof e==`string`&&qr(e,t,H.get(t)??t,H,L).rewrites!==0&&(te.has(t)||te.set(t,e),ae.add(t),H.has(t)||ne.add(t))}}Xr(ae);for(let{from:e}of B)if(typeof te.get(e)!=`string`)throw new ManagedRenameMissingDocumentError(e);let ce=createManagedRenameRecoveryJournal({fromPath:e,toPath:s,affectedDocs:[...B],snapshots:Hr([...te.keys()],te)}),de=[],me=[...ne].sort((e,t)=>e.localeCompare(t));return await withManagedRenameRecovery(Ce??g,ce,async()=>{for(let e of se)ue.deleteDocument(e);for(let e of me){let s=t.documents.get(e)?Gr(e,H,L):qr(te.get(e)??``,e,e,H,L);s.rewrites>0&&(Wr(e,s.markdown),de.push({docName:e,rewrites:s.rewrites})),ue.updateDocumentFromMarkdown(e,s.markdown)}if(Ie)for(let{from:e,to:t}of B)isSystemDoc(e)||isConfigDoc(e)||(Ie.setRenamed(e,t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:e,to:t,kind:`renamed`,source:`spine`})));let w=resolveContentEntryPath(g,S,e),D=resolveContentEntryPath(g,S,s);await renameTrackedPathInGit(Ce,w,D)||renamePathOnDisk(w,D),S===`folder`&&st(e,s);let k=await Br([...H.keys()],`renamed`);if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_RENAME_FAULT===`pre-append`)throw Error(`OK_TEST_RENAME_FAULT=pre-append`);if(ee?.current){let e=ee.current,t=B.filter(({from:e,to:t})=>stripDocExtension(e)!==stripDocExtension(t));t.length>0&&withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":S}},s=>{let g=randomUUID(),w=new Date().toISOString(),D=oe?.()??`main`,O=getOrLoadRenameLogIndex(e.gitDir),k=E?.actor?{writerId:E.actor.writerId,displayName:E.actor.displayName}:{writerId:SERVICE_WRITER.id,displayName:SERVICE_WRITER.name},j=0;for(let{from:s,to:F}of t){let t={v:1,from:s,to:F,at:w,commitSha:``,branch:D,groupId:g,kind:S,actor:k};appendRenameLogEntry(e.gitDir,t,O,e),j+=1,E?.actor?recordContributor(F,E.actor.writerId,E.actor.displayName,E.actor.colorSeed,formatRenameSubject(s,F),E.actor.actorMetadata,void 0,[{from:s,to:F}]):recordContributor(F,SERVICE_WRITER.id,SERVICE_WRITER.name,SERVICE_WRITER.id,formatRenameSubject(s,F),void 0,void 0,[{from:s,to:F}])}s.setAttribute(`rename.entries_appended`,j)})}let j=S===`file`&&isSupportedDocFile(s)?extname(s):null;for(let{from:e,to:t}of B){let s=isSupportedDocFile(e)?extname(e):getDocExtension(e);forgetDocExtension(e),registerDocExtension(t,j??s)}let F=[...B].sort((e,t)=>e.from.localeCompare(t.from));for(let{from:e,to:t}of F){let s=resolveContentEntryPath(g,`file`,e),S=resolveContentEntryPath(g,`file`,t),w=qr(k.get(e)??te.get(e)??readFileSync(S,`utf-8`),e,t,H,L);Vr([{fromDocName:e,toDocName:t}],new Map([[e,w.markdown]])),setReconciledBase(t,w.markdown),O?.({kind:`rename`,oldPath:s,newPath:S,oldDocName:e,newDocName:t,content:w.markdown}),ue.renameDocument(e,t,w.markdown),w.rewrites>0&&de.push({docName:t,rewrites:w.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`)}),ue.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${s}:`,t)}),fe?.(`files`),fe?.(`backlinks`),fe?.(`graph`),de.sort((e,t)=>e.docName.localeCompare(t.docName)),D.setAttribute(`rename.rewrite_count`,de.length),{renamed:q,renamedAssets:L,rewrittenDocs:de}}))}function Qi(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 Ra(e){return{principalId:we?.()?.id,agentType:resolveAgentType(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function eo(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 to(e){return{value:e.value}}function so(e,t=!1){e.kind===`value`&&(incrementSummariesProvided(),e.truncatedFrom!==void 0&&!t&&incrementSummariesTruncated())}function _s(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=eo(S),E=g||!w.response?w.response:to(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(),so(S,!g);for(let{docName:e}of s)Ht(e,`rename-path`);return E}case`principal`:{let t=eo(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)}so(e.summary,!1);for(let{docName:e}of s)Ht(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 xs(e,t,s){let g=t.replace(/\/$/,``),S=g===``?``:`${g}/`;return e===`template`?`${S}.ok/templates/${s}`:e===`skill`?`${S}.ok/skills/${s}`:e===`folder-frontmatter`?`${S}.ok/frontmatter`:g===``?`.`:g}function Cs(e,t,s,g){if(e.kind!==`agent`&&e.kind!==`principal`)return;let S=eo(e.summary);recordContributor(t,e.writerId,e.displayName,e.colorSeed,s,e.actor,S.stored,g)}async function Ts(e){if(Y)try{await Y()}catch(t){console.warn(`[${e}] flushContributors failed; attribution stays queued for the next flush:`,t)}}let Ds=withValidation(AgentWriteRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`agent-write`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Qi(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}=eo(H);try{let t=iconFromClientName(F),s=AGENT_ICON_COLORS[t]??colorFromSeed(j??O);ge?.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,Ra({clientName:F,clientVersion:L,label:B}),ne),incrementAgentWriteCalls(),so(H)}finally{ge?.touchMode(O,`idle`)}let ae=await Ut(D);if(ae?.kind===`failure`){Wt(w,ae.failure,`agent-write`);return}if(ae?.kind===`divergence`){Xt(w,`agent-write`);return}Ht(D,`agent-write`),_e?.();let oe=Zt(ee);successResponse(w,200,AgentWriteSuccessSchema,{timestamp:J,...te?{summary:te}:{},...oe?{warning:oe,warnings:[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$7.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`}),Os=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=zt(D),{agentId:k,agentName:j,colorSeed:F,clientName:L,clientVersion:B,label:H}=Qi(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}=eo(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);ge?.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,Ra({clientName:L,clientVersion:B,label:H}),J),incrementAgentWriteCalls(),so(q)}finally{ge?.touchMode(k,`idle`)}let oe=await Ut(O);if(oe?.kind===`failure`){Wt(w,oe.failure,`agent-write-md`);return}if(oe?.kind===`divergence`){Xt(w,`agent-write-md`);return}Ht(O,`agent-write-md`),me?.setFocus(k,{agentName:j,currentDoc:O,writeKind:`write`,ts:Date.now()}),_e?.();let se=Rt(O),ce=Y.dc.document.getText(`source`).toString();rn(O,ce);let ue=await validateMermaidFences(ce,O),de=en();de.add(O);let fe=computeBrokenOutboundLinks(ce,O,de,tn),ve=Bt(O),ye=Vt();ye===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(L)});let Ce=Zt(te),we=ae===void 0?void 0:toContentDivergenceWarning(ae),Te=[...we?[we]:[],...Ce?[Ce]:[],...ue??[]];successResponse(w,200,AgentWriteMdSuccessSchema,{timestamp:ne,subscriberCount:ve,systemSubscriberCount:ye,...se?{hints:se}:{},...ee?{summary:ee}:{},...we?{warning:we}:Ce?{warning:Ce}:{},...Te.length>0?{warnings:Te}:{},brokenLinks:fe},{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$7.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`}),ks=withValidation(FrontmatterPatchRequestSchema,async(S,w,E)=>{try{let S=requireNonEmptyDocName(E.docName,w,`frontmatter-patch`);if(S===null)return;let D=zt(S),{agentId:O,agentName:k,colorSeed:j,clientName:F,clientVersion:L,label:B}=Qi(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}=eo(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,se=!1,ce=!1,ue=[];try{let e=iconFromClientName(F),t=AGENT_ICON_COLORS[e]??colorFromSeed(j??O);ge?.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))ue.push(e);if(s.nextFenced!==e){let g=e===``&&t!==``&&!t.startsWith(`
|
|
1945
1945
|
`),S=s.nextFenced+(g?`
|
|
1946
|
-
`:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),ce=!0}se=!0},te.origin)})}finally{ge?.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;case`invalid_path`:e={[oe.path.map(String).join(`.`)||`__path__`]: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(se&&ue.length>0){if(recordContributor(D,O,k,j,void 0,Zi({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),xs(ee),ce){let e=await Ut(D);if(e?.kind===`failure`){Wt(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Kt(w,`frontmatter-patch`);return}}Ht(D,`frontmatter-patch`)}me?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),_e?.();let de=Bt(D),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=$t(ne);Fr(D,te.dc.document.getText(`source`).toString());let ye=jr();ye.add(D);let Ce=computeBrokenOutboundLinks(te.dc.document.getText(`source`).toString(),D,ye,Mr);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:de,systemSubscriberCount:fe,appliedKeys:ue,...J?{summary:J}:{},...ve?{warning:ve,warnings:[ve]}:{},brokenLinks:Ce},{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$7.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 Ps(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 Is=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=zt(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:Ps(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:Ps(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}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$7.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`),E=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(E&&De&&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:De,dirFilter:S,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$7.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$7.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(E&&De){let e=`showAll:${O===1?`d1:`:``}${S??``}`,s=Ke.get(e);if(!s){let t=new AbortController,w=(async()=>{let e=[],s=getShowAllMaxEntries(),{truncated:w}=await walkContentDirForShowAll({contentDir:g,contentFilter:De,dirFilter:S,documents:e,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$7.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;Ke.set(e,E),w.finally(()=>{Ke.get(e)===E&&Ke.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(),Ke.get(e)===w&&Ke.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(),F=D(),L=j?.()??new Map,H=[];for(let[e,t]of L)S&&!e.startsWith(`${S}/`)&&e!==S||H.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let q=[];try{let e=vt(k);$e?.signature!==e&&($e={signature:e,assets:collectReferencedAssets({contentDir:g,fileIndex:k,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:De?e=>De.isPathIgnored(e):void 0})}),q=$e?.assets??[]}catch(e){$e=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}let ee=new Set;for(let e of q)S&&!e.path.startsWith(`${S}/`)&&e.path!==S||(ee.add(e.path),H.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}));for(let[e,t]of F){if(t.kind===`markdown`){if(S&&!e.startsWith(`${S}/`)&&e!==S)continue;let s=getDocExtension(e);H.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=toPosix(relative(g,t.canonicalPath));H.push({kind:`document`,docName:w,docExt:s,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:E})}continue}if((!S||e===S||e.startsWith(`${S}/`))&&!ee.has(e)){let s=synthesizeShowAllAssetExt(e);H.push({kind:`file`,docName:e,path:e,docExt:`.${s}`,assetExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let s of t.aliases){if(!(!S||s===S||s.startsWith(`${S}/`))||ee.has(s))continue;let w=toPosix(relative(g,t.canonicalPath)),E=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${E}`,assetExt:E,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:w})}}let J=B?.()??new Map;if(J.size>0){let e=e=>!S||e===S||e.startsWith(`${S}/`),t=new Map;for(let[e,s]of J){let g=t.get(s);g?g.push(e):t.set(s,[e])}for(let[s,S]of t){let t=L.get(s),w=t?toPosix(relative(g,t.canonicalPath)):s;for(let g of S)e(g)&&H.push({kind:`folder`,path:g,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:s,targetPath:w})}let s=(s,g)=>{for(let S=s.indexOf(`/`);S!==-1;S=s.indexOf(`/`,S+1)){let w=t.get(s.slice(0,S));if(!w)continue;let E=s.slice(S);for(let t of w){let s=`${t}${E}`;e(s)&&g(s)}}};for(let[e,t]of L)s(e,s=>{H.push({kind:`folder`,path:s,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:toPosix(relative(g,t.canonicalPath))})});for(let[e,t]of F)s(e,s=>{let S=toPosix(relative(g,t.canonicalPath));if(t.kind===`markdown`)H.push({kind:`document`,docName:s,docExt:getDocExtension(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S});else{let g=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${g}`,assetExt:g,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S})}})}H.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:H},{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}),$s=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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:ue.getBacklinks(s).map(e=>({source:e.source,anchor:e.anchor,title:jt(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}),ec=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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]=ue.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}),tc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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=jr();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ue.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Mt(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}),nc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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}=ue.getLinkGraphNeighborhood(g,e))}else ({nodes:w,links:E}=ue.getLinkGraph());let D=jr();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=Lt(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Mt(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}),rc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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:ue.getOrphans([...w().keys()],s).map(e=>({docName:e,title:jt(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}),ic=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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=jr();successResponse(t,200,HubsSuccessSchema,{hubs:ue.getHubs(S).map(e=>({docName:e.docName,title:Mt(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}),ac=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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=>zt(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ue.getDeadLinks(jr(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:jt(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}),oc=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=zt(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=Xi(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,se=!1,ce;try{let t=iconFromClientName(H),s=AGENT_ICON_COLORS[t]??colorFromSeed(B??F);if(ge?.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){se=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));ce=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),ce!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":j,position:`patch`,intendedBytes:ce.intendedBytes,actualBytes:ce.actualBytes,byteDelta:ce.byteDelta,"agent.id":F,"agent.client_name":H})),!ae&&!oe&&!se){let{stored:e}=ka(J);recordContributor(j,F,L,B,void 0,Zi({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),xs(J),recordContentDivergenceGate(`agent-patch`,ce)}}finally{ge?.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(se){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 ue=await Ut(j);if(ue?.kind===`failure`){Wt(w,ue.failure,`agent-patch`);return}if(ue?.kind===`divergence`){Kt(w,`agent-patch`);return}Ht(j,`agent-patch`),me?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),_e?.();let de=Bt(j),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=ka(J),ye=Y.dc.document.getText(`source`).toString();Fr(j,ye);let Ce=await validateMermaidFences(ye,j),we=jr();we.add(j);let Te=computeBrokenOutboundLinks(ye,j,we,Mr),De=$t(te),je=ce===void 0?void 0:toContentDivergenceWarning(ce),Me=[...je?[je]:[],...De?[De]:[],...Ce??[]];successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ne,subscriberCount:de,systemSubscriberCount:fe,...ve?{summary:ve}:{},...je?{warning:je}:De?{warning:De}:{},...Me.length>0?{warnings:Me}:{},brokenLinks:Te},{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$7.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`}),sc=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=zt(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Xi(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);ge?.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,Zi({clientName:k,clientVersion:j,label:F}))}finally{ge?.touchMode(E,`idle`)}if(q){let e=await Ut(w);if(e?.kind===`failure`){Wt(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Kt(g,`agent-undo`);return}Ht(w,`agent-undo`)}me?.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$7.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`}),cc=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$7.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}),lc=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=zt(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$7.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}),uc=withValidation(EmptyRequestSchema,async(e,t)=>{try{await J?.(),successResponse(t,200,TestFlushGitSuccessSchema,{},{handler:`test-flush-git`})}catch(e){log$7.error({err:e},`[test-flush-git] flush failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:e})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),dc=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=zt(w.searchParams.get(`docName`)??`test-doc`),D;try{D=safeContentPath(E,g)}catch(e){log$7.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(Me??t.unloadDocument.bind(t))(k),writeFileSync(D,``,`utf-8`),ue&&(ue.deleteDocument(E),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${E}:`,e)}),fe?.(`backlinks`),fe?.(`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`),De&&await De.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}fe?.(`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}),fc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ue.rebuildFromDisk(),await ue.ingestGlobalSkillBundles([resolve(nu,`.ok`,`skills`)]),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),fe?.(`backlinks`),fe?.(`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}),pc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!H){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await H(),fe?.(`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}),mc=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Xi(s),E=ee?.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=[],k=!1;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}let j=oe?.()??`main`;if(O.length===0)if(e!==void 0)O=[{id:g,name:w?`${S} (${w})`:S,email:`${g}@openknowledge.local`}];else{let e=(await enumerateWipChains(E,j)).filter(e=>!e.isPark);O=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[SERVICE_WRITER],k=!0}let F=ce??`.`,L=normalizeSummary(typeof s.summary==`string`?s.summary:void 0),B=await saveVersion(E,F,O,j,L.kind===`value`?L.value:void 0,k?{includeUpstream:!1}:void 0);getLogger(`history`).info({checkpointRef:B.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:B.checkpointRef},{handler:`save-version`})}catch(e){log$7.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`}),hc=withValidation(EmptyRequestSchema,async(e,t)=>{let s=ee?.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`)??oe?.()??`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=Il(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),j=`folder\0${E}\0${e.folderRel}\0${D}\0${k}`,{promise:F,coalesced:L}=Xe.run(j,()=>getFolderTimeline(s,e.folderRel,ce??`.`,{branch:E,limit:D,offset:k}));L&&recordTimelineCoalesced(`folder`),successResponse(t,200,HistorySuccessSchema,{...await F},{handler:`history`});return}let D=ce??`.`,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`),F=Math.min(200,Number.isFinite(k)?k:50),L=Number.isFinite(j)?j:0,B=g.searchParams.get(`type`)??void 0,H=g.searchParams.get(`author`)??void 0,q=g.searchParams.get(`excludeAuthor`)??void 0,J=g.searchParams.get(`includeAutoCheckpoints`)===`true`,Y=`doc\0${E}\0${S}\0${F}\0${L}\0${B??``}\0${H??``}\0${q??``}\0${J?`1`:`0`}`,te=Date.now();try{let{promise:e,coalesced:g}=Xe.run(Y,()=>getDocumentHistory(s,{docName:S,branch:E,limit:F,offset:L,type:B,author:H,excludeAuthor:q,includeAutoCheckpoints:J},D));g&&recordTimelineCoalesced(`doc`);let w=await e,O=Date.now()-te;getLogger(`timeline`).info({docName:S,entries:w.entries.length,durationMs:O},`query`),successResponse(t,200,HistorySuccessSchema,{...w},{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 gc(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=ee?.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=ce??`.`,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=oe?.()??`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 _c=withValidation(RollbackRequestSchema,async(s,g,S)=>{let w=extractActorIdentity(S,we);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:docNameToRelativePath(S.docName)}),`rollback`);return}let D=ee?.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=ce??`.`,F=safeDocPath(O,j);if(`error`in F){errorResponse(g,400,`urn:ok:error:invalid-request`,F.error,{handler:`rollback`});return}let L=shadowGit(D),B=Date.now();try{let s=getOrLoadRenameLogIndex(D.gitDir),S=createAncestorShaSetCache(),E=await resolveDocPathAtCommit(D,O,k,oe?.()??`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 L.raw(`show`,`${k}:${E}`),H=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,J;q.transact(()=>{replaceRawBody(q,F,ee),J=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),J!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:J.intendedBytes,actualBytes:J.actualBytes,byteDelta:J.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,J);let Y;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=ka(s);Y=t||!g.response?g.response:_s(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),xs(s,!t);break}case`principal`:{let e=ka(w.summary);Y=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),xs(w.summary,!1);break}case`anonymous`:log$7.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 te=await Ut(O);if(te?.kind===`failure`){Wt(g,te.failure,`rollback`);return}if(te?.kind===`divergence`){Kt(g,`rollback`);return}Ht(O,`rollback`);let ne=Date.now()-B;getLogger(`rollback`).info({docName:O,from:k.slice(0,8),durationMs:ne},`rollback`),w.kind===`agent`&&me?.setFocus(w.writerId,{agentName:w.displayName,currentDoc:O,writeKind:`rollback-apply`,ts:Date.now()});let ae=J===void 0?void 0:toContentDivergenceWarning(J);successResponse(g,200,RollbackSuccessSchema,{restoredFrom:k,timestamp:H,...Y?{summary:Y}:{},...ae?{warning:ae,warnings:[ae]}:{}},{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`}),vc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$7.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}),yc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$7.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}),bc=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$7.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=se?.(),g=getBootTimings();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s},...g===void 0?{}:{boot:g}},{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 xc(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=we?.()??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 Sc(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=ge?.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$7.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 Cc(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 wc(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 Tc=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(De?.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$7.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}),Ec=1048576,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-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>Ec){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${Ec}-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}),Oc=1440*60*1e3,kc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ee?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),s=[],g=resolve(ee.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$7.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=oe?.()??`main`,t=await listRescueCheckpoints(ee.current,e);for(let e of t)s.push({...e,source:`timeline`})}catch(e){log$7.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}),Ac=withValidation(CreatePageRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);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 w=resolve(g),E=resolve(w,S);if(!isWithinDir(E,w)){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let D=stripDocExtension(S);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`});return}if(S.split(`/`)[0]===`.ok`||isManagedArtifactDocName(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page under .ok/ — skills and templates are authored through their own validating flows.`});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(w,s),E=g.find(e=>e.name===k);if(!E){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(w,E.path),O;try{O=readFileSync(D,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${E.path}.`,{handler:`create-page`,cause:e});return}let L=instantiateDoc(O),B=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;j=applySubstitution(L,{date:todayIsoUtc(),user:B}),F=E.scope}mkdirSync(dirname(E),{recursive:!0});try{writeFileSync(E,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(Ie?.delete(L),De&&De.incrementMdDir(dirname(L)),registerWrite(E,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)}`)}O?.({kind:`create`,path:E,docName:L,content:j}),ue&&(ue.updateDocumentFromMarkdown(L,j),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${L}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`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`}),jc=withValidation(CreateFolderRequestSchema,async(e,t,s)=>{try{if(extractActorIdentity(s,we).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(De?.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}),it(e),fe?.(`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`}),Mc=withValidation(DuplicatePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:w}=S,E=S.path,D=w===`file`?stripDocExtension(E):E;if(!isValidRelativeContentPath(E)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||w===`file`&&(isSystemDoc(D)||isConfigDoc(D))||w===`folder`&&isReservedSyntheticFolderPath(E)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}w===`file`&&probeAndRegisterSourceFileExtension(g,E);let k=resolveContentEntryPath(g,w,E);if(!existsSync(k)){if(w===`file`){let e=resolveContentEntryPath(g,`folder`,E);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}}errorResponse(s,404,`urn:ok:error:doc-not-found`,`${w} does not exist.`,{handler:`duplicate-path`});return}let j=statSync(k);if(w===`file`&&!j.isFile()||w===`folder`&&!j.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}let F=w===`file`?[docNameForFileOperationPath(g,E)]:Hi(resolveContentEntryPath(g,`folder`,E)),L=ve?.(),B=new Set(L?L.getConflicts().map(e=>e.file):[]);for(let e of F){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=B.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let H,q=[];if(w===`file`){let e=extname(k);if(H=nextAvailableDuplicateDocName(g,D).docName,isSystemDoc(H)||isConfigDoc(H)||De?.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(k,`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 j=!1;try{registerDocExtension(H,e),Ie?.delete(H),De&&(De.incrementMdDir(dirname(H)),j=!0),registerWrite(t,contentHash(S)),O?.({kind:`create`,path:t,docName:H,content:S}),ue?.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),De&&j&&De.decrementMdDir(dirname(H)),O?.({kind:`delete`,path:t,docName:H}),e}}else{if(H=nextAvailableDuplicateFolderPath(g,E).folderPath,De?.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(k,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))it(e);let e=collectMarkdownCopies(g,H);q=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(stripDocExtension(t.docName),e),Ie?.delete(t.docName),De&&De.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),O?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),ue?.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)}`)}ue&&q.length>0&&(ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),successResponse(s,200,DuplicatePathSuccessSchema,{kind:w,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`}),Nc=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=Dt(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}),Pc=withValidation(RenamePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);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}let O=w===`asset`&&isSupportedDocFile(E)&&isSupportedDocFile(D)?`file`:w;if(O===`asset`){let t;try{t=isSupportedDocFile(E)&&!isSupportedDocFile(D)?await Ki(E,D):await Gi(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=Br(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&Tt();let g;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let s=`Renamed asset ${E} → ${D}`;g=Cs(e,s,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:s})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$7.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}),Y)try{await Y()}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}O===`file`&&probeAndRegisterSourceFileExtension(g,E);let k=O===`file`?[docNameForFileOperationPath(g,E)]:Hi(resolveContentEntryPath(g,`folder`,E)),j=ve?.(),F=new Set(j?j.getConflicts().map(e=>e.file):[]);for(let e of k){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=F.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`rename-path`);return}}if(De){let e=isSupportedDocFile(E)?extname(E):getDocExtension(E);if(O===`file`?De.isExcluded(isSupportedDocFile(D)?D:`${D}${e}`):De.isDirExcluded(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Destination ${O===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let L=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,B;try{B=await Yi(E,D,O,L?{actor:L}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,zr(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(B.renamed.length===0&&B.renamedAssets.length===0){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}B.renamedAssets.length>0&&Tt();let H,q=B.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(q.length>0&&(H=Cs(e,`Renamed ${E} → ${D}`,q.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$7.debug({kind:w,fromPath:E,toPath:D,affectedDocs:B.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${O}`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:B.renamed,renamedAssets:B.renamedAssets,rewrittenDocs:B.rewrittenDocs,...H?{summary:H}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:g,error:S}=Br(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Fc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Xi(S);let{kind:e,path:w}=S;if(!isValidRelativeContentPath(w)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let E=e===`asset`?ji(w):{path:w,ambiguous:!1};if(E.ambiguous){errorResponse(s,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let D=E.path,k=e===`asset`&&isSupportedDocFile(D)?`file`:e;if(k===`file`&&probeAndRegisterSourceFileExtension(g,D),k===`asset`&&isReservedProjectStatePath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let j=k===`asset`?resolveContentEntryPath(g,`folder`,D):resolveContentEntryPath(g,k,D);if(!existsSync(j)){errorResponse(s,404,`urn:ok:error:doc-not-found`,`${k} does not exist.`,{handler:`delete-path`});return}let F=statSync(j);if(k===`file`&&!F.isFile()||k===`asset`&&!F.isFile()||k===`folder`&&!F.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${k}.`,{handler:`delete-path`});return}let L=k===`asset`?[]:k===`file`?[docNameForFileOperationPath(g,D)]:Hi(resolveContentEntryPath(g,`folder`,D)),B=ve?.(),H=new Set(B?B.getConflicts().map(e=>e.file):[]);for(let e of L){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=H.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`delete-path`);return}}if(await Vr(L,`deleted-upstream`),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));k===`file`||k===`asset`?tracedUnlinkSync(j):(tracedRmSync(j,{recursive:!0,force:!1}),at(D)),Tt();for(let e of L)O?.({kind:`delete`,path:resolve(g,docNameToRelativePath(e)),docName:e});fe?.(`files`),successResponse(s,200,DeletePathSuccessSchema,{deletedDocNames:L},{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`}),Ic=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,we).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===`asset`&&isSupportedDocFile(S)?`file`:e,D=stripDocExtension(S);E===`file`&&probeAndRegisterSourceFileExtension(g,S);let k=E===`folder`&&isReservedSyntheticFolderPath(S),j=E===`asset`&&isReservedProjectStatePath(S);if(E===`file`&&(isSystemDoc(D)||isConfigDoc(D))||k||j){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${S}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(E===`asset`){Tt(),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let F=w(),L=E===`file`?F.has(D)?[D]:[]:listAffectedDocNames(F,E,S);if(Tt(),L.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Vr(L,`deleted-upstream`),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of L)O?.({kind:`delete`,path:resolve(g,docNameToRelativePath(e)),docName:e});E===`folder`&&at(S),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:L},{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`}),Lc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=w(),s=[];for(let[t,S]of e){let e=getDocExtension(t),w,E;if(S.title!==void 0)w=S.title,E=S.icon;else{w=t;try{let s=readFileSync(resolve(g,`${t}${e}`),`utf-8`);w=extractPageTitle(s,t),E=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}}s.push({docName:t,title:w,docExt:e,size:S.size,modified:S.modified,icon:E})}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}),Rc=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 zc(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,Ce??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:D,byteLength:O,parentDocName:k,placement:j}=s,F=()=>{if(existsSync(w))try{unlinkSync(w)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:k,placement:j||void 0},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B,placement:H}=L.value,{agentId:q,agentName:ee}=Xi(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(O===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(g),Y;try{Y=H===`parent-dir`?`./`:E?.()??`./`}catch(e){F(),log$7.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!isValidAttachmentFolderPath(Y)){F(),errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let te=resolveUploadDestDir(B,normalizeAttachmentFolderPath(Y),J);if(!isWithinContentDir(te,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(te,J)}catch(e){if(F(),(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$7.error({err:e,destDir:te},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(te,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){F();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(te),s;try{s=realpathSync(J)}catch{s=J}if(!isWithinContentDir(e,s)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ne=readTempFileHead(w,4100),ae=await fileTypeFromBuffer(ne),oe=ae?.mime,se=ae?.ext;if(!oe){let e=ne.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(oe=`image/svg+xml`,se=`svg`)}{let s=await findDuplicateAsset(te,D,O);if(s){F();let S=toPosix(relative(g,resolve(te,s)));log$7.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!0,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!0},{handler:`upload-asset`});return}}let ce;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=se??t??``;ce=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else ce=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,te,ce),S=toPosix(relative(g,resolve(te,s)));log$7.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!1,mime:oe??null,size:O,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$7.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,filename:ce,size:O,reason:g,httpStatus:uploadStatusFor(g),err:s},`[upload] write failed`),errorResponse(t,uploadStatusFor(g),g,uploadTitleFor(g),{handler:`upload-asset`,cause:s})}}let Bc=`/api/local-op/clone`,Vc=`/api/local-op/ok-init`,Hc=600*1e3,Uc=45e3,Wc=`local-op-clone`,Gc=withValidation(LocalOpCloneRequestSchema,Kc,{handler:Wc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Wc})});async function Kc(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:Wc,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:Wc,cause:Error(`dir=${S}`)});return}if(!Ge.tryAcquire(Bc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Wc,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,Wc),D=null,O=runCloneSubprocess({cliArgs:ye,url:g,dir:S,branch:w,timeoutMs:Hc,onEvent:e=>{if(e.type===`complete`){D=e.dir;return}if(e.type===`error`){e.message&&log$7.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 qc(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$7.error({err:e,handler:Wc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ge.release(Bc)}})(),t.on(`close`,()=>{O.cancel()})}async function qc(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]=ye,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$7.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$7.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 Jc=`local-op-ok-init`,Yc=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:Jc,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:Jc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Jc,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:Jc});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:Jc});return}if(!Ge.tryAcquire(Vc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Jc,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:Jc})}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:Jc})}finally{Ge.release(Vc)}},{handler:Jc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Jc})}),Xc=`/api/local-op/auth/login`,Zc=`/api/local-op/auth/status`,Qc=`/api/local-op/auth/repos`,$c=`/api/local-op/auth/signout`,nl=null,il=`local-op-auth-login`,al=withValidation(LocalOpAuthHostRequestSchema,cl,{handler:il,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:il})});async function cl(e,t,s){let g=s.host??`github.com`;if(!Ge.tryAcquire(Xc)){let e=nl;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:il,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),nl=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,il),w=runDeviceFlowSubprocess({cliArgs:ye,host:g,timeoutMs:Hc,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,ve),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});nl=w;let E=()=>{w.cancel(),nl===w&&(nl=null,Ge.release(Xc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}nl===w&&(nl=null,Ge.release(Xc))})}let ll=`local-op-auth-status`,ul=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire(Zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:ll,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,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(`
|
|
1947
|
-
`).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:
|
|
1948
|
-
`);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$7.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(),Ge.release(Qc))}),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()),Ge.release(Qc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Ge.release(Qc))})}let ml=`local-op-auth-signout`,hl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire($c)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:ml,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,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:ml})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:ml,cause:e})}finally{Ge.release($c)}},{handler:ml,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ml})}),gl=`/api/local-op/auth/set-identity`,_l=`local-op-auth-set-identity`,vl=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!Ce){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:_l});return}if(!Ge.tryAcquire(gl)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:_l,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(Ce,g,S),ve?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:_l})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:_l,cause:e})}finally{Ge.release(gl)}},{handler:_l,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:_l})});async function yl(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=ve?.();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 xl=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=ve?.();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`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Cl(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=ve?.();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 Tl=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=ve?.();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`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function El(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(!Ce){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=ve?.(),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:Ce,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=Re?Re(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 Dl(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 Ol=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 kl(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 jl=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,Et.probeAll)}catch(e){t.headersSent||(log$7.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 Pl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:de.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 Fl(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(!de){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=de.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:jt(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 Il(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 Ll=/^[A-Za-z0-9_-]+$/;function Rl(e,t,s=`template`){return!e||!Ll.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 zl(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 Bl(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 Vl(e,t){if(e.method===`GET`)return Hl(e,t);if(e.method===`PUT`)return Ul(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Hl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=Il(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}),Ul=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(We){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,we);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=Il(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`&&(Ds(e,Ts(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Os(`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 Wl(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}function Gl(e,s,g){let S=t.documents.get(e);return S&&isDocInConflict(S)?(respondDocInConflict(g,new DocInConflictError({file:`${e}.md`}),s),!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 ql(e,t){if(e.method===`GET`)return Yl(e,t);if(e.method===`PUT`)return Xl(e,t);if(e.method===`POST`)return Ql(e,t);if(e.method===`DELETE`)return Zl(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Jl=e=>{let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{frontmatter:g,body:s}},Yl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Rl(g,t,`template-get`))return;let S=Il(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=zl(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,F=parseTemplateFile(await readFile$1(O,`utf-8`)),L=F.identity,B=F.starterContent;successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:L,body:B}},{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}),Xl=withValidation(TemplatePutRequestSchema,async(e,t,g)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let S=g.name;if(!Rl(S,t,`template-put`))return;let w=Il(g.folder,t,`folder`,`template-put`);if(!w||Wl(w.folderRel,S,`template-put`,t))return;let E=composeTemplateContent({name:S,body:typeof g.body==`string`?g.body:``,frontmatter:Bl(g.frontmatter)});if(!E.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}let D=resolve(w.resolvedContentDir,w.folderRel,`.ok`,`templates`,`${S}.md`),O=!existsSync(D),k=relative(w.resolvedContentDir,D).split(/[\\/]/).filter(Boolean).join(`/`),j=iu(w.folderRel,S),{agentId:F,agentName:L,colorSeed:B,clientName:H}=Xi(g),q=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H});q.dc.document.transact(()=>{composeAndWriteRawBody(q.dc.document,E.content,`agent`)},q.origin);let ee=await Ut(j);if(ee?.kind===`failure`){Wt(t,ee.failure,`template-put`);return}if(ee?.kind===`divergence`){Kt(t,`template-put`);return}Ds(e,Ts(`template`,w.folderRel,S),`${O?`template-create`:`template-edit`}: ${k}`),await Os(`template-put`),successResponse(t,200,TemplatePutSuccessSchema,{path:k,created:O,warnings:E.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`}),Zl=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Rl(g,t,`template-delete`))return;let S=Il(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},we);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Wl(S.folderRel,g,`template-delete`,t))return;await Vr([iu(S.folderRel,g)],`deleted-upstream`);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&&(Ds(E,Ts(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Os(`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}),Ql=withValidation(TemplateMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Rl(s.fromName,t,`template-move`)||!Rl(s.toName,t,`template-move`))return;let g=Il(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=Il(s.toFolder,t,`folder`,`template-move`);if(!S||Wl(g.folderRel,s.fromName,`template-move`,t))return;await Vr([iu(g.folderRel,s.fromName)],`renamed`);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(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!w.ok){if(w.error.code===`TEMPLATE_NOT_FOUND`){let e=zl(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=instantiateDoc(readFileSync(resolve(S.resolvedContentDir,w.toPath),`utf-8`))}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:Bl(s.frontmatter)});t.ok||(E=t.error)}}if(Ds(e,Ts(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Os(`template-move`),fe?.(`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`}),$l=500;function eu(e,t,s){return!e||e.length>64||!SKILL_NAME_REGEX.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:s}),!1):!0}function tu(e,t,s){let g=SkillScopeSchema.safeParse(e??`project`);return g.success?g.data:(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:s}),null)}let nu=Te??homedir();function ru(e){return resolve(e===`global`?nu:g,`.ok`,`skills`)}function iu(e,t){return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function au(e){return e===`navigation`||e===`relevance`?e:void 0}function ou(e,t){return relative(t===`global`?nu:g,e).split(/[\\/]/).filter(Boolean).join(`/`)}function su(e){return e===`global`?nu:Ce}async function cu(e,t){let s=await removeSkillInstall(e,t);return reverseProjectSkill(t,e,PROJECT_SKILL_EDITOR_IDS),s!==null}function lu(e,t){let s=[];if(!existsSync(e))return{skills:s,truncated:!1};let g;try{g=readdirSync(e,{withFileTypes:!0})}catch(g){return getLogger(`skills`).warn({err:g,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:s,truncated:!1}}let S=!1;for(let w of g.sort((e,t)=>e.name.localeCompare(t.name))){if(!w.isDirectory()||!SKILL_NAME_REGEX.test(w.name))continue;if(s.length>=500){S=!0;break}let g=resolve(e,w.name,`SKILL.md`);if(!existsSync(g))continue;let E,D;try{let{frontmatter:e}=Jl(readFileSync(g,`utf-8`));typeof e.description==`string`&&(E=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(D=e.version)}catch{}s.push({name:w.name,...E===void 0?{}:{description:E},scope:t,path:ou(g,t),absolutePath:g,...D===void 0?{}:{installedVersion:D}})}return{skills:s,truncated:S}}let uu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=lu(ru(`project`),`project`),s=lu(ru(`global`),`global`),g=Ce?readInstalledSkills(Ce).skills:{},S=readInstalledSkills(nu).skills,w=(e,t)=>e.skills.map(e=>{let s=t[e.name]?.hosts??[],g=computePackUpdateStatus(e.name,e.installedVersion);return{...e,installed:s.length>0,hosts:s,...g}});successResponse(t,200,SkillsListSuccessSchema,{skills:[...w(e,g),...w(s,S)],truncated:e.truncated||s.truncated},{handler:`skills-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list skills.`,{handler:`skills-list`,cause:e})}},{handler:`skills-list`,method:`GET`,skipBodyParse:!0});async function du(e,t){if(e.method===`GET`)return _u(e,t);if(e.method===`PUT`)return vu(e,t);if(e.method===`POST`)return bu(e,t);if(e.method===`DELETE`)return yu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let fu=object$1({managed:boolean().nullable(),importable:number().int().nonnegative()}),pu=()=>({managed:Ce?readSkillManagement(Ce)?.manageEditorSkills??null:null,importable:Ce?countImportableEditorSkills({projectDir:Ce,skillsRoot:ru(`project`)}):0}),mu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}successResponse(t,200,fu,pu(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),hu=withValidation(object$1({manageEditorSkills:boolean()}),async(e,t,s)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await writeSkillManagement(Ce,{manageEditorSkills:s.manageEditorSkills,surface:`ui`}),s.manageEditorSkills){let e=await reconcileSkillInstalls({projectDir:Ce,skillsRoot:ru(`project`)});e.adopted.length+e.collided.length>0&&fe?.(`files`)}successResponse(t,200,fu,pu(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`});async function gu(e,t){if(e.method===`GET`)return mu(e,t);if(e.method===`PUT`)return hu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skills-management`,extraHeaders:{Allow:`GET, PUT`}})}let _u=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-get`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-get`);if(S===null)return;let w=ru(S),E=resolve(w,g,`SKILL.md`);if(!existsSync(E)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${g}" not found in ${S} scope.`});return}let{frontmatter:D,body:O}=Jl(await readFile$1(E,`utf-8`));successResponse(t,200,SkillGetSuccessSchema,{skill:{name:g,scope:S,path:ou(E,S),frontmatter:{name:typeof D.name==`string`?D.name:g,description:typeof D.description==`string`?D.description:``},body:O,files:readSkillBundledFiles(resolve(w,g))}},{handler:`skill-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),vu=withValidation(SkillPutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!eu(g.name,t,`skill-put`))return;let S=composeSkillContent({name:g.name,body:typeof g.body==`string`?g.body:``,frontmatter:{name:g.frontmatter.name,description:g.frontmatter.description}});if(!S.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:S.error.code,cause:Error(S.error.message)});return}let w=ru(g.scope),E=resolve(w,g.name,`SKILL.md`),D=!existsSync(E),O=relative(w,E).split(/[\\/]/).filter(Boolean).join(`/`),k=skillLiveDocName(g.scope,g.name);if(Gl(k,`skill-put`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Xi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-put`);return}if(q?.kind===`divergence`){Kt(t,`skill-put`);return}g.scope===`project`&&(Ds(e,Ts(`skill`,``,g.name),`${D?`skill-create`:`skill-edit`}: ${O}`),await Os(`skill-put`)),fe?.(`files`),successResponse(t,200,SkillPutSuccessSchema,{path:O,created:D,warnings:S.warnings},{handler:`skill-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),yu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-delete`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-delete`);if(S===null)return;let w=ru(S),E=s.searchParams,D=extractActorIdentity({agentId:E.get(`agentId`)??void 0,agentName:E.get(`agentName`)??void 0,colorSeed:E.get(`colorSeed`)??void 0,clientName:E.get(`clientName`)??void 0,clientVersion:E.get(`clientVersion`)??void 0,label:E.get(`label`)??void 0,summary:E.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Vr([skillLiveDocName(S,g)],`deleted-upstream`);let O=applySkillDelete({skillsRoot:w,name:g});if(!O.ok){let e=O.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:O.error.code,cause:Error(O.error.message)});return}O.existed&&(S===`project`&&(Ds(D,Ts(`skill`,``,g),`skill-delete: ${O.path}`),await Os(`skill-delete`)),fe?.(`files`));let k=su(S);k&&await cu(k,g),successResponse(t,200,SkillDeleteSuccessSchema,{existed:O.existed,path:O.path},{handler:`skill-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),bu=withValidation(SkillMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!eu(s.fromName,t,`skill-move`)||!eu(s.toName,t,`skill-move`))return;let g=ru(s.scope);await Vr([skillLiveDocName(s.scope,s.fromName)],`renamed`);let S=await applySkillMove({skillsRoot:g,fromName:s.fromName,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!S.ok){if(S.error.code===`SKILL_NOT_FOUND`){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:S.error.message});return}if(S.error.code===`SKILL_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,S.error.message,{handler:`skill-move`,detail:S.error.code});return}let e=S.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 skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:S.error.code,cause:Error(S.error.message)});return}let w=null,E=resolve(g,s.toName,`SKILL.md`),D=``,O=``;try{let e=Jl(readFileSync(E,`utf-8`));D=e.body,typeof e.frontmatter.description==`string`&&(O=e.frontmatter.description)}catch{}let k=typeof s.body==`string`?s.body:D,j=s.frontmatter===void 0?O:s.frontmatter.description,F=applySkillWrite({skillsRoot:g,name:s.toName,body:k,frontmatter:{name:s.toName,description:j}});if(F.ok||(w=F.error),s.scope===`project`&&!w)try{Tu(g,s.fromName,s.toName)}catch(e){getLogger(`skill-move`).warn({err:e,fromName:s.fromName,toName:s.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let L=ou(resolve(g,s.fromName),s.scope),B=ou(resolve(g,s.toName),s.scope);s.scope===`project`&&(Ds(e,Ts(`skill`,``,s.toName),`skill-rename: ${L} -> ${B}`,[{from:L,to:B}]),await Os(`skill-move`));let H=su(s.scope);if(H){let e=await removeSkillInstall(H,s.fromName);if(e){let t=resolvedHosts(e.hosts);reverseProjectSkill(s.fromName,H,t);let S=projectSkill(resolve(g,s.toName),s.toName,H,t);await recordSkillInstall(H,s.toName,{...e,hosts:S})}}if(fe?.(`files`),w){let e=w.code===`WRITE_ERROR`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${s.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:w.code,cause:Error(w.message)});return}successResponse(t,200,SkillMoveSuccessSchema,{from:L,to:B,committed:S.committed},{handler:`skill-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`});function xu(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function Su(e,t,s){return e===`project`&&t===`reference`&&s.toLowerCase().endsWith(`.md`)}function Cu(e,t){let s=t.replace(/\.md$/i,``);return`${projectSkillContentDocName(e).replace(/\/SKILL$/,``)}/${s}`}function wu(e,t){let s=resolve(e,t,`references`);if(!existsSync(s))return[];let g=[],S=(e,t)=>{for(let s of readdirSync(e,{withFileTypes:!0})){let w=t?`${t}/${s.name}`:s.name;s.isDirectory()?S(resolve(e,s.name),w):s.isFile()&&s.name.toLowerCase().endsWith(`.md`)&&g.push(`references/${w}`)}};return S(s,``),g}function Tu(e,t,s){if(!ue)return;let g=(e,t,s)=>{let g;try{g=readFileSync(s,`utf-8`)}catch{ue.deleteDocument(e),de?.deleteDocument(e);return}ue.renameDocument(e,t,g),de?.renameDocument(e,t,g)};g(projectSkillContentDocName(t),projectSkillContentDocName(s),resolve(e,s,`SKILL.md`));for(let S of wu(e,s))g(Cu(t,S),Cu(s,S),resolve(e,s,S));fe?.(`backlinks`),fe?.(`graph`)}let Eu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!eu(g,t,`skill-file-get`))return;let S=tu(s.searchParams.get(`scope`),t,`skill-file-get`);if(S===null)return;let w=s.searchParams.get(`path`)??``,E=xu(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let D=resolve(ru(S),g),O=resolve(D,w);if(O!==D&&!O.startsWith(`${D}${sep}`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let k=O,j=w;if(!existsSync(k)){let e=w.match(/^(.*)\.(?:md|mdx)$/),s=e?SUPPORTED_DOC_EXTENSIONS.map(t=>`${e[1]}${t}`).find(e=>e!==w&&existsSync(resolve(D,e))):void 0;if(s===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${w} not found in skill "${g}" (${S}).`});return}j=s,k=resolve(D,s)}let F=await readFile$1(k);if(F.includes(0)){errorResponse(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}successResponse(t,200,SkillFileGetSuccessSchema,{path:j.replace(/\\/g,`/`),kind:E,text:F.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),Du=withValidation(SkillFilePutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!eu(g.name,t,`skill-file-put`))return;let S=xu(g.path);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(g.content,`utf-8`)>262144){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let w=ru(g.scope);if(!existsSync(resolve(w,g.name,`SKILL.md`))){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${g.name}" before adding bundle files.`});return}let E=g.path.replace(/\\/g,`/`),D=Su(g.scope,S,E),O;if(D){let e=Cu(g.name,E);if(Gl(e,`skill-file-put`,t))return;if(O=!existsSync(resolve(w,g.name,E)),O&&countBundleFiles(resolve(w,g.name))>=50){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${g.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:S,agentName:D,colorSeed:k,clientName:j}=Xi(g),F=await s.getSession(e,S,{displayName:D,colorSeed:k,clientName:j});F.dc.document.transact(()=>{composeAndWriteRawBody(F.dc.document,g.content,`agent`)},F.origin);let L=await Ut(e);if(L?.kind===`failure`){Wt(t,L.failure,`skill-file-put`);return}if(L?.kind===`divergence`){Kt(t,`skill-file-put`);return}}else{let e=applySkillBundleFileWrite({skillsRoot:w,name:g.name,relPath:E,content:g.content});if(!e.ok){let s=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;errorResponse(t,s,s===500?`urn:ok:error:internal-server-error`:s===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,s===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}O=e.created}g.scope===`project`&&(Ds(e,Ts(`skill`,``,g.name),`${O?`skill-file-create`:`skill-file-edit`}: .ok/skills/${g.name}/${E}`),await Os(`skill-file-put`)),fe?.(`files`),successResponse(t,200,SkillFilePutSuccessSchema,{path:E,created:O,kind:S,content:D},{handler:`skill-file-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),Ou=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams,g=s.get(`name`)??``;if(!eu(g,t,`skill-file-delete`))return;let S=tu(s.get(`scope`),t,`skill-file-delete`);if(S===null)return;let w=(s.get(`path`)??``).replace(/\\/g,`/`),E=xu(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let D=extractActorIdentity({agentId:s.get(`agentId`)??void 0,agentName:s.get(`agentName`)??void 0,colorSeed:s.get(`colorSeed`)??void 0,clientName:s.get(`clientName`)??void 0,clientVersion:s.get(`clientVersion`)??void 0,label:s.get(`label`)??void 0,summary:s.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let O=ru(S);Su(S,E,w)&&await Vr([Cu(g,w)],`deleted-upstream`);let k=applySkillBundleFileDelete({skillsRoot:O,name:g,relPath:w});if(!k.ok){let e=k.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:k.error.code,cause:Error(k.error.message)});return}k.existed&&S===`project`&&(Ds(D,Ts(`skill`,``,g),`skill-file-delete: .ok/skills/${g}/${w}`),await Os(`skill-file-delete`)),k.existed&&fe?.(`files`),successResponse(t,200,SkillFileDeleteSuccessSchema,{path:w,existed:k.existed,kind:E},{handler:`skill-file-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0});async function ku(e,t){if(e.method===`GET`)return Eu(e,t);if(e.method===`PUT`)return Du(e,t);if(e.method===`DELETE`)return Ou(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-file`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Au=withValidation(SkillInstallRequestSchema,async(e,t,s)=>{try{let e=ru(s.scope);if(!eu(s.name,t,`skill-install`))return;if(s.scope===`project`&&!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let g=su(s.scope),S=resolve(e,s.name);if(!existsSync(S)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${s.name}" not found in ${s.scope} scope — create it with write({ skill }) first.`});return}let w=validateSkillForInstall(S,s.name);if(!w.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${s.name}" cannot be installed: ${w.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let E=s.scope===`global`?s.targets?PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)):[...PROJECT_SKILL_EDITOR_IDS]:s.targets===void 0?resolveSkillTargets(g,readSkillTargets(g)??void 0):PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)),D=[],O=[];E.length===0&&s.targets===void 0&&(D.push(s.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),O.push(`no-targets`)),w.hasScripts&&(D.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),O.push(`scripts-present`));let k=resolvedHosts(readInstalledSkills(g).skills[s.name]?.hosts??[]).filter(e=>!E.includes(e));k.length>0&&reverseProjectSkill(s.name,g,k);let j=projectSkill(S,s.name,g,E);j.length===0?await removeSkillInstall(g,s.name):await recordSkillInstall(g,s.name,{hosts:j,scope:s.scope,scripts:w.hasScripts,installedAt:new Date().toISOString()}),fe?.(`files`),successResponse(t,200,SkillInstallSuccessSchema,{name:s.name,hosts:j,scripts:w.hasScripts,warnings:D,warningCodes:O},{handler:`skill-install`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),ju=withValidation(SkillUninstallRequestSchema,async(e,t,s)=>{try{if(!eu(s.name,t,`skill-uninstall`))return;let e=su(s.scope);if(!e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let g=await cu(e,s.name);fe?.(`files`),successResponse(t,200,SkillUninstallSuccessSchema,{name:s.name,uninstalled:g},{handler:`skill-uninstall`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`});async function Mu(e,t){if(e.method===`GET`)return Nu(e,t);if(e.method===`PUT`)return Pu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-targets`,extraHeaders:{Allow:`GET, PUT`}})}let Nu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=Ce?readSkillTargets(Ce):null;successResponse(t,200,SkillTargetsGetSuccessSchema,{targets:resolveSkillTargets(Ce??``,e??void 0),configured:e!==null},{handler:`skill-targets-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),Pu=withValidation(SkillTargetsPutRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let e=s.targets,g=new Set(e),S=resolveSkillTargets(Ce,readSkillTargets(Ce)??void 0),w=ru(`project`);await writeSkillTargets(Ce,e);let{reprojected:E,bundleHosts:D}=await reprojectAllManagedSkills({projectDir:Ce,skillsRoot:w,targets:e});fe?.(`files`),successResponse(t,200,SkillTargetsPutSuccessSchema,{targets:e,reprojected:E,bundleHosts:D,removedFrom:S.filter(e=>!g.has(e))},{handler:`skill-targets-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`}),Fu=withValidation(SkillRestoreRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!eu(s.name,t,`skill-restore`))return;if(s.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let S=ee?.current;if(!S){errorResponse(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let w=await restoreSkillVersion({shadow:S,contentDir:g,contentRoot:ce??`.`,name:s.name,version:s.version});if(!w.ok){let[e,s]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[w.code];errorResponse(t,e,s,w.error,{handler:`skill-restore`,detail:w.code});return}let E=[],D=validateSkillForInstall(resolve(g,`.ok`,`skills`,s.name),s.name);D.ok||E.push(`Restored, but the skill no longer validates: ${D.errors.join(` `)}`),E.push("Run `install` to push the restored version to your editors."),Ds(e,Ts(`skill`,``,s.name),`skill-restore: ${s.name} @ ${s.version.slice(0,8)}`),await Os(`skill-restore`),fe?.(`files`),successResponse(t,200,SkillRestoreSuccessSchema,{name:s.name,version:s.version,restoredFiles:w.restoredFiles,warnings:E},{handler:`skill-restore`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Iu=withValidation(SkillUpdateRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!eu(g.name,t,`skill-update`))return;if(!isPackSkillName(g.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(g.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let S=readBundledPackSkill(g.name);if(S===null||S.version===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let w=resolve(ru(`project`),g.name,`SKILL.md`);if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let E;try{E=readSkillVersion(readFileSync(w,`utf-8`))}catch{}let D,O=ee?.current;if(O)try{let e=oe?.()??`main`;D=(await saveVersion(O,ce??`.`,[SERVICE_WRITER],e,`Before updating ${g.name} (${E??`unversioned`} → ${S.version})`)).checkpointRef}catch(e){getLogger(`skills`).warn({err:e,skill:g.name},`pre-update checkpoint failed — proceeding with overwrite`)}let k=skillLiveDocName(`project`,g.name);if(Gl(k,`skill-update`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Xi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-update`);return}if(q?.kind===`divergence`){Kt(t,`skill-update`);return}Ds(e,Ts(`skill`,``,g.name),`skill-pack-update: ${g.name} (${E??`unversioned`} → ${S.version})`),await Os(`skill-update`),fe?.(`files`),successResponse(t,200,SkillUpdateSuccessSchema,{name:g.name,version:S.version,...E===void 0?{}:{previousVersion:E},...D===void 0?{}:{checkpointRef:D}},{handler:`skill-update`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function Lu(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 Ru(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}`.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,`�`)}function zu(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Bu(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`||e===`file`);return s.length>0?s:void 0}function Vu(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Hu(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function Uu(e,t,s,g){let S=g.documents.filter(e=>!isHiddenDocName(e.path)),w=S.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!Be?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:w,capable:!1};Be.embedCorpus(S);let E,D=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await Be.queryScores(e,S);if(D=performance.now()-t,s&&s.size>0){let e=Ve?.();E=e===void 0?{scores:s}:{scores:s,similarityFloor:e}}}let O=Be.getStatus();return{input:E,status:{capable:O.capable,applied:!1,coverage:{embedded:O.embeddedCount,total:w}},queryEmbedMs:D,pageTotal:w,capable:O.capable}}function Wu(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`?Ru(e.document.content,t):void 0}}async function Gu(e){let t=performance.now();if(ed())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:s,truncated:g}=await td(),S=await Uu(e.query,e.intent,e.semanticParam,s),w=searchWorkspaceCorpus(s,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:S.input}).map(t=>Wu(t,e.query)),E;if(S.status){let t=w.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),s=t>0;E={...S.status,applied:s},recordSemanticQuery({outcome:S.capable?s?`applied`:S.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:S.capable,embedded:S.status.coverage.embedded,total:S.pageTotal,queryEmbedMs:S.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:w,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...E?{semantic:E}:{},...g?{truncated:!0}:{}}}function Ku(){let e=ru(`project`);if(!existsSync(e))return[];let t;try{t=readdirSync(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let g of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!g.isDirectory()||!SKILL_NAME_REGEX.test(g.name))continue;let t=resolve(e,g.name,`SKILL.md`);try{let e=statSync(t);s.push({name:g.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return s}function qu(){let e=[];for(let t of Ku()){let s=t.name,g=``;try{let{frontmatter:e,body:S}=Jl(readFileSync(t.absolutePath,`utf-8`));typeof e.name==`string`&&e.name&&(s=e.name),g=`${typeof e.description==`string`?e.description:``}\n\n${S}`.trim()}catch{}e.push(createWorkspaceSearchDocument({kind:`page`,path:skillLiveDocName(`project`,t.name),title:s,content:g,modifiedTs:t.mtimeMs}))}return e}function Ju(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let Yu=new Map;async function Xu(){let e=[],t=[],s=new Set;for(let[g,S]of D()){if(isSystemDoc(g)||isConfigDoc(g)||g.startsWith(`.ok/skills/`))continue;if(S.kind===`file`){t.push(createWorkspaceSearchDocument({kind:`file`,path:g,modifiedTs:Date.parse(S.modified),aliases:S.aliases}));continue}s.add(g);let w=Ju(S),E=Yu.get(g);if(E&&E.key===w){e.push(E.doc);continue}let D=``,O=g,k=!1;try{D=await readFile$1(S.canonicalPath,`utf-8`)}catch(e){k=!0,console.warn(`[search] Failed to read ${g}:`,e)}if(!k)try{O=extractPageTitle(D,g)}catch(e){console.warn(`[search] Failed to extract title for ${g}:`,e)}let j=createWorkspaceSearchDocument({kind:`page`,path:g,title:O,content:D,modifiedTs:Date.parse(S.modified),aliases:S.aliases});k||Yu.set(g,{key:w,doc:j}),e.push(j)}for(let e of Yu.keys())s.has(e)||Yu.delete(e);let g=getSearchMaxEntries(),S=t,w=!1;return t.length>g&&(w=!0,S=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,g),getLogger(`search`).warn({dropped:t.length-S.length,retained:S.length,limit:g},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),searchCorpusTruncatedCounter().add(1)),{documents:[...e,...qu(),...S,...Lu([...e,...S])],truncated:w}}function Zu(){return Ku().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function Qu(){return k?`gen:${k()}|skills${Zu()}`:`${[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${Ju(t)}`).join(``)}|skills${Zu()}`}let $u=Pe===void 0;Pe?.then(()=>{$u=!0},e=>{$u=!0,log$7.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function ed(){return!$u}async function td(){let e=`${g}${Ce??``}`,t=Qu(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return{corpus:s.corpus,truncated:s.truncated??!1};if(s?.fingerprint===t&&s.pending)return s.pending;let S=Xu().then(({documents:e,truncated:t})=>({corpus:createWorkspaceSearchCorpus(e),truncated:t}));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.corpus,truncated:s.truncated}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function nd(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{td().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}nd();async function rd(e,t){if(e.method===`GET`)return ad(e,t);if(e.method===`POST`)return od(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let ad=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=zu(s.searchParams.get(`intent`)),E=au(s.searchParams.get(`ranking`)),D=Bu(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),O=Vu(s.searchParams.get(`semantic`)),k=Hu(s.searchParams.get(`source`)),j=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 Gu({query:S,intent:w,ranking:E,scopes:D,limit:j,semanticParam:O,source:k}),{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}),od=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=zu(s.intent),w=au(s.ranking),E=Bu(s.scopes??s.scope),D=typeof s.limit==`number`?s.limit:void 0,O=Vu(s.semantic),k=Hu(s.source);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 Gu({query:g,intent:S,ranking:w,scopes:E,limit:D,semanticParam:O,source:k}),{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`}),sd=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 cd(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform,isSchemeRegistered:Et.probeWithCache})}catch(e){t.headersSent||(log$7.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 ld(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$7.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 ud=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!Ce){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=s.kind===`doc`?s.docPath:s.folderPath;if(!isValidSharePath(e,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 S=readGitHeadBranch(Ce);if(S===null){if(readOriginGitHubRepo(Ce).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 w=readOriginGitHubRepo(Ce);if(w.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(w.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(Ce,S)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:S},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let E=toGitRelativePath(Ce,g);if(E===null)throw Error(`content dir is not contained within the project dir`);let D=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;E!==``&&D&&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 O;if(s.kind===`doc`)O=buildGitHubBlobUrl(w.owner,w.repo,S,s.docPath);else{let e=s.folderPath===``?E:s.folderPath;O=buildGitHubTreeUrl(w.owner,w.repo,S,e)}let k=`${SHARE_BASE_URL}${encodeShareUrl(O)}`,j=await computeShareFreshness(Ce,S,E===``?e:e===``?E:`${E}/${e}`,s.kind);emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind,freshness:j}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:k,sharedUrl:O,branch:S,freshness:j},{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})}),dd=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!Ce){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(Ce,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}),fd=withValidation(ShareTargetStatusRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}if(!isValidBranchInfoPath(s.path,s.kind)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}let e=toGitRelativePath(Ce,g);if(e===null)throw Error(`content dir is not contained within the project dir`);let S=e===``?s.path:s.path===``?e:`${e}/${s.path}`;successResponse(t,200,ShareTargetStatusResponseSchema,await computeShareTargetStatus(Ce,s.branch,S,s.kind),{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG,cause:e})}},{handler:SHARE_TARGET_STATUS_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}),pd=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!Ce){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(Ce,s.branch,{fastForward:s.fastForward===!0})),{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 md(e){let[t,...s]=ye,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 hd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.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 md([`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{Ge.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})}),gd=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(!Ge.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 md([`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{Ge.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})}),_d=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!Ce){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(!Ge.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`,Ce,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await md(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&ve?.()?.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{Ge.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),vd=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`})}),yd=Ce?getLocalDir(Ce):null;async function bd(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}yd&&clearArmedPaneTarget(yd),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:yd?readServerLock(yd)?.port??0:0,paneTarget:yd?readArmedPaneTarget(yd):null,singleFile:We};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 xd=`local-op-embeddings-set-key`,Sd=`local-op-embeddings-clear-key`,Cd=`/api/local-op/embeddings`,wd=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Ge.tryAcquire(Cd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:xd,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(Ue).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:xd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:xd,cause:e})}finally{Ge.release(Cd)}},{handler:xd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:xd})}),Td=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(Cd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Sd,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(Ue),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:Sd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Sd,cause:e})}finally{Ge.release(Cd)}},{handler:Sd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Sd})}),Ed=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(Be){let t=Be.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(Ue).get(),D=process.env.OK_EMBEDDINGS_API_KEY??null,O=E?`file`:D?`env`:null,k=O!==null,j=E??D,F=j&&j.length>=8?j.slice(-4):null,L=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(L+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:k,keySource:O,keyHint:F,ready:s,capable:g,embedded:S,total:L},{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}),Dd={"/api/config":bd,"/api/asset":Tc,"/api/asset-text":Dc,"/api/document":Is,"/api/documents":Rs,"/api/backlinks":$s,"/api/backlink-counts":ec,"/api/forward-links":tc,"/api/link-graph":nc,"/api/dead-links":ac,"/api/orphans":rc,"/api/hubs":ic,"/api/tags":Pl,"/api/pages":Lc,"/api/folder-config":Vl,"/api/template":ql,"/api/templates":Kl,"/api/skill":du,"/api/skill-file":ku,"/api/skills":uu,"/api/skills/management":gu,"/api/skill/install":Au,"/api/skill/uninstall":ju,"/api/skill/restore":Fu,"/api/skill/update":Iu,"/api/skill-targets":Mu,"/api/search":rd,"/api/semantic-status":Ed,"/api/suggest-links":Rc,"/api/page-headings":Nc,"/api/create-page":Ac,"/api/create-folder":jc,"/api/duplicate-path":Mc,"/api/rename-path":Pc,"/api/delete-path":Fc,"/api/trash/cleanup":Ic,"/api/upload":zc,"/api/agent-write":ks,"/api/agent-write-md":As,"/api/frontmatter-patch":Ns,"/api/agent-patch":oc,"/api/agent-undo":sc,"/api/agent-activity":cc,"/api/agent-burst-diff":lc,"/api/save-version":mc,"/api/history":hc,"/api/rollback":_c,"/api/metrics/reconciliation":vc,"/api/metrics/parse-health":yc,"/api/metrics/agent-presence":Sc,"/api/__embed-detect":Cc,"/api/server-info":bc,"/api/share/construct-url":ud,"/api/share/target-status":fd,"/api/git/branch-info":dd,"/api/git/checkout":pd,"/api/share/publish/owners":hd,"/api/share/publish/name-check":gd,"/api/share/publish":_d,"/api/principal":xc,"/api/rescue":kc,"/api/workspace":wc,"/api/sync/status":yl,"/api/sync/trigger":xl,"/api/sync/conflicts":Cl,"/api/sync/conflict-content":El,"/api/sync/resolve-conflict":Tl,"/api/local-op/clone":Gc,"/api/local-op/ok-init":Yc,"/api/local-op/auth/login":al,"/api/local-op/auth/status":ul,"/api/local-op/auth/repos":fl,"/api/local-op/auth/signout":hl,"/api/local-op/auth/set-identity":vl,"/api/local-op/embeddings/set-key":wd,"/api/local-op/embeddings/clear-key":Td,"/api/installed-agents":Ml,"/api/spawn-cursor":ld,"/api/handoff":cd,"/api/install-skill":jl,"/api/skill/install-state":sd,"/api/seed/plan":Dl,"/api/seed/apply":Ol,"/api/seed/packs":kl,"/api/client-logs":vd};q&&(Dd[`/api/test-reset`]=dc,Dd[`/api/test-flush-git`]=uc,Dd[`/api/test-rescan-backlinks`]=fc,Dd[`/api/test-rescan-files`]=pc);let Od=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-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),kd=[`/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(Od.has(s)||kd.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(We&&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`:Dd[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=Dd[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 gc(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await Fl(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 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=toPosix(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)}var AutoStartDisabledError=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const log$6=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$6.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$6.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$6.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-DjEtQkHv-DQXg1XhZ.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(!isWithinDir(g,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$6.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let{splitNulSeparatedPaths:e}=await import(`./git-handle-DjEtQkHv-DQXg1XhZ.mjs`),t=e(await w.git.raw([`diff`,`--name-only`,`--diff-filter=U`,`-z`]));for(let e of t)this.addConflict({file:e,detectedAt:s});g=t.length>0}catch(e){log$6.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$6.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 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_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 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 SPAWN_TIMEOUT_MS=2e3,LOCK_SCAN_MAX_DEPTH=3,LOCK_SCAN_MAX_ENTRIES=2e3,OK_LOCK_DIR_ARG_PREFIX=`--ok-lock-dir-b64=`,OK_PROJECT_PATH_ARG_PREFIX=`--ok-project-path=`,OK_PROCESS_PGREP_QUERY=`cli\\.mjs|open-knowledge|Open ?Knowledge(\\.app| Helper)|--ok-lock-dir-b64=|--ok-project-path=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`,OK_PROCESS_PATTERNS=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function isOkProcess(e){return OK_PROCESS_PATTERNS.some(t=>t.test(e))}function extractMarkedLockDir(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(OK_LOCK_DIR_ARG_PREFIX));if(t==null)return null;let s=t.slice(18);if(!s)return null;try{let e=Buffer.from(s,`base64url`).toString(`utf8`);return isAbsolute(e)?e:null}catch{return null}}function extractProjectPathArg(e){let t=e.indexOf(OK_PROJECT_PATH_ARG_PREFIX);if(t===-1)return null;let s=t+18,g=e.slice(s),S=g.search(/\s--/),w=(S===-1?g:g.slice(0,S)).trim();return w&&isAbsolute(w)?w:null}function parsePgrepOutput(e){let t=[];for(let s of e.split(`
|
|
1946
|
+
`:``)+t;composeAndWriteRawBody(te.dc.document,S,`agent`),recordFrontmatterEditSurface(`mcp-write`),ce=!0}se=!0},te.origin)})}finally{ge?.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;case`invalid_path`:e={[oe.path.map(String).join(`.`)||`__path__`]: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(se&&ue.length>0){if(recordContributor(D,O,k,j,void 0,Ra({clientName:F,clientVersion:L,label:B}),Y),incrementAgentWriteCalls(),so(ee),ce){let e=await Ut(D);if(e?.kind===`failure`){Wt(w,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Xt(w,`frontmatter-patch`);return}}Ht(D,`frontmatter-patch`)}me?.setFocus(O,{agentName:k,currentDoc:D,writeKind:`write`,ts:Date.now()}),_e?.();let de=Bt(D),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(F)});let ve=Zt(ne);rn(D,te.dc.document.getText(`source`).toString());let ye=en();ye.add(D);let Ce=computeBrokenOutboundLinks(te.dc.document.getText(`source`).toString(),D,ye,tn);successResponse(w,200,FrontmatterPatchSuccessSchema,{timestamp:ae,subscriberCount:de,systemSubscriberCount:fe,appliedKeys:ue,...J?{summary:J}:{},...ve?{warning:ve,warnings:[ve]}:{},brokenLinks:Ce},{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$7.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 Ms(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 Ns=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=zt(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:Ms(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:Ms(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}),Ps=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$7.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`),E=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(E&&De&&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:De,dirFilter:S,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$7.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$7.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(E&&De){let e=`showAll:${O===1?`d1:`:``}${S??``}`,s=Ke.get(e);if(!s){let t=new AbortController,w=(async()=>{let e=[],s=getShowAllMaxEntries(),{truncated:w}=await walkContentDirForShowAll({contentDir:g,contentFilter:De,dirFilter:S,documents:e,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$7.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;Ke.set(e,E),w.finally(()=>{Ke.get(e)===E&&Ke.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(),Ke.get(e)===w&&Ke.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(),F=D(),L=j?.()??new Map,H=[];for(let[e,t]of L)S&&!e.startsWith(`${S}/`)&&e!==S||H.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let q=[];try{let e=vt(k);$e?.signature!==e&&($e={signature:e,assets:collectReferencedAssets({contentDir:g,fileIndex:k,readMarkdown:e=>{try{return readFileSync(e,`utf-8`)}catch{return null}},isExcluded:De?e=>De.isPathIgnored(e):void 0})}),q=$e?.assets??[]}catch(e){$e=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}let ee=new Set;for(let e of q)S&&!e.path.startsWith(`${S}/`)&&e.path!==S||(ee.add(e.path),H.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}));for(let[e,t]of F){if(t.kind===`markdown`){if(S&&!e.startsWith(`${S}/`)&&e!==S)continue;let s=getDocExtension(e);H.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=toPosix(relative(g,t.canonicalPath));H.push({kind:`document`,docName:w,docExt:s,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:E})}continue}if((!S||e===S||e.startsWith(`${S}/`))&&!ee.has(e)){let s=synthesizeShowAllAssetExt(e);H.push({kind:`file`,docName:e,path:e,docExt:`.${s}`,assetExt:s,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let s of t.aliases){if(!(!S||s===S||s.startsWith(`${S}/`))||ee.has(s))continue;let w=toPosix(relative(g,t.canonicalPath)),E=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${E}`,assetExt:E,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:w})}}let J=B?.()??new Map;if(J.size>0){let e=e=>!S||e===S||e.startsWith(`${S}/`),t=new Map;for(let[e,s]of J){let g=t.get(s);g?g.push(e):t.set(s,[e])}for(let[s,S]of t){let t=L.get(s),w=t?toPosix(relative(g,t.canonicalPath)):s;for(let g of S)e(g)&&H.push({kind:`folder`,path:g,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:s,targetPath:w})}let s=(s,g)=>{for(let S=s.indexOf(`/`);S!==-1;S=s.indexOf(`/`,S+1)){let w=t.get(s.slice(0,S));if(!w)continue;let E=s.slice(S);for(let t of w){let s=`${t}${E}`;e(s)&&g(s)}}};for(let[e,t]of L)s(e,s=>{H.push({kind:`folder`,path:s,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:toPosix(relative(g,t.canonicalPath))})});for(let[e,t]of F)s(e,s=>{let S=toPosix(relative(g,t.canonicalPath));if(t.kind===`markdown`)H.push({kind:`document`,docName:s,docExt:getDocExtension(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S});else{let g=synthesizeShowAllAssetExt(s);H.push({kind:`file`,docName:s,path:s,docExt:`.${g}`,assetExt:g,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:S})}})}H.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:H},{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}),Is=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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:ue.getBacklinks(s).map(e=>({source:e.source,anchor:e.anchor,title:jt(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}),Ls=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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]=ue.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}),Rs=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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=en();successResponse(t,200,ForwardLinksSuccessSchema,{docName:s,forwardLinks:ue.getForwardLinkEntries(s).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Mt(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}),ec=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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}=ue.getLinkGraphNeighborhood(g,e))}else ({nodes:w,links:E}=ue.getLinkGraph());let D=en();successResponse(t,200,LinkGraphSuccessSchema,{nodes:w.map(e=>{if(e.kind===`doc`){let t=Lt(e.docName,D);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Mt(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}),tc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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:ue.getOrphans([...w().keys()],s).map(e=>({docName:e,title:jt(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}),nc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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=en();successResponse(t,200,HubsSuccessSchema,{hubs:ue.getHubs(S).map(e=>({docName:e.docName,title:Mt(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}),rc=withValidation(EmptyRequestSchema,async(e,t)=>{if(!ue){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=>zt(e)))]:void 0;successResponse(t,200,DeadLinksSuccessSchema,{deadLinks:ue.getDeadLinks(en(),g).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:jt(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}),ic=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=zt(k),{agentId:F,agentName:L,colorSeed:B,clientName:H,clientVersion:q,label:ee}=Qi(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,se=!1,ce;try{let t=iconFromClientName(H),s=AGENT_ICON_COLORS[t]??colorFromSeed(B??F);if(ge?.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){se=!0;return}let{body:E}=stripFrontmatter(g.slice(0,w)+D+g.slice(w+S.length));ce=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),ce!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":j,position:`patch`,intendedBytes:ce.intendedBytes,actualBytes:ce.actualBytes,byteDelta:ce.byteDelta,"agent.id":F,"agent.client_name":H})),!ae&&!oe&&!se){let{stored:e}=eo(J);recordContributor(j,F,L,B,void 0,Ra({clientName:H,clientVersion:q,label:ee}),e),incrementAgentWriteCalls(),so(J),recordContentDivergenceGate(`agent-patch`,ce)}}finally{ge?.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(se){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 ue=await Ut(j);if(ue?.kind===`failure`){Wt(w,ue.failure,`agent-patch`);return}if(ue?.kind===`divergence`){Xt(w,`agent-patch`);return}Ht(j,`agent-patch`),me?.setFocus(F,{agentName:L,currentDoc:j,writeKind:`edit`,ts:Date.now()}),_e?.();let de=Bt(j),fe=Vt();fe===0&&hintEmittedCounter().add(1,{"shadow.writer":`agent`,"agent.type":resolveAgentType(H)});let{response:ve}=eo(J),ye=Y.dc.document.getText(`source`).toString();rn(j,ye);let Ce=await validateMermaidFences(ye,j),we=en();we.add(j);let Te=computeBrokenOutboundLinks(ye,j,we,tn),De=Zt(te),je=ce===void 0?void 0:toContentDivergenceWarning(ce),Me=[...je?[je]:[],...De?[De]:[],...Ce??[]];successResponse(w,200,AgentPatchSuccessSchema,{timestamp:ne,subscriberCount:de,systemSubscriberCount:fe,...ve?{summary:ve}:{},...je?{warning:je}:De?{warning:De}:{},...Me.length>0?{warnings:Me}:{},brokenLinks:Te},{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$7.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`}),ac=withValidation(AgentUndoRequestSchema,async(t,g,S)=>{try{let t=requireNonEmptyDocName(S.docName,g,`agent-undo`);if(t===null)return;let w=zt(t),{agentId:E,agentName:D,colorSeed:O,clientName:k,clientVersion:j,label:F}=Qi(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);ge?.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,Ra({clientName:k,clientVersion:j,label:F}))}finally{ge?.touchMode(E,`idle`)}if(q){let e=await Ut(w);if(e?.kind===`failure`){Wt(g,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Xt(g,`agent-undo`);return}Ht(w,`agent-undo`)}me?.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$7.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`}),oc=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$7.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}),sc=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=zt(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$7.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}),cc=withValidation(EmptyRequestSchema,async(e,t)=>{try{await J?.(),successResponse(t,200,TestFlushGitSuccessSchema,{},{handler:`test-flush-git`})}catch(e){log$7.error({err:e},`[test-flush-git] flush failed`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:e})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),lc=withValidation(EmptyRequestSchema,async(e,S)=>{try{let w=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),E=zt(w.searchParams.get(`docName`)??`test-doc`),D;try{D=safeContentPath(E,g)}catch(e){log$7.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(Me??t.unloadDocument.bind(t))(k),writeFileSync(D,``,`utf-8`),ue&&(ue.deleteDocument(E),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${E}:`,e)}),fe?.(`backlinks`),fe?.(`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`),De&&await De.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}fe?.(`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}),uc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ue){errorResponse(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ue.rebuildFromDisk(),await ue.ingestGlobalSkillBundles([resolve(cu,`.ok`,`skills`)]),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),fe?.(`backlinks`),fe?.(`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}),dc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!H){errorResponse(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await H(),fe?.(`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}),fc=withValidation(SaveVersionRequestSchema,async(e,t,s)=>{try{let{rawAgentId:e,agentId:g,agentName:S,clientName:w}=Qi(s),E=ee?.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=[],k=!1;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}let j=oe?.()??`main`;if(O.length===0)if(e!==void 0)O=[{id:g,name:w?`${S} (${w})`:S,email:`${g}@openknowledge.local`}];else{let e=(await enumerateWipChains(E,j)).filter(e=>!e.isPark);O=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[SERVICE_WRITER],k=!0}let F=ce??`.`,L=normalizeSummary(typeof s.summary==`string`?s.summary:void 0),B=await saveVersion(E,F,O,j,L.kind===`value`?L.value:void 0,k?{includeUpstream:!1}:void 0);getLogger(`history`).info({checkpointRef:B.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:B.checkpointRef},{handler:`save-version`})}catch(e){log$7.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`}),pc=withValidation(EmptyRequestSchema,async(e,t)=>{let s=ee?.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`)??oe?.()??`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=Hl(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),j=`folder\0${E}\0${e.folderRel}\0${D}\0${k}`,{promise:F,coalesced:L}=Xe.run(j,()=>getFolderTimeline(s,e.folderRel,ce??`.`,{branch:E,limit:D,offset:k}));L&&recordTimelineCoalesced(`folder`),successResponse(t,200,HistorySuccessSchema,{...await F},{handler:`history`});return}let D=ce??`.`,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`),F=Math.min(200,Number.isFinite(k)?k:50),L=Number.isFinite(j)?j:0,B=g.searchParams.get(`type`)??void 0,H=g.searchParams.get(`author`)??void 0,q=g.searchParams.get(`excludeAuthor`)??void 0,J=g.searchParams.get(`includeAutoCheckpoints`)===`true`,Y=`doc\0${E}\0${S}\0${F}\0${L}\0${B??``}\0${H??``}\0${q??``}\0${J?`1`:`0`}`,te=Date.now();try{let{promise:e,coalesced:g}=Xe.run(Y,()=>getDocumentHistory(s,{docName:S,branch:E,limit:F,offset:L,type:B,author:H,excludeAuthor:q,includeAutoCheckpoints:J},D));g&&recordTimelineCoalesced(`doc`);let w=await e,O=Date.now()-te;getLogger(`timeline`).info({docName:S,entries:w.entries.length,durationMs:O},`query`),successResponse(t,200,HistorySuccessSchema,{...w},{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 mc(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=ee?.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=ce??`.`,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=oe?.()??`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 hc=withValidation(RollbackRequestSchema,async(s,g,S)=>{let w=extractActorIdentity(S,we);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:docNameToRelativePath(S.docName)}),`rollback`);return}let D=ee?.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=ce??`.`,F=safeDocPath(O,j);if(`error`in F){errorResponse(g,400,`urn:ok:error:invalid-request`,F.error,{handler:`rollback`});return}let L=shadowGit(D),B=Date.now();try{let s=getOrLoadRenameLogIndex(D.gitDir),S=createAncestorShaSetCache(),E=await resolveDocPathAtCommit(D,O,k,oe?.()??`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 L.raw(`show`,`${k}:${E}`),H=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,J;q.transact(()=>{replaceRawBody(q,F,ee),J=evaluateContentDivergence(q.getText(`source`).toString(),F,`rollback`)},ROLLBACK_ORIGIN),J!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":O,position:`rollback`,intendedBytes:J.intendedBytes,actualBytes:J.actualBytes,byteDelta:J.byteDelta,"actor.kind":w.kind,...w.kind===`agent`||w.kind===`principal`?{"actor.writer_id":w.writerId}:{}})),recordContentDivergenceGate(`rollback`,J);let Y;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=eo(s);Y=t||!g.response?g.response:to(g.response),recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,g.stored),incrementAgentWriteCalls(),so(s,!t);break}case`principal`:{let e=eo(w.summary);Y=e.response,recordContributor(O,w.writerId,w.displayName,w.colorSeed,formatRollbackSubject(O,k),w.actor,e.stored),so(w.summary,!1);break}case`anonymous`:log$7.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 te=await Ut(O);if(te?.kind===`failure`){Wt(g,te.failure,`rollback`);return}if(te?.kind===`divergence`){Xt(g,`rollback`);return}Ht(O,`rollback`);let ne=Date.now()-B;getLogger(`rollback`).info({docName:O,from:k.slice(0,8),durationMs:ne},`rollback`),w.kind===`agent`&&me?.setFocus(w.writerId,{agentName:w.displayName,currentDoc:O,writeKind:`rollback-apply`,ts:Date.now()});let ae=J===void 0?void 0:toContentDivergenceWarning(J);successResponse(g,200,RollbackSuccessSchema,{restoredFrom:k,timestamp:H,...Y?{summary:Y}:{},...ae?{warning:ae,warnings:[ae]}:{}},{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`}),gc=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsReconciliationSuccessSchema,getMetrics(),{handler:`metrics-reconciliation`})}catch(e){log$7.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}),_c=withValidation(EmptyRequestSchema,async(e,t)=>{try{successResponse(t,200,MetricsParseHealthSuccessSchema,getParseHealth(),{handler:`metrics-parse-health`})}catch(e){log$7.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}),vc=withValidation(EmptyRequestSchema,async(e,t)=>{try{Pe&&await Pe.catch(e=>{log$7.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=se?.(),g=getBootTimings();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s},...g===void 0?{}:{boot:g}},{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 yc(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=we?.()??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 bc(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=ge?.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$7.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 xc(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 Sc(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 Cc=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(De?.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$7.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}),wc=1048576,Tc=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>wc){errorResponse(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${wc}-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}),Ec=1440*60*1e3,Dc=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!ee?.current){successResponse(t,200,RescueListSuccessSchema,[],{handler:`rescue-list`});return}let e=Date.now(),s=[],g=resolve(ee.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$7.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=oe?.()??`main`,t=await listRescueCheckpoints(ee.current,e);for(let e of t)s.push({...e,source:`timeline`})}catch(e){log$7.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}),Oc=withValidation(CreatePageRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);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 w=resolve(g),E=resolve(w,S);if(!isWithinDir(E,w)){errorResponse(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let D=stripDocExtension(S);if(isSystemDoc(D)||isConfigDoc(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`});return}if(S.split(`/`)[0]===`.ok`||isManagedArtifactDocName(D)){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${D}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page under .ok/ — skills and templates are authored through their own validating flows.`});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(w,s),E=g.find(e=>e.name===k);if(!E){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(w,E.path),O;try{O=readFileSync(D,`utf-8`)}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${E.path}.`,{handler:`create-page`,cause:e});return}let L=instantiateDoc(O),B=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;j=applySubstitution(L,{date:todayIsoUtc(),user:B}),F=E.scope}mkdirSync(dirname(E),{recursive:!0});try{writeFileSync(E,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(Ie?.delete(L),De&&De.incrementMdDir(dirname(L)),registerWrite(E,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)}`)}O?.({kind:`create`,path:E,docName:L,content:j}),ue&&(ue.updateDocumentFromMarkdown(L,j),ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${L}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`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`}),kc=withValidation(CreateFolderRequestSchema,async(e,t,s)=>{try{if(extractActorIdentity(s,we).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(De?.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}),it(e),fe?.(`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`}),Ac=withValidation(DuplicatePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);if(e.kind===`invalid-summary`){errorResponse(s,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:w}=S,E=S.path,D=w===`file`?stripDocExtension(E):E;if(!isValidRelativeContentPath(E)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(E===`.ok`||E.startsWith(`.ok/`)||w===`file`&&(isSystemDoc(D)||isConfigDoc(D))||w===`folder`&&isReservedSyntheticFolderPath(E)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}w===`file`&&probeAndRegisterSourceFileExtension(g,E);let k=resolveContentEntryPath(g,w,E);if(!existsSync(k)){if(w===`file`){let e=resolveContentEntryPath(g,`folder`,E);if(existsSync(e)&&statSync(e).isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}}errorResponse(s,404,`urn:ok:error:doc-not-found`,`${w} does not exist.`,{handler:`duplicate-path`});return}let j=statSync(k);if(w===`file`&&!j.isFile()||w===`folder`&&!j.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}let F=w===`file`?[docNameForFileOperationPath(g,E)]:Gi(resolveContentEntryPath(g,`folder`,E)),L=ve?.(),B=new Set(L?L.getConflicts().map(e=>e.file):[]);for(let e of F){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=B.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let H,q=[];if(w===`file`){let e=extname(k);if(H=nextAvailableDuplicateDocName(g,D).docName,isSystemDoc(H)||isConfigDoc(H)||De?.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(k,`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 j=!1;try{registerDocExtension(H,e),Ie?.delete(H),De&&(De.incrementMdDir(dirname(H)),j=!0),registerWrite(t,contentHash(S)),O?.({kind:`create`,path:t,docName:H,content:S}),ue?.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),De&&j&&De.decrementMdDir(dirname(H)),O?.({kind:`delete`,path:t,docName:H}),e}}else{if(H=nextAvailableDuplicateFolderPath(g,E).folderPath,De?.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(k,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))it(e);let e=collectMarkdownCopies(g,H);q=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(stripDocExtension(t.docName),e),Ie?.delete(t.docName),De&&De.incrementMdDir(dirname(t.docName)),registerWrite(t.fullPath,contentHash(t.content)),O?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),ue?.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)}`)}ue&&q.length>0&&(ue.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),successResponse(s,200,DuplicatePathSuccessSchema,{kind:w,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`}),jc=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=Et(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}),Mc=withValidation(RenamePathRequestSchema,async(e,s,S)=>{try{let e=extractActorIdentity(S,we);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}let O=w===`asset`&&isSupportedDocFile(E)&&isSupportedDocFile(D)?`file`:w;if(O===`asset`){let t;try{t=isSupportedDocFile(E)&&!isSupportedDocFile(D)?await Yi(E,D):await Ji(E,D)}catch(e){if(e instanceof DocInConflictError){respondDocInConflict(s,e,`rename-path`);return}let{status:t,type:g,error:S}=zr(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&St();let g;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let s=`Renamed asset ${E} → ${D}`;g=_s(e,s,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:s})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{log$7.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}),Y)try{await Y()}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}O===`file`&&probeAndRegisterSourceFileExtension(g,E);let k=O===`file`?[docNameForFileOperationPath(g,E)]:Gi(resolveContentEntryPath(g,`folder`,E)),j=ve?.(),F=new Set(j?j.getConflicts().map(e=>e.file):[]);for(let e of k){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=F.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`rename-path`);return}}if(De){let e=isSupportedDocFile(E)?extname(E):getDocExtension(E);if(O===`file`?De.isExcluded(isSupportedDocFile(D)?D:`${D}${e}`):De.isDirExcluded(D)){errorResponse(s,400,`urn:ok:error:invalid-request`,`Destination ${O===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let L=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,B;try{B=await Xi(E,D,O,L?{actor:L}:{})}catch(e){if(e instanceof ManagedRenameCollisionError){errorResponse(s,409,`urn:ok:error:doc-already-exists`,Mr(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(B.renamed.length===0&&B.renamedAssets.length===0){successResponse(s,200,RenamePathSuccessSchema,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}B.renamedAssets.length>0&&St();let H,q=B.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(q.length>0&&(H=_s(e,`Renamed ${E} → ${D}`,q.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:formatRenameSubject(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{log$7.debug({kind:w,fromPath:E,toPath:D,affectedDocs:B.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),renameAttributionCounter().add(1,{kind:`rename-${O}`,attribution_kind:e.kind}),Y)try{await Y()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}successResponse(s,200,RenamePathSuccessSchema,{renamed:B.renamed,renamedAssets:B.renamedAssets,rewrittenDocs:B.rewrittenDocs,...H?{summary:H}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:g,error:S}=zr(e);errorResponse(s,t,g,S,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Nc=withValidation(DeletePathRequestSchema,async(e,s,S)=>{try{Qi(S);let{kind:e,path:w}=S;if(!isValidRelativeContentPath(w)){errorResponse(s,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let E=e===`asset`?Qr(w):{path:w,ambiguous:!1};if(E.ambiguous){errorResponse(s,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let D=E.path,k=e===`asset`&&isSupportedDocFile(D)?`file`:e;if(k===`file`&&probeAndRegisterSourceFileExtension(g,D),k===`asset`&&isReservedProjectStatePath(D)){errorResponse(s,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let j=k===`asset`?resolveContentEntryPath(g,`folder`,D):resolveContentEntryPath(g,k,D);if(!existsSync(j)){errorResponse(s,404,`urn:ok:error:doc-not-found`,`${k} does not exist.`,{handler:`delete-path`});return}let F=statSync(j);if(k===`file`&&!F.isFile()||k===`asset`&&!F.isFile()||k===`folder`&&!F.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${k}.`,{handler:`delete-path`});return}let L=k===`asset`?[]:k===`file`?[docNameForFileOperationPath(g,D)]:Gi(resolveContentEntryPath(g,`folder`,D)),B=ve?.(),H=new Set(B?B.getConflicts().map(e=>e.file):[]);for(let e of L){let g=e,S=t.documents.get(g),w=docNameToRelativePath(g),E=S!==void 0&&isDocInConflict(S),D=H.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`delete-path`);return}}if(await Br(L,`deleted-upstream`),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));k===`file`||k===`asset`?tracedUnlinkSync(j):(tracedRmSync(j,{recursive:!0,force:!1}),at(D)),St();for(let e of L)O?.({kind:`delete`,path:resolve(g,docNameToRelativePath(e)),docName:e});fe?.(`files`),successResponse(s,200,DeletePathSuccessSchema,{deletedDocNames:L},{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`}),Pc=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,we).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===`asset`&&isSupportedDocFile(S)?`file`:e,D=stripDocExtension(S);E===`file`&&probeAndRegisterSourceFileExtension(g,S);let k=E===`folder`&&isReservedSyntheticFolderPath(S),j=E===`asset`&&isReservedProjectStatePath(S);if(E===`file`&&(isSystemDoc(D)||isConfigDoc(D))||k||j){errorResponse(t,400,`urn:ok:error:reserved-doc-name`,`'${S}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(E===`asset`){St(),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let F=w(),L=E===`file`?F.has(D)?[D]:[]:listAffectedDocNames(F,E,S);if(St(),L.length===0){successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Br(L,`deleted-upstream`),Ie)for(let e of L)isSystemDoc(e)||isConfigDoc(e)||(Ie.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of L)O?.({kind:`delete`,path:resolve(g,docNameToRelativePath(e)),docName:e});E===`folder`&&at(S),fe?.(`files`),successResponse(t,200,TrashCleanupSuccessSchema,{deletedDocNames:L},{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`}),Fc=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=w(),s=[];for(let[t,S]of e){let e=getDocExtension(t),w,E;if(S.title!==void 0)w=S.title,E=S.icon;else{w=t;try{let s=readFileSync(resolve(g,`${t}${e}`),`utf-8`);w=extractPageTitle(s,t),E=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}}s.push({docName:t,title:w,docExt:e,size:S.size,modified:S.modified,icon:E})}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}),Ic=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 Lc(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,Ce??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:D,byteLength:O,parentDocName:k,placement:j}=s,F=()=>{if(existsSync(w))try{unlinkSync(w)}catch{}},L=validateBody(UploadRequestSchema,{parentDocName:k,placement:j||void 0},t,{handler:`upload-asset`});if(!L.ok){F();return}let{parentDocName:B,placement:H}=L.value,{agentId:q,agentName:ee}=Qi(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(O===0){F(),errorResponse(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(B.includes(`\0`)||B.includes(`..`)||B.startsWith(`/`)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let J=resolve(g),Y;try{Y=H===`parent-dir`?`./`:E?.()??`./`}catch(e){F(),log$7.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),errorResponse(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!isValidAttachmentFolderPath(Y)){F(),errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let te=resolveUploadDestDir(B,normalizeAttachmentFolderPath(Y),J);if(!isWithinContentDir(te,J)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{assertNoSymlinkEscape(te,J)}catch(e){if(F(),(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$7.error({err:e,destDir:te},`[upload] failed to validate destination directory`),errorResponse(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{mkdirSync(te,{recursive:!0})}catch(e){if(!isAlreadyExistsError(e)){F();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(te),s;try{s=realpathSync(J)}catch{s=J}if(!isWithinContentDir(e,s)){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){F(),errorResponse(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let ne=readTempFileHead(w,4100),ae=await fileTypeFromBuffer(ne),oe=ae?.mime,se=ae?.ext;if(!oe){let e=ne.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(oe=`image/svg+xml`,se=`svg`)}{let s=await findDuplicateAsset(te,D,O);if(s){F();let S=toPosix(relative(g,resolve(te,s)));log$7.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!0,mime:oe??null,size:O,destPath:S,httpStatus:200},`[upload] dedup hit`),successResponse(t,200,UploadAssetSuccessSchema,{src:s,path:S,deduped:!0},{handler:`upload-asset`});return}}let ce;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=se??t??``;ce=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else ce=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,te,ce),S=toPosix(relative(g,resolve(te,s)));log$7.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!1,mime:oe??null,size:O,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$7.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,filename:ce,size:O,reason:g,httpStatus:uploadStatusFor(g),err:s},`[upload] write failed`),errorResponse(t,uploadStatusFor(g),g,uploadTitleFor(g),{handler:`upload-asset`,cause:s})}}let Rc=`/api/local-op/clone`,zc=`/api/local-op/ok-init`,Bc=600*1e3,Vc=45e3,Hc=`local-op-clone`,Uc=withValidation(LocalOpCloneRequestSchema,Wc,{handler:Hc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Hc})});async function Wc(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:Hc,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:Hc,cause:Error(`dir=${S}`)});return}if(!Ge.tryAcquire(Rc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Hc,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,Hc),D=null,O=runCloneSubprocess({cliArgs:ye,url:g,dir:S,branch:w,timeoutMs:Bc,onEvent:e=>{if(e.type===`complete`){D=e.dir;return}if(e.type===`error`){e.message&&log$7.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 Gc(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$7.error({err:e,handler:Hc},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ge.release(Rc)}})(),t.on(`close`,()=>{O.cancel()})}async function Gc(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]=ye,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$7.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$7.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 Kc=`local-op-ok-init`,qc=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:Kc,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:Kc});return}if(!isSafeLocalPath(S)){errorResponse(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Kc,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:Kc});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:Kc});return}if(!Ge.tryAcquire(zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Kc,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:Kc})}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:Kc})}finally{Ge.release(zc)}},{handler:Kc,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Kc})}),Jc=`/api/local-op/auth/login`,Yc=`/api/local-op/auth/status`,Xc=`/api/local-op/auth/repos`,Zc=`/api/local-op/auth/signout`,Qc=null,$c=`local-op-auth-login`,dl=withValidation(LocalOpAuthHostRequestSchema,ml,{handler:$c,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:$c})});async function ml(e,t,s){let g=s.host??`github.com`;if(!Ge.tryAcquire(Jc)){let e=Qc;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:$c,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),Qc=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,$c),w=runDeviceFlowSubprocess({cliArgs:ye,host:g,timeoutMs:Bc,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,ve),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});Qc=w;let E=()=>{w.cancel(),Qc===w&&(Qc=null,Ge.release(Jc))};t.on(`close`,E),w.done.finally(()=>{if(t.off(`close`,E),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}Qc===w&&(Qc=null,Ge.release(Jc))})}let hl=`local-op-auth-status`,gl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire(Yc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:hl,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,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(`
|
|
1947
|
+
`).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:hl}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,E,{handler:hl})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:hl,cause:e})}finally{Ge.release(Yc)}},{handler:hl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:hl})}),_l=`local-op-auth-repos`,vl=withValidation(LocalOpAuthHostRequestSchema,yl,{handler:_l,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:_l})});async function yl(e,t,s){let g=s.host??`github.com`;if(!Ge.tryAcquire(Xc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:_l,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,_l),[w,...E]=ye,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`)},Bc);j.stdout.on(`data`,e=>{k+=e.toString(`utf-8`);let s=k.split(`
|
|
1948
|
+
`);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$7.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(),Ge.release(Xc))}),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()),Ge.release(Xc))}),t.on(`close`,()=>{O||(O=!0,clearTimeout(F),j.kill(`SIGTERM`),Ge.release(Xc))})}let xl=`local-op-auth-signout`,Cl=withValidation(LocalOpAuthHostRequestSchema,async(e,t,s)=>{let g=s.host??`github.com`;if(!Ge.tryAcquire(Zc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:xl,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...s]=ye,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:xl})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:xl,cause:e})}finally{Ge.release(Zc)}},{handler:xl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:xl})}),Tl=`/api/local-op/auth/set-identity`,El=`local-op-auth-set-identity`,Dl=withValidation(LocalOpAuthSetIdentityRequestSchema,async(e,t,s)=>{let g=s.name.trim(),S=s.email.trim();if(!Ce){errorResponse(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:El});return}if(!Ge.tryAcquire(Tl)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:El,extraHeaders:{"Retry-After":`5`}});return}try{writeGitIdentity(Ce,g,S),ve?.()?.refreshIdentity().catch(()=>{}),successResponse(t,200,LocalOpAuthEmptySuccessSchema,{},{handler:El})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:El,cause:e})}finally{Ge.release(Tl)}},{handler:El,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:El})});async function Ol(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=ve?.();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 kl=withValidation(SyncTriggerRequestSchema,async(e,t,s)=>{let g=ve?.();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`})?ve?.()?!0:(errorResponse(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function jl(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=ve?.();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 Ml=withValidation(SyncResolveConflictRequestSchema,async(e,t,s)=>{let g=ve?.();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`})?ve?.()?!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(!Ce){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=ve?.(),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:Ce,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=Re?Re(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 Fl(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 Il=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 Ll(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 Rl=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 zl(e,t){if(checkLocalOpSecurity(e,t,{handler:`installed-agents`}))try{await handleInstalledAgents(e,t,Tt.probeAll)}catch(e){t.headersSent||(log$7.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 Bl=withValidation(EmptyRequestSchema,async(e,t)=>{if(!de){errorResponse(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{successResponse(t,200,TagsListSuccessSchema,{tags:de.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 Vl(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(!de){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=de.getDocsForTagWithMatches(g).map(({docName:e,matchingTags:t})=>({docName:e,title:jt(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 Hl(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 Ul=/^[A-Za-z0-9_-]+$/;function Wl(e,t,s=`template`){return!e||!Ul.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 Gl(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 Kl(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 ql(e,t){if(e.method===`GET`)return Jl(e,t);if(e.method===`PUT`)return Yl(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=Hl(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}),Yl=withValidation(FolderConfigPutRequestSchema,async(e,t,s)=>{try{if(We){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,we);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=Hl(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`&&(Cs(e,xs(`folder-frontmatter`,g.folderRel),`folder-frontmatter-${w.action===`deleted`?`delete`:`edit`}: ${w.path}`),await Ts(`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 Xl(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}function Zl(e,s,g){let S=t.documents.get(e);return S&&isDocInConflict(S)?(respondDocInConflict(g,new DocInConflictError({file:`${e}.md`}),s),!0):!1}let Ql=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 $l(e,t){if(e.method===`GET`)return tu(e,t);if(e.method===`PUT`)return nu(e,t);if(e.method===`POST`)return iu(e,t);if(e.method===`DELETE`)return ru(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let eu=e=>{let{frontmatter:t,body:s}=stripFrontmatter(e),g={};if(t!==``)try{let e=(0,import_dist$1.parse)(unwrapFrontmatterFences(t));e&&typeof e==`object`&&!Array.isArray(e)&&(g=e)}catch{}return{frontmatter:g,body:s}},tu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Wl(g,t,`template-get`))return;let S=Hl(s.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!S)return;let{folderRel:w,resolvedContentDir:E}=S,D=Gl(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,F=parseTemplateFile(await readFile$1(O,`utf-8`)),L=F.identity,B=F.starterContent;successResponse(t,200,TemplateGetSuccessSchema,{template:{name:g,folder:k,scope:j,path:relative(E,O).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:L,body:B}},{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}),nu=withValidation(TemplatePutRequestSchema,async(e,t,g)=>{try{if(We){errorResponse(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let S=g.name;if(!Wl(S,t,`template-put`))return;let w=Hl(g.folder,t,`folder`,`template-put`);if(!w||Xl(w.folderRel,S,`template-put`,t))return;let E=composeTemplateContent({name:S,body:typeof g.body==`string`?g.body:``,frontmatter:Kl(g.frontmatter)});if(!E.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:E.error.code,cause:Error(E.error.message)});return}let D=resolve(w.resolvedContentDir,w.folderRel,`.ok`,`templates`,`${S}.md`),O=!existsSync(D),k=relative(w.resolvedContentDir,D).split(/[\\/]/).filter(Boolean).join(`/`),j=uu(w.folderRel,S),{agentId:F,agentName:L,colorSeed:B,clientName:H}=Qi(g),q=await s.getSession(j,F,{displayName:L,colorSeed:B,clientName:H});q.dc.document.transact(()=>{composeAndWriteRawBody(q.dc.document,E.content,`agent`)},q.origin);let ee=await Ut(j);if(ee?.kind===`failure`){Wt(t,ee.failure,`template-put`);return}if(ee?.kind===`divergence`){Xt(t,`template-put`);return}Cs(e,xs(`template`,w.folderRel,S),`${O?`template-create`:`template-edit`}: ${k}`),await Ts(`template-put`),successResponse(t,200,TemplatePutSuccessSchema,{path:k,created:O,warnings:E.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`}),ru=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!Wl(g,t,`template-delete`))return;let S=Hl(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},we);if(E.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Xl(S.folderRel,g,`template-delete`,t))return;await Br([uu(S.folderRel,g)],`deleted-upstream`);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&&(Cs(E,xs(`template`,S.folderRel,g),`template-delete: ${D.path}`),await Ts(`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}),iu=withValidation(TemplateMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Wl(s.fromName,t,`template-move`)||!Wl(s.toName,t,`template-move`))return;let g=Hl(s.fromFolder,t,`folder`,`template-move`);if(!g)return;let S=Hl(s.toFolder,t,`folder`,`template-move`);if(!S||Xl(g.folderRel,s.fromName,`template-move`,t))return;await Br([uu(g.folderRel,s.fromName)],`renamed`);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(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!w.ok){if(w.error.code===`TEMPLATE_NOT_FOUND`){let e=Gl(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=instantiateDoc(readFileSync(resolve(S.resolvedContentDir,w.toPath),`utf-8`))}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:Kl(s.frontmatter)});t.ok||(E=t.error)}}if(Cs(e,xs(`template`,S.folderRel,s.toName),`template-rename: ${w.fromPath} -> ${w.toPath}`,[{from:w.fromPath,to:w.toPath}]),await Ts(`template-move`),fe?.(`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`}),au=500;function ou(e,t,s){return!e||e.length>64||!SKILL_NAME_REGEX.test(e)?(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:s}),!1):!0}function su(e,t,s){let g=SkillScopeSchema.safeParse(e??`project`);return g.success?g.data:(errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:s}),null)}let cu=Te??homedir();function lu(e){return resolve(e===`global`?cu:g,`.ok`,`skills`)}function uu(e,t){return`${MANAGED_ARTIFACT_PREFIX_TEMPLATE}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function du(e){return e===`navigation`||e===`relevance`?e:void 0}function fu(e,t){return relative(t===`global`?cu:g,e).split(/[\\/]/).filter(Boolean).join(`/`)}function pu(e){return e===`global`?cu:Ce}async function mu(e,t){let s=await removeSkillInstall(e,t);return reverseProjectSkill(t,e,PROJECT_SKILL_EDITOR_IDS),s!==null}function hu(e,t){let s=[];if(!existsSync(e))return{skills:s,truncated:!1};let g;try{g=readdirSync(e,{withFileTypes:!0})}catch(g){return getLogger(`skills`).warn({err:g,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:s,truncated:!1}}let S=!1;for(let w of g.sort((e,t)=>e.name.localeCompare(t.name))){if(!w.isDirectory()||!SKILL_NAME_REGEX.test(w.name))continue;if(s.length>=500){S=!0;break}let g=resolve(e,w.name,`SKILL.md`);if(!existsSync(g))continue;let E,D;try{let{frontmatter:e}=eu(readFileSync(g,`utf-8`));typeof e.description==`string`&&(E=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(D=e.version)}catch{}s.push({name:w.name,...E===void 0?{}:{description:E},scope:t,path:fu(g,t),absolutePath:g,...D===void 0?{}:{installedVersion:D}})}return{skills:s,truncated:S}}let gu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=hu(lu(`project`),`project`),s=hu(lu(`global`),`global`),g=Ce?readInstalledSkills(Ce).skills:{},S=readInstalledSkills(cu).skills,w=(e,t)=>e.skills.map(e=>{let s=t[e.name]?.hosts??[],g=computePackUpdateStatus(e.name,e.installedVersion);return{...e,installed:s.length>0,hosts:s,...g}});successResponse(t,200,SkillsListSuccessSchema,{skills:[...w(e,g),...w(s,S)],truncated:e.truncated||s.truncated},{handler:`skills-list`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list skills.`,{handler:`skills-list`,cause:e})}},{handler:`skills-list`,method:`GET`,skipBodyParse:!0});async function _u(e,t){if(e.method===`GET`)return Cu(e,t);if(e.method===`PUT`)return wu(e,t);if(e.method===`POST`)return Eu(e,t);if(e.method===`DELETE`)return Tu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let vu=object$1({managed:boolean().nullable(),importable:number().int().nonnegative()}),yu=()=>({managed:Ce?readSkillManagement(Ce)?.manageEditorSkills??null:null,importable:Ce?countImportableEditorSkills({projectDir:Ce,skillsRoot:lu(`project`)}):0}),bu=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}successResponse(t,200,vu,yu(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),xu=withValidation(object$1({manageEditorSkills:boolean()}),async(e,t,s)=>{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await writeSkillManagement(Ce,{manageEditorSkills:s.manageEditorSkills,surface:`ui`}),s.manageEditorSkills){let e=await reconcileSkillInstalls({projectDir:Ce,skillsRoot:lu(`project`)});e.adopted.length+e.collided.length>0&&fe?.(`files`)}successResponse(t,200,vu,yu(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`});async function Su(e,t){if(e.method===`GET`)return bu(e,t);if(e.method===`PUT`)return xu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skills-management`,extraHeaders:{Allow:`GET, PUT`}})}let Cu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!ou(g,t,`skill-get`))return;let S=su(s.searchParams.get(`scope`),t,`skill-get`);if(S===null)return;let w=lu(S),E=resolve(w,g,`SKILL.md`);if(!existsSync(E)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${g}" not found in ${S} scope.`});return}let{frontmatter:D,body:O}=eu(await readFile$1(E,`utf-8`));successResponse(t,200,SkillGetSuccessSchema,{skill:{name:g,scope:S,path:fu(E,S),frontmatter:{name:typeof D.name==`string`?D.name:g,description:typeof D.description==`string`?D.description:``},body:O,files:readSkillBundledFiles(resolve(w,g))}},{handler:`skill-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),wu=withValidation(SkillPutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!ou(g.name,t,`skill-put`))return;let S=composeSkillContent({name:g.name,body:typeof g.body==`string`?g.body:``,frontmatter:{name:g.frontmatter.name,description:g.frontmatter.description}});if(!S.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:S.error.code,cause:Error(S.error.message)});return}let w=lu(g.scope),E=resolve(w,g.name,`SKILL.md`),D=!existsSync(E),O=relative(w,E).split(/[\\/]/).filter(Boolean).join(`/`),k=skillLiveDocName(g.scope,g.name);if(Zl(k,`skill-put`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Qi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-put`);return}if(q?.kind===`divergence`){Xt(t,`skill-put`);return}g.scope===`project`&&(Cs(e,xs(`skill`,``,g.name),`${D?`skill-create`:`skill-edit`}: ${O}`),await Ts(`skill-put`)),fe?.(`files`),successResponse(t,200,SkillPutSuccessSchema,{path:O,created:D,warnings:S.warnings},{handler:`skill-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),Tu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!ou(g,t,`skill-delete`))return;let S=su(s.searchParams.get(`scope`),t,`skill-delete`);if(S===null)return;let w=lu(S),E=s.searchParams,D=extractActorIdentity({agentId:E.get(`agentId`)??void 0,agentName:E.get(`agentName`)??void 0,colorSeed:E.get(`colorSeed`)??void 0,clientName:E.get(`clientName`)??void 0,clientVersion:E.get(`clientVersion`)??void 0,label:E.get(`label`)??void 0,summary:E.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Br([skillLiveDocName(S,g)],`deleted-upstream`);let O=applySkillDelete({skillsRoot:w,name:g});if(!O.ok){let e=O.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:O.error.code,cause:Error(O.error.message)});return}O.existed&&(S===`project`&&(Cs(D,xs(`skill`,``,g),`skill-delete: ${O.path}`),await Ts(`skill-delete`)),fe?.(`files`));let k=pu(S);k&&await mu(k,g),successResponse(t,200,SkillDeleteSuccessSchema,{existed:O.existed,path:O.path},{handler:`skill-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),Eu=withValidation(SkillMoveRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!ou(s.fromName,t,`skill-move`)||!ou(s.toName,t,`skill-move`))return;let g=lu(s.scope);await Br([skillLiveDocName(s.scope,s.fromName)],`renamed`);let S=await applySkillMove({skillsRoot:g,fromName:s.fromName,toName:s.toName,relocate:async(e,t)=>{let s=await renameTrackedPathInGit(Ce,e,t);return s||renamePathOnDisk(e,t),s}});if(!S.ok){if(S.error.code===`SKILL_NOT_FOUND`){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:S.error.message});return}if(S.error.code===`SKILL_EXISTS`){errorResponse(t,409,`urn:ok:error:doc-already-exists`,S.error.message,{handler:`skill-move`,detail:S.error.code});return}let e=S.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 skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:S.error.code,cause:Error(S.error.message)});return}let w=null,E=resolve(g,s.toName,`SKILL.md`),D=``,O=``;try{let e=eu(readFileSync(E,`utf-8`));D=e.body,typeof e.frontmatter.description==`string`&&(O=e.frontmatter.description)}catch{}let k=typeof s.body==`string`?s.body:D,j=s.frontmatter===void 0?O:s.frontmatter.description,F=applySkillWrite({skillsRoot:g,name:s.toName,body:k,frontmatter:{name:s.toName,description:j}});if(F.ok||(w=F.error),s.scope===`project`&&!w)try{ju(g,s.fromName,s.toName)}catch(e){getLogger(`skill-move`).warn({err:e,fromName:s.fromName,toName:s.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let L=fu(resolve(g,s.fromName),s.scope),B=fu(resolve(g,s.toName),s.scope);s.scope===`project`&&(Cs(e,xs(`skill`,``,s.toName),`skill-rename: ${L} -> ${B}`,[{from:L,to:B}]),await Ts(`skill-move`));let H=pu(s.scope);if(H){let e=await removeSkillInstall(H,s.fromName);if(e){let t=resolvedHosts(e.hosts);reverseProjectSkill(s.fromName,H,t);let S=projectSkill(resolve(g,s.toName),s.toName,H,t);await recordSkillInstall(H,s.toName,{...e,hosts:S})}}if(fe?.(`files`),w){let e=w.code===`WRITE_ERROR`;errorResponse(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${s.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:w.code,cause:Error(w.message)});return}successResponse(t,200,SkillMoveSuccessSchema,{from:L,to:B,committed:S.committed},{handler:`skill-move`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`});function Du(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function Ou(e,t,s){return e===`project`&&t===`reference`&&s.toLowerCase().endsWith(`.md`)}function ku(e,t){let s=t.replace(/\.md$/i,``);return`${projectSkillContentDocName(e).replace(/\/SKILL$/,``)}/${s}`}function Au(e,t){let s=resolve(e,t,`references`);if(!existsSync(s))return[];let g=[],S=(e,t)=>{for(let s of readdirSync(e,{withFileTypes:!0})){let w=t?`${t}/${s.name}`:s.name;s.isDirectory()?S(resolve(e,s.name),w):s.isFile()&&s.name.toLowerCase().endsWith(`.md`)&&g.push(`references/${w}`)}};return S(s,``),g}function ju(e,t,s){if(!ue)return;let g=(e,t,s)=>{let g;try{g=readFileSync(s,`utf-8`)}catch{ue.deleteDocument(e),de?.deleteDocument(e);return}ue.renameDocument(e,t,g),de?.renameDocument(e,t,g)};g(projectSkillContentDocName(t),projectSkillContentDocName(s),resolve(e,s,`SKILL.md`));for(let S of Au(e,s))g(ku(t,S),ku(s,S),resolve(e,s,S));fe?.(`backlinks`),fe?.(`graph`)}let Mu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`name`)??``;if(!ou(g,t,`skill-file-get`))return;let S=su(s.searchParams.get(`scope`),t,`skill-file-get`);if(S===null)return;let w=s.searchParams.get(`path`)??``,E=Du(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let D=resolve(lu(S),g),O=resolve(D,w);if(O!==D&&!O.startsWith(`${D}${sep}`)){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let k=O,j=w;if(!existsSync(k)){let e=w.match(/^(.*)\.(?:md|mdx)$/),s=e?SUPPORTED_DOC_EXTENSIONS.map(t=>`${e[1]}${t}`).find(e=>e!==w&&existsSync(resolve(D,e))):void 0;if(s===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${w} not found in skill "${g}" (${S}).`});return}j=s,k=resolve(D,s)}let F=await readFile$1(k);if(F.includes(0)){errorResponse(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}successResponse(t,200,SkillFileGetSuccessSchema,{path:j.replace(/\\/g,`/`),kind:E,text:F.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),Nu=withValidation(SkillFilePutRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!ou(g.name,t,`skill-file-put`))return;let S=Du(g.path);if(S===null){errorResponse(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(g.content,`utf-8`)>262144){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let w=lu(g.scope);if(!existsSync(resolve(w,g.name,`SKILL.md`))){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${g.name}" before adding bundle files.`});return}let E=g.path.replace(/\\/g,`/`),D=Ou(g.scope,S,E),O;if(D){let e=ku(g.name,E);if(Zl(e,`skill-file-put`,t))return;if(O=!existsSync(resolve(w,g.name,E)),O&&countBundleFiles(resolve(w,g.name))>=50){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${g.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:S,agentName:D,colorSeed:k,clientName:j}=Qi(g),F=await s.getSession(e,S,{displayName:D,colorSeed:k,clientName:j});F.dc.document.transact(()=>{composeAndWriteRawBody(F.dc.document,g.content,`agent`)},F.origin);let L=await Ut(e);if(L?.kind===`failure`){Wt(t,L.failure,`skill-file-put`);return}if(L?.kind===`divergence`){Xt(t,`skill-file-put`);return}}else{let e=applySkillBundleFileWrite({skillsRoot:w,name:g.name,relPath:E,content:g.content});if(!e.ok){let s=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;errorResponse(t,s,s===500?`urn:ok:error:internal-server-error`:s===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,s===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}O=e.created}g.scope===`project`&&(Cs(e,xs(`skill`,``,g.name),`${O?`skill-file-create`:`skill-file-edit`}: .ok/skills/${g.name}/${E}`),await Ts(`skill-file-put`)),fe?.(`files`),successResponse(t,200,SkillFilePutSuccessSchema,{path:E,created:O,kind:S,content:D},{handler:`skill-file-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),Pu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let s=new URL(e.url??``,`http://localhost`).searchParams,g=s.get(`name`)??``;if(!ou(g,t,`skill-file-delete`))return;let S=su(s.get(`scope`),t,`skill-file-delete`);if(S===null)return;let w=(s.get(`path`)??``).replace(/\\/g,`/`),E=Du(w);if(E===null){errorResponse(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let D=extractActorIdentity({agentId:s.get(`agentId`)??void 0,agentName:s.get(`agentName`)??void 0,colorSeed:s.get(`colorSeed`)??void 0,clientName:s.get(`clientName`)??void 0,clientVersion:s.get(`clientVersion`)??void 0,label:s.get(`label`)??void 0,summary:s.get(`summary`)??void 0},we);if(D.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let O=lu(S);Ou(S,E,w)&&await Br([ku(g,w)],`deleted-upstream`);let k=applySkillBundleFileDelete({skillsRoot:O,name:g,relPath:w});if(!k.ok){let e=k.error.code===`UNLINK_FAILED`?500:400;errorResponse(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:k.error.code,cause:Error(k.error.message)});return}k.existed&&S===`project`&&(Cs(D,xs(`skill`,``,g),`skill-file-delete: .ok/skills/${g}/${w}`),await Ts(`skill-file-delete`)),k.existed&&fe?.(`files`),successResponse(t,200,SkillFileDeleteSuccessSchema,{path:w,existed:k.existed,kind:E},{handler:`skill-file-delete`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0});async function Fu(e,t){if(e.method===`GET`)return Mu(e,t);if(e.method===`PUT`)return Nu(e,t);if(e.method===`DELETE`)return Pu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-file`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Iu=withValidation(SkillInstallRequestSchema,async(e,t,s)=>{try{let e=lu(s.scope);if(!ou(s.name,t,`skill-install`))return;if(s.scope===`project`&&!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let g=pu(s.scope),S=resolve(e,s.name);if(!existsSync(S)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${s.name}" not found in ${s.scope} scope — create it with write({ skill }) first.`});return}let w=validateSkillForInstall(S,s.name);if(!w.ok){errorResponse(t,400,`urn:ok:error:invalid-request`,`Skill "${s.name}" cannot be installed: ${w.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let E=s.scope===`global`?s.targets?PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)):[...PROJECT_SKILL_EDITOR_IDS]:s.targets===void 0?resolveSkillTargets(g,readSkillTargets(g)??void 0):PROJECT_SKILL_EDITOR_IDS.filter(e=>s.targets?.some(t=>t===e)),D=[],O=[];E.length===0&&s.targets===void 0&&(D.push(s.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),O.push(`no-targets`)),w.hasScripts&&(D.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),O.push(`scripts-present`));let k=resolvedHosts(readInstalledSkills(g).skills[s.name]?.hosts??[]).filter(e=>!E.includes(e));k.length>0&&reverseProjectSkill(s.name,g,k);let j=projectSkill(S,s.name,g,E);j.length===0?await removeSkillInstall(g,s.name):await recordSkillInstall(g,s.name,{hosts:j,scope:s.scope,scripts:w.hasScripts,installedAt:new Date().toISOString()}),fe?.(`files`),successResponse(t,200,SkillInstallSuccessSchema,{name:s.name,hosts:j,scripts:w.hasScripts,warnings:D,warningCodes:O},{handler:`skill-install`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Lu=withValidation(SkillUninstallRequestSchema,async(e,t,s)=>{try{if(!ou(s.name,t,`skill-uninstall`))return;let e=pu(s.scope);if(!e){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let g=await mu(e,s.name);fe?.(`files`),successResponse(t,200,SkillUninstallSuccessSchema,{name:s.name,uninstalled:g},{handler:`skill-uninstall`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`});async function Ru(e,t){if(e.method===`GET`)return zu(e,t);if(e.method===`PUT`)return Bu(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-targets`,extraHeaders:{Allow:`GET, PUT`}})}let zu=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=Ce?readSkillTargets(Ce):null;successResponse(t,200,SkillTargetsGetSuccessSchema,{targets:resolveSkillTargets(Ce??``,e??void 0),configured:e!==null},{handler:`skill-targets-get`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),Bu=withValidation(SkillTargetsPutRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let e=s.targets,g=new Set(e),S=resolveSkillTargets(Ce,readSkillTargets(Ce)??void 0),w=lu(`project`);await writeSkillTargets(Ce,e);let{reprojected:E,bundleHosts:D}=await reprojectAllManagedSkills({projectDir:Ce,skillsRoot:w,targets:e});fe?.(`files`),successResponse(t,200,SkillTargetsPutSuccessSchema,{targets:e,reprojected:E,bundleHosts:D,removedFrom:S.filter(e=>!g.has(e))},{handler:`skill-targets-put`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`}),Vu=withValidation(SkillRestoreRequestSchema,async(e,t,s)=>{try{let e=extractActorIdentity(s,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!ou(s.name,t,`skill-restore`))return;if(s.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let S=ee?.current;if(!S){errorResponse(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let w=await restoreSkillVersion({shadow:S,contentDir:g,contentRoot:ce??`.`,name:s.name,version:s.version});if(!w.ok){let[e,s]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[w.code];errorResponse(t,e,s,w.error,{handler:`skill-restore`,detail:w.code});return}let E=[],D=validateSkillForInstall(resolve(g,`.ok`,`skills`,s.name),s.name);D.ok||E.push(`Restored, but the skill no longer validates: ${D.errors.join(` `)}`),E.push("Run `install` to push the restored version to your editors."),Cs(e,xs(`skill`,``,s.name),`skill-restore: ${s.name} @ ${s.version.slice(0,8)}`),await Ts(`skill-restore`),fe?.(`files`),successResponse(t,200,SkillRestoreSuccessSchema,{name:s.name,version:s.version,restoredFiles:w.restoredFiles,warnings:E},{handler:`skill-restore`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Hu=withValidation(SkillUpdateRequestSchema,async(e,t,g)=>{try{let e=extractActorIdentity(g,we);if(e.kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!ou(g.name,t,`skill-update`))return;if(!isPackSkillName(g.name)){errorResponse(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(g.scope===`global`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let S=readBundledPackSkill(g.name);if(S===null||S.version===void 0){errorResponse(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let w=resolve(lu(`project`),g.name,`SKILL.md`);if(!existsSync(w)){errorResponse(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let E;try{E=readSkillVersion(readFileSync(w,`utf-8`))}catch{}let D,O=ee?.current;if(O)try{let e=oe?.()??`main`;D=(await saveVersion(O,ce??`.`,[SERVICE_WRITER],e,`Before updating ${g.name} (${E??`unversioned`} → ${S.version})`)).checkpointRef}catch(e){getLogger(`skills`).warn({err:e,skill:g.name},`pre-update checkpoint failed — proceeding with overwrite`)}let k=skillLiveDocName(`project`,g.name);if(Zl(k,`skill-update`,t))return;let{agentId:j,agentName:F,colorSeed:L,clientName:B}=Qi(g),H=await s.getSession(k,j,{displayName:F,colorSeed:L,clientName:B});H.dc.document.transact(()=>{composeAndWriteRawBody(H.dc.document,S.content,`agent`)},H.origin);let q=await Ut(k);if(q?.kind===`failure`){Wt(t,q.failure,`skill-update`);return}if(q?.kind===`divergence`){Xt(t,`skill-update`);return}Cs(e,xs(`skill`,``,g.name),`skill-pack-update: ${g.name} (${E??`unversioned`} → ${S.version})`),await Ts(`skill-update`),fe?.(`files`),successResponse(t,200,SkillUpdateSuccessSchema,{name:g.name,version:S.version,...E===void 0?{}:{previousVersion:E},...D===void 0?{}:{checkpointRef:D}},{handler:`skill-update`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function Uu(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 Wu(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}`.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,`�`)}function Gu(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Ku(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`||e===`file`);return s.length>0?s:void 0}function qu(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Ju(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function Yu(e,t,s,g){let S=g.documents.filter(e=>!isHiddenDocName(e.path)),w=S.reduce((e,t)=>e+(t.kind===`page`?1:0),0);if(!Be?.isEnabled()||s!==!0)return{queryEmbedMs:null,pageTotal:w,capable:!1};Be.embedCorpus(S);let E,D=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),s=await Be.queryScores(e,S);if(D=performance.now()-t,s&&s.size>0){let e=Ve?.();E=e===void 0?{scores:s}:{scores:s,similarityFloor:e}}}let O=Be.getStatus();return{input:E,status:{capable:O.capable,applied:!1,coverage:{embedded:O.embeddedCount,total:w}},queryEmbedMs:D,pageTotal:w,capable:O.capable}}function Xu(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`?Wu(e.document.content,t):void 0}}async function Zu(e){let t=performance.now();if(sd())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:s,truncated:g}=await cd(),S=await Yu(e.query,e.intent,e.semanticParam,s),w=searchWorkspaceCorpus(s,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:S.input}).map(t=>Xu(t,e.query)),E;if(S.status){let t=w.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),s=t>0;E={...S.status,applied:s},recordSemanticQuery({outcome:S.capable?s?`applied`:S.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:S.capable,embedded:S.status.coverage.embedded,total:S.pageTotal,queryEmbedMs:S.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:w,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...E?{semantic:E}:{},...g?{truncated:!0}:{}}}function Qu(){let e=lu(`project`);if(!existsSync(e))return[];let t;try{t=readdirSync(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let g of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!g.isDirectory()||!SKILL_NAME_REGEX.test(g.name))continue;let t=resolve(e,g.name,`SKILL.md`);try{let e=statSync(t);s.push({name:g.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return s}function $u(){let e=[];for(let t of Qu()){let s=t.name,g=``;try{let{frontmatter:e,body:S}=eu(readFileSync(t.absolutePath,`utf-8`));typeof e.name==`string`&&e.name&&(s=e.name),g=`${typeof e.description==`string`?e.description:``}\n\n${S}`.trim()}catch{}e.push(createWorkspaceSearchDocument({kind:`page`,path:skillLiveDocName(`project`,t.name),title:s,content:g,modifiedTs:t.mtimeMs}))}return e}function ed(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let td=new Map;async function nd(){let e=[],t=[],s=new Set;for(let[g,S]of D()){if(isSystemDoc(g)||isConfigDoc(g)||g.startsWith(`.ok/skills/`))continue;if(S.kind===`file`){t.push(createWorkspaceSearchDocument({kind:`file`,path:g,modifiedTs:Date.parse(S.modified),aliases:S.aliases}));continue}s.add(g);let w=ed(S),E=td.get(g);if(E&&E.key===w){e.push(E.doc);continue}let D=``,O=g,k=!1;try{D=await readFile$1(S.canonicalPath,`utf-8`)}catch(e){k=!0,console.warn(`[search] Failed to read ${g}:`,e)}if(!k)try{O=extractPageTitle(D,g)}catch(e){console.warn(`[search] Failed to extract title for ${g}:`,e)}let j=createWorkspaceSearchDocument({kind:`page`,path:g,title:O,content:D,modifiedTs:Date.parse(S.modified),aliases:S.aliases});k||td.set(g,{key:w,doc:j}),e.push(j)}for(let e of td.keys())s.has(e)||td.delete(e);let g=getSearchMaxEntries(),S=t,w=!1;return t.length>g&&(w=!0,S=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,g),getLogger(`search`).warn({dropped:t.length-S.length,retained:S.length,limit:g},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),searchCorpusTruncatedCounter().add(1)),{documents:[...e,...$u(),...S,...Uu([...e,...S])],truncated:w}}function rd(){return Qu().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function ad(){return k?`gen:${k()}|skills${rd()}`:`${[...D()].filter(([e])=>!isSystemDoc(e)&&!isConfigDoc(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${ed(t)}`).join(``)}|skills${rd()}`}let od=Pe===void 0;Pe?.then(()=>{od=!0},e=>{od=!0,log$7.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function sd(){return!od}async function cd(){let e=`${g}${Ce??``}`,t=ad(),s=workspaceSearchCaches.get(e);if(s?.fingerprint===t&&s.corpus)return{corpus:s.corpus,truncated:s.truncated??!1};if(s?.fingerprint===t&&s.pending)return s.pending;let S=nd().then(({documents:e,truncated:t})=>({corpus:createWorkspaceSearchCorpus(e),truncated:t}));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.corpus,truncated:s.truncated}),s}catch(t){throw workspaceSearchCaches.get(e)?.pending===S&&workspaceSearchCaches.delete(e),t}}function ld(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{cd().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}ld();async function ud(e,t){if(e.method===`GET`)return dd(e,t);if(e.method===`POST`)return fd(e,t);errorResponse(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let dd=withValidation(EmptyRequestSchema,async(e,t)=>{let s=new URL(e.url??``,`http://localhost`),g=s.searchParams.get(`limit`),S=s.searchParams.get(`query`)??``,w=Gu(s.searchParams.get(`intent`)),E=du(s.searchParams.get(`ranking`)),D=Ku(s.searchParams.get(`scope`)??s.searchParams.get(`scopes`)),O=qu(s.searchParams.get(`semantic`)),k=Ju(s.searchParams.get(`source`)),j=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 Zu({query:S,intent:w,ranking:E,scopes:D,limit:j,semanticParam:O,source:k}),{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}),fd=withValidation(SearchRequestSchema,async(e,t,s)=>{let g=typeof s.query==`string`?s.query:``,S=Gu(s.intent),w=du(s.ranking),E=Ku(s.scopes??s.scope),D=typeof s.limit==`number`?s.limit:void 0,O=qu(s.semantic),k=Ju(s.source);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 Zu({query:g,intent:S,ranking:w,scopes:E,limit:D,semanticParam:O,source:k}),{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`}),pd=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 md(e,t){if(checkLocalOpSecurity(e,t,{handler:`handoff`}))try{await handleHandoffDispatch(e,t,{contentDir:g,platform:process.platform,isSchemeRegistered:Tt.probeWithCache})}catch(e){t.headersSent||(log$7.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 hd(e,t){if(checkLocalOpSecurity(e,t,{handler:`spawn-cursor`}))try{await handleSpawnCursor(e,t,{contentDir:g,platform:process.platform})}catch(e){t.headersSent||(log$7.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 gd=withValidation(ShareConstructUrlRequestSchema,async(e,t,s)=>{try{if(!Ce){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=s.kind===`doc`?s.docPath:s.folderPath;if(!isValidSharePath(e,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 S=readGitHeadBranch(Ce);if(S===null){if(readOriginGitHubRepo(Ce).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 w=readOriginGitHubRepo(Ce);if(w.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(w.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(Ce,S)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:S},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let E=toGitRelativePath(Ce,g);if(E===null)throw Error(`content dir is not contained within the project dir`);let D=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;E!==``&&D&&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 O;if(s.kind===`doc`)O=buildGitHubBlobUrl(w.owner,w.repo,S,s.docPath);else{let e=s.folderPath===``?E:s.folderPath;O=buildGitHubTreeUrl(w.owner,w.repo,S,e)}let k=`${SHARE_BASE_URL}${encodeShareUrl(O)}`,j=await computeShareFreshness(Ce,S,E===``?e:e===``?E:`${E}/${e}`,s.kind);emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind,freshness:j}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:k,sharedUrl:O,branch:S,freshness:j},{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})}),_d=withValidation(EmptyRequestSchema,async(e,t)=>{try{if(!Ce){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(Ce,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}),vd=withValidation(ShareTargetStatusRequestSchema,async(e,t,s)=>{try{if(!Ce){errorResponse(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}if(!isValidBranchInfoPath(s.path,s.kind)){errorResponse(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG});return}let e=toGitRelativePath(Ce,g);if(e===null)throw Error(`content dir is not contained within the project dir`);let S=e===``?s.path:s.path===``?e:`${e}/${s.path}`;successResponse(t,200,ShareTargetStatusResponseSchema,await computeShareTargetStatus(Ce,s.branch,S,s.kind),{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_TARGET_STATUS_HANDLER_TAG,cause:e})}},{handler:SHARE_TARGET_STATUS_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_TARGET_STATUS_HANDLER_TAG})}),yd=withValidation(CheckoutRequestSchema,async(e,t,s)=>{if(extractActorIdentity(s,we).kind===`invalid-summary`){errorResponse(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:CHECKOUT_HANDLER_TAG});return}if(!Ce){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(Ce,s.branch,{fastForward:s.fastForward===!0})),{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 bd(e){let[t,...s]=ye,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 xd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.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 bd([`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{Ge.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})}),Sd=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(!Ge.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 bd([`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{Ge.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})}),Cd=withValidation(SharePublishRequestSchema,async(e,t,s)=>{if(!Ce){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(!Ge.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`,Ce,`--json`];s.description!==void 0&&s.description.length>0&&e.push(`--description`,s.description);let{stdout:g}=await bd(e),S=parsePublishEvent(pickTerminalJsonLine(g));emitSharePublishLog(`publish-create`,S.ok?`ok`:S.error),S.ok&&ve?.()?.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{Ge.release(SHARE_PUBLISH_KEY)}},{handler:SHARE_PUBLISH_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_PUBLISH_HANDLER_TAG})}),wd=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`})}),Td=Ce?getLocalDir(Ce):null;async function Ed(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}Td&&clearArmedPaneTarget(Td),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:Td?readServerLock(Td)?.port??0:0,paneTarget:Td?readArmedPaneTarget(Td):null,singleFile:We};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 Dd=`local-op-embeddings-set-key`,Od=`local-op-embeddings-clear-key`,kd=`/api/local-op/embeddings`,Ad=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Ge.tryAcquire(kd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Dd,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(Ue).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:Dd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Dd,cause:e})}finally{Ge.release(kd)}},{handler:Dd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Dd})}),jd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(kd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Od,extraHeaders:{"Retry-After":`5`}});return}try{await clearEmbeddingsKeyFromAllBackends(Ue),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:Od,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Od,cause:e})}finally{Ge.release(kd)}},{handler:Od,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:Od})}),Md=withValidation(EmptyRequestSchema,async(e,t)=>{try{let e=!1,s=!1,g=!1,S=0;if(Be){let t=Be.getStatus();e=t.enabled,s=t.ready,g=t.capable,S=t.embeddedCount}let E=await new FileEmbeddingsBackend(Ue).get(),D=process.env.OK_EMBEDDINGS_API_KEY??null,O=E?`file`:D?`env`:null,k=O!==null,j=E??D,F=j&&j.length>=8?j.slice(-4):null,L=0;for(let[e]of w())!isSystemDoc(e)&&!isConfigDoc(e)&&!isHiddenDocName(e)&&(L+=1);successResponse(t,200,SemanticIndexStatusSchema,{enabled:e,keyPresent:k,keySource:O,keyHint:F,ready:s,capable:g,embedded:S,total:L},{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}),Nd={"/api/config":Ed,"/api/asset":Cc,"/api/asset-text":Tc,"/api/document":Ns,"/api/documents":Ps,"/api/backlinks":Is,"/api/backlink-counts":Ls,"/api/forward-links":Rs,"/api/link-graph":ec,"/api/dead-links":rc,"/api/orphans":tc,"/api/hubs":nc,"/api/tags":Bl,"/api/pages":Fc,"/api/folder-config":ql,"/api/template":$l,"/api/templates":Ql,"/api/skill":_u,"/api/skill-file":Fu,"/api/skills":gu,"/api/skills/management":Su,"/api/skill/install":Iu,"/api/skill/uninstall":Lu,"/api/skill/restore":Vu,"/api/skill/update":Hu,"/api/skill-targets":Ru,"/api/search":ud,"/api/semantic-status":Md,"/api/suggest-links":Ic,"/api/page-headings":jc,"/api/create-page":Oc,"/api/create-folder":kc,"/api/duplicate-path":Ac,"/api/rename-path":Mc,"/api/delete-path":Nc,"/api/trash/cleanup":Pc,"/api/upload":Lc,"/api/agent-write":Ds,"/api/agent-write-md":Os,"/api/frontmatter-patch":ks,"/api/agent-patch":ic,"/api/agent-undo":ac,"/api/agent-activity":oc,"/api/agent-burst-diff":sc,"/api/save-version":fc,"/api/history":pc,"/api/rollback":hc,"/api/metrics/reconciliation":gc,"/api/metrics/parse-health":_c,"/api/metrics/agent-presence":bc,"/api/__embed-detect":xc,"/api/server-info":vc,"/api/share/construct-url":gd,"/api/share/target-status":vd,"/api/git/branch-info":_d,"/api/git/checkout":yd,"/api/share/publish/owners":xd,"/api/share/publish/name-check":Sd,"/api/share/publish":Cd,"/api/principal":yc,"/api/rescue":Dc,"/api/workspace":Sc,"/api/sync/status":Ol,"/api/sync/trigger":kl,"/api/sync/conflicts":jl,"/api/sync/conflict-content":Pl,"/api/sync/resolve-conflict":Ml,"/api/local-op/clone":Uc,"/api/local-op/ok-init":qc,"/api/local-op/auth/login":dl,"/api/local-op/auth/status":gl,"/api/local-op/auth/repos":vl,"/api/local-op/auth/signout":Cl,"/api/local-op/auth/set-identity":Dl,"/api/local-op/embeddings/set-key":Ad,"/api/local-op/embeddings/clear-key":jd,"/api/installed-agents":zl,"/api/spawn-cursor":hd,"/api/handoff":md,"/api/install-skill":Rl,"/api/skill/install-state":pd,"/api/seed/plan":Fl,"/api/seed/apply":Il,"/api/seed/packs":Ll,"/api/client-logs":wd};q&&(Nd[`/api/test-reset`]=lc,Nd[`/api/test-flush-git`]=cc,Nd[`/api/test-rescan-backlinks`]=uc,Nd[`/api/test-rescan-files`]=dc);let Pd=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-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),Fd=[`/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(Pd.has(s)||Fd.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(We&&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`:Nd[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=Nd[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 mc(e,t,g))}else if(s.startsWith(`/api/tags/`)){let g=s.slice(10);g&&(E=!0,await Vl(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 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=toPosix(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)}var AutoStartDisabledError=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const log$6=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$6.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$6.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$6.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-DjEtQkHv-DQXg1XhZ.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(!isWithinDir(g,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$6.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let{splitNulSeparatedPaths:e}=await import(`./git-handle-DjEtQkHv-DQXg1XhZ.mjs`),t=e(await w.git.raw([`diff`,`--name-only`,`--diff-filter=U`,`-z`]));for(let e of t)this.addConflict({file:e,detectedAt:s});g=t.length>0}catch(e){log$6.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$6.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 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_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 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 SPAWN_TIMEOUT_MS=2e3,LOCK_SCAN_MAX_DEPTH=3,LOCK_SCAN_MAX_ENTRIES=2e3,OK_LOCK_DIR_ARG_PREFIX=`--ok-lock-dir-b64=`,OK_PROJECT_PATH_ARG_PREFIX=`--ok-project-path=`,OK_PROCESS_PGREP_QUERY=`cli\\.mjs|open-knowledge|Open ?Knowledge(\\.app| Helper)|--ok-lock-dir-b64=|--ok-project-path=|(^|[ /])ok[ ]+(start|mcp|ui)([ ]|$)|packages/(cli|app)|hocuspocus|vite`,OK_PROCESS_PATTERNS=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function isOkProcess(e){return OK_PROCESS_PATTERNS.some(t=>t.test(e))}function extractMarkedLockDir(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(OK_LOCK_DIR_ARG_PREFIX));if(t==null)return null;let s=t.slice(18);if(!s)return null;try{let e=Buffer.from(s,`base64url`).toString(`utf8`);return isAbsolute(e)?e:null}catch{return null}}function extractProjectPathArg(e){let t=e.indexOf(OK_PROJECT_PATH_ARG_PREFIX);if(t===-1)return null;let s=t+18,g=e.slice(s),S=g.search(/\s--/),w=(S===-1?g:g.slice(0,S)).trim();return w&&isAbsolute(w)?w:null}function parsePgrepOutput(e){let t=[];for(let s of e.split(`
|
|
1949
1949
|
`)){let e=s.trim();if(!e)continue;let g=e.indexOf(` `);if(g===-1)continue;let S=e.slice(0,g),w=e.slice(g+1),E=Number.parseInt(S,10);!Number.isNaN(E)&&isOkProcess(w)&&t.push({pid:E,command:w})}return t}function parsePsOutput(e){let t=[],s=e.split(`
|
|
1950
1950
|
`);for(let e=1;e<s.length;e++){let g=s[e]?.trim();if(!g)continue;let S=g.indexOf(` `);if(S===-1)continue;let w=g.slice(0,S),E=g.slice(S+1).trim(),D=Number.parseInt(w,10);!Number.isNaN(D)&&isOkProcess(E)&&t.push({pid:D,command:E})}return t}async function findOkProcessEntries(){let e=spawnSync(`pgrep`,[`-a`,`-f`,OK_PROCESS_PGREP_QUERY],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});if(!(e.error!=null&&e.error.code===`ENOENT`)){let t=e.stdout??``,s=parsePgrepOutput(t);if(s.length>0||t.trim()===``)return s}let t=spawnSync(`ps`,[`-axo`,`pid,command`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});return t.error!=null||!t.stdout?[]:parsePsOutput(t.stdout)}function extractOkBinaryPath(e){let t=e.trim().split(/\s+/).filter(Boolean);for(let e of t){if(e.startsWith(`@`))continue;let t=basename(e);if(t===`open-knowledge`||t===`ok`||e.endsWith(`/packages/cli/src/cli.ts`)||e.endsWith(`/packages/cli/dist/cli.mjs`)||t===`cli.mjs`||t===`cli.ts`)return e}return null}function processCommand(e){let t=spawnSync(`ps`,[`-p`,String(e),`-o`,`command=`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});return t.error!=null||!t.stdout?null:t.stdout.trim()||null}function processUsage(e){let t=spawnSync(`ps`,[`-p`,String(e),`-o`,`%cpu=,%mem=`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});if(t.error!=null||!t.stdout)return null;let[s,g]=t.stdout.trim().split(/\s+/),S=Number.parseFloat(s??``),w=Number.parseFloat(g??``);return Number.isNaN(S)||Number.isNaN(w)?null:{cpuPercent:S,memPercent:w}}async function pidCwd(e){let t=spawnSync(`lsof`,[`-p`,String(e),`-a`,`-d`,`cwd`,`-Fn`],{encoding:`utf-8`,timeout:SPAWN_TIMEOUT_MS});if(t.error!=null)return null;let s=t.stdout??``;for(let e of s.split(`
|
|
1951
1951
|
`))if(e.startsWith(`n`)&&e.length>1)return e.slice(1);return null}function parseListeningPids(e){let t=[],s=e.split(`
|
|
@@ -1966,7 +1966,7 @@ Change history for this knowledge base, newest entry first. Add a dated entry (\
|
|
|
1966
1966
|
`),H={brokenLinks:F};return O&&(H.summary=O),j&&(H.warnings=j),textPlusStructured(B,nestDocResult(E,D?buildPreviewAttachWarning(E,S):void 0,H))}function templateFilePath(e,t,s){let g=resolveWithinRoot(e,`${t.replace(/\/+$/,``)}/.ok/templates/${s}.md`);return g.ok?{ok:!0,abs:g.abs}:{ok:!1}}function parseTemplateFrontmatter(e){let t=unwrapFrontmatterFences(e).trim();if(t===``)return{title:``};let s=(0,import_dist$1.parse)(t);if(typeof s!=`object`||!s||Array.isArray(s))return{title:``};let g=s;return{title:typeof g.title==`string`?g.title:``,...typeof g.description==`string`?{description:g.description}:{},...Array.isArray(g.tags)?{tags:g.tags.map(e=>String(e))}:{}}}async function handleTemplate$1(e,t,s,g,S){let w=bodyOrFrontmatterError(e,`template`);if(w)return textResult(`Error: ${w}`,!0);let E=resolveTemplatePath(e.path);if(!E.ok)return textResult(`Error: ${E.error}`,!0);let{folder:D,name:O}=E;if(!g)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let k=templateFilePath(s,D,O);if(!k.ok||!existsSync(k.abs))return textResult(`Error: template "${O}" not found in ${D||`(root)`}. Create it with \`write({ template })\` first.`,!0);let j;try{j=readFileSync(k.abs,`utf-8`)}catch(e){return textResult(`Error: could not read template: ${e.message}`,!0)}let{frontmatter:F,body:L}=stripFrontmatter(j),B=parseTemplateFrontmatter(F);if(e.frontmatter!==void 0){let s=await httpPut(g,`/api/template`,{folder:D,name:O,body:L,frontmatter:mergePatch(B,e.frontmatter),...t===void 0?{}:{summary:t},...agentIdentityFields(S.identityRef?.current)});if(!s.ok)return textResult(`Error: ${s.error}`,!0);let w=typeof s.path==`string`?s.path:void 0;return textPlusStructured(`Patched template "${O}" frontmatter${w?` (${w})`:``}.`,{template:{ok:!0,path:w}})}let H=e.occurrence??1,q=nthOccurrenceOffset(L,e.find,H);if(q===-1)return textResult(`Error: \`find\` occurs fewer than ${H} time(s) in template "${O}".`,!0);let ee=await httpPut(g,`/api/template`,{folder:D,name:O,body:L.slice(0,q)+e.replace+L.slice(q+e.find.length),frontmatter:B,...t===void 0?{}:{summary:t},...agentIdentityFields(S.identityRef?.current)});if(!ee.ok)return textResult(`Error: ${ee.error}`,!0);let J=typeof ee.path==`string`?ee.path:void 0;return textPlusStructured(`Edited template "${O}"${J?` (${J})`:``}.`,{template:{ok:!0,path:J}})}async function handleSkillFileEdit(e,t,s,g){let S=resolveSkillName(e.name);if(!S.ok)return textResult(`Error: ${S.error}`,!0);let w=resolveSkillFilePath(e.file);if(!w.ok)return textResult(`Error: ${w.error}`,!0);if(e.description!==void 0)return textResult("Error: `description` edits SKILL.md, not a bundle file. Drop `file`, or edit the file body with find+replace.",!0);if(e.find===void 0||e.replace===void 0)return textResult("Error: a bundle-file edit needs `find` + `replace`: { skill: { name, file, find, replace } }.",!0);if(!t)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let E=e.scope??`project`,D=await readSkillFile(t,E,e.name,w.path);if(!D.ok)return textResult(`Error: skill file "${w.path}" not found in skill "${e.name}" (${E} scope). Create it with \`write({ skill: { name, files: [...] } })\` first.`,!0);let O=e.occurrence??1,k=nthOccurrenceOffset(D.text,e.find,O);if(k===-1)return textResult(`Error: \`find\` occurs fewer than ${O} time(s) in skill file "${w.path}".`,!0);let j=D.text.slice(0,k)+e.replace+D.text.slice(k+e.find.length);return writeSkillFile(t,{name:e.name,scope:E,path:w.path,content:j,summary:s,identity:g})}async function handleSkill(e,t,s,g,S){let w=resolveSkillName(e.name);if(!w.ok)return textResult(`Error: ${w.error}`,!0);if(e.file!==void 0)return handleSkillFileEdit(e,s,t,g.identityRef?.current);let E=e.find!==void 0||e.replace!==void 0,D=e.description!==void 0;if(e.find!==void 0&&e.replace===void 0)return textResult("Error: `find` needs a `replace`. Body edit: { skill: { name, find, replace } }.",!0);if(e.replace!==void 0&&e.find===void 0)return textResult("Error: `replace` needs a `find`. Body edit: { skill: { name, find, replace } }.",!0);if(E&&D)return textResult("Error: Pick ONE: edit the body (find+replace) OR the `description`, not both in one call.",!0);if(!E&&!D)return textResult("Error: Provide either a body edit (find+replace) or a `description` for { skill }.",!0);if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let O=e.scope??`project`,k=await fetchSkill(s,O,e.name);if(!k.ok)return textResult(`Error: skill "${e.name}" not found in ${O} scope. Create it with \`write({ skill })\` first.`,!0);let j=k.body,F=k.description;if(D)F=e.description;else{let t=e.occurrence??1,s=nthOccurrenceOffset(k.body,e.find,t);if(s===-1)return textResult(`Error: \`find\` occurs fewer than ${t} time(s) in skill "${e.name}".`,!0);j=k.body.slice(0,s)+e.replace+k.body.slice(s+e.find.length)}return writeSkill(s,{scope:O,name:e.name,description:F,body:j,summary:t,identity:g.identityRef?.current,lockDir:S})}async function handleFolder$1(e,t,s,g){if(!s)return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0);let S=await httpPut(s,`/api/folder-config`,{path:e.path,frontmatter:e.frontmatter,...t===void 0?{}:{summary:t},...agentIdentityFields(g.identityRef?.current)});if(!S.ok)return textResult(`Error: ${S.error}`,!0);let w=(Array.isArray(S.applied)?S.applied:[])[0]??{},E=w.action??`written`;return textPlusStructured(`${E===`deleted`?`Cleared`:E===`noop`?`No change to`:`Updated`} folder properties for ${e.path}.`,{folder:{ok:!0,path:w.path??`${e.path}/.ok/frontmatter.yml`,action:E}})}function register$14(e,t){let s={find:string().optional().describe("Exact BODY text to find. Use WITH `replace`. For metadata, use `frontmatter` instead — not this."),replace:string().optional().describe("Replacement for the `find` match."),occurrence:number().int().positive().optional().describe(`Which match to edit (1 = first). Default: first.`)};e.registerTool(`edit`,{description:DESCRIPTION$14,inputSchema:{document:object$1({path:string().describe(`Document path, no extension — the slashes are its folder. Example: "meetings/standup".`),...s,frontmatter:FrontmatterArg.optional().describe("Metadata merge-patch (set keys; `null` deletes a key). Use INSTEAD of find/replace.")}).optional().describe(`Edit a DOCUMENT: its body (find+replace) OR its frontmatter (patch). Body: { document: { path, find, replace } }. Metadata: { document: { path, frontmatter } }.`),folder:object$1({path:string().describe(`Folder path.`),frontmatter:FrontmatterArg.describe("Update the folder's own title/description/tags (merge-patch; `null` deletes).")}).optional().describe(`Edit a FOLDER: only its frontmatter (folders have no body). Example: { folder: { path: "meetings", frontmatter: { description: "All-hands" } } }`),template:object$1({path:string().describe(TEMPLATE_PATH_DESCRIBE),...s,frontmatter:FrontmatterArg.optional().describe(`Template metadata merge-patch.`)}).optional().describe(`Edit a TEMPLATE: body (find+replace) or frontmatter (patch).`),skill:object$1({name:string().describe(SKILL_NAME_DESCRIBE),file:string().optional().describe(SKILL_FILE_DESCRIBE),...s,description:string().optional().describe(SKILL_DESCRIPTION_DESCRIBE),scope:SkillScopeArg.optional()}).optional().describe("Edit a SKILL: SKILL.md body (find+replace) OR its `description`; or pass `file` to find/replace inside ONE `references/**`+`scripts/**` bundle file."),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1(documentResultBaseShape).optional().describe("Document edit result. Always present on a successful document edit (body or frontmatter) — it carries `brokenLinks` (possibly `[]`) plus any `summary`/`warnings`. Absent only for folder/template edits."),folder:object$1({ok:boolean(),path:string(),action:string().describe("`written` (created/updated) | `deleted` (cleared) | `noop`.")}).optional().describe(`Folder frontmatter edit result.`),template:object$1({ok:boolean(),path:string()}).optional().describe(`Template edit result.`),skill:object$1({ok:boolean(),path:string().optional(),created:boolean().optional().describe(`Always false for an edit (the skill already existed).`),file:object$1({path:string(),kind:string().optional(),created:boolean().optional()}).optional().describe(`Present for a bundle-file edit: the file edited.`)}).optional().describe(`Skill edit result (SKILL.md or a bundle file).`),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=resolveContentDir(S,g),D=S.appearance.preview.autoOpen,O=exactlyOneTargetError(e,[`document`,`folder`,`template`,`skill`]);if(O)return textResult(`Error: ${O}`,!0);if(e.document!==void 0){let s=bodyOrFrontmatterError(e.document,`document`);return s?textResult(`Error: ${s}`,!0):w?e.document.frontmatter===void 0?handleDocBody(e.document,e,g,E,w,t,D):handleDocFrontmatter({path:e.document.path,frontmatter:e.document.frontmatter},e,g,E,w,t,D):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)}return e.folder===void 0?e.skill===void 0?handleTemplate$1(e.template,e.summary,g,w,t):handleSkill(e.skill,e.summary,w,t,resolveLockDir(g)):handleFolder$1(e.folder,e.summary,w,t)})}const PRODUCER_COMMANDS=new Set([`cat`,`ls`,`grep`,`find`]),PATH_FALLBACK_RE=/\b[\w./-]+\.(md|mdx)\b/g;function isWikiPath(e){return/\.(md|mdx)$/.test(e)}function normalize$1(e){let t=e.trim();return t?(t=t.replace(/\/+/g,`/`),t.startsWith(`./`)&&(t=t.slice(2)),t.endsWith(`/`)&&(t=t.slice(0,-1)),t):``}function argsOf(e){return e.args.slice(1)}function nonFlagArgs(e){return e.filter(e=>!e.startsWith(`-`))}function extractFromCat(e){return nonFlagArgs(argsOf(e)).filter(isWikiPath)}function extractFromLs(e,t){let s=nonFlagArgs(argsOf(t)),g=s.length>0?s[s.length-1]:``,S=g&&g!==`.`?normalize$1(g):``,w=[];S&&w.push(S);for(let t of e.split(`
|
|
1967
1967
|
`)){let e=t.trim();if(!e||/\.[a-z0-9]+$/i.test(e)&&!isWikiPath(e))continue;let s=S?`${S}/${e}`:e;w.push(s)}return w}function extractFromGrep(e){let t=[];for(let s of e.split(`
|
|
1968
1968
|
`)){if(!s)continue;let e=s.indexOf(`:`);if(e<0)continue;let g=normalize$1(s.slice(0,e));isWikiPath(g)&&t.push(g)}return t}function extractFromFind(e){let t=[];for(let s of e.split(`
|
|
1969
|
-
`)){let e=normalize$1(s);e&&isWikiPath(e)&&t.push(e)}return t}function extractFromHeadTail(e){return nonFlagArgs(argsOf(e)).filter(isWikiPath)}function headTailActsAsProducer(e){return nonFlagArgs(argsOf(e)).length>0}function fallback(e){let t=[],s=e.matchAll(PATH_FALLBACK_RE);for(let e of s)t.push(normalize$1(e[0]));return t}function extractReferencedPaths(e,t){let s=null;for(let e=t.length-1;e>=0;e--){let g=t[e];if(PRODUCER_COMMANDS.has(g.command)){s=g;break}if((g.command===`head`||g.command===`tail`)&&headTailActsAsProducer(g)){s=g;break}}let g;if(!s)g=fallback(e);else{switch(s.command){case`cat`:g=extractFromCat(s);break;case`ls`:g=extractFromLs(e,s);break;case`grep`:g=extractFromGrep(e);break;case`find`:g=extractFromFind(e);break;case`head`:case`tail`:g=extractFromHeadTail(s);break;default:g=fallback(e)}g.length===0&&(g=fallback(e))}let S=new Set,w=[];for(let e of g){let t=normalize$1(e);!t||S.has(t)||(S.add(t),w.push(t))}return w}function shellEscape(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const MAX_STDOUT_BYTES=16*1024*1024;var StdoutOverflowError=class extends Error{limitBytes;actualBytes;partial;constructor(e,t,s){super(`Output exceeded ${e} byte buffer (got ${t}); narrow the command`),this.name=`StdoutOverflowError`,this.limitBytes=e,this.actualBytes=t,this.partial=s}};function createBashInstance(e){if(!isAbsolute(e))throw Error(`createBashInstance: cwd must be absolute (got: ${e})`);return new
|
|
1969
|
+
`)){let e=normalize$1(s);e&&isWikiPath(e)&&t.push(e)}return t}function extractFromHeadTail(e){return nonFlagArgs(argsOf(e)).filter(isWikiPath)}function headTailActsAsProducer(e){return nonFlagArgs(argsOf(e)).length>0}function fallback(e){let t=[],s=e.matchAll(PATH_FALLBACK_RE);for(let e of s)t.push(normalize$1(e[0]));return t}function extractReferencedPaths(e,t){let s=null;for(let e=t.length-1;e>=0;e--){let g=t[e];if(PRODUCER_COMMANDS.has(g.command)){s=g;break}if((g.command===`head`||g.command===`tail`)&&headTailActsAsProducer(g)){s=g;break}}let g;if(!s)g=fallback(e);else{switch(s.command){case`cat`:g=extractFromCat(s);break;case`ls`:g=extractFromLs(e,s);break;case`grep`:g=extractFromGrep(e);break;case`find`:g=extractFromFind(e);break;case`head`:case`tail`:g=extractFromHeadTail(s);break;default:g=fallback(e)}g.length===0&&(g=fallback(e))}let S=new Set,w=[];for(let e of g){let t=normalize$1(e);!t||S.has(t)||(S.add(t),w.push(t))}return w}function shellEscape(e){return e===``?`''`:/^[\w.\-/]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}const MAX_STDOUT_BYTES=16*1024*1024;var StdoutOverflowError=class extends Error{limitBytes;actualBytes;partial;constructor(e,t,s){super(`Output exceeded ${e} byte buffer (got ${t}); narrow the command`),this.name=`StdoutOverflowError`,this.limitBytes=e,this.actualBytes=t,this.partial=s}};function createBashInstance(e){if(!isAbsolute(e))throw Error(`createBashInstance: cwd must be absolute (got: ${e})`);return new Dt({cwd:`/`,fs:new As({root:resolve(e),allowSymlinks:!1})})}async function execBash(e,t){let s=await e.exec(t);if(s.stdout.length>MAX_STDOUT_BYTES)throw new StdoutOverflowError(MAX_STDOUT_BYTES,s.stdout.length,{stdout:s.stdout.slice(0,MAX_STDOUT_BYTES),stderr:s.stderr,exitCode:s.exitCode});return{stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode}}const SCAN_CAP=1e3,SKIP_DIRS=new Set([`.git`,`.ok`,`node_modules`,`.changeset`,`.claude`,`.agents`,`dist`,`build`]);async function snapshotMtimes(e){let t=resolve(e),s=new Map,g=0,S=!1;async function w(e){if(S)return;let E;try{E=await readdir(e,{withFileTypes:!0})}catch{return}for(let D of E){if(S)return;if(D.isDirectory()&&SKIP_DIRS.has(D.name))continue;let E=resolve(e,D.name);if(D.isDirectory()){await w(E);continue}if(D.isFile()){if(g>=SCAN_CAP){S=!0;return}try{let e=await stat$1(E);s.set(relative(t,E),e.mtimeMs),g++}catch{}}}}return await w(t),{snapshot:s,truncated:S}}function diffMtimes(e,t){let s=[];for(let[g,S]of t){let t=e.get(g);(t===void 0||t!==S)&&s.push(g)}for(let[g]of e)t.has(g)||s.push(g);return{changed:s}}const WIKI_EXCLUDE_DIRS=[`node_modules`,`.git`,`dist`,`build`,`.next`,`.turbo`,`.nuxt`,`coverage`,`.cache`,`.parcel-cache`,`.vercel`,`.ok`,`.claude`];function isRecursiveGrepFlag(e){return e===`--recursive`||e===`--dereference-recursive`?!0:e.startsWith(`--`)||!e.startsWith(`-`)?!1:/[rR]/.test(e.slice(1))}const STRATEGIES=[{command:`grep`,applies:e=>e.slice(1).some(isRecursiveGrepFlag),hasUserExcludes:e=>e.some(e=>e===`--exclude-dir`||e.startsWith(`--exclude-dir=`)),buildExcludeArgs:e=>e.map(e=>`--exclude-dir=${e}`),insertionIndex:()=>1},{command:`find`,applies:()=>!0,hasUserExcludes:e=>e.slice(1).some(e=>e===`-not`||e===`!`||e===`-prune`),buildExcludeArgs:e=>{let t=[];for(let s of e)t.push(`-not`,`-path`,`*/${s}/*`);return t},insertionIndex:e=>{for(let t=1;t<e.length;t++)if(e[t].startsWith(`-`))return t;return e.length}}];function augmentStagesWithExcludes(e){return e.map(e=>{let t=STRATEGIES.find(t=>t.command===e.command);if(!t||!t.applies(e.args)||t.hasUserExcludes(e.args))return e;let s=t.buildExcludeArgs(WIKI_EXCLUDE_DIRS),g=t.insertionIndex(e.args);return{command:e.command,args:[...e.args.slice(0,g),...s,...e.args.slice(g)]}})}function serializeStages(e){return e.map(e=>e.args.map(shellEscape).join(` `)).join(` | `)}const ALLOWLIST=new Set([`cat`,`ls`,`grep`,`find`,`head`,`tail`,`wc`,`sort`,`uniq`,`cut`]),ALLOWLIST_HINT=`cat, ls, grep, find, head, tail, wc, sort, uniq, cut`,WRITE_OPS=new Set([`>`,`>>`,`<`,`>&`,`<&`,`|&`]),SHELL_CONSTRUCT_OPS=new Set([`&`,`;`,`;;`,`&&`,`||`,`(`,`)`,`<(`,`>(`,`<<`,`<<-`]),UNIVERSAL_FLAG_DENY=new Set([`-o`,`--output-file`,`--output`]),UNIVERSAL_FLAG_PREFIX_DENY=[`-o=`,`--output-file=`,`--output=`],FIND_FLAG_DENY=new Set([`-exec`,`-execdir`,`-delete`,`-fprint`,`-fprintf`,`-fprint0`,`-ok`,`-okdir`]),SUSPICIOUS_STRING_RE=/[`]|\$\(|\$\{|\$'/;function isOpToken(e){return typeof e==`object`&&!!e&&`op`in e}function opTokenError(e){let t=typeof e.op==`string`?e.op:`(unknown)`;return WRITE_OPS.has(t)?{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use the \`write\` or \`edit\` tool.`}:SHELL_CONSTRUCT_OPS.has(t)?{category:`shell_construct_blocked`,message:`Shell construct '${t}' is not supported — exec runs ONE command or a pipe (|), not a shell. Run separate exec calls, or pass multiple paths to one command (e.g. \`ls -A a b c\`, \`cat a b c\`).`}:{category:`shell_construct_blocked`,message:`Operator '${t}' is not supported.`}}function buildStageArgs(e){let t=[];for(let s of e){if(typeof s==`string`){if(SUSPICIOUS_STRING_RE.test(s))return{error:{category:`shell_construct_blocked`,message:`Argument '${s}' contains a shell-injection pattern (backtick, $(), or \${}); not supported.`}};t.push(s);continue}if(!isOpToken(s))return{error:{category:`shell_construct_blocked`,message:`Unrecognized token shape.`}};if(s.op===`glob`&&typeof s.pattern==`string`){t.push(s.pattern);continue}return typeof s.comment==`string`?{error:{category:`shell_construct_blocked`,message:`Comments are not allowed in exec commands.`}}:{error:opTokenError(s)}}return{args:t}}function checkStage(e){if(!ALLOWLIST.has(e.command))return{category:`unknown_command`,message:`Command '${e.command}' is not in the allowlist. For pattern matching try 'grep'; for file listing try 'ls' or 'find'. Allowlist: ${ALLOWLIST_HINT}.`};for(let t of e.args.slice(1)){if(UNIVERSAL_FLAG_DENY.has(t)||UNIVERSAL_FLAG_PREFIX_DENY.some(e=>t.startsWith(e)))return{category:`write_blocked`,message:`Write operation blocked: '${t}'. exec is read-only. For document changes, use the \`write\` or \`edit\` tool.`};if(e.command===`find`&&FIND_FLAG_DENY.has(t))return{category:`write_blocked`,message:`find flag '${t}' is blocked (executes commands or deletes files). Use exec for read-only discovery; chain with another allowlisted tool via '|' if you need to transform output.`}}return null}function parseCommand(e){let t=e.trim();if(!t)return{error:{category:`unknown_command`,message:`Empty command.`}};let s;try{s=import_shell_quote.parse(t)}catch{return{error:{category:`shell_construct_blocked`,message:`Failed to parse command — likely malformed quoting or an unsupported construct.`}}}let g=[],S=[];for(let e of s){if(isOpToken(e)&&e.op===`|`){g.push(S),S=[];continue}S.push(e)}g.push(S);let w=[];for(let e of g){let t=buildStageArgs(e);if(`error`in t)return t;if(t.args.length===0)return{error:{category:`shell_construct_blocked`,message:`Empty pipeline stage (trailing pipe or leading pipe).`}};let s={command:t.args[0],args:t.args},g=checkStage(s);if(g)return{error:g};w.push(s)}return{stages:w}}const SOFT_CAP_LINES=500,SOFT_CAP_BYTES=32768-8*1024,BINARY_EXT_RE=/\.(png|jpe?g|gif|webp|svg|pdf|zip|tar|gz|tgz|mp4|mov|mp3|wav|ico|bmp)$/i,DESCRIPTION$13=["**STOP — when the project has `.ok/`, do NOT use native `Read`/`Grep`/`Glob` on in-scope `.md`/`.mdx`; use `exec` (this tool).** Native tools skip the frontmatter, backlinks, shadow-repo activity, and git history `exec` returns per wiki file. Reserve native tools for source code, non-markdown, and projects without `.ok/`. (Full rule + escape hatch: the `open-knowledge` skill.)",``,`Run a read-only bash-like command against the project content directory. Returns raw stdout plus enriched metadata for every wiki file referenced (frontmatter, backlink/forward-link counts, shadow-repo activity with agent/human attribution).`,``,"Allowlist: cat, ls, grep, find, head, tail, wc, sort, uniq, cut. One command or a pipe (|) per call — NOT a shell: `&&`, `;`, redirections, subshells, and writes are rejected. To do several things, make separate exec calls or pass multiple paths to one command (e.g. `ls -A a b c`, `cat a b c`).",``,"cwd: the command runs in the explicit absolute `cwd` you pass, or in the MCP client's only advertised root when there is exactly one. If the client has zero or multiple roots, pass `cwd` explicitly. Paths inside the command resolve relative to that cwd; traversal above it is rejected.",``,"Stdout provenance headers (GNU-style): `ls <dir>/` prepends `<dir>/:`, single-file `cat`/`head`/`tail` prepends `==> <path> <==`, so the subject of the command is visible in raw output. Multi-file `cat a b` emits no header — the `enrichedPaths` array still lists every file. `head`/`tail` used as pipe trimmers (no file arg) defer to the upstream producer.",``,`Examples:`,'- `exec({ command: "cat articles/auth.md" })` — file contents + full enrichment','- `exec({ command: "ls articles/" })` — listing + per-file enrichment (slim)','- `exec({ command: "grep -rn oauth articles/ | head -5" })` — pipe with enrichment on matched files','- `exec({ command: "ls", cwd: "/abs/path/to/other-repo" })` — run in a different project'].join(`
|
|
1970
1970
|
`);function applySoftCap(e){let t=e.split(`
|
|
1971
1971
|
`),s=t[t.length-1]===``?t.length-1:t.length;if(s<=SOFT_CAP_LINES&&e.length<=SOFT_CAP_BYTES)return{text:e,truncated:!1,omittedLines:0};let g=Math.min(s,SOFT_CAP_LINES),S=0,w=0;for(let e=0;e<g;e++){let s=t[e];if(S+=s.length+1,S>SOFT_CAP_BYTES)break;w++}let E=t.slice(0,w).join(`
|
|
1972
1972
|
`),D=s-w;return{text:`${E}\n<truncated: ${D} more lines — re-run with a more-specific query>`,truncated:!0,omittedLines:D}}function detectBinaryArgs(e){let t=[];for(let s of e)if(s.command===`cat`)for(let e of s.args.slice(1))e.startsWith(`-`)||BINARY_EXT_RE.test(e)&&t.push(e);return t}function extractHeadTailLimit(e){for(let t=1;t<e.length;t++){let s=e[t],g=s.match(/^--lines=(\d+)$/);if(g)return Number(g[1]);if(s===`--lines`&&t+1<e.length){let s=Number(e[t+1]);if(Number.isFinite(s))return s}if(s===`-n`&&t+1<e.length){let s=Number(e[t+1]);if(Number.isFinite(s))return s}let S=s.match(/^-n(\d+)$/);if(S)return Number(S[1]);let w=s.match(/^-(\d+)$/);if(w)return Number(w[1])}return 10}function detectHeadTailTruncation(e,t){if(e.length<2)return null;let s=e[e.length-1];if(s.command!==`head`&&s.command!==`tail`)return null;let g=extractHeadTailLimit(s.args),S=t.split(`
|
|
@@ -3253,7 +3253,7 @@ Incremental by default — don't re-read the whole repo.
|
|
|
3253
3253
|
`,`
|
|
3254
3254
|
`).split(`
|
|
3255
3255
|
`),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(!isLinkIndexExcludedDoc(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(isLinkIndexExcludedDoc(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=toPosix(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=toPosix(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 resolveUpstreamChanges(e,t,s,g){let S=new Map;if(!s)return S;let w;try{w=spawnSync(`git`,[`-c`,`core.quotePath=false`,`log`,`${s}..${g}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],{cwd:e,encoding:`utf-8`,timeout:5e3})}catch(e){return getLogger(`upstream-attribution`).warn({err:e,oldHead:s,newHead:g},`git log spawn threw; upstream docs keep file-system attribution`),S}if(w.error||w.status!==0||typeof w.stdout!=`string`)return getLogger(`upstream-attribution`).warn({err:w.error,status:w.status,signal:w.signal,stderr:typeof w.stderr==`string`?w.stderr.slice(0,500):void 0,oldHead:s,newHead:g},`git log failed; upstream docs keep file-system attribution`),S;let E=null;for(let s of w.stdout.split(`
|
|
3256
|
-
`)){let g=s.trim();if(g===``)continue;if(g.startsWith(`C\0`)){let[,e,t]=g.split(`\0`);E=e&&t?{name:e,email:t}:null;continue}if(!E||!g.endsWith(`.md`)&&!g.endsWith(`.mdx`))continue;let w=resolve(e,g);if(!isWithinContentDir(w,t))continue;let D=pathToDocName(w,t);S.has(D)||existsSync(w)&&S.set(D,E)}return S}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`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=isKnownConfigError(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}Y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function ne(){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;if(t!=null)return t===!0;e.valid||Y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let g=readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});return g.valid||Y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),g.value.autoSync?.default===!0}function ae(){return readProjectLocalSemanticConfig(s,{configHomedirOverride:k,onWarn:e=>Y.warn({message:e},`[config] could not read project-local config`)})}function oe(e){return`${normalizeProviderId(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}function se(e){let t;(e===`__config__/project`||e===`__local__/project`)&&(t=ne(),Lr?.setEnabled(t).catch(s=>{Y.warn({err:s,enabled:t,docName:e},`[sync] failed to apply autoSync.enabled from config`)}));let s=ae();ze.applyConfig({enabled:s.enabled,providerFingerprint:oe(s)}),Y.info({docName:e,autoSyncEnabled:t,semanticEnabled:s.enabled},`[config] applied persisted config to in-process consumers`)}initTelemetry();let ce=randomUUID(),ue=getLocalDir(s);if(acquireServerLock(ue,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:ue,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(ue),e}let de=createBasenameIndex(),fe=(e,t)=>de.resolveEmbed(e,t),me=(e,s)=>{let g=de.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g);if(!isWithinDir(S,resolve(t)))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},ge,_e,ve,ye,Ce,we,Te,De,je=null,Me=null,Pe=null,Ie=null,Re=ae(),ze=new SemanticSearchService({loadEmbedder:e.embedderLoader??(()=>{let t=ae();return loadOpenAiEmbedder({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:join(getLocalDir(s),`embeddings`),enabled:Re.enabled,providerFingerprint:oe(Re)}),Be=null,Ve=new Set,Ue=!1,We,Ge,Ke,Xe=new Promise((e,t)=>{Ge=e,Ke=t});function $e(e){je?.signal(e)}let nt=2e3,rt=null;function it(){rt!==null&&clearTimeout(rt),rt=setTimeout(()=>{rt=null,_e.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let at=2e3,st=null,vt=!1,Tt=()=>{try{saveRemovedDocsJournal(s,Et.entries())}catch(e){Y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Et=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e),onMutate:()=>{!vt||st!==null||(st=setTimeout(()=>{st=null,Tt()},2e3))}});for(let[e,g]of loadRemovedDocsJournal(s))isReservedForUserTree(e)||isSafeDocName(e)&&([`.md`,`.mdx`].some(s=>{let g=resolve(t,`${e}${s}`);return isWithinDir(g,resolve(t))&&existsSync(g)})||Et.restore(e,g));vt=!0;let Dt=(e,t)=>{isReservedForUserTree(e)||Et.setRenamed(e,t)},jt=e=>{if(!isReservedForUserTree(e)){if(Et.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Et.setDeleted(e)}},Mt=e=>{isReservedForUserTree(e)||Et.delete(e)};try{ge=createContentFilter({projectDir:s,contentDir:t,singleDocRelPath:ee,onAfterRebuild:()=>{_e.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),ve.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),reconcileFileIndexAfterFilterRebuild(Fr).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`)})}}),_e=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:ge}),ve=new TagIndex({contentDir:t,contentFilter:ge}),ve.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[server-factory] tag-index init failed; continuing with empty index`)}),ye={current:F},Ce=E?createMaintenanceCoordinator({getShadow:()=>ye.current??null,getCurrentBranch:()=>Ir?.getLastKnownBranch()??null,contentRoot:L??``,projectGitDir:resolveGitDir(s)??void 0,isWriterLive:e=>{if(!Pe&&!De)return getLogger(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Pe?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of De?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,we=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:ye,ephemeral:J,contentRoot:L,backlinkIndex:_e,configHomedirOverride:k,getCurrentBranch:()=>Ir?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:me,getPrincipal:()=>Be,onAgentCommit:()=>je?.signal(`session-activity`),onFlushCommit:()=>Ce?.noteFlushCommit(),onDiskFlush:(e,t,s,g)=>{je?.emitDiskAck(e,t),!isReservedForUserTree(e)&&assetReferencesChanged(g,s)&&(Ie?.(),$e(`files`))},onConfigRejected:(e,t)=>je?.emitConfigValidationRejected(e,t),onConfigPersisted:se,isRecentlyRemoved:e=>Et.has(e),mdManager:e.mdManager}),Te=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[we.extension]});let B=Te.shouldUnloadDocument.bind(Te);Te.shouldUnloadDocument=e=>{if(Ve.has(e)||Ue&&B(e))return!0;let t=e.name;return isReservedForUserTree(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},We=async e=>{Ve.add(e);try{await Te.unloadDocument(e)}finally{Ve.delete(e)}},je=new CC1Broadcaster(Te),Me=new AgentFocusBroadcaster(Te),Pe=new AgentPresenceBroadcaster(Te),De=new AgentSessionManager(Te);let q=createLiveDerivedIndexExtension({backlinkIndex:_e,tagIndex:ve,signalChannel:$e});Te.configuration.extensions.push(q),Te.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!==ce)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ce}`);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`&&(Be&&s.principalId===Be.id?E.principalId=Be.id:Be?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Be.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),Te.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName)&&!isManagedArtifactDoc(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 ne(e){if(!isSafeDocName(e))return null;let t=resolve(Y,docNameToRelativePath(e));return isWithinDir(t,Y)?t:null}Te.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:Et,resolveFilePath:ne,fileExists:existsSync})}}),Te.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=parseHocuspocusAuthToken(e.token);runDocLineageGuard(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Te.documents.get(e)})}}),Te.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 oe=createApiExtension({hocuspocus:Te,sessionManager:De,contentDir:t,contentFilter:ge,serverInstanceId:ce,getFileIndex:()=>Fr?Fr.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>Fr?Fr.getAllFilesIndex():new Map,getFileIndexGeneration:()=>Fr?.getFileIndexGeneration()??0,mutateFileIndex:e=>Fr?.mutateFileIndex(e),getFolderIndex:()=>Fr?Fr.getFolderIndex():new Map,getAliasMap:()=>Fr?Fr.getAliasMap():new Map,getFolderAliasIndex:()=>Fr?Fr.getFolderAliasIndex():new Map,rescanFiles:()=>Fr?.rescanFromDisk(),enableTestRoutes:j,shadowRef:ye,flushGitCommit:()=>we.flushPendingGitCommit(),flushContributors:()=>we.flushContributors(),takeStoreFailure:e=>we.takeStoreFailure(e),takeStoreDivergence:e=>we.takeStoreDivergence(e),markAgentWriteStore:e=>we.markAgentWriteStore(e),getCurrentBranch:()=>Ir?.getLastKnownBranch()??null,getDiskAckSVs:()=>je?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:_e,tagIndex:ve,signalChannel:$e,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Lr,localOpCliArgs:H,projectDir:s,resolveEmbed:fe,getPrincipal:()=>Be,homeDirOverride:k,forceUnloadDocument:We,ready:Xe,recentlyRemovedDocs:Et,serializeDoc:zt,evictManagedArtifactLkg:e=>{we.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:ze,getSemanticSimilarityFloor:()=>ae().similarityFloor,embeddingsSecretsFile:secretsFilePath(k),ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{Ie=e}});Te.configuration.extensions.push(oe),Te.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:ye,contentRoot:L,getCurrentBranch:()=>Ir?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:me})),Te.configuration.extensions.push(createSyncHandshakeSpanExtension()),Te.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>Lr,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(ue),e}let Ft=null,It=new Map,Lt=[];function Rt(e,t){let s=resolve(e,`rescue`),g=resolve(s,docNameToRelativePath(t));return isWithinDir(g,s)?g:null}function zt(e){let t=Te.documents.get(e);return t?serializeYDocSource(t):null}let Bt=(e,t)=>applyExternalChange(Te,e,t,fe,me);function Vt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Ht=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of Te.documents){if(isReservedForUserTree(s))continue;let g=Te.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,fe,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}`)}}},Ut=null,Wt=e=>{e&&(Ut===null&&(Ut=new Set,setImmediate(()=>{let e=Ut;if(Ut=null,e)try{for(let t of e)Ht(t)}catch(t){Y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Ut.add(e))};function Kt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function $t(e){try{switch(e.kind){case`create`:Y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),_e.updateDocumentFromMarkdown(e.docName,e.content),it(),ve.updateDocumentFromMarkdown(e.docName,e.content),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),Mt(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=Te.documents.get(t);if(!g){_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`);return}let S=getReconciledBase(t)??``,w=zt(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`:Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`);break;case`clean`:try{Bt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),Vt(g)}break;case`merged`:try{Bt(t,E.newContent),setReconciledBase(t,s),incrementReconcile(),Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),Vt(g)}break;case`conflicts`:try{Bt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`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=Te.documents.get(t);if(!s){_e.deleteDocument(t),it(),ve.deleteDocument(t),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),jt(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=zt(t)??``,w=S!==g;if(w&&ye.current){let e=ye.current,s=Ir?.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),_e.deleteDocument(t),it(),ve.deleteDocument(t),Y.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),Te.closeConnections(t),await We(s),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),jt(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=Te.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),_e.renameDocument(t,s,g),it(),ve.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}`),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),Dt(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=Te.documents.get(t);if(!s)return;let g=zt(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`:de.add(e.relativePath),$e(`files`),Wt(basename(e.relativePath));break;case`asset-delete`:de.remove(e.relativePath),$e(`files`),Wt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:$e(`files`);break;case`file-create`:case`file-update`:case`file-delete`:$e(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Kt(e);Y.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let en=[];async function jr(e){if(isBatchInProgress()){en.push(e);return}await $t(e)}async function Mr(){let e=en.splice(0,en.length);for(let t of e)await $t(t)}let Fr=null,Ir=null,Lr=null,zr=null;async function Br(e){if(Te.documents.size===0)return;let t=!1,s=new Promise(e=>{Te.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(Te.documents.keys());Te.closeConnections(),Te.flushPendingStores();for(let e of Te.documents.values())e.getConnectionsCount()===0&&Te.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(Te.documents.keys()),S=[],E=[];if(ye.current){for(let e of s)if(!isReservedForUserTree(e))try{let t=zt(e);if(t===null){Y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=Rt(ye.current.gitDir,e);if(!s){Y.warn({docName:e,gitDir:ye.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 Vr(){return zr||(zr=(async()=>{let e=Date.now(),t=[];Ue=!0;try{markServerLockDraining(ue)}catch(e){Y.warn({err:e},`[server] failed to mark server.lock draining`)}if(rt!==null&&(clearTimeout(rt),rt=null),st!==null&&(clearTimeout(st),st=null),vt)try{saveRemovedDocsJournal(s,Et.entries())}catch(e){Y.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let g,S=await Promise.race([Xe.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=Te.documents.size;Ce?.destroy();try{try{try{Ir&&=(await Ir.unsubscribe(),null),Fr&&=(await Fr.unsubscribe(),null);for(let{docName:e,cleanup:t}of Lt)try{await t()}catch(t){Y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Lt.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{je?.destroy(),Pe?.destroy(),Ft&&=(await Ft.disconnect(),null);for(let[e,t]of It)try{await t.disconnect()}catch(t){Y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}It.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 De.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 Br(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 we.flushPendingGitCommit(),await we.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{Lr&&=(await Lr.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(ye.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(ye.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(ye.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(ue,{deferUnlinkToExit:!0})}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)})}}})(),zr)}let Hr=[];async function Ur(){try{Be=await loadPrincipal(s),Y.info({principalId:Be.id},`[server] principal loaded`)}catch(e){Y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!ye.current)try{ye.current=await initShadowRepo(s),Y.info({gitDir:ye.current.gitDir},`[server] history repo initialized at ${ye.current.gitDir}`)}catch(e){Y.error({err:e},`[server] history repo init failed`),Hr.push(`shadow-repo`)}if(ye.current){let e=null;try{e=loadRenameLogIndex(ye.current.gitDir),sweepLazyPopOrphans(ye.current.gitDir,e),setRenameLogIndex(ye.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(ye.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`)}}try{await Ce?.runBootMaintenance()}catch(e){Y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(ye.current)try{await shadowGit(ye.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{ye.current=await initShadowRepo(s)}catch(e){Y.error({err:e},`[server] history repo reinit failed`),ye.current=void 0,Hr.includes(`shadow-repo`)||Hr.push(`shadow-repo`)}}else Y.error({err:e},`[server] history repo check failed (transient?)`)}if(ye.current)try{let e=resolve(ye.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(ye.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`),Hr.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`),Hr.push(`upload-tempfile-sweep`)}try{Ft=await Te.openDirectConnection(SYSTEM_DOC_NAME),je?.emitServerInfo(ce,getActiveBranch())}catch(e){Y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Hr.push(`cc1-push`)}let g=J?[]:CONFIG_DOC_NAMES;for(let e of g)try{let t=await Te.openDirectConnection(e);It.set(e,t)}catch(t){Y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Hr.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=Te.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,we.configPersistenceCtx);Y.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),se(e)});Lt.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}`),Hr.push(`config-file-watcher:${e}`)}}if(!J){let e=(e,t)=>{let s=managedArtifactDocNameForPath(e,we.managedArtifactCtx);if(!s)return;let g=applyExternalManagedArtifactChange(Te.documents.get(s)??null,s,t,we.managedArtifactCtx);Y.info({docName:s,outcome:g},`[managed-artifact-watcher] external change`),parseGlobalSkillBundleDoc(s)&&_e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),getActiveBranch()).then(()=>{$e(`backlinks`),$e(`graph`)}).catch(e=>{Y.warn({err:e,docName:s},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=managedArtifactSkillsRoots(we.managedArtifactCtx),s=await startManagedArtifactWatcher(t,e);Lt.push({docName:`__skill-files__`,cleanup:s}),Y.info({roots:t},`[managed-artifact-watcher] skills started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),Hr.push(`managed-artifact-watcher:skills`)}try{let t=new Set([``]);try{for(let e of resolveProjectTemplates(s).templates)t.add(e.source_folder)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let g=[...t].map(e=>e?resolve(s,e,`.ok`,`templates`):resolve(s,`.ok`,`templates`)),S=await startManagedArtifactWatcher(g,e,TEMPLATE_WATCH_OPTIONS);Lt.push({docName:`__template-files__`,cleanup:S}),Y.info({rootCount:g.length},`[managed-artifact-watcher] templates started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),Hr.push(`managed-artifact-watcher:templates`)}}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(Te.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,we.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 ge.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`),je?.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`),je?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});D&&(Lt.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`),Hr.push(`ignore-files-watcher`)}let w=resolveGitDir(s),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),_e.switchBranch(E);let D=performance.now();try{await withSpan(`ok.boot.indexes`,void 0,async()=>{let e=getActiveBranch();try{if(await _e.loadFromDisk(e)){let t=await _e.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&Y.info({added:t.added,updated:t.updated,deleted:t.deleted},`[backlinks] startup reconcile: offline changes applied`);let s=0;for(let e of t.deletedDocNames)isReservedForUserTree(e)||Et.peek(e)?.kind!==`renamed`&&(Et.setDeleted(e),s++);s>0&&Y.info({count:s},`[removal-guard] tombstoned docs deleted while the server was down`)}else await _e.rebuildFromDisk(e);try{await _e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),e)}catch(t){Y.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}_e.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`)}let s=performance.now();Fr=await withSpan(`ok.boot.seed-walk`,void 0,async()=>startWatcher(t,jr,ge)),recordBootPhase(`seedWalkMs`,Math.round(performance.now()-s));{let e=resolve(t),s=0;for(let[t]of Et.entries()){if(!isSafeDocName(t))continue;let g=resolve(e,`${t}${getDocExtension(t)}`);isWithinDir(g,e)&&existsSync(g)&&(Et.delete(t),s++)}s>0&&Y.info({count:s},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}try{await ve.init()}catch(e){Y.error({err:e},`[tag-index] startup re-init failed; tag index updates incrementally via watcher events`),Hr.push(`tag-index`)}let g=0;try{ee===void 0?await seedBasenameIndex({contentDir:t,contentFilter:ge,basenameIndex:de,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):seedSingleDirBasenameIndex({contentDir:t,basenameIndex:de,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),g>0&&(Y.warn({count:g},`[basename-index] startup seed completed with ${g} skipped entries — embeds under inaccessible subtrees will not resolve`),Hr.push(`basename-index-partial`))}catch(e){Y.error({err:e},`[basename-index] startup seed failed`),Hr.push(`basename-index`)}})}catch(e){Y.error({err:e},`[server] disk bridge watcher failed to start`),Hr.push(`file-watcher`)}finally{recordBootPhase(`indexesMs`,Math.round(performance.now()-D)),Fr&&setBootField(`fileCount`,Fr.getFileIndex().size)}try{Ir=await startHeadWatcher(s,async({trigger:e})=>{if(Y.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),Te.flushPendingStores(),await we.flushPendingGitCommit(),setBatchInProgress(!0),ye.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of Te.documents){if(isReservedForUserTree(e))continue;let s=null;if(t.transact(()=>{s=zt(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(ye.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 g=en.length,S=e.newBranch??`main`;if(Y.info({kind:e.batchKind,headMoved:e.headMoved,docs:g,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${g}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await Mr(),e.headMoved&&e.newHead){let g=resolveUpstreamChanges(s,resolve(t),e.oldHead,e.newHead);if(g.size>0){dropPendingDocs(g.keys());for(let[e,t]of g)recordContributor(e,gitAuthorWriterId(t.email),t.name,t.email,formatReconcileSubject(e));await we.flushContributors()}}if(await we.flushDeferredStores(`within-branch`),Lr!==null)try{await Lr.reconcileConflictsFromGit()}catch(e){Y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),en.splice(0,en.length),switchReconciledBaseScope(S),rt!==null&&(clearTimeout(rt),rt=null),_e.switchBranch(S),ge.rebuildDirCount();try{let e=0;de.clear(),await seedBasenameIndex({contentDir:t,contentFilter:ge,basenameIndex:de,onSkip:(t,s,g)=>{e++,Y.warn({reason:t,code:s,path:g,branch:S},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e,branch:S},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Hr.includes(`basename-index-partial`)||Hr.push(`basename-index-partial`))}catch(e){Y.error({err:e,branch:S},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of Te.documents)if(!isReservedForUserTree(e))try{let g=safeContentPath(e,t);if(!existsSync(g)){let t=getReconciledBase(e)??``,g=zt(e)??``;if(g!==t&&ye.current){let t=ye.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:g,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,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:S},`[branch-switch] tombstone: ${e} (not on ${S})`);continue}let w=readFileSync(g,`utf-8`);Bt(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:S,docCount:Te.documents.size},`[branch-switch] loaded branch ${S} (${Te.documents.size} docs)`);try{if(await _e.loadFromDisk(S)){let e=await _e.reconcileWithDisk(S);(e.added>0||e.updated>0||e.deleted>0)&&Y.info(e,`[backlinks] branch-switch reconcile for ${S}`)}else await _e.rebuildFromDisk(S);try{await _e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),S)}catch(e){Y.warn({err:e,branch:S},`[backlinks] branch-switch global skill bundle ingest failed`)}_e.saveToDisk(S).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${S}:`,e)})}catch(e){Y.error({err:e,branch:S},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(await ve.init(),ye.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Te.documents)if(!isReservedForUserTree(t))try{let s=await readParkedState(ye.current,S,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let g=getReconciledBase(t);if(!g)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:g});switch(w.kind){case`merged`:case`clean`:Bt(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:Bt(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=Te.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:S},`[branch-switch] restored ${e} parked docs on ${S}`)}if(e.oldBranch?.startsWith(`detached-`)&&ye.current)try{let t=shadowGit(ye.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
|
|
3257
|
-
`))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 we.flushDeferredStores(`discard-stale`),je?.emitBranchSwitched(S)}if(e.headMoved&&e.newHead&&ye.current&&g>0){let t=L??`.`;try{let s=await commitUpstreamImport(ye.current,t,e.oldHead,e.newHead,S);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`),Hr.push(`head-watcher`)}function O(e){for(let g of e)try{let e=toPosix(relative(t,join(s,g)));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=Te.documents.get(S);if(!w)continue;let E=zt(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 j=buildSyncCredentialArgs(H);try{Lr=new SyncEngine({projectDir:s,contentDir:t,contentFilter:ge,contentRoot:L,syncEnabled:ne(),credentialArgs:j,cc1Broadcaster:je,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||we.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:O,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 Lr.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Lr=null}$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`);let F=bootElapsedMs();F!==void 0&&recordBootPhase(`readyMs`,F)}return Ur().then(Ge,Ke),{hocuspocus:Te,sessionManager:De,cc1Broadcaster:je,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,maintenanceCoordinator:Ce,contentFilter:ge,basenameIndex:de,serverInstanceId:ce,destroy:Vr,ready:Xe,degraded:Hr,lockDir:ue,get syncEngine(){return Lr}}}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 TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`,TELEMETRY_PREV_FILENAME=`tolerance-telemetry.prev.jsonl`,TELEMETRY_MAX_BYTES=8*1024*1024;let appender=null,appendFailureWarned=!1;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);appender=new RotatingAppender({currentPath:resolve(t,TELEMETRY_FILENAME),previousPath:resolve(t,TELEMETRY_PREV_FILENAME),maxBytes:TELEMETRY_MAX_BYTES}),setToleranceTelemetryHook(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};appender?.append(`${JSON.stringify(t)}\n`).catch(e=>{appendFailureWarned||(appendFailureWarned=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null),await appender?.drain(),appender=null,appendFailureWarned=!1}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){startBootTimings();let t=e.projectDir??e.contentDir,s=resolveLocalSinkConfig({projectDir:t});if(s){let e=s.telemetry.attributeDenylist,t=[];for(let s of e){t.push(s);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)t.push(`${`*.`.repeat(e)}${s}`)}loggerFactory.configure({pinoConfig:{fileSink:s.logs,redactPaths:t}})}initTelemetry({localSink:s?.telemetry}),initToleranceTelemetryWriter(t),installServerMemoryGauge();let{kind:g,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":g};S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S));let E=process.env.OK_STARTUP_TRACEPARENT,D=()=>withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e));if(E)try{let e=propagation.extract(context.active(),{traceparent:E});return context.with(e,D)}catch(e){getLogger(`boot`).warn({err:e instanceof Error?e.message:String(e)},`ok.boot trace-join failed — starting unparented boot`)}return D()}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`),{markServerLockDraining:O,releaseServerLock:k,updateServerLockPort:j}=await import(`./server-lock-GuuouVft-BFFcTQcA.mjs`),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.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 H=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&H()}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(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let q=findLegacyRuntimeFiles(B);q.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${q.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let ee=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:J,destroy:Y,ready:te,degraded:ne,lockDir:ae,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,maintenanceCoordinator:ue}=ee,de=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),fe=e.port??0,me=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${de}:${fe}`,log:S}),ge=D();ge.headersTimeout=3e4,ge.requestTimeout=6e4;let _e=e.serveContentAssets?createAssetServeMiddleware({contentFilter:ee.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ve=!1;if(e.reactShellDistDir)try{acquireUiLock(ae,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ve=!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:ae},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await Y().catch(()=>{}),k(ae),e}let ye=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,Ce=mountMcpAndApi({httpServer:ge,hocuspocus:J,mcpHttpHandler:me,log:S,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,maintenanceCoordinator:ue,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:_e,reactShellMiddleware:ye,ephemeral:e.ephemeral}),we=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Te=null;g!==null&&(Te=attachIdleShutdown({httpServer:ge,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await we()})})),await restoreLifecycleFromConflictsJson({hocuspocus:J,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);ge.once(`error`,g),ge.listen(e.port,e.host,()=>{ge.removeListener(`error`,g),t()})})}catch(e){if(ve)try{releaseUiLock(ae)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await Y().catch(()=>{}),k(ae),e}let De=bootElapsedMs();De!==void 0&&recordBootPhase(`httpListenMs`,De);let je=ge.address(),Me=typeof je==`object`&&je?je.port:e.port??0;if(fe=Me,j(ae,Me),ve&&updateUiLockPort(ae,Me),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ae,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let Pe=!1,Ie=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)}};we=async()=>{if(Pe)return;Pe=!0;let e=[],t=async(t,s)=>{try{await Ie(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{O(ae),ve&&markUiLockDraining(ae)}catch(e){S.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{Te?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>Ce.shutdown()),me!==void 0&&await t(`mcpHttpHandler.close`,()=>me.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{Ce.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{ge.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ge.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>Y()),ve&&await t(`releaseUiLock`,async()=>releaseUiLock(ae,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await reconcileSkillInstalls({projectDir:L,skillsRoot:resolve(e.contentDir,`.ok`,`skills`)}),s=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;s>0&&S.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${s} editor skill entr${s===1?`y`:`ies`} to the symlink model.`)}catch(e){S.warn?.({event:`installed-skills-reconcile-failed`,error:String(e)},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:ge,destroy:we,lockDir:ae,contentDir:e.contentDir,port:Me,ready:te,degraded:ne,didAutoInit:F,serverInstance:ee}}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`,`-z`]);E=new Set(splitNulSeparatedPaths(g))}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,t){try{let{stdout:s}=await execFileAsync(e,[`rev-parse`,`--is-inside-work-tree`],{cwd:t});return s.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}let w;try{w=assertGitAvailable()}catch(e){throw e instanceof GitNotAvailableError||e instanceof GitTooOldError?(emitPreflightFailureSpan(e),log.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof GitTooOldError?`too_old`:`not_available`,detectedVersion:e instanceof GitTooOldError?e.detected:``},e instanceof GitTooOldError?`git binary too old`:`git binary not found`)):log.warn({event:`git_preflight_unexpected_error`,message:e instanceof Error?e.message:String(e)},`unexpected error during git preflight`),e}let E=w.resolvedPath;if(!S&&await isInsideExistingWorkTree(E,t))return{didInit:!1};let D=``;try{D=(await execFileAsync(E,[`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)`,D);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(`OpenKnowledge 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/
|
|
3256
|
+
`)){let g=s.trim();if(g===``)continue;if(g.startsWith(`C\0`)){let[,e,t]=g.split(`\0`);E=e&&t?{name:e,email:t}:null;continue}if(!E||!g.endsWith(`.md`)&&!g.endsWith(`.mdx`))continue;let w=resolve(e,g);if(!isWithinContentDir(w,t))continue;let D=pathToDocName(w,t);S.has(D)||existsSync(w)&&S.set(D,E)}return S}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`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=isKnownConfigError(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}Y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function ne(){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;if(t!=null)return t===!0;e.valid||Y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let g=readConfigSafely({absPath:resolveConfigPath(`project`,s),sideline:!1,warn:e=>Y.warn({message:e},`[config] could not read project config`)});return g.valid||Y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),g.value.autoSync?.default===!0}function ae(){return readProjectLocalSemanticConfig(s,{configHomedirOverride:k,onWarn:e=>Y.warn({message:e},`[config] could not read project-local config`)})}function oe(e){return`${normalizeProviderId(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}function se(e){let t;(e===`__config__/project`||e===`__local__/project`)&&(t=ne(),jr?.setEnabled(t).catch(s=>{Y.warn({err:s,enabled:t,docName:e},`[sync] failed to apply autoSync.enabled from config`)}));let s=ae();ze.applyConfig({enabled:s.enabled,providerFingerprint:oe(s)}),Y.info({docName:e,autoSyncEnabled:t,semanticEnabled:s.enabled},`[config] applied persisted config to in-process consumers`)}initTelemetry();let ce=randomUUID(),ue=getLocalDir(s);if(acquireServerLock(ue,{port:e.port??0,worktreeRoot:s,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!q)try{assertCompatibleStateManifest({lockDir:ue,shadowRepoDir:resolveShadowDir(s)})}catch(e){throw releaseServerLock(ue),e}let de=createBasenameIndex(),fe=(e,t)=>de.resolveEmbed(e,t),me=(e,s)=>{let g=de.resolveEmbed(e,s);if(!g&&e.includes(`/`)&&(g=e.replace(/^\.?\//,``)),!g)return null;let S=resolve(t,g);if(!isWithinDir(S,resolve(t)))return null;try{let e=statSync(S);return e.isFile()?e.size:null}catch{return null}},ge,_e,ve,ye,Ce,we,Te,De,je=null,Me=null,Pe=null,Ie=null,Re=ae(),ze=new SemanticSearchService({loadEmbedder:e.embedderLoader??(()=>{let t=ae();return loadOpenAiEmbedder({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:join(getLocalDir(s),`embeddings`),enabled:Re.enabled,providerFingerprint:oe(Re)}),Be=null,Ve=new Set,Ue=!1,We,Ge,Ke,Xe=new Promise((e,t)=>{Ge=e,Ke=t});function $e(e){je?.signal(e)}let nt=2e3,rt=null;function it(){rt!==null&&clearTimeout(rt),rt=setTimeout(()=>{rt=null,_e.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let at=2e3,st=null,vt=!1,St=()=>{try{saveRemovedDocsJournal(s,Tt.entries())}catch(e){Y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Tt=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e),onMutate:()=>{!vt||st!==null||(st=setTimeout(()=>{st=null,St()},2e3))}});for(let[e,g]of loadRemovedDocsJournal(s))isReservedForUserTree(e)||isSafeDocName(e)&&([`.md`,`.mdx`].some(s=>{let g=resolve(t,`${e}${s}`);return isWithinDir(g,resolve(t))&&existsSync(g)})||Tt.restore(e,g));vt=!0;let Et=(e,t)=>{isReservedForUserTree(e)||Tt.setRenamed(e,t)},jt=e=>{if(!isReservedForUserTree(e)){if(Tt.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Tt.setDeleted(e)}},Mt=e=>{isReservedForUserTree(e)||Tt.delete(e)};try{ge=createContentFilter({projectDir:s,contentDir:t,singleDocRelPath:ee,onAfterRebuild:()=>{_e.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),ve.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),reconcileFileIndexAfterFilterRebuild(rn).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`)})}}),_e=new BacklinkIndex({projectDir:s,contentDir:t,contentFilter:ge}),ve=new TagIndex({contentDir:t,contentFilter:ge}),ve.init().catch(e=>{getLogger(`server-factory`).warn({err:e},`[server-factory] tag-index init failed; continuing with empty index`)}),ye={current:F},Ce=E?createMaintenanceCoordinator({getShadow:()=>ye.current??null,getCurrentBranch:()=>sn?.getLastKnownBranch()??null,contentRoot:L??``,projectGitDir:resolveGitDir(s)??void 0,isWriterLive:e=>{if(!Pe&&!De)return getLogger(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Pe?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of De?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,we=createPersistenceExtension({contentDir:t,projectDir:s,gitEnabled:E,commitDebounceMs:D,wipRef:O,shadowRef:ye,ephemeral:J,contentRoot:L,backlinkIndex:_e,configHomedirOverride:k,getCurrentBranch:()=>sn?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:me,getPrincipal:()=>Be,onAgentCommit:()=>je?.signal(`session-activity`),onFlushCommit:()=>Ce?.noteFlushCommit(),onDiskFlush:(e,t,s,g)=>{je?.emitDiskAck(e,t),!isReservedForUserTree(e)&&assetReferencesChanged(g,s)&&(Ie?.(),$e(`files`))},onConfigRejected:(e,t)=>je?.emitConfigValidationRejected(e,t),onConfigPersisted:se,isRecentlyRemoved:e=>Tt.has(e),mdManager:e.mdManager}),Te=new Hocuspocus({quiet:g,debounce:S,maxDebounce:w,extensions:[we.extension]});let B=Te.shouldUnloadDocument.bind(Te);Te.shouldUnloadDocument=e=>{if(Ve.has(e)||Ue&&B(e))return!0;let t=e.name;return isReservedForUserTree(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:B(e)},We=async e=>{Ve.add(e);try{await Te.unloadDocument(e)}finally{Ve.delete(e)}},je=new CC1Broadcaster(Te),Me=new AgentFocusBroadcaster(Te),Pe=new AgentPresenceBroadcaster(Te),De=new AgentSessionManager(Te);let q=createLiveDerivedIndexExtension({backlinkIndex:_e,tagIndex:ve,signalChannel:$e});Te.configuration.extensions.push(q),Te.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!==ce)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${g}, this server is ${ce}`);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`&&(Be&&s.principalId===Be.id?E.principalId=Be.id:Be?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:s.principalId,loaded:Be.id})):E.principalId=s.principalId),typeof s.tabSessionId==`string`&&(E.tabSessionId=s.tabSessionId),E.kind=`human`}}),Te.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName)&&!isManagedArtifactDoc(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 ne(e){if(!isSafeDocName(e))return null;let t=resolve(Y,docNameToRelativePath(e));return isWithinDir(t,Y)?t:null}Te.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:Tt,resolveFilePath:ne,fileExists:existsSync})}}),Te.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=parseHocuspocusAuthToken(e.token);runDocLineageGuard(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Te.documents.get(e)})}}),Te.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 oe=createApiExtension({hocuspocus:Te,sessionManager:De,contentDir:t,contentFilter:ge,serverInstanceId:ce,getFileIndex:()=>rn?rn.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>rn?rn.getAllFilesIndex():new Map,getFileIndexGeneration:()=>rn?.getFileIndexGeneration()??0,mutateFileIndex:e=>rn?.mutateFileIndex(e),getFolderIndex:()=>rn?rn.getFolderIndex():new Map,getAliasMap:()=>rn?rn.getAliasMap():new Map,getFolderAliasIndex:()=>rn?rn.getFolderAliasIndex():new Map,rescanFiles:()=>rn?.rescanFromDisk(),enableTestRoutes:j,shadowRef:ye,flushGitCommit:()=>we.flushPendingGitCommit(),flushContributors:()=>we.flushContributors(),takeStoreFailure:e=>we.takeStoreFailure(e),takeStoreDivergence:e=>we.takeStoreDivergence(e),markAgentWriteStore:e=>we.markAgentWriteStore(e),getCurrentBranch:()=>sn?.getLastKnownBranch()??null,getDiskAckSVs:()=>je?.getLatestDiskAckSVsAsBase64()??{},contentRoot:L,backlinkIndex:_e,tagIndex:ve,signalChannel:$e,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>jr,localOpCliArgs:H,projectDir:s,resolveEmbed:fe,getPrincipal:()=>Be,homeDirOverride:k,forceUnloadDocument:We,ready:Xe,recentlyRemovedDocs:Tt,serializeDoc:zt,evictManagedArtifactLkg:e=>{we.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:ze,getSemanticSimilarityFloor:()=>ae().similarityFloor,embeddingsSecretsFile:secretsFilePath(k),ephemeral:J,onReferencedAssetsCacheInvalidator:e=>{Ie=e}});Te.configuration.extensions.push(oe),Te.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:ye,contentRoot:L,getCurrentBranch:()=>sn?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:me})),Te.configuration.extensions.push(createSyncHandshakeSpanExtension()),Te.configuration.extensions.push(createConflictLifecycleSeedExtension({getSyncEngine:()=>jr,projectDir:s,contentDir:t}))}catch(e){throw releaseServerLock(ue),e}let Ft=null,It=new Map,Lt=[];function Rt(e,t){let s=resolve(e,`rescue`),g=resolve(s,docNameToRelativePath(t));return isWithinDir(g,s)?g:null}function zt(e){let t=Te.documents.get(e);return t?serializeYDocSource(t):null}let Bt=(e,t)=>applyExternalChange(Te,e,t,fe,me);function Vt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Ht=e=>{if(!e)return;let t=`[[${e}]]`;for(let[s]of Te.documents){if(isReservedForUserTree(s))continue;let g=Te.documents.get(s);if(!g)continue;let S=g.getText(`source`).toString();if(S.includes(t))try{g.transact(()=>{applyDiskContentToDoc(g,S,fe,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}`)}}},Ut=null,Wt=e=>{e&&(Ut===null&&(Ut=new Set,setImmediate(()=>{let e=Ut;if(Ut=null,e)try{for(let t of e)Ht(t)}catch(t){Y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Ut.add(e))};function Xt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-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}`),_e.updateDocumentFromMarkdown(e.docName,e.content),it(),ve.updateDocumentFromMarkdown(e.docName,e.content),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),Mt(e.docName);break;case`update`:{let{docName:t,content:s}=e,g=Te.documents.get(t);if(!g){_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`);return}let S=getReconciledBase(t)??``,w=zt(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`:Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`);break;case`clean`:try{Bt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,s),Vt(g)}break;case`merged`:try{Bt(t,E.newContent),setReconciledBase(t,s),incrementReconcile(),Vt(g),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`tags`)}catch(e){Y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,s),Vt(g)}break;case`conflicts`:try{Bt(t,E.newContent),setReconciledBase(t,E.newContent),incrementReconcile(),incrementConflict(),_e.updateDocumentFromMarkdown(t,s),it(),ve.updateDocumentFromMarkdown(t,s),$e(`backlinks`),$e(`graph`),$e(`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=Te.documents.get(t);if(!s){_e.deleteDocument(t),it(),ve.deleteDocument(t),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),jt(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let g=getReconciledBase(t)??``,S=zt(t)??``,w=S!==g;if(w&&ye.current){let e=ye.current,s=sn?.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),_e.deleteDocument(t),it(),ve.deleteDocument(t),Y.info({docName:t,isDirty:w},`[reconcile] delete: ${t} (dirty=${w})`),Te.closeConnections(t),await We(s),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),jt(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=Te.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(s,g),_e.renameDocument(t,s,g),it(),ve.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}`),$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`),Et(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=Te.documents.get(t);if(!s)return;let g=zt(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`:de.add(e.relativePath),$e(`files`),Wt(basename(e.relativePath));break;case`asset-delete`:de.remove(e.relativePath),$e(`files`),Wt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:$e(`files`);break;case`file-create`:case`file-update`:case`file-delete`:$e(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let s=Xt(e);Y.error({err:t,kind:e.kind,label:s},`[reconcile] failed to handle ${e.kind} for ${s}`)}}let $t=[];async function en(e){if(isBatchInProgress()){$t.push(e);return}await Zt(e)}async function tn(){let e=$t.splice(0,$t.length);for(let t of e)await Zt(t)}let rn=null,sn=null,jr=null,Mr=null;async function zr(e){if(Te.documents.size===0)return;let t=!1,s=new Promise(e=>{Te.configuration.extensions.push({async afterUnloadDocument({instance:s}){!t&&s.getDocumentsCount()===0&&(t=!0,e())}})}),g=Array.from(Te.documents.keys());Te.closeConnections(),Te.flushPendingStores();for(let e of Te.documents.values())e.getConnectionsCount()===0&&Te.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(Te.documents.keys()),S=[],E=[];if(ye.current){for(let e of s)if(!isReservedForUserTree(e))try{let t=zt(e);if(t===null){Y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),E.push(e);continue}let s=Rt(ye.current.gitDir,e);if(!s){Y.warn({docName:e,gitDir:ye.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 Br(){return Mr||(Mr=(async()=>{let e=Date.now(),t=[];Ue=!0;try{markServerLockDraining(ue)}catch(e){Y.warn({err:e},`[server] failed to mark server.lock draining`)}if(rt!==null&&(clearTimeout(rt),rt=null),st!==null&&(clearTimeout(st),st=null),vt)try{saveRemovedDocsJournal(s,Tt.entries())}catch(e){Y.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let g,S=await Promise.race([Xe.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=Te.documents.size;Ce?.destroy();try{try{try{sn&&=(await sn.unsubscribe(),null),rn&&=(await rn.unsubscribe(),null);for(let{docName:e,cleanup:t}of Lt)try{await t()}catch(t){Y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Lt.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{je?.destroy(),Pe?.destroy(),Ft&&=(await Ft.disconnect(),null);for(let[e,t]of It)try{await t.disconnect()}catch(t){Y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}It.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 De.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 zr(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 we.flushPendingGitCommit(),await we.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{jr&&=(await jr.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(ye.current){try{let e=(await esm_default({baseDir:s,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(ye.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(ye.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(ue,{deferUnlinkToExit:!0})}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)})}}})(),Mr)}let Vr=[];async function Hr(){try{Be=await loadPrincipal(s),Y.info({principalId:Be.id},`[server] principal loaded`)}catch(e){Y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!ye.current)try{ye.current=await initShadowRepo(s),Y.info({gitDir:ye.current.gitDir},`[server] history repo initialized at ${ye.current.gitDir}`)}catch(e){Y.error({err:e},`[server] history repo init failed`),Vr.push(`shadow-repo`)}if(ye.current){let e=null;try{e=loadRenameLogIndex(ye.current.gitDir),sweepLazyPopOrphans(ye.current.gitDir,e),setRenameLogIndex(ye.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(ye.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`)}}try{await Ce?.runBootMaintenance()}catch(e){Y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(ye.current)try{await shadowGit(ye.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{ye.current=await initShadowRepo(s)}catch(e){Y.error({err:e},`[server] history repo reinit failed`),ye.current=void 0,Vr.includes(`shadow-repo`)||Vr.push(`shadow-repo`)}}else Y.error({err:e},`[server] history repo check failed (transient?)`)}if(ye.current)try{let e=resolve(ye.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(ye.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`),Vr.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`),Vr.push(`upload-tempfile-sweep`)}try{Ft=await Te.openDirectConnection(SYSTEM_DOC_NAME),je?.emitServerInfo(ce,getActiveBranch())}catch(e){Y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Vr.push(`cc1-push`)}let g=J?[]:CONFIG_DOC_NAMES;for(let e of g)try{let t=await Te.openDirectConnection(e);It.set(e,t)}catch(t){Y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Vr.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=Te.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,we.configPersistenceCtx);Y.info({docName:e,outcome:g},`[config-file-watcher] applyExternalConfigChange outcome`),se(e)});Lt.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}`),Vr.push(`config-file-watcher:${e}`)}}if(!J){let e=(e,t)=>{let s=managedArtifactDocNameForPath(e,we.managedArtifactCtx);if(!s)return;let g=applyExternalManagedArtifactChange(Te.documents.get(s)??null,s,t,we.managedArtifactCtx);Y.info({docName:s,outcome:g},`[managed-artifact-watcher] external change`),parseGlobalSkillBundleDoc(s)&&_e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),getActiveBranch()).then(()=>{$e(`backlinks`),$e(`graph`)}).catch(e=>{Y.warn({err:e,docName:s},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=managedArtifactSkillsRoots(we.managedArtifactCtx),s=await startManagedArtifactWatcher(t,e);Lt.push({docName:`__skill-files__`,cleanup:s}),Y.info({roots:t},`[managed-artifact-watcher] skills started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),Vr.push(`managed-artifact-watcher:skills`)}try{let t=new Set([``]);try{for(let e of resolveProjectTemplates(s).templates)t.add(e.source_folder)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let g=[...t].map(e=>e?resolve(s,e,`.ok`,`templates`):resolve(s,`.ok`,`templates`)),S=await startManagedArtifactWatcher(g,e,TEMPLATE_WATCH_OPTIONS);Lt.push({docName:`__template-files__`,cleanup:S}),Y.info({rootCount:g.length},`[managed-artifact-watcher] templates started`)}catch(e){Y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),Vr.push(`managed-artifact-watcher:templates`)}}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(Te.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,g,we.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 ge.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`),je?.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`),je?.emitConfigIgnoreNestedError(e,S.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(s,t)||`.`},`[ignore-watcher] handler threw`)})});D&&(Lt.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`),Vr.push(`ignore-files-watcher`)}let w=resolveGitDir(s),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),_e.switchBranch(E);let D=performance.now();try{await withSpan(`ok.boot.indexes`,void 0,async()=>{let e=getActiveBranch();try{if(await _e.loadFromDisk(e)){let t=await _e.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&Y.info({added:t.added,updated:t.updated,deleted:t.deleted},`[backlinks] startup reconcile: offline changes applied`);let s=0;for(let e of t.deletedDocNames)isReservedForUserTree(e)||Tt.peek(e)?.kind!==`renamed`&&(Tt.setDeleted(e),s++);s>0&&Y.info({count:s},`[removal-guard] tombstoned docs deleted while the server was down`)}else await _e.rebuildFromDisk(e);try{await _e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),e)}catch(t){Y.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}_e.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`)}let s=performance.now();rn=await withSpan(`ok.boot.seed-walk`,void 0,async()=>startWatcher(t,en,ge)),recordBootPhase(`seedWalkMs`,Math.round(performance.now()-s));{let e=resolve(t),s=0;for(let[t]of Tt.entries()){if(!isSafeDocName(t))continue;let g=resolve(e,`${t}${getDocExtension(t)}`);isWithinDir(g,e)&&existsSync(g)&&(Tt.delete(t),s++)}s>0&&Y.info({count:s},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}try{await ve.init()}catch(e){Y.error({err:e},`[tag-index] startup re-init failed; tag index updates incrementally via watcher events`),Vr.push(`tag-index`)}let g=0;try{ee===void 0?await seedBasenameIndex({contentDir:t,contentFilter:ge,basenameIndex:de,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):seedSingleDirBasenameIndex({contentDir:t,basenameIndex:de,onSkip:(e,t,s)=>{g++,Y.warn({reason:e,code:t,path:s},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),g>0&&(Y.warn({count:g},`[basename-index] startup seed completed with ${g} skipped entries — embeds under inaccessible subtrees will not resolve`),Vr.push(`basename-index-partial`))}catch(e){Y.error({err:e},`[basename-index] startup seed failed`),Vr.push(`basename-index`)}})}catch(e){Y.error({err:e},`[server] disk bridge watcher failed to start`),Vr.push(`file-watcher`)}finally{recordBootPhase(`indexesMs`,Math.round(performance.now()-D)),rn&&setBootField(`fileCount`,rn.getFileIndex().size)}try{sn=await startHeadWatcher(s,async({trigger:e})=>{if(Y.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),Te.flushPendingStores(),await we.flushPendingGitCommit(),setBatchInProgress(!0),ye.current){let e=getActiveBranch(),t=resolveGitDir(s),g=t?readBranchFromHead(t)??e:e,S=[];for(let[e,t]of Te.documents){if(isReservedForUserTree(e))continue;let s=null;if(t.transact(()=>{s=zt(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(ye.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 g=$t.length,S=e.newBranch??`main`;if(Y.info({kind:e.batchKind,headMoved:e.headMoved,docs:g,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${g}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await tn(),e.headMoved&&e.newHead){let g=resolveUpstreamChanges(s,resolve(t),e.oldHead,e.newHead);if(g.size>0){dropPendingDocs(g.keys());for(let[e,t]of g)recordContributor(e,gitAuthorWriterId(t.email),t.name,t.email,formatReconcileSubject(e));await we.flushContributors()}}if(await we.flushDeferredStores(`within-branch`),jr!==null)try{await jr.reconcileConflictsFromGit()}catch(e){Y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),$t.splice(0,$t.length),switchReconciledBaseScope(S),rt!==null&&(clearTimeout(rt),rt=null),_e.switchBranch(S),ge.rebuildDirCount();try{let e=0;de.clear(),await seedBasenameIndex({contentDir:t,contentFilter:ge,basenameIndex:de,onSkip:(t,s,g)=>{e++,Y.warn({reason:t,code:s,path:g,branch:S},`[basename-index] skipped entry during branch-switch reseed (${t}${s?` ${s}`:``})`)}}),e>0&&(Y.warn({count:e,branch:S},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Vr.includes(`basename-index-partial`)||Vr.push(`basename-index-partial`))}catch(e){Y.error({err:e,branch:S},`[basename-index] branch-switch reseed failed`)}for(let[e,s]of Te.documents)if(!isReservedForUserTree(e))try{let g=safeContentPath(e,t);if(!existsSync(g)){let t=getReconciledBase(e)??``,g=zt(e)??``;if(g!==t&&ye.current){let t=ye.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,L??``,{kind:`external-change-rescue`,docName:e,contents:g,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,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:S},`[branch-switch] tombstone: ${e} (not on ${S})`);continue}let w=readFileSync(g,`utf-8`);Bt(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:S,docCount:Te.documents.size},`[branch-switch] loaded branch ${S} (${Te.documents.size} docs)`);try{if(await _e.loadFromDisk(S)){let e=await _e.reconcileWithDisk(S);(e.added>0||e.updated>0||e.deleted>0)&&Y.info(e,`[backlinks] branch-switch reconcile for ${S}`)}else await _e.rebuildFromDisk(S);try{await _e.ingestGlobalSkillBundles(managedArtifactSkillsRoots(we.managedArtifactCtx),S)}catch(e){Y.warn({err:e,branch:S},`[backlinks] branch-switch global skill bundle ingest failed`)}_e.saveToDisk(S).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${S}:`,e)})}catch(e){Y.error({err:e,branch:S},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(await ve.init(),ye.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Te.documents)if(!isReservedForUserTree(t))try{let s=await readParkedState(ye.current,S,SERVICE_WRITER.id,t);if(!s||s.markdown===s.diskSnapshot)continue;let g=getReconciledBase(t);if(!g)continue;let w=reconcile({docName:t,base:s.diskSnapshot,ours:s.markdown,theirs:g});switch(w.kind){case`merged`:case`clean`:Bt(t,w.newContent),setReconciledBase(t,w.newContent),e++;break;case`conflicts`:Bt(t,w.newContent),setReconciledBase(t,w.newContent),incrementConflict(),e++;{let e=Te.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:S},`[branch-switch] restored ${e} parked docs on ${S}`)}if(e.oldBranch?.startsWith(`detached-`)&&ye.current)try{let t=shadowGit(ye.current),s=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(s){for(let e of s.split(`
|
|
3257
|
+
`))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 we.flushDeferredStores(`discard-stale`),je?.emitBranchSwitched(S)}if(e.headMoved&&e.newHead&&ye.current&&g>0){let t=L??`.`;try{let s=await commitUpstreamImport(ye.current,t,e.oldHead,e.newHead,S);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`),Vr.push(`head-watcher`)}function O(e){for(let g of e)try{let e=toPosix(relative(t,join(s,g)));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=Te.documents.get(S);if(!w)continue;let E=zt(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 j=buildSyncCredentialArgs(H);try{jr=new SyncEngine({projectDir:s,contentDir:t,contentFilter:ge,contentRoot:L,syncEnabled:ne(),credentialArgs:j,cc1Broadcaster:je,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||we.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:O,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 jr.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),jr=null}$e(`files`),$e(`backlinks`),$e(`graph`),$e(`tags`);let F=bootElapsedMs();F!==void 0&&recordBootPhase(`readyMs`,F)}return Hr().then(Ge,Ke),{hocuspocus:Te,sessionManager:De,cc1Broadcaster:je,agentFocusBroadcaster:Me,agentPresenceBroadcaster:Pe,maintenanceCoordinator:Ce,contentFilter:ge,basenameIndex:de,serverInstanceId:ce,destroy:Br,ready:Xe,degraded:Vr,lockDir:ue,get syncEngine(){return jr}}}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 TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`,TELEMETRY_PREV_FILENAME=`tolerance-telemetry.prev.jsonl`,TELEMETRY_MAX_BYTES=8*1024*1024;let appender=null,appendFailureWarned=!1;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);appender=new RotatingAppender({currentPath:resolve(t,TELEMETRY_FILENAME),previousPath:resolve(t,TELEMETRY_PREV_FILENAME),maxBytes:TELEMETRY_MAX_BYTES}),setToleranceTelemetryHook(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};appender?.append(`${JSON.stringify(t)}\n`).catch(e=>{appendFailureWarned||(appendFailureWarned=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null),await appender?.drain(),appender=null,appendFailureWarned=!1}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){startBootTimings();let t=e.projectDir??e.contentDir,s=resolveLocalSinkConfig({projectDir:t});if(s){let e=s.telemetry.attributeDenylist,t=[];for(let s of e){t.push(s);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)t.push(`${`*.`.repeat(e)}${s}`)}loggerFactory.configure({pinoConfig:{fileSink:s.logs,redactPaths:t}})}initTelemetry({localSink:s?.telemetry}),initToleranceTelemetryWriter(t),installServerMemoryGauge();let{kind:g,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":g};S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S));let E=process.env.OK_STARTUP_TRACEPARENT,D=()=>withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e));if(E)try{let e=propagation.extract(context.active(),{traceparent:E});return context.with(e,D)}catch(e){getLogger(`boot`).warn({err:e instanceof Error?e.message:String(e)},`ok.boot trace-join failed — starting unparented boot`)}return D()}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`),{markServerLockDraining:O,releaseServerLock:k,updateServerLockPort:j}=await import(`./server-lock-GuuouVft-BFFcTQcA.mjs`),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.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 H=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&H()}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(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let q=findLegacyRuntimeFiles(B);q.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${q.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let ee=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:J,destroy:Y,ready:te,degraded:ne,lockDir:ae,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,maintenanceCoordinator:ue}=ee,de=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),fe=e.port??0,me=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${de}:${fe}`,log:S}),ge=D();ge.headersTimeout=3e4,ge.requestTimeout=6e4;let _e=e.serveContentAssets?createAssetServeMiddleware({contentFilter:ee.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ve=!1;if(e.reactShellDistDir)try{acquireUiLock(ae,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ve=!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:ae},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await Y().catch(()=>{}),k(ae),e}let ye=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,Ce=mountMcpAndApi({httpServer:ge,hocuspocus:J,mcpHttpHandler:me,log:S,sessionManager:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:ce,maintenanceCoordinator:ue,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:_e,reactShellMiddleware:ye,ephemeral:e.ephemeral}),we=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Te=null;g!==null&&(Te=attachIdleShutdown({httpServer:ge,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await we()})})),await restoreLifecycleFromConflictsJson({hocuspocus:J,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);ge.once(`error`,g),ge.listen(e.port,e.host,()=>{ge.removeListener(`error`,g),t()})})}catch(e){if(ve)try{releaseUiLock(ae)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await Y().catch(()=>{}),k(ae),e}let De=bootElapsedMs();De!==void 0&&recordBootPhase(`httpListenMs`,De);let je=ge.address(),Me=typeof je==`object`&&je?je.port:e.port??0;if(fe=Me,j(ae,Me),ve&&updateUiLockPort(ae,Me),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ae,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let Pe=!1,Ie=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)}};we=async()=>{if(Pe)return;Pe=!0;let e=[],t=async(t,s)=>{try{await Ie(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{O(ae),ve&&markUiLockDraining(ae)}catch(e){S.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{Te?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>Ce.shutdown()),me!==void 0&&await t(`mcpHttpHandler.close`,()=>me.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{Ce.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{ge.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ge.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>Y()),ve&&await t(`releaseUiLock`,async()=>releaseUiLock(ae,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await reconcileSkillInstalls({projectDir:L,skillsRoot:resolve(e.contentDir,`.ok`,`skills`)}),s=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;s>0&&S.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${s} editor skill entr${s===1?`y`:`ies`} to the symlink model.`)}catch(e){S.warn?.({event:`installed-skills-reconcile-failed`,error:String(e)},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:ge,destroy:we,lockDir:ae,contentDir:e.contentDir,port:Me,ready:te,degraded:ne,didAutoInit:F,serverInstance:ee}}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`,`-z`]);E=new Set(splitNulSeparatedPaths(g))}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,t){try{let{stdout:s}=await execFileAsync(e,[`rev-parse`,`--is-inside-work-tree`],{cwd:t});return s.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}let w;try{w=assertGitAvailable()}catch(e){throw e instanceof GitNotAvailableError||e instanceof GitTooOldError?(emitPreflightFailureSpan(e),log.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof GitTooOldError?`too_old`:`not_available`,detectedVersion:e instanceof GitTooOldError?e.detected:``},e instanceof GitTooOldError?`git binary too old`:`git binary not found`)):log.warn({event:`git_preflight_unexpected_error`,message:e instanceof Error?e.message:String(e)},`unexpected error during git preflight`),e}let E=w.resolvedPath;if(!S&&await isInsideExistingWorkTree(E,t))return{didInit:!1};let D=``;try{D=(await execFileAsync(E,[`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)`,D);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(`OpenKnowledge 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/
|
|
3258
3258
|
`,`utf-8`),t}export{STARTER_PACKS as $,validateCloneInputs as $i,isAllowedWorkspaceHostHeader as $n,resetMetrics as $r,createExternalChangeHandler as $t,HocuspocusAuthRejection as A,spansCurrentPath as Ai,formatPackRationale as An,planSeed as Ar,bundleSkillMdPath as At,McpLogger as B,tracedLinkSync as Bi,handleCollabSocketError as Bn,readSkillInstallStateSnapshot as Br,compareSemver as Bt,FILE_WATCHER_ORIGIN as C,resolveGitDirDetailed as Ca,seedBasenameIndex as Ci,fallbackPaths as Cn,normalizeFsPath as Cr,bootServer as Ct,GitNotAvailableError as D,shadowGit as Di,formatAuthRejectionWire as Dn,parseHocuspocusAuthToken as Dr,buildSkillZip as Dt,GIT_UPSTREAM_WRITER as E,setupServerObservers as Ei,flushFileLogger as En,parseGitVersion as Er,buildExecResult as Et,MANAGED_RENAME_ORIGIN as F,streamingProblemEvent as Fi,getLogger as Fn,readArmedPaneTarget as Fr,clearEmbeddingsKeyFromAllBackends as Ft,PinoLogger as G,tracedRmSync as Gi,initContent as Gn,readUiLock as Gr,countStaleAgentWipRefs as Gt,OBSERVER_SYNC_ORIGIN as H,tracedMkdirSync as Hi,hasGcLogLatch as Hn,readStateManifest as Hr,contentHash as Ht,MAX_AGENT_SESSIONS as I,swapContributors as Ii,getLogsDir as In,readBranchFromHead as Ir,coercePackId as It,ROOT_GITIGNORE_TEMPLATE as J,tracedWriteFile as Ji,initToleranceTelemetryWriter as Jn,recordSkillInstallEvent as Jr,createAssetServeMiddleware as Jt,ProjectGitInitError as K,tracedRmdirSync as Ki,initShadowRepo as Kn,reconcile as Kr,countWipRefs as Kt,MCP_CONNECTION_ID_HEADER as L,teardownToleranceTelemetryWriter as Li,getMeter as Ln,readBundleDecision as Lr,commitUpstreamImport as Lt,INSTALLED_AGENTS_SCHEMES as M,spawnDetached as Mi,getCurrentMcpLogger as Mn,processCommand as Mr,classifyFsPath as Mt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as N,splitMarkdownBlocks as Ni,getLocalDir as Nn,processUsage as Nr,clearArmedPaneTarget as Nt,GitTooOldError as O,shutdownTelemetry as Oi,formatContributors as On,parseKeepaliveConnectionId as Or,buildStarterFolderFrontmatterYaml as Ot,LOG_MD_TEMPLATE as P,startWatcher as Pi,getLogFilePath as Pn,readAllTargets as Pr,clearContributors as Pt,STARTER_FOLDER_FRONTMATTER_FILENAME as Q,validateAgentId as Qi,isAllowedApiOrigin as Qn,removeLastKnownHash as Qr,createEphemeralProjectDir as Qt,MIN_GIT_VERSION as R,toBroadcasterKey as Ri,getMetrics as Rn,readProjectLocalSemanticConfig as Rr,commitWip as Rt,FILE_SYSTEM_WRITER as S,parseCheckpoint as Sa,saveVersion as Si,extractWikiLinksFromMarkdown as Sn,mountMcpAndApi as Sr,attachIdleShutdown as St,GIT_PREFLIGHT_FAIL_SPAN_NAME as T,setActiveSpanAttributes as Ti,findEnclosingProjectRoot as Tn,parseAuthRejectionWire as Tr,buildConfigYmlContent as Tt,OK_OKIGNORE_TEMPLATE as U,tracedRename as Ui,incrementCollabSocketFilteredError as Un,readTargetRecordedAt as Ur,contributorCount as Ut,MissingOkConfigError as V,tracedMkdir as Vi,handleSpawnCursor as Vn,readSkillManagement as Vr,containsConflictMarkers as Vt,PANE_TARGET_TTL_MS as W,tracedRenameSync as Wi,incrementServerObserverFire as Wn,readTargetVersion as Wr,countShadowObjects as Wt,SKILL_INSTALL_EVENTS_FILE_REL as X,updateLastKnownHash as Xi,installTestLoggers as Xn,registerWrite as Xr,createContentFilterAsync as Xt,SERVICE_WRITER as Y,tracedWriteFileSync as Yi,installPrettyZodErrors as Yn,registerAllTools as Yr,createContentFilter as Yt,STARTER_FOLDERS as Z,updateUiLockPort as Zi,installUserSkill as Zn,releaseUiLock as Zr,createEmbeddingsSecretStore as Zt,ConfigSchema as _,resolveConfigPath as _a,safeContentPath as _i,encodeSkillRoute as _n,loadPrincipal as _r,applySeed as _t,AgentPresenceBroadcaster as a,writeSkillManagement as aa,resolvePack as ai,createServer$1 as an,isManagedArtifactDoc as ar,SingleFileNotAFileError as at,DEFAULT_PACK_ID as b,GitDirAccessError as ba,sanitizeClientName as bi,evictStaleTrackerEntries as bn,logsPreviousPath as br,assertGitAvailable as bt,AutoStartDisabledError as c,writeTracker as ca,restoreContributors as ci,createTestLogger as cn,isProjectRoot as cr,StateManifestError as ct,BUNDLE_SKILL_NAME as d,LATEST_PROTOCOL_VERSION as da,rewriteWikiLinksForDocumentRename as di,detectGit as dn,isSelfWrite as dr,UiLockCollisionError as dt,validateSkillZip as ea,resolveBundledSkillDir as ei,createFileLogger as en,isConfigDoc as er,STARTER_PACK_IDS as et,BacklinkIndex as f,isInitializedNotification as fa,runAuthReposSubprocess as fi,detectProjectShape as fn,isSystemDoc as fr,__getShowAllWalkStatsForTesting as ft,CURSOR_BUNDLE_PATHS_BY_PLATFORM as g,readConfigSafely as ga,runWithMcpLogger as gi,encodeFolderRoute as gn,listStarterPacks as gr,applyExternalChange as gt,CONFLICT_MARKER_RE as h,atomicWriteFileSync as ha,runDeviceFlowSubprocess as hi,encodeDocName as hn,listRescueCheckpoints as hr,applyAgentMarkdownWrite as ht,AgentFocusBroadcaster as i,writeRootGitignoreForNewRepo as ia,resolveLockDir as ii,createPersistenceExtension as in,isLoopbackAddress as ir,SeedRootDirError as it,HocuspocusAuthTokenSchema as j,spansPreviousPath as ji,gcCheckpointRefs as jn,prepareSingleFileOpen as jr,classifyEvents as jt,HOCUSPOCUS_AUTH_REJECTION_REASONS as k,skillManagementPath as ki,formatContributorsFrom as kn,pathToDocName as kr,buildWipTree as kt,BUNDLE_IDS as l,McpServer as la,restoreLifecycleFromConflictsJson as li,describeStoredEmbeddingsKey as ln,isProjectSkillManaged as lr,TagIndex as lt,CONFIG_FILENAME as m,isJSONRPCResultResponse as ma,runCloneSubprocess as mi,emitPreflightFailureSpan as mn,lastKnownHash as mr,acquireUiLock as mt,AGENT_ID_RE as n,withSpanSync as na,resolveCursorBinaryDefault as ni,createMcpHttpHandler as nn,isKnownPackId as nr,STATE_MANIFEST_FILENAME as nt,AgentSessionCapacityError as o,writeStateManifest as oa,resolvePackageVersion as oi,createServerObserverExtension as on,isPairedWriteOrigin as or,SingleFileNotFoundError as ot,CC1Broadcaster as p,isJSONRPCRequest as pa,runAuthStatusSubprocess as pi,discoverLockDirs as pn,isToleranceTelemetryEnabled as pr,__resetShowAllWalkStatsForTesting as pt,ROLLBACK_ORIGIN as q,tracedUnlinkSync as qi,initTelemetry as qn,recordContributor as qr,createApiExtension as qt,AGENT_WRITE_ORIGIN as r,writeBundleDecision as ra,resolveCursorSpawnInvocation as ri,createOsProbe as rn,isLinkIndexExcludedDoc as rr,SeedPrerequisiteError as rt,AgentSessionManager as s,writeTargetVersion as sa,resolveUiInfo as si,createStreamingErrorWriter as sn,isPathWithinDir as sr,SingleFileNotMarkdownError as st,AGENT_ID_MAX_LEN as t,withSpan as ta,resolveContentDir as ti,createLiveDerivedIndexExtension as tn,isHocuspocusAuthRejectionReason as tr,STARTER_TEMPLATES as tt,BUNDLE_SCOPE as u,JSONRPCMessageSchema as ua,rewriteMarkdownLinksForDocumentRename as ui,detectClaudeDesktopPresence as un,isReservedForUserTree as ur,USER_GLOBAL_BUNDLE_IDS as ut,DEFAULT_CHECKPOINT_RETENTION as v,withFileLockSync as va,safeSubdir as vi,ensureProjectGit as vn,loggerFactory as vr,armPaneTarget as vt,FileEmbeddingsBackend as w,resolveShadowDir as wa,serializeError as wi,findEnclosingGitRoot as wn,packageVersionMajorMinor as wr,buildAndOpenSkill as wt,EMBEDDINGS_API_KEY_ENV as x,MalformedGitPointerError as xa,saveInMemoryCheckpoint as xi,extractOkBinaryPath as xn,makeLazyEmbeddingsKeyStore as xr,assertNeverDiskEvent as xt,DEFAULT_EMBEDDINGS_DIMENSIONS as y,writeConfigPatch as ya,safetyCheckpoint as yi,errorResponse as yn,logsCurrentPath as yr,assertCompatibleStateManifest as yt,MISSING_OK_CONFIG_MESSAGE as z,tracedAppendFileSync as zi,getTracer as zn,readServerPackageVersion as zr,commitWipFromTree as zt};
|
|
3259
|
-
//# sourceMappingURL=dist-
|
|
3259
|
+
//# sourceMappingURL=dist-CPsLcVzP.mjs.map
|