@inkeep/open-knowledge 0.21.0 → 0.21.1-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +1 -1
- package/dist/assets/skills/write-skill/SKILL.md +1 -1
- package/dist/cli.mjs +6 -6
- package/dist/constants-D_fn2gJ5.mjs +2 -0
- package/dist/{dist-1VwAWeko.mjs → dist-BoIBsVKQ.mjs} +4 -4
- package/dist/{dist-B7w8INvo.mjs → dist-CyrjbW_1.mjs} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/init-C2FFPegh.mjs +1 -0
- package/dist/{init-bEV7Zdcj.mjs → init-aFKryDql.mjs} +4 -4
- package/dist/loader-BRXvCpfb.mjs +1 -0
- package/dist/{loader-BHztUj3Y.mjs → loader-cHaFsfjb.mjs} +2 -2
- package/dist/preview-COxjHZAN.mjs +1 -0
- package/dist/{preview-Gk_dvsiY.mjs → preview-D-tqQRoR.mjs} +2 -2
- package/dist/public/assets/{ActivityModeContent-D247jYIx.js → ActivityModeContent-JcuqYTcN.js} +1 -1
- package/dist/public/assets/{DocumentContext-Dp34RL1b.js → DocumentContext-CS9CRE3q.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-3GfeTlU_.js → ManagedArtifactProperties-Cjg3FRVy.js} +1 -1
- package/dist/public/assets/{PropertyPanel-BPt3vBiZ.js → PropertyPanel-CraqaB9N.js} +1 -1
- package/dist/public/assets/{SettingsDialogBody-XSleH_pq.js → SettingsDialogBody-DkJ4RyFM.js} +1 -1
- package/dist/public/assets/{SourceEditor-67Xo2sLX.js → SourceEditor-28ru_CJh.js} +1 -1
- package/dist/public/assets/{config-validation-events-DC_j_did.js → config-validation-events-DP4yGHlz.js} +1 -1
- package/dist/public/assets/{index-B8UWwvZN.js → index-Cq9y9rMZ.js} +5 -5
- package/dist/public/assets/{selection-context-Dnus99C9.js → selection-context-Di_xmsrN.js} +1 -1
- package/dist/public/assets/{telemetry-impl-DZfG0f1d.js → telemetry-impl-BJxTjOze.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-B9U9Xf1T.js → typing-burst-detector-Ctlm0p3c.js} +1 -1
- package/dist/public/index.html +6 -6
- package/dist/{repair-launch-json-CkgTn5Nw.mjs → repair-launch-json-uFBfGKLP.mjs} +2 -2
- package/dist/{repair-mcp-configs-BiRRgleX.mjs → repair-mcp-configs-6LApQ0mX.mjs} +2 -2
- package/dist/repair-skills-BTQFXB6F.mjs +1 -0
- package/dist/{repair-skills-CxJ2qorQ.mjs → repair-skills-YawjMuJ1.mjs} +2 -2
- package/dist/{src-Depwoh5A.mjs → src-5CVv-qoH.mjs} +2 -2
- package/dist/{start-BKBgmBrV.mjs → start-CdzWaARn.mjs} +2 -2
- package/dist/start-DwYEgK3b.mjs +1 -0
- package/dist/{write-project-skill-BIAc-bQF.mjs → write-project-skill--BR_4GZD.mjs} +2 -2
- package/package.json +1 -1
- package/dist/constants-BJyjK2O3.mjs +0 -2
- package/dist/init-B0LRBzCQ.mjs +0 -1
- package/dist/loader-COH9hMAs.mjs +0 -1
- package/dist/preview-Dn1IFNsr.mjs +0 -1
- package/dist/repair-skills-BkkXENQk.mjs +0 -1
- package/dist/start-CWSh0suU.mjs +0 -1
|
@@ -35,10 +35,10 @@ To resolve the conflict:`,(0,g.getConflictResolutionRecipe)(S,e))),w=E):s.diag.w
|
|
|
35
35
|
`,`Details:
|
|
36
36
|
`,(0,g.getIncompatibilityDetails)(S,e),`To resolve the conflict:
|
|
37
37
|
`,(0,g.getConflictResolutionRecipe)(S,e))}return w}}})),require_MultiWritableMetricStorage=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiMetricStorage=void 0,e.MultiMetricStorage=class{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,s,g){this._backingStorages.forEach(S=>{S.record(e,t,s,g)})}}})),require_ObservableResult=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchObservableResultImpl=e.ObservableResultImpl=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_HashMap(),g=require_Instruments();e.ObservableResultImpl=class{_buffer=new s.AttributeHashMap;_instrumentName;_valueType;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,s={}){if(typeof e!=`number`){t.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===t.ValueType.INT&&!Number.isInteger(e)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(s,e)}},e.BatchObservableResultImpl=class{_buffer=new Map;observe(e,S,w={}){if(!(0,g.isObservableInstrument)(e))return;let E=this._buffer.get(e);if(E??(E=new s.AttributeHashMap,this._buffer.set(e,E)),typeof S!=`number`){t.diag.warn(`non-number value provided to metric ${e._descriptor.name}: ${S}`);return}e._descriptor.valueType===t.ValueType.INT&&!Number.isInteger(S)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),S=Math.trunc(S),!Number.isInteger(S))||E.set(w,S)}}})),require_ObservableRegistry=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ObservableRegistry=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_Instruments(),g=require_ObservableResult(),S=require_utils$3();e.ObservableRegistry=class{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let s=this._findCallback(e,t);s<0||this._callbacks.splice(s,1)}addBatchCallback(e,g){let S=new Set(g.filter(s.isObservableInstrument));if(S.size===0){t.diag.error(`BatchObservableCallback is not associated with valid instruments`,g);return}this._findBatchCallback(e,S)>=0||this._batchCallbacks.push({callback:e,instruments:S})}removeBatchCallback(e,t){let g=new Set(t.filter(s.isObservableInstrument)),S=this._findBatchCallback(e,g);S<0||this._batchCallbacks.splice(S,1)}async observe(e,t){let s=this._observeCallbacks(e,t),g=this._observeBatchCallbacks(e,t);return(await Promise.allSettled([...s,...g])).filter(e=>e.status===`rejected`).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:s,instrument:w})=>{let E=new g.ObservableResultImpl(w._descriptor.name,w._descriptor.valueType),D=Promise.resolve(s(E));t!=null&&(D=(0,S.callWithTimeout)(D,t)),await D,w._metricStorages.forEach(t=>{t.record(E._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:s,instruments:w})=>{let E=new g.BatchObservableResultImpl,D=Promise.resolve(s(E));t!=null&&(D=(0,S.callWithTimeout)(D,t)),await D,w.forEach(t=>{let s=E._buffer.get(t);s!=null&&t._metricStorages.forEach(t=>{t.record(s,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(s=>s.callback===e&&s.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(s=>s.callback===e&&(0,S.setEquals)(s.instruments,t))}}})),require_SyncMetricStorage=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SyncMetricStorage=void 0;let t=require_MetricStorage(),s=require_DeltaMetricProcessor(),g=require_TemporalMetricProcessor();e.SyncMetricStorage=class extends t.MetricStorage{_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;_attributesProcessor;constructor(e,t,S,w,E){super(e),this._aggregationCardinalityLimit=E,this._deltaMetricStorage=new s.DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new g.TemporalMetricProcessor(t,w),this._attributesProcessor=S}record(e,t,s,g){t=this._attributesProcessor.process(t,s),this._deltaMetricStorage.record(e,t,s,g)}collect(e,t){let s=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,s,t)}}})),require_AttributesProcessor=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.createMultiAttributesProcessor=e.createNoopAttributesProcessor=void 0;var t=class{process(e,t){return e}},s=class{_processors;constructor(e){this._processors=e}process(e,t){let s=e;for(let e of this._processors)s=e.process(s,t);return s}},g=class{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=e}process(e,t){let s={};return Object.keys(e).forEach(t=>{this._allowedAttributeNames.includes(t)&&(s[t]=e[t])}),s}},S=class{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=e}process(e,t){let s={};return Object.keys(e).forEach(t=>{this._deniedAttributeNames.includes(t)||(s[t]=e[t])}),s}};function w(){return k}e.createNoopAttributesProcessor=w;function E(e){return new s(e)}e.createMultiAttributesProcessor=E;function D(e){return new g(e)}e.createAllowListAttributesProcessor=D;function O(e){return new S(e)}e.createDenyListAttributesProcessor=O;let k=new t})),require_MeterSharedState=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSharedState=void 0;let t=require_InstrumentDescriptor(),s=require_Meter(),g=require_AsyncMetricStorage(),S=require_MetricStorageRegistry(),w=require_MultiWritableMetricStorage(),E=require_ObservableRegistry(),D=require_SyncMetricStorage(),O=require_AttributesProcessor();e.MeterSharedState=class{metricStorageRegistry=new S.MetricStorageRegistry;observableRegistry=new E.ObservableRegistry;meter;_meterProviderSharedState;_instrumentationScope;constructor(e,t){this.meter=new s.Meter(this),this._meterProviderSharedState=e,this._instrumentationScope=t}registerMetricStorage(e){let t=this._registerMetricStorage(e,D.SyncMetricStorage);return t.length===1?t[0]:new w.MultiMetricStorage(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,g.AsyncMetricStorage)}async collect(e,t,s){let g=await this.observableRegistry.observe(t,s?.timeoutMillis),S=this.metricStorageRegistry.getStorages(e);if(S.length===0)return null;let w=[];return S.forEach(s=>{let g=s.collect(e,t);g!=null&&w.push(g)}),w.length===0?{errors:g}:{scopeMetrics:{scope:this._instrumentationScope,metrics:w},errors:g}}_registerMetricStorage(e,s){let g=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(g=>{let S=(0,t.createInstrumentDescriptorWithView)(g,e),w=this.metricStorageRegistry.findOrUpdateCompatibleStorage(S);if(w!=null)return w;let E=new s(S,g.aggregation.createAggregator(S),g.attributesProcessor,this._meterProviderSharedState.metricCollectors,g.aggregationCardinalityLimit);return this.metricStorageRegistry.register(E),E});if(g.length===0){let t=this._meterProviderSharedState.selectAggregations(e.type).map(([t,g])=>{let S=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(t,e);if(S!=null)return S;let w=g.createAggregator(e),E=t.selectCardinalityLimit(e.type),D=new s(e,w,(0,O.createNoopAttributesProcessor)(),[t],E);return this.metricStorageRegistry.registerForCollector(t,D),D});g=g.concat(t)}return g}}})),require_MeterProviderSharedState=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProviderSharedState=void 0;let t=require_utils$3(),s=require_ViewRegistry(),g=require_MeterSharedState(),S=require_AggregationOption();e.MeterProviderSharedState=class{viewRegistry=new s.ViewRegistry;metricCollectors=[];meterSharedStates=new Map;resource;constructor(e){this.resource=e}getMeterSharedState(e){let s=(0,t.instrumentationScopeId)(e),S=this.meterSharedStates.get(s);return S??(S=new g.MeterSharedState(this,e),this.meterSharedStates.set(s,S)),S}selectAggregations(e){let t=[];for(let s of this.metricCollectors)t.push([s,(0,S.toAggregation)(s.selectAggregation(e))]);return t}}})),require_MetricCollector=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricCollector=void 0;let t=require_src$14();e.MetricCollector=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let s=(0,t.millisToHrTime)(Date.now()),g=[],S=[],w=Array.from(this._sharedState.meterSharedStates.values()).map(async t=>{let w=await t.collect(this,s,e);w?.scopeMetrics!=null&&g.push(w.scopeMetrics),w?.errors!=null&&S.push(...w.errors)});return await Promise.all(w),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:g},errors:S}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}})),require_Predicate=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExactPredicate=e.PatternPredicate=void 0;let t=/[\^$\\.+?()[\]{}|]/g;e.PatternPredicate=class e{_matchAll;_regexp;constructor(t){t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(t,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},e.ExactPredicate=class{_matchAll;_pattern;constructor(e){this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}}})),require_InstrumentSelector=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InstrumentSelector=void 0;let t=require_Predicate();e.InstrumentSelector=class{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new t.PatternPredicate(e?.name??`*`),this._type=e?.type,this._unitFilter=new t.ExactPredicate(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}})),require_MeterSelector=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSelector=void 0;let t=require_Predicate();e.MeterSelector=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new t.ExactPredicate(e?.name),this._versionFilter=new t.ExactPredicate(e?.version),this._schemaUrlFilter=new t.ExactPredicate(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}})),require_View=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.View=void 0;let t=require_Predicate(),s=require_AttributesProcessor(),g=require_InstrumentSelector(),S=require_MeterSelector(),w=require_AggregationOption();function E(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function D(e){if(E(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||t.PatternPredicate.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}e.View=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){D(e),e.attributesProcessors==null?this.attributesProcessor=(0,s.createNoopAttributesProcessor)():this.attributesProcessor=(0,s.createMultiAttributesProcessor)(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=(0,w.toAggregation)(e.aggregation??{type:w.AggregationType.DEFAULT}),this.instrumentSelector=new g.InstrumentSelector({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new S.MeterSelector({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),require_MeterProvider=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProvider=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$2(),g=require_MeterProviderSharedState(),S=require_MetricCollector(),w=require_View();e.MeterProvider=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new g.MeterProviderSharedState(e?.resource??(0,s.defaultResource)()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new w.View(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let e=new S.MetricCollector(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,s=``,g={}){return this._shutdown?(t.diag.warn(`A shutdown MeterProvider cannot provide a Meter`),(0,t.createNoopMeter)()):this._sharedState.getMeterSharedState({name:e,version:s,schemaUrl:g.schemaUrl}).meter}async shutdown(e){if(this._shutdown){t.diag.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){t.diag.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}})),require_src$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TimeoutError=e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.AggregationType=e.MeterProvider=e.ConsoleMetricExporter=e.InMemoryMetricExporter=e.PeriodicExportingMetricReader=e.MetricReader=e.InstrumentType=e.DataPointType=e.AggregationTemporality=void 0;var t=require_AggregationTemporality();Object.defineProperty(e,`AggregationTemporality`,{enumerable:!0,get:function(){return t.AggregationTemporality}});var s=require_MetricData();Object.defineProperty(e,`DataPointType`,{enumerable:!0,get:function(){return s.DataPointType}}),Object.defineProperty(e,`InstrumentType`,{enumerable:!0,get:function(){return s.InstrumentType}});var g=require_MetricReader();Object.defineProperty(e,`MetricReader`,{enumerable:!0,get:function(){return g.MetricReader}});var S=require_PeriodicExportingMetricReader();Object.defineProperty(e,`PeriodicExportingMetricReader`,{enumerable:!0,get:function(){return S.PeriodicExportingMetricReader}});var w=require_InMemoryMetricExporter();Object.defineProperty(e,`InMemoryMetricExporter`,{enumerable:!0,get:function(){return w.InMemoryMetricExporter}});var E=require_ConsoleMetricExporter();Object.defineProperty(e,`ConsoleMetricExporter`,{enumerable:!0,get:function(){return E.ConsoleMetricExporter}});var D=require_MeterProvider();Object.defineProperty(e,`MeterProvider`,{enumerable:!0,get:function(){return D.MeterProvider}});var O=require_AggregationOption();Object.defineProperty(e,`AggregationType`,{enumerable:!0,get:function(){return O.AggregationType}});var k=require_AttributesProcessor();Object.defineProperty(e,`createAllowListAttributesProcessor`,{enumerable:!0,get:function(){return k.createAllowListAttributesProcessor}}),Object.defineProperty(e,`createDenyListAttributesProcessor`,{enumerable:!0,get:function(){return k.createDenyListAttributesProcessor}});var j=require_utils$3();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return j.TimeoutError}})})),require_enums=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExceptionEventName=void 0,e.ExceptionEventName=`exception`})),require_Span=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SpanImpl=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$14(),g=(init_esm$1(),__toCommonJS(esm_exports$1)),S=require_enums();e.SpanImpl=class{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;_attributesCount=0;name;status={code:t.SpanStatusCode.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_recordEndMetrics;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(e){let t=Date.now();if(this._spanContext=e.spanContext,this._performanceStartTime=s.otperformance.now(),this._performanceOffset=t-(this._performanceStartTime+s.otperformance.timeOrigin),this._startTimeProvided=e.startTime!=null,this._spanLimits=e.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit??0,this._spanProcessor=e.spanProcessor,this.name=e.name,this.parentSpanContext=e.parentSpanContext,this.kind=e.kind,e.links)for(let t of e.links)this.addLink(t);this.startTime=this._getTime(e.startTime??t),this.resource=e.resource,this.instrumentationScope=e.scope,this._recordEndMetrics=e.recordEndMetrics,e.attributes!=null&&this.setAttributes(e.attributes),this._spanProcessor.onStart(this,e.context)}spanContext(){return this._spanContext}setAttribute(e,g){if(g==null||this._isSpanEnded())return this;if(e.length===0)return t.diag.warn(`Invalid attribute key: ${e}`),this;if(!(0,s.isAttributeValue)(g))return t.diag.warn(`Invalid attribute value set for key: ${e}`),this;let{attributeCountLimit:S}=this._spanLimits,w=!Object.prototype.hasOwnProperty.call(this.attributes,e);return S!==void 0&&this._attributesCount>=S&&w?(this._droppedAttributesCount++,this):(this.attributes[e]=this._truncateToSize(g),w&&this._attributesCount++,this)}setAttributes(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setAttribute(t,e[t]);return this}addEvent(e,g,S){if(this._isSpanEnded())return this;let{eventCountLimit:w}=this._spanLimits;if(w===0)return t.diag.warn(`No events allowed.`),this._droppedEventsCount++,this;w!==void 0&&this.events.length>=w&&(this._droppedEventsCount===0&&t.diag.debug(`Dropping extra events.`),this.events.shift(),this._droppedEventsCount++),(0,s.isTimeInput)(g)&&((0,s.isTimeInput)(S)||(S=g),g=void 0);let E=(0,s.sanitizeAttributes)(g),{attributePerEventCountLimit:D}=this._spanLimits,O={},k=0,j=0;for(let e in E){if(!Object.prototype.hasOwnProperty.call(E,e))continue;let t=E[e];if(D!==void 0&&j>=D){k++;continue}O[e]=this._truncateToSize(t),j++}return this.events.push({name:e,attributes:O,time:this._getTime(S),droppedAttributesCount:k}),this}addLink(e){if(this._isSpanEnded())return this;let{linkCountLimit:g}=this._spanLimits;if(g===0)return this._droppedLinksCount++,this;g!==void 0&&this.links.length>=g&&(this._droppedLinksCount===0&&t.diag.debug(`Dropping extra links.`),this.links.shift(),this._droppedLinksCount++);let{attributePerLinkCountLimit:S}=this._spanLimits,w=(0,s.sanitizeAttributes)(e.attributes),E={},D=0,O=0;for(let e in w){if(!Object.prototype.hasOwnProperty.call(w,e))continue;let t=w[e];if(S!==void 0&&O>=S){D++;continue}E[e]=this._truncateToSize(t),O++}let k={context:e.context};return O>0&&(k.attributes=E),D>0&&(k.droppedAttributesCount=D),this.links.push(k),this}addLinks(e){for(let t of e)this.addLink(t);return this}setStatus(e){if(this._isSpanEnded()||e.code===t.SpanStatusCode.UNSET||this.status.code===t.SpanStatusCode.OK)return this;let s={code:e.code};return e.code===t.SpanStatusCode.ERROR&&(typeof e.message==`string`?s.message=e.message:e.message!=null&&t.diag.warn(`Dropping invalid status.message of type '${typeof e.message}', expected 'string'`)),this.status=s,this}updateName(e){return this._isSpanEnded()||(this.name=e),this}end(e){if(this._isSpanEnded()){t.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`);return}this.endTime=this._getTime(e),this._duration=(0,s.hrTimeDuration)(this.startTime,this.endTime),this._duration[0]<0&&(t.diag.warn(`Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.`,this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&t.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._droppedLinksCount>0&&t.diag.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`),this._spanProcessor.onEnding&&this._spanProcessor.onEnding(this),this._recordEndMetrics?.(),this._ended=!0,this._spanProcessor.onEnd(this)}_getTime(e){if(typeof e==`number`&&e<=s.otperformance.now())return(0,s.hrTime)(e+this._performanceOffset);if(typeof e==`number`)return(0,s.millisToHrTime)(e);if(e instanceof Date)return(0,s.millisToHrTime)(e.getTime());if((0,s.isTimeInputHrTime)(e))return e;if(this._startTimeProvided)return(0,s.millisToHrTime)(Date.now());let t=s.otperformance.now()-this._performanceStartTime;return(0,s.addHrTimes)(this.startTime,(0,s.millisToHrTime)(t))}isRecording(){return this._ended===!1}recordException(e,s){let w={};typeof e==`string`?w[g.ATTR_EXCEPTION_MESSAGE]=e:e&&(e.code?w[g.ATTR_EXCEPTION_TYPE]=e.code.toString():e.name&&(w[g.ATTR_EXCEPTION_TYPE]=e.name),e.message&&(w[g.ATTR_EXCEPTION_MESSAGE]=e.message),e.stack&&(w[g.ATTR_EXCEPTION_STACKTRACE]=e.stack)),w[g.ATTR_EXCEPTION_TYPE]||w[g.ATTR_EXCEPTION_MESSAGE]?this.addEvent(S.ExceptionEventName,w,s):t.diag.warn(`Failed to record an exception ${e}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){let e=Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);t.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,e)}return this._ended}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_truncateToSize(e){let s=this._attributeValueLengthLimit;return s<=0?(t.diag.warn(`Attribute value limit must be positive, got ${s}`),e):typeof e==`string`?this._truncateToLimitUtil(e,s):Array.isArray(e)?e.map(e=>typeof e==`string`?this._truncateToLimitUtil(e,s):e):e}}})),require_Sampler=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SamplingDecision=void 0,(function(e){e[e.NOT_RECORD=0]=`NOT_RECORD`,e[e.RECORD=1]=`RECORD`,e[e.RECORD_AND_SAMPLED=2]=`RECORD_AND_SAMPLED`})(e.SamplingDecision||={})})),require_AlwaysOffSampler=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AlwaysOffSampler=void 0;let t=require_Sampler();e.AlwaysOffSampler=class{shouldSample(){return{decision:t.SamplingDecision.NOT_RECORD}}toString(){return`AlwaysOffSampler`}}})),require_AlwaysOnSampler=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AlwaysOnSampler=void 0;let t=require_Sampler();e.AlwaysOnSampler=class{shouldSample(){return{decision:t.SamplingDecision.RECORD_AND_SAMPLED}}toString(){return`AlwaysOnSampler`}}})),require_ParentBasedSampler=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ParentBasedSampler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$14(),g=require_AlwaysOffSampler(),S=require_AlwaysOnSampler();e.ParentBasedSampler=class{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(e){this._root=e.root,this._root||=((0,s.globalErrorHandler)(Error(`ParentBasedSampler must have a root sampler configured`)),new S.AlwaysOnSampler),this._remoteParentSampled=e.remoteParentSampled??new S.AlwaysOnSampler,this._remoteParentNotSampled=e.remoteParentNotSampled??new g.AlwaysOffSampler,this._localParentSampled=e.localParentSampled??new S.AlwaysOnSampler,this._localParentNotSampled=e.localParentNotSampled??new g.AlwaysOffSampler}shouldSample(e,s,g,S,w,E){let D=t.trace.getSpanContext(e);return!D||!(0,t.isSpanContextValid)(D)?this._root.shouldSample(e,s,g,S,w,E):D.isRemote?D.traceFlags&t.TraceFlags.SAMPLED?this._remoteParentSampled.shouldSample(e,s,g,S,w,E):this._remoteParentNotSampled.shouldSample(e,s,g,S,w,E):D.traceFlags&t.TraceFlags.SAMPLED?this._localParentSampled.shouldSample(e,s,g,S,w,E):this._localParentNotSampled.shouldSample(e,s,g,S,w,E)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}})),require_TraceIdRatioBasedSampler=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TraceIdRatioBasedSampler=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_Sampler();e.TraceIdRatioBasedSampler=class{_ratio;_upperBound;constructor(e=0){this._ratio=this._normalize(e),this._upperBound=Math.floor(this._ratio*4294967295)}shouldSample(e,g){return{decision:(0,t.isValidTraceId)(g)&&this._accumulate(g)<this._upperBound?s.SamplingDecision.RECORD_AND_SAMPLED:s.SamplingDecision.NOT_RECORD}}toString(){return`TraceIdRatioBased{${this._ratio}}`}_normalize(e){return typeof e!=`number`||isNaN(e)?0:e>=1?1:e<=0?0:e}_accumulate(e){let t=0;for(let s=0;s<e.length/8;s++){let g=s*8,S=parseInt(e.slice(g,g+8),16);t=(t^S)>>>0}return t}}})),require_config=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.buildSamplerFromEnv=e.loadDefaultConfig=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$14(),g=require_AlwaysOffSampler(),S=require_AlwaysOnSampler(),w=require_ParentBasedSampler(),E=require_TraceIdRatioBasedSampler();var D;(function(e){e.AlwaysOff=`always_off`,e.AlwaysOn=`always_on`,e.ParentBasedAlwaysOff=`parentbased_always_off`,e.ParentBasedAlwaysOn=`parentbased_always_on`,e.ParentBasedTraceIdRatio=`parentbased_traceidratio`,e.TraceIdRatio=`traceidratio`})(D||={});let O=1;function k(){return{sampler:j(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:(0,s.getNumberFromEnv)(`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,attributeCountLimit:(0,s.getNumberFromEnv)(`OTEL_ATTRIBUTE_COUNT_LIMIT`)??128},spanLimits:{attributeValueLengthLimit:(0,s.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,attributeCountLimit:(0,s.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`)??128,linkCountLimit:(0,s.getNumberFromEnv)(`OTEL_SPAN_LINK_COUNT_LIMIT`)??128,eventCountLimit:(0,s.getNumberFromEnv)(`OTEL_SPAN_EVENT_COUNT_LIMIT`)??128,attributePerEventCountLimit:(0,s.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT`)??128,attributePerLinkCountLimit:(0,s.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT`)??128}}}e.loadDefaultConfig=k;function j(){let e=(0,s.getStringFromEnv)(`OTEL_TRACES_SAMPLER`)??D.ParentBasedAlwaysOn;switch(e){case D.AlwaysOn:return new S.AlwaysOnSampler;case D.AlwaysOff:return new g.AlwaysOffSampler;case D.ParentBasedAlwaysOn:return new w.ParentBasedSampler({root:new S.AlwaysOnSampler});case D.ParentBasedAlwaysOff:return new w.ParentBasedSampler({root:new g.AlwaysOffSampler});case D.TraceIdRatio:return new E.TraceIdRatioBasedSampler(F());case D.ParentBasedTraceIdRatio:return new w.ParentBasedSampler({root:new E.TraceIdRatioBasedSampler(F())});default:return t.diag.error(`OTEL_TRACES_SAMPLER value "${e}" invalid, defaulting to "${D.ParentBasedAlwaysOn}".`),new w.ParentBasedSampler({root:new S.AlwaysOnSampler})}}e.buildSamplerFromEnv=j;function F(){let e=(0,s.getNumberFromEnv)(`OTEL_TRACES_SAMPLER_ARG`);return e==null?(t.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to 1.`),1):e<0||e>1?(t.diag.error(`OTEL_TRACES_SAMPLER_ARG=${e} was given, but it is out of range ([0..1]), defaulting to 1.`),1):e}})),require_utility=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reconfigureLimits=e.mergeConfig=e.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=e.DEFAULT_ATTRIBUTE_COUNT_LIMIT=void 0;let t=require_config(),s=require_src$14();e.DEFAULT_ATTRIBUTE_COUNT_LIMIT=128,e.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=1/0;function g(e){let s={sampler:(0,t.buildSamplerFromEnv)()},g=(0,t.loadDefaultConfig)(),S=Object.assign({},g,s,e);return S.generalLimits=Object.assign({},g.generalLimits,e.generalLimits||{}),S.spanLimits=Object.assign({},g.spanLimits,e.spanLimits||{}),S}e.mergeConfig=g;function S(t){let g=Object.assign({},t.spanLimits);return g.attributeCountLimit=t.spanLimits?.attributeCountLimit??t.generalLimits?.attributeCountLimit??(0,s.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`)??(0,s.getNumberFromEnv)(`OTEL_ATTRIBUTE_COUNT_LIMIT`)??e.DEFAULT_ATTRIBUTE_COUNT_LIMIT,g.attributeValueLengthLimit=t.spanLimits?.attributeValueLengthLimit??t.generalLimits?.attributeValueLengthLimit??(0,s.getNumberFromEnv)(`OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??(0,s.getNumberFromEnv)(`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??e.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,Object.assign({},t,{spanLimits:g})}e.reconfigureLimits=S})),require_BatchSpanProcessorBase=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchSpanProcessorBase=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$14();e.BatchSpanProcessorBase=class{_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_exporter;_isExporting=!1;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(e,g){this._exporter=e,this._maxExportBatchSize=typeof g?.maxExportBatchSize==`number`?g.maxExportBatchSize:(0,s.getNumberFromEnv)(`OTEL_BSP_MAX_EXPORT_BATCH_SIZE`)??512,this._maxQueueSize=typeof g?.maxQueueSize==`number`?g.maxQueueSize:(0,s.getNumberFromEnv)(`OTEL_BSP_MAX_QUEUE_SIZE`)??2048,this._scheduledDelayMillis=typeof g?.scheduledDelayMillis==`number`?g.scheduledDelayMillis:(0,s.getNumberFromEnv)(`OTEL_BSP_SCHEDULE_DELAY`)??5e3,this._exportTimeoutMillis=typeof g?.exportTimeoutMillis==`number`?g.exportTimeoutMillis:(0,s.getNumberFromEnv)(`OTEL_BSP_EXPORT_TIMEOUT`)??3e4,this._shutdownOnce=new s.BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(t.diag.warn(`BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize`),this._maxExportBatchSize=this._maxQueueSize)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(e,t){}onEnd(e){this._shutdownOnce.isCalled||(e.spanContext().traceFlags&t.TraceFlags.SAMPLED)!==0&&this._addToBuffer(e)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>this._exporter.shutdown())}_addToBuffer(e){if(this._finishedSpans.length>=this._maxQueueSize){this._droppedSpansCount===0&&t.diag.debug(`maxQueueSize reached, dropping spans`),this._droppedSpansCount++;return}this._droppedSpansCount>0&&(t.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(e),this._maybeStartTimer()}_flushAll(){return new Promise((e,t)=>{let s=[],g=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);for(let e=0,t=g;e<t;e++)s.push(this._flushOneBatch());Promise.all(s).then(()=>{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),this._finishedSpans.length===0?Promise.resolve():new Promise((e,g)=>{let S=setTimeout(()=>{g(Error(`Timeout`))},this._exportTimeoutMillis);t.context.with((0,s.suppressTracing)(t.context.active()),()=>{let t;this._finishedSpans.length<=this._maxExportBatchSize?(t=this._finishedSpans,this._finishedSpans=[]):t=this._finishedSpans.splice(0,this._maxExportBatchSize);let w=()=>this._exporter.export(t,t=>{clearTimeout(S),t.code===s.ExportResultCode.SUCCESS?e():g(t.error??Error(`BatchSpanProcessor: span export failed`))}),E=null;for(let e=0,s=t.length;e<s;e++){let s=t[e];s.resource.asyncAttributesPending&&s.resource.waitForAsyncAttributes&&(E??=[],E.push(s.resource.waitForAsyncAttributes()))}E===null?w():Promise.all(E).then(w,e=>{(0,s.globalErrorHandler)(e),g(e)})})})}_maybeStartTimer(){if(this._isExporting)return;let e=()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{this._isExporting=!1,(0,s.globalErrorHandler)(e)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return e();this._timer===void 0&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),typeof this._timer!=`number`&&this._timer.unref())}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}}})),require_BatchSpanProcessor=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchSpanProcessor=void 0;let t=require_BatchSpanProcessorBase();e.BatchSpanProcessor=class extends t.BatchSpanProcessorBase{onShutdown(){}}})),require_RandomIdGenerator=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.RandomIdGenerator=void 0;let t=8,s=16;e.RandomIdGenerator=class{generateTraceId=S(16);generateSpanId=S(8)};let g=Buffer.allocUnsafe(16);function S(e){return function(){for(let t=0;t<e/4;t++)g.writeUInt32BE(Math.random()*2**32>>>0,t*4);for(let t=0;t<e&&!(g[t]>0);t++)t===e-1&&(g[e-1]=1);return g.toString(`hex`,0,e)}}})),require_node=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.RandomIdGenerator=e.BatchSpanProcessor=void 0;var t=require_BatchSpanProcessor();Object.defineProperty(e,`BatchSpanProcessor`,{enumerable:!0,get:function(){return t.BatchSpanProcessor}});var s=require_RandomIdGenerator();Object.defineProperty(e,`RandomIdGenerator`,{enumerable:!0,get:function(){return s.RandomIdGenerator}})})),require_platform=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.RandomIdGenerator=e.BatchSpanProcessor=void 0;var t=require_node();Object.defineProperty(e,`BatchSpanProcessor`,{enumerable:!0,get:function(){return t.BatchSpanProcessor}}),Object.defineProperty(e,`RandomIdGenerator`,{enumerable:!0,get:function(){return t.RandomIdGenerator}})})),require_semconv=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.METRIC_OTEL_SDK_SPAN_STARTED=e.METRIC_OTEL_SDK_SPAN_LIVE=e.ATTR_OTEL_SPAN_SAMPLING_RESULT=e.ATTR_OTEL_SPAN_PARENT_ORIGIN=void 0,e.ATTR_OTEL_SPAN_PARENT_ORIGIN=`otel.span.parent.origin`,e.ATTR_OTEL_SPAN_SAMPLING_RESULT=`otel.span.sampling_result`,e.METRIC_OTEL_SDK_SPAN_LIVE=`otel.sdk.span.live`,e.METRIC_OTEL_SDK_SPAN_STARTED=`otel.sdk.span.started`})),require_TracerMetrics=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TracerMetrics=void 0;let t=require_Sampler(),s=require_semconv();e.TracerMetrics=class{startedSpans;liveSpans;constructor(e){this.startedSpans=e.createCounter(s.METRIC_OTEL_SDK_SPAN_STARTED,{unit:`{span}`,description:`The number of created spans.`}),this.liveSpans=e.createUpDownCounter(s.METRIC_OTEL_SDK_SPAN_LIVE,{unit:`{span}`,description:`The number of currently live spans.`})}startSpan(e,w){let E=S(w);if(this.startedSpans.add(1,{[s.ATTR_OTEL_SPAN_PARENT_ORIGIN]:g(e),[s.ATTR_OTEL_SPAN_SAMPLING_RESULT]:E}),w===t.SamplingDecision.NOT_RECORD)return()=>{};let D={[s.ATTR_OTEL_SPAN_SAMPLING_RESULT]:E};return this.liveSpans.add(1,D),()=>{this.liveSpans.add(-1,D)}}};function g(e){return e?e.isRemote?`remote`:`local`:`none`}function S(e){switch(e){case t.SamplingDecision.RECORD_AND_SAMPLED:return`RECORD_AND_SAMPLE`;case t.SamplingDecision.RECORD:return`RECORD_ONLY`;case t.SamplingDecision.NOT_RECORD:return`DROP`}}})),require_version=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.7.0`})),require_Tracer=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Tracer=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$14(),g=require_Span(),S=require_utility(),w=require_platform(),E=require_TracerMetrics(),D=require_version();e.Tracer=class{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;_tracerMetrics;constructor(e,s,g,O){let k=(0,S.mergeConfig)(s);this._sampler=k.sampler,this._generalLimits=k.generalLimits,this._spanLimits=k.spanLimits,this._idGenerator=s.idGenerator||new w.RandomIdGenerator,this._resource=g,this._spanProcessor=O,this.instrumentationScope=e;let j=k.meterProvider?k.meterProvider.getMeter(`@opentelemetry/sdk-trace`,D.VERSION):t.createNoopMeter();this._tracerMetrics=new E.TracerMetrics(j)}startSpan(e,S={},w=t.context.active()){S.root&&(w=t.trace.deleteSpan(w));let E=t.trace.getSpan(w);if((0,s.isTracingSuppressed)(w))return t.diag.debug(`Instrumentation suppressed, returning Noop Span`),t.trace.wrapSpanContext(t.INVALID_SPAN_CONTEXT);let D=E?.spanContext(),O=this._idGenerator.generateSpanId(),k,j,F;!D||!t.trace.isSpanContextValid(D)?j=this._idGenerator.generateTraceId():(j=D.traceId,F=D.traceState,k=D);let L=S.kind??t.SpanKind.INTERNAL,B=(S.links??[]).map(e=>({context:e.context,attributes:(0,s.sanitizeAttributes)(e.attributes)})),H=(0,s.sanitizeAttributes)(S.attributes),q=this._sampler.shouldSample(w,j,e,L,H,B),ee=this._tracerMetrics.startSpan(D,q.decision);F=q.traceState??F;let J=q.decision===t.SamplingDecision.RECORD_AND_SAMPLED?t.TraceFlags.SAMPLED:t.TraceFlags.NONE,Y={traceId:j,spanId:O,traceFlags:J,traceState:F};if(q.decision===t.SamplingDecision.NOT_RECORD)return t.diag.debug(`Recording is off, propagating context in a non-recording span`),t.trace.wrapSpanContext(Y);let te=(0,s.sanitizeAttributes)(Object.assign(H,q.attributes));return new g.SpanImpl({resource:this._resource,scope:this.instrumentationScope,context:w,spanContext:Y,name:e,kind:L,links:B,parentSpanContext:k,attributes:te,startTime:S.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits,recordEndMetrics:ee})}startActiveSpan(e,s,g,S){let w,E,D;if(arguments.length<2)return;arguments.length===2?D=s:arguments.length===3?(w=s,D=g):(w=s,E=g,D=S);let O=E??t.context.active(),k=this.startSpan(e,w,O),j=t.trace.setSpan(O,k);return t.context.with(j,D,void 0,k)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}})),require_MultiSpanProcessor=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiSpanProcessor=void 0;let t=require_src$14();e.MultiSpanProcessor=class{_spanProcessors;constructor(e){this._spanProcessors=e}forceFlush(){let e=[];for(let t of this._spanProcessors)e.push(t.forceFlush());return new Promise(s=>{Promise.all(e).then(()=>{s()}).catch(e=>{(0,t.globalErrorHandler)(e||Error(`MultiSpanProcessor: forceFlush failed`)),s()})})}onStart(e,t){for(let s of this._spanProcessors)s.onStart(e,t)}onEnding(e){for(let t of this._spanProcessors)t.onEnding&&t.onEnding(e)}onEnd(e){for(let t of this._spanProcessors)t.onEnd(e)}shutdown(){let e=[];for(let t of this._spanProcessors)e.push(t.shutdown());return new Promise((t,s)=>{Promise.all(e).then(()=>{t()},s)})}}})),require_BasicTracerProvider=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BasicTracerProvider=e.ForceFlushState=void 0;let t=require_src$14(),s=require_src$2(),g=require_Tracer(),S=require_config(),w=require_MultiSpanProcessor(),E=require_utility();var D;(function(e){e[e.resolved=0]=`resolved`,e[e.timeout=1]=`timeout`,e[e.error=2]=`error`,e[e.unresolved=3]=`unresolved`})(D=e.ForceFlushState||={}),e.BasicTracerProvider=class{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(e={}){let g=(0,t.merge)({},(0,S.loadDefaultConfig)(),(0,E.reconfigureLimits)(e));this._resource=g.resource??(0,s.defaultResource)(),this._config=Object.assign({},g,{resource:this._resource});let D=[];e.spanProcessors?.length&&D.push(...e.spanProcessors),this._activeSpanProcessor=new w.MultiSpanProcessor(D)}getTracer(e,t,s){let S=`${e}@${t||``}:${s?.schemaUrl||``}`;return this._tracers.has(S)||this._tracers.set(S,new g.Tracer({name:e,version:t,schemaUrl:s?.schemaUrl},this._config,this._resource,this._activeSpanProcessor)),this._tracers.get(S)}forceFlush(){let e=this._config.forceFlushTimeoutMillis,t=this._activeSpanProcessor._spanProcessors.map(t=>new Promise(s=>{let g,S=setTimeout(()=>{s(Error(`Span processor did not completed within timeout period of ${e} ms`)),g=D.timeout},e);t.forceFlush().then(()=>{clearTimeout(S),g!==D.timeout&&(g=D.resolved,s(g))}).catch(e=>{clearTimeout(S),g=D.error,s(e)})}));return new Promise((e,s)=>{Promise.all(t).then(t=>{let g=t.filter(e=>e!==D.resolved);g.length>0?s(g):e()}).catch(e=>s([e]))})}shutdown(){return this._activeSpanProcessor.shutdown()}}})),require_ConsoleSpanExporter=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ConsoleSpanExporter=void 0;let t=require_src$14();e.ConsoleSpanExporter=class{export(e,t){return this._sendSpans(e,t)}shutdown(){return this._sendSpans([]),this.forceFlush()}forceFlush(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,traceId:e.spanContext().traceId,parentSpanContext:e.parentSpanContext,traceState:e.spanContext().traceState?.serialize(),name:e.name,id:e.spanContext().spanId,kind:e.kind,timestamp:(0,t.hrTimeToMicroseconds)(e.startTime),duration:(0,t.hrTimeToMicroseconds)(e.duration),attributes:e.attributes,status:e.status,events:e.events,links:e.links}}_sendSpans(e,s){for(let t of e)console.dir(this._exportInfo(t),{depth:3});if(s)return s({code:t.ExportResultCode.SUCCESS})}}})),require_InMemorySpanExporter=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InMemorySpanExporter=void 0;let t=require_src$14();e.InMemorySpanExporter=class{_finishedSpans=[];_stopped=!1;export(e,s){if(this._stopped)return s({code:t.ExportResultCode.FAILED,error:Error(`Exporter has been stopped`)});this._finishedSpans.push(...e),setTimeout(()=>s({code:t.ExportResultCode.SUCCESS}),0)}shutdown(){return this._stopped=!0,this._finishedSpans=[],this.forceFlush()}forceFlush(){return Promise.resolve()}reset(){this._finishedSpans=[]}getFinishedSpans(){return this._finishedSpans}}})),require_SimpleSpanProcessor=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SimpleSpanProcessor=void 0;let t=(init_esm$2(),__toCommonJS(esm_exports$2)),s=require_src$14();e.SimpleSpanProcessor=class{_exporter;_shutdownOnce;_pendingExports;constructor(e){this._exporter=e,this._shutdownOnce=new s.BindOnceFuture(this._shutdown,this),this._pendingExports=new Set}async forceFlush(){await Promise.all(Array.from(this._pendingExports)),this._exporter.forceFlush&&await this._exporter.forceFlush()}onStart(e,t){}onEnd(e){if(this._shutdownOnce.isCalled||(e.spanContext().traceFlags&t.TraceFlags.SAMPLED)===0)return;let g=this._doExport(e).catch(e=>(0,s.globalErrorHandler)(e));this._pendingExports.add(g),g.finally(()=>this._pendingExports.delete(g))}async _doExport(e){e.resource.asyncAttributesPending&&await e.resource.waitForAsyncAttributes?.();let t=await s.internal._export(this._exporter,[e]);if(t.code!==s.ExportResultCode.SUCCESS)throw t.error??Error(`SimpleSpanProcessor: span export failed (status ${t})`)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}})),require_NoopSpanProcessor=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.NoopSpanProcessor=void 0,e.NoopSpanProcessor=class{onStart(e,t){}onEnd(e){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}}})),require_src=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SamplingDecision=e.TraceIdRatioBasedSampler=e.ParentBasedSampler=e.AlwaysOnSampler=e.AlwaysOffSampler=e.NoopSpanProcessor=e.SimpleSpanProcessor=e.InMemorySpanExporter=e.ConsoleSpanExporter=e.RandomIdGenerator=e.BatchSpanProcessor=e.BasicTracerProvider=void 0;var t=require_BasicTracerProvider();Object.defineProperty(e,`BasicTracerProvider`,{enumerable:!0,get:function(){return t.BasicTracerProvider}});var s=require_platform();Object.defineProperty(e,`BatchSpanProcessor`,{enumerable:!0,get:function(){return s.BatchSpanProcessor}}),Object.defineProperty(e,`RandomIdGenerator`,{enumerable:!0,get:function(){return s.RandomIdGenerator}});var g=require_ConsoleSpanExporter();Object.defineProperty(e,`ConsoleSpanExporter`,{enumerable:!0,get:function(){return g.ConsoleSpanExporter}});var S=require_InMemorySpanExporter();Object.defineProperty(e,`InMemorySpanExporter`,{enumerable:!0,get:function(){return S.InMemorySpanExporter}});var w=require_SimpleSpanProcessor();Object.defineProperty(e,`SimpleSpanProcessor`,{enumerable:!0,get:function(){return w.SimpleSpanProcessor}});var E=require_NoopSpanProcessor();Object.defineProperty(e,`NoopSpanProcessor`,{enumerable:!0,get:function(){return E.NoopSpanProcessor}});var D=require_AlwaysOffSampler();Object.defineProperty(e,`AlwaysOffSampler`,{enumerable:!0,get:function(){return D.AlwaysOffSampler}});var O=require_AlwaysOnSampler();Object.defineProperty(e,`AlwaysOnSampler`,{enumerable:!0,get:function(){return O.AlwaysOnSampler}});var k=require_ParentBasedSampler();Object.defineProperty(e,`ParentBasedSampler`,{enumerable:!0,get:function(){return k.ParentBasedSampler}});var j=require_TraceIdRatioBasedSampler();Object.defineProperty(e,`TraceIdRatioBasedSampler`,{enumerable:!0,get:function(){return j.TraceIdRatioBasedSampler}});var F=require_Sampler();Object.defineProperty(e,`SamplingDecision`,{enumerable:!0,get:function(){return F.SamplingDecision}})})),require_utils$2=__commonJSMin$2(((e,t)=>{function s(e){if(e.length===0)return;let t=Object.create(null),s=0;for(;s<e.length;++s){let t=e.charCodeAt(s);if(j[t]!==1){if(t!==47||s===0)return;break}}if(s===e.length)return;let S=e.slice(0,s).toLowerCase(),w=++s;for(;s<e.length;++s)if(j[e.charCodeAt(s)]!==1){if(s===w||g(e,s,t)===void 0)return;break}if(s!==w)return{type:S,subtype:e.slice(w,s).toLowerCase(),params:t}}function g(e,t,s){for(;t<e.length;){for(;t<e.length;++t){let s=e.charCodeAt(t);if(s!==32&&s!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let s=e.charCodeAt(t);if(s!==32&&s!==9)break}if(t===e.length)return;let g,S=t;for(;t<e.length;++t){let s=e.charCodeAt(t);if(j[s]!==1){if(s!==61)return;break}}if(t===e.length||(g=e.slice(S,t),++t,t===e.length))return;let w=``,E;if(e.charCodeAt(t)===34){E=++t;let s=!1;for(;t<e.length;++t){let g=e.charCodeAt(t);if(g===92){s?(E=t,s=!1):(w+=e.slice(E,t),s=!0);continue}if(g===34){if(s){E=t,s=!1;continue}w+=e.slice(E,t);break}if(s&&=(E=t-1,!1),F[g]!==1)return}if(t===e.length)return;++t}else{for(E=t;t<e.length;++t)if(j[e.charCodeAt(t)]!==1){if(t===E)return;break}w=e.slice(E,t)}g=g.toLowerCase(),s[g]===void 0&&(s[g]=w)}return s}function S(e,t){if(e.length===0)return;let s=Object.create(null),g=0;for(;g<e.length;++g)if(j[e.charCodeAt(g)]!==1){if(w(e,g,s,t)===void 0)return;break}return{type:e.slice(0,g).toLowerCase(),params:s}}function w(e,t,s,g){for(;t<e.length;){for(;t<e.length;++t){let s=e.charCodeAt(t);if(s!==32&&s!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let s=e.charCodeAt(t);if(s!==32&&s!==9)break}if(t===e.length)return;let S,w=t;for(;t<e.length;++t){let s=e.charCodeAt(t);if(j[s]!==1){if(s===61)break;return}}if(t===e.length)return;let E=``,D,k;if(S=e.slice(w,t),S.charCodeAt(S.length-1)===42){let s=++t;for(;t<e.length;++t){let s=e.charCodeAt(t);if(L[s]!==1){if(s!==39)return;break}}if(t===e.length)return;for(k=e.slice(s,t),++t;t<e.length&&e.charCodeAt(t)!==39;++t);if(t===e.length||(++t,t===e.length))return;D=t;let g=0;for(;t<e.length;++t){let s=e.charCodeAt(t);if(B[s]!==1){if(s===37){let s,S;if(t+2<e.length&&(s=H[e.charCodeAt(t+1)])!==-1&&(S=H[e.charCodeAt(t+2)])!==-1){let w=(s<<4)+S;E+=e.slice(D,t),E+=String.fromCharCode(w),t+=2,D=t+1,w>=128?g=2:g===0&&(g=1);continue}return}break}}if(E+=e.slice(D,t),E=O(E,k,g),E===void 0)return}else{if(++t,t===e.length)return;if(e.charCodeAt(t)===34){D=++t;let s=!1;for(;t<e.length;++t){let g=e.charCodeAt(t);if(g===92){s?(D=t,s=!1):(E+=e.slice(D,t),s=!0);continue}if(g===34){if(s){D=t,s=!1;continue}E+=e.slice(D,t);break}if(s&&=(D=t-1,!1),F[g]!==1)return}if(t===e.length)return;++t}else{for(D=t;t<e.length;++t)if(j[e.charCodeAt(t)]!==1){if(t===D)return;break}E=e.slice(D,t)}if(E=g(E,2),E===void 0)return}S=S.toLowerCase(),s[S]===void 0&&(s[S]=E)}return s}function E(e){let t;for(;;)switch(e){case`utf-8`:case`utf8`:return D.utf8;case`latin1`:case`ascii`:case`us-ascii`:case`iso-8859-1`:case`iso8859-1`:case`iso88591`:case`iso_8859-1`:case`windows-1252`:case`iso_8859-1:1987`:case`cp1252`:case`x-cp1252`:return D.latin1;case`utf16le`:case`utf-16le`:case`ucs2`:case`ucs-2`:return D.utf16le;case`base64`:return D.base64;default:if(t===void 0){t=!0,e=e.toLowerCase();continue}return D.other.bind(e)}}let D={utf8:(e,t)=>{if(e.length===0)return``;if(typeof e==`string`){if(t<2)return e;e=Buffer.from(e,`latin1`)}return e.utf8Slice(0,e.length)},latin1:(e,t)=>e.length===0?``:typeof e==`string`?e:e.latin1Slice(0,e.length),utf16le:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.ucs2Slice(0,e.length)),base64:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.base64Slice(0,e.length)),other:(t,s)=>{if(t.length===0)return``;typeof t==`string`&&(t=Buffer.from(t,`latin1`));try{return new TextDecoder(e).decode(t)}catch{}}};function O(e,t,s){let g=E(t);if(g)return g(e,s)}function k(e){if(typeof e!=`string`)return``;for(let t=e.length-1;t>=0;--t)switch(e.charCodeAt(t)){case 47:case 92:return e=e.slice(t+1),e===`..`||e===`.`?``:e}return e===`..`||e===`.`?``:e}let j=[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,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,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,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,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],F=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,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,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,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,1,1,1,1,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,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,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,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,1,1,1,1,1,1,1,1,1,1,1,1],L=[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,0,0,0,0,1,0,1,0,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,1,0,1,1,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,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,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,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],B=[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,0,1,0,0,0,0,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,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,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,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,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],H=[-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,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-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,10,11,12,13,14,15,-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,-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,-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,-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,-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,-1,-1,-1,-1,-1,-1,-1,-1];t.exports={basename:k,convertToUTF8:O,getDecoder:E,parseContentType:s,parseDisposition:S}})),require_sbmh=__commonJSMin$2(((e,t)=>{function s(e,t,s,g,S){for(let w=0;w<S;++w)if(e[t+w]!==s[g+w])return!1;return!0}var g=class{constructor(e,t){if(typeof t!=`function`)throw Error(`Missing match callback`);if(typeof e==`string`)e=Buffer.from(e);else if(!Buffer.isBuffer(e))throw Error(`Expected Buffer for needle, got ${typeof e}`);let s=e.length;if(this.maxMatches=1/0,this.matches=0,this._cb=t,this._lookbehindSize=0,this._needle=e,this._bufPos=0,this._lookbehind=Buffer.allocUnsafe(s),this._occ=[s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s,s],s>1)for(let t=0;t<s-1;++t)this._occ[e[t]]=s-1-t}reset(){this.matches=0,this._lookbehindSize=0,this._bufPos=0}push(e,t){let s;Buffer.isBuffer(e)||(e=Buffer.from(e,`latin1`));let g=e.length;for(this._bufPos=t||0;s!==g&&this.matches<this.maxMatches;)s=S(this,e);return s}destroy(){let e=this._lookbehindSize;e&&this._cb(!1,this._lookbehind,0,e,!1),this.reset()}};function S(e,t){let g=t.length,S=e._needle,E=S.length,D=-e._lookbehindSize,O=E-1,k=S[O],j=g-E,F=e._occ,L=e._lookbehind;if(D<0){for(;D<0&&D<=j;){let s=D+O,g=s<0?L[e._lookbehindSize+s]:t[s];if(g===k&&w(e,t,D,O))return e._lookbehindSize=0,++e.matches,D>-e._lookbehindSize?e._cb(!0,L,0,e._lookbehindSize+D,!1):e._cb(!0,void 0,0,0,!0),e._bufPos=D+E;D+=F[g]}for(;D<0&&!w(e,t,D,g-D);)++D;if(D<0){let s=e._lookbehindSize+D;return s>0&&e._cb(!1,L,0,s,!1),e._lookbehindSize-=s,L.copy(L,0,s,e._lookbehindSize),L.set(t,e._lookbehindSize),e._lookbehindSize+=g,e._bufPos=g,g}e._cb(!1,L,0,e._lookbehindSize,!1),e._lookbehindSize=0}D+=e._bufPos;let B=S[0];for(;D<=j;){let g=t[D+O];if(g===k&&t[D]===B&&s(S,0,t,D,O))return++e.matches,D>0?e._cb(!0,t,e._bufPos,D,!0):e._cb(!0,void 0,0,0,!0),e._bufPos=D+E;D+=F[g]}for(;D<g;){if(t[D]!==B||!s(t,D,S,0,g-D)){++D;continue}t.copy(L,0,D,g),e._lookbehindSize=g-D;break}return D>0&&e._cb(!1,t,e._bufPos,D<g?D:g,!0),e._bufPos=g,g}function w(e,t,s,g){let S=e._lookbehind,w=e._lookbehindSize,E=e._needle;for(let e=0;e<g;++e,++s)if((s<0?S[w+s]:t[s])!==E[e])return!1;return!0}t.exports=g})),require_multipart=__commonJSMin$2(((e,t)=>{let{Readable:s,Writable:g}=__require$2(`stream`),S=require_sbmh(),{basename:w,convertToUTF8:E,getDecoder:D,parseContentType:O,parseDisposition:k}=require_utils$2(),j=Buffer.from(`\r
|
|
38
|
-
`),F=Buffer.from(`\r`),L=Buffer.from(`-`);function B(){}let H=2e3,q=16*1024,ee=0,J=1,Y=2;var te=class{constructor(e){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0,this.cb=e}reset(){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0}push(e,t,s){let g=t;for(;t<s;)switch(this.state){case 0:{let S=!1;for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(fe[s]!==1){if(s!==58||(this.name+=e.latin1Slice(g,t),this.name.length===0))return-1;++t,S=!0,this.state=1;break}}if(!S){this.name+=e.latin1Slice(g,t);break}}case 1:{let S=!1;for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(s!==32&&s!==9){g=t,S=!0,this.state=2;break}}if(!S)break}case 2:switch(this.crlf){case 0:for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(me[s]!==1){if(s!==13)return-1;++this.crlf;break}}this.value+=e.latin1Slice(g,t++);break;case 1:if(this.byteCount===q||(++this.byteCount,e[t++]!==10))return-1;++this.crlf;break;case 2:{if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];s===32||s===9?(g=t,this.crlf=0):(++this.pairCount<2e3&&(this.name=this.name.toLowerCase(),this.header[this.name]===void 0?this.header[this.name]=[this.value]:this.header[this.name].push(this.value)),s===13?(++this.crlf,++t):(g=t,this.crlf=0,this.state=0,this.name=``,this.value=``));break}case 3:{if(this.byteCount===q||(++this.byteCount,e[t++]!==10))return-1;let s=this.header;return this.reset(),this.cb(s),t}}break}return t}},ne=class extends s{constructor(e,t){super(e),this.truncated=!1,this._readcb=null,this.once(`end`,()=>{if(this._read(),--t._fileEndsLeft===0&&t._finalcb){let e=t._finalcb;t._finalcb=null,process.nextTick(e)}})}_read(e){let t=this._readcb;t&&(this._readcb=null,t())}};let ae={push:(e,t)=>{},destroy:()=>{}};function oe(e,t){let s=e._writecb;e._writecb=null,t?e.destroy(t):s&&s()}function se(e,t){return e}var ce=class extends g{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};if(super(t),!e.conType.params||typeof e.conType.params.boundary!=`string`)throw Error(`Multipart: Boundary not found`);let s=e.conType.params.boundary,g=typeof e.defParamCharset==`string`&&e.defParamCharset?D(e.defParamCharset):se,H=e.defCharset||`utf8`,q=e.preservePath,ee={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.fileHwm==`number`?e.fileHwm:void 0},J=e.limits,Y=J&&typeof J.fieldSize==`number`?J.fieldSize:1*1024*1024,oe=J&&typeof J.fileSize==`number`?J.fileSize:1/0,ce=J&&typeof J.files==`number`?J.files:1/0,ue=J&&typeof J.fields==`number`?J.fields:1/0,de=J&&typeof J.parts==`number`?J.parts:1/0,fe=-1,me=0,ge=0,_e=!1;this._fileEndsLeft=0,this._fileStream=void 0,this._complete=!1;let ve=0,ye,Ce=0,we,Te,De,je,Me=!1,Pe=!1,Ie=!1;this._hparser=null;let Re=new te(e=>{this._hparser=null,_e=!1,De=`text/plain`,we=H,Te=`7bit`,je=void 0,Me=!1;let t;if(!e[`content-disposition`]){_e=!0;return}let s=k(e[`content-disposition`][0],g);if(!s||s.type!==`form-data`){_e=!0;return}if(s.params&&(s.params.name&&(je=s.params.name),s.params[`filename*`]?t=s.params[`filename*`]:s.params.filename&&(t=s.params.filename),t!==void 0&&!q&&(t=w(t))),e[`content-type`]){let t=O(e[`content-type`][0]);t&&(De=`${t.type}/${t.subtype}`,t.params&&typeof t.params.charset==`string`&&(we=t.params.charset.toLowerCase()))}if(e[`content-transfer-encoding`]&&(Te=e[`content-transfer-encoding`][0].toLowerCase()),De===`application/octet-stream`||t!==void 0){if(ge===ce){Pe||(Pe=!0,this.emit(`filesLimit`)),_e=!0;return}if(++ge,this.listenerCount(`file`)===0){_e=!0;return}ve=0,this._fileStream=new ne(ee,this),++this._fileEndsLeft,this.emit(`file`,je,this._fileStream,{filename:t,encoding:Te,mimeType:De})}else{if(me===ue){Ie||(Ie=!0,this.emit(`fieldsLimit`)),_e=!0;return}if(++me,this.listenerCount(`field`)===0){_e=!0;return}ye=[],Ce=0}}),ze=0,Be=(e,t,s,g,S)=>{retrydata:for(;t;){if(this._hparser!==null){let e=this._hparser.push(t,s,g);if(e===-1){this._hparser=null,Re.reset(),this.emit(`error`,Error(`Malformed part header`));break}s=e}if(s===g)break;if(ze!==0){if(ze===1){switch(t[s]){case 45:ze=2,++s;break;case 13:ze=3,++s;break;default:ze=0}if(s===g)return}if(ze===2){if(ze=0,t[s]===45){this._complete=!0,this._bparser=ae;return}let e=this._writecb;this._writecb=B,Be(!1,L,0,1,!1),this._writecb=e}else if(ze===3)if(ze=0,t[s]===10){if(++s,fe>=de||(this._hparser=Re,s===g))break;continue retrydata}else{let e=this._writecb;this._writecb=B,Be(!1,F,0,1,!1),this._writecb=e}}if(!_e){if(this._fileStream){let e,w=Math.min(g-s,oe-ve);S?e=t.slice(s,s+w):(e=Buffer.allocUnsafe(w),t.copy(e,0,s,s+w)),ve+=e.length,ve===oe?(e.length>0&&this._fileStream.push(e),this._fileStream.emit(`limit`),this._fileStream.truncated=!0,_e=!0):this._fileStream.push(e)||(this._writecb&&(this._fileStream._readcb=this._writecb),this._writecb=null)}else if(ye!==void 0){let e,w=Math.min(g-s,Y-Ce);S?e=t.slice(s,s+w):(e=Buffer.allocUnsafe(w),t.copy(e,0,s,s+w)),Ce+=w,ye.push(e),Ce===Y&&(_e=!0,Me=!0)}}break}if(e){if(ze=1,this._fileStream)this._fileStream.push(null),this._fileStream=null;else if(ye!==void 0){let e;switch(ye.length){case 0:e=``;break;case 1:e=E(ye[0],we,0);break;default:e=E(Buffer.concat(ye,Ce),we,0)}ye=void 0,Ce=0,this.emit(`field`,je,e,{nameTruncated:!1,valueTruncated:Me,encoding:Te,mimeType:De})}++fe===de&&this.emit(`partsLimit`)}};this._bparser=new S(`\r\n--${s}`,Be),this._writecb=null,this._finalcb=null,this.write(j)}static detect(e){return e.type===`multipart`&&e.subtype===`form-data`}_write(e,t,s){this._writecb=s,this._bparser.push(e,0),this._writecb&&oe(this)}_destroy(e,t){this._hparser=null,this._bparser=ae,e||=de(this);let s=this._fileStream;s&&(this._fileStream=null,s.destroy(e)),t(e)}_final(e){if(this._bparser.destroy(),!this._complete)return e(Error(`Unexpected end of form`));this._fileEndsLeft?this._finalcb=ue.bind(null,this,e):ue(this,e)}};function ue(e,t,s){if(s)return t(s);s=de(e),t(s)}function de(e){if(e._hparser)return Error(`Malformed part header`);let t=e._fileStream;if(t&&(e._fileStream=null,t.destroy(Error(`Unexpected end of file`))),!e._complete)return Error(`Unexpected end of form`)}let fe=[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,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,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,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,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],me=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,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,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,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,1,1,1,1,1,1,1,1,1,1,1,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,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,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,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,1,1,1,1,1,1,1,1,1,1,1,1];t.exports=ce})),require_urlencoded=__commonJSMin$2(((e,t)=>{let{Writable:s}=__require$2(`stream`),{getDecoder:g}=require_utils$2();var S=class extends s{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};super(t);let s=e.defCharset||`utf8`;e.conType.params&&typeof e.conType.params.charset==`string`&&(s=e.conType.params.charset),this.charset=s;let S=e.limits;this.fieldSizeLimit=S&&typeof S.fieldSize==`number`?S.fieldSize:1*1024*1024,this.fieldsLimit=S&&typeof S.fields==`number`?S.fields:1/0,this.fieldNameSizeLimit=S&&typeof S.fieldNameSize==`number`?S.fieldNameSize:100,this._inKey=!0,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,this._fields=0,this._key=``,this._val=``,this._byte=-2,this._lastPos=0,this._encode=0,this._decoder=g(s)}static detect(e){return e.type===`application`&&e.subtype===`x-www-form-urlencoded`}_write(e,t,s){if(this._fields>=this.fieldsLimit)return s();let g=0,S=e.length;if(this._lastPos=0,this._byte!==-2){if(g=w(this,e,g,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();this._inKey?++this._bytesKey:++this._bytesVal}main:for(;g<S;)if(this._inKey){for(g=E(this,e,g,S);g<S;){switch(e[g]){case 61:this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._key=this._decoder(this._key,this._encode),this._encode=0,this._inKey=!1;continue main;case 38:if(this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._key=this._decoder(this._key,this._encode),this._encode=0,this._bytesKey>0&&this.emit(`field`,this._key,``,{nameTruncated:this._keyTrunc,valueTruncated:!1,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),s();continue;case 43:this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._key+=` `,this._lastPos=g+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=g+1,this._byte=-1,g=w(this,e,g+1,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();++this._bytesKey,g=E(this,e,g,S);continue}++g,++this._bytesKey,g=E(this,e,g,S)}this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g))}else{for(g=D(this,e,g,S);g<S;){switch(e[g]){case 38:if(this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._inKey=!0,this._val=this._decoder(this._val,this._encode),this._encode=0,(this._bytesKey>0||this._bytesVal>0)&&this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),s();continue main;case 43:this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._val+=` `,this._lastPos=g+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._lastPos=g+1,this._byte=-1,g=w(this,e,g+1,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();++this._bytesVal,g=D(this,e,g,S);continue}++g,++this._bytesVal,g=D(this,e,g,S)}this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g))}s()}_final(e){if(this._byte!==-2)return e(Error(`Malformed urlencoded form`));(!this._inKey||this._bytesKey>0||this._bytesVal>0)&&(this._inKey?this._key=this._decoder(this._key,this._encode):this._val=this._decoder(this._val,this._encode),this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`})),e()}};function w(e,t,s,g){if(s>=g)return g;if(e._byte===-1){let S=O[t[s++]];if(S===-1)return-1;if(S>=8&&(e._encode=2),s<g){let g=O[t[s++]];if(g===-1)return-1;e._inKey?e._key+=String.fromCharCode((S<<4)+g):e._val+=String.fromCharCode((S<<4)+g),e._byte=-2,e._lastPos=s}else e._byte=S}else{let g=O[t[s++]];if(g===-1)return-1;e._inKey?e._key+=String.fromCharCode((e._byte<<4)+g):e._val+=String.fromCharCode((e._byte<<4)+g),e._byte=-2,e._lastPos=s}return s}function E(e,t,s,g){if(e._bytesKey>e.fieldNameSizeLimit){for(e._keyTrunc||e._lastPos<s&&(e._key+=t.latin1Slice(e._lastPos,s-1)),e._keyTrunc=!0;s<g;++s){let g=t[s];if(g===61||g===38)break;++e._bytesKey}e._lastPos=s}return s}function D(e,t,s,g){if(e._bytesVal>e.fieldSizeLimit){for(e._valTrunc||e._lastPos<s&&(e._val+=t.latin1Slice(e._lastPos,s-1)),e._valTrunc=!0;s<g&&t[s]!==38;++s)++e._bytesVal;e._lastPos=s}return s}let O=[-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,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-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,10,11,12,13,14,15,-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,-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,-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,-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,-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,-1,-1,-1,-1,-1,-1,-1,-1];t.exports=S})),require_lib=__commonJSMin$2(((e,t)=>{let{parseContentType:s}=require_utils$2();function g(e){let t=e.headers,g=s(t[`content-type`]);if(!g)throw Error(`Malformed content type`);for(let s of S){if(!s.detect(g))continue;let S={limits:e.limits,headers:t,conType:g,highWaterMark:void 0,fileHwm:void 0,defCharset:void 0,defParamCharset:void 0,preservePath:!1};return e.highWaterMark&&(S.highWaterMark=e.highWaterMark),e.fileHwm&&(S.fileHwm=e.fileHwm),S.defCharset=e.defCharset,S.defParamCharset=e.defParamCharset,S.preservePath=e.preservePath,new s(S)}throw Error(`Unsupported content type: ${t[`content-type`]}`)}let S=[require_multipart(),require_urlencoded()].filter(function(e){return typeof e.detect==`function`});t.exports=e=>{if((typeof e!=`object`||!e)&&(e={}),typeof e.headers!=`object`||e.headers===null||typeof e.headers[`content-type`]!=`string`)throw Error(`Missing Content-Type`);return g(e)}}));const WINDOWS_1252_EXTRA={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},WINDOWS_1252_REVERSE={};for(let[e,t]of Object.entries(WINDOWS_1252_EXTRA))WINDOWS_1252_REVERSE[t]=Number.parseInt(e,10);let _utf8Decoder;function utf8Decoder(){if(globalThis.TextDecoder!==void 0)return _utf8Decoder??=new globalThis.TextDecoder(`utf-8`)}const CHUNK=32*1024,REPLACEMENT=65533;function textDecode(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=utf8Decoder();return t?t.decode(e):decodeUTF8(e)}case`utf-16le`:return decodeUTF16LE(e);case`us-ascii`:case`ascii`:return decodeASCII(e);case`latin1`:case`iso-8859-1`:return decodeLatin1(e);case`windows-1252`:return decodeWindows1252(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function flushChunk(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function pushCodeUnit(e,t,s){t.push(s),t.length>=CHUNK&&flushChunk(e,t)}function pushCodePoint(e,t,s){if(s<=65535){pushCodeUnit(e,t,s);return}s-=65536,pushCodeUnit(e,t,55296+(s>>10)),pushCodeUnit(e,t,56320+(s&1023))}function decodeUTF8(e){let t=[],s=[],g=0;for(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191&&(g=3);g<e.length;){let S=e[g];if(S<=127){pushCodeUnit(t,s,S),g++;continue}if(S<194||S>244){pushCodeUnit(t,s,REPLACEMENT),g++;continue}if(S<=223){if(g+1>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1];if((w&192)!=128){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodeUnit(t,s,(S&31)<<6|w&63),g+=2;continue}if(S<=239){if(g+2>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1],E=e[g+2];if(!((w&192)==128&&(E&192)==128&&!(S===224&&w<160)&&!(S===237&&w>=160))){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodeUnit(t,s,(S&15)<<12|(w&63)<<6|E&63),g+=3;continue}if(g+3>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1],E=e[g+2],D=e[g+3];if(!((w&192)==128&&(E&192)==128&&(D&192)==128&&!(S===240&&w<144)&&!(S===244&&w>143))){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodePoint(t,s,(S&7)<<18|(w&63)<<12|(E&63)<<6|D&63),g+=4}return flushChunk(t,s),t.join(``)}function decodeUTF16LE(e){let t=[],s=[],g=e.length,S=0;for(;S+1<g;){let w=e[S]|e[S+1]<<8;if(S+=2,w>=55296&&w<=56319){if(S+1<g){let g=e[S]|e[S+1]<<8;g>=56320&&g<=57343?(pushCodeUnit(t,s,w),pushCodeUnit(t,s,g),S+=2):pushCodeUnit(t,s,REPLACEMENT)}else pushCodeUnit(t,s,REPLACEMENT);continue}if(w>=56320&&w<=57343){pushCodeUnit(t,s,REPLACEMENT);continue}pushCodeUnit(t,s,w)}return S<g&&pushCodeUnit(t,s,REPLACEMENT),flushChunk(t,s),t.join(``)}function decodeASCII(e){let t=[];for(let s=0;s<e.length;s+=CHUNK){let g=Math.min(e.length,s+CHUNK),S=Array(g-s);for(let t=s,w=0;t<g;t++,w++)S[w]=e[t]&127;t.push(String.fromCharCode.apply(null,S))}return t.join(``)}function decodeLatin1(e){let t=[];for(let s=0;s<e.length;s+=CHUNK){let g=Math.min(e.length,s+CHUNK),S=Array(g-s);for(let t=s,w=0;t<g;t++,w++)S[w]=e[t];t.push(String.fromCharCode.apply(null,S))}return t.join(``)}function decodeWindows1252(e){let t=[],s=``;for(let g=0;g<e.length;g++){let S=e[g],w=S>=128&&S<=159?WINDOWS_1252_EXTRA[S]:void 0;s+=w??String.fromCharCode(S),s.length>=CHUNK&&(t.push(s),s=``)}return s&&t.push(s),t.join(``)}function dv(e){return new DataView(e.buffer,e.byteOffset)}const UINT8={len:1,get(e,t){return dv(e).getUint8(t)},put(e,t,s){return dv(e).setUint8(t,s),t+1}},UINT16_LE={len:2,get(e,t){return dv(e).getUint16(t,!0)},put(e,t,s){return dv(e).setUint16(t,s,!0),t+2}},UINT16_BE={len:2,get(e,t){return dv(e).getUint16(t)},put(e,t,s){return dv(e).setUint16(t,s),t+2}},UINT32_LE={len:4,get(e,t){return dv(e).getUint32(t,!0)},put(e,t,s){return dv(e).setUint32(t,s,!0),t+4}},UINT32_BE={len:4,get(e,t){return dv(e).getUint32(t)},put(e,t,s){return dv(e).setUint32(t,s),t+4}},INT32_BE={len:4,get(e,t){return dv(e).getInt32(t)},put(e,t,s){return dv(e).setInt32(t,s),t+4}},UINT64_LE={len:8,get(e,t){return dv(e).getBigUint64(t,!0)},put(e,t,s){return dv(e).setBigUint64(t,s,!0),t+8}};var StringType=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return textDecode(e.subarray(t,t+this.len),this.encoding)}};const defaultMessages=`End-Of-Stream`;var EndOfStreamError=class extends Error{constructor(){super(defaultMessages),this.name=`EndOfStreamError`}},AbortError=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},AbstractStreamReader=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let s=await this.read(e,t);return this.peekQueue.push(e.subarray(0,s)),s}async read(e,t=!1){if(e.length===0)return 0;let s=this.readFromPeekBuffer(e);if(this.endOfStream||(s+=await this.readRemainderFromStream(e.subarray(s),t)),s===0&&!t)throw new EndOfStreamError;return s}readFromPeekBuffer(e){let t=e.length,s=0;for(;this.peekQueue.length>0&&t>0;){let g=this.peekQueue.pop();if(!g)throw Error(`peekData should be defined`);let S=Math.min(g.length,t);e.set(g.subarray(0,S),s),s+=S,t-=S,S<g.length&&this.peekQueue.push(g.subarray(S))}return s}async readRemainderFromStream(e,t){let s=0;for(;s<e.length&&!this.endOfStream;){if(this.interrupted)throw new AbortError;let g=await this.readFromStream(e.subarray(s),t);if(g===0)break;s+=g}if(!t&&s<e.length)throw new EndOfStreamError;return s}},WebStreamReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},WebStreamByobReader=class extends WebStreamReader{async readFromStream(e,t){if(e.length===0)return 0;let s=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return s.done&&(this.endOfStream=s.done),s.value?(e.set(s.value),s.value.length):0}},WebStreamDefaultReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let s=Math.min(t.length,e.length);return e.set(t.subarray(0,s)),s<t.length?this.buffer=t.subarray(s):this.buffer=null,s}async readFromStream(e,t){if(e.length===0)return 0;let s=0;for(this.buffer&&(s+=this.writeChunk(e,this.buffer));s<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(s+=this.writeChunk(e.subarray(s),t.value))}if(!t&&s===0&&this.endOfStream)throw new EndOfStreamError;return s}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function makeWebStreamReader(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new WebStreamDefaultReader(t):new WebStreamByobReader(t)}catch(t){if(t instanceof TypeError)return new WebStreamDefaultReader(e.getReader());throw t}}var AbstractTokenizer=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let s=new Uint8Array(e.len);if(await this.readBuffer(s,{position:t})<e.len)throw new EndOfStreamError;return e.get(s,0)}async peekToken(e,t=this.position){let s=new Uint8Array(e.len);if(await this.peekBuffer(s,{position:t})<e.len)throw new EndOfStreamError;return e.get(s,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};const maxBufferSize=256e3;var ReadStreamTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let s=this.normalizeOptions(e,t),g=s.position-this.position;if(g>0)return await this.ignore(g),this.readBuffer(e,t);if(g<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(s.length===0)return 0;let S=await this.streamReader.read(e.subarray(0,s.length),s.mayBeLess);if(this.position+=S,(!t||!t.mayBeLess)&&S<s.length)throw new EndOfStreamError;return S}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=0;if(s.position){let t=s.position-this.position;if(t>0){let S=new Uint8Array(s.length+t);return g=await this.peekBuffer(S,{mayBeLess:s.mayBeLess}),e.set(S.subarray(t)),g-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(s.length>0){try{g=await this.streamReader.peek(e.subarray(0,s.length),s.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof EndOfStreamError)return 0;throw e}if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError}return g}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);let t=Math.min(maxBufferSize,e),s=new Uint8Array(t),g=0;for(;g<e;){let S=e-g,w=await this.readBuffer(s,{length:Math.min(t,S)});if(w<0)return w;g+=w}return g}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},BufferTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let s=await this.peekBuffer(e,t);return this.position+=s,s}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=Math.min(this.uint8Array.length-s.position,s.length);if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError;return e.set(this.uint8Array.subarray(s.position,s.position+g)),g}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},BlobTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let s=await this.peekBuffer(e,t);return this.position+=s,s}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=Math.min(this.blob.size-s.position,s.length);if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError;let S=await this.blob.slice(s.position,s.position+g).arrayBuffer();return e.set(new Uint8Array(S)),g}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function fromWebStream(e,t){let s=makeWebStreamReader(e),g=t??{},S=g.onClose;return g.onClose=async()=>{if(await s.close(),S)return S()},new ReadStreamTokenizer(s,g)}function fromBuffer(e,t){return new BufferTokenizer(e,t)}function fromBlob(e,t){return new BlobTokenizer(e,t)}const Signature={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},DataDescriptor={get(e){return{signature:UINT32_LE.get(e,0),compressedSize:UINT32_LE.get(e,8),uncompressedSize:UINT32_LE.get(e,12)}},len:16},LocalFileHeaderToken={get(e){let t=UINT16_LE.get(e,6);return{signature:UINT32_LE.get(e,0),minVersion:UINT16_LE.get(e,4),dataDescriptor:!!(t&8),compressedMethod:UINT16_LE.get(e,8),compressedSize:UINT32_LE.get(e,18),uncompressedSize:UINT32_LE.get(e,22),filenameLength:UINT16_LE.get(e,26),extraFieldLength:UINT16_LE.get(e,28),filename:null}},len:30},EndOfCentralDirectoryRecordToken={get(e){return{signature:UINT32_LE.get(e,0),nrOfThisDisk:UINT16_LE.get(e,4),nrOfThisDiskWithTheStart:UINT16_LE.get(e,6),nrOfEntriesOnThisDisk:UINT16_LE.get(e,8),nrOfEntriesOfSize:UINT16_LE.get(e,10),sizeOfCd:UINT32_LE.get(e,12),offsetOfStartOfCd:UINT32_LE.get(e,16),zipFileCommentLength:UINT16_LE.get(e,20)}},len:22},FileHeader={get(e){let t=UINT16_LE.get(e,8);return{signature:UINT32_LE.get(e,0),minVersion:UINT16_LE.get(e,6),dataDescriptor:!!(t&8),compressedMethod:UINT16_LE.get(e,10),compressedSize:UINT32_LE.get(e,20),uncompressedSize:UINT32_LE.get(e,24),filenameLength:UINT16_LE.get(e,28),extraFieldLength:UINT16_LE.get(e,30),fileCommentLength:UINT16_LE.get(e,32),relativeOffsetOfLocalHeader:UINT32_LE.get(e,42),filename:null}},len:46};var import_src$8=__toESM$2(require_src$15(),1);function signatureToArray(e){let t=new Uint8Array(UINT32_LE.len);return UINT32_LE.put(t,0,e),t}const debug=(0,import_src$8.default)(`tokenizer:inflate`),syncBufferSize=256*1024,ddSignatureArray=signatureToArray(Signature.DataDescriptor),eocdSignatureBytes=signatureToArray(Signature.EndOfCentralDirectory);var ZipHandler=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(syncBufferSize)}async isZip(){return await this.peekSignature()===Signature.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(UINT32_LE)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),s=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(s,{position:e.fileInfo.size-t});for(let g=s.length-4;g>=0;g--)if(s[g]===eocdSignatureBytes[0]&&s[g+1]===eocdSignatureBytes[1]&&s[g+2]===eocdSignatureBytes[2]&&s[g+3]===eocdSignatureBytes[3])return e.fileInfo.size-t+g;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){debug(`Cannot reading central-directory without random-read support`);return}debug(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){debug(`Central-directory 32-bit signature found`);let s=await this.tokenizer.readToken(EndOfCentralDirectoryRecordToken,t),g=[];this.tokenizer.setPosition(s.offsetOfStartOfCd);for(let e=0;e<s.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(FileHeader);if(t.signature!==Signature.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new StringType(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),g.push(t),debug(`Add central-directory file-entry: n=${e+1}/${g.length}: filename=${g[e].filename}`)}return this.tokenizer.setPosition(e),g}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let s=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let g=e(t);s=!!g.stop;let S;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],s=syncBufferSize;debug(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let S=-1;for(;S<0&&s===syncBufferSize;){s=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),S=indexOf(this.syncBuffer.subarray(0,s),ddSignatureArray);let t=S>=0?S:s;if(g.handler){let s=new Uint8Array(t);await this.tokenizer.readBuffer(s),e.push(s)}else await this.tokenizer.ignore(t)}debug(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),g.handler&&await this.inflate(t,mergeArrays(e),g.handler)}else g.handler?(debug(`Reading compressed-file-data: ${t.compressedSize} bytes`),S=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(S),await this.inflate(t,S,g.handler)):(debug(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(debug(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(DataDescriptor)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-DataDescriptor.len}`)}while(!s)}async iterateOverCentralDirectory(e,t){for(let s of e){let e=t(s);if(e.handler){this.tokenizer.setPosition(s.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let g=new Uint8Array(s.compressedSize);await this.tokenizer.readBuffer(g),await this.inflate(t,g,e.handler)}}if(e.stop)break}}async inflate(t,s,g){if(t.compressedMethod===0)return g(s);if(t.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${t.compressedMethod}`);return debug(`Decompress filename=${t.filename}, compressed-size=${s.length}`),g(await e.decompressDeflateRaw(s))}static async decompressDeflateRaw(e){let t=new ReadableStream({start(t){t.enqueue(e),t.close()}}),s=new DecompressionStream(`deflate-raw`),g=t.pipeThrough(s);try{let e=await new Response(g).arrayBuffer();return new Uint8Array(e)}catch(e){let t=e instanceof Error?`Failed to deflate ZIP entry: ${e.message}`:`Unknown decompression error in ZIP entry`;throw TypeError(t)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(UINT32_LE);if(e===Signature.LocalFileHeader){let e=await this.tokenizer.readToken(LocalFileHeaderToken);return e.filename=await this.tokenizer.readToken(new StringType(e.filenameLength,`utf-8`)),e}if(e===Signature.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}};function indexOf(e,t){let s=e.length,g=t.length;if(g>s)return-1;for(let S=0;S<=s-g;S++){let s=!0;for(let w=0;w<g;w++)if(e[S+w]!==t[w]){s=!1;break}if(s)return S}return-1}function mergeArrays(e){let t=e.reduce((e,t)=>e+t.length,0),s=new Uint8Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return s}var GzipHandler=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let s=new Uint8Array(1024),g=await e.readBuffer(s,{mayBeLess:!0});if(g===0){t.close();return}t.enqueue(s.subarray(0,g))}}).pipeThrough(new DecompressionStream(`gzip`))}};const objectToString=Object.prototype.toString,uint8ArrayStringified=`[object Uint8Array]`;function isType(e,t,s){return e?e.constructor===t?!0:objectToString.call(e)===s:!1}function isUint8Array(e){return isType(e,Uint8Array,uint8ArrayStringified)}function assertUint8Array(e){if(!isUint8Array(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function concatUint8Arrays(e,t){if(e.length===0)return new Uint8Array;t??=e.reduce((e,t)=>e+t.length,0);let s=new Uint8Array(t),g=0;for(let t of e)assertUint8Array(t),s.set(t,g),g+=t.length;return s}const cachedDecoders={utf8:new globalThis.TextDecoder(`utf8`)},cachedEncoder=new globalThis.TextEncoder,byteToHexLookupTable=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function getUintBE(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function stringToBytes(e,t){if(t===`utf-16le`){let t=[];for(let s=0;s<e.length;s++){let g=e.charCodeAt(s);t.push(g&255,g>>8&255)}return t}if(t===`utf-16be`){let t=[];for(let s=0;s<e.length;s++){let g=e.charCodeAt(s);t.push(g>>8&255,g&255)}return t}return[...e].map(e=>e.charCodeAt(0))}function tarHeaderChecksumMatches(e,t=0){let s=Number.parseInt(new StringType(6).get(e,148).replace(/\0.*$/v,``).trim(),8);if(Number.isNaN(s))return!1;let g=256;for(let s=t;s<t+148;s++)g+=e[s];for(let s=t+156;s<t+512;s++)g+=e[s];return s===g}const uint32SyncSafeToken={get:(e,t)=>e[t+3]&127|(e[t+2]&127)<<7|(e[t+1]&127)<<14|(e[t]&127)<<21,len:4},extensions=`jpg,png,apng,gif,webp,flif,xcf,cr2,cr3,orf,arw,dng,nef,rw2,raf,tif,bmp,icns,jxr,psd,indd,zip,tar,rar,gz,bz2,7z,dmg,mp4,mid,mkv,webm,mov,avi,mpg,mp2,mp3,m4a,oga,ogg,ogv,opus,flac,wav,spx,amr,pdf,epub,elf,macho,exe,swf,rtf,wasm,woff,woff2,eot,ttf,otf,ttc,ico,flv,ps,xz,sqlite,nes,crx,xpi,cab,deb,ar,rpm,Z,lz,cfb,mxf,mts,blend,bpg,docx,pptx,xlsx,3gp,3g2,j2c,jp2,jpm,jpx,mj2,aif,qcp,odt,ods,odp,xml,mobi,heic,cur,ktx,ape,wv,dcm,ics,glb,pcap,dsf,lnk,alias,voc,ac3,m4v,m4p,m4b,f4v,f4p,f4b,f4a,mie,asf,ogm,ogx,mpc,arrow,shp,aac,mp1,it,s3m,xm,skp,avif,eps,lzh,pgp,asar,stl,chm,3mf,zst,jxl,vcf,jls,pst,dwg,parquet,class,arj,cpio,ace,avro,icc,fbx,vsdx,vtt,apk,drc,lz4,potx,xltx,dotx,xltm,ott,ots,otp,odg,otg,xlsm,docm,dotm,potm,pptm,jar,jmp,rm,sav,ppsm,ppsx,tar.gz,reg,dat,key,numbers,pages`.split(`,`),mimeTypes=`image/jpeg,image/png,image/gif,image/webp,image/flif,image/x-xcf,image/x-canon-cr2,image/x-canon-cr3,image/tiff,image/bmp,image/vnd.ms-photo,image/vnd.adobe.photoshop,application/x-indesign,application/epub+zip,application/x-xpinstall,application/vnd.ms-powerpoint.slideshow.macroenabled.12,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.spreadsheet,application/vnd.oasis.opendocument.presentation,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/zip,application/x-tar,application/x-rar-compressed,application/gzip,application/x-bzip2,application/x-7z-compressed,application/x-apple-diskimage,application/vnd.apache.arrow.file,video/mp4,audio/midi,video/matroska,video/webm,video/quicktime,video/vnd.avi,audio/wav,audio/qcelp,audio/x-ms-asf,video/x-ms-asf,application/vnd.ms-asf,video/mpeg,video/3gpp,audio/mpeg,audio/mp4,video/ogg,audio/ogg,audio/ogg; codecs=opus,application/ogg,audio/flac,audio/ape,audio/wavpack,audio/amr,application/pdf,application/x-elf,application/x-mach-binary,application/x-msdownload,application/x-shockwave-flash,application/rtf,application/wasm,font/woff,font/woff2,application/vnd.ms-fontobject,font/ttf,font/otf,font/collection,image/x-icon,video/x-flv,application/postscript,application/eps,application/x-xz,application/x-sqlite3,application/x-nintendo-nes-rom,application/x-google-chrome-extension,application/vnd.ms-cab-compressed,application/x-deb,application/x-unix-archive,application/x-rpm,application/x-compress,application/lzip,application/x-cfb,application/x-mie,application/mxf,video/mp2t,application/x-blender,image/bpg,image/j2c,image/jp2,image/jpx,image/jpm,image/mj2,audio/aiff,application/xml,application/x-mobipocket-ebook,image/heif,image/heif-sequence,image/heic,image/heic-sequence,image/icns,image/ktx,application/dicom,audio/x-musepack,text/calendar,text/vcard,text/vtt,model/gltf-binary,application/vnd.tcpdump.pcap,audio/x-dsf,application/x-ms-shortcut,application/x-ft-apple.alias,audio/x-voc,audio/vnd.dolby.dd-raw,audio/x-m4a,image/apng,image/x-olympus-orf,image/x-sony-arw,image/x-adobe-dng,image/x-nikon-nef,image/x-panasonic-rw2,image/x-fujifilm-raf,video/x-m4v,video/3gpp2,application/x-esri-shape,audio/aac,audio/x-it,audio/x-s3m,audio/x-xm,video/MP1S,video/MP2P,application/vnd.sketchup.skp,image/avif,application/x-lzh-compressed,application/pgp-encrypted,application/x-asar,model/stl,application/vnd.ms-htmlhelp,model/3mf,image/jxl,application/zstd,image/jls,application/vnd.ms-outlook,image/vnd.dwg,application/vnd.apache.parquet,application/java-vm,application/x-arj,application/x-cpio,application/x-ace-compressed,application/avro,application/vnd.iccprofile,application/x-ft-fbx,application/vnd.visio,application/vnd.android.package-archive,application/x-ft-draco,application/x-lz4,application/vnd.openxmlformats-officedocument.presentationml.template,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/vnd.ms-excel.template.macroenabled.12,application/vnd.oasis.opendocument.text-template,application/vnd.oasis.opendocument.spreadsheet-template,application/vnd.oasis.opendocument.presentation-template,application/vnd.oasis.opendocument.graphics,application/vnd.oasis.opendocument.graphics-template,application/vnd.ms-excel.sheet.macroenabled.12,application/vnd.ms-word.document.macroenabled.12,application/vnd.ms-word.template.macroenabled.12,application/vnd.ms-powerpoint.template.macroenabled.12,application/vnd.ms-powerpoint.presentation.macroenabled.12,application/java-archive,application/vnd.rn-realmedia,application/x-spss-sav,application/x-ms-regedit,application/x-ft-windows-registry-hive,application/x-jmp-data,application/vnd.apple.keynote,application/vnd.apple.numbers,application/vnd.apple.pages`.split(`,`),maximumUntrustedSkipSizeInBytes=16*1024*1024;var ParserHardLimitError=class extends Error{};function getSafeBound(e,t,s){if(!Number.isFinite(e)||e<0||e>t)throw new ParserHardLimitError(`${s} has invalid size ${e} (maximum ${t} bytes)`);return e}async function safeIgnore(e,t,{maximumLength:s=maximumUntrustedSkipSizeInBytes,reason:g=`skip`}={}){let S=getSafeBound(t,s,g);await e.ignore(S)}async function safeReadBuffer(e,t,s,{maximumLength:g=t.length,reason:S=`read`}={}){let w=getSafeBound(s?.length??t.length,g,S);return e.readBuffer(t,{...s,length:w})}function checkBytes(e,t,s){s={offset:0,...s};for(let[g,S]of t.entries())if(s.mask){if(S!==(s.mask[g]&e[g+s.offset]))return!1}else if(S!==e[g+s.offset])return!1;return!0}function hasUnknownFileSize(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function hasExceededUnknownSizeScanBudget(e,t,s){return hasUnknownFileSize(e)&&e.position-t>s}const maximumZipEntrySizeInBytes=1024*1024,maximumZipEntryCount=1024,maximumZipBufferedReadSizeInBytes=2**31-1,maximumZipTextEntrySizeInBytes=maximumZipEntrySizeInBytes,recoverableZipErrorMessages=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),recoverableZipErrorMessagePrefixes=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],recoverableZipErrorCodes=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]);async function decompressDeflateRawWithLimit(e,{maximumLength:t=maximumZipEntrySizeInBytes}={}){let s=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(`deflate-raw`)).getReader(),g=[],S=0;try{for(;;){let{done:e,value:w}=await s.read();if(e)break;if(S+=w.length,S>t)throw await s.cancel(),Error(`ZIP entry decompressed data exceeds ${t} bytes`);g.push(w)}}finally{s.releaseLock()}let w=new Uint8Array(S),E=0;for(let e of g)w.set(e,E),E+=e.length;return w}function mergeByteChunks(e,t){let s=new Uint8Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return s}function getMaximumZipBufferedReadLength(e){let t=e.fileInfo.size,s=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(s,maximumZipBufferedReadSizeInBytes)}function isRecoverableZipError(e){if(e instanceof EndOfStreamError||e instanceof ParserHardLimitError)return!0;if(!(e instanceof Error))return!1;if(recoverableZipErrorMessages.has(e.message)||recoverableZipErrorCodes.has(e.code))return!0;for(let t of recoverableZipErrorMessagePrefixes)if(e.message.startsWith(t))return!0;return!1}function canReadZipEntryForDetection(e,t=maximumZipEntrySizeInBytes){let s=[e.compressedSize,e.uncompressedSize];for(let e of s)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function createIWorkZipDetectionState(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function updateIWorkZipDetectionStateFromFilename(e,t){t===`Index/Document.iwa`&&(e.hasDocumentEntry=!0),t.startsWith(`Index/MasterSlide`)&&(e.hasMasterSlideEntry=!0),t.startsWith(`Index/Tables/`)&&(e.hasTablesEntry=!0),t===`Index/CalculationEngine.iwa`&&(e.hasCalculationEngineEntry=!0)}function getIWorkFileTypeFromZipEntries(e){if(e.hasDocumentEntry)return e.hasMasterSlideEntry?{ext:`key`,mime:`application/vnd.apple.keynote`}:e.hasTablesEntry?{ext:`numbers`,mime:`application/vnd.apple.numbers`}:{ext:`pages`,mime:`application/vnd.apple.pages`}}function getFileTypeFromMimeType(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function createOpenXmlZipDetectionState(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function updateOpenXmlZipDetectionStateFromFilename(e,t){t.startsWith(`word/`)&&(e.hasWordDirectory=!0),t.startsWith(`ppt/`)&&(e.hasPresentationDirectory=!0),t.startsWith(`xl/`)&&(e.hasSpreadsheetDirectory=!0),t.startsWith(`3D/`)&&t.endsWith(`.model`)&&(e.hasThreeDimensionalModelEntry=!0)}function getOpenXmlFileTypeFromDirectoryNames(e){if(e.hasWordDirectory)return{ext:`docx`,mime:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};if(e.hasPresentationDirectory)return{ext:`pptx`,mime:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};if(e.hasSpreadsheetDirectory)return{ext:`xlsx`,mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};if(e.hasThreeDimensionalModelEntry)return{ext:`3mf`,mime:`model/3mf`}}function getOpenXmlFileTypeFromZipEntries(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry))return getOpenXmlFileTypeFromDirectoryNames(e)}function getOpenXmlMimeTypeFromContentTypesXml(e){let t=e.indexOf(`.main+xml"`);if(t===-1){let t=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;return e.includes(`ContentType="${t}"`)?t:void 0}let s=e.slice(0,t),g=s.lastIndexOf(`"`);return s.slice(g+1)}const zipDataDescriptorSignature=134695760,zipDataDescriptorLengthInBytes=16,zipDataDescriptorOverlapLengthInBytes=zipDataDescriptorLengthInBytes-1;function findZipDataDescriptorOffset(e,t){if(e.length<zipDataDescriptorLengthInBytes)return-1;let s=e.length-zipDataDescriptorLengthInBytes;for(let g=0;g<=s;g++)if(UINT32_LE.get(e,g)===zipDataDescriptorSignature&&UINT32_LE.get(e,g+8)===t+g)return g;return-1}async function readZipDataDescriptorEntryWithLimit(e,{shouldBuffer:t,maximumLength:s=maximumZipEntrySizeInBytes}={}){let{syncBuffer:g}=e,{length:S}=g,w=[],E=0;for(;;){let D=await e.tokenizer.peekBuffer(g,{mayBeLess:!0}),O=findZipDataDescriptorOffset(g.subarray(0,D),E),k=O>=0?0:D===S?Math.min(zipDataDescriptorOverlapLengthInBytes,D-1):0,j=O>=0?O:D-k;if(j===0)break;if(E+=j,E>s)throw Error(`ZIP entry compressed data exceeds ${s} bytes`);if(t){let t=new Uint8Array(j);await e.tokenizer.readBuffer(t),w.push(t)}else await e.tokenizer.ignore(j);if(O>=0)break}if(hasUnknownFileSize(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=E),t)return mergeByteChunks(w,E)}function getRemainingZipScanBudget(e,t){return hasUnknownFileSize(e.tokenizer)?Math.max(0,maximumUntrustedSkipSizeInBytes-(e.tokenizer.position-t)):Math.max(0,maximumZipEntrySizeInBytes-e.knownSizeDescriptorScannedBytes)}async function readZipEntryData(e,t,{shouldBuffer:s,maximumDescriptorLength:g=maximumZipEntrySizeInBytes}={}){if(t.dataDescriptor&&t.compressedSize===0)return readZipDataDescriptorEntryWithLimit(e,{shouldBuffer:s,maximumLength:g});if(!s){await safeIgnore(e.tokenizer,t.compressedSize,{maximumLength:hasUnknownFileSize(e.tokenizer)?maximumZipEntrySizeInBytes:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let S=getMaximumZipBufferedReadLength(e.tokenizer);if(!Number.isFinite(t.compressedSize)||t.compressedSize<0||t.compressedSize>S)throw Error(`ZIP entry compressed data exceeds ${S} bytes`);let w=new Uint8Array(t.compressedSize);return await e.tokenizer.readBuffer(w),w}ZipHandler.prototype.inflate=async function(e,t,s){if(e.compressedMethod===0)return s(t);if(e.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);return s(await decompressDeflateRawWithLimit(t,{maximumLength:maximumZipEntrySizeInBytes}))},ZipHandler.prototype.unzip=async function(e){let t=!1,s=0,g=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(hasExceededUnknownSizeScanBudget(this.tokenizer,g,16777216))throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`);let S=await this.readLocalFileHeader();if(!S)break;if(s++,s>maximumZipEntryCount)throw Error(`ZIP entry count exceeds ${maximumZipEntryCount}`);let w=e(S);t=!!w.stop,await this.tokenizer.ignore(S.extraFieldLength);let E=await readZipEntryData(this,S,{shouldBuffer:!!w.handler,maximumDescriptorLength:Math.min(maximumZipEntrySizeInBytes,getRemainingZipScanBudget(this,g))});if(w.handler&&await this.inflate(S,E,w.handler),S.dataDescriptor){let e=new Uint8Array(zipDataDescriptorLengthInBytes);if(await this.tokenizer.readBuffer(e),UINT32_LE.get(e,0)!==zipDataDescriptorSignature)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(hasExceededUnknownSizeScanBudget(this.tokenizer,g,16777216))throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`)}while(!t)};async function detectZip(e){let t,s=createOpenXmlZipDetectionState(),g=createIWorkZipDetectionState();try{await new ZipHandler(e).unzip(e=>{if(updateOpenXmlZipDetectionStateFromFilename(s,e.filename),updateIWorkZipDetectionStateFromFilename(g,e.filename),g.hasDocumentEntry&&(g.hasMasterSlideEntry||g.hasTablesEntry))return t=getIWorkFileTypeFromZipEntries(g),{stop:!0};let S=e.filename===`[Content_Types].xml`,w=getOpenXmlFileTypeFromZipEntries(s);if(!S&&w)return t=w,{stop:!0};switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return canReadZipEntryForDetection(e,maximumZipTextEntrySizeInBytes)?{async handler(e){t=getFileTypeFromMimeType(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return s.hasContentTypesEntry=!0,canReadZipEntryForDetection(e,maximumZipTextEntrySizeInBytes)?(s.isParsingContentTypes=!0,{async handler(e){let g=getOpenXmlMimeTypeFromContentTypesXml(new TextDecoder(`utf-8`).decode(e));g&&(t=getFileTypeFromMimeType(g)),s.hasParsedContentTypesEntry=!0,s.isParsingContentTypes=!1},stop:!0}):(s.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/v.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}})}catch(e){if(!isRecoverableZipError(e))throw e;s.isParsingContentTypes&&(s.isParsingContentTypes=!1,s.hasUnparseableContentTypes=!0),!t&&e instanceof EndOfStreamError&&!s.hasContentTypesEntry&&(t=getOpenXmlFileTypeFromDirectoryNames(s))}let S=hasUnknownFileSize(e)&&g.hasDocumentEntry&&!g.hasMasterSlideEntry&&!g.hasTablesEntry&&!g.hasCalculationEngineEntry?void 0:getIWorkFileTypeFromZipEntries(g);return t??getOpenXmlFileTypeFromZipEntries(s)??S??{ext:`zip`,mime:`application/zip`}}const maximumEbmlDocumentTypeSizeInBytes=64,maximumEbmlElementPayloadSizeInBytes=1024*1024,maximumEbmlElementCount=256;async function detectEbml(e){async function t(){let t=await e.peekNumber(UINT8),s=128,g=0;for(;(t&s)===0&&s!==0;)++g,s>>=1;let S=new Uint8Array(g+1);return await safeReadBuffer(e,S,void 0,{maximumLength:S.length,reason:`EBML field`}),S}async function s(){let e=await t(),s=await t();s[0]^=128>>s.length-1;let g=Math.min(6,s.length),S=new DataView(e.buffer),w=new DataView(s.buffer,s.length-g,g);return{id:getUintBE(S),len:getUintBE(w)}}async function g(t){let g=0;for(;t>0;){if(g++,g>maximumEbmlElementCount||hasExceededUnknownSizeScanBudget(e,w,16777216))return;let S=e.position,E=await s();if(E.id===17026){if(E.len>maximumEbmlDocumentTypeSizeInBytes)return;let t=getSafeBound(E.len,maximumEbmlDocumentTypeSizeInBytes,`EBML DocType`);return(await e.readToken(new StringType(t))).replaceAll(/\0.*$/gv,``)}if(hasUnknownFileSize(e)&&(!Number.isFinite(E.len)||E.len<0||E.len>maximumEbmlElementPayloadSizeInBytes)||(await safeIgnore(e,E.len,{maximumLength:hasUnknownFileSize(e)?maximumEbmlElementPayloadSizeInBytes:e.fileInfo.size,reason:`EBML payload`}),--t,e.position<=S))return}}let S=await s(),w=e.position;switch(await g(S.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:}}const maximumPngChunkCount=512,maximumPngStreamScanBudgetInBytes=16*1024*1024,maximumPngChunkSizeInBytes=1024*1024;function isPngAncillaryChunk(e){return(e.codePointAt(0)&32)!=0}async function detectPng(e){let t={ext:`png`,mime:`image/png`},s={ext:`apng`,mime:`image/apng`};await e.ignore(8);async function g(){return{length:await e.readToken(INT32_BE),type:await e.readToken(new StringType(4,`latin1`))}}let S=hasUnknownFileSize(e),w=e.position,E=0,D=!1;do{if(E++,E>maximumPngChunkCount||hasExceededUnknownSizeScanBudget(e,w,maximumPngStreamScanBudgetInBytes))break;let O=e.position,k=await g();if(k.length<0)return;if(k.type===`IHDR`){if(k.length!==13)return;D=!0}switch(k.type){case`IDAT`:return t;case`acTL`:return s;default:if(!D&&k.type!==`CgBI`)return;if(S&&k.length>maximumPngChunkSizeInBytes)return D&&isPngAncillaryChunk(k.type)?t:void 0;try{await safeIgnore(e,k.length+4,{maximumLength:S?maximumPngChunkSizeInBytes+4:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!S&&(e instanceof ParserHardLimitError||e instanceof EndOfStreamError))return t;throw e}}if(e.position<=O)break}while(e.position+8<e.fileInfo.size);return t}const maximumAsfHeaderObjectCount=512,maximumAsfHeaderPayloadSizeInBytes=1024*1024;async function detectAsf(e){let t=!1;try{async function s(){let t=new Uint8Array(16);return await safeReadBuffer(e,t,void 0,{maximumLength:t.length,reason:`ASF header GUID`}),{id:t,size:Number(await e.readToken(UINT64_LE))}}await safeIgnore(e,30,{maximumLength:30,reason:`ASF header prelude`});let g=hasUnknownFileSize(e),S=e.position,w=0;for(;e.position+24<e.fileInfo.size&&(w++,!(w>maximumAsfHeaderObjectCount||hasExceededUnknownSizeScanBudget(e,S,16777216)));){let S=e.position,w=await s(),E=w.size-24;if(!Number.isFinite(E)||E<0){t=!0;break}if(checkBytes(w.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(E-=await safeReadBuffer(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),checkBytes(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(checkBytes(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}if(g&&E>maximumAsfHeaderPayloadSizeInBytes){t=!0;break}if(await safeIgnore(e,E,{maximumLength:g?maximumAsfHeaderPayloadSizeInBytes:e.fileInfo.size,reason:`ASF header payload`}),e.position<=S){t=!0;break}}}catch(s){if(s instanceof EndOfStreamError||s instanceof ParserHardLimitError)hasUnknownFileSize(e)&&(t=!0);else throw s}if(!t)return{ext:`asf`,mime:`application/vnd.ms-asf`}}const reasonableDetectionSizeInBytes=4100,maximumMpegOffsetTolerance=reasonableDetectionSizeInBytes-2,maximumNestedGzipDetectionSizeInBytes=maximumUntrustedSkipSizeInBytes,maximumNestedGzipProbeDepth=1,unknownSizeGzipProbeTimeoutInMilliseconds=100,maximumId3HeaderSizeInBytes=maximumUntrustedSkipSizeInBytes,maximumTiffTagCount=512,maximumDetectionReentryCount=256,maximumTiffStreamIfdOffsetInBytes=1024*1024,maximumTiffIfdOffsetInBytes=maximumUntrustedSkipSizeInBytes;function normalizeSampleSize(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):reasonableDetectionSizeInBytes}function normalizeMpegOffsetTolerance(e){return Number.isFinite(e)?Math.max(0,Math.min(maximumMpegOffsetTolerance,Math.trunc(e))):0}function getKnownFileSizeOrMaximum(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function importAtRuntime(e){return import(e)}function toDefaultStream(e){return e.pipeThrough(new TransformStream)}function readWithSignal(e,t){return t===void 0?e.read():(t.throwIfAborted(),Promise.race([e.read(),new Promise((s,g)=>{t.addEventListener(`abort`,()=>{g(t.reason),e.cancel(t.reason).catch(()=>{})},{once:!0})})]))}function createByteLimitedReadableStream(e,t){let s=e.getReader(),g=0,S=!1,w=!1,E=async e=>{S||w||(w=!0,await s.cancel(e))};return new ReadableStream({async pull(e){if(g>=t){e.close(),await E();return}let{done:w,value:D}=await s.read();if(w||!D){S=!0,e.close();return}let O=t-g;if(D.length>O){e.enqueue(D.subarray(0,O)),g+=O,e.close(),await E();return}e.enqueue(D),g+=D.length},async cancel(e){await E(e)}})}var FileTypeParser=class e{constructor(e){let t=normalizeMpegOffsetTolerance(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return fromWebStream(toDefaultStream(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let s=e.position;for(let t of this.detectors){let g;try{g=await t.detect(e)}catch(e){if(e instanceof EndOfStreamError||e instanceof ParserHardLimitError)return;throw e}if(g)return g;if(s!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(fromBuffer(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=fromBlob(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async fromFile(e){this.options.signal?.throwIfAborted();let[{default:t},{FileTokenizer:s}]=await Promise.all([importAtRuntime(`node:fs/promises`),importAtRuntime(`strtok3`)]),g=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),S=await g.stat();if(!S.isFile()){await g.close();return}let w=new s(g,{...this.getTokenizerOptions(),fileInfo:{path:e,size:S.size}});return this.fromTokenizer(w)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let s=normalizeSampleSize(t?.sampleSize??4100),g,S=!1,w=e.getReader(),E=[],D=0;try{for(;D<s;){let{value:e,done:t}=await readWithSignal(w,this.options.signal);if(t||!e){S=!0;break}E.push(e),D+=e.length}if(!S&&D===s){let{value:e,done:t}=await readWithSignal(w,this.options.signal);t||!e?S=!0:(E.push(e),D+=e.length)}}finally{w.releaseLock()}if(D>0){let e=E.length===1?E[0]:concatUint8Arrays(E);try{g=await this.fromBuffer(e.subarray(0,s))}catch(e){if(!(e instanceof EndOfStreamError))throw e;g=void 0}!S&&g?.ext===`pages`&&(g={ext:`zip`,mime:`application/zip`})}let O=new TransformStream({start(e){for(let t of E)e.enqueue(t)},transform(e,t){t.enqueue(e)}}),k=e.pipeThrough(O);return k.fileType=g,k}async detectGzip(t){if(this.gzipProbeDepth>=maximumNestedGzipProbeDepth)return{ext:`gz`,mime:`application/gzip`};let s=createByteLimitedReadableStream(new GzipHandler(t).inflate(),maximumNestedGzipDetectionSizeInBytes),g=hasUnknownFileSize(t),S,w,E,D;if(g){let t=new AbortController;S=setTimeout(()=>{t.abort(new DOMException(`Operation timed out after ${unknownSizeGzipProbeTimeoutInMilliseconds} ms`,`TimeoutError`))},unknownSizeGzipProbeTimeoutInMilliseconds),w=this.options.signal===void 0?t.signal:AbortSignal.any([this.options.signal,t.signal]),E=new e({...this.options,signal:w}),E.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{D=await(E??this).fromStream(s)}catch(e){if(e?.name===`AbortError`&&w?.reason?.name!==`TimeoutError`)throw e}finally{clearTimeout(S),g||this.gzipProbeDepth--}return D?.ext===`tar`?{ext:`tar.gz`,mime:`application/gzip`}:{ext:`gz`,mime:`application/gzip`}}check(e,t){return checkBytes(this.buffer,e,t)}checkString(e,t){return this.check(stringToBytes(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(reasonableDetectionSizeInBytes),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,hasUnknownFileSize(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.detectionReentryCount>=maximumDetectionReentryCount?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(e));if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return this.detectGzip(e);if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await safeIgnore(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(uint32SyncSafeToken),s=hasUnknownFileSize(e);if(!Number.isFinite(t)||t<0||s&&(t>maximumId3HeaderSizeInBytes||e.position+t>maximumId3HeaderSizeInBytes))return;if(e.position+t>e.fileInfo.size)return s?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await safeIgnore(e,t,{maximumLength:s?maximumId3HeaderSizeInBytes:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}return this.detectionReentryCount>=maximumDetectionReentryCount?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4]))return detectZip(e);if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),checkBytes(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:checkBytes(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:checkBytes(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:checkBytes(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:checkBytes(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:checkBytes(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163]))return detectEbml(e);if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.checkString(`regf`))return{ext:`dat`,mime:`application/x-ft-windows-registry-hive`};if(this.checkString(`$FL2`)||this.checkString(`$FL3`))return{ext:`sav`,mime:`application/x-spss-sav`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(String.raw`{\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190])){let e=UINT32_BE.get(this.buffer,4),t=UINT16_BE.get(this.buffer,6);if(e>0&&e<=30)return{ext:`macho`,mime:`application/x-mach-binary`};if(t>30)return{ext:`class`,mime:`application/java-vm`}}if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/x-ft-draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new StringType(4,`latin1`).get(this.buffer,2);if(/^\d+$/v.test(e)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new StringType(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
|
|
38
|
+
`),F=Buffer.from(`\r`),L=Buffer.from(`-`);function B(){}let H=2e3,q=16*1024,ee=0,J=1,Y=2;var te=class{constructor(e){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0,this.cb=e}reset(){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0}push(e,t,s){let g=t;for(;t<s;)switch(this.state){case 0:{let S=!1;for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(fe[s]!==1){if(s!==58||(this.name+=e.latin1Slice(g,t),this.name.length===0))return-1;++t,S=!0,this.state=1;break}}if(!S){this.name+=e.latin1Slice(g,t);break}}case 1:{let S=!1;for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(s!==32&&s!==9){g=t,S=!0,this.state=2;break}}if(!S)break}case 2:switch(this.crlf){case 0:for(;t<s;++t){if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];if(me[s]!==1){if(s!==13)return-1;++this.crlf;break}}this.value+=e.latin1Slice(g,t++);break;case 1:if(this.byteCount===q||(++this.byteCount,e[t++]!==10))return-1;++this.crlf;break;case 2:{if(this.byteCount===q)return-1;++this.byteCount;let s=e[t];s===32||s===9?(g=t,this.crlf=0):(++this.pairCount<2e3&&(this.name=this.name.toLowerCase(),this.header[this.name]===void 0?this.header[this.name]=[this.value]:this.header[this.name].push(this.value)),s===13?(++this.crlf,++t):(g=t,this.crlf=0,this.state=0,this.name=``,this.value=``));break}case 3:{if(this.byteCount===q||(++this.byteCount,e[t++]!==10))return-1;let s=this.header;return this.reset(),this.cb(s),t}}break}return t}},ne=class extends s{constructor(e,t){super(e),this.truncated=!1,this._readcb=null,this.once(`end`,()=>{if(this._read(),--t._fileEndsLeft===0&&t._finalcb){let e=t._finalcb;t._finalcb=null,process.nextTick(e)}})}_read(e){let t=this._readcb;t&&(this._readcb=null,t())}};let ae={push:(e,t)=>{},destroy:()=>{}};function oe(e,t){let s=e._writecb;e._writecb=null,t?e.destroy(t):s&&s()}function se(e,t){return e}var ce=class extends g{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};if(super(t),!e.conType.params||typeof e.conType.params.boundary!=`string`)throw Error(`Multipart: Boundary not found`);let s=e.conType.params.boundary,g=typeof e.defParamCharset==`string`&&e.defParamCharset?D(e.defParamCharset):se,H=e.defCharset||`utf8`,q=e.preservePath,ee={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.fileHwm==`number`?e.fileHwm:void 0},J=e.limits,Y=J&&typeof J.fieldSize==`number`?J.fieldSize:1*1024*1024,oe=J&&typeof J.fileSize==`number`?J.fileSize:1/0,ce=J&&typeof J.files==`number`?J.files:1/0,ue=J&&typeof J.fields==`number`?J.fields:1/0,de=J&&typeof J.parts==`number`?J.parts:1/0,fe=-1,me=0,ge=0,_e=!1;this._fileEndsLeft=0,this._fileStream=void 0,this._complete=!1;let ve=0,ye,Ce=0,we,Te,De,je,Me=!1,Pe=!1,Ie=!1;this._hparser=null;let Re=new te(e=>{this._hparser=null,_e=!1,De=`text/plain`,we=H,Te=`7bit`,je=void 0,Me=!1;let t;if(!e[`content-disposition`]){_e=!0;return}let s=k(e[`content-disposition`][0],g);if(!s||s.type!==`form-data`){_e=!0;return}if(s.params&&(s.params.name&&(je=s.params.name),s.params[`filename*`]?t=s.params[`filename*`]:s.params.filename&&(t=s.params.filename),t!==void 0&&!q&&(t=w(t))),e[`content-type`]){let t=O(e[`content-type`][0]);t&&(De=`${t.type}/${t.subtype}`,t.params&&typeof t.params.charset==`string`&&(we=t.params.charset.toLowerCase()))}if(e[`content-transfer-encoding`]&&(Te=e[`content-transfer-encoding`][0].toLowerCase()),De===`application/octet-stream`||t!==void 0){if(ge===ce){Pe||(Pe=!0,this.emit(`filesLimit`)),_e=!0;return}if(++ge,this.listenerCount(`file`)===0){_e=!0;return}ve=0,this._fileStream=new ne(ee,this),++this._fileEndsLeft,this.emit(`file`,je,this._fileStream,{filename:t,encoding:Te,mimeType:De})}else{if(me===ue){Ie||(Ie=!0,this.emit(`fieldsLimit`)),_e=!0;return}if(++me,this.listenerCount(`field`)===0){_e=!0;return}ye=[],Ce=0}}),ze=0,Be=(e,t,s,g,S)=>{retrydata:for(;t;){if(this._hparser!==null){let e=this._hparser.push(t,s,g);if(e===-1){this._hparser=null,Re.reset(),this.emit(`error`,Error(`Malformed part header`));break}s=e}if(s===g)break;if(ze!==0){if(ze===1){switch(t[s]){case 45:ze=2,++s;break;case 13:ze=3,++s;break;default:ze=0}if(s===g)return}if(ze===2){if(ze=0,t[s]===45){this._complete=!0,this._bparser=ae;return}let e=this._writecb;this._writecb=B,Be(!1,L,0,1,!1),this._writecb=e}else if(ze===3)if(ze=0,t[s]===10){if(++s,fe>=de||(this._hparser=Re,s===g))break;continue retrydata}else{let e=this._writecb;this._writecb=B,Be(!1,F,0,1,!1),this._writecb=e}}if(!_e){if(this._fileStream){let e,w=Math.min(g-s,oe-ve);S?e=t.slice(s,s+w):(e=Buffer.allocUnsafe(w),t.copy(e,0,s,s+w)),ve+=e.length,ve===oe?(e.length>0&&this._fileStream.push(e),this._fileStream.emit(`limit`),this._fileStream.truncated=!0,_e=!0):this._fileStream.push(e)||(this._writecb&&(this._fileStream._readcb=this._writecb),this._writecb=null)}else if(ye!==void 0){let e,w=Math.min(g-s,Y-Ce);S?e=t.slice(s,s+w):(e=Buffer.allocUnsafe(w),t.copy(e,0,s,s+w)),Ce+=w,ye.push(e),Ce===Y&&(_e=!0,Me=!0)}}break}if(e){if(ze=1,this._fileStream)this._fileStream.push(null),this._fileStream=null;else if(ye!==void 0){let e;switch(ye.length){case 0:e=``;break;case 1:e=E(ye[0],we,0);break;default:e=E(Buffer.concat(ye,Ce),we,0)}ye=void 0,Ce=0,this.emit(`field`,je,e,{nameTruncated:!1,valueTruncated:Me,encoding:Te,mimeType:De})}++fe===de&&this.emit(`partsLimit`)}};this._bparser=new S(`\r\n--${s}`,Be),this._writecb=null,this._finalcb=null,this.write(j)}static detect(e){return e.type===`multipart`&&e.subtype===`form-data`}_write(e,t,s){this._writecb=s,this._bparser.push(e,0),this._writecb&&oe(this)}_destroy(e,t){this._hparser=null,this._bparser=ae,e||=de(this);let s=this._fileStream;s&&(this._fileStream=null,s.destroy(e)),t(e)}_final(e){if(this._bparser.destroy(),!this._complete)return e(Error(`Unexpected end of form`));this._fileEndsLeft?this._finalcb=ue.bind(null,this,e):ue(this,e)}};function ue(e,t,s){if(s)return t(s);s=de(e),t(s)}function de(e){if(e._hparser)return Error(`Malformed part header`);let t=e._fileStream;if(t&&(e._fileStream=null,t.destroy(Error(`Unexpected end of file`))),!e._complete)return Error(`Unexpected end of form`)}let fe=[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,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,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,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,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],me=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,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,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,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,1,1,1,1,1,1,1,1,1,1,1,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,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,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,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,1,1,1,1,1,1,1,1,1,1,1,1];t.exports=ce})),require_urlencoded=__commonJSMin$2(((e,t)=>{let{Writable:s}=__require$2(`stream`),{getDecoder:g}=require_utils$2();var S=class extends s{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};super(t);let s=e.defCharset||`utf8`;e.conType.params&&typeof e.conType.params.charset==`string`&&(s=e.conType.params.charset),this.charset=s;let S=e.limits;this.fieldSizeLimit=S&&typeof S.fieldSize==`number`?S.fieldSize:1*1024*1024,this.fieldsLimit=S&&typeof S.fields==`number`?S.fields:1/0,this.fieldNameSizeLimit=S&&typeof S.fieldNameSize==`number`?S.fieldNameSize:100,this._inKey=!0,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,this._fields=0,this._key=``,this._val=``,this._byte=-2,this._lastPos=0,this._encode=0,this._decoder=g(s)}static detect(e){return e.type===`application`&&e.subtype===`x-www-form-urlencoded`}_write(e,t,s){if(this._fields>=this.fieldsLimit)return s();let g=0,S=e.length;if(this._lastPos=0,this._byte!==-2){if(g=w(this,e,g,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();this._inKey?++this._bytesKey:++this._bytesVal}main:for(;g<S;)if(this._inKey){for(g=E(this,e,g,S);g<S;){switch(e[g]){case 61:this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._key=this._decoder(this._key,this._encode),this._encode=0,this._inKey=!1;continue main;case 38:if(this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._key=this._decoder(this._key,this._encode),this._encode=0,this._bytesKey>0&&this.emit(`field`,this._key,``,{nameTruncated:this._keyTrunc,valueTruncated:!1,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),s();continue;case 43:this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._key+=` `,this._lastPos=g+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g)),this._lastPos=g+1,this._byte=-1,g=w(this,e,g+1,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();++this._bytesKey,g=E(this,e,g,S);continue}++g,++this._bytesKey,g=E(this,e,g,S)}this._lastPos<g&&(this._key+=e.latin1Slice(this._lastPos,g))}else{for(g=D(this,e,g,S);g<S;){switch(e[g]){case 38:if(this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._lastPos=++g,this._inKey=!0,this._val=this._decoder(this._val,this._encode),this._encode=0,(this._bytesKey>0||this._bytesVal>0)&&this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),s();continue main;case 43:this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._val+=` `,this._lastPos=g+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g)),this._lastPos=g+1,this._byte=-1,g=w(this,e,g+1,S),g===-1)return s(Error(`Malformed urlencoded form`));if(g>=S)return s();++this._bytesVal,g=D(this,e,g,S);continue}++g,++this._bytesVal,g=D(this,e,g,S)}this._lastPos<g&&(this._val+=e.latin1Slice(this._lastPos,g))}s()}_final(e){if(this._byte!==-2)return e(Error(`Malformed urlencoded form`));(!this._inKey||this._bytesKey>0||this._bytesVal>0)&&(this._inKey?this._key=this._decoder(this._key,this._encode):this._val=this._decoder(this._val,this._encode),this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`})),e()}};function w(e,t,s,g){if(s>=g)return g;if(e._byte===-1){let S=O[t[s++]];if(S===-1)return-1;if(S>=8&&(e._encode=2),s<g){let g=O[t[s++]];if(g===-1)return-1;e._inKey?e._key+=String.fromCharCode((S<<4)+g):e._val+=String.fromCharCode((S<<4)+g),e._byte=-2,e._lastPos=s}else e._byte=S}else{let g=O[t[s++]];if(g===-1)return-1;e._inKey?e._key+=String.fromCharCode((e._byte<<4)+g):e._val+=String.fromCharCode((e._byte<<4)+g),e._byte=-2,e._lastPos=s}return s}function E(e,t,s,g){if(e._bytesKey>e.fieldNameSizeLimit){for(e._keyTrunc||e._lastPos<s&&(e._key+=t.latin1Slice(e._lastPos,s-1)),e._keyTrunc=!0;s<g;++s){let g=t[s];if(g===61||g===38)break;++e._bytesKey}e._lastPos=s}return s}function D(e,t,s,g){if(e._bytesVal>e.fieldSizeLimit){for(e._valTrunc||e._lastPos<s&&(e._val+=t.latin1Slice(e._lastPos,s-1)),e._valTrunc=!0;s<g&&t[s]!==38;++s)++e._bytesVal;e._lastPos=s}return s}let O=[-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,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-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,10,11,12,13,14,15,-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,-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,-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,-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,-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,-1,-1,-1,-1,-1,-1,-1,-1];t.exports=S})),require_lib=__commonJSMin$2(((e,t)=>{let{parseContentType:s}=require_utils$2();function g(e){let t=e.headers,g=s(t[`content-type`]);if(!g)throw Error(`Malformed content type`);for(let s of S){if(!s.detect(g))continue;let S={limits:e.limits,headers:t,conType:g,highWaterMark:void 0,fileHwm:void 0,defCharset:void 0,defParamCharset:void 0,preservePath:!1};return e.highWaterMark&&(S.highWaterMark=e.highWaterMark),e.fileHwm&&(S.fileHwm=e.fileHwm),S.defCharset=e.defCharset,S.defParamCharset=e.defParamCharset,S.preservePath=e.preservePath,new s(S)}throw Error(`Unsupported content type: ${t[`content-type`]}`)}let S=[require_multipart(),require_urlencoded()].filter(function(e){return typeof e.detect==`function`});t.exports=e=>{if((typeof e!=`object`||!e)&&(e={}),typeof e.headers!=`object`||e.headers===null||typeof e.headers[`content-type`]!=`string`)throw Error(`Missing Content-Type`);return g(e)}}));const WINDOWS_1252_EXTRA={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},WINDOWS_1252_REVERSE={};for(let[e,t]of Object.entries(WINDOWS_1252_EXTRA))WINDOWS_1252_REVERSE[t]=Number.parseInt(e,10);let _utf8Decoder;function utf8Decoder(){if(globalThis.TextDecoder!==void 0)return _utf8Decoder??=new globalThis.TextDecoder(`utf-8`)}const CHUNK=32*1024,REPLACEMENT=65533;function textDecode(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=utf8Decoder();return t?t.decode(e):decodeUTF8(e)}case`utf-16le`:return decodeUTF16LE(e);case`us-ascii`:case`ascii`:return decodeASCII(e);case`latin1`:case`iso-8859-1`:return decodeLatin1(e);case`windows-1252`:return decodeWindows1252(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function flushChunk(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function pushCodeUnit(e,t,s){t.push(s),t.length>=CHUNK&&flushChunk(e,t)}function pushCodePoint(e,t,s){if(s<=65535){pushCodeUnit(e,t,s);return}s-=65536,pushCodeUnit(e,t,55296+(s>>10)),pushCodeUnit(e,t,56320+(s&1023))}function decodeUTF8(e){let t=[],s=[],g=0;for(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191&&(g=3);g<e.length;){let S=e[g];if(S<=127){pushCodeUnit(t,s,S),g++;continue}if(S<194||S>244){pushCodeUnit(t,s,REPLACEMENT),g++;continue}if(S<=223){if(g+1>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1];if((w&192)!=128){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodeUnit(t,s,(S&31)<<6|w&63),g+=2;continue}if(S<=239){if(g+2>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1],E=e[g+2];if(!((w&192)==128&&(E&192)==128&&!(S===224&&w<160)&&!(S===237&&w>=160))){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodeUnit(t,s,(S&15)<<12|(w&63)<<6|E&63),g+=3;continue}if(g+3>=e.length){pushCodeUnit(t,s,REPLACEMENT),g++;continue}let w=e[g+1],E=e[g+2],D=e[g+3];if(!((w&192)==128&&(E&192)==128&&(D&192)==128&&!(S===240&&w<144)&&!(S===244&&w>143))){pushCodeUnit(t,s,REPLACEMENT),g++;continue}pushCodePoint(t,s,(S&7)<<18|(w&63)<<12|(E&63)<<6|D&63),g+=4}return flushChunk(t,s),t.join(``)}function decodeUTF16LE(e){let t=[],s=[],g=e.length,S=0;for(;S+1<g;){let w=e[S]|e[S+1]<<8;if(S+=2,w>=55296&&w<=56319){if(S+1<g){let g=e[S]|e[S+1]<<8;g>=56320&&g<=57343?(pushCodeUnit(t,s,w),pushCodeUnit(t,s,g),S+=2):pushCodeUnit(t,s,REPLACEMENT)}else pushCodeUnit(t,s,REPLACEMENT);continue}if(w>=56320&&w<=57343){pushCodeUnit(t,s,REPLACEMENT);continue}pushCodeUnit(t,s,w)}return S<g&&pushCodeUnit(t,s,REPLACEMENT),flushChunk(t,s),t.join(``)}function decodeASCII(e){let t=[];for(let s=0;s<e.length;s+=CHUNK){let g=Math.min(e.length,s+CHUNK),S=Array(g-s);for(let t=s,w=0;t<g;t++,w++)S[w]=e[t]&127;t.push(String.fromCharCode.apply(null,S))}return t.join(``)}function decodeLatin1(e){let t=[];for(let s=0;s<e.length;s+=CHUNK){let g=Math.min(e.length,s+CHUNK),S=Array(g-s);for(let t=s,w=0;t<g;t++,w++)S[w]=e[t];t.push(String.fromCharCode.apply(null,S))}return t.join(``)}function decodeWindows1252(e){let t=[],s=``;for(let g=0;g<e.length;g++){let S=e[g],w=S>=128&&S<=159?WINDOWS_1252_EXTRA[S]:void 0;s+=w??String.fromCharCode(S),s.length>=CHUNK&&(t.push(s),s=``)}return s&&t.push(s),t.join(``)}function dv(e){return new DataView(e.buffer,e.byteOffset)}const UINT8={len:1,get(e,t){return dv(e).getUint8(t)},put(e,t,s){return dv(e).setUint8(t,s),t+1}},UINT16_LE={len:2,get(e,t){return dv(e).getUint16(t,!0)},put(e,t,s){return dv(e).setUint16(t,s,!0),t+2}},UINT16_BE={len:2,get(e,t){return dv(e).getUint16(t)},put(e,t,s){return dv(e).setUint16(t,s),t+2}},UINT32_LE={len:4,get(e,t){return dv(e).getUint32(t,!0)},put(e,t,s){return dv(e).setUint32(t,s,!0),t+4}},UINT32_BE={len:4,get(e,t){return dv(e).getUint32(t)},put(e,t,s){return dv(e).setUint32(t,s),t+4}},INT32_BE={len:4,get(e,t){return dv(e).getInt32(t)},put(e,t,s){return dv(e).setInt32(t,s),t+4}},UINT64_LE={len:8,get(e,t){return dv(e).getBigUint64(t,!0)},put(e,t,s){return dv(e).setBigUint64(t,s,!0),t+8}};var StringType=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return textDecode(e.subarray(t,t+this.len),this.encoding)}};const defaultMessages=`End-Of-Stream`;var EndOfStreamError=class extends Error{constructor(){super(defaultMessages),this.name=`EndOfStreamError`}},AbortError=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},AbstractStreamReader=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let s=await this.read(e,t);return this.peekQueue.push(e.subarray(0,s)),s}async read(e,t=!1){if(e.length===0)return 0;let s=this.readFromPeekBuffer(e);if(this.endOfStream||(s+=await this.readRemainderFromStream(e.subarray(s),t)),s===0&&!t)throw new EndOfStreamError;return s}readFromPeekBuffer(e){let t=e.length,s=0;for(;this.peekQueue.length>0&&t>0;){let g=this.peekQueue.pop();if(!g)throw Error(`peekData should be defined`);let S=Math.min(g.length,t);e.set(g.subarray(0,S),s),s+=S,t-=S,S<g.length&&this.peekQueue.push(g.subarray(S))}return s}async readRemainderFromStream(e,t){let s=0;for(;s<e.length&&!this.endOfStream;){if(this.interrupted)throw new AbortError;let g=await this.readFromStream(e.subarray(s),t);if(g===0)break;s+=g}if(!t&&s<e.length)throw new EndOfStreamError;return s}},WebStreamReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},WebStreamByobReader=class extends WebStreamReader{async readFromStream(e,t){if(e.length===0)return 0;let s=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return s.done&&(this.endOfStream=s.done),s.value?(e.set(s.value),s.value.length):0}},WebStreamDefaultReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let s=Math.min(t.length,e.length);return e.set(t.subarray(0,s)),s<t.length?this.buffer=t.subarray(s):this.buffer=null,s}async readFromStream(e,t){if(e.length===0)return 0;let s=0;for(this.buffer&&(s+=this.writeChunk(e,this.buffer));s<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(s+=this.writeChunk(e.subarray(s),t.value))}if(!t&&s===0&&this.endOfStream)throw new EndOfStreamError;return s}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function makeWebStreamReader(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new WebStreamDefaultReader(t):new WebStreamByobReader(t)}catch(t){if(t instanceof TypeError)return new WebStreamDefaultReader(e.getReader());throw t}}var AbstractTokenizer=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let s=new Uint8Array(e.len);if(await this.readBuffer(s,{position:t})<e.len)throw new EndOfStreamError;return e.get(s,0)}async peekToken(e,t=this.position){let s=new Uint8Array(e.len);if(await this.peekBuffer(s,{position:t})<e.len)throw new EndOfStreamError;return e.get(s,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};const maxBufferSize=256e3;var ReadStreamTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let s=this.normalizeOptions(e,t),g=s.position-this.position;if(g>0)return await this.ignore(g),this.readBuffer(e,t);if(g<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(s.length===0)return 0;let S=await this.streamReader.read(e.subarray(0,s.length),s.mayBeLess);if(this.position+=S,(!t||!t.mayBeLess)&&S<s.length)throw new EndOfStreamError;return S}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=0;if(s.position){let t=s.position-this.position;if(t>0){let S=new Uint8Array(s.length+t);return g=await this.peekBuffer(S,{mayBeLess:s.mayBeLess}),e.set(S.subarray(t)),g-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(s.length>0){try{g=await this.streamReader.peek(e.subarray(0,s.length),s.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof EndOfStreamError)return 0;throw e}if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError}return g}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);let t=Math.min(maxBufferSize,e),s=new Uint8Array(t),g=0;for(;g<e;){let S=e-g,w=await this.readBuffer(s,{length:Math.min(t,S)});if(w<0)return w;g+=w}return g}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},BufferTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let s=await this.peekBuffer(e,t);return this.position+=s,s}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=Math.min(this.uint8Array.length-s.position,s.length);if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError;return e.set(this.uint8Array.subarray(s.position,s.position+g)),g}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},BlobTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let s=await this.peekBuffer(e,t);return this.position+=s,s}async peekBuffer(e,t){let s=this.normalizeOptions(e,t),g=Math.min(this.blob.size-s.position,s.length);if(!s.mayBeLess&&g<s.length)throw new EndOfStreamError;let S=await this.blob.slice(s.position,s.position+g).arrayBuffer();return e.set(new Uint8Array(S)),g}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function fromWebStream(e,t){let s=makeWebStreamReader(e),g=t??{},S=g.onClose;return g.onClose=async()=>{if(await s.close(),S)return S()},new ReadStreamTokenizer(s,g)}function fromBuffer(e,t){return new BufferTokenizer(e,t)}function fromBlob(e,t){return new BlobTokenizer(e,t)}const Signature={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},DataDescriptor={get(e){return{signature:UINT32_LE.get(e,0),compressedSize:UINT32_LE.get(e,8),uncompressedSize:UINT32_LE.get(e,12)}},len:16},LocalFileHeaderToken={get(e){let t=UINT16_LE.get(e,6);return{signature:UINT32_LE.get(e,0),minVersion:UINT16_LE.get(e,4),dataDescriptor:!!(t&8),compressedMethod:UINT16_LE.get(e,8),compressedSize:UINT32_LE.get(e,18),uncompressedSize:UINT32_LE.get(e,22),filenameLength:UINT16_LE.get(e,26),extraFieldLength:UINT16_LE.get(e,28),filename:null}},len:30},EndOfCentralDirectoryRecordToken={get(e){return{signature:UINT32_LE.get(e,0),nrOfThisDisk:UINT16_LE.get(e,4),nrOfThisDiskWithTheStart:UINT16_LE.get(e,6),nrOfEntriesOnThisDisk:UINT16_LE.get(e,8),nrOfEntriesOfSize:UINT16_LE.get(e,10),sizeOfCd:UINT32_LE.get(e,12),offsetOfStartOfCd:UINT32_LE.get(e,16),zipFileCommentLength:UINT16_LE.get(e,20)}},len:22},FileHeader={get(e){let t=UINT16_LE.get(e,8);return{signature:UINT32_LE.get(e,0),minVersion:UINT16_LE.get(e,6),dataDescriptor:!!(t&8),compressedMethod:UINT16_LE.get(e,10),compressedSize:UINT32_LE.get(e,20),uncompressedSize:UINT32_LE.get(e,24),filenameLength:UINT16_LE.get(e,28),extraFieldLength:UINT16_LE.get(e,30),fileCommentLength:UINT16_LE.get(e,32),relativeOffsetOfLocalHeader:UINT32_LE.get(e,42),filename:null}},len:46};var import_src$8=__toESM$2(require_src$15(),1);function signatureToArray(e){let t=new Uint8Array(UINT32_LE.len);return UINT32_LE.put(t,0,e),t}const debug=(0,import_src$8.default)(`tokenizer:inflate`),syncBufferSize=256*1024,ddSignatureArray=signatureToArray(Signature.DataDescriptor),eocdSignatureBytes=signatureToArray(Signature.EndOfCentralDirectory);var ZipHandler=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(syncBufferSize)}async isZip(){return await this.peekSignature()===Signature.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(UINT32_LE)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),s=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(s,{position:e.fileInfo.size-t});for(let g=s.length-4;g>=0;g--)if(s[g]===eocdSignatureBytes[0]&&s[g+1]===eocdSignatureBytes[1]&&s[g+2]===eocdSignatureBytes[2]&&s[g+3]===eocdSignatureBytes[3])return e.fileInfo.size-t+g;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){debug(`Cannot reading central-directory without random-read support`);return}debug(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){debug(`Central-directory 32-bit signature found`);let s=await this.tokenizer.readToken(EndOfCentralDirectoryRecordToken,t),g=[];this.tokenizer.setPosition(s.offsetOfStartOfCd);for(let e=0;e<s.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(FileHeader);if(t.signature!==Signature.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new StringType(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),g.push(t),debug(`Add central-directory file-entry: n=${e+1}/${g.length}: filename=${g[e].filename}`)}return this.tokenizer.setPosition(e),g}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let s=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let g=e(t);s=!!g.stop;let S;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],s=syncBufferSize;debug(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let S=-1;for(;S<0&&s===syncBufferSize;){s=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),S=indexOf(this.syncBuffer.subarray(0,s),ddSignatureArray);let t=S>=0?S:s;if(g.handler){let s=new Uint8Array(t);await this.tokenizer.readBuffer(s),e.push(s)}else await this.tokenizer.ignore(t)}debug(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),g.handler&&await this.inflate(t,mergeArrays(e),g.handler)}else g.handler?(debug(`Reading compressed-file-data: ${t.compressedSize} bytes`),S=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(S),await this.inflate(t,S,g.handler)):(debug(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(debug(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(DataDescriptor)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-DataDescriptor.len}`)}while(!s)}async iterateOverCentralDirectory(e,t){for(let s of e){let e=t(s);if(e.handler){this.tokenizer.setPosition(s.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let g=new Uint8Array(s.compressedSize);await this.tokenizer.readBuffer(g),await this.inflate(t,g,e.handler)}}if(e.stop)break}}async inflate(t,s,g){if(t.compressedMethod===0)return g(s);if(t.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${t.compressedMethod}`);return debug(`Decompress filename=${t.filename}, compressed-size=${s.length}`),g(await e.decompressDeflateRaw(s))}static async decompressDeflateRaw(e){let t=new ReadableStream({start(t){t.enqueue(e),t.close()}}),s=new DecompressionStream(`deflate-raw`),g=t.pipeThrough(s);try{let e=await new Response(g).arrayBuffer();return new Uint8Array(e)}catch(e){let t=e instanceof Error?`Failed to deflate ZIP entry: ${e.message}`:`Unknown decompression error in ZIP entry`;throw TypeError(t)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(UINT32_LE);if(e===Signature.LocalFileHeader){let e=await this.tokenizer.readToken(LocalFileHeaderToken);return e.filename=await this.tokenizer.readToken(new StringType(e.filenameLength,`utf-8`)),e}if(e===Signature.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}};function indexOf(e,t){let s=e.length,g=t.length;if(g>s)return-1;for(let S=0;S<=s-g;S++){let s=!0;for(let w=0;w<g;w++)if(e[S+w]!==t[w]){s=!1;break}if(s)return S}return-1}function mergeArrays(e){let t=e.reduce((e,t)=>e+t.length,0),s=new Uint8Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return s}var GzipHandler=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let s=new Uint8Array(1024),g=await e.readBuffer(s,{mayBeLess:!0});if(g===0){t.close();return}t.enqueue(s.subarray(0,g))}}).pipeThrough(new DecompressionStream(`gzip`))}};const objectToString=Object.prototype.toString,uint8ArrayStringified=`[object Uint8Array]`;function isType(e,t,s){return e?e.constructor===t?!0:objectToString.call(e)===s:!1}function isUint8Array(e){return isType(e,Uint8Array,uint8ArrayStringified)}function assertUint8Array(e){if(!isUint8Array(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function concatUint8Arrays(e,t){if(e.length===0)return new Uint8Array;t??=e.reduce((e,t)=>e+t.length,0);let s=new Uint8Array(t),g=0;for(let t of e)assertUint8Array(t),s.set(t,g),g+=t.length;return s}const cachedDecoders={utf8:new globalThis.TextDecoder(`utf8`)},cachedEncoder=new globalThis.TextEncoder,byteToHexLookupTable=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function getUintBE(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function stringToBytes(e,t){if(t===`utf-16le`){let t=[];for(let s=0;s<e.length;s++){let g=e.charCodeAt(s);t.push(g&255,g>>8&255)}return t}if(t===`utf-16be`){let t=[];for(let s=0;s<e.length;s++){let g=e.charCodeAt(s);t.push(g>>8&255,g&255)}return t}return[...e].map(e=>e.charCodeAt(0))}function tarHeaderChecksumMatches(e,t=0){let s=Number.parseInt(new StringType(6).get(e,148).replace(/\0.*$/v,``).trim(),8);if(Number.isNaN(s))return!1;let g=256;for(let s=t;s<t+148;s++)g+=e[s];for(let s=t+156;s<t+512;s++)g+=e[s];return s===g}const uint32SyncSafeToken={get:(e,t)=>e[t+3]&127|(e[t+2]&127)<<7|(e[t+1]&127)<<14|(e[t]&127)<<21,len:4},extensions=`jpg,png,apng,gif,webp,flif,xcf,cr2,cr3,orf,arw,dng,nef,rw2,raf,tif,bmp,icns,jxr,psd,indd,zip,tar,rar,gz,bz2,7z,dmg,mp4,mid,mkv,webm,mov,avi,mpg,mp2,mp3,m4a,oga,ogg,ogv,opus,flac,wav,spx,amr,pdf,epub,elf,macho,exe,swf,rtf,wasm,woff,woff2,eot,ttf,otf,ttc,ico,flv,ps,xz,sqlite,nes,crx,xpi,cab,deb,ar,rpm,Z,lz,cfb,mxf,mts,blend,bpg,docx,pptx,xlsx,3gp,3g2,j2c,jp2,jpm,jpx,mj2,aif,qcp,odt,ods,odp,xml,mobi,heic,cur,ktx,ape,wv,dcm,ics,glb,pcap,dsf,lnk,alias,voc,ac3,m4v,m4p,m4b,f4v,f4p,f4b,f4a,mie,asf,ogm,ogx,mpc,arrow,shp,aac,mp1,it,s3m,xm,skp,avif,eps,lzh,pgp,asar,stl,chm,3mf,zst,jxl,vcf,jls,pst,dwg,parquet,class,arj,cpio,ace,avro,icc,fbx,vsdx,vtt,apk,drc,lz4,potx,xltx,dotx,xltm,ott,ots,otp,odg,otg,xlsm,docm,dotm,potm,pptm,jar,jmp,rm,sav,ppsm,ppsx,tar.gz,reg,dat,key,numbers,pages`.split(`,`),mimeTypes=`image/jpeg,image/png,image/gif,image/webp,image/flif,image/x-xcf,image/x-canon-cr2,image/x-canon-cr3,image/tiff,image/bmp,image/vnd.ms-photo,image/vnd.adobe.photoshop,application/x-indesign,application/epub+zip,application/x-xpinstall,application/vnd.ms-powerpoint.slideshow.macroenabled.12,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.spreadsheet,application/vnd.oasis.opendocument.presentation,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/zip,application/x-tar,application/x-rar-compressed,application/gzip,application/x-bzip2,application/x-7z-compressed,application/x-apple-diskimage,application/vnd.apache.arrow.file,video/mp4,audio/midi,video/matroska,video/webm,video/quicktime,video/vnd.avi,audio/wav,audio/qcelp,audio/x-ms-asf,video/x-ms-asf,application/vnd.ms-asf,video/mpeg,video/3gpp,audio/mpeg,audio/mp4,video/ogg,audio/ogg,audio/ogg; codecs=opus,application/ogg,audio/flac,audio/ape,audio/wavpack,audio/amr,application/pdf,application/x-elf,application/x-mach-binary,application/x-msdownload,application/x-shockwave-flash,application/rtf,application/wasm,font/woff,font/woff2,application/vnd.ms-fontobject,font/ttf,font/otf,font/collection,image/x-icon,video/x-flv,application/postscript,application/eps,application/x-xz,application/x-sqlite3,application/x-nintendo-nes-rom,application/x-google-chrome-extension,application/vnd.ms-cab-compressed,application/x-deb,application/x-unix-archive,application/x-rpm,application/x-compress,application/lzip,application/x-cfb,application/x-mie,application/mxf,video/mp2t,application/x-blender,image/bpg,image/j2c,image/jp2,image/jpx,image/jpm,image/mj2,audio/aiff,application/xml,application/x-mobipocket-ebook,image/heif,image/heif-sequence,image/heic,image/heic-sequence,image/icns,image/ktx,application/dicom,audio/x-musepack,text/calendar,text/vcard,text/vtt,model/gltf-binary,application/vnd.tcpdump.pcap,audio/x-dsf,application/x-ms-shortcut,application/x-ft-apple.alias,audio/x-voc,audio/vnd.dolby.dd-raw,audio/x-m4a,image/apng,image/x-olympus-orf,image/x-sony-arw,image/x-adobe-dng,image/x-nikon-nef,image/x-panasonic-rw2,image/x-fujifilm-raf,video/x-m4v,video/3gpp2,application/x-esri-shape,audio/aac,audio/x-it,audio/x-s3m,audio/x-xm,video/MP1S,video/MP2P,application/vnd.sketchup.skp,image/avif,application/x-lzh-compressed,application/pgp-encrypted,application/x-asar,model/stl,application/vnd.ms-htmlhelp,model/3mf,image/jxl,application/zstd,image/jls,application/vnd.ms-outlook,image/vnd.dwg,application/vnd.apache.parquet,application/java-vm,application/x-arj,application/x-cpio,application/x-ace-compressed,application/avro,application/vnd.iccprofile,application/x-ft-fbx,application/vnd.visio,application/vnd.android.package-archive,application/x-ft-draco,application/x-lz4,application/vnd.openxmlformats-officedocument.presentationml.template,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/vnd.ms-excel.template.macroenabled.12,application/vnd.oasis.opendocument.text-template,application/vnd.oasis.opendocument.spreadsheet-template,application/vnd.oasis.opendocument.presentation-template,application/vnd.oasis.opendocument.graphics,application/vnd.oasis.opendocument.graphics-template,application/vnd.ms-excel.sheet.macroenabled.12,application/vnd.ms-word.document.macroenabled.12,application/vnd.ms-word.template.macroenabled.12,application/vnd.ms-powerpoint.template.macroenabled.12,application/vnd.ms-powerpoint.presentation.macroenabled.12,application/java-archive,application/vnd.rn-realmedia,application/x-spss-sav,application/x-ms-regedit,application/x-ft-windows-registry-hive,application/x-jmp-data,application/vnd.apple.keynote,application/vnd.apple.numbers,application/vnd.apple.pages`.split(`,`),maximumUntrustedSkipSizeInBytes=16*1024*1024;var ParserHardLimitError=class extends Error{};function getSafeBound(e,t,s){if(!Number.isFinite(e)||e<0||e>t)throw new ParserHardLimitError(`${s} has invalid size ${e} (maximum ${t} bytes)`);return e}async function safeIgnore(e,t,{maximumLength:s=maximumUntrustedSkipSizeInBytes,reason:g=`skip`}={}){let S=getSafeBound(t,s,g);await e.ignore(S)}async function safeReadBuffer(e,t,s,{maximumLength:g=t.length,reason:S=`read`}={}){let w=getSafeBound(s?.length??t.length,g,S);return e.readBuffer(t,{...s,length:w})}function checkBytes(e,t,s){s={offset:0,...s};for(let[g,S]of t.entries())if(s.mask){if(S!==(s.mask[g]&e[g+s.offset]))return!1}else if(S!==e[g+s.offset])return!1;return!0}function hasUnknownFileSize(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function hasExceededUnknownSizeScanBudget(e,t,s){return hasUnknownFileSize(e)&&e.position-t>s}const maximumZipEntrySizeInBytes=1024*1024,maximumZipEntryCount=1024,maximumZipBufferedReadSizeInBytes=2**31-1,maximumZipTextEntrySizeInBytes=maximumZipEntrySizeInBytes,recoverableZipErrorMessages=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),recoverableZipErrorMessagePrefixes=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],recoverableZipErrorCodes=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]);async function decompressDeflateRawWithLimit(e,{maximumLength:t=maximumZipEntrySizeInBytes}={}){let s=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(`deflate-raw`)).getReader(),g=[],S=0;try{for(;;){let{done:e,value:w}=await s.read();if(e)break;if(S+=w.length,S>t)throw await s.cancel(),Error(`ZIP entry decompressed data exceeds ${t} bytes`);g.push(w)}}finally{s.releaseLock()}let w=new Uint8Array(S),E=0;for(let e of g)w.set(e,E),E+=e.length;return w}function mergeByteChunks(e,t){let s=new Uint8Array(t),g=0;for(let t of e)s.set(t,g),g+=t.length;return s}function getMaximumZipBufferedReadLength(e){let t=e.fileInfo.size,s=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(s,maximumZipBufferedReadSizeInBytes)}function isRecoverableZipError(e){if(e instanceof EndOfStreamError||e instanceof ParserHardLimitError)return!0;if(!(e instanceof Error))return!1;if(recoverableZipErrorMessages.has(e.message)||recoverableZipErrorCodes.has(e.code))return!0;for(let t of recoverableZipErrorMessagePrefixes)if(e.message.startsWith(t))return!0;return!1}function canReadZipEntryForDetection(e,t=maximumZipEntrySizeInBytes){let s=[e.compressedSize,e.uncompressedSize];for(let e of s)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function createIWorkZipDetectionState(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function updateIWorkZipDetectionStateFromFilename(e,t){t===`Index/Document.iwa`&&(e.hasDocumentEntry=!0),t.startsWith(`Index/MasterSlide`)&&(e.hasMasterSlideEntry=!0),t.startsWith(`Index/Tables/`)&&(e.hasTablesEntry=!0),t===`Index/CalculationEngine.iwa`&&(e.hasCalculationEngineEntry=!0)}function getIWorkFileTypeFromZipEntries(e){if(e.hasDocumentEntry)return e.hasMasterSlideEntry?{ext:`key`,mime:`application/vnd.apple.keynote`}:e.hasTablesEntry?{ext:`numbers`,mime:`application/vnd.apple.numbers`}:{ext:`pages`,mime:`application/vnd.apple.pages`}}function getFileTypeFromMimeType(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function createOpenXmlZipDetectionState(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function updateOpenXmlZipDetectionStateFromFilename(e,t){t.startsWith(`word/`)&&(e.hasWordDirectory=!0),t.startsWith(`ppt/`)&&(e.hasPresentationDirectory=!0),t.startsWith(`xl/`)&&(e.hasSpreadsheetDirectory=!0),t.startsWith(`3D/`)&&t.endsWith(`.model`)&&(e.hasThreeDimensionalModelEntry=!0)}function getOpenXmlFileTypeFromDirectoryNames(e){if(e.hasWordDirectory)return{ext:`docx`,mime:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};if(e.hasPresentationDirectory)return{ext:`pptx`,mime:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};if(e.hasSpreadsheetDirectory)return{ext:`xlsx`,mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};if(e.hasThreeDimensionalModelEntry)return{ext:`3mf`,mime:`model/3mf`}}function getOpenXmlFileTypeFromZipEntries(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry))return getOpenXmlFileTypeFromDirectoryNames(e)}function getOpenXmlMimeTypeFromContentTypesXml(e){let t=e.indexOf(`.main+xml"`);if(t===-1){let t=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;return e.includes(`ContentType="${t}"`)?t:void 0}let s=e.slice(0,t),g=s.lastIndexOf(`"`);return s.slice(g+1)}const zipDataDescriptorSignature=134695760,zipDataDescriptorLengthInBytes=16,zipDataDescriptorOverlapLengthInBytes=zipDataDescriptorLengthInBytes-1;function findZipDataDescriptorOffset(e,t){if(e.length<zipDataDescriptorLengthInBytes)return-1;let s=e.length-zipDataDescriptorLengthInBytes;for(let g=0;g<=s;g++)if(UINT32_LE.get(e,g)===zipDataDescriptorSignature&&UINT32_LE.get(e,g+8)===t+g)return g;return-1}async function readZipDataDescriptorEntryWithLimit(e,{shouldBuffer:t,maximumLength:s=maximumZipEntrySizeInBytes}={}){let{syncBuffer:g}=e,{length:S}=g,w=[],E=0;for(;;){let D=await e.tokenizer.peekBuffer(g,{mayBeLess:!0}),O=findZipDataDescriptorOffset(g.subarray(0,D),E),k=O>=0?0:D===S?Math.min(zipDataDescriptorOverlapLengthInBytes,D-1):0,j=O>=0?O:D-k;if(j===0)break;if(E+=j,E>s)throw Error(`ZIP entry compressed data exceeds ${s} bytes`);if(t){let t=new Uint8Array(j);await e.tokenizer.readBuffer(t),w.push(t)}else await e.tokenizer.ignore(j);if(O>=0)break}if(hasUnknownFileSize(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=E),t)return mergeByteChunks(w,E)}function getRemainingZipScanBudget(e,t){return hasUnknownFileSize(e.tokenizer)?Math.max(0,maximumUntrustedSkipSizeInBytes-(e.tokenizer.position-t)):Math.max(0,maximumZipEntrySizeInBytes-e.knownSizeDescriptorScannedBytes)}async function readZipEntryData(e,t,{shouldBuffer:s,maximumDescriptorLength:g=maximumZipEntrySizeInBytes}={}){if(t.dataDescriptor&&t.compressedSize===0)return readZipDataDescriptorEntryWithLimit(e,{shouldBuffer:s,maximumLength:g});if(!s){await safeIgnore(e.tokenizer,t.compressedSize,{maximumLength:hasUnknownFileSize(e.tokenizer)?maximumZipEntrySizeInBytes:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let S=getMaximumZipBufferedReadLength(e.tokenizer);if(!Number.isFinite(t.compressedSize)||t.compressedSize<0||t.compressedSize>S)throw Error(`ZIP entry compressed data exceeds ${S} bytes`);let w=new Uint8Array(t.compressedSize);return await e.tokenizer.readBuffer(w),w}ZipHandler.prototype.inflate=async function(e,t,s){if(e.compressedMethod===0)return s(t);if(e.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);return s(await decompressDeflateRawWithLimit(t,{maximumLength:maximumZipEntrySizeInBytes}))},ZipHandler.prototype.unzip=async function(e){let t=!1,s=0,g=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(hasExceededUnknownSizeScanBudget(this.tokenizer,g,16777216))throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`);let S=await this.readLocalFileHeader();if(!S)break;if(s++,s>maximumZipEntryCount)throw Error(`ZIP entry count exceeds ${maximumZipEntryCount}`);let w=e(S);t=!!w.stop,await this.tokenizer.ignore(S.extraFieldLength);let E=await readZipEntryData(this,S,{shouldBuffer:!!w.handler,maximumDescriptorLength:Math.min(maximumZipEntrySizeInBytes,getRemainingZipScanBudget(this,g))});if(w.handler&&await this.inflate(S,E,w.handler),S.dataDescriptor){let e=new Uint8Array(zipDataDescriptorLengthInBytes);if(await this.tokenizer.readBuffer(e),UINT32_LE.get(e,0)!==zipDataDescriptorSignature)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(hasExceededUnknownSizeScanBudget(this.tokenizer,g,16777216))throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`)}while(!t)};async function detectZip(e){let t,s=createOpenXmlZipDetectionState(),g=createIWorkZipDetectionState();try{await new ZipHandler(e).unzip(e=>{if(updateOpenXmlZipDetectionStateFromFilename(s,e.filename),updateIWorkZipDetectionStateFromFilename(g,e.filename),g.hasDocumentEntry&&(g.hasMasterSlideEntry||g.hasTablesEntry))return t=getIWorkFileTypeFromZipEntries(g),{stop:!0};let S=e.filename===`[Content_Types].xml`,w=getOpenXmlFileTypeFromZipEntries(s);if(!S&&w)return t=w,{stop:!0};switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return canReadZipEntryForDetection(e,maximumZipTextEntrySizeInBytes)?{async handler(e){t=getFileTypeFromMimeType(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return s.hasContentTypesEntry=!0,canReadZipEntryForDetection(e,maximumZipTextEntrySizeInBytes)?(s.isParsingContentTypes=!0,{async handler(e){let g=getOpenXmlMimeTypeFromContentTypesXml(new TextDecoder(`utf-8`).decode(e));g&&(t=getFileTypeFromMimeType(g)),s.hasParsedContentTypesEntry=!0,s.isParsingContentTypes=!1},stop:!0}):(s.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/v.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}})}catch(e){if(!isRecoverableZipError(e))throw e;s.isParsingContentTypes&&(s.isParsingContentTypes=!1,s.hasUnparseableContentTypes=!0),!t&&e instanceof EndOfStreamError&&!s.hasContentTypesEntry&&(t=getOpenXmlFileTypeFromDirectoryNames(s))}let S=hasUnknownFileSize(e)&&g.hasDocumentEntry&&!g.hasMasterSlideEntry&&!g.hasTablesEntry&&!g.hasCalculationEngineEntry?void 0:getIWorkFileTypeFromZipEntries(g);return t??getOpenXmlFileTypeFromZipEntries(s)??S??{ext:`zip`,mime:`application/zip`}}const maximumEbmlDocumentTypeSizeInBytes=64,maximumEbmlElementPayloadSizeInBytes=1024*1024,maximumEbmlElementCount=256;async function detectEbml(e){async function t(){let t=await e.peekNumber(UINT8),s=128,g=0;for(;(t&s)===0&&s!==0;)++g,s>>=1;let S=new Uint8Array(g+1);return await safeReadBuffer(e,S,void 0,{maximumLength:S.length,reason:`EBML field`}),S}async function s(){let e=await t(),s=await t();s[0]^=128>>s.length-1;let g=Math.min(6,s.length),S=new DataView(e.buffer),w=new DataView(s.buffer,s.length-g,g);return{id:getUintBE(S),len:getUintBE(w)}}async function g(t){let g=0;for(;t>0;){if(g++,g>maximumEbmlElementCount||hasExceededUnknownSizeScanBudget(e,w,16777216))return;let S=e.position,E=await s();if(E.id===17026){if(E.len>maximumEbmlDocumentTypeSizeInBytes)return;let t=getSafeBound(E.len,maximumEbmlDocumentTypeSizeInBytes,`EBML DocType`);return(await e.readToken(new StringType(t))).replaceAll(/\0.*$/gv,``)}if(hasUnknownFileSize(e)&&(!Number.isFinite(E.len)||E.len<0||E.len>maximumEbmlElementPayloadSizeInBytes)||(await safeIgnore(e,E.len,{maximumLength:hasUnknownFileSize(e)?maximumEbmlElementPayloadSizeInBytes:e.fileInfo.size,reason:`EBML payload`}),--t,e.position<=S))return}}let S=await s(),w=e.position;switch(await g(S.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:}}const maximumPngChunkCount=512,maximumPngStreamScanBudgetInBytes=16*1024*1024,maximumPngChunkSizeInBytes=1024*1024;function isPngAncillaryChunk(e){return(e.codePointAt(0)&32)!=0}async function detectPng(e){let t={ext:`png`,mime:`image/png`},s={ext:`apng`,mime:`image/apng`};await e.ignore(8);async function g(){return{length:await e.readToken(INT32_BE),type:await e.readToken(new StringType(4,`latin1`))}}let S=hasUnknownFileSize(e),w=e.position,E=0,D=!1;do{if(E++,E>maximumPngChunkCount||hasExceededUnknownSizeScanBudget(e,w,maximumPngStreamScanBudgetInBytes))break;let O=e.position,k=await g();if(k.length<0)return;if(k.type===`IHDR`){if(k.length!==13)return;D=!0}switch(k.type){case`IDAT`:return t;case`acTL`:return s;default:if(!D&&k.type!==`CgBI`)return;if(S&&k.length>maximumPngChunkSizeInBytes)return D&&isPngAncillaryChunk(k.type)?t:void 0;try{await safeIgnore(e,k.length+4,{maximumLength:S?maximumPngChunkSizeInBytes+4:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!S&&(e instanceof ParserHardLimitError||e instanceof EndOfStreamError))return t;throw e}}if(e.position<=O)break}while(e.position+8<e.fileInfo.size);return t}const maximumAsfHeaderObjectCount=512,maximumAsfHeaderPayloadSizeInBytes=1024*1024;async function detectAsf(e){let t=!1;try{async function s(){let t=new Uint8Array(16);return await safeReadBuffer(e,t,void 0,{maximumLength:t.length,reason:`ASF header GUID`}),{id:t,size:Number(await e.readToken(UINT64_LE))}}await safeIgnore(e,30,{maximumLength:30,reason:`ASF header prelude`});let g=hasUnknownFileSize(e),S=e.position,w=0;for(;e.position+24<e.fileInfo.size&&(w++,!(w>maximumAsfHeaderObjectCount||hasExceededUnknownSizeScanBudget(e,S,16777216)));){let S=e.position,w=await s(),E=w.size-24;if(!Number.isFinite(E)||E<0){t=!0;break}if(checkBytes(w.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(E-=await safeReadBuffer(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),checkBytes(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(checkBytes(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}if(g&&E>maximumAsfHeaderPayloadSizeInBytes){t=!0;break}if(await safeIgnore(e,E,{maximumLength:g?maximumAsfHeaderPayloadSizeInBytes:e.fileInfo.size,reason:`ASF header payload`}),e.position<=S){t=!0;break}}}catch(s){if(s instanceof EndOfStreamError||s instanceof ParserHardLimitError)hasUnknownFileSize(e)&&(t=!0);else throw s}if(!t)return{ext:`asf`,mime:`application/vnd.ms-asf`}}const reasonableDetectionSizeInBytes=4100,maximumMpegOffsetTolerance=reasonableDetectionSizeInBytes-2,maximumNestedGzipDetectionSizeInBytes=maximumUntrustedSkipSizeInBytes,maximumNestedGzipProbeDepth=1,unknownSizeGzipProbeTimeoutInMilliseconds=100,maximumId3HeaderSizeInBytes=maximumUntrustedSkipSizeInBytes,maximumTiffTagCount=512,maximumDetectionReentryCount=256,maximumTiffStreamIfdOffsetInBytes=1024*1024,maximumTiffIfdOffsetInBytes=maximumUntrustedSkipSizeInBytes;function normalizeSampleSize(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):reasonableDetectionSizeInBytes}function normalizeMpegOffsetTolerance(e){return Number.isFinite(e)?Math.max(0,Math.min(maximumMpegOffsetTolerance,Math.trunc(e))):0}function getKnownFileSizeOrMaximum(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function importAtRuntime(e){return import(e)}function toDefaultStream(e){return e.pipeThrough(new TransformStream)}function readWithSignal(e,t){return t===void 0?e.read():(t.throwIfAborted(),Promise.race([e.read(),new Promise((s,g)=>{t.addEventListener(`abort`,()=>{g(t.reason),e.cancel(t.reason).catch(()=>{})},{once:!0})})]))}function createByteLimitedReadableStream(e,t){let s=e.getReader(),g=0,S=!1,w=!1,E=async e=>{S||w||(w=!0,await s.cancel(e))};return new ReadableStream({async pull(e){if(g>=t){e.close(),await E();return}let{done:w,value:D}=await s.read();if(w||!D){S=!0,e.close();return}let O=t-g;if(D.length>O){e.enqueue(D.subarray(0,O)),g+=O,e.close(),await E();return}e.enqueue(D),g+=D.length},async cancel(e){await E(e)}})}async function fileTypeFromBuffer(e,t){return new FileTypeParser(t).fromBuffer(e)}var FileTypeParser=class e{constructor(e){let t=normalizeMpegOffsetTolerance(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return fromWebStream(toDefaultStream(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let s=e.position;for(let t of this.detectors){let g;try{g=await t.detect(e)}catch(e){if(e instanceof EndOfStreamError||e instanceof ParserHardLimitError)return;throw e}if(g)return g;if(s!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(fromBuffer(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=fromBlob(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async fromFile(e){this.options.signal?.throwIfAborted();let[{default:t},{FileTokenizer:s}]=await Promise.all([importAtRuntime(`node:fs/promises`),importAtRuntime(`strtok3`)]),g=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),S=await g.stat();if(!S.isFile()){await g.close();return}let w=new s(g,{...this.getTokenizerOptions(),fileInfo:{path:e,size:S.size}});return this.fromTokenizer(w)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let s=normalizeSampleSize(t?.sampleSize??4100),g,S=!1,w=e.getReader(),E=[],D=0;try{for(;D<s;){let{value:e,done:t}=await readWithSignal(w,this.options.signal);if(t||!e){S=!0;break}E.push(e),D+=e.length}if(!S&&D===s){let{value:e,done:t}=await readWithSignal(w,this.options.signal);t||!e?S=!0:(E.push(e),D+=e.length)}}finally{w.releaseLock()}if(D>0){let e=E.length===1?E[0]:concatUint8Arrays(E);try{g=await this.fromBuffer(e.subarray(0,s))}catch(e){if(!(e instanceof EndOfStreamError))throw e;g=void 0}!S&&g?.ext===`pages`&&(g={ext:`zip`,mime:`application/zip`})}let O=new TransformStream({start(e){for(let t of E)e.enqueue(t)},transform(e,t){t.enqueue(e)}}),k=e.pipeThrough(O);return k.fileType=g,k}async detectGzip(t){if(this.gzipProbeDepth>=maximumNestedGzipProbeDepth)return{ext:`gz`,mime:`application/gzip`};let s=createByteLimitedReadableStream(new GzipHandler(t).inflate(),maximumNestedGzipDetectionSizeInBytes),g=hasUnknownFileSize(t),S,w,E,D;if(g){let t=new AbortController;S=setTimeout(()=>{t.abort(new DOMException(`Operation timed out after ${unknownSizeGzipProbeTimeoutInMilliseconds} ms`,`TimeoutError`))},unknownSizeGzipProbeTimeoutInMilliseconds),w=this.options.signal===void 0?t.signal:AbortSignal.any([this.options.signal,t.signal]),E=new e({...this.options,signal:w}),E.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{D=await(E??this).fromStream(s)}catch(e){if(e?.name===`AbortError`&&w?.reason?.name!==`TimeoutError`)throw e}finally{clearTimeout(S),g||this.gzipProbeDepth--}return D?.ext===`tar`?{ext:`tar.gz`,mime:`application/gzip`}:{ext:`gz`,mime:`application/gzip`}}check(e,t){return checkBytes(this.buffer,e,t)}checkString(e,t){return this.check(stringToBytes(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(reasonableDetectionSizeInBytes),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,hasUnknownFileSize(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.detectionReentryCount>=maximumDetectionReentryCount?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(e));if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return this.detectGzip(e);if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await safeIgnore(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(uint32SyncSafeToken),s=hasUnknownFileSize(e);if(!Number.isFinite(t)||t<0||s&&(t>maximumId3HeaderSizeInBytes||e.position+t>maximumId3HeaderSizeInBytes))return;if(e.position+t>e.fileInfo.size)return s?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await safeIgnore(e,t,{maximumLength:s?maximumId3HeaderSizeInBytes:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}return this.detectionReentryCount>=maximumDetectionReentryCount?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4]))return detectZip(e);if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),checkBytes(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:checkBytes(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:checkBytes(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:checkBytes(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:checkBytes(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:checkBytes(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163]))return detectEbml(e);if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.checkString(`regf`))return{ext:`dat`,mime:`application/x-ft-windows-registry-hive`};if(this.checkString(`$FL2`)||this.checkString(`$FL3`))return{ext:`sav`,mime:`application/x-spss-sav`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(String.raw`{\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190])){let e=UINT32_BE.get(this.buffer,4),t=UINT16_BE.get(this.buffer,6);if(e>0&&e<=30)return{ext:`macho`,mime:`application/x-mach-binary`};if(t>30)return{ext:`class`,mime:`application/java-vm`}}if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/x-ft-draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new StringType(4,`latin1`).get(this.buffer,2);if(/^\d+$/v.test(e)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new StringType(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
|
|
39
39
|
`,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10]))return detectPng(e);if(this.check([65,82,82,79,87,49,0,0]))return{ext:`arrow`,mime:`application/vnd.apache.arrow.file`};if(this.check([103,108,84,70,2,0,0,0]))return{ext:`glb`,mime:`model/gltf-binary`};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:`mov`,mime:`video/quicktime`};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:`orf`,mime:`image/x-olympus-orf`};if(this.checkString(`gimp xcf `))return{ext:`xcf`,mime:`image/x-xcf`};if(this.checkString(`ftyp`,{offset:4})&&this.buffer[8]&96){let e=new StringType(4,`latin1`).get(this.buffer,8).replace(`\0`,` `).trim();switch(e){case`avif`:case`avis`:return{ext:`avif`,mime:`image/avif`};case`mif1`:return{ext:`heic`,mime:`image/heif`};case`msf1`:return{ext:`heic`,mime:`image/heif-sequence`};case`heic`:case`heix`:return{ext:`heic`,mime:`image/heic`};case`hevc`:case`hevx`:return{ext:`heic`,mime:`image/heic-sequence`};case`qt`:return{ext:`mov`,mime:`video/quicktime`};case`M4V`:case`M4VH`:case`M4VP`:return{ext:`m4v`,mime:`video/x-m4v`};case`M4P`:return{ext:`m4p`,mime:`video/mp4`};case`M4B`:return{ext:`m4b`,mime:`audio/mp4`};case`M4A`:return{ext:`m4a`,mime:`audio/x-m4a`};case`F4V`:return{ext:`f4v`,mime:`video/mp4`};case`F4P`:return{ext:`f4p`,mime:`video/mp4`};case`F4A`:return{ext:`f4a`,mime:`audio/mp4`};case`F4B`:return{ext:`f4b`,mime:`audio/mp4`};case`crx`:return{ext:`cr3`,mime:`image/x-canon-cr3`};default:return e.startsWith(`3g`)?e.startsWith(`3g2`)?{ext:`3g2`,mime:`video/3gpp2`}:{ext:`3gp`,mime:`video/3gpp`}:{ext:`mp4`,mime:`video/mp4`}}}if(this.checkString(`REGEDIT4\r
|
|
40
40
|
`))return{ext:`reg`,mime:`application/x-ms-regedit`};if(this.check([82,73,70,70])){if(this.checkString(`WEBP`,{offset:8}))return{ext:`webp`,mime:`image/webp`};if(this.check([65,86,73],{offset:8}))return{ext:`avi`,mime:`video/vnd.avi`};if(this.check([87,65,86,69],{offset:8}))return{ext:`wav`,mime:`audio/wav`};if(this.check([81,76,67,77],{offset:8}))return{ext:`qcp`,mime:`audio/qcelp`}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:`rw2`,mime:`image/x-panasonic-rw2`};if(this.check([48,38,178,117,142,102,207,17,166,217]))return detectAsf(e);if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:`ktx`,mime:`image/ktx`};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:`mie`,mime:`application/x-mie`};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:`shp`,mime:`application/x-esri-shape`};if(this.check([255,79,255,81]))return{ext:`j2c`,mime:`image/j2c`};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new StringType(4,`ascii`))){case`jp2 `:return{ext:`jp2`,mime:`image/jp2`};case`jpx `:return{ext:`jpx`,mime:`image/jpx`};case`jpm `:return{ext:`jpm`,mime:`image/jpm`};case`mjp2`:return{ext:`mj2`,mime:`image/mj2`};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:`jxl`,mime:`image/jxl`};if(this.check([254,255]))return this.checkString(`<?xml `,{offset:2,encoding:`utf-16be`})?{ext:`xml`,mime:`application/xml`}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:`cfb`,mime:`application/x-cfb`};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:`icc`,mime:`application/vnd.iccprofile`};if(this.checkString(`**ACE`,{offset:7})&&this.checkString(`**`,{offset:12}))return{ext:`ace`,mime:`application/x-ace-compressed`};if(this.checkString(`BEGIN:`)){if(this.checkString(`VCARD`,{offset:6}))return{ext:`vcf`,mime:`text/vcard`};if(this.checkString(`VCALENDAR`,{offset:6}))return{ext:`ics`,mime:`text/calendar`}}if(this.checkString(`FUJIFILMCCD-RAW`))return{ext:`raf`,mime:`image/x-fujifilm-raf`};if(this.checkString(`Extended Module:`))return{ext:`xm`,mime:`audio/x-xm`};if(this.checkString(`Creative Voice File`))return{ext:`voc`,mime:`audio/x-voc`};if(this.check([4,0,0,0])&&this.buffer.length>=16){let e=new DataView(this.buffer.buffer).getUint32(12,!0);if(e>12&&this.buffer.length>=e+16)try{let t=new TextDecoder().decode(this.buffer.subarray(16,e+16));if(JSON.parse(t).files)return{ext:`asar`,mime:`application/x-asar`}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:`mxf`,mime:`application/mxf`};if(this.checkString(`SCRM`,{offset:44}))return{ext:`s3m`,mime:`audio/x-s3m`};if(this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:`mts`,mime:`video/mp2t`};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:`mobi`,mime:`application/x-mobipocket-ebook`};if(this.check([68,73,67,77],{offset:128}))return{ext:`dcm`,mime:`application/dicom`};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:`lnk`,mime:`application/x-ms-shortcut`};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:`alias`,mime:`application/x-ft-apple.alias`};if(this.checkString(`Kaydara FBX Binary \0`))return{ext:`fbx`,mime:`application/x-ft-fbx`};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:`eot`,mime:`application/vnd.ms-fontobject`};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:`indd`,mime:`application/x-indesign`};if(this.check([255,255,0,0,7,0,0,0,4,0,0,0,1,0,1,0])||this.check([0,0,255,255,0,0,0,7,0,0,0,4,0,1,0,1]))return{ext:`jmp`,mime:`application/x-jmp-data`};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString(`ustar`,{offset:257})&&(this.checkString(`\0`,{offset:262})||this.checkString(` `,{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&tarHeaderChecksumMatches(this.buffer))return{ext:`tar`,mime:`application/x-tar`};if(this.check([255,254])){let e=`utf-16le`;return this.checkString(`<?xml `,{offset:2,encoding:e})?{ext:`xml`,mime:`application/xml`}:this.check([255,14],{offset:2})&&this.checkString(`SketchUp Model`,{offset:4,encoding:e})?{ext:`skp`,mime:`application/vnd.sketchup.skp`}:this.checkString(`Windows Registry Editor Version 5.00\r
|
|
41
|
-
`,{offset:2,encoding:e})?{ext:`reg`,mime:`application/x-ms-regedit`}:void 0}if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}};detectImprecise=async e=>{this.buffer=new Uint8Array(reasonableDetectionSizeInBytes);let t=getKnownFileSizeOrMaximum(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);switch(await this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);if(!(t>maximumTiffTagCount)&&!(hasUnknownFileSize(this.tokenizer)&&2+t*12>maximumTiffIfdOffsetInBytes))for(let s=0;s<t;++s){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t={ext:`tif`,mime:`image/tiff`},s=(e?UINT16_BE:UINT16_LE).get(this.buffer,2),g=(e?UINT32_BE:UINT32_LE).get(this.buffer,4);if(s===42){if(g>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(g>=8){let t=(e?UINT16_BE:UINT16_LE).get(this.buffer,8),s=(e?UINT16_BE:UINT16_LE).get(this.buffer,10);if(t===28&&s===254||t===31&&s===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(hasUnknownFileSize(this.tokenizer)&&g>maximumTiffStreamIfdOffsetInBytes)return t;let s=hasUnknownFileSize(this.tokenizer)?maximumTiffIfdOffsetInBytes:this.tokenizer.fileInfo.size;try{await safeIgnore(this.tokenizer,g,{maximumLength:s,reason:`TIFF IFD offset`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}let S;try{S=await this.readTiffIFD(e)}catch(e){if(e instanceof EndOfStreamError)return;throw e}return S??t}if(s===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}};const supportedExtensions=new Set(extensions),supportedMimeTypes=new Set(mimeTypes);async function fileTypeFromFile(e,t){return new FileTypeParser(t).fromFile(e)}var util;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function s(e){throw Error()}e.assertNever=s,e.arrayToEnum=e=>{let t={};for(let s of e)t[s]=s;return t},e.getValidEnumValues=t=>{let s=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),g={};for(let e of s)g[e]=t[e];return e.objectValues(g)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.push(s);return t},e.find=(e,t)=>{for(let s of e)if(t(s))return s},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function g(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=g,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(util||={});var objectUtil;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||={});const ZodParsedType=util.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),getParsedType=e=>{switch(typeof e){case`undefined`:return ZodParsedType.undefined;case`string`:return ZodParsedType.string;case`number`:return Number.isNaN(e)?ZodParsedType.nan:ZodParsedType.number;case`boolean`:return ZodParsedType.boolean;case`function`:return ZodParsedType.function;case`bigint`:return ZodParsedType.bigint;case`symbol`:return ZodParsedType.symbol;case`object`:return Array.isArray(e)?ZodParsedType.array:e===null?ZodParsedType.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?ZodParsedType.promise:typeof Map<`u`&&e instanceof Map?ZodParsedType.map:typeof Set<`u`&&e instanceof Set?ZodParsedType.set:typeof Date<`u`&&e instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var ZodError=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},s={_errors:[]},g=e=>{for(let S of e.issues)if(S.code===`invalid_union`)S.unionErrors.map(g);else if(S.code===`invalid_return_type`)g(S.returnTypeError);else if(S.code===`invalid_arguments`)g(S.argumentsError);else if(S.path.length===0)s._errors.push(t(S));else{let e=s,g=0;for(;g<S.path.length;){let s=S.path[g];g===S.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(S))):e[s]=e[s]||{_errors:[]},e=e[s],g++}}};return g(this),s}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),s=[];for(let g of this.issues)if(g.path.length>0){let s=g.path[0];t[s]=t[s]||[],t[s].push(e(g))}else s.push(e(g));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};ZodError.create=e=>new ZodError(e);const errorMap=(e,t)=>{let s;switch(e.code){case ZodIssueCode.invalid_type:s=e.received===ZodParsedType.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case ZodIssueCode.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:s=`Unrecognized key(s) in object: ${util.joinValues(e.keys,`, `)}`;break;case ZodIssueCode.invalid_union:s=`Invalid input`;break;case ZodIssueCode.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${util.joinValues(e.options)}`;break;case ZodIssueCode.invalid_enum_value:s=`Invalid enum value. Expected ${util.joinValues(e.options)}, received '${e.received}'`;break;case ZodIssueCode.invalid_arguments:s=`Invalid function arguments`;break;case ZodIssueCode.invalid_return_type:s=`Invalid function return type`;break;case ZodIssueCode.invalid_date:s=`Invalid date`;break;case ZodIssueCode.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:util.assertNever(e.validation):s=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case ZodIssueCode.too_small:s=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case ZodIssueCode.too_big:s=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case ZodIssueCode.custom:s=`Invalid input`;break;case ZodIssueCode.invalid_intersection_types:s=`Intersection results could not be merged`;break;case ZodIssueCode.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case ZodIssueCode.not_finite:s=`Number must be finite`;break;default:s=t.defaultError,util.assertNever(e)}return{message:s}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=e=>{let{data:t,path:s,errorMaps:g,issueData:S}=e,w=[...s,...S.path||[]],E={...S,path:w};if(S.message!==void 0)return{...S,path:w,message:S.message};let D=``,O=g.filter(e=>!!e).slice().reverse();for(let e of O)D=e(E,{data:t,defaultError:D}).message;return{...S,path:w,message:D}};function addIssueToContext(e,t){let s=getErrorMap(),g=makeIssue({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===errorMap?void 0:errorMap].filter(e=>!!e)});e.common.issues.push(g)}var ParseStatus=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let s=[];for(let g of t){if(g.status===`aborted`)return INVALID;g.status===`dirty`&&e.dirty(),s.push(g.value)}return{status:e.value,value:s}}static async mergeObjectAsync(t,s){let g=[];for(let e of s){let t=await e.key,s=await e.value;g.push({key:t,value:s})}return e.mergeObjectSync(t,g)}static mergeObjectSync(e,t){let s={};for(let g of t){let{key:t,value:S}=g;if(t.status===`aborted`||S.status===`aborted`)return INVALID;t.status===`dirty`&&e.dirty(),S.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(S.value!==void 0||g.alwaysSet)&&(s[t.value]=S.value)}return{status:e.value,value:s}}};const INVALID=Object.freeze({status:`aborted`}),DIRTY=e=>({status:`dirty`,value:e}),OK=e=>({status:`valid`,value:e}),isAborted=e=>e.status===`aborted`,isDirty=e=>e.status===`dirty`,isValid=e=>e.status===`valid`,isAsync=e=>typeof Promise<`u`&&e instanceof Promise;var errorUtil;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(errorUtil||={});var ParseInputLazyPath=class{constructor(e,t,s,g){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=g}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const handleResult=(e,t)=>{if(isValid(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new ZodError(e.common.issues),this._error}}};function processCreateParams(e){if(!e)return{};let{errorMap:t,invalid_type_error:s,required_error:g,description:S}=e;if(t&&(s||g))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:S}:{errorMap:(t,S)=>{let{message:w}=e;return t.code===`invalid_enum_value`?{message:w??S.defaultError}:S.data===void 0?{message:w??g??S.defaultError}:t.code===`invalid_type`?{message:w??s??S.defaultError}:{message:S.defaultError}},description:S}}var ZodType=class{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(isAsync(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){let s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};return handleResult(s,this._parseSync({data:e,path:s.path,parent:s}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this[`~standard`].async)try{let s=this._parseSync({data:e,path:[],parent:t});return isValid(s)?{value:s.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>isValid(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},g=this._parse({data:e,path:s.path,parent:s});return handleResult(s,await(isAsync(g)?g:Promise.resolve(g)))}refine(e,t){let s=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,g)=>{let S=e(t),w=()=>g.addIssue({code:ZodIssueCode.custom,...s(t)});return typeof Promise<`u`&&S instanceof Promise?S.then(e=>e?!0:(w(),!1)):S?!0:(w(),!1)})}refinement(e,t){return this._refinement((s,g)=>e(s)?!0:(g.addIssue(typeof t==`function`?t(s,g):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;let emojiRegex$1;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,dateRegex=RegExp(`^${dateRegexSource}$`);function timeRegexSource(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let s=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${s}`}function timeRegex(e){return RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${dateRegexSource}T${timeRegexSource(e)}`,s=[];return s.push(e.local?`Z?`:`Z`),e.offset&&s.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${s.join(`|`)})`,RegExp(`^${t}$`)}function isValidIP(e,t){return!!((t===`v4`||!t)&&ipv4Regex.test(e)||(t===`v6`||!t)&&ipv6Regex.test(e))}function isValidJWT(e,t){if(!jwtRegex.test(e))return!1;try{let[s]=e.split(`.`);if(!s)return!1;let g=s.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(s.length+(4-s.length%4)%4,`=`),S=JSON.parse(atob(g));return!(typeof S!=`object`||!S||`typ`in S&&S?.typ!==`JWT`||!S.alg||t&&S.alg!==t)}catch{return!1}}function isValidCidr(e,t){return!!((t===`v4`||!t)&&ipv4CidrRegex.test(e)||(t===`v6`||!t)&&ipv6CidrRegex.test(e))}var ZodString=class e extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:t.parsedType}),INVALID}let t=new ParseStatus,s;for(let g of this._def.checks)if(g.kind===`min`)e.data.length<g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.value,type:`string`,inclusive:!0,exact:!1,message:g.message}),t.dirty());else if(g.kind===`max`)e.data.length>g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.value,type:`string`,inclusive:!0,exact:!1,message:g.message}),t.dirty());else if(g.kind===`length`){let S=e.data.length>g.value,w=e.data.length<g.value;(S||w)&&(s=this._getOrReturnCtx(e,s),S?addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.value,type:`string`,inclusive:!0,exact:!0,message:g.message}):w&&addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.value,type:`string`,inclusive:!0,exact:!0,message:g.message}),t.dirty())}else if(g.kind===`email`)emailRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`email`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`emoji`)emojiRegex$1||=new RegExp(_emojiRegex,`u`),emojiRegex$1.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`emoji`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`uuid`)uuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`uuid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`nanoid`)nanoidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`nanoid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`cuid`)cuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cuid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`cuid2`)cuid2Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cuid2`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`ulid`)ulidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`ulid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`url`)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`url`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()}else g.kind===`regex`?(g.regex.lastIndex=0,g.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`regex`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty())):g.kind===`trim`?e.data=e.data.trim():g.kind===`includes`?e.data.includes(g.value,g.position)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{includes:g.value,position:g.position},message:g.message}),t.dirty()):g.kind===`toLowerCase`?e.data=e.data.toLowerCase():g.kind===`toUpperCase`?e.data=e.data.toUpperCase():g.kind===`startsWith`?e.data.startsWith(g.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{startsWith:g.value},message:g.message}),t.dirty()):g.kind===`endsWith`?e.data.endsWith(g.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{endsWith:g.value},message:g.message}),t.dirty()):g.kind===`datetime`?datetimeRegex(g).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`datetime`,message:g.message}),t.dirty()):g.kind===`date`?dateRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`date`,message:g.message}),t.dirty()):g.kind===`time`?timeRegex(g).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`time`,message:g.message}),t.dirty()):g.kind===`duration`?durationRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`duration`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`ip`?isValidIP(e.data,g.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`ip`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`jwt`?isValidJWT(e.data,g.alg)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`jwt`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`cidr`?isValidCidr(e.data,g.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cidr`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`base64`?base64Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`base64`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`base64url`?base64urlRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`base64url`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):util.assertNever(g);return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement(t=>e.test(t),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...errorUtil.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodString.create=e=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:e?.coerce??!1,...processCreateParams(e)});function floatSafeRemainder(e,t){let s=(e.toString().split(`.`)[1]||``).length,g=(t.toString().split(`.`)[1]||``).length,S=s>g?s:g;return Number.parseInt(e.toFixed(S).replace(`.`,``))%Number.parseInt(t.toFixed(S).replace(`.`,``))/10**S}var ZodNumber=class e extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:t.parsedType}),INVALID}let t,s=new ParseStatus;for(let g of this._def.checks)g.kind===`int`?util.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:`integer`,received:`float`,message:g.message}),s.dirty()):g.kind===`min`?(g.inclusive?e.data<g.value:e.data<=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:g.value,type:`number`,inclusive:g.inclusive,exact:!1,message:g.message}),s.dirty()):g.kind===`max`?(g.inclusive?e.data>g.value:e.data>=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:g.value,type:`number`,inclusive:g.inclusive,exact:!1,message:g.message}),s.dirty()):g.kind===`multipleOf`?floatSafeRemainder(e.data,g.value)!==0&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:g.value,message:g.message}),s.dirty()):g.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_finite,message:g.message}),s.dirty()):util.assertNever(g);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(t,s,g,S){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:g,message:errorUtil.toString(S)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:errorUtil.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let s of this._def.checks)if(s.kind===`finite`||s.kind===`int`||s.kind===`multipleOf`)return!0;else s.kind===`min`?(t===null||s.value>t)&&(t=s.value):s.kind===`max`&&(e===null||s.value<e)&&(e=s.value);return Number.isFinite(t)&&Number.isFinite(e)}};ZodNumber.create=e=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodBigInt=class e extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let t,s=new ParseStatus;for(let g of this._def.checks)g.kind===`min`?(g.inclusive?e.data<g.value:e.data<=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,type:`bigint`,minimum:g.value,inclusive:g.inclusive,message:g.message}),s.dirty()):g.kind===`max`?(g.inclusive?e.data>g.value:e.data>=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,type:`bigint`,maximum:g.value,inclusive:g.inclusive,message:g.message}),s.dirty()):g.kind===`multipleOf`?e.data%g.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:g.value,message:g.message}),s.dirty()):util.assertNever(g);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(t,s,g,S){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:g,message:errorUtil.toString(S)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodBigInt.create=e=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:e?.coerce??!1,...processCreateParams(e)});var ZodBoolean=class extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:t.parsedType}),INVALID}return OK(e.data)}};ZodBoolean.create=e=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodDate=class e extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:t.parsedType}),INVALID}if(Number.isNaN(e.data.getTime()))return addIssueToContext(this._getOrReturnCtx(e),{code:ZodIssueCode.invalid_date}),INVALID;let t=new ParseStatus,s;for(let g of this._def.checks)g.kind===`min`?e.data.getTime()<g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,message:g.message,inclusive:!0,exact:!1,minimum:g.value,type:`date`}),t.dirty()):g.kind===`max`?e.data.getTime()>g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,message:g.message,inclusive:!0,exact:!1,maximum:g.value,type:`date`}),t.dirty()):util.assertNever(g);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};ZodDate.create=e=>new ZodDate({checks:[],coerce:e?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(e)});var ZodSymbol=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:t.parsedType}),INVALID}return OK(e.data)}};ZodSymbol.create=e=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(e)});var ZodUndefined=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:t.parsedType}),INVALID}return OK(e.data)}};ZodUndefined.create=e=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(e)});var ZodNull=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:t.parsedType}),INVALID}return OK(e.data)}};ZodNull.create=e=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(e)});var ZodAny=class extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}};ZodAny.create=e=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(e)});var ZodUnknown=class extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}};ZodUnknown.create=e=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(e)});var ZodNever=class extends ZodType{_parse(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}};ZodNever.create=e=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(e)});var ZodVoid=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:t.parsedType}),INVALID}return OK(e.data)}};ZodVoid.create=e=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(e)});var ZodArray=class e extends ZodType{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),g=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(g.exactLength!==null){let e=t.data.length>g.exactLength.value,S=t.data.length<g.exactLength.value;(e||S)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:S?g.exactLength.value:void 0,maximum:e?g.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:g.exactLength.message}),s.dirty())}if(g.minLength!==null&&t.data.length<g.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:g.minLength.value,type:`array`,inclusive:!0,exact:!1,message:g.minLength.message}),s.dirty()),g.maxLength!==null&&t.data.length>g.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:g.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:g.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((e,s)=>g.type._parseAsync(new ParseInputLazyPath(t,e,t.path,s)))).then(e=>ParseStatus.mergeArray(s,e));let S=[...t.data].map((e,s)=>g.type._parseSync(new ParseInputLazyPath(t,e,t.path,s)));return ParseStatus.mergeArray(s,S)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:errorUtil.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:errorUtil.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:errorUtil.toString(s)}})}nonempty(e){return this.min(1,e)}};ZodArray.create=(e,t)=>new ZodArray({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(t)});function deepPartialify(e){if(e instanceof ZodObject){let t={};for(let s in e.shape){let g=e.shape[s];t[s]=ZodOptional.create(deepPartialify(g))}return new ZodObject({...e._def,shape:()=>t})}else if(e instanceof ZodArray)return new ZodArray({...e._def,type:deepPartialify(e.element)});else if(e instanceof ZodOptional)return ZodOptional.create(deepPartialify(e.unwrap()));else if(e instanceof ZodNullable)return ZodNullable.create(deepPartialify(e.unwrap()));else if(e instanceof ZodTuple)return ZodTuple.create(e.items.map(e=>deepPartialify(e)));else return e}var ZodObject=class e extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:util.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID}let{status:t,ctx:s}=this._processInputParams(e),{shape:g,keys:S}=this._getCached(),w=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys===`strip`))for(let e in s.data)S.includes(e)||w.push(e);let E=[];for(let e of S){let t=g[e],S=s.data[e];E.push({key:{status:`valid`,value:e},value:t._parse(new ParseInputLazyPath(s,S,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof ZodNever){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of w)E.push({key:{status:`valid`,value:e},value:{status:`valid`,value:s.data[e]}});else if(e===`strict`)w.length>0&&(addIssueToContext(s,{code:ZodIssueCode.unrecognized_keys,keys:w}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of w){let g=s.data[t];E.push({key:{status:`valid`,value:t},value:e._parse(new ParseInputLazyPath(s,g,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of E){let s=await t.key,g=await t.value;e.push({key:s,value:g,alwaysSet:t.alwaysSet})}return e}).then(e=>ParseStatus.mergeObjectSync(t,e)):ParseStatus.mergeObjectSync(t,E)}get shape(){return this._def.shape()}strict(t){return errorUtil.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,s)=>{let g=this._def.errorMap?.(e,s).message??s.defaultError;return e.code===`unrecognized_keys`?{message:errorUtil.errToObj(t).message??g}:{message:g}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let s={};for(let e of util.objectKeys(t))t[e]&&this.shape[e]&&(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}omit(t){let s={};for(let e of util.objectKeys(this.shape))t[e]||(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}deepPartial(){return deepPartialify(this)}partial(t){let s={};for(let e of util.objectKeys(this.shape)){let g=this.shape[e];t&&!t[e]?s[e]=g:s[e]=g.optional()}return new e({...this._def,shape:()=>s})}required(t){let s={};for(let e of util.objectKeys(this.shape))if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof ZodOptional;)t=t._def.innerType;s[e]=t}return new e({...this._def,shape:()=>s})}keyof(){return createZodEnum(util.objectKeys(this.shape))}};ZodObject.create=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.strictCreate=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strict`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.lazycreate=(e,t)=>new ZodObject({shape:e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)});var ZodUnion=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=this._def.options;function g(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let s of e)if(s.result.status===`dirty`)return t.common.issues.push(...s.ctx.common.issues),s.result;let s=e.map(e=>new ZodError(e.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:s}),INVALID}if(t.common.async)return Promise.all(s.map(async e=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(g);{let e,g=[];for(let S of s){let s={...t,common:{...t.common,issues:[]},parent:null},w=S._parseSync({data:t.data,path:t.path,parent:s});if(w.status===`valid`)return w;w.status===`dirty`&&!e&&(e={result:w,ctx:s}),s.common.issues.length&&g.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let S=g.map(e=>new ZodError(e));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:S}),INVALID}}get options(){return this._def.options}};ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(t)});const getDiscriminator=e=>e instanceof ZodLazy?getDiscriminator(e.schema):e instanceof ZodEffects?getDiscriminator(e.innerType()):e instanceof ZodLiteral?[e.value]:e instanceof ZodEnum?e.options:e instanceof ZodNativeEnum?util.objectValues(e.enum):e instanceof ZodDefault?getDiscriminator(e._def.innerType):e instanceof ZodUndefined?[void 0]:e instanceof ZodNull?[null]:e instanceof ZodOptional?[void 0,...getDiscriminator(e.unwrap())]:e instanceof ZodNullable?[null,...getDiscriminator(e.unwrap())]:e instanceof ZodBranded||e instanceof ZodReadonly?getDiscriminator(e.unwrap()):e instanceof ZodCatch?getDiscriminator(e._def.innerType):[];var ZodDiscriminatedUnion=class e extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.object)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID;let s=this.discriminator,g=t.data[s],S=this.optionsMap.get(g);return S?t.common.async?S._parseAsync({data:t.data,path:t.path,parent:t}):S._parseSync({data:t.data,path:t.path,parent:t}):(addIssueToContext(t,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,s,g){let S=new Map;for(let e of s){let s=getDiscriminator(e.shape[t]);if(!s.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let g of s){if(S.has(g))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(g)}`);S.set(g,e)}}return new e({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:S,...processCreateParams(g)})}};function mergeValues(e,t){let s=getParsedType(e),g=getParsedType(t);if(e===t)return{valid:!0,data:e};if(s===ZodParsedType.object&&g===ZodParsedType.object){let s=util.objectKeys(t),g=util.objectKeys(e).filter(e=>s.indexOf(e)!==-1),S={...e,...t};for(let s of g){let g=mergeValues(e[s],t[s]);if(!g.valid)return{valid:!1};S[s]=g.data}return{valid:!0,data:S}}else if(s===ZodParsedType.array&&g===ZodParsedType.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let g=0;g<e.length;g++){let S=e[g],w=t[g],E=mergeValues(S,w);if(!E.valid)return{valid:!1};s.push(E.data)}return{valid:!0,data:s}}else if(s===ZodParsedType.date&&g===ZodParsedType.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var ZodIntersection=class extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),g=(e,g)=>{if(isAborted(e)||isAborted(g))return INVALID;let S=mergeValues(e.value,g.value);return S.valid?((isDirty(e)||isDirty(g))&&t.dirty(),{status:t.value,value:S.data}):(addIssueToContext(s,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([e,t])=>g(e,t)):g(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};ZodIntersection.create=(e,t,s)=>new ZodIntersection({left:e,right:t,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(s)});var ZodTuple=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.array)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:s.parsedType}),INVALID;if(s.data.length<this._def.items.length)return addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),INVALID;!this._def.rest&&s.data.length>this._def.items.length&&(addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let g=[...s.data].map((e,t)=>{let g=this._def.items[t]||this._def.rest;return g?g._parse(new ParseInputLazyPath(s,e,s.path,t)):null}).filter(e=>!!e);return s.common.async?Promise.all(g).then(e=>ParseStatus.mergeArray(t,e)):ParseStatus.mergeArray(t,g)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ZodTuple.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new ZodTuple({items:e,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(t)})};var ZodRecord=class e extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.object)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:s.parsedType}),INVALID;let g=[],S=this._def.keyType,w=this._def.valueType;for(let e in s.data)g.push({key:S._parse(new ParseInputLazyPath(s,e,s.path,e)),value:w._parse(new ParseInputLazyPath(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?ParseStatus.mergeObjectAsync(t,g):ParseStatus.mergeObjectSync(t,g)}get element(){return this._def.valueType}static create(t,s,g){return s instanceof ZodType?new e({keyType:t,valueType:s,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(g)}):new e({keyType:ZodString.create(),valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(s)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.map)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:s.parsedType}),INVALID;let g=this._def.keyType,S=this._def.valueType,w=[...s.data.entries()].map(([e,t],w)=>({key:g._parse(new ParseInputLazyPath(s,e,s.path,[w,`key`])),value:S._parse(new ParseInputLazyPath(s,t,s.path,[w,`value`]))}));if(s.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let s of w){let g=await s.key,S=await s.value;if(g.status===`aborted`||S.status===`aborted`)return INVALID;(g.status===`dirty`||S.status===`dirty`)&&t.dirty(),e.set(g.value,S.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let s of w){let g=s.key,S=s.value;if(g.status===`aborted`||S.status===`aborted`)return INVALID;(g.status===`dirty`||S.status===`dirty`)&&t.dirty(),e.set(g.value,S.value)}return{status:t.value,value:e}}}};ZodMap.create=(e,t,s)=>new ZodMap({valueType:t,keyType:e,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(s)});var ZodSet=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.set)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:s.parsedType}),INVALID;let g=this._def;g.minSize!==null&&s.data.size<g.minSize.value&&(addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.minSize.value,type:`set`,inclusive:!0,exact:!1,message:g.minSize.message}),t.dirty()),g.maxSize!==null&&s.data.size>g.maxSize.value&&(addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:g.maxSize.message}),t.dirty());let S=this._def.valueType;function w(e){let s=new Set;for(let g of e){if(g.status===`aborted`)return INVALID;g.status===`dirty`&&t.dirty(),s.add(g.value)}return{status:t.value,value:s}}let E=[...s.data.values()].map((e,t)=>S._parse(new ParseInputLazyPath(s,e,s.path,t)));return s.common.async?Promise.all(E).then(e=>w(e)):w(E)}min(t,s){return new e({...this._def,minSize:{value:t,message:errorUtil.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:errorUtil.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ZodSet.create=(e,t)=>new ZodSet({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(t)});var ZodFunction=class e extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.function)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:t.parsedType}),INVALID;function s(e,s){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:s}})}function g(e,s){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:s}})}let S={errorMap:t.common.contextualErrorMap},w=t.data;if(this._def.returns instanceof ZodPromise){let e=this;return OK(async function(...t){let E=new ZodError([]),D=await e._def.args.parseAsync(t,S).catch(e=>{throw E.addIssue(s(t,e)),E}),O=await Reflect.apply(w,this,D);return await e._def.returns._def.type.parseAsync(O,S).catch(e=>{throw E.addIssue(g(O,e)),E})})}else{let e=this;return OK(function(...t){let E=e._def.args.safeParse(t,S);if(!E.success)throw new ZodError([s(t,E.error)]);let D=Reflect.apply(w,this,E.data),O=e._def.returns.safeParse(D,S);if(!O.success)throw new ZodError([g(D,O.error)]);return O.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ZodTuple.create(t).rest(ZodUnknown.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,s,g){return new e({args:t||ZodTuple.create([]).rest(ZodUnknown.create()),returns:s||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(g)})}},ZodLazy=class extends ZodType{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ZodLazy.create=(e,t)=>new ZodLazy({getter:e,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(t)});var ZodLiteral=class extends ZodType{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(t)});function createZodEnum(e,t){return new ZodEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(t)})}var ZodEnum=class e extends ZodType{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),s=this._def.values;return addIssueToContext(t,{expected:util.joinValues(s),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:s}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,s=this._def){return e.create(t,{...this._def,...s})}exclude(t,s=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...s})}};ZodEnum.create=createZodEnum;var ZodNativeEnum=class extends ZodType{_parse(e){let t=util.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==ZodParsedType.string&&s.parsedType!==ZodParsedType.number){let e=util.objectValues(t);return addIssueToContext(s,{expected:util.joinValues(e),received:s.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(util.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=util.objectValues(t);return addIssueToContext(s,{received:s.data,code:ZodIssueCode.invalid_enum_value,options:e}),INVALID}return OK(e.data)}get enum(){return this._def.values}};ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(t)});var ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==ZodParsedType.promise&&t.common.async===!1?(addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID):OK((t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(t)});var ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),g=this._def.effect||null,S={addIssue:e=>{addIssueToContext(s,e),e.fatal?t.abort():t.dirty()},get path(){return s.path}};if(S.addIssue=S.addIssue.bind(S),g.type===`preprocess`){let e=g.transform(s.data,S);if(s.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return INVALID;let g=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return g.status===`aborted`?INVALID:g.status===`dirty`||t.value===`dirty`?DIRTY(g.value):g});{if(t.value===`aborted`)return INVALID;let g=this._def.schema._parseSync({data:e,path:s.path,parent:s});return g.status===`aborted`?INVALID:g.status===`dirty`||t.value===`dirty`?DIRTY(g.value):g}}if(g.type===`refinement`){let e=e=>{let t=g.refinement(e,S);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(s.common.async===!1){let g=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return g.status===`aborted`?INVALID:(g.status===`dirty`&&t.dirty(),e(g.value),{status:t.value,value:g.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(s=>s.status===`aborted`?INVALID:(s.status===`dirty`&&t.dirty(),e(s.value).then(()=>({status:t.value,value:s.value}))))}if(g.type===`transform`)if(s.common.async===!1){let e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!isValid(e))return INVALID;let w=g.transform(e.value,S);if(w instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:w}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(e=>isValid(e)?Promise.resolve(g.transform(e.value,S)).then(e=>({status:t.value,value:e})):INVALID);util.assertNever(g)}};ZodEffects.create=(e,t,s)=>new ZodEffects({schema:e,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:t,...processCreateParams(s)}),ZodEffects.createWithPreprocess=(e,t,s)=>new ZodEffects({schema:t,effect:{type:`preprocess`,transform:e},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(s)});var ZodOptional=class extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(t)});var ZodNullable=class extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(t)});var ZodDefault=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===ZodParsedType.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...processCreateParams(t)});var ZodCatch=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},g=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return isAsync(g)?g.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new ZodError(s.common.issues)},input:s.data})})):{status:`valid`,value:g.status===`valid`?g.value:this._def.catchValue({get error(){return new ZodError(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...processCreateParams(t)});var ZodNaN=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:t.parsedType}),INVALID}return{status:`valid`,value:e.data}}};ZodNaN.create=e=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(e)});var ZodBranded=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},ZodPipeline=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})();{let e=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:s.path,parent:s})}}static create(t,s){return new e({in:t,out:s,typeName:ZodFirstPartyTypeKind.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(e){let t=this._def.innerType._parse(e),s=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then(e=>s(e)):s(t)}unwrap(){return this._def.innerType}};ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)});const late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(ZodFirstPartyTypeKind||={});const stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ZodMiniType=$constructor(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);$ZodType.init(e,t),e.def=t,e.type=t.type,e.parse=(t,s)=>parse$1(e,t,s,{callee:e.parse}),e.safeParse=(t,s)=>safeParse$1(e,t,s),e.parseAsync=async(t,s)=>parseAsync(e,t,s,{callee:e.parseAsync}),e.safeParseAsync=async(t,s)=>safeParseAsync$1(e,t,s),e.check=(...s)=>e.clone({...t,checks:[...t.checks??[],...s.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,s)=>clone(e,t,s),e.brand=()=>e,e.register=((t,s)=>(t.add(e,s),e)),e.apply=t=>t(e)}),ZodMiniObject=$constructor(`ZodMiniObject`,(e,t)=>{$ZodObject.init(e,t),ZodMiniType.init(e,t),defineLazy(e,`shape`,()=>t.shape)});function object(e,t){return new ZodMiniObject({type:`object`,shape:e??{},...normalizeParams(t)})}const describe=describe$1,meta=meta$1;function isZ4Schema(e){return!!e._zod}function objectFromShape(e){let t=Object.values(e);if(t.length===0)return object({});let s=t.every(isZ4Schema),g=t.every(e=>!isZ4Schema(e));if(s)return object(e);if(g)return objectType(e);throw Error(`Mixed Zod versions detected in object shape.`)}function safeParse(e,t){return isZ4Schema(e)?safeParse$1(e,t):e.safeParse(t)}async function safeParseAsync(e,t){return isZ4Schema(e)?await safeParseAsync$1(e,t):await e.safeParseAsync(t)}function getObjectShape(e){if(!e)return;let t;if(t=isZ4Schema(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function normalizeObjectSchema(e){if(e){if(typeof e==`object`){let t=e,s=e;if(!t._def&&!s._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return objectFromShape(e)}}if(isZ4Schema(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function getParseErrorMessage(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function getSchemaDescription(e){return e.description}function isSchemaOptional(e){if(isZ4Schema(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function getLiteralValue(e){if(isZ4Schema(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let s=e.value;if(s!==void 0)return s}const LATEST_PROTOCOL_VERSION=`2025-11-25`,DEFAULT_NEGOTIATED_PROTOCOL_VERSION=`2025-03-26`,SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],RELATED_TASK_META_KEY=`io.modelcontextprotocol/related-task`,JSONRPC_VERSION=`2.0`,AssertObjectSchema=custom(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),ProgressTokenSchema=union([string(),number().int()]),CursorSchema=string(),TaskCreationParamsSchema=looseObject({ttl:number().optional(),pollInterval:number().optional()}),TaskMetadataSchema=object$1({ttl:number().optional()}),RelatedTaskMetadataSchema=object$1({taskId:string()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=e=>TaskAugmentedRequestParamsSchema.safeParse(e).success,RequestSchema=object$1({method:string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),NotificationSchema=object$1({method:string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union([string(),number().int()]),JSONRPCRequestSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=e=>JSONRPCRequestSchema.safeParse(e).success,JSONRPCNotificationSchema=object$1({jsonrpc:literal(`2.0`),...NotificationSchema.shape}).strict(),isJSONRPCNotification=e=>JSONRPCNotificationSchema.safeParse(e).success,JSONRPCResultResponseSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=e=>JSONRPCResultResponseSchema.safeParse(e).success;var ErrorCode;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(ErrorCode||={});const JSONRPCErrorResponseSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema.optional(),error:object$1({code:number().int(),message:string(),data:unknown().optional()})}).strict(),isJSONRPCErrorResponse=e=>JSONRPCErrorResponseSchema.safeParse(e).success,JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal(`notifications/cancelled`),params:CancelledNotificationParamsSchema}),IconSchema=object$1({src:string(),mimeType:string().optional(),sizes:array(string()).optional(),theme:_enum([`light`,`dark`]).optional()}),IconsSchema=object$1({icons:array(IconSchema).optional()}),BaseMetadataSchema=object$1({name:string(),title:string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string(),websiteUrl:string().optional(),description:string().optional()}),FormElicitationCapabilitySchema=intersection(object$1({applyDefaults:boolean().optional()}),record(string(),unknown())),ElicitationCapabilitySchema=preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,intersection(object$1({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),record(string(),unknown()).optional())),ClientTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({tools:looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object$1({experimental:record(string(),AssertObjectSchema).optional(),sampling:object$1({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object$1({listChanged:boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string(),AssertObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal(`initialize`),params:InitializeRequestParamsSchema}),isInitializeRequest=e=>InitializeRequestSchema.safeParse(e).success,ServerCapabilitiesSchema=object$1({experimental:record(string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object$1({listChanged:boolean().optional()}).optional(),resources:object$1({subscribe:boolean().optional(),listChanged:boolean().optional()}).optional(),tools:object$1({listChanged:boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string(),AssertObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/initialized`),params:NotificationsParamsSchema.optional()}),isInitializedNotification=e=>InitializedNotificationSchema.safeParse(e).success,PingRequestSchema=RequestSchema.extend({method:literal(`ping`),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object$1({progress:number(),total:optional(number()),message:optional(string())}),ProgressNotificationParamsSchema=object$1({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal(`notifications/progress`),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=_enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),TaskSchema=object$1({taskId:string(),status:TaskStatusSchema,ttl:union([number(),_null()]),createdAt:string(),lastUpdatedAt:string(),pollInterval:optional(number()),statusMessage:optional(string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal(`notifications/tasks/status`),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal(`tasks/get`),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal(`tasks/result`),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal(`tasks/list`)}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal(`tasks/cancel`),params:BaseRequestParamsSchema.extend({taskId:string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=object$1({uri:string(),mimeType:optional(string()),_meta:record(string(),unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string()}),Base64Schema=string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum([`user`,`assistant`]),AnnotationsSchema=object$1({audience:array(RoleSchema).optional(),priority:number().min(0).max(1).optional(),lastModified:datetime({offset:!0}).optional()}),ResourceSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string(),description:optional(string()),mimeType:optional(string()),size:optional(number()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string(),description:optional(string()),mimeType:optional(string()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal(`resources/list`)}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal(`resources/templates/list`)}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal(`resources/read`),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/list_changed`),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal(`resources/subscribe`),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal(`resources/unsubscribe`),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/updated`),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object$1({name:string(),description:optional(string()),required:optional(boolean())}),PromptSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal(`prompts/list`)}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string(),arguments:record(string(),string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal(`prompts/get`),params:GetPromptRequestParamsSchema}),TextContentSchema=object$1({type:literal(`text`),text:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ImageContentSchema=object$1({type:literal(`image`),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),AudioContentSchema=object$1({type:literal(`audio`),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ToolUseContentSchema=object$1({type:literal(`tool_use`),name:string(),id:string(),input:record(string(),unknown()),_meta:record(string(),unknown()).optional()}),EmbeddedResourceSchema=object$1({type:literal(`resource`),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal(`resource_link`)}),ContentBlockSchema=union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object$1({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/prompts/list_changed`),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object$1({title:string().optional(),readOnlyHint:boolean().optional(),destructiveHint:boolean().optional(),idempotentHint:boolean().optional(),openWorldHint:boolean().optional()}),ToolExecutionSchema=object$1({taskSupport:_enum([`required`,`optional`,`forbidden`]).optional()}),ToolSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string().optional(),inputSchema:object$1({type:literal(`object`),properties:record(string(),AssertObjectSchema).optional(),required:array(string()).optional()}).catchall(unknown()),outputSchema:object$1({type:literal(`object`),properties:record(string(),AssertObjectSchema).optional(),required:array(string()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string(),unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal(`tools/list`)}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:record(string(),unknown()).optional(),isError:boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string(),arguments:record(string(),unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal(`tools/call`),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/tools/list_changed`),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object$1({autoRefresh:boolean().default(!0),debounceMs:number().int().nonnegative().default(300)}),LoggingLevelSchema=_enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal(`logging/setLevel`),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string().optional(),data:unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal(`notifications/message`),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object$1({name:string().optional()}),ModelPreferencesSchema=object$1({hints:array(ModelHintSchema).optional(),costPriority:number().min(0).max(1).optional(),speedPriority:number().min(0).max(1).optional(),intelligencePriority:number().min(0).max(1).optional()}),ToolChoiceSchema=object$1({mode:_enum([`auto`,`required`,`none`]).optional()}),ToolResultContentSchema=object$1({type:literal(`tool_result`),toolUseId:string().describe(`The unique identifier for the corresponding tool call.`),content:array(ContentBlockSchema).default([]),structuredContent:object$1({}).loose().optional(),isError:boolean().optional(),_meta:record(string(),unknown()).optional()}),SamplingContentSchema=discriminatedUnion(`type`,[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion(`type`,[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object$1({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string(),unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string().optional(),includeContext:_enum([`none`,`thisServer`,`allServers`]).optional(),temperature:number().optional(),maxTokens:number().int(),stopSequences:array(string()).optional(),metadata:AssertObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal(`sampling/createMessage`),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`]).or(string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(string())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object$1({type:literal(`boolean`),title:string().optional(),description:string().optional(),default:boolean().optional()}),StringSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),minLength:number().optional(),maxLength:number().optional(),format:_enum([`email`,`uri`,`date`,`date-time`]).optional(),default:string().optional()}),NumberSchemaSchema=object$1({type:_enum([`number`,`integer`]),title:string().optional(),description:string().optional(),minimum:number().optional(),maximum:number().optional(),default:number().optional()}),UntitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),enum:array(string()),default:string().optional()}),TitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),oneOf:array(object$1({const:string(),title:string()})),default:string().optional()}),LegacyTitledEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),enum:array(string()),enumNames:array(string()).optional(),default:string().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string().optional(),description:string().optional(),minItems:number().optional(),maxItems:number().optional(),items:object$1({type:literal(`string`),enum:array(string())}),default:array(string()).optional()}),TitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string().optional(),description:string().optional(),minItems:number().optional(),maxItems:number().optional(),items:object$1({anyOf:array(object$1({const:string(),title:string()}))}),default:array(string()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`form`).optional(),message:string(),requestedSchema:object$1({type:literal(`object`),properties:record(string(),PrimitiveSchemaDefinitionSchema),required:array(string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`url`),message:string(),elicitationId:string(),url:string().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal(`elicitation/create`),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal(`notifications/elicitation/complete`),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum([`accept`,`decline`,`cancel`]),content:preprocess(e=>e===null?void 0:e,record(string(),union([string(),number(),boolean(),array(string())])).optional())}),ResourceTemplateReferenceSchema=object$1({type:literal(`ref/resource`),uri:string()}),PromptReferenceSchema=object$1({type:literal(`ref/prompt`),name:string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object$1({name:string(),value:string()}),context:object$1({arguments:record(string(),string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal(`completion/complete`),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function assertCompleteRequestResourceTemplate(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string()).max(100),total:optional(number().int()),hasMore:optional(boolean())})}),RootSchema=object$1({uri:string().startsWith(`file://`),name:string().optional(),_meta:record(string(),unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal(`roots/list`),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/roots/list_changed`),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]);var McpError=class e extends Error{constructor(e,t,s){super(`MCP error ${e}: ${t}`),this.code=e,this.data=s,this.name=`McpError`}static fromError(t,s,g){if(t===ErrorCode.UrlElicitationRequired&&g){let e=g;if(e.elicitations)return new UrlElicitationRequiredError(e.elicitations,s)}return new e(t,s,g)}},UrlElicitationRequiredError=class extends McpError{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(ErrorCode.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(e){return e===`completed`||e===`failed`||e===`cancelled`}const ignoreOverride=Symbol(`Let zodToJsonSchema decide on which parser to use`),defaultOptions={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},getDefaultOptions=e=>typeof e==`string`?{...defaultOptions,name:e}:{...defaultOptions,...e},getRefs=e=>{let t=getDefaultOptions(e),s=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:s,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function addErrorMessage(e,t,s,g){g?.errorMessages&&s&&(e.errorMessage={...e.errorMessage,[t]:s})}function setResponseValueAndErrors(e,t,s,g,S){e[t]=s,addErrorMessage(e,t,g,S)}const getRelativePath=(e,t)=>{let s=0;for(;s<e.length&&s<t.length&&e[s]===t[s];s++);return[(e.length-s).toString(),...t.slice(s)].join(`/`)};function parseAnyDef(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?getRelativePath(t,e.currentPath):t.join(`/`)}}function parseArrayDef(e,t){let s={type:`array`};return e.type?._def&&e.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(s.items=parseDef(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&setResponseValueAndErrors(s,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&setResponseValueAndErrors(s,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(setResponseValueAndErrors(s,`minItems`,e.exactLength.value,e.exactLength.message,t),setResponseValueAndErrors(s,`maxItems`,e.exactLength.value,e.exactLength.message,t)),s}function parseBigintDef(e,t){let s={type:`integer`,format:`int64`};if(!e.checks)return s;for(let g of e.checks)switch(g.kind){case`min`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`minimum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMinimum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMinimum=!0),setResponseValueAndErrors(s,`minimum`,g.value,g.message,t));break;case`max`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`maximum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMaximum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMaximum=!0),setResponseValueAndErrors(s,`maximum`,g.value,g.message,t));break;case`multipleOf`:setResponseValueAndErrors(s,`multipleOf`,g.value,g.message,t);break}return s}function parseBooleanDef(){return{type:`boolean`}}function parseBrandedDef(e,t){return parseDef(e.type._def,t)}const parseCatchDef=(e,t)=>parseDef(e.innerType._def,t);function parseDateDef(e,t,s){let g=s??t.dateStrategy;if(Array.isArray(g))return{anyOf:g.map((s,g)=>parseDateDef(e,t,s))};switch(g){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return integerDateParser(e,t)}}const integerDateParser=(e,t)=>{let s={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return s;for(let g of e.checks)switch(g.kind){case`min`:setResponseValueAndErrors(s,`minimum`,g.value,g.message,t);break;case`max`:setResponseValueAndErrors(s,`maximum`,g.value,g.message,t);break}return s};function parseDefaultDef(e,t){return{...parseDef(e.innerType._def,t),default:e.defaultValue()}}function parseEffectsDef(e,t){return t.effectStrategy===`input`?parseDef(e.schema._def,t):parseAnyDef(t)}function parseEnumDef(e){return{type:`string`,enum:Array.from(e.values)}}const isJsonSchema7AllOfType=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function parseIntersectionDef(e,t){let s=[parseDef(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),parseDef(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),g=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,S=[];return s.forEach(e=>{if(isJsonSchema7AllOfType(e))S.push(...e.allOf),e.unevaluatedProperties===void 0&&(g=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:s,...g}=e;t=g}else g=void 0;S.push(t)}}),S.length?{allOf:S,...g}:void 0}function parseLiteralDef(e,t){let s=typeof e.value;return s!==`bigint`&&s!==`number`&&s!==`boolean`&&s!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:s===`bigint`?`integer`:s,enum:[e.value]}:{type:s===`bigint`?`integer`:s,const:e.value}}let emojiRegex;const zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(emojiRegex===void 0&&(emojiRegex=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),emojiRegex),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(e,t){let s={type:`string`};if(e.checks)for(let g of e.checks)switch(g.kind){case`min`:setResponseValueAndErrors(s,`minLength`,typeof s.minLength==`number`?Math.max(s.minLength,g.value):g.value,g.message,t);break;case`max`:setResponseValueAndErrors(s,`maxLength`,typeof s.maxLength==`number`?Math.min(s.maxLength,g.value):g.value,g.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:addFormat(s,`email`,g.message,t);break;case`format:idn-email`:addFormat(s,`idn-email`,g.message,t);break;case`pattern:zod`:addPattern(s,zodPatterns.email,g.message,t);break}break;case`url`:addFormat(s,`uri`,g.message,t);break;case`uuid`:addFormat(s,`uuid`,g.message,t);break;case`regex`:addPattern(s,g.regex,g.message,t);break;case`cuid`:addPattern(s,zodPatterns.cuid,g.message,t);break;case`cuid2`:addPattern(s,zodPatterns.cuid2,g.message,t);break;case`startsWith`:addPattern(s,RegExp(`^${escapeLiteralCheckValue(g.value,t)}`),g.message,t);break;case`endsWith`:addPattern(s,RegExp(`${escapeLiteralCheckValue(g.value,t)}$`),g.message,t);break;case`datetime`:addFormat(s,`date-time`,g.message,t);break;case`date`:addFormat(s,`date`,g.message,t);break;case`time`:addFormat(s,`time`,g.message,t);break;case`duration`:addFormat(s,`duration`,g.message,t);break;case`length`:setResponseValueAndErrors(s,`minLength`,typeof s.minLength==`number`?Math.max(s.minLength,g.value):g.value,g.message,t),setResponseValueAndErrors(s,`maxLength`,typeof s.maxLength==`number`?Math.min(s.maxLength,g.value):g.value,g.message,t);break;case`includes`:addPattern(s,RegExp(escapeLiteralCheckValue(g.value,t)),g.message,t);break;case`ip`:g.version!==`v6`&&addFormat(s,`ipv4`,g.message,t),g.version!==`v4`&&addFormat(s,`ipv6`,g.message,t);break;case`base64url`:addPattern(s,zodPatterns.base64url,g.message,t);break;case`jwt`:addPattern(s,zodPatterns.jwt,g.message,t);break;case`cidr`:g.version!==`v6`&&addPattern(s,zodPatterns.ipv4Cidr,g.message,t),g.version!==`v4`&&addPattern(s,zodPatterns.ipv6Cidr,g.message,t);break;case`emoji`:addPattern(s,zodPatterns.emoji(),g.message,t);break;case`ulid`:addPattern(s,zodPatterns.ulid,g.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:addFormat(s,`binary`,g.message,t);break;case`contentEncoding:base64`:setResponseValueAndErrors(s,`contentEncoding`,`base64`,g.message,t);break;case`pattern:zod`:addPattern(s,zodPatterns.base64,g.message,t);break}break;case`nanoid`:addPattern(s,zodPatterns.nanoid,g.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(g)}return s}function escapeLiteralCheckValue(e,t){return t.patternStrategy===`escape`?escapeNonAlphaNumeric(e):e}const ALPHA_NUMERIC=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function escapeNonAlphaNumeric(e){let t=``;for(let s=0;s<e.length;s++)ALPHA_NUMERIC.has(e[s])||(t+=`\\`),t+=e[s];return t}function addFormat(e,t,s,g){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&g.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...s&&g.errorMessages&&{errorMessage:{format:s}}})):setResponseValueAndErrors(e,`format`,t,s,g)}function addPattern(e,t,s,g){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&g.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:stringifyRegExpWithFlags(t,g),...s&&g.errorMessages&&{errorMessage:{pattern:s}}})):setResponseValueAndErrors(e,`pattern`,stringifyRegExpWithFlags(t,g),s,g)}function stringifyRegExpWithFlags(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let s={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},g=s.i?e.source.toLowerCase():e.source,S=``,w=!1,E=!1,D=!1;for(let e=0;e<g.length;e++){if(w){S+=g[e],w=!1;continue}if(s.i){if(E){if(g[e].match(/[a-z]/)){D?(S+=g[e],S+=`${g[e-2]}-${g[e]}`.toUpperCase(),D=!1):g[e+1]===`-`&&g[e+2]?.match(/[a-z]/)?(S+=g[e],D=!0):S+=`${g[e]}${g[e].toUpperCase()}`;continue}}else if(g[e].match(/[a-z]/)){S+=`[${g[e]}${g[e].toUpperCase()}]`;continue}}if(s.m){if(g[e]===`^`){S+=`(^|(?<=[\r
|
|
41
|
+
`,{offset:2,encoding:e})?{ext:`reg`,mime:`application/x-ms-regedit`}:void 0}if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}};detectImprecise=async e=>{this.buffer=new Uint8Array(reasonableDetectionSizeInBytes);let t=getKnownFileSizeOrMaximum(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);switch(await this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?UINT16_BE:UINT16_LE);if(!(t>maximumTiffTagCount)&&!(hasUnknownFileSize(this.tokenizer)&&2+t*12>maximumTiffIfdOffsetInBytes))for(let s=0;s<t;++s){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t={ext:`tif`,mime:`image/tiff`},s=(e?UINT16_BE:UINT16_LE).get(this.buffer,2),g=(e?UINT32_BE:UINT32_LE).get(this.buffer,4);if(s===42){if(g>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(g>=8){let t=(e?UINT16_BE:UINT16_LE).get(this.buffer,8),s=(e?UINT16_BE:UINT16_LE).get(this.buffer,10);if(t===28&&s===254||t===31&&s===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(hasUnknownFileSize(this.tokenizer)&&g>maximumTiffStreamIfdOffsetInBytes)return t;let s=hasUnknownFileSize(this.tokenizer)?maximumTiffIfdOffsetInBytes:this.tokenizer.fileInfo.size;try{await safeIgnore(this.tokenizer,g,{maximumLength:s,reason:`TIFF IFD offset`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}let S;try{S=await this.readTiffIFD(e)}catch(e){if(e instanceof EndOfStreamError)return;throw e}return S??t}if(s===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}};const supportedExtensions=new Set(extensions),supportedMimeTypes=new Set(mimeTypes);var util;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function s(e){throw Error()}e.assertNever=s,e.arrayToEnum=e=>{let t={};for(let s of e)t[s]=s;return t},e.getValidEnumValues=t=>{let s=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),g={};for(let e of s)g[e]=t[e];return e.objectValues(g)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.push(s);return t},e.find=(e,t)=>{for(let s of e)if(t(s))return s},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function g(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=g,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(util||={});var objectUtil;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||={});const ZodParsedType=util.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),getParsedType=e=>{switch(typeof e){case`undefined`:return ZodParsedType.undefined;case`string`:return ZodParsedType.string;case`number`:return Number.isNaN(e)?ZodParsedType.nan:ZodParsedType.number;case`boolean`:return ZodParsedType.boolean;case`function`:return ZodParsedType.function;case`bigint`:return ZodParsedType.bigint;case`symbol`:return ZodParsedType.symbol;case`object`:return Array.isArray(e)?ZodParsedType.array:e===null?ZodParsedType.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?ZodParsedType.promise:typeof Map<`u`&&e instanceof Map?ZodParsedType.map:typeof Set<`u`&&e instanceof Set?ZodParsedType.set:typeof Date<`u`&&e instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var ZodError=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},s={_errors:[]},g=e=>{for(let S of e.issues)if(S.code===`invalid_union`)S.unionErrors.map(g);else if(S.code===`invalid_return_type`)g(S.returnTypeError);else if(S.code===`invalid_arguments`)g(S.argumentsError);else if(S.path.length===0)s._errors.push(t(S));else{let e=s,g=0;for(;g<S.path.length;){let s=S.path[g];g===S.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(S))):e[s]=e[s]||{_errors:[]},e=e[s],g++}}};return g(this),s}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),s=[];for(let g of this.issues)if(g.path.length>0){let s=g.path[0];t[s]=t[s]||[],t[s].push(e(g))}else s.push(e(g));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};ZodError.create=e=>new ZodError(e);const errorMap=(e,t)=>{let s;switch(e.code){case ZodIssueCode.invalid_type:s=e.received===ZodParsedType.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case ZodIssueCode.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:s=`Unrecognized key(s) in object: ${util.joinValues(e.keys,`, `)}`;break;case ZodIssueCode.invalid_union:s=`Invalid input`;break;case ZodIssueCode.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${util.joinValues(e.options)}`;break;case ZodIssueCode.invalid_enum_value:s=`Invalid enum value. Expected ${util.joinValues(e.options)}, received '${e.received}'`;break;case ZodIssueCode.invalid_arguments:s=`Invalid function arguments`;break;case ZodIssueCode.invalid_return_type:s=`Invalid function return type`;break;case ZodIssueCode.invalid_date:s=`Invalid date`;break;case ZodIssueCode.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:util.assertNever(e.validation):s=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case ZodIssueCode.too_small:s=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case ZodIssueCode.too_big:s=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case ZodIssueCode.custom:s=`Invalid input`;break;case ZodIssueCode.invalid_intersection_types:s=`Intersection results could not be merged`;break;case ZodIssueCode.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case ZodIssueCode.not_finite:s=`Number must be finite`;break;default:s=t.defaultError,util.assertNever(e)}return{message:s}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=e=>{let{data:t,path:s,errorMaps:g,issueData:S}=e,w=[...s,...S.path||[]],E={...S,path:w};if(S.message!==void 0)return{...S,path:w,message:S.message};let D=``,O=g.filter(e=>!!e).slice().reverse();for(let e of O)D=e(E,{data:t,defaultError:D}).message;return{...S,path:w,message:D}};function addIssueToContext(e,t){let s=getErrorMap(),g=makeIssue({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===errorMap?void 0:errorMap].filter(e=>!!e)});e.common.issues.push(g)}var ParseStatus=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let s=[];for(let g of t){if(g.status===`aborted`)return INVALID;g.status===`dirty`&&e.dirty(),s.push(g.value)}return{status:e.value,value:s}}static async mergeObjectAsync(t,s){let g=[];for(let e of s){let t=await e.key,s=await e.value;g.push({key:t,value:s})}return e.mergeObjectSync(t,g)}static mergeObjectSync(e,t){let s={};for(let g of t){let{key:t,value:S}=g;if(t.status===`aborted`||S.status===`aborted`)return INVALID;t.status===`dirty`&&e.dirty(),S.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(S.value!==void 0||g.alwaysSet)&&(s[t.value]=S.value)}return{status:e.value,value:s}}};const INVALID=Object.freeze({status:`aborted`}),DIRTY=e=>({status:`dirty`,value:e}),OK=e=>({status:`valid`,value:e}),isAborted=e=>e.status===`aborted`,isDirty=e=>e.status===`dirty`,isValid=e=>e.status===`valid`,isAsync=e=>typeof Promise<`u`&&e instanceof Promise;var errorUtil;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(errorUtil||={});var ParseInputLazyPath=class{constructor(e,t,s,g){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=g}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const handleResult=(e,t)=>{if(isValid(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new ZodError(e.common.issues),this._error}}};function processCreateParams(e){if(!e)return{};let{errorMap:t,invalid_type_error:s,required_error:g,description:S}=e;if(t&&(s||g))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:S}:{errorMap:(t,S)=>{let{message:w}=e;return t.code===`invalid_enum_value`?{message:w??S.defaultError}:S.data===void 0?{message:w??g??S.defaultError}:t.code===`invalid_type`?{message:w??s??S.defaultError}:{message:S.defaultError}},description:S}}var ZodType=class{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(isAsync(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){let s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};return handleResult(s,this._parseSync({data:e,path:s.path,parent:s}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this[`~standard`].async)try{let s=this._parseSync({data:e,path:[],parent:t});return isValid(s)?{value:s.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>isValid(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},g=this._parse({data:e,path:s.path,parent:s});return handleResult(s,await(isAsync(g)?g:Promise.resolve(g)))}refine(e,t){let s=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,g)=>{let S=e(t),w=()=>g.addIssue({code:ZodIssueCode.custom,...s(t)});return typeof Promise<`u`&&S instanceof Promise?S.then(e=>e?!0:(w(),!1)):S?!0:(w(),!1)})}refinement(e,t){return this._refinement((s,g)=>e(s)?!0:(g.addIssue(typeof t==`function`?t(s,g):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;let emojiRegex$1;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,dateRegex=RegExp(`^${dateRegexSource}$`);function timeRegexSource(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let s=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${s}`}function timeRegex(e){return RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${dateRegexSource}T${timeRegexSource(e)}`,s=[];return s.push(e.local?`Z?`:`Z`),e.offset&&s.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${s.join(`|`)})`,RegExp(`^${t}$`)}function isValidIP(e,t){return!!((t===`v4`||!t)&&ipv4Regex.test(e)||(t===`v6`||!t)&&ipv6Regex.test(e))}function isValidJWT(e,t){if(!jwtRegex.test(e))return!1;try{let[s]=e.split(`.`);if(!s)return!1;let g=s.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(s.length+(4-s.length%4)%4,`=`),S=JSON.parse(atob(g));return!(typeof S!=`object`||!S||`typ`in S&&S?.typ!==`JWT`||!S.alg||t&&S.alg!==t)}catch{return!1}}function isValidCidr(e,t){return!!((t===`v4`||!t)&&ipv4CidrRegex.test(e)||(t===`v6`||!t)&&ipv6CidrRegex.test(e))}var ZodString=class e extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:t.parsedType}),INVALID}let t=new ParseStatus,s;for(let g of this._def.checks)if(g.kind===`min`)e.data.length<g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.value,type:`string`,inclusive:!0,exact:!1,message:g.message}),t.dirty());else if(g.kind===`max`)e.data.length>g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.value,type:`string`,inclusive:!0,exact:!1,message:g.message}),t.dirty());else if(g.kind===`length`){let S=e.data.length>g.value,w=e.data.length<g.value;(S||w)&&(s=this._getOrReturnCtx(e,s),S?addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.value,type:`string`,inclusive:!0,exact:!0,message:g.message}):w&&addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.value,type:`string`,inclusive:!0,exact:!0,message:g.message}),t.dirty())}else if(g.kind===`email`)emailRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`email`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`emoji`)emojiRegex$1||=new RegExp(_emojiRegex,`u`),emojiRegex$1.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`emoji`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`uuid`)uuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`uuid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`nanoid`)nanoidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`nanoid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`cuid`)cuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cuid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`cuid2`)cuid2Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cuid2`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`ulid`)ulidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`ulid`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty());else if(g.kind===`url`)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`url`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()}else g.kind===`regex`?(g.regex.lastIndex=0,g.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`regex`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty())):g.kind===`trim`?e.data=e.data.trim():g.kind===`includes`?e.data.includes(g.value,g.position)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{includes:g.value,position:g.position},message:g.message}),t.dirty()):g.kind===`toLowerCase`?e.data=e.data.toLowerCase():g.kind===`toUpperCase`?e.data=e.data.toUpperCase():g.kind===`startsWith`?e.data.startsWith(g.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{startsWith:g.value},message:g.message}),t.dirty()):g.kind===`endsWith`?e.data.endsWith(g.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{endsWith:g.value},message:g.message}),t.dirty()):g.kind===`datetime`?datetimeRegex(g).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`datetime`,message:g.message}),t.dirty()):g.kind===`date`?dateRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`date`,message:g.message}),t.dirty()):g.kind===`time`?timeRegex(g).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:`time`,message:g.message}),t.dirty()):g.kind===`duration`?durationRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`duration`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`ip`?isValidIP(e.data,g.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`ip`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`jwt`?isValidJWT(e.data,g.alg)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`jwt`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`cidr`?isValidCidr(e.data,g.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`cidr`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`base64`?base64Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`base64`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):g.kind===`base64url`?base64urlRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:`base64url`,code:ZodIssueCode.invalid_string,message:g.message}),t.dirty()):util.assertNever(g);return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement(t=>e.test(t),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...errorUtil.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodString.create=e=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:e?.coerce??!1,...processCreateParams(e)});function floatSafeRemainder(e,t){let s=(e.toString().split(`.`)[1]||``).length,g=(t.toString().split(`.`)[1]||``).length,S=s>g?s:g;return Number.parseInt(e.toFixed(S).replace(`.`,``))%Number.parseInt(t.toFixed(S).replace(`.`,``))/10**S}var ZodNumber=class e extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:t.parsedType}),INVALID}let t,s=new ParseStatus;for(let g of this._def.checks)g.kind===`int`?util.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:`integer`,received:`float`,message:g.message}),s.dirty()):g.kind===`min`?(g.inclusive?e.data<g.value:e.data<=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:g.value,type:`number`,inclusive:g.inclusive,exact:!1,message:g.message}),s.dirty()):g.kind===`max`?(g.inclusive?e.data>g.value:e.data>=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:g.value,type:`number`,inclusive:g.inclusive,exact:!1,message:g.message}),s.dirty()):g.kind===`multipleOf`?floatSafeRemainder(e.data,g.value)!==0&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:g.value,message:g.message}),s.dirty()):g.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_finite,message:g.message}),s.dirty()):util.assertNever(g);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(t,s,g,S){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:g,message:errorUtil.toString(S)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:errorUtil.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let s of this._def.checks)if(s.kind===`finite`||s.kind===`int`||s.kind===`multipleOf`)return!0;else s.kind===`min`?(t===null||s.value>t)&&(t=s.value):s.kind===`max`&&(e===null||s.value<e)&&(e=s.value);return Number.isFinite(t)&&Number.isFinite(e)}};ZodNumber.create=e=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodBigInt=class e extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let t,s=new ParseStatus;for(let g of this._def.checks)g.kind===`min`?(g.inclusive?e.data<g.value:e.data<=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,type:`bigint`,minimum:g.value,inclusive:g.inclusive,message:g.message}),s.dirty()):g.kind===`max`?(g.inclusive?e.data>g.value:e.data>=g.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,type:`bigint`,maximum:g.value,inclusive:g.inclusive,message:g.message}),s.dirty()):g.kind===`multipleOf`?e.data%g.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:g.value,message:g.message}),s.dirty()):util.assertNever(g);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(t,s,g,S){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:g,message:errorUtil.toString(S)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodBigInt.create=e=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:e?.coerce??!1,...processCreateParams(e)});var ZodBoolean=class extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:t.parsedType}),INVALID}return OK(e.data)}};ZodBoolean.create=e=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodDate=class e extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:t.parsedType}),INVALID}if(Number.isNaN(e.data.getTime()))return addIssueToContext(this._getOrReturnCtx(e),{code:ZodIssueCode.invalid_date}),INVALID;let t=new ParseStatus,s;for(let g of this._def.checks)g.kind===`min`?e.data.getTime()<g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,message:g.message,inclusive:!0,exact:!1,minimum:g.value,type:`date`}),t.dirty()):g.kind===`max`?e.data.getTime()>g.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,message:g.message,inclusive:!0,exact:!1,maximum:g.value,type:`date`}),t.dirty()):util.assertNever(g);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};ZodDate.create=e=>new ZodDate({checks:[],coerce:e?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(e)});var ZodSymbol=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:t.parsedType}),INVALID}return OK(e.data)}};ZodSymbol.create=e=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(e)});var ZodUndefined=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:t.parsedType}),INVALID}return OK(e.data)}};ZodUndefined.create=e=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(e)});var ZodNull=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:t.parsedType}),INVALID}return OK(e.data)}};ZodNull.create=e=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(e)});var ZodAny=class extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}};ZodAny.create=e=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(e)});var ZodUnknown=class extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}};ZodUnknown.create=e=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(e)});var ZodNever=class extends ZodType{_parse(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}};ZodNever.create=e=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(e)});var ZodVoid=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:t.parsedType}),INVALID}return OK(e.data)}};ZodVoid.create=e=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(e)});var ZodArray=class e extends ZodType{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),g=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(g.exactLength!==null){let e=t.data.length>g.exactLength.value,S=t.data.length<g.exactLength.value;(e||S)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:S?g.exactLength.value:void 0,maximum:e?g.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:g.exactLength.message}),s.dirty())}if(g.minLength!==null&&t.data.length<g.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:g.minLength.value,type:`array`,inclusive:!0,exact:!1,message:g.minLength.message}),s.dirty()),g.maxLength!==null&&t.data.length>g.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:g.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:g.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((e,s)=>g.type._parseAsync(new ParseInputLazyPath(t,e,t.path,s)))).then(e=>ParseStatus.mergeArray(s,e));let S=[...t.data].map((e,s)=>g.type._parseSync(new ParseInputLazyPath(t,e,t.path,s)));return ParseStatus.mergeArray(s,S)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:errorUtil.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:errorUtil.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:errorUtil.toString(s)}})}nonempty(e){return this.min(1,e)}};ZodArray.create=(e,t)=>new ZodArray({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(t)});function deepPartialify(e){if(e instanceof ZodObject){let t={};for(let s in e.shape){let g=e.shape[s];t[s]=ZodOptional.create(deepPartialify(g))}return new ZodObject({...e._def,shape:()=>t})}else if(e instanceof ZodArray)return new ZodArray({...e._def,type:deepPartialify(e.element)});else if(e instanceof ZodOptional)return ZodOptional.create(deepPartialify(e.unwrap()));else if(e instanceof ZodNullable)return ZodNullable.create(deepPartialify(e.unwrap()));else if(e instanceof ZodTuple)return ZodTuple.create(e.items.map(e=>deepPartialify(e)));else return e}var ZodObject=class e extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:util.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID}let{status:t,ctx:s}=this._processInputParams(e),{shape:g,keys:S}=this._getCached(),w=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys===`strip`))for(let e in s.data)S.includes(e)||w.push(e);let E=[];for(let e of S){let t=g[e],S=s.data[e];E.push({key:{status:`valid`,value:e},value:t._parse(new ParseInputLazyPath(s,S,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof ZodNever){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of w)E.push({key:{status:`valid`,value:e},value:{status:`valid`,value:s.data[e]}});else if(e===`strict`)w.length>0&&(addIssueToContext(s,{code:ZodIssueCode.unrecognized_keys,keys:w}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of w){let g=s.data[t];E.push({key:{status:`valid`,value:t},value:e._parse(new ParseInputLazyPath(s,g,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of E){let s=await t.key,g=await t.value;e.push({key:s,value:g,alwaysSet:t.alwaysSet})}return e}).then(e=>ParseStatus.mergeObjectSync(t,e)):ParseStatus.mergeObjectSync(t,E)}get shape(){return this._def.shape()}strict(t){return errorUtil.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,s)=>{let g=this._def.errorMap?.(e,s).message??s.defaultError;return e.code===`unrecognized_keys`?{message:errorUtil.errToObj(t).message??g}:{message:g}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let s={};for(let e of util.objectKeys(t))t[e]&&this.shape[e]&&(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}omit(t){let s={};for(let e of util.objectKeys(this.shape))t[e]||(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}deepPartial(){return deepPartialify(this)}partial(t){let s={};for(let e of util.objectKeys(this.shape)){let g=this.shape[e];t&&!t[e]?s[e]=g:s[e]=g.optional()}return new e({...this._def,shape:()=>s})}required(t){let s={};for(let e of util.objectKeys(this.shape))if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof ZodOptional;)t=t._def.innerType;s[e]=t}return new e({...this._def,shape:()=>s})}keyof(){return createZodEnum(util.objectKeys(this.shape))}};ZodObject.create=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.strictCreate=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strict`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.lazycreate=(e,t)=>new ZodObject({shape:e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)});var ZodUnion=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=this._def.options;function g(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let s of e)if(s.result.status===`dirty`)return t.common.issues.push(...s.ctx.common.issues),s.result;let s=e.map(e=>new ZodError(e.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:s}),INVALID}if(t.common.async)return Promise.all(s.map(async e=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(g);{let e,g=[];for(let S of s){let s={...t,common:{...t.common,issues:[]},parent:null},w=S._parseSync({data:t.data,path:t.path,parent:s});if(w.status===`valid`)return w;w.status===`dirty`&&!e&&(e={result:w,ctx:s}),s.common.issues.length&&g.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let S=g.map(e=>new ZodError(e));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:S}),INVALID}}get options(){return this._def.options}};ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(t)});const getDiscriminator=e=>e instanceof ZodLazy?getDiscriminator(e.schema):e instanceof ZodEffects?getDiscriminator(e.innerType()):e instanceof ZodLiteral?[e.value]:e instanceof ZodEnum?e.options:e instanceof ZodNativeEnum?util.objectValues(e.enum):e instanceof ZodDefault?getDiscriminator(e._def.innerType):e instanceof ZodUndefined?[void 0]:e instanceof ZodNull?[null]:e instanceof ZodOptional?[void 0,...getDiscriminator(e.unwrap())]:e instanceof ZodNullable?[null,...getDiscriminator(e.unwrap())]:e instanceof ZodBranded||e instanceof ZodReadonly?getDiscriminator(e.unwrap()):e instanceof ZodCatch?getDiscriminator(e._def.innerType):[];var ZodDiscriminatedUnion=class e extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.object)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID;let s=this.discriminator,g=t.data[s],S=this.optionsMap.get(g);return S?t.common.async?S._parseAsync({data:t.data,path:t.path,parent:t}):S._parseSync({data:t.data,path:t.path,parent:t}):(addIssueToContext(t,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,s,g){let S=new Map;for(let e of s){let s=getDiscriminator(e.shape[t]);if(!s.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let g of s){if(S.has(g))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(g)}`);S.set(g,e)}}return new e({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:S,...processCreateParams(g)})}};function mergeValues(e,t){let s=getParsedType(e),g=getParsedType(t);if(e===t)return{valid:!0,data:e};if(s===ZodParsedType.object&&g===ZodParsedType.object){let s=util.objectKeys(t),g=util.objectKeys(e).filter(e=>s.indexOf(e)!==-1),S={...e,...t};for(let s of g){let g=mergeValues(e[s],t[s]);if(!g.valid)return{valid:!1};S[s]=g.data}return{valid:!0,data:S}}else if(s===ZodParsedType.array&&g===ZodParsedType.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let g=0;g<e.length;g++){let S=e[g],w=t[g],E=mergeValues(S,w);if(!E.valid)return{valid:!1};s.push(E.data)}return{valid:!0,data:s}}else if(s===ZodParsedType.date&&g===ZodParsedType.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var ZodIntersection=class extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),g=(e,g)=>{if(isAborted(e)||isAborted(g))return INVALID;let S=mergeValues(e.value,g.value);return S.valid?((isDirty(e)||isDirty(g))&&t.dirty(),{status:t.value,value:S.data}):(addIssueToContext(s,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([e,t])=>g(e,t)):g(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};ZodIntersection.create=(e,t,s)=>new ZodIntersection({left:e,right:t,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(s)});var ZodTuple=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.array)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:s.parsedType}),INVALID;if(s.data.length<this._def.items.length)return addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),INVALID;!this._def.rest&&s.data.length>this._def.items.length&&(addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let g=[...s.data].map((e,t)=>{let g=this._def.items[t]||this._def.rest;return g?g._parse(new ParseInputLazyPath(s,e,s.path,t)):null}).filter(e=>!!e);return s.common.async?Promise.all(g).then(e=>ParseStatus.mergeArray(t,e)):ParseStatus.mergeArray(t,g)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ZodTuple.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new ZodTuple({items:e,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(t)})};var ZodRecord=class e extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.object)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:s.parsedType}),INVALID;let g=[],S=this._def.keyType,w=this._def.valueType;for(let e in s.data)g.push({key:S._parse(new ParseInputLazyPath(s,e,s.path,e)),value:w._parse(new ParseInputLazyPath(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?ParseStatus.mergeObjectAsync(t,g):ParseStatus.mergeObjectSync(t,g)}get element(){return this._def.valueType}static create(t,s,g){return s instanceof ZodType?new e({keyType:t,valueType:s,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(g)}):new e({keyType:ZodString.create(),valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(s)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.map)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:s.parsedType}),INVALID;let g=this._def.keyType,S=this._def.valueType,w=[...s.data.entries()].map(([e,t],w)=>({key:g._parse(new ParseInputLazyPath(s,e,s.path,[w,`key`])),value:S._parse(new ParseInputLazyPath(s,t,s.path,[w,`value`]))}));if(s.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let s of w){let g=await s.key,S=await s.value;if(g.status===`aborted`||S.status===`aborted`)return INVALID;(g.status===`dirty`||S.status===`dirty`)&&t.dirty(),e.set(g.value,S.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let s of w){let g=s.key,S=s.value;if(g.status===`aborted`||S.status===`aborted`)return INVALID;(g.status===`dirty`||S.status===`dirty`)&&t.dirty(),e.set(g.value,S.value)}return{status:t.value,value:e}}}};ZodMap.create=(e,t,s)=>new ZodMap({valueType:t,keyType:e,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(s)});var ZodSet=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ZodParsedType.set)return addIssueToContext(s,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:s.parsedType}),INVALID;let g=this._def;g.minSize!==null&&s.data.size<g.minSize.value&&(addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:g.minSize.value,type:`set`,inclusive:!0,exact:!1,message:g.minSize.message}),t.dirty()),g.maxSize!==null&&s.data.size>g.maxSize.value&&(addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:g.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:g.maxSize.message}),t.dirty());let S=this._def.valueType;function w(e){let s=new Set;for(let g of e){if(g.status===`aborted`)return INVALID;g.status===`dirty`&&t.dirty(),s.add(g.value)}return{status:t.value,value:s}}let E=[...s.data.values()].map((e,t)=>S._parse(new ParseInputLazyPath(s,e,s.path,t)));return s.common.async?Promise.all(E).then(e=>w(e)):w(E)}min(t,s){return new e({...this._def,minSize:{value:t,message:errorUtil.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:errorUtil.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ZodSet.create=(e,t)=>new ZodSet({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(t)});var ZodFunction=class e extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.function)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:t.parsedType}),INVALID;function s(e,s){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:s}})}function g(e,s){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:s}})}let S={errorMap:t.common.contextualErrorMap},w=t.data;if(this._def.returns instanceof ZodPromise){let e=this;return OK(async function(...t){let E=new ZodError([]),D=await e._def.args.parseAsync(t,S).catch(e=>{throw E.addIssue(s(t,e)),E}),O=await Reflect.apply(w,this,D);return await e._def.returns._def.type.parseAsync(O,S).catch(e=>{throw E.addIssue(g(O,e)),E})})}else{let e=this;return OK(function(...t){let E=e._def.args.safeParse(t,S);if(!E.success)throw new ZodError([s(t,E.error)]);let D=Reflect.apply(w,this,E.data),O=e._def.returns.safeParse(D,S);if(!O.success)throw new ZodError([g(D,O.error)]);return O.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ZodTuple.create(t).rest(ZodUnknown.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,s,g){return new e({args:t||ZodTuple.create([]).rest(ZodUnknown.create()),returns:s||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(g)})}},ZodLazy=class extends ZodType{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ZodLazy.create=(e,t)=>new ZodLazy({getter:e,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(t)});var ZodLiteral=class extends ZodType{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(t)});function createZodEnum(e,t){return new ZodEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(t)})}var ZodEnum=class e extends ZodType{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),s=this._def.values;return addIssueToContext(t,{expected:util.joinValues(s),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:s}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,s=this._def){return e.create(t,{...this._def,...s})}exclude(t,s=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...s})}};ZodEnum.create=createZodEnum;var ZodNativeEnum=class extends ZodType{_parse(e){let t=util.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==ZodParsedType.string&&s.parsedType!==ZodParsedType.number){let e=util.objectValues(t);return addIssueToContext(s,{expected:util.joinValues(e),received:s.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(util.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=util.objectValues(t);return addIssueToContext(s,{received:s.data,code:ZodIssueCode.invalid_enum_value,options:e}),INVALID}return OK(e.data)}get enum(){return this._def.values}};ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(t)});var ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==ZodParsedType.promise&&t.common.async===!1?(addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID):OK((t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(t)});var ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),g=this._def.effect||null,S={addIssue:e=>{addIssueToContext(s,e),e.fatal?t.abort():t.dirty()},get path(){return s.path}};if(S.addIssue=S.addIssue.bind(S),g.type===`preprocess`){let e=g.transform(s.data,S);if(s.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return INVALID;let g=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return g.status===`aborted`?INVALID:g.status===`dirty`||t.value===`dirty`?DIRTY(g.value):g});{if(t.value===`aborted`)return INVALID;let g=this._def.schema._parseSync({data:e,path:s.path,parent:s});return g.status===`aborted`?INVALID:g.status===`dirty`||t.value===`dirty`?DIRTY(g.value):g}}if(g.type===`refinement`){let e=e=>{let t=g.refinement(e,S);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(s.common.async===!1){let g=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return g.status===`aborted`?INVALID:(g.status===`dirty`&&t.dirty(),e(g.value),{status:t.value,value:g.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(s=>s.status===`aborted`?INVALID:(s.status===`dirty`&&t.dirty(),e(s.value).then(()=>({status:t.value,value:s.value}))))}if(g.type===`transform`)if(s.common.async===!1){let e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!isValid(e))return INVALID;let w=g.transform(e.value,S);if(w instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:w}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(e=>isValid(e)?Promise.resolve(g.transform(e.value,S)).then(e=>({status:t.value,value:e})):INVALID);util.assertNever(g)}};ZodEffects.create=(e,t,s)=>new ZodEffects({schema:e,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:t,...processCreateParams(s)}),ZodEffects.createWithPreprocess=(e,t,s)=>new ZodEffects({schema:t,effect:{type:`preprocess`,transform:e},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(s)});var ZodOptional=class extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(t)});var ZodNullable=class extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(t)});var ZodDefault=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===ZodParsedType.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...processCreateParams(t)});var ZodCatch=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},g=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return isAsync(g)?g.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new ZodError(s.common.issues)},input:s.data})})):{status:`valid`,value:g.status===`valid`?g.value:this._def.catchValue({get error(){return new ZodError(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...processCreateParams(t)});var ZodNaN=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:t.parsedType}),INVALID}return{status:`valid`,value:e.data}}};ZodNaN.create=e=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(e)});var ZodBranded=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},ZodPipeline=class e extends ZodType{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})();{let e=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:s.path,parent:s})}}static create(t,s){return new e({in:t,out:s,typeName:ZodFirstPartyTypeKind.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(e){let t=this._def.innerType._parse(e),s=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then(e=>s(e)):s(t)}unwrap(){return this._def.innerType}};ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)});const late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(ZodFirstPartyTypeKind||={});const stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ZodMiniType=$constructor(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);$ZodType.init(e,t),e.def=t,e.type=t.type,e.parse=(t,s)=>parse$1(e,t,s,{callee:e.parse}),e.safeParse=(t,s)=>safeParse$1(e,t,s),e.parseAsync=async(t,s)=>parseAsync(e,t,s,{callee:e.parseAsync}),e.safeParseAsync=async(t,s)=>safeParseAsync$1(e,t,s),e.check=(...s)=>e.clone({...t,checks:[...t.checks??[],...s.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,s)=>clone(e,t,s),e.brand=()=>e,e.register=((t,s)=>(t.add(e,s),e)),e.apply=t=>t(e)}),ZodMiniObject=$constructor(`ZodMiniObject`,(e,t)=>{$ZodObject.init(e,t),ZodMiniType.init(e,t),defineLazy(e,`shape`,()=>t.shape)});function object(e,t){return new ZodMiniObject({type:`object`,shape:e??{},...normalizeParams(t)})}const describe=describe$1,meta=meta$1;function isZ4Schema(e){return!!e._zod}function objectFromShape(e){let t=Object.values(e);if(t.length===0)return object({});let s=t.every(isZ4Schema),g=t.every(e=>!isZ4Schema(e));if(s)return object(e);if(g)return objectType(e);throw Error(`Mixed Zod versions detected in object shape.`)}function safeParse(e,t){return isZ4Schema(e)?safeParse$1(e,t):e.safeParse(t)}async function safeParseAsync(e,t){return isZ4Schema(e)?await safeParseAsync$1(e,t):await e.safeParseAsync(t)}function getObjectShape(e){if(!e)return;let t;if(t=isZ4Schema(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function normalizeObjectSchema(e){if(e){if(typeof e==`object`){let t=e,s=e;if(!t._def&&!s._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return objectFromShape(e)}}if(isZ4Schema(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function getParseErrorMessage(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function getSchemaDescription(e){return e.description}function isSchemaOptional(e){if(isZ4Schema(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function getLiteralValue(e){if(isZ4Schema(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let s=e.value;if(s!==void 0)return s}const LATEST_PROTOCOL_VERSION=`2025-11-25`,DEFAULT_NEGOTIATED_PROTOCOL_VERSION=`2025-03-26`,SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],RELATED_TASK_META_KEY=`io.modelcontextprotocol/related-task`,JSONRPC_VERSION=`2.0`,AssertObjectSchema=custom(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),ProgressTokenSchema=union([string(),number().int()]),CursorSchema=string(),TaskCreationParamsSchema=looseObject({ttl:number().optional(),pollInterval:number().optional()}),TaskMetadataSchema=object$1({ttl:number().optional()}),RelatedTaskMetadataSchema=object$1({taskId:string()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=e=>TaskAugmentedRequestParamsSchema.safeParse(e).success,RequestSchema=object$1({method:string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),NotificationSchema=object$1({method:string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union([string(),number().int()]),JSONRPCRequestSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=e=>JSONRPCRequestSchema.safeParse(e).success,JSONRPCNotificationSchema=object$1({jsonrpc:literal(`2.0`),...NotificationSchema.shape}).strict(),isJSONRPCNotification=e=>JSONRPCNotificationSchema.safeParse(e).success,JSONRPCResultResponseSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=e=>JSONRPCResultResponseSchema.safeParse(e).success;var ErrorCode;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(ErrorCode||={});const JSONRPCErrorResponseSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema.optional(),error:object$1({code:number().int(),message:string(),data:unknown().optional()})}).strict(),isJSONRPCErrorResponse=e=>JSONRPCErrorResponseSchema.safeParse(e).success,JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal(`notifications/cancelled`),params:CancelledNotificationParamsSchema}),IconSchema=object$1({src:string(),mimeType:string().optional(),sizes:array(string()).optional(),theme:_enum([`light`,`dark`]).optional()}),IconsSchema=object$1({icons:array(IconSchema).optional()}),BaseMetadataSchema=object$1({name:string(),title:string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string(),websiteUrl:string().optional(),description:string().optional()}),FormElicitationCapabilitySchema=intersection(object$1({applyDefaults:boolean().optional()}),record(string(),unknown())),ElicitationCapabilitySchema=preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,intersection(object$1({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),record(string(),unknown()).optional())),ClientTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({tools:looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object$1({experimental:record(string(),AssertObjectSchema).optional(),sampling:object$1({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object$1({listChanged:boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string(),AssertObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal(`initialize`),params:InitializeRequestParamsSchema}),isInitializeRequest=e=>InitializeRequestSchema.safeParse(e).success,ServerCapabilitiesSchema=object$1({experimental:record(string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object$1({listChanged:boolean().optional()}).optional(),resources:object$1({subscribe:boolean().optional(),listChanged:boolean().optional()}).optional(),tools:object$1({listChanged:boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string(),AssertObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/initialized`),params:NotificationsParamsSchema.optional()}),isInitializedNotification=e=>InitializedNotificationSchema.safeParse(e).success,PingRequestSchema=RequestSchema.extend({method:literal(`ping`),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object$1({progress:number(),total:optional(number()),message:optional(string())}),ProgressNotificationParamsSchema=object$1({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal(`notifications/progress`),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=_enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),TaskSchema=object$1({taskId:string(),status:TaskStatusSchema,ttl:union([number(),_null()]),createdAt:string(),lastUpdatedAt:string(),pollInterval:optional(number()),statusMessage:optional(string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal(`notifications/tasks/status`),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal(`tasks/get`),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal(`tasks/result`),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal(`tasks/list`)}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal(`tasks/cancel`),params:BaseRequestParamsSchema.extend({taskId:string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=object$1({uri:string(),mimeType:optional(string()),_meta:record(string(),unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string()}),Base64Schema=string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum([`user`,`assistant`]),AnnotationsSchema=object$1({audience:array(RoleSchema).optional(),priority:number().min(0).max(1).optional(),lastModified:datetime({offset:!0}).optional()}),ResourceSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string(),description:optional(string()),mimeType:optional(string()),size:optional(number()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string(),description:optional(string()),mimeType:optional(string()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal(`resources/list`)}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal(`resources/templates/list`)}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal(`resources/read`),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/list_changed`),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal(`resources/subscribe`),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal(`resources/unsubscribe`),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/updated`),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object$1({name:string(),description:optional(string()),required:optional(boolean())}),PromptSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal(`prompts/list`)}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string(),arguments:record(string(),string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal(`prompts/get`),params:GetPromptRequestParamsSchema}),TextContentSchema=object$1({type:literal(`text`),text:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ImageContentSchema=object$1({type:literal(`image`),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),AudioContentSchema=object$1({type:literal(`audio`),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ToolUseContentSchema=object$1({type:literal(`tool_use`),name:string(),id:string(),input:record(string(),unknown()),_meta:record(string(),unknown()).optional()}),EmbeddedResourceSchema=object$1({type:literal(`resource`),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal(`resource_link`)}),ContentBlockSchema=union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object$1({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/prompts/list_changed`),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object$1({title:string().optional(),readOnlyHint:boolean().optional(),destructiveHint:boolean().optional(),idempotentHint:boolean().optional(),openWorldHint:boolean().optional()}),ToolExecutionSchema=object$1({taskSupport:_enum([`required`,`optional`,`forbidden`]).optional()}),ToolSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string().optional(),inputSchema:object$1({type:literal(`object`),properties:record(string(),AssertObjectSchema).optional(),required:array(string()).optional()}).catchall(unknown()),outputSchema:object$1({type:literal(`object`),properties:record(string(),AssertObjectSchema).optional(),required:array(string()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string(),unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal(`tools/list`)}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:record(string(),unknown()).optional(),isError:boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string(),arguments:record(string(),unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal(`tools/call`),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/tools/list_changed`),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object$1({autoRefresh:boolean().default(!0),debounceMs:number().int().nonnegative().default(300)}),LoggingLevelSchema=_enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal(`logging/setLevel`),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string().optional(),data:unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal(`notifications/message`),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object$1({name:string().optional()}),ModelPreferencesSchema=object$1({hints:array(ModelHintSchema).optional(),costPriority:number().min(0).max(1).optional(),speedPriority:number().min(0).max(1).optional(),intelligencePriority:number().min(0).max(1).optional()}),ToolChoiceSchema=object$1({mode:_enum([`auto`,`required`,`none`]).optional()}),ToolResultContentSchema=object$1({type:literal(`tool_result`),toolUseId:string().describe(`The unique identifier for the corresponding tool call.`),content:array(ContentBlockSchema).default([]),structuredContent:object$1({}).loose().optional(),isError:boolean().optional(),_meta:record(string(),unknown()).optional()}),SamplingContentSchema=discriminatedUnion(`type`,[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion(`type`,[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object$1({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string(),unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string().optional(),includeContext:_enum([`none`,`thisServer`,`allServers`]).optional(),temperature:number().optional(),maxTokens:number().int(),stopSequences:array(string()).optional(),metadata:AssertObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal(`sampling/createMessage`),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`]).or(string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(string())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object$1({type:literal(`boolean`),title:string().optional(),description:string().optional(),default:boolean().optional()}),StringSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),minLength:number().optional(),maxLength:number().optional(),format:_enum([`email`,`uri`,`date`,`date-time`]).optional(),default:string().optional()}),NumberSchemaSchema=object$1({type:_enum([`number`,`integer`]),title:string().optional(),description:string().optional(),minimum:number().optional(),maximum:number().optional(),default:number().optional()}),UntitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),enum:array(string()),default:string().optional()}),TitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),oneOf:array(object$1({const:string(),title:string()})),default:string().optional()}),LegacyTitledEnumSchemaSchema=object$1({type:literal(`string`),title:string().optional(),description:string().optional(),enum:array(string()),enumNames:array(string()).optional(),default:string().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string().optional(),description:string().optional(),minItems:number().optional(),maxItems:number().optional(),items:object$1({type:literal(`string`),enum:array(string())}),default:array(string()).optional()}),TitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string().optional(),description:string().optional(),minItems:number().optional(),maxItems:number().optional(),items:object$1({anyOf:array(object$1({const:string(),title:string()}))}),default:array(string()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`form`).optional(),message:string(),requestedSchema:object$1({type:literal(`object`),properties:record(string(),PrimitiveSchemaDefinitionSchema),required:array(string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`url`),message:string(),elicitationId:string(),url:string().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal(`elicitation/create`),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal(`notifications/elicitation/complete`),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum([`accept`,`decline`,`cancel`]),content:preprocess(e=>e===null?void 0:e,record(string(),union([string(),number(),boolean(),array(string())])).optional())}),ResourceTemplateReferenceSchema=object$1({type:literal(`ref/resource`),uri:string()}),PromptReferenceSchema=object$1({type:literal(`ref/prompt`),name:string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object$1({name:string(),value:string()}),context:object$1({arguments:record(string(),string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal(`completion/complete`),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function assertCompleteRequestResourceTemplate(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string()).max(100),total:optional(number().int()),hasMore:optional(boolean())})}),RootSchema=object$1({uri:string().startsWith(`file://`),name:string().optional(),_meta:record(string(),unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal(`roots/list`),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/roots/list_changed`),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]);var McpError=class e extends Error{constructor(e,t,s){super(`MCP error ${e}: ${t}`),this.code=e,this.data=s,this.name=`McpError`}static fromError(t,s,g){if(t===ErrorCode.UrlElicitationRequired&&g){let e=g;if(e.elicitations)return new UrlElicitationRequiredError(e.elicitations,s)}return new e(t,s,g)}},UrlElicitationRequiredError=class extends McpError{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(ErrorCode.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(e){return e===`completed`||e===`failed`||e===`cancelled`}const ignoreOverride=Symbol(`Let zodToJsonSchema decide on which parser to use`),defaultOptions={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},getDefaultOptions=e=>typeof e==`string`?{...defaultOptions,name:e}:{...defaultOptions,...e},getRefs=e=>{let t=getDefaultOptions(e),s=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:s,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function addErrorMessage(e,t,s,g){g?.errorMessages&&s&&(e.errorMessage={...e.errorMessage,[t]:s})}function setResponseValueAndErrors(e,t,s,g,S){e[t]=s,addErrorMessage(e,t,g,S)}const getRelativePath=(e,t)=>{let s=0;for(;s<e.length&&s<t.length&&e[s]===t[s];s++);return[(e.length-s).toString(),...t.slice(s)].join(`/`)};function parseAnyDef(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?getRelativePath(t,e.currentPath):t.join(`/`)}}function parseArrayDef(e,t){let s={type:`array`};return e.type?._def&&e.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(s.items=parseDef(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&setResponseValueAndErrors(s,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&setResponseValueAndErrors(s,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(setResponseValueAndErrors(s,`minItems`,e.exactLength.value,e.exactLength.message,t),setResponseValueAndErrors(s,`maxItems`,e.exactLength.value,e.exactLength.message,t)),s}function parseBigintDef(e,t){let s={type:`integer`,format:`int64`};if(!e.checks)return s;for(let g of e.checks)switch(g.kind){case`min`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`minimum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMinimum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMinimum=!0),setResponseValueAndErrors(s,`minimum`,g.value,g.message,t));break;case`max`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`maximum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMaximum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMaximum=!0),setResponseValueAndErrors(s,`maximum`,g.value,g.message,t));break;case`multipleOf`:setResponseValueAndErrors(s,`multipleOf`,g.value,g.message,t);break}return s}function parseBooleanDef(){return{type:`boolean`}}function parseBrandedDef(e,t){return parseDef(e.type._def,t)}const parseCatchDef=(e,t)=>parseDef(e.innerType._def,t);function parseDateDef(e,t,s){let g=s??t.dateStrategy;if(Array.isArray(g))return{anyOf:g.map((s,g)=>parseDateDef(e,t,s))};switch(g){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return integerDateParser(e,t)}}const integerDateParser=(e,t)=>{let s={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return s;for(let g of e.checks)switch(g.kind){case`min`:setResponseValueAndErrors(s,`minimum`,g.value,g.message,t);break;case`max`:setResponseValueAndErrors(s,`maximum`,g.value,g.message,t);break}return s};function parseDefaultDef(e,t){return{...parseDef(e.innerType._def,t),default:e.defaultValue()}}function parseEffectsDef(e,t){return t.effectStrategy===`input`?parseDef(e.schema._def,t):parseAnyDef(t)}function parseEnumDef(e){return{type:`string`,enum:Array.from(e.values)}}const isJsonSchema7AllOfType=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function parseIntersectionDef(e,t){let s=[parseDef(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),parseDef(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),g=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,S=[];return s.forEach(e=>{if(isJsonSchema7AllOfType(e))S.push(...e.allOf),e.unevaluatedProperties===void 0&&(g=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:s,...g}=e;t=g}else g=void 0;S.push(t)}}),S.length?{allOf:S,...g}:void 0}function parseLiteralDef(e,t){let s=typeof e.value;return s!==`bigint`&&s!==`number`&&s!==`boolean`&&s!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:s===`bigint`?`integer`:s,enum:[e.value]}:{type:s===`bigint`?`integer`:s,const:e.value}}let emojiRegex;const zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(emojiRegex===void 0&&(emojiRegex=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),emojiRegex),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(e,t){let s={type:`string`};if(e.checks)for(let g of e.checks)switch(g.kind){case`min`:setResponseValueAndErrors(s,`minLength`,typeof s.minLength==`number`?Math.max(s.minLength,g.value):g.value,g.message,t);break;case`max`:setResponseValueAndErrors(s,`maxLength`,typeof s.maxLength==`number`?Math.min(s.maxLength,g.value):g.value,g.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:addFormat(s,`email`,g.message,t);break;case`format:idn-email`:addFormat(s,`idn-email`,g.message,t);break;case`pattern:zod`:addPattern(s,zodPatterns.email,g.message,t);break}break;case`url`:addFormat(s,`uri`,g.message,t);break;case`uuid`:addFormat(s,`uuid`,g.message,t);break;case`regex`:addPattern(s,g.regex,g.message,t);break;case`cuid`:addPattern(s,zodPatterns.cuid,g.message,t);break;case`cuid2`:addPattern(s,zodPatterns.cuid2,g.message,t);break;case`startsWith`:addPattern(s,RegExp(`^${escapeLiteralCheckValue(g.value,t)}`),g.message,t);break;case`endsWith`:addPattern(s,RegExp(`${escapeLiteralCheckValue(g.value,t)}$`),g.message,t);break;case`datetime`:addFormat(s,`date-time`,g.message,t);break;case`date`:addFormat(s,`date`,g.message,t);break;case`time`:addFormat(s,`time`,g.message,t);break;case`duration`:addFormat(s,`duration`,g.message,t);break;case`length`:setResponseValueAndErrors(s,`minLength`,typeof s.minLength==`number`?Math.max(s.minLength,g.value):g.value,g.message,t),setResponseValueAndErrors(s,`maxLength`,typeof s.maxLength==`number`?Math.min(s.maxLength,g.value):g.value,g.message,t);break;case`includes`:addPattern(s,RegExp(escapeLiteralCheckValue(g.value,t)),g.message,t);break;case`ip`:g.version!==`v6`&&addFormat(s,`ipv4`,g.message,t),g.version!==`v4`&&addFormat(s,`ipv6`,g.message,t);break;case`base64url`:addPattern(s,zodPatterns.base64url,g.message,t);break;case`jwt`:addPattern(s,zodPatterns.jwt,g.message,t);break;case`cidr`:g.version!==`v6`&&addPattern(s,zodPatterns.ipv4Cidr,g.message,t),g.version!==`v4`&&addPattern(s,zodPatterns.ipv6Cidr,g.message,t);break;case`emoji`:addPattern(s,zodPatterns.emoji(),g.message,t);break;case`ulid`:addPattern(s,zodPatterns.ulid,g.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:addFormat(s,`binary`,g.message,t);break;case`contentEncoding:base64`:setResponseValueAndErrors(s,`contentEncoding`,`base64`,g.message,t);break;case`pattern:zod`:addPattern(s,zodPatterns.base64,g.message,t);break}break;case`nanoid`:addPattern(s,zodPatterns.nanoid,g.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(g)}return s}function escapeLiteralCheckValue(e,t){return t.patternStrategy===`escape`?escapeNonAlphaNumeric(e):e}const ALPHA_NUMERIC=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function escapeNonAlphaNumeric(e){let t=``;for(let s=0;s<e.length;s++)ALPHA_NUMERIC.has(e[s])||(t+=`\\`),t+=e[s];return t}function addFormat(e,t,s,g){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&g.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...s&&g.errorMessages&&{errorMessage:{format:s}}})):setResponseValueAndErrors(e,`format`,t,s,g)}function addPattern(e,t,s,g){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&g.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:stringifyRegExpWithFlags(t,g),...s&&g.errorMessages&&{errorMessage:{pattern:s}}})):setResponseValueAndErrors(e,`pattern`,stringifyRegExpWithFlags(t,g),s,g)}function stringifyRegExpWithFlags(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let s={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},g=s.i?e.source.toLowerCase():e.source,S=``,w=!1,E=!1,D=!1;for(let e=0;e<g.length;e++){if(w){S+=g[e],w=!1;continue}if(s.i){if(E){if(g[e].match(/[a-z]/)){D?(S+=g[e],S+=`${g[e-2]}-${g[e]}`.toUpperCase(),D=!1):g[e+1]===`-`&&g[e+2]?.match(/[a-z]/)?(S+=g[e],D=!0):S+=`${g[e]}${g[e].toUpperCase()}`;continue}}else if(g[e].match(/[a-z]/)){S+=`[${g[e]}${g[e].toUpperCase()}]`;continue}}if(s.m){if(g[e]===`^`){S+=`(^|(?<=[\r
|
|
42
42
|
]))`;continue}else if(g[e]===`$`){S+=`($|(?=[\r
|
|
43
43
|
]))`;continue}}if(s.s&&g[e]===`.`){S+=E?`${g[e]}\r\n`:`[${g[e]}\r\n]`;continue}S+=g[e],g[e]===`\\`?w=!0:E&&g[e]===`]`?E=!1:!E&&g[e]===`[`&&(E=!0)}try{new RegExp(S)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return S}function parseRecordDef(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((s,g)=>({...s,[g]:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,g]})??parseAnyDef(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let s={type:`object`,additionalProperties:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return s;if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.checks?.length){let{type:g,...S}=parseStringDef(e.keyType._def,t);return{...s,propertyNames:S}}else if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{...s,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&e.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.type._def.checks?.length){let{type:g,...S}=parseBrandedDef(e.keyType._def,t);return{...s,propertyNames:S}}return s}function parseMapDef(e,t){return t.mapStrategy===`record`?parseRecordDef(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[parseDef(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||parseAnyDef(t),parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||parseAnyDef(t)],minItems:2,maxItems:2}}}function parseNativeEnumDef(e){let t=e.values,s=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),g=Array.from(new Set(s.map(e=>typeof e)));return{type:g.length===1?g[0]===`string`?`string`:`number`:[`string`,`number`],enum:s}}function parseNeverDef(e){return e.target===`openAi`?void 0:{not:parseAnyDef({...e,currentPath:[...e.currentPath,`not`]})}}function parseNullDef(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const primitiveMappings={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function parseUnionDef(e,t){if(t.target===`openApi3`)return asAnyOf(e,t);let s=e.options instanceof Map?Array.from(e.options.values()):e.options;if(s.every(e=>e._def.typeName in primitiveMappings&&(!e._def.checks||!e._def.checks.length))){let e=s.reduce((e,t)=>{let s=primitiveMappings[t._def.typeName];return s&&!e.includes(s)?[...e,s]:e},[]);return{type:e.length>1?e:e[0]}}else if(s.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=s.reduce((e,t)=>{let s=typeof t._def.value;switch(s){case`string`:case`number`:case`boolean`:return[...e,s];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===s.length){let t=e.filter((e,t,s)=>s.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:s.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(s.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:s.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return asAnyOf(e,t)}const asAnyOf=(e,t)=>{let s=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,s)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${s}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return s.length?{anyOf:s}:void 0};function parseNullableDef(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:primitiveMappings[e.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let s=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath]});return s&&`$ref`in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}let s=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return s&&{anyOf:[s,{type:`null`}]}}function parseNumberDef(e,t){let s={type:`number`};if(!e.checks)return s;for(let g of e.checks)switch(g.kind){case`int`:s.type=`integer`,addErrorMessage(s,`type`,g.message,t);break;case`min`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`minimum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMinimum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMinimum=!0),setResponseValueAndErrors(s,`minimum`,g.value,g.message,t));break;case`max`:t.target===`jsonSchema7`?g.inclusive?setResponseValueAndErrors(s,`maximum`,g.value,g.message,t):setResponseValueAndErrors(s,`exclusiveMaximum`,g.value,g.message,t):(g.inclusive||(s.exclusiveMaximum=!0),setResponseValueAndErrors(s,`maximum`,g.value,g.message,t));break;case`multipleOf`:setResponseValueAndErrors(s,`multipleOf`,g.value,g.message,t);break}return s}function parseObjectDef(e,t){let s=t.target===`openAi`,g={type:`object`,properties:{}},S=[],w=e.shape();for(let e in w){let E=w[e];if(E===void 0||E._def===void 0)continue;let D=safeIsOptional(E);D&&s&&(E._def.typeName===`ZodOptional`&&(E=E._def.innerType),E.isNullable()||(E=E.nullable()),D=!1);let O=parseDef(E._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});O!==void 0&&(g.properties[e]=O,D||S.push(e))}S.length&&(g.required=S);let E=decideAdditionalProperties(e,t);return E!==void 0&&(g.additionalProperties=E),g}function decideAdditionalProperties(e,t){if(e.catchall._def.typeName!==`ZodNever`)return parseDef(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function safeIsOptional(e){try{return e.isOptional()}catch{return!0}}const parseOptionalDef=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return parseDef(e.innerType._def,t);let s=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return s?{anyOf:[{not:parseAnyDef(t)},s]}:parseAnyDef(t)},parsePipelineDef=(e,t)=>{if(t.pipeStrategy===`input`)return parseDef(e.in._def,t);if(t.pipeStrategy===`output`)return parseDef(e.out._def,t);let s=parseDef(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[s,parseDef(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,s?`1`:`0`]})].filter(e=>e!==void 0)}};function parsePromiseDef(e,t){return parseDef(e.type._def,t)}function parseSetDef(e,t){let s={type:`array`,uniqueItems:!0,items:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&setResponseValueAndErrors(s,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&setResponseValueAndErrors(s,`maxItems`,e.maxSize.value,e.maxSize.message,t),s}function parseTupleDef(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,s)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`items`,`${s}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:parseDef(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,s)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`items`,`${s}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function parseUndefinedDef(e){return{not:parseAnyDef(e)}}function parseUnknownDef(e){return parseAnyDef(e)}const parseReadonlyDef=(e,t)=>parseDef(e.innerType._def,t),selectParser=(e,t,s)=>{switch(t){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(e,s);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(e,s);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(e,s);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(e,s);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(e,s);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef(s);case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(s);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(e,s);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(e,s);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(e,s);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(e,s);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(e,s);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(e,s);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(e);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(e);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(e,s);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(e,s);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(e,s);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(e,s);case ZodFirstPartyTypeKind.ZodLazy:return()=>e.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(e,s);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef(s);case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(e,s);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef(s);case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef(s);case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(e,s);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(e,s);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(e,s);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(e,s);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(e,s);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:return;default:return(e=>void 0)(t)}};function parseDef(e,t,s=!1){let g=t.seen.get(e);if(t.override){let S=t.override?.(e,t,g,s);if(S!==ignoreOverride)return S}if(g&&!s){let e=get$ref(g,t);if(e!==void 0)return e}let S={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,S);let w=selectParser(e,e.typeName,t),E=typeof w==`function`?parseDef(w(),t):w;if(E&&addMeta(e,t,E),t.postProcess){let s=t.postProcess(E,e,t);return S.jsonSchema=E,s}return S.jsonSchema=E,E}const get$ref=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:getRelativePath(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,s)=>t.currentPath[s]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),parseAnyDef(t)):t.$refStrategy===`seen`?parseAnyDef(t):void 0}},addMeta=(e,t,s)=>(e.description&&(s.description=e.description,t.markdownDescription&&(s.markdownDescription=e.description)),s),zodToJsonSchema=(e,t)=>{let s=getRefs(t),g=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,g])=>({...e,[t]:parseDef(g._def,{...s,currentPath:[...s.basePath,s.definitionPath,t]},!0)??parseAnyDef(s)}),{}):void 0,S=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,w=parseDef(e._def,S===void 0?s:{...s,currentPath:[...s.basePath,s.definitionPath,S]},!1)??parseAnyDef(s),E=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;E!==void 0&&(w.title=E),s.flags.hasReferencedOpenAiAnyType&&(g||={},g[s.openAiAnyTypeName]||(g[s.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:s.$refStrategy===`relative`?`1`:[...s.basePath,s.definitionPath,s.openAiAnyTypeName].join(`/`)}}));let D=S===void 0?g?{...w,[s.definitionPath]:g}:w:{$ref:[...s.$refStrategy===`relative`?[]:s.basePath,s.definitionPath,S].join(`/`),[s.definitionPath]:{...g,[S]:w}};return s.target===`jsonSchema7`?D.$schema=`http://json-schema.org/draft-07/schema#`:(s.target===`jsonSchema2019-09`||s.target===`openAi`)&&(D.$schema=`https://json-schema.org/draft/2019-09/schema#`),s.target===`openAi`&&(`anyOf`in D||`oneOf`in D||`allOf`in D||`type`in D&&Array.isArray(D.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),D};function mapMiniTarget(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function toJsonSchemaCompat(e,t){return isZ4Schema(e)?toJSONSchema(e,{target:mapMiniTarget(t?.target),io:t?.pipeStrategy??`input`}):zodToJsonSchema(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function getMethodLiteral(e){let t=getObjectShape(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let s=getLiteralValue(t);if(typeof s!=`string`)throw Error(`Schema method literal must be a string`);return s}function parseWithCompat(e,t){let s=safeParse(e,t);if(!s.success)throw s.error;return s.data}const DEFAULT_REQUEST_TIMEOUT_MSEC=6e4;var Protocol=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(CancelledNotificationSchema,e=>{this._oncancel(e)}),this.setNotificationHandler(ProgressNotificationSchema,e=>{this._onprogress(e)}),this.setRequestHandler(PingRequestSchema,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(GetTaskRequestSchema,async(e,t)=>{let s=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!s)throw new McpError(ErrorCode.InvalidParams,`Failed to retrieve task: Task not found`);return{...s}}),this.setRequestHandler(GetTaskPayloadRequestSchema,async(e,t)=>{let s=async()=>{let g=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(g,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,s=t.id,g=this._requestResolvers.get(s);if(g)if(this._requestResolvers.delete(s),e.type===`response`)g(t);else{let e=t;g(new McpError(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${s}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let S=await this._taskStore.getTask(g,t.sessionId);if(!S)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${g}`);if(!isTerminal(S.status))return await this._waitForTaskUpdate(g,t.signal),await s();if(isTerminal(S.status)){let e=await this._taskStore.getTaskResult(g,t.sessionId);return this._clearTaskQueue(g),{...e,_meta:{...e._meta,[RELATED_TASK_META_KEY]:{taskId:g}}}}return await s()};return await s()}),this.setRequestHandler(ListTasksRequestSchema,async(e,t)=>{try{let{tasks:s,nextCursor:g}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:s,nextCursor:g,_meta:{}}}catch(e){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(CancelTaskRequestSchema,async(e,t)=>{try{let s=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!s)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${e.params.taskId}`);if(isTerminal(s.status))throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let g=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!g)throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...g}}catch(e){throw e instanceof McpError?e:new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,s,g,S=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(g,t),startTime:Date.now(),timeout:t,maxTotalTimeout:s,resetTimeoutOnProgress:S,onTimeout:g})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let s=Date.now()-t.startTime;if(t.maxTotalTimeout&&s>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),McpError.fromError(ErrorCode.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:s});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let s=this.transport?.onerror;this._transport.onerror=e=>{s?.(e),this._onerror(e)};let g=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{g?.(e,t),isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e)?this._onresponse(e):isJSONRPCRequest(e)?this._onrequest(e,t):isJSONRPCNotification(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=McpError.fromError(ErrorCode.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let s of e.values())s(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let s=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,g=this._transport,S=e.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;if(s===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:ErrorCode.MethodNotFound,message:`Method not found`}};S&&this._taskMessageQueue?this._enqueueTaskMessage(S,{type:`error`,message:t,timestamp:Date.now()},g?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):g?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let w=new AbortController;this._requestHandlerAbortControllers.set(e.id,w);let E=isTaskAugmentedRequestParams(e.params)?e.params.task:void 0,D=this._taskStore?this.requestTaskStore(e,g?.sessionId):void 0,O={signal:w.signal,sessionId:g?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(w.signal.aborted)return;let s={relatedRequestId:e.id};S&&(s.relatedTask={taskId:S}),await this.notification(t,s)},sendRequest:async(t,s,g)=>{if(w.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,`Request was cancelled`);let E={...g,relatedRequestId:e.id};S&&!E.relatedTask&&(E.relatedTask={taskId:S});let O=E.relatedTask?.taskId??S;return O&&D&&await D.updateTaskStatus(O,`input_required`),await this.request(t,s,E)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:S,taskStore:D,taskRequestedTtl:E?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{E&&this.assertTaskHandlerCapability(e.method)}).then(()=>s(e,O)).then(async t=>{if(w.signal.aborted)return;let s={result:t,jsonrpc:`2.0`,id:e.id};S&&this._taskMessageQueue?await this._enqueueTaskMessage(S,{type:`response`,message:s,timestamp:Date.now()},g?.sessionId):await g?.send(s)},async t=>{if(w.signal.aborted)return;let s={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:ErrorCode.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};S&&this._taskMessageQueue?await this._enqueueTaskMessage(S,{type:`error`,message:s,timestamp:Date.now()},g?.sessionId):await g?.send(s)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===w&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...s}=e.params,g=Number(t),S=this._progressHandlers.get(g);if(!S){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let w=this._responseHandlers.get(g),E=this._timeoutInfo.get(g);if(E&&w&&E.resetTimeoutOnProgress)try{this._resetTimeout(g)}catch(e){this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),w(e);return}S(s)}_onresponse(e){let t=Number(e.id),s=this._requestResolvers.get(t);if(s){this._requestResolvers.delete(t),isJSONRPCResultResponse(e)?s(e):s(new McpError(e.error.code,e.error.message,e.error.data));return}let g=this._responseHandlers.get(t);if(g===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let S=!1;if(isJSONRPCResultResponse(e)&&e.result&&typeof e.result==`object`){let s=e.result;if(s.task&&typeof s.task==`object`){let e=s.task;typeof e.taskId==`string`&&(S=!0,this._taskProgressTokens.set(e.taskId,t))}}S||this._progressHandlers.delete(t),isJSONRPCResultResponse(e)?g(e):g(McpError.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,s){let{task:g}=s??{};if(!g){try{yield{type:`result`,result:await this.request(e,t,s)}}catch(e){yield{type:`error`,error:e instanceof McpError?e:new McpError(ErrorCode.InternalError,String(e))}}return}let S;try{let g=await this.request(e,CreateTaskResultSchema,s);if(g.task)S=g.task.taskId,yield{type:`taskCreated`,task:g.task};else throw new McpError(ErrorCode.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:S},s);if(yield{type:`taskStatus`,task:e},isTerminal(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:S},t,s)}:e.status===`failed`?yield{type:`error`,error:new McpError(ErrorCode.InternalError,`Task ${S} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new McpError(ErrorCode.InternalError,`Task ${S} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:S},t,s)};return}let g=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,g)),s?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof McpError?e:new McpError(ErrorCode.InternalError,String(e))}}}request(e,t,s){let{relatedRequestId:g,resumptionToken:S,onresumptiontoken:w,task:E,relatedTask:D}=s??{};return new Promise((O,k)=>{let j=e=>{k(e)};if(!this._transport){j(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),E&&this.assertTaskCapability(e.method)}catch(e){j(e);return}s?.signal?.throwIfAborted();let F=this._requestMessageId++,L={...e,jsonrpc:`2.0`,id:F};s?.onprogress&&(this._progressHandlers.set(F,s.onprogress),L.params={...e.params,_meta:{...e.params?._meta||{},progressToken:F}}),E&&(L.params={...L.params,task:E}),D&&(L.params={...L.params,_meta:{...L.params?._meta||{},[RELATED_TASK_META_KEY]:D}});let B=e=>{this._responseHandlers.delete(F),this._progressHandlers.delete(F),this._cleanupTimeout(F),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:F,reason:String(e)}},{relatedRequestId:g,resumptionToken:S,onresumptiontoken:w}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),k(e instanceof McpError?e:new McpError(ErrorCode.RequestTimeout,String(e)))};this._responseHandlers.set(F,e=>{if(!s?.signal?.aborted){if(e instanceof Error)return k(e);try{let s=safeParse(t,e.result);s.success?O(s.data):k(s.error)}catch(e){k(e)}}}),s?.signal?.addEventListener(`abort`,()=>{B(s?.signal?.reason)});let H=s?.timeout??6e4;this._setupTimeout(F,H,s?.maxTotalTimeout,()=>B(McpError.fromError(ErrorCode.RequestTimeout,`Request timed out`,{timeout:H})),s?.resetTimeoutOnProgress??!1);let q=D?.taskId;q?(this._requestResolvers.set(F,e=>{let t=this._responseHandlers.get(F);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${F}`))}),this._enqueueTaskMessage(q,{type:`request`,message:L,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(F),k(e)})):this._transport.send(L,{relatedRequestId:g,resumptionToken:S,onresumptiontoken:w}).catch(e=>{this._cleanupTimeout(F),k(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},GetTaskResultSchema,t)}async getTaskResult(e,t,s){return this.request({method:`tasks/result`,params:e},t,s)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},ListTasksResultSchema,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},CancelTaskResultSchema,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let s=t?.relatedTask?.taskId;if(s){let g={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[RELATED_TASK_META_KEY]:t.relatedTask}}};await this._enqueueTaskMessage(s,{type:`notification`,message:g,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:`2.0`};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[RELATED_TASK_META_KEY]:t.relatedTask}}}),this._transport?.send(s,t).catch(e=>this._onerror(e))});return}let g={...e,jsonrpc:`2.0`};t?.relatedTask&&(g={...g,params:{...g.params,_meta:{...g.params?._meta||{},[RELATED_TASK_META_KEY]:t.relatedTask}}}),await this._transport.send(g,t)}setRequestHandler(e,t){let s=getMethodLiteral(e);this.assertRequestHandlerCapability(s),this._requestHandlers.set(s,(s,g)=>{let S=parseWithCompat(e,s);return Promise.resolve(t(S,g))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let s=getMethodLiteral(e);this._notificationHandlers.set(s,s=>{let g=parseWithCompat(e,s);return Promise.resolve(t(g))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,s){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let g=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,s,g)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let s=await this._taskMessageQueue.dequeueAll(e,t);for(let t of s)if(t.type===`request`&&isJSONRPCRequest(t.message)){let s=t.message.id,g=this._requestResolvers.get(s);g?(g(new McpError(ErrorCode.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(s)):this._onerror(Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let s=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(s=t.pollInterval)}catch{}return new Promise((e,g)=>{if(t.aborted){g(new McpError(ErrorCode.InvalidRequest,`Request cancelled`));return}let S=setTimeout(e,s);t.addEventListener(`abort`,()=>{clearTimeout(S),g(new McpError(ErrorCode.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let s=this._taskStore;if(!s)throw Error(`No task store configured`);return{createTask:async g=>{if(!e)throw Error(`No request provided`);return await s.createTask(g,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let g=await s.getTask(e,t);if(!g)throw new McpError(ErrorCode.InvalidParams,`Failed to retrieve task: Task not found`);return g},storeTaskResult:async(e,g,S)=>{await s.storeTaskResult(e,g,S,t);let w=await s.getTask(e,t);if(w){let t=TaskStatusNotificationSchema.parse({method:`notifications/tasks/status`,params:w});await this.notification(t),isTerminal(w.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>s.getTaskResult(e,t),updateTaskStatus:async(e,g,S)=>{let w=await s.getTask(e,t);if(!w)throw new McpError(ErrorCode.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(isTerminal(w.status))throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${e}" from terminal status "${w.status}" to "${g}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await s.updateTaskStatus(e,g,S,t);let E=await s.getTask(e,t);if(E){let t=TaskStatusNotificationSchema.parse({method:`notifications/tasks/status`,params:E});await this.notification(t),isTerminal(E.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>s.listTasks(e,t)}}};function isPlainObject$1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mergeCapabilities(e,t){let s={...e};for(let e in t){let g=e,S=t[g];if(S===void 0)continue;let w=s[g];isPlainObject$1(w)&&isPlainObject$1(S)?s[g]={...w,...S}:s[g]=S}return s}var require_code$1=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var s=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=s;var g=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){var e;return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){var e;return this._names??=this._items.reduce((e,t)=>(t instanceof s&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=g,e.nil=new g(``);function S(e,...t){let s=[e[0]],S=0;for(;S<t.length;)D(s,t[S]),s.push(e[++S]);return new g(s)}e._=S;let w=new g(`+`);function E(e,...t){let s=[B(e[0])],S=0;for(;S<t.length;)s.push(w),D(s,t[S]),s.push(w,B(e[++S]));return O(s),new g(s)}e.str=E;function D(e,t){t instanceof g?e.push(...t._items):t instanceof s?e.push(t):e.push(F(t))}e.addCodeArg=D;function O(e){let t=1;for(;t<e.length-1;){if(e[t]===w){let s=k(e[t-1],e[t+1]);if(s!==void 0){e.splice(t-1,3,s);continue}e[t++]=`+`}t++}}function k(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof s||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof s))return`"${e}${t.slice(1)}`}function j(e,t){return t.emptyStr()?e:e.emptyStr()?t:E`${e}${t}`}e.strConcat=j;function F(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:B(Array.isArray(e)?e.join(`,`):e)}function L(e){return new g(B(e))}e.stringify=L;function B(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=B;function H(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new g(`.${t}`):S`[${t}]`}e.getProperty=H;function q(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new g(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=q;function ee(e){return new g(e.toString())}e.regexpCode=ee})),require_scope=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=require_code$1();var s=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},g;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(g||(e.UsedValueState=g={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var S=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,s;if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=S;var w=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:s,itemIndex:g}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(s)}[${g}]`}};e.ValueScopeName=w;let E=(0,t._)`\n`;e.ValueScope=class extends S{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?E:t.nil}}get(){return this._scope}name(e){return new w(e,this._newName(e))}value(e,t){var s;if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let g=this.toName(e),{prefix:S}=g,w=t.key??t.ref,E=this._values[S];if(E){let e=E.get(w);if(e)return e}else E=this._values[S]=new Map;E.set(w,g);let D=this._scope[S]||(this._scope[S]=[]),O=D.length;return D[O]=t.ref,g.setValue(t,{property:S,itemIndex:O}),g}getValue(e,t){let s=this._values[e];if(s)return s.get(t)}scopeRefs(e,s=this._values){return this._reduceValues(s,s=>{if(s.scopePath===void 0)throw Error(`CodeGen: name "${s}" has no value`);return(0,t._)`${e}${s.scopePath}`})}scopeCode(e=this._values,t,s){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,s)}_reduceValues(S,w,E={},D){let O=t.nil;for(let k in S){let j=S[k];if(!j)continue;let F=E[k]=E[k]||new Map;j.forEach(S=>{if(F.has(S))return;F.set(S,g.Started);let E=w(S);if(E){let s=this.opts.es5?e.varKinds.var:e.varKinds.const;O=(0,t._)`${O}${s} ${S} = ${E};${this.opts._n}`}else if(E=D?.(S))O=(0,t._)`${O}${E}${this.opts._n}`;else throw new s(S);F.set(S,g.Completed)})}return O}}})),require_codegen=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=require_code$1(),s=require_scope();var g=require_code$1();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return g._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return g.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return g.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return g.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return g.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return g.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return g.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return g.Name}});var S=require_scope();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return S.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return S.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return S.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return S.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var w=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},E=class extends w{constructor(e,t,s){super(),this.varKind=e,this.name=t,this.rhs=s}render({es5:e,_n:t}){let g=e?s.varKinds.var:this.varKind,S=this.rhs===void 0?``:` = ${this.rhs}`;return`${g} ${this.name}${S};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=ge(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},D=class extends w{constructor(e,t,s){super(),this.lhs=e,this.rhs=t,this.sideEffects=s}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,s){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ge(this.rhs,e,s),this}get names(){return me(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},O=class extends D{constructor(e,t,s,g){super(e,s,g),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},k=class extends w{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},j=class extends w{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},F=class extends w{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},L=class extends w{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ge(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},B=class extends w{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,s)=>t+s.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let s=e[t].optimizeNodes();Array.isArray(s)?e.splice(t,1,...s):s?e[t]=s:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:s}=this,g=s.length;for(;g--;){let S=s[g];S.optimizeNames(e,t)||(_e(e,S.names),s.splice(g,1))}return s.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>fe(e,t.names),{})}},H=class extends B{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},q=class extends B{},ee=class extends H{};ee.kind=`else`;var J=class e extends H{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let s=this.else;if(s){let e=s.optimizeNodes();s=this.else=Array.isArray(e)?new ee(e):e}if(s)return t===!1?s instanceof e?s:s.nodes:this.nodes.length?this:new e(ve(t),s instanceof e?[s]:s.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){var s;if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=ge(this.condition,e,t),this}get names(){let e=super.names;return me(e,this.condition),this.else&&fe(e,this.else.names),e}};J.kind=`if`;var Y=class extends H{};Y.kind=`for`;var te=class extends Y{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=ge(this.iteration,e,t),this}get names(){return fe(super.names,this.iteration.names)}},ne=class extends Y{constructor(e,t,s,g){super(),this.varKind=e,this.name=t,this.from=s,this.to=g}render(e){let t=e.es5?s.varKinds.var:this.varKind,{name:g,from:S,to:w}=this;return`for(${t} ${g}=${S}; ${g}<${w}; ${g}++)`+super.render(e)}get names(){return me(me(super.names,this.from),this.to)}},ae=class extends Y{constructor(e,t,s,g){super(),this.loop=e,this.varKind=t,this.name=s,this.iterable=g}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=ge(this.iterable,e,t),this}get names(){return fe(super.names,this.iterable.names)}},oe=class extends H{constructor(e,t,s){super(),this.name=e,this.args=t,this.async=s}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};oe.kind=`func`;var se=class extends B{render(e){return`return `+super.render(e)}};se.kind=`return`;var ce=class extends H{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var s,g;return super.optimizeNames(e,t),(s=this.catch)==null||s.optimizeNames(e,t),(g=this.finally)==null||g.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&fe(e,this.catch.names),this.finally&&fe(e,this.finally.names),e}},ue=class extends H{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ue.kind=`catch`;var de=class extends H{render(e){return`finally`+super.render(e)}};de.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
44
44
|
`:``},this._extScope=e,this._scope=new s.Scope({parent:e}),this._nodes=[new q]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let s=this._extScope.value(e,t);return(this._values[s.prefix]||(this._values[s.prefix]=new Set)).add(s),s}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,s,g){let S=this._scope.toName(t);return s!==void 0&&g&&(this._constants[S.str]=s),this._leafNode(new E(e,S,s)),S}const(e,t,g){return this._def(s.varKinds.const,e,t,g)}let(e,t,g){return this._def(s.varKinds.let,e,t,g)}var(e,t,g){return this._def(s.varKinds.var,e,t,g)}assign(e,t,s){return this._leafNode(new D(e,t,s))}add(t,s){return this._leafNode(new O(t,e.operators.ADD,s))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new L(e)),this}object(...e){let s=[`{`];for(let[g,S]of e)s.length>1&&s.push(`,`),s.push(g),(g!==S||this.opts.es5)&&(s.push(`:`),(0,t.addCodeArg)(s,S));return s.push(`}`),new t._Code(s)}if(e,t,s){if(this._blockNode(new J(e)),t&&s)this.code(t).else().code(s).endIf();else if(t)this.code(t).endIf();else if(s)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new J(e))}else(){return this._elseNode(new ee)}endIf(){return this._endBlockNode(J,ee)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new te(e),t)}forRange(e,t,g,S,w=this.opts.es5?s.varKinds.var:s.varKinds.let){let E=this._scope.toName(e);return this._for(new ne(w,E,t,g),()=>S(E))}forOf(e,g,S,w=s.varKinds.const){let E=this._scope.toName(e);if(this.opts.es5){let e=g instanceof t.Name?g:this.var(`_arr`,g);return this.forRange(`_i`,0,(0,t._)`${e}.length`,s=>{this.var(E,(0,t._)`${e}[${s}]`),S(E)})}return this._for(new ae(`of`,w,E,g),()=>S(E))}forIn(e,g,S,w=this.opts.es5?s.varKinds.var:s.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${g})`,S);let E=this._scope.toName(e);return this._for(new ae(`in`,w,E,g),()=>S(E))}endFor(){return this._endBlockNode(Y)}label(e){return this._leafNode(new k(e))}break(e){return this._leafNode(new j(e))}return(e){let t=new se;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(se)}try(e,t,s){if(!t&&!s)throw Error(`CodeGen: "try" without "catch" and "finally"`);let g=new ce;if(this._blockNode(g),this.code(e),t){let e=this.name(`e`);this._currNode=g.catch=new ue(e),t(e)}return s&&(this._currNode=g.finally=new de,this.code(s)),this._endBlockNode(ue,de)}throw(e){return this._leafNode(new F(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let s=this._nodes.length-t;if(s<0||e!==void 0&&s!==e)throw Error(`CodeGen: wrong number of nodes: ${s} vs ${e} expected`);return this._nodes.length=t,this}func(e,s=t.nil,g,S){return this._blockNode(new oe(e,s,g)),S&&this.code(S).endFunc(),this}endFunc(){return this._endBlockNode(oe)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let s=this._currNode;if(s instanceof e||t&&s instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof J))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function fe(e,t){for(let s in t)e[s]=(e[s]||0)+(t[s]||0);return e}function me(e,s){return s instanceof t._CodeOrName?fe(e,s.names):e}function ge(e,s,g){if(e instanceof t.Name)return S(e);if(!w(e))return e;return new t._Code(e._items.reduce((e,s)=>(s instanceof t.Name&&(s=S(s)),s instanceof t._Code?e.push(...s._items):e.push(s),e),[]));function S(e){let t=g[e.str];return t===void 0||s[e.str]!==1?e:(delete s[e.str],t)}function w(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&s[e.str]===1&&g[e.str]!==void 0)}}function _e(e,t){for(let s in t)e[s]=(e[s]||0)-(t[s]||0)}function ve(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${je(e)}`}e.not=ve;let ye=De(e.operators.AND);function Ce(...e){return e.reduce(ye)}e.and=Ce;let we=De(e.operators.OR);function Te(...e){return e.reduce(we)}e.or=Te;function De(e){return(s,g)=>s===t.nil?g:g===t.nil?s:(0,t._)`${je(s)} ${e} ${je(g)}`}function je(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),require_util=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=require_codegen(),s=require_code$1();function g(e){let t={};for(let s of e)t[s]=!0;return t}e.toHash=g;function S(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(w(e,t),!E(t,e.self.RULES.all))}e.alwaysValidSchema=S;function w(e,t=e.schema){let{opts:s,self:g}=e;if(!s.strictSchema||typeof t==`boolean`)return;let S=g.RULES.keywords;for(let s in t)S[s]||ae(e,`unknown keyword: "${s}"`)}e.checkUnknownRules=w;function E(e,t){if(typeof e==`boolean`)return!e;for(let s in e)if(t[s])return!0;return!1}e.schemaHasRules=E;function D(e,t){if(typeof e==`boolean`)return!e;for(let s in e)if(s!==`$ref`&&t.all[s])return!0;return!1}e.schemaHasRulesButRef=D;function O({topSchemaRef:e,schemaPath:s},g,S,w){if(!w){if(typeof g==`number`||typeof g==`boolean`)return g;if(typeof g==`string`)return(0,t._)`${g}`}return(0,t._)`${e}${s}${(0,t.getProperty)(S)}`}e.schemaRefOrVal=O;function k(e){return L(decodeURIComponent(e))}e.unescapeFragment=k;function j(e){return encodeURIComponent(F(e))}e.escapeFragment=j;function F(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=F;function L(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=L;function B(e,t){if(Array.isArray(e))for(let s of e)t(s);else t(e)}e.eachItem=B;function H({mergeNames:e,mergeToName:s,mergeValues:g,resultToName:S}){return(w,E,D,O)=>{let k=D===void 0?E:D instanceof t.Name?(E instanceof t.Name?e(w,E,D):s(w,E,D),D):E instanceof t.Name?(s(w,D,E),E):g(E,D);return O===t.Name&&!(k instanceof t.Name)?S(w,k):k}}e.mergeEvaluated={props:H({mergeNames:(e,s,g)=>e.if((0,t._)`${g} !== true && ${s} !== undefined`,()=>{e.if((0,t._)`${s} === true`,()=>e.assign(g,!0),()=>e.assign(g,(0,t._)`${g} || {}`).code((0,t._)`Object.assign(${g}, ${s})`))}),mergeToName:(e,s,g)=>e.if((0,t._)`${g} !== true`,()=>{s===!0?e.assign(g,!0):(e.assign(g,(0,t._)`${g} || {}`),ee(e,g,s))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:q}),items:H({mergeNames:(e,s,g)=>e.if((0,t._)`${g} !== true && ${s} !== undefined`,()=>e.assign(g,(0,t._)`${s} === true ? true : ${g} > ${s} ? ${g} : ${s}`)),mergeToName:(e,s,g)=>e.if((0,t._)`${g} !== true`,()=>e.assign(g,s===!0?!0:(0,t._)`${g} > ${s} ? ${g} : ${s}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function q(e,s){if(s===!0)return e.var(`props`,!0);let g=e.var(`props`,(0,t._)`{}`);return s!==void 0&&ee(e,g,s),g}e.evaluatedPropsToName=q;function ee(e,s,g){Object.keys(g).forEach(g=>e.assign((0,t._)`${s}${(0,t.getProperty)(g)}`,!0))}e.setEvaluated=ee;let J={};function Y(e,t){return e.scopeValue(`func`,{ref:t,code:J[t.code]||(J[t.code]=new s._Code(t.code))})}e.useFunc=Y;var te;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(te||(e.Type=te={}));function ne(e,s,g){if(e instanceof t.Name){let S=s===te.Num;return g?S?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:S?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return g?(0,t.getProperty)(e).toString():`/`+F(e)}e.getErrorPath=ne;function ae(e,t,s=e.opts.strictSchema){if(s){if(t=`strict mode: ${t}`,s===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=ae})),require_names=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_codegen();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),require_errors=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=require_codegen(),s=require_util(),g=require_names();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:s})=>s?(0,t.str)`"${e}" keyword must be ${s} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function S(s,g=e.keywordError,S,w){let{it:E}=s,{gen:D,compositeRule:j,allErrors:L}=E,B=F(s,g,S);w??(j||L)?O(D,B):k(E,(0,t._)`[${B}]`)}e.reportError=S;function w(t,s=e.keywordError,S){let{it:w}=t,{gen:E,compositeRule:D,allErrors:j}=w;O(E,F(t,s,S)),D||j||k(w,g.default.vErrors)}e.reportExtraError=w;function E(e,s){e.assign(g.default.errors,s),e.if((0,t._)`${g.default.vErrors} !== null`,()=>e.if(s,()=>e.assign((0,t._)`${g.default.vErrors}.length`,s),()=>e.assign(g.default.vErrors,null)))}e.resetErrorsCount=E;function D({gen:e,keyword:s,schemaValue:S,data:w,errsCount:E,it:D}){if(E===void 0)throw Error(`ajv implementation error`);let O=e.name(`err`);e.forRange(`i`,E,g.default.errors,E=>{e.const(O,(0,t._)`${g.default.vErrors}[${E}]`),e.if((0,t._)`${O}.instancePath === undefined`,()=>e.assign((0,t._)`${O}.instancePath`,(0,t.strConcat)(g.default.instancePath,D.errorPath))),e.assign((0,t._)`${O}.schemaPath`,(0,t.str)`${D.errSchemaPath}/${s}`),D.opts.verbose&&(e.assign((0,t._)`${O}.schema`,S),e.assign((0,t._)`${O}.data`,w))})}e.extendErrors=D;function O(e,s){let S=e.const(`err`,s);e.if((0,t._)`${g.default.vErrors} === null`,()=>e.assign(g.default.vErrors,(0,t._)`[${S}]`),(0,t._)`${g.default.vErrors}.push(${S})`),e.code((0,t._)`${g.default.errors}++`)}function k(e,s){let{gen:g,validateName:S,schemaEnv:w}=e;w.$async?g.throw((0,t._)`new ${e.ValidationError}(${s})`):(g.assign((0,t._)`${S}.errors`,s),g.return(!1))}let j={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function F(e,s,g){let{createErrors:S}=e.it;return S===!1?(0,t._)`{}`:L(e,s,g)}function L(e,t,s={}){let{gen:g,it:S}=e,w=[B(S,s),H(e,s)];return q(e,t,w),g.object(...w)}function B({errorPath:e},{instancePath:S}){let w=S?(0,t.str)`${e}${(0,s.getErrorPath)(S,s.Type.Str)}`:e;return[g.default.instancePath,(0,t.strConcat)(g.default.instancePath,w)]}function H({keyword:e,it:{errSchemaPath:g}},{schemaPath:S,parentSchema:w}){let E=w?g:(0,t.str)`${g}/${e}`;return S&&(E=(0,t.str)`${E}${(0,s.getErrorPath)(S,s.Type.Str)}`),[j.schemaPath,E]}function q(e,{params:s,message:S},w){let{keyword:E,data:D,schemaValue:O,it:k}=e,{opts:F,propertyName:L,topSchemaRef:B,schemaPath:H}=k;w.push([j.keyword,E],[j.params,typeof s==`function`?s(e):s||(0,t._)`{}`]),F.messages&&w.push([j.message,typeof S==`function`?S(e):S]),F.verbose&&w.push([j.schema,O],[j.parentSchema,(0,t._)`${B}${H}`],[g.default.data,D]),L&&w.push([j.propertyName,L])}})),require_boolSchema=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=require_errors(),s=require_codegen(),g=require_names(),S={message:`boolean schema is false`};function w(e){let{gen:t,schema:S,validateName:w}=e;S===!1?D(e,!1):typeof S==`object`&&S.$async===!0?t.return(g.default.data):(t.assign((0,s._)`${w}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=w;function E(e,t){let{gen:s,schema:g}=e;g===!1?(s.var(t,!1),D(e)):s.var(t,!0)}e.boolOrEmptySchema=E;function D(e,s){let{gen:g,data:w}=e,E={gen:g,keyword:`false schema`,data:w,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(E,S,void 0,s)}})),require_rules=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function s(e){return typeof e==`string`&&t.has(e)}e.isJSONType=s;function g(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=g})),require_applicability=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},g){let S=t.RULES.types[g];return S&&S!==!0&&s(e,S)}e.schemaHasRulesForType=t;function s(e,t){return t.rules.some(t=>g(e,t))}e.shouldUseGroup=s;function g(e,t){var s;return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=g})),require_dataType=__commonJSMin$2((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=require_rules(),s=require_applicability(),g=require_errors(),S=require_codegen(),w=require_util();var E;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(E||(e.DataType=E={}));function D(e){let t=O(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=D;function O(e){let s=Array.isArray(e)?e:e?[e]:[];if(s.every(t.isJSONType))return s;throw Error(`type must be JSONType or JSONType[]: `+s.join(`,`))}e.getJSONTypes=O;function k(e,t){let{gen:g,data:S,opts:w}=e,D=F(t,w.coerceTypes),O=t.length>0&&!(D.length===0&&t.length===1&&(0,s.schemaHasRulesForType)(e,t[0]));if(O){let s=q(t,S,w.strictNumbers,E.Wrong);g.if(s,()=>{D.length?L(e,t,D):J(e)})}return O}e.coerceAndCheckDataType=k;let j=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function F(e,t){return t?e.filter(e=>j.has(e)||t===`array`&&e===`array`):[]}function L(e,t,s){let{gen:g,data:w,opts:E}=e,D=g.let(`dataType`,(0,S._)`typeof ${w}`),O=g.let(`coerced`,(0,S._)`undefined`);E.coerceTypes===`array`&&g.if((0,S._)`${D} == 'object' && Array.isArray(${w}) && ${w}.length == 1`,()=>g.assign(w,(0,S._)`${w}[0]`).assign(D,(0,S._)`typeof ${w}`).if(q(t,w,E.strictNumbers),()=>g.assign(O,w))),g.if((0,S._)`${O} !== undefined`);for(let e of s)(j.has(e)||e===`array`&&E.coerceTypes===`array`)&&k(e);g.else(),J(e),g.endIf(),g.if((0,S._)`${O} !== undefined`,()=>{g.assign(w,O),B(e,O)});function k(e){switch(e){case`string`:g.elseIf((0,S._)`${D} == "number" || ${D} == "boolean"`).assign(O,(0,S._)`"" + ${w}`).elseIf((0,S._)`${w} === null`).assign(O,(0,S._)`""`);return;case`number`:g.elseIf((0,S._)`${D} == "boolean" || ${w} === null
|
|
@@ -1937,7 +1937,7 @@ Change history for this knowledge base, newest entry first. Add a dated entry (\
|
|
|
1937
1937
|
`)){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(`
|
|
1938
1938
|
`)}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,`${e}${getDocExtension(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$6.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$6.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=isSupportedDocFile(e)?e:`${e}${getDocExtension(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$6.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){let g=new Map;for(let s of e){let e=t.documents.get(s);e&&g.set(s,e.getText(`source`).toString())}for(let t of e)await s.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let s of e){let e=t.documents.get(s);deleteReconciledBase(s),ze?.(s),e&&(t.closeConnections(s),await(Me??t.unloadDocument.bind(t))(e))}return g}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=`${s}${getDocExtension(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=stripDocExtension(E);registerDocExtension(D,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])).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`?[stripDocExtension(e)]:Hi(k)).map(t=>({from:t,to:S===`file`?stripDocExtension(s):remapDocNameForRename(t,S,e,s)}));if(D.setAttribute(`rename.affected_docs`,B.length),B.length===0){let t=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()]);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})=>e!==t);t.length>0&&withSpanSync(`rename.appendLog`,{attributes:{"rename.kind":S}},s=>{let g=randomUUID$1(),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=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$6.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$6.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(`
|
|
1939
1939
|
`),S=s.nextFenced+(g?`
|
|
1940
|
-
`:``)+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$6.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$6.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,getDocExtension,maxEntries:t,maxDepth:O,signal:e.signal}),E=0,D=await s.next();for(;!D.done;)await w(`${JSON.stringify(D.value)}\n`),E+=1,D=await s.next();let{truncated:k}=D.value;k&&log$6.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$6.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,getDocExtension,maxEntries:s,maxDepth:O,signal:t.signal});return e.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),w&&log$6.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$6.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$6.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$6.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$6.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$6.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$6.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$6.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:`${S.docName}${getDocExtension(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$6.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$6.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$6.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$6.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=se?.();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function 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$6.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$6.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$6.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$6.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=w===`file`?stripDocExtension(S.path):S.path;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(E)||isConfigDoc(E))||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 D=resolveContentEntryPath(g,w,E);if(!existsSync(D)){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 k=statSync(D);if(w===`file`&&!k.isFile()||w===`folder`&&!k.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}let j=w===`file`?[E]:Hi(resolveContentEntryPath(g,`folder`,E)),F=ve?.(),L=new Set(F?F.getConflicts().map(e=>e.file):[]);for(let e of j){let g=stripDocExtension(e),S=t.documents.get(g),w=`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),D=L.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let B,H=[];if(w===`file`){let e=extname(D);if(B=nextAvailableDuplicateDocName(g,E).docName,isSystemDoc(B)||isConfigDoc(B)||De?.isExcluded(`${B}${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,B,e),S=readFileSync(D,`utf-8`),w=dirname(t),k=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(!k)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(B,e),Ie?.delete(B),De&&(De.incrementMdDir(dirname(B)),j=!0),registerWrite(t,contentHash(S)),O?.({kind:`create`,path:t,docName:B,content:S}),ue?.updateDocumentFromMarkdown(B,S),H=[B]}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(B),De&&j&&De.decrementMdDir(dirname(B)),O?.({kind:`delete`,path:t,docName:B}),e}}else{if(B=nextAvailableDuplicateFolderPath(g,E).folderPath,De?.isDirExcluded(B)){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`,B);try{tracedCpSync(D,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,B))it(e);let e=collectMarkdownCopies(g,B);H=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(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 H)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&&H.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:B,duplicatedDocNames:H},{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$6.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}let k=O===`file`?[stripDocExtension(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=stripDocExtension(e),S=t.documents.get(g),w=O===`file`?E:`${g}${getDocExtension(e)}`,D=S!==void 0&&isDocInConflict(S),k=F.has(w);if(D||k){respondDocInConflict(s,new DocInConflictError({file:w}),`rename-path`);return}}if(O===`file`&&probeAndRegisterSourceFileExtension(g,E),De&&(O===`file`?De.isExcluded(isSupportedDocFile(D)?D:`${D}${getDocExtension(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$6.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`?[stripDocExtension(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=stripDocExtension(e),S=t.documents.get(g),w=k===`file`&&isSupportedDocFile(D)?D:`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),O=H.has(w);if(E||O){respondDocInConflict(s,new DocInConflictError({file:w}),`delete-path`);return}}if(await Vr(L),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,`${e}${getDocExtension(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),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,`${e}${getDocExtension(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=t,w,E=getDocExtension(t);try{let s=readFileSync(resolve(g,`${t}${E}`),`utf-8`);e=extractPageTitle(s,t),w=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}s.push({docName:t,title:e,docExt:E,size:S.size,modified:S.modified,icon:w})}s.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:s},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),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$6.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$6.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=await fileTypeFromFile(w),ae=ne?.mime,oe=ne?.ext;if(!ae){let e=readTempFileHead(w,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(ae=`image/svg+xml`,oe=`svg`)}{let s=await findDuplicateAsset(te,D,O);if(s){F();let S=toPosix(relative(g,resolve(te,s)));log$6.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!0,mime:ae??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 se;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=oe??t??``;se=s===``?`pasted-${e}`:`pasted-${e}.${s}`}else se=sanitizeFilename(S);try{let s=linkTempToFinalWithCollisionRetry(w,te,se),S=toPosix(relative(g,resolve(te,s)));log$6.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,dedup:!1,mime:ae??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$6.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:q,agentName:ee,filename:se,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$6.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$6.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$6.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$6.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(`
|
|
1940
|
+
`:``)+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$6.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$6.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,getDocExtension,maxEntries:t,maxDepth:O,signal:e.signal}),E=0,D=await s.next();for(;!D.done;)await w(`${JSON.stringify(D.value)}\n`),E+=1,D=await s.next();let{truncated:k}=D.value;k&&log$6.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$6.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,getDocExtension,maxEntries:s,maxDepth:O,signal:t.signal});return e.sort((e,t)=>{let s=e.kind===`folder`?e.path??``:e.docName??e.path??``,g=t.kind===`folder`?t.path??``:t.docName??t.path??``;return s.localeCompare(g)}),w&&log$6.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$6.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$6.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$6.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$6.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$6.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$6.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$6.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:`${S.docName}${getDocExtension(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$6.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$6.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$6.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$6.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=getActiveBranch(),s=se?.();successResponse(t,200,ServerInfoSuccessSchema,{serverInstanceId:S,currentBranch:e,...s===void 0?{}:{currentDiskAckSVs:s}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function 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$6.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$6.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$6.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$6.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=w===`file`?stripDocExtension(S.path):S.path;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(E)||isConfigDoc(E))||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 D=resolveContentEntryPath(g,w,E);if(!existsSync(D)){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 k=statSync(D);if(w===`file`&&!k.isFile()||w===`folder`&&!k.isDirectory()){errorResponse(s,400,`urn:ok:error:invalid-request`,`Target path is not a ${w}.`,{handler:`duplicate-path`});return}let j=w===`file`?[E]:Hi(resolveContentEntryPath(g,`folder`,E)),F=ve?.(),L=new Set(F?F.getConflicts().map(e=>e.file):[]);for(let e of j){let g=stripDocExtension(e),S=t.documents.get(g),w=`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),D=L.has(w);if(E||D){respondDocInConflict(s,new DocInConflictError({file:w}),`duplicate-path`);return}}let B,H=[];if(w===`file`){let e=extname(D);if(B=nextAvailableDuplicateDocName(g,E).docName,isSystemDoc(B)||isConfigDoc(B)||De?.isExcluded(`${B}${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,B,e),S=readFileSync(D,`utf-8`),w=dirname(t),k=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(!k)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(B,e),Ie?.delete(B),De&&(De.incrementMdDir(dirname(B)),j=!0),registerWrite(t,contentHash(S)),O?.({kind:`create`,path:t,docName:B,content:S}),ue?.updateDocumentFromMarkdown(B,S),H=[B]}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(B),De&&j&&De.decrementMdDir(dirname(B)),O?.({kind:`delete`,path:t,docName:B}),e}}else{if(B=nextAvailableDuplicateFolderPath(g,E).folderPath,De?.isDirExcluded(B)){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`,B);try{tracedCpSync(D,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,B))it(e);let e=collectMarkdownCopies(g,B);H=e.map(e=>e.docName);for(let t of e){let e=extname(t.fullPath);registerDocExtension(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 H)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&&H.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:B,duplicatedDocNames:H},{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$6.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}let k=O===`file`?[stripDocExtension(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=stripDocExtension(e),S=t.documents.get(g),w=O===`file`?E:`${g}${getDocExtension(e)}`,D=S!==void 0&&isDocInConflict(S),k=F.has(w);if(D||k){respondDocInConflict(s,new DocInConflictError({file:w}),`rename-path`);return}}if(O===`file`&&probeAndRegisterSourceFileExtension(g,E),De&&(O===`file`?De.isExcluded(isSupportedDocFile(D)?D:`${D}${getDocExtension(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$6.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`?[stripDocExtension(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=stripDocExtension(e),S=t.documents.get(g),w=k===`file`&&isSupportedDocFile(D)?D:`${g}${getDocExtension(g)}`,E=S!==void 0&&isDocInConflict(S),O=H.has(w);if(E||O){respondDocInConflict(s,new DocInConflictError({file:w}),`delete-path`);return}}if(await Vr(L),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,`${e}${getDocExtension(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),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,`${e}${getDocExtension(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=t,w,E=getDocExtension(t);try{let s=readFileSync(resolve(g,`${t}${E}`),`utf-8`);e=extractPageTitle(s,t),w=extractPageIcon(s)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}s.push({docName:t,title:e,docExt:E,size:S.size,modified:S.modified,icon:w})}s.sort((e,t)=>e.docName.localeCompare(t.docName)),successResponse(t,200,PagesSuccessSchema,{pages:s},{handler:`pages`})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),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$6.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$6.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$6.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$6.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$6.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$6.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$6.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$6.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$6.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(`
|
|
1941
1941
|
`).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:ll}):successResponse(t,200,LocalOpAuthStatusSuccessSchema,E,{handler:ll})}catch(e){errorResponse(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:ll,cause:e})}finally{Ge.release(Zc)}},{handler:ll,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:ll})}),dl=`local-op-auth-repos`,fl=withValidation(LocalOpAuthHostRequestSchema,pl,{handler:dl,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:dl})});async function pl(e,t,s){let g=s.host??`github.com`;if(!Ge.tryAcquire(Qc)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:dl,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,dl),[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`)},Hc);j.stdout.on(`data`,e=>{k+=e.toString(`utf-8`);let s=k.split(`
|
|
1942
1942
|
`);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$6.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$6.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)]);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)]);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)]);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)]);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)]);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}`}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$6.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$6.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$6.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}if(!isValidSharePath(s.kind===`doc`?s.docPath:s.folderPath,s.kind)){emitShareConstructUrlLog(`invalid-path`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`invalid-path`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let e=readGitHeadBranch(Ce);if(e===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 S=readOriginGitHubRepo(Ce);if(S.kind===`no-remote`){emitShareConstructUrlLog(`no-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`no-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(S.kind===`non-github`){emitShareConstructUrlLog(`non-github-remote`,{kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`non-github-remote`},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}if(!branchExistsOnOrigin(Ce,e)){emitShareConstructUrlLog(`branch-not-on-origin`,{branchExists:!1,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!1,error:`branch-not-on-origin`,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG});return}let w=toGitRelativePath(Ce,g);if(w===null)throw Error(`content dir is not contained within the project dir`);let E=s.kind===`doc`?s.docPath!==``:s.folderPath!==``;w!==``&&E&&getLogger(`share`).warn({action:`construct-url`,kind:s.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let D;if(s.kind===`doc`)D=buildGitHubBlobUrl(S.owner,S.repo,e,s.docPath);else{let t=s.folderPath===``?w:s.folderPath;D=buildGitHubTreeUrl(S.owner,S.repo,e,t)}let O=`${SHARE_BASE_URL}${encodeShareUrl(D)}`;emitShareConstructUrlLog(`ok`,{branchExists:!0,kind:s.kind}),successResponse(t,200,ShareConstructUrlResponseSchema,{ok:!0,shareUrl:O,sharedUrl:D,branch:e},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,cause:e})}},{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:SHARE_CONSTRUCT_URL_HANDLER_TAG})}),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(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)),{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 pd(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 md=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 pd([`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})}),hd=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 pd([`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})}),gd=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 pd(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})}),_d=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`})}),vd=Ce?getLocalDir(Ce):null;async function yd(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}vd&&clearArmedPaneTarget(vd),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:vd?readServerLock(vd)?.port??0:0,paneTarget:vd?readArmedPaneTarget(vd):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 bd=`local-op-embeddings-set-key`,xd=`local-op-embeddings-clear-key`,Sd=`/api/local-op/embeddings`,Cd=withValidation(LocalOpEmbeddingsSetKeyRequestSchema,async(e,t,s)=>{if(!Ge.tryAcquire(Sd)){errorResponse(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:bd,extraHeaders:{"Retry-After":`5`}});return}try{await new FileEmbeddingsBackend(Ue).set(s.key),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!0},{handler:bd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:bd,cause:e})}finally{Ge.release(Sd)}},{handler:bd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:bd})}),wd=withValidation(EmptyRequestSchema,async(e,t)=>{if(!Ge.tryAcquire(Sd)){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 clearEmbeddingsKeyFromAllBackends(Ue),successResponse(t,200,LocalOpEmbeddingsMutationSuccessSchema,{keyPresent:!1},{handler:xd,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){errorResponse(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:xd,cause:e})}finally{Ge.release(Sd)}},{handler:xd,method:`POST`,preBodyGate:(e,t)=>checkLocalOpSecurity(e,t,{handler:xd})}),Td=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}),Ed={"/api/config":yd,"/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":Td,"/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/git/branch-info":dd,"/api/git/checkout":fd,"/api/share/publish/owners":md,"/api/share/publish/name-check":hd,"/api/share/publish":gd,"/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":Cd,"/api/local-op/embeddings/clear-key":wd,"/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":_d};q&&(Ed[`/api/test-reset`]=dc,Ed[`/api/test-flush-git`]=uc,Ed[`/api/test-rescan-backlinks`]=fc,Ed[`/api/test-rescan-files`]=pc);let Dd=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(`.`)),Od=[`/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(Dd.has(s)||Od.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`:Ed[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=Ed[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$5=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$5.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$5.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$5.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-DdgvPBh6-Dv4DjLoy.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$5.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let s=new Date().toISOString(),g=!1;try{let e=(await w.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
|
|
1943
1943
|
`).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:s});g=e.length>0}catch(e){log$5.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$5.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(`
|
|
@@ -3251,4 +3251,4 @@ Incremental by default — don't re-read the whole repo.
|
|
|
3251
3251
|
`))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 Ce.flushDeferredStores(`discard-stale`),De?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&ve.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(ve.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),Y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:s.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${s.slice(0,8)}`)}catch(e){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Ir.push(`head-watcher`)}function D(e){for(let g of e)try{let e=toPosix(relative(t,join(s,g)));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=we.documents.get(S);if(!w)continue;let E=Mt(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let O=buildSyncCredentialArgs(H);try{en=new SyncEngine({projectDir:s,contentDir:t,contentFilter:me,contentRoot:L,syncEnabled:ne(),credentialArgs:O,cc1Broadcaster:De,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||Ce.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:D,onAutoDisable:async e=>{Y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:s,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||Y.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,s)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await en.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),en=null}Xe(`files`),Xe(`backlinks`),Xe(`graph`),Xe(`tags`)}return Lr().then(We,Ge),{hocuspocus:we,sessionManager:Te,cc1Broadcaster:De,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,maintenanceCoordinator:ye,contentFilter:me,basenameIndex:ue,serverInstanceId:se,destroy:Fr,ready:Ke,degraded:Ir,lockDir:ce,get syncEngine(){return en}}}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){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};return S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S)),withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,s=e.attachUiSibling??!0,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-8Lv6A-Xa-DqbpfxSh.mjs`),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let L=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:q,destroy:ee,ready:J,degraded:Y,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se}=H,ce=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ue=e.port??0,de=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:S}),fe=D();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:H.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ge=!1;if(e.reactShellDistDir)try{acquireUiLock(te,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ge=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:te},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await ee().catch(()=>{}),e}let _e=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ve=mountMcpAndApi({httpServer:fe,hocuspocus:q,mcpHttpHandler:de,log:S,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:_e,ephemeral:e.ephemeral}),ye=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Ce=null;g!==null&&(Ce=attachIdleShutdown({httpServer:fe,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ye()})})),await restoreLifecycleFromConflictsJson({hocuspocus:q,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);fe.once(`error`,g),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,g),t()})})}catch(e){if(ge)try{releaseUiLock(te)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await ee().catch(()=>{}),e}let we=fe.address(),Te=typeof we==`object`&&we?we.port:e.port??0;if(ue=Te,O(te,Te),ge&&updateUiLockPort(te,Te),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:te,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let De=!1,je=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)}};ye=async()=>{if(De)return;De=!0;let e=[],t=async(t,s)=>{try{await je(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{Ce?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ve.shutdown()),de!==void 0&&await t(`mcpHttpHandler.close`,()=>de.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ve.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>ee()),ge&&await t(`releaseUiLock`,async()=>releaseUiLock(te)),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:j,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:fe,destroy:ye,lockDir:te,contentDir:e.contentDir,port:Te,ready:J,degraded:Y,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
|
|
3252
3252
|
`).map(e=>e.trim()).filter(Boolean):[])}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),s=e.platformName??process.platform,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!0});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},g)}function flushFileLogger(e,t=250){return new Promise(s=>{if(!e){s();return}let g=e[import_pino.default.symbols.streamSym],S=!1,w=()=>{S||(S=!0,s())};if(!g||typeof g.flushSync!=`function`){w();return}let E=()=>{try{g.flushSync?.()}catch{}w()},D=setTimeout(w,t);typeof D.unref==`function`&&D.unref(),typeof g.fd==`number`&&g.fd>=0?(clearTimeout(D),E()):typeof g.once==`function`?g.once(`ready`,()=>{clearTimeout(D),E()}):(clearTimeout(D),E())})}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e,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/
|
|
3253
3253
|
`,`utf-8`),t}export{STARTER_PACKS as $,withSpan as $i,isAllowedWorkspaceHostHeader as $n,resolveBundledSkillDir as $r,createExternalChangeHandler as $t,HocuspocusAuthRejection as A,spawnDetached as Ai,formatPackRationale as An,planSeed as Ar,bundleSkillMdPath as At,McpLogger as B,tracedMkdirSync as Bi,handleCollabSocketError as Bn,readSkillManagement as Br,compareSemver as Bt,FILE_WATCHER_ORIGIN as C,serializeError as Ci,fallbackPaths as Cn,normalizeFsPath as Cr,bootServer as Ct,GitNotAvailableError as D,skillManagementPath as Di,formatAuthRejectionWire as Dn,parseHocuspocusAuthToken as Dr,buildSkillZip as Dt,GIT_UPSTREAM_WRITER as E,shutdownTelemetry as Ei,flushFileLogger as En,parseGitVersion as Er,buildExecResult as Et,MANAGED_RENAME_ORIGIN as F,teardownToleranceTelemetryWriter as Fi,getLogger as Fn,readArmedPaneTarget as Fr,clearEmbeddingsKeyFromAllBackends as Ft,PinoLogger as G,tracedUnlinkSync as Gi,initContent as Gn,reconcile as Gr,countStaleAgentWipRefs as Gt,OBSERVER_SYNC_ORIGIN as H,tracedRenameSync as Hi,hasGcLogLatch as Hn,readTargetRecordedAt as Hr,contentHash as Ht,MAX_AGENT_SESSIONS as I,toBroadcasterKey as Ii,getLogsDir as In,readBranchFromHead as Ir,coercePackId as It,ROOT_GITIGNORE_TEMPLATE as J,updateLastKnownHash as Ji,initToleranceTelemetryWriter as Jn,registerAllTools as Jr,createAssetServeMiddleware as Jt,ProjectGitInitError as K,tracedWriteFile as Ki,initShadowRepo as Kn,recordContributor as Kr,countWipRefs as Kt,MCP_CONNECTION_ID_HEADER as L,tracedAppendFileSync as Li,getMeter as Ln,readProjectLocalSemanticConfig as Lr,commitUpstreamImport as Lt,INSTALLED_AGENTS_SCHEMES as M,startWatcher as Mi,getCurrentMcpLogger as Mn,processCommand as Mr,classifyFsPath as Mt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as N,streamingProblemEvent as Ni,getLocalDir as Nn,processUsage as Nr,clearArmedPaneTarget as Nt,GitTooOldError as O,spansCurrentPath as Oi,formatContributors as On,parseKeepaliveConnectionId as Or,buildStarterFolderFrontmatterYaml as Ot,LOG_MD_TEMPLATE as P,swapContributors as Pi,getLogFilePath as Pn,readAllTargets as Pr,clearContributors as Pt,STARTER_FOLDER_FRONTMATTER_FILENAME as Q,validateSkillZip as Qi,isAllowedApiOrigin as Qn,resetMetrics as Qr,createEphemeralProjectDir as Qt,MIN_GIT_VERSION as R,tracedLinkSync as Ri,getMetrics as Rn,readServerPackageVersion as Rr,commitWip as Rt,FILE_SYSTEM_WRITER as S,seedBasenameIndex as Si,extractWikiLinksFromMarkdown as Sn,mountMcpAndApi as Sr,attachIdleShutdown as St,GIT_PREFLIGHT_FAIL_SPAN_NAME as T,shadowGit as Ti,findEnclosingProjectRoot as Tn,parseAuthRejectionWire as Tr,buildConfigYmlContent as Tt,OK_OKIGNORE_TEMPLATE as U,tracedRmSync as Ui,incrementCollabSocketFilteredError as Un,readTargetVersion as Ur,contributorCount as Ut,MissingOkConfigError as V,tracedRename as Vi,handleSpawnCursor as Vn,readStateManifest as Vr,containsConflictMarkers as Vt,PANE_TARGET_TTL_MS as W,tracedRmdirSync as Wi,incrementServerObserverFire as Wn,readUiLock as Wr,countShadowObjects as Wt,SKILL_INSTALL_EVENTS_FILE_REL as X,validateAgentId as Xi,installTestLoggers as Xn,releaseUiLock as Xr,createContentFilterAsync as Xt,SERVICE_WRITER as Y,updateUiLockPort as Yi,installPrettyZodErrors as Yn,registerWrite as Yr,createContentFilter as Yt,STARTER_FOLDERS as Z,validateCloneInputs as Zi,installUserSkill as Zn,removeLastKnownHash as Zr,createEmbeddingsSecretStore as Zt,ConfigSchema as _,GitDirAccessError as _a,safeSubdir as _i,encodeSkillRoute as _n,loadPrincipal as _r,applySeed as _t,AgentPresenceBroadcaster as a,writeTracker as aa,resolvePackageVersion as ai,createServer$1 as an,isManagedArtifactDoc as ar,SingleFileNotAFileError as at,DEFAULT_PACK_ID as b,resolveGitDirDetailed as ba,saveInMemoryCheckpoint as bi,evictStaleTrackerEntries as bn,logsPreviousPath as br,assertGitAvailable as bt,AutoStartDisabledError as c,LATEST_PROTOCOL_VERSION as ca,restoreLifecycleFromConflictsJson as ci,createTestLogger as cn,isProjectRoot as cr,StateManifestError as ct,BUNDLE_SKILL_NAME as d,isJSONRPCResultResponse as da,runAuthReposSubprocess as di,detectGit as dn,isSelfWrite as dr,UiLockCollisionError as dt,withSpanSync as ea,resolveContentDir as ei,createFileLogger as en,isConfigDoc as er,STARTER_PACK_IDS as et,BacklinkIndex as f,atomicWriteFileSync as fa,runAuthStatusSubprocess as fi,detectProjectShape as fn,isSystemDoc as fr,__getShowAllWalkStatsForTesting as ft,CURSOR_BUNDLE_PATHS_BY_PLATFORM as g,writeConfigPatch as ga,safeContentPath as gi,encodeFolderRoute as gn,listStarterPacks as gr,applyExternalChange as gt,CONFLICT_MARKER_RE as h,withFileLockSync as ha,runWithMcpLogger as hi,encodeDocName as hn,listRescueCheckpoints as hr,applyAgentMarkdownWrite as ht,AgentFocusBroadcaster as i,writeTargetVersion as ia,resolvePack as ii,createPersistenceExtension as in,isLoopbackAddress as ir,SeedRootDirError as it,HocuspocusAuthTokenSchema as j,splitMarkdownBlocks as ji,gcCheckpointRefs as jn,prepareSingleFileOpen as jr,classifyEvents as jt,HOCUSPOCUS_AUTH_REJECTION_REASONS as k,spansPreviousPath as ki,formatContributorsFrom as kn,pathToDocName as kr,buildWipTree as kt,BUNDLE_IDS as l,isInitializedNotification as la,rewriteMarkdownLinksForDocumentRename as li,describeStoredEmbeddingsKey as ln,isProjectSkillManaged as lr,TagIndex as lt,CONFIG_FILENAME as m,resolveConfigPath as ma,runDeviceFlowSubprocess as mi,emitPreflightFailureSpan as mn,lastKnownHash as mr,acquireUiLock as mt,AGENT_ID_RE as n,writeSkillManagement as na,resolveCursorSpawnInvocation as ni,createMcpHttpHandler as nn,isKnownPackId as nr,STATE_MANIFEST_FILENAME as nt,AgentSessionCapacityError as o,McpServer as oa,resolveUiInfo as oi,createServerObserverExtension as on,isPairedWriteOrigin as or,SingleFileNotFoundError as ot,CC1Broadcaster as p,readConfigSafely as pa,runCloneSubprocess as pi,discoverLockDirs as pn,isToleranceTelemetryEnabled as pr,__resetShowAllWalkStatsForTesting as pt,ROLLBACK_ORIGIN as q,tracedWriteFileSync as qi,initTelemetry as qn,recordSkillInstallEvent as qr,createApiExtension as qt,AGENT_WRITE_ORIGIN as r,writeStateManifest as ra,resolveLockDir as ri,createOsProbe as rn,isLinkIndexExcludedDoc as rr,SeedPrerequisiteError as rt,AgentSessionManager as s,JSONRPCMessageSchema as sa,restoreContributors as si,createStreamingErrorWriter as sn,isPathWithinDir as sr,SingleFileNotMarkdownError as st,AGENT_ID_MAX_LEN as t,writeRootGitignoreForNewRepo as ta,resolveCursorBinaryDefault as ti,createLiveDerivedIndexExtension as tn,isHocuspocusAuthRejectionReason as tr,STARTER_TEMPLATES as tt,BUNDLE_SCOPE as u,isJSONRPCRequest as ua,rewriteWikiLinksForDocumentRename as ui,detectClaudeDesktopPresence as un,isReservedForUserTree as ur,USER_GLOBAL_BUNDLE_IDS as ut,DEFAULT_CHECKPOINT_RETENTION as v,MalformedGitPointerError as va,safetyCheckpoint as vi,ensureProjectGit as vn,loggerFactory as vr,armPaneTarget as vt,FileEmbeddingsBackend as w,setActiveSpanAttributes as wi,findEnclosingGitRoot as wn,packageVersionMajorMinor as wr,buildAndOpenSkill as wt,EMBEDDINGS_API_KEY_ENV as x,resolveShadowDir as xa,saveVersion as xi,extractOkBinaryPath as xn,makeLazyEmbeddingsKeyStore as xr,assertNeverDiskEvent as xt,DEFAULT_EMBEDDINGS_DIMENSIONS as y,parseCheckpoint as ya,sanitizeClientName as yi,errorResponse as yn,logsCurrentPath as yr,assertCompatibleStateManifest as yt,MISSING_OK_CONFIG_MESSAGE as z,tracedMkdir as zi,getTracer as zn,readSkillInstallStateSnapshot as zr,commitWipFromTree as zt};
|
|
3254
|
-
//# sourceMappingURL=dist-
|
|
3254
|
+
//# sourceMappingURL=dist-BoIBsVKQ.mjs.map
|