@newfold/wp-module-ai-chat 1.0.2 → 1.0.3
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/build/index.asset.php +1 -1
- package/build/index.js +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -5,4 +5,4 @@
|
|
|
5
5
|
missingProperty: ${r},
|
|
6
6
|
depsCount: ${t},
|
|
7
7
|
deps: ${n}}`};const a={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(e){const[t,n]=function({schema:e}){const t={},n={};for(const s in e)"__proto__"!==s&&((Array.isArray(e[s])?t:n)[s]=e[s]);return[t,n]}(e);i(e,t),c(e,n)}};function i(e,t=e.schema){const{gen:n,data:r,it:a}=e;if(0===Object.keys(t).length)return;const i=n.let("missing");for(const c in t){const l=t[c];if(0===l.length)continue;const u=(0,o.propertyInData)(n,r,c,a.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(", ")}),a.allErrors?n.if(u,()=>{for(const t of l)(0,o.checkReportMissingProp)(e,t)}):(n.if(s._`${u} && (${(0,o.checkMissingProp)(e,l,i)})`),(0,o.reportMissingProp)(e,i),n.else())}}function c(e,t=e.schema){const{gen:n,data:s,keyword:a,it:i}=e,c=n.name("valid");for(const l in t)(0,r.alwaysValidSchema)(i,t[l])||(n.if((0,o.propertyInData)(n,s,l,i.opts.ownProperties),()=>{const t=e.subschema({keyword:a,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>n.var(c,!0)),e.ok(c))}t.validatePropertyDeps=i,t.validateSchemaDeps=c,t.default=a},1239(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(9029),r=n(4227),o={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:e})=>s.str`must match "${e.ifClause}" schema`,params:({params:e})=>s._`{failingKeyword: ${e.ifClause}}`},code(e){const{gen:t,parentSchema:n,it:o}=e;void 0===n.then&&void 0===n.else&&(0,r.checkStrictMode)(o,'"if" without "then" and "else" is ignored');const i=a(o,"then"),c=a(o,"else");if(!i&&!c)return;const l=t.let("valid",!0),u=t.name("_valid");if(function(){const t=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}(),e.reset(),i&&c){const n=t.let("ifClause");e.setParams({ifClause:n}),t.if(u,d("then",n),d("else",n))}else i?t.if(u,d("then")):t.if((0,s.not)(u),d("else"));function d(n,r){return()=>{const o=e.subschema({keyword:n},u);t.assign(l,u),e.mergeValidEvaluated(o,l),r?t.assign(r,s._`${n}`):e.setParams({ifClause:n})}}e.pass(l,()=>e.error(!0))}};function a(e,t){const n=e.schema[t];return void 0!==n&&!(0,r.alwaysValidSchema)(e,n)}t.default=o},6378(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(5457),r=n(5354),o=n(494),a=n(3966),i=n(2661),c=n(3025),l=n(9713),u=n(8660),d=n(117),h=n(5333),p=n(7923),f=n(6505),m=n(6163),g=n(5844),_=n(1239),y=n(4426);t.default=function(e=!1){const t=[p.default,f.default,m.default,g.default,_.default,y.default,l.default,u.default,c.default,d.default,h.default];return e?t.push(r.default,a.default):t.push(s.default,o.default),t.push(i.default),t}},494(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateTuple=void 0;const s=n(9029),r=n(4227),o=n(5765),a={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return i(e,"additionalItems",t);n.items=!0,(0,r.alwaysValidSchema)(n,t)||e.ok((0,o.validateArray)(e))}};function i(e,t,n=e.schema){const{gen:o,parentSchema:a,data:i,keyword:c,it:l}=e;!function(e){const{opts:s,errSchemaPath:o}=l,a=n.length,i=a===e.minItems&&(a===e.maxItems||!1===e[t]);if(s.strictTuples&&!i){const e=`"${c}" is ${a}-tuple, but minItems or maxItems/${t} are not specified or different at path "${o}"`;(0,r.checkStrictMode)(l,e,s.strictTuples)}}(a),l.opts.unevaluated&&n.length&&!0!==l.items&&(l.items=r.mergeEvaluated.items(o,n.length,l.items));const u=o.name("valid"),d=o.const("len",s._`${i}.length`);n.forEach((t,n)=>{(0,r.alwaysValidSchema)(l,t)||(o.if(s._`${d} > ${n}`,()=>e.subschema({keyword:c,schemaProp:n,dataProp:n},u)),e.ok(u))})}t.validateTuple=i,t.default=a},3966(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(9029),r=n(4227),o=n(5765),a=n(5457),i={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:e}})=>s.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>s._`{limit: ${e}}`},code(e){const{schema:t,parentSchema:n,it:s}=e,{prefixItems:i}=n;s.items=!0,(0,r.alwaysValidSchema)(s,t)||(i?(0,a.validateAdditionalItems)(e,i):e.ok((0,o.validateArray)(e)))}};t.default=i},7923(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(4227),r={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:r}=e;if((0,s.alwaysValidSchema)(r,n))return void e.fail();const o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};t.default=r},6163(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(9029),r=n(4227),o={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:e})=>s._`{passingSchemas: ${e.passing}}`},code(e){const{gen:t,schema:n,parentSchema:o,it:a}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(a.opts.discriminator&&o.discriminator)return;const i=n,c=t.let("valid",!1),l=t.let("passing",null),u=t.name("_valid");e.setParams({passing:l}),t.block(function(){i.forEach((n,o)=>{let i;(0,r.alwaysValidSchema)(a,n)?t.var(u,!0):i=e.subschema({keyword:"oneOf",schemaProp:o,compositeRule:!0},u),o>0&&t.if(s._`${u} && ${c}`).assign(c,!1).assign(l,s._`[${l}, ${o}]`).else(),t.if(u,()=>{t.assign(c,!0),t.assign(l,o),i&&e.mergeEvaluated(i,s.Name)})})}),e.result(c,()=>e.reset(),()=>e.error(!0))}};t.default=o},5333(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(5765),r=n(9029),o=n(4227),a=n(4227),i={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,data:i,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,s.allSchemaProperties)(n),h=d.filter(e=>(0,o.alwaysValidSchema)(l,n[e]));if(0===d.length||h.length===d.length&&(!l.opts.unevaluated||!0===l.props))return;const p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,f=t.name("valid");!0===l.props||l.props instanceof r.Name||(l.props=(0,a.evaluatedPropsToName)(t,l.props));const{props:m}=l;function g(e){for(const t in p)new RegExp(e).test(t)&&(0,o.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function _(n){t.forIn("key",i,o=>{t.if(r._`${(0,s.usePattern)(e,n)}.test(${o})`,()=>{const s=h.includes(n);s||e.subschema({keyword:"patternProperties",schemaProp:n,dataProp:o,dataPropType:a.Type.Str},f),l.opts.unevaluated&&!0!==m?t.assign(r._`${m}[${o}]`,!0):s||l.allErrors||t.if((0,r.not)(f),()=>t.break())})})}!function(){for(const e of d)p&&g(e),l.allErrors?_(e):(t.var(f,!0),_(e),t.if(f))}()}};t.default=i},5354(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(494),r={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,s.validateTuple)(e,"items")};t.default=r},117(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(2586),r=n(5765),o=n(4227),a=n(8660),i={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,parentSchema:i,data:c,it:l}=e;"all"===l.opts.removeAdditional&&void 0===i.additionalProperties&&a.default.code(new s.KeywordCxt(l,a.default,"additionalProperties"));const u=(0,r.allSchemaProperties)(n);for(const e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&!0!==l.props&&(l.props=o.mergeEvaluated.props(t,(0,o.toHash)(u),l.props));const d=u.filter(e=>!(0,o.alwaysValidSchema)(l,n[e]));if(0===d.length)return;const h=t.name("valid");for(const n of d)p(n)?f(n):(t.if((0,r.propertyInData)(t,c,n,l.opts.ownProperties)),f(n),l.allErrors||t.else().var(h,!0),t.endIf()),e.it.definedProperties.add(n),e.ok(h);function p(e){return l.opts.useDefaults&&!l.compositeRule&&void 0!==n[e].default}function f(t){e.subschema({keyword:"properties",schemaProp:t,dataProp:t},h)}}};t.default=i},9713(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(9029),r=n(4227),o={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:e})=>s._`{propertyName: ${e.propertyName}}`},code(e){const{gen:t,schema:n,data:o,it:a}=e;if((0,r.alwaysValidSchema)(a,n))return;const i=t.name("valid");t.forIn("key",o,n=>{e.setParams({propertyName:n}),e.subschema({keyword:"propertyNames",data:n,dataTypes:["string"],propertyName:n,compositeRule:!0},i),t.if((0,s.not)(i),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(i)}};t.default=o},4426(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(4227),r={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){void 0===t.if&&(0,s.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};t.default=r},5765(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateUnion=t.validateArray=t.usePattern=t.callValidateCode=t.schemaProperties=t.allSchemaProperties=t.noPropertyInData=t.propertyInData=t.isOwnProperty=t.hasPropFunc=t.reportMissingProp=t.checkMissingProp=t.checkReportMissingProp=void 0;const s=n(9029),r=n(4227),o=n(2023),a=n(4227);function i(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:s._`Object.prototype.hasOwnProperty`})}function c(e,t,n){return s._`${i(e)}.call(${t}, ${n})`}function l(e,t,n,r){const o=s._`${t}${(0,s.getProperty)(n)} === undefined`;return r?(0,s.or)(o,(0,s.not)(c(e,t,n))):o}function u(e){return e?Object.keys(e).filter(e=>"__proto__"!==e):[]}t.checkReportMissingProp=function(e,t){const{gen:n,data:r,it:o}=e;n.if(l(n,r,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:s._`${t}`},!0),e.error()})},t.checkMissingProp=function({gen:e,data:t,it:{opts:n}},r,o){return(0,s.or)(...r.map(r=>(0,s.and)(l(e,t,r,n.ownProperties),s._`${o} = ${r}`)))},t.reportMissingProp=function(e,t){e.setParams({missingProperty:t},!0),e.error()},t.hasPropFunc=i,t.isOwnProperty=c,t.propertyInData=function(e,t,n,r){const o=s._`${t}${(0,s.getProperty)(n)} !== undefined`;return r?s._`${o} && ${c(e,t,n)}`:o},t.noPropertyInData=l,t.allSchemaProperties=u,t.schemaProperties=function(e,t){return u(t).filter(n=>!(0,r.alwaysValidSchema)(e,t[n]))},t.callValidateCode=function({schemaCode:e,data:t,it:{gen:n,topSchemaRef:r,schemaPath:a,errorPath:i},it:c},l,u,d){const h=d?s._`${e}, ${t}, ${r}${a}`:t,p=[[o.default.instancePath,(0,s.strConcat)(o.default.instancePath,i)],[o.default.parentData,c.parentData],[o.default.parentDataProperty,c.parentDataProperty],[o.default.rootData,o.default.rootData]];c.opts.dynamicRef&&p.push([o.default.dynamicAnchors,o.default.dynamicAnchors]);const f=s._`${h}, ${n.object(...p)}`;return u!==s.nil?s._`${l}.call(${u}, ${f})`:s._`${l}(${f})`};const d=s._`new RegExp`;t.usePattern=function({gen:e,it:{opts:t}},n){const r=t.unicodeRegExp?"u":"",{regExp:o}=t.code,i=o(n,r);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:s._`${"new RegExp"===o.code?d:(0,a.useFunc)(e,o)}(${n}, ${r})`})},t.validateArray=function(e){const{gen:t,data:n,keyword:o,it:a}=e,i=t.name("valid");if(a.allErrors){const e=t.let("valid",!0);return c(()=>t.assign(e,!1)),e}return t.var(i,!0),c(()=>t.break()),i;function c(a){const c=t.const("len",s._`${n}.length`);t.forRange("i",0,c,n=>{e.subschema({keyword:o,dataProp:n,dataPropType:r.Type.Num},i),t.if((0,s.not)(i),a)})}},t.validateUnion=function(e){const{gen:t,schema:n,keyword:o,it:a}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(e=>(0,r.alwaysValidSchema)(a,e))&&!a.opts.unevaluated)return;const i=t.let("valid",!1),c=t.name("_valid");t.block(()=>n.forEach((n,r)=>{const a=e.subschema({keyword:o,schemaProp:r,compositeRule:!0},c);t.assign(i,s._`${i} || ${c}`),e.mergeValidEvaluated(a,c)||t.if((0,s.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}},3463(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};t.default=n},2128(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(3463),r=n(3693),o=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",s.default,r.default];t.default=o},3693(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.callRef=t.getValidate=void 0;const s=n(4551),r=n(5765),o=n(9029),a=n(2023),i=n(3835),c=n(4227),l={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:n,it:r}=e,{baseId:a,schemaEnv:c,validateName:l,opts:h,self:p}=r,{root:f}=c;if(("#"===n||"#/"===n)&&a===f.baseId)return function(){if(c===f)return d(e,l,c,c.$async);const n=t.scopeValue("root",{ref:f});return d(e,o._`${n}.validate`,f,f.$async)}();const m=i.resolveRef.call(p,f,a,n);if(void 0===m)throw new s.default(r.opts.uriResolver,a,n);return m instanceof i.SchemaEnv?function(t){const n=u(e,t);d(e,n,t,t.$async)}(m):function(s){const r=t.scopeValue("schema",!0===h.code.source?{ref:s,code:(0,o.stringify)(s)}:{ref:s}),a=t.name("valid"),i=e.subschema({schema:s,dataTypes:[],schemaPath:o.nil,topSchemaRef:r,errSchemaPath:n},a);e.mergeEvaluated(i),e.ok(a)}(m)}};function u(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):o._`${n.scopeValue("wrapper",{ref:t})}.validate`}function d(e,t,n,s){const{gen:i,it:l}=e,{allErrors:u,schemaEnv:d,opts:h}=l,p=h.passContext?a.default.this:o.nil;function f(e){const t=o._`${e}.errors`;i.assign(a.default.vErrors,o._`${a.default.vErrors} === null ? ${t} : ${a.default.vErrors}.concat(${t})`),i.assign(a.default.errors,o._`${a.default.vErrors}.length`)}function m(e){var t;if(!l.opts.unevaluated)return;const s=null===(t=null==n?void 0:n.validate)||void 0===t?void 0:t.evaluated;if(!0!==l.props)if(s&&!s.dynamicProps)void 0!==s.props&&(l.props=c.mergeEvaluated.props(i,s.props,l.props));else{const t=i.var("props",o._`${e}.evaluated.props`);l.props=c.mergeEvaluated.props(i,t,l.props,o.Name)}if(!0!==l.items)if(s&&!s.dynamicItems)void 0!==s.items&&(l.items=c.mergeEvaluated.items(i,s.items,l.items));else{const t=i.var("items",o._`${e}.evaluated.items`);l.items=c.mergeEvaluated.items(i,t,l.items,o.Name)}}s?function(){if(!d.$async)throw new Error("async schema referenced by sync schema");const n=i.let("valid");i.try(()=>{i.code(o._`await ${(0,r.callValidateCode)(e,t,p)}`),m(t),u||i.assign(n,!0)},e=>{i.if(o._`!(${e} instanceof ${l.ValidationError})`,()=>i.throw(e)),f(e),u||i.assign(n,!1)}),e.ok(n)}():e.result((0,r.callValidateCode)(e,t,p),()=>m(t),()=>f(t))}t.getValidate=u,t.callRef=d,t.default=l},6653(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(9029),r=n(7652),o=n(3835),a=n(4551),i=n(4227),c={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:e,tagName:t}})=>e===r.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>s._`{error: ${e}, tag: ${n}, tagValue: ${t}}`},code(e){const{gen:t,data:n,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw new Error("discriminator: requires discriminator option");const h=c.propertyName;if("string"!=typeof h)throw new Error("discriminator: requires propertyName");if(c.mapping)throw new Error("discriminator: mapping is not supported");if(!d)throw new Error("discriminator: requires oneOf keyword");const p=t.let("valid",!1),f=t.const("tag",s._`${n}${(0,s.getProperty)(h)}`);function m(n){const r=t.name("valid"),o=e.subschema({keyword:"oneOf",schemaProp:n},r);return e.mergeEvaluated(o,s.Name),r}t.if(s._`typeof ${f} == "string"`,()=>function(){const n=function(){var e;const t={},n=r(l);let s=!0;for(let t=0;t<d.length;t++){let l=d[t];if((null==l?void 0:l.$ref)&&!(0,i.schemaHasRulesButRef)(l,u.self.RULES)){const e=l.$ref;if(l=o.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),l instanceof o.SchemaEnv&&(l=l.schema),void 0===l)throw new a.default(u.opts.uriResolver,u.baseId,e)}const p=null===(e=null==l?void 0:l.properties)||void 0===e?void 0:e[h];if("object"!=typeof p)throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${h}"`);s=s&&(n||r(l)),c(p,t)}if(!s)throw new Error(`discriminator: "${h}" must be required`);return t;function r({required:e}){return Array.isArray(e)&&e.includes(h)}function c(e,t){if(e.const)p(e.const,t);else{if(!e.enum)throw new Error(`discriminator: "properties/${h}" must have "const" or "enum"`);for(const n of e.enum)p(n,t)}}function p(e,n){if("string"!=typeof e||e in t)throw new Error(`discriminator: "${h}" values must be unique strings`);t[e]=n}}();t.if(!1);for(const e in n)t.elseIf(s._`${f} === ${e}`),t.assign(p,m(n[e]));t.else(),e.error(!1,{discrError:r.DiscrError.Mapping,tag:f,tagName:h}),t.endIf()}(),()=>e.error(!1,{discrError:r.DiscrError.Tag,tag:f,tagName:h})),e.ok(p)}};t.default=c},7652(e,t){"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.DiscrError=void 0,function(e){e.Tag="tag",e.Mapping="mapping"}(n||(t.DiscrError=n={}))},6144(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(2128),r=n(7060),o=n(6378),a=n(7532),i=n(9857),c=[s.default,r.default,(0,o.default)(),a.default,i.metadataVocabulary,i.contentVocabulary];t.default=c},4737(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(9029),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>s.str`must match format "${e}"`,params:({schemaCode:e})=>s._`{format: ${e}}`},code(e,t){const{gen:n,data:r,$data:o,schema:a,schemaCode:i,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:h}=c;l.validateFormats&&(o?function(){const o=n.scopeValue("formats",{ref:h.formats,code:l.code.formats}),a=n.const("fDef",s._`${o}[${i}]`),c=n.let("fType"),u=n.let("format");n.if(s._`typeof ${a} == "object" && !(${a} instanceof RegExp)`,()=>n.assign(c,s._`${a}.type || "string"`).assign(u,s._`${a}.validate`),()=>n.assign(c,s._`"string"`).assign(u,a)),e.fail$data((0,s.or)(!1===l.strictSchema?s.nil:s._`${i} && !${u}`,function(){const e=d.$async?s._`(${a}.async ? await ${u}(${r}) : ${u}(${r}))`:s._`${u}(${r})`,n=s._`(typeof ${u} == "function" ? ${e} : ${u}.test(${r}))`;return s._`${u} && ${u} !== true && ${c} === ${t} && !${n}`}()))}():function(){const o=h.formats[a];if(!o)return void function(){if(!1!==l.strictSchema)throw new Error(e());function e(){return`unknown format "${a}" ignored in schema at path "${u}"`}h.logger.warn(e())}();if(!0===o)return;const[i,c,p]=function(e){const t=e instanceof RegExp?(0,s.regexpCode)(e):l.code.formats?s._`${l.code.formats}${(0,s.getProperty)(a)}`:void 0,r=n.scopeValue("formats",{key:a,ref:e,code:t});return"object"!=typeof e||e instanceof RegExp?["string",e,r]:[e.type||"string",e.validate,s._`${r}.validate`]}(o);i===t&&e.pass(function(){if("object"==typeof o&&!(o instanceof RegExp)&&o.async){if(!d.$async)throw new Error("async format in sync schema");return s._`await ${p}(${r})`}return"function"==typeof c?s._`${p}(${r})`:s._`${p}.test(${r})`}())}())}};t.default=r},7532(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=[n(4737).default];t.default=s},9857(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.contentVocabulary=t.metadataVocabulary=void 0,t.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],t.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]},7935(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(9029),r=n(4227),o=n(6250),a={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:e})=>s._`{allowedValue: ${e}}`},code(e){const{gen:t,data:n,$data:a,schemaCode:i,schema:c}=e;a||c&&"object"==typeof c?e.fail$data(s._`!${(0,r.useFunc)(t,o.default)}(${n}, ${i})`):e.fail(s._`${c} !== ${n}`)}};t.default=a},8643(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(9029),r=n(4227),o=n(6250),a={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:e})=>s._`{allowedValues: ${e}}`},code(e){const{gen:t,data:n,$data:a,schema:i,schemaCode:c,it:l}=e;if(!a&&0===i.length)throw new Error("enum must have non-empty array");const u=i.length>=l.opts.loopEnum;let d;const h=()=>null!=d?d:d=(0,r.useFunc)(t,o.default);let p;if(u||a)p=t.let("valid"),e.block$data(p,function(){t.assign(p,!1),t.forOf("v",c,e=>t.if(s._`${h()}(${n}, ${e})`,()=>t.assign(p,!0).break()))});else{if(!Array.isArray(i))throw new Error("ajv implementation error");const e=t.const("vSchema",c);p=(0,s.or)(...i.map((_x,t)=>function(e,t){const r=i[t];return"object"==typeof r&&null!==r?s._`${h()}(${n}, ${e}[${t}])`:s._`${n} === ${r}`}(e,t)))}e.pass(p)}};t.default=a},7060(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(5882),r=n(3439),o=n(7307),a=n(422),i=n(4486),c=n(4003),l=n(1163),u=n(617),d=n(7935),h=n(8643),p=[s.default,r.default,o.default,a.default,i.default,c.default,l.default,u.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},d.default,h.default];t.default=p},1163(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(9029),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxItems"===e?"more":"fewer";return s.str`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>s._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:r}=e,o="maxItems"===t?s.operators.GT:s.operators.LT;e.fail$data(s._`${n}.length ${o} ${r}`)}};t.default=r},7307(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(9029),r=n(4227),o=n(3853),a={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxLength"===e?"more":"fewer";return s.str`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>s._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:a,it:i}=e,c="maxLength"===t?s.operators.GT:s.operators.LT,l=!1===i.opts.unicode?s._`${n}.length`:s._`${(0,r.useFunc)(e.gen,o.default)}(${n})`;e.fail$data(s._`${l} ${c} ${a}`)}};t.default=a},5882(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(9029),r=s.operators,o={maximum:{okStr:"<=",ok:r.LTE,fail:r.GT},minimum:{okStr:">=",ok:r.GTE,fail:r.LT},exclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},exclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},a={message:({keyword:e,schemaCode:t})=>s.str`must be ${o[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>s._`{comparison: ${o[e].okStr}, limit: ${t}}`},i={keyword:Object.keys(o),type:"number",schemaType:"number",$data:!0,error:a,code(e){const{keyword:t,data:n,schemaCode:r}=e;e.fail$data(s._`${n} ${o[t].fail} ${r} || isNaN(${n})`)}};t.default=i},4486(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(9029),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:e,schemaCode:t}){const n="maxProperties"===e?"more":"fewer";return s.str`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>s._`{limit: ${e}}`},code(e){const{keyword:t,data:n,schemaCode:r}=e,o="maxProperties"===t?s.operators.GT:s.operators.LT;e.fail$data(s._`Object.keys(${n}).length ${o} ${r}`)}};t.default=r},3439(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(9029),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:e})=>s.str`must be multiple of ${e}`,params:({schemaCode:e})=>s._`{multipleOf: ${e}}`},code(e){const{gen:t,data:n,schemaCode:r,it:o}=e,a=o.opts.multipleOfPrecision,i=t.let("res"),c=a?s._`Math.abs(Math.round(${i}) - ${i}) > 1e-${a}`:s._`${i} !== parseInt(${i})`;e.fail$data(s._`(${r} === 0 || (${i} = ${n}/${r}, ${c}))`)}};t.default=r},422(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(5765),r=n(9029),o={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:e})=>r.str`must match pattern "${e}"`,params:({schemaCode:e})=>r._`{pattern: ${e}}`},code(e){const{data:t,$data:n,schema:o,schemaCode:a,it:i}=e,c=i.opts.unicodeRegExp?"u":"",l=n?r._`(new RegExp(${a}, ${c}))`:(0,s.usePattern)(e,o);e.fail$data(r._`!${l}.test(${t})`)}};t.default=o},4003(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(5765),r=n(9029),o=n(4227),a={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:e}})=>r.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>r._`{missingProperty: ${e}}`},code(e){const{gen:t,schema:n,schemaCode:a,data:i,$data:c,it:l}=e,{opts:u}=l;if(!c&&0===n.length)return;const d=n.length>=u.loopRequired;if(l.allErrors?function(){if(d||c)e.block$data(r.nil,h);else for(const t of n)(0,s.checkReportMissingProp)(e,t)}():function(){const o=t.let("missing");if(d||c){const n=t.let("valid",!0);e.block$data(n,()=>function(n,o){e.setParams({missingProperty:n}),t.forOf(n,a,()=>{t.assign(o,(0,s.propertyInData)(t,i,n,u.ownProperties)),t.if((0,r.not)(o),()=>{e.error(),t.break()})},r.nil)}(o,n)),e.ok(n)}else t.if((0,s.checkMissingProp)(e,n,o)),(0,s.reportMissingProp)(e,o),t.else()}(),u.strictRequired){const t=e.parentSchema.properties,{definedProperties:s}=e.it;for(const e of n)if(void 0===(null==t?void 0:t[e])&&!s.has(e)){const t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,o.checkStrictMode)(l,t,l.opts.strictRequired)}}function h(){t.forOf("prop",a,n=>{e.setParams({missingProperty:n}),t.if((0,s.noPropertyInData)(t,i,n,u.ownProperties),()=>e.error())})}}};t.default=a},617(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=n(208),r=n(9029),o=n(4227),a=n(6250),i={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:e,j:t}})=>r.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>r._`{i: ${e}, j: ${t}}`},code(e){const{gen:t,data:n,$data:i,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!i&&!c)return;const h=t.let("valid"),p=l.items?(0,s.getSchemaTypes)(l.items):[];function f(o,a){const i=t.name("item"),c=(0,s.checkDataTypes)(p,i,d.opts.strictNumbers,s.DataType.Wrong),l=t.const("indices",r._`{}`);t.for(r._`;${o}--;`,()=>{t.let(i,r._`${n}[${o}]`),t.if(c,r._`continue`),p.length>1&&t.if(r._`typeof ${i} == "string"`,r._`${i} += "_"`),t.if(r._`typeof ${l}[${i}] == "number"`,()=>{t.assign(a,r._`${l}[${i}]`),e.error(),t.assign(h,!1).break()}).code(r._`${l}[${i}] = ${o}`)})}function m(s,i){const c=(0,o.useFunc)(t,a.default),l=t.name("outer");t.label(l).for(r._`;${s}--;`,()=>t.for(r._`${i} = ${s}; ${i}--;`,()=>t.if(r._`${c}(${n}[${s}], ${n}[${i}])`,()=>{e.error(),t.assign(h,!1).break(l)})))}e.block$data(h,function(){const s=t.let("i",r._`${n}.length`),o=t.let("j");e.setParams({i:s,j:o}),t.assign(h,!0),t.if(r._`${s} > 1`,()=>(p.length>0&&!p.some(e=>"object"===e||"array"===e)?f:m)(s,o))},r._`${u} === false`),e.ok(h)}};t.default=i},2017(e){"use strict";e.exports=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){if(t.constructor!==n.constructor)return!1;var s,r,o;if(Array.isArray(t)){if((s=t.length)!=n.length)return!1;for(r=s;0!==r--;)if(!e(t[r],n[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if((s=(o=Object.keys(t)).length)!==Object.keys(n).length)return!1;for(r=s;0!==r--;)if(!Object.prototype.hasOwnProperty.call(n,o[r]))return!1;for(r=s;0!==r--;){var a=o[r];if(!e(t[a],n[a]))return!1}return!0}return t!=t&&n!=n}},7106(e){"use strict";var t=e.exports=function(e,t,s){"function"==typeof t&&(s=t,t={}),n(t,"function"==typeof(s=t.cb||s)?s:s.pre||function(){},s.post||function(){},e,"",e)};function n(e,r,o,a,i,c,l,u,d,h){if(a&&"object"==typeof a&&!Array.isArray(a)){for(var p in r(a,i,c,l,u,d,h),a){var f=a[p];if(Array.isArray(f)){if(p in t.arrayKeywords)for(var m=0;m<f.length;m++)n(e,r,o,f[m],i+"/"+p+"/"+m,c,i,p,a,m)}else if(p in t.propsKeywords){if(f&&"object"==typeof f)for(var g in f)n(e,r,o,f[g],i+"/"+p+"/"+s(g),c,i,p,a,g)}else(p in t.keywords||e.allKeys&&!(p in t.skipKeywords))&&n(e,r,o,f,i+"/"+p,c,i,p,a)}o(a,i,c,l,u,d,h)}}function s(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}},6942(e,t){var n;!function(){"use strict";var s={}.hasOwnProperty;function r(){for(var e="",t=0;t<arguments.length;t++){var n=arguments[t];n&&(e=a(e,o(n)))}return e}function o(e){if("string"==typeof e||"number"==typeof e)return e;if("object"!=typeof e)return"";if(Array.isArray(e))return r.apply(null,e);if(e.toString!==Object.prototype.toString&&!e.toString.toString().includes("[native code]"))return e.toString();var t="";for(var n in e)s.call(e,n)&&e[n]&&(t=a(t,n));return t}function a(e,t){return t?e?e+" "+t:e+t:e}e.exports?(r.default=r,e.exports=r):void 0===(n=function(){return r}.apply(t,[]))||(e.exports=n)}()},8343(e,t,n){"use strict";const{normalizeIPv6:s,removeDotSegments:r,recomposeAuthority:o,normalizeComponentEncoding:a,isIPv4:i,nonSimpleDomain:c}=n(4834),{SCHEMES:l,getSchemeHandler:u}=n(343);function d(e,t,n,s){const o={};return s||(e=f(h(e,n),n),t=f(h(t,n),n)),!(n=n||{}).tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=r(t.path||""),o.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=r(t.path||""),o.query=t.query):(t.path?("/"===t.path[0]?o.path=r(t.path):(void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path:o.path="/"+t.path,o.path=r(o.path)),o.query=t.query):(o.path=e.path,void 0!==t.query?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function h(e,t){const n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},s=Object.assign({},t),a=[],i=u(s.scheme||n.scheme);i&&i.serialize&&i.serialize(n,s),void 0!==n.path&&(s.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),void 0!==n.scheme&&(n.path=n.path.split("%3A").join(":")))),"suffix"!==s.reference&&n.scheme&&a.push(n.scheme,":");const c=o(n);if(void 0!==c&&("suffix"!==s.reference&&a.push("//"),a.push(c),n.path&&"/"!==n.path[0]&&a.push("/")),void 0!==n.path){let e=n.path;s.absolutePath||i&&i.absolutePath||(e=r(e)),void 0===c&&"/"===e[0]&&"/"===e[1]&&(e="/%2F"+e.slice(2)),a.push(e)}return void 0!==n.query&&a.push("?",n.query),void 0!==n.fragment&&a.push("#",n.fragment),a.join("")}const p=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function f(e,t){const n=Object.assign({},t),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let o=!1;"suffix"===n.reference&&(e=n.scheme?n.scheme+":"+e:"//"+e);const a=e.match(p);if(a){if(r.scheme=a[1],r.userinfo=a[3],r.host=a[4],r.port=parseInt(a[5],10),r.path=a[6]||"",r.query=a[7],r.fragment=a[8],isNaN(r.port)&&(r.port=a[5]),r.host)if(!1===i(r.host)){const e=s(r.host);r.host=e.host.toLowerCase(),o=e.isIPV6}else o=!0;void 0!==r.scheme||void 0!==r.userinfo||void 0!==r.host||void 0!==r.port||void 0!==r.query||r.path?void 0===r.scheme?r.reference="relative":void 0===r.fragment?r.reference="absolute":r.reference="uri":r.reference="same-document",n.reference&&"suffix"!==n.reference&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");const t=u(n.scheme||r.scheme);if(!(n.unicodeSupport||t&&t.unicodeSupport)&&r.host&&(n.domainHost||t&&t.domainHost)&&!1===o&&c(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(e){r.error=r.error||"Host's domain name can not be converted to ASCII: "+e}(!t||t&&!t.skipNormalize)&&(-1!==e.indexOf("%")&&(void 0!==r.scheme&&(r.scheme=unescape(r.scheme)),void 0!==r.host&&(r.host=unescape(r.host))),r.path&&(r.path=escape(unescape(r.path))),r.fragment&&(r.fragment=encodeURI(decodeURIComponent(r.fragment)))),t&&t.parse&&t.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return r}const m={SCHEMES:l,normalize:function(e,t){return"string"==typeof e?e=h(f(e,t),t):"object"==typeof e&&(e=f(h(e,t),t)),e},resolve:function(e,t,n){const s=n?Object.assign({scheme:"null"},n):{scheme:"null"},r=d(f(e,s),f(t,s),s,!0);return s.skipEscape=!0,h(r,s)},resolveComponent:d,equal:function(e,t,n){return"string"==typeof e?(e=unescape(e),e=h(a(f(e,n),!0),{...n,skipEscape:!0})):"object"==typeof e&&(e=h(a(e,!0),{...n,skipEscape:!0})),"string"==typeof t?(t=unescape(t),t=h(a(f(t,n),!0),{...n,skipEscape:!0})):"object"==typeof t&&(t=h(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()},serialize:h,parse:f};e.exports=m,e.exports.default=m,e.exports.fastUri=m},343(e,t,n){"use strict";const{isUUID:s}=n(4834),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,o=["http","https","ws","wss","urn","urn:uuid"];function a(e){return!0===e.secure||!1!==e.secure&&!!e.scheme&&!(3!==e.scheme.length||"w"!==e.scheme[0]&&"W"!==e.scheme[0]||"s"!==e.scheme[1]&&"S"!==e.scheme[1]||"s"!==e.scheme[2]&&"S"!==e.scheme[2])}function i(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function c(e){const t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}const l={scheme:"http",domainHost:!0,parse:i,serialize:c},u={scheme:"ws",domainHost:!0,parse:function(e){return e.secure=a(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e){if(e.port!==(a(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,n]=e.resourceName.split("?");e.path=t&&"/"!==t?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}},d={http:l,https:{scheme:"https",domainHost:l.domainHost,parse:i,serialize:c},ws:u,wss:{scheme:"wss",domainHost:u.domainHost,parse:u.parse,serialize:u.serialize},urn:{scheme:"urn",parse:function(e,t){if(!e.path)return e.error="URN can not be parsed",e;const n=e.path.match(r);if(n){const s=t.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];const r=h(`${s}:${t.nid||e.nid}`);e.path=void 0,r&&(e=r.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e},serialize:function(e,t){if(void 0===e.nid)throw new Error("URN without nid cannot be serialized");const n=t.scheme||e.scheme||"urn",s=e.nid.toLowerCase(),r=h(`${n}:${t.nid||s}`);r&&(e=r.serialize(e,t));const o=e,a=e.nss;return o.path=`${s||t.nid}:${a}`,t.skipEscape=!0,o},skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:function(e,t){const n=e;return n.uuid=n.nss,n.nss=void 0,t.tolerant||n.uuid&&s(n.uuid)||(n.error=n.error||"UUID is not valid."),n},serialize:function(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t},skipNormalize:!0}};function h(e){return e&&(d[e]||d[e.toLowerCase()])||void 0}Object.setPrototypeOf(d,null),e.exports={wsIsSecure:a,SCHEMES:d,isValidSchemeName:function(e){return-1!==o.indexOf(e)},getSchemeHandler:h}},4834(e){"use strict";const t=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),n=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function s(e){let t="",n=0,s=0;for(s=0;s<e.length;s++)if(n=e[s].charCodeAt(0),48!==n){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[s];break}for(s+=1;s<e.length;s++){if(n=e[s].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[s]}return t}const r=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function a(e,t,n){if(e.length){const r=s(e);if(""===r)return n.error=!0,!1;t.push(r),e.length=0}return!0}function i(e){if(function(e){let t=0;for(let n=0;n<e.length;n++)":"===e[n]&&t++;return t}(e)<2)return{host:e,isIPV6:!1};const t=function(e){let t=0;const n={error:!1,address:"",zone:""},r=[],i=[];let c=!1,l=!1,u=a;for(let s=0;s<e.length;s++){const a=e[s];if("["!==a&&"]"!==a)if(":"!==a)if("%"===a){if(!u(i,r,n))break;u=o}else i.push(a);else{if(!0===c&&(l=!0),!u(i,r,n))break;if(++t>7){n.error=!0;break}s>0&&":"===e[s-1]&&(c=!0),r.push(":")}}return i.length&&(u===o?n.zone=i.join(""):l?r.push(i.join("")):r.push(s(i))),n.address=r.join(""),n}(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+="%"+t.zone,n+="%25"+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}e.exports={nonSimpleDomain:r,recomposeAuthority:function(e){const t=[];if(void 0!==e.userinfo&&(t.push(e.userinfo),t.push("@")),void 0!==e.host){let s=unescape(e.host);if(!n(s)){const t=i(s);s=!0===t.isIPV6?`[${t.escapedHost}]`:e.host}t.push(s)}return"number"!=typeof e.port&&"string"!=typeof e.port||(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0},normalizeComponentEncoding:function(e,t){const n=!0!==t?escape:unescape;return void 0!==e.scheme&&(e.scheme=n(e.scheme)),void 0!==e.userinfo&&(e.userinfo=n(e.userinfo)),void 0!==e.host&&(e.host=n(e.host)),void 0!==e.path&&(e.path=n(e.path)),void 0!==e.query&&(e.query=n(e.query)),void 0!==e.fragment&&(e.fragment=n(e.fragment)),e},removeDotSegments:function(e){let t=e;const n=[];let s=-1,r=0;for(;r=t.length;){if(1===r){if("."===t)break;if("/"===t){n.push("/");break}n.push(t);break}if(2===r){if("."===t[0]){if("."===t[1])break;if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&("."===t[1]||"/"===t[1])){n.push("/");break}}else if(3===r&&"/.."===t){0!==n.length&&n.pop(),n.push("/");break}if("."===t[0]){if("."===t[1]){if("/"===t[2]){t=t.slice(3);continue}}else if("/"===t[1]){t=t.slice(2);continue}}else if("/"===t[0]&&"."===t[1]){if("/"===t[2]){t=t.slice(2);continue}if("."===t[2]&&"/"===t[3]){t=t.slice(3),0!==n.length&&n.pop();continue}}if(-1===(s=t.indexOf("/",1))){n.push(t);break}n.push(t.slice(0,s)),t=t.slice(s)}return n.join("")},isIPv4:n,isUUID:t,normalizeIPv6:i,stringArrayToHexStripped:s}},3837(e){"use strict";e.exports=JSON.parse('{"$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON AnySchema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}')},2079(e){"use strict";e.exports=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}')}},t={};function n(s){var r=t[s];if(void 0!==r)return r.exports;var o=t[s]={exports:{}};return e[s](o,o.exports,n),o.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};(()=>{"use strict";n.r(s),n.d(s,{AILogo:()=>um,BluBetaHeading:()=>am,CHAT_STATUS:()=>Hh,ChatHeader:()=>cm,ChatHistoryDropdown:()=>vm,ChatHistoryList:()=>ym,ChatInput:()=>sm,ChatMessage:()=>Bf,ChatMessages:()=>Qf,CloudflareOpenAIClient:()=>Mh,ErrorAlert:()=>Zf,HeaderBar:()=>im,INPUT:()=>Cf,MCPError:()=>Ii,NFD_AGENTS_WEBSOCKET:()=>Bh,OpenAIError:()=>jh,SuggestionButton:()=>dm,TYPING_STATUS:()=>sp,ToolExecutionList:()=>Wf,TypingIndicator:()=>Yf,WelcomeScreen:()=>hm,WordPressMCPClient:()=>Ci,archiveConversation:()=>pm,buildWebSocketUrl:()=>tp,containsHtml:()=>If,containsMarkdown:()=>kp,convertToWebSocketUrl:()=>Qh,createMCPClient:()=>Pi,createOpenAIClient:()=>zh,debounce:()=>Fh,generateSessionId:()=>qh,getChatHistoryStorageKeys:()=>Yh,isInitialGreeting:()=>op,isLocalhost:()=>ep,mcpClient:()=>Ri,normalizeUrl:()=>np,openaiClient:()=>Dh,parseMarkdown:()=>Sp,removeConversationFromArchive:()=>fm,sanitizeHtml:()=>Tf,simpleHash:()=>Uh,useAIChat:()=>Vh,useNfdAgentsWebSocket:()=>gp});const e=Object.freeze({status:"aborted"});function t(e,t,n){function s(n,s){var r;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(r=n._zod).traits??(r.traits=new Set),n._zod.traits.add(e),t(n,s);for(const e in a.prototype)e in n||Object.defineProperty(n,e,{value:a.prototype[e].bind(n)});n._zod.constr=a,n._zod.def=s}const r=n?.Parent??Object;class o extends r{}function a(e){var t;const r=n?.Parent?new o:this;s(r,e),(t=r._zod).deferred??(t.deferred=[]);for(const e of r._zod.deferred)e();return r}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(a,"init",{value:s}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}Symbol("zod_brand");class r extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const o={};function a(e){return e&&Object.assign(o,e),o}function i(e,t){return"bigint"==typeof t?t.toString():t}function c(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function l(e){return null==e}function u(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function d(e,t,n){Object.defineProperty(e,t,{get(){{const s=n();return e[t]=s,s}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function h(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function p(e){return JSON.stringify(e)}const f=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function m(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const g=c(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function _(e){if(!1===m(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==m(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}const y=new Set(["string","number","symbol"]);function w(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function v(e,t,n){const s=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(s._zod.parent=e),s}function b(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}new Set(["string","number","bigint","boolean","symbol","undefined"]);const $={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function k(e,t=0){for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function S(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function x(e){return"string"==typeof e?e:e?.message}function E(e,t,n){const s={...e,path:e.path??[]};if(!e.message){const r=x(e.inst?._zod.def?.error?.(e))??x(t?.error?.(e))??x(n.customError?.(e))??x(n.localeError?.(e))??"Invalid input";s.message=r}return delete s.inst,delete s.continue,t?.reportInput||delete s.input,s}function T(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function I(...e){const[t,n,s]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:s}:{...t}}const C=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get:()=>JSON.stringify(t,i,2),enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},P=t("$ZodError",C),R=t("$ZodError",C,{Parent:Error}),A=e=>(t,n,s,o)=>{const i=s?Object.assign(s,{async:!1}):{async:!1},c=t._zod.run({value:n,issues:[]},i);if(c instanceof Promise)throw new r;if(c.issues.length){const t=new(o?.Err??e)(c.issues.map(e=>E(e,i,a())));throw f(t,o?.callee),t}return c.value},N=e=>async(t,n,s,r)=>{const o=s?Object.assign(s,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){const t=new(r?.Err??e)(i.issues.map(e=>E(e,o,a())));throw f(t,r?.callee),t}return i.value},O=e=>(t,n,s)=>{const o=s?{...s,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new r;return i.issues.length?{success:!1,error:new(e??P)(i.issues.map(e=>E(e,o,a())))}:{success:!0,data:i.value}},j=O(R),M=e=>async(t,n,s)=>{const r=s?Object.assign(s,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},r);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>E(e,r,a())))}:{success:!0,data:o.value}},z=M(R);function D(e){return!!e._zod}function L(e,t){return D(e)?j(e,t):e.safeParse(t)}function U(e){if(!e)return;let t;if(D(e)){const n=e;t=n._zod?.def?.shape}else t=e.shape;if(t){if("function"==typeof t)try{return t()}catch{return}return t}}const q=/^[cC][^\s-]{8,}$/,F=/^[0-9a-z]+$/,H=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,V=/^[0-9a-vA-V]{20}$/,W=/^[A-Za-z0-9]{27}$/,B=/^[a-zA-Z0-9_-]{21}$/,Z=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,G=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,K=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,J=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,X=/^(?:(?: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])$/,Y=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Q=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,ee=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,te=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ne=/^[A-Za-z0-9_-]*$/,se=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,re=/^\+(?:[0-9]){6,14}[0-9]$/,oe="(?:(?:\\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])))",ae=new RegExp(`^${oe}$`);function ie(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const ce=/^\d+$/,le=/^-?\d+(?:\.\d+)?/i,ue=/true|false/i,de=/null/i,he=/^[^A-Z]*$/,pe=/^[^a-z]*$/,fe=t("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),me={number:"number",bigint:"bigint",object:"date"},ge=t("$ZodCheckLessThan",(e,t)=>{fe.init(e,t);const n=me[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,s=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:n,code:"too_big",maximum:t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_e=t("$ZodCheckGreaterThan",(e,t)=>{fe.init(e,t);const n=me[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,s=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:n,code:"too_small",minimum:t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ye=t("$ZodCheckMultipleOf",(e,t)=>{fe.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===function(e,t){const n=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,r=n>s?n:s;return Number.parseInt(e.toFixed(r).replace(".",""))%Number.parseInt(t.toFixed(r).replace(".",""))/10**r}(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),we=t("$ZodCheckNumberFormat",(e,t)=>{fe.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),s=n?"int":"number",[r,o]=$[t.format];e._zod.onattach.push(e=>{const s=e._zod.bag;s.format=t.format,s.minimum=r,s.maximum=o,n&&(s.pattern=ce)}),e._zod.check=a=>{const i=a.value;if(n){if(!Number.isInteger(i))return void a.issues.push({expected:s,format:t.format,code:"invalid_type",input:i,inst:e});if(!Number.isSafeInteger(i))return void(i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,continue:!t.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,continue:!t.abort}))}i<r&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),i>o&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:o,inst:e})}}),ve=t("$ZodCheckMaxLength",(e,t)=>{var n;fe.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!l(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const s=n.value;if(s.length<=t.maximum)return;const r=T(s);n.issues.push({origin:r,code:"too_big",maximum:t.maximum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),be=t("$ZodCheckMinLength",(e,t)=>{var n;fe.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!l(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const s=n.value;if(s.length>=t.minimum)return;const r=T(s);n.issues.push({origin:r,code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),$e=t("$ZodCheckLengthEquals",(e,t)=>{var n;fe.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!l(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const s=n.value,r=s.length;if(r===t.length)return;const o=T(s),a=r>t.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ke=t("$ZodCheckStringFormat",(e,t)=>{var n,s;fe.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),Se=t("$ZodCheckRegex",(e,t)=>{ke.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),xe=t("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=he),ke.init(e,t)}),Ee=t("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=pe),ke.init(e,t)}),Te=t("$ZodCheckIncludes",(e,t)=>{fe.init(e,t);const n=w(t.includes),s=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=s,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(s)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Ie=t("$ZodCheckStartsWith",(e,t)=>{fe.init(e,t);const n=new RegExp(`^${w(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Ce=t("$ZodCheckEndsWith",(e,t)=>{fe.init(e,t);const n=new RegExp(`.*${w(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Pe=t("$ZodCheckOverwrite",(e,t)=>{fe.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Re{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),s=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const e of s)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const Ae={major:4,minor:0,patch:0},Ne=t("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ae;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const t of s)for(const n of t._zod.onattach)n(e);if(0===s.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let s,o=k(e);for(const a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(o)continue;const t=e.issues.length,i=a._zod.check(e);if(i instanceof Promise&&!1===n?.async)throw new r;if(s||i instanceof Promise)s=(s??Promise.resolve()).then(async()=>{await i,e.issues.length!==t&&(o||(o=k(e,t)))});else{if(e.issues.length===t)continue;o||(o=k(e,t))}}return s?s.then(()=>e):e};e._zod.run=(n,o)=>{const a=e._zod.parse(n,o);if(a instanceof Promise){if(!1===o.async)throw new r;return a.then(e=>t(e,s,o))}return t(a,s,o)}}e["~standard"]={validate:t=>{try{const n=j(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return z(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),Oe=t("$ZodString",(e,t)=>{var n;Ne.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=String(n.value)}catch(s){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),je=t("$ZodStringFormat",(e,t)=>{ke.init(e,t),Oe.init(e,t)}),Me=t("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=G),je.init(e,t)}),ze=t("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=K(e))}else t.pattern??(t.pattern=K());je.init(e,t)}),De=t("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=J),je.init(e,t)}),Le=t("$ZodURL",(e,t)=>{je.init(e,t),e._zod.check=n=>{try{const s=n.value,r=new URL(s),o=r.href;return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:se.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(!s.endsWith("/")&&o.endsWith("/")?n.value=o.slice(0,-1):n.value=o)}catch(s){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Ue=t("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),je.init(e,t)}),qe=t("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=B),je.init(e,t)}),Fe=t("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=q),je.init(e,t)}),He=t("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=F),je.init(e,t)}),Ve=t("$ZodULID",(e,t)=>{t.pattern??(t.pattern=H),je.init(e,t)}),We=t("$ZodXID",(e,t)=>{t.pattern??(t.pattern=V),je.init(e,t)}),Be=t("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=W),je.init(e,t)}),Ze=t("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=ie({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const s=`${t}(?:${n.join("|")})`;return new RegExp(`^${oe}T(?:${s})$`)}(t)),je.init(e,t)}),Ge=t("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ae),je.init(e,t)}),Ke=t("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${ie(t)}$`)),je.init(e,t)}),Je=t("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Z),je.init(e,t)}),Xe=t("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=X),je.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),Ye=t("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Y),je.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Qe=t("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Q),je.init(e,t)}),et=t("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ee),je.init(e,t),e._zod.check=n=>{const[s,r]=n.value.split("/");try{if(!r)throw new Error;const e=Number(r);if(`${e}`!==r)throw new Error;if(e<0||e>128)throw new Error;new URL(`http://[${s}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function tt(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const nt=t("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=te),je.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{tt(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),st=t("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ne),je.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{(function(e){if(!ne.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return tt(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),rt=t("$ZodE164",(e,t)=>{t.pattern??(t.pattern=re),je.init(e,t)}),ot=t("$ZodJWT",(e,t)=>{je.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[s]=n;if(!s)return!1;const r=JSON.parse(atob(s));return!("typ"in r&&"JWT"!==r?.typ||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),at=t("$ZodNumber",(e,t)=>{Ne.init(e,t),e._zod.pattern=e._zod.bag.pattern??le,e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const r=n.value;if("number"==typeof r&&!Number.isNaN(r)&&Number.isFinite(r))return n;const o="number"==typeof r?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...o?{received:o}:{}}),n}}),it=t("$ZodNumber",(e,t)=>{we.init(e,t),at.init(e,t)}),ct=t("$ZodBoolean",(e,t)=>{Ne.init(e,t),e._zod.pattern=ue,e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}const r=n.value;return"boolean"==typeof r||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),lt=t("$ZodNull",(e,t)=>{Ne.init(e,t),e._zod.pattern=de,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{const s=t.value;return null===s||t.issues.push({expected:"null",code:"invalid_type",input:s,inst:e}),t}}),ut=t("$ZodAny",(e,t)=>{Ne.init(e,t),e._zod.parse=e=>e}),dt=t("$ZodUnknown",(e,t)=>{Ne.init(e,t),e._zod.parse=e=>e}),ht=t("$ZodNever",(e,t)=>{Ne.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function pt(e,t,n){e.issues.length&&t.issues.push(...S(n,e.issues)),t.value[n]=e.value}const ft=t("$ZodArray",(e,t)=>{Ne.init(e,t),e._zod.parse=(n,s)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const o=[];for(let e=0;e<r.length;e++){const a=r[e],i=t.element._zod.run({value:a,issues:[]},s);i instanceof Promise?o.push(i.then(t=>pt(t,n,e))):pt(i,n,e)}return o.length?Promise.all(o).then(()=>n):n}});function mt(e,t,n){e.issues.length&&t.issues.push(...S(n,e.issues)),t.value[n]=e.value}function gt(e,t,n,s){e.issues.length?void 0===s[n]?t.value[n]=n in s?void 0:e.value:t.issues.push(...S(n,e.issues)):void 0===e.value?n in s&&(t.value[n]=void 0):t.value[n]=e.value}const _t=t("$ZodObject",(e,t)=>{Ne.init(e,t);const n=c(()=>{const e=Object.keys(t.shape);for(const n of e)if(!(t.shape[n]instanceof Ne))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const n=(s=t.shape,Object.keys(s).filter(e=>"optional"===s[e]._zod.optin&&"optional"===s[e]._zod.optout));var s;return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}});let s;d(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const s=e[t]._zod;if(s.values){n[t]??(n[t]=new Set);for(const e of s.values)n[t].add(e)}}return n});const r=m,a=!o.jitless,i=a&&g.value,l=t.catchall;let u;e._zod.parse=(o,c)=>{u??(u=n.value);const d=o.value;if(!r(d))return o.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),o;const h=[];if(a&&i&&!1===c?.async&&!0!==c.jitless)s||(s=(e=>{const t=new Re(["shape","payload","ctx"]),s=n.value,r=e=>{const t=p(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let a=0;for(const e of s.keys)o[e]="key_"+a++;t.write("const newResult = {}");for(const e of s.keys)if(s.optionalKeys.has(e)){const n=o[e];t.write(`const ${n} = ${r(e)};`);const s=p(e);t.write(`\n if (${n}.issues.length) {\n if (input[${s}] === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n payload.issues = payload.issues.concat(\n ${n}.issues.map((iss) => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}],\n }))\n );\n }\n } else if (${n}.value === undefined) {\n if (${s} in input) newResult[${s}] = undefined;\n } else {\n newResult[${s}] = ${n}.value;\n }\n `)}else{const n=o[e];t.write(`const ${n} = ${r(e)};`),t.write(`\n if (${n}.issues.length) payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${p(e)}, ...iss.path] : [${p(e)}]\n })));`),t.write(`newResult[${p(e)}] = ${n}.value`)}t.write("payload.value = newResult;"),t.write("return payload;");const i=t.compile();return(t,n)=>i(e,t,n)})(t.shape)),o=s(o,c);else{o.value={};const e=u.shape;for(const t of u.keys){const n=e[t],s=n._zod.run({value:d[t],issues:[]},c),r="optional"===n._zod.optin&&"optional"===n._zod.optout;s instanceof Promise?h.push(s.then(e=>r?gt(e,o,t,d):mt(e,o,t))):r?gt(s,o,t,d):mt(s,o,t)}}if(!l)return h.length?Promise.all(h).then(()=>o):o;const f=[],m=u.keySet,g=l._zod,_=g.def.type;for(const e of Object.keys(d)){if(m.has(e))continue;if("never"===_){f.push(e);continue}const t=g.run({value:d[e],issues:[]},c);t instanceof Promise?h.push(t.then(t=>mt(t,o,e))):mt(t,o,e)}return f.length&&o.issues.push({code:"unrecognized_keys",keys:f,input:d,inst:e}),h.length?Promise.all(h).then(()=>o):o}});function yt(e,t,n,s){for(const n of e)if(0===n.issues.length)return t.value=n.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>E(e,s,a())))}),t}const wt=t("$ZodUnion",(e,t)=>{Ne.init(e,t),d(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),d(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),d(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),d(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>u(e.source)).join("|")})$`)}}),e._zod.parse=(n,s)=>{let r=!1;const o=[];for(const e of t.options){const t=e._zod.run({value:n.value,issues:[]},s);if(t instanceof Promise)o.push(t),r=!0;else{if(0===t.issues.length)return t;o.push(t)}}return r?Promise.all(o).then(t=>yt(t,n,e,s)):yt(o,n,e,s)}}),vt=t("$ZodDiscriminatedUnion",(e,t)=>{wt.init(e,t);const n=e._zod.parse;d(e._zod,"propValues",()=>{const e={};for(const n of t.options){const s=n._zod.propValues;if(!s||0===Object.keys(s).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(s)){e[t]||(e[t]=new Set);for(const s of n)e[t].add(s)}}return e});const s=c(()=>{const e=t.options,n=new Map;for(const s of e){const e=s._zod.propValues[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,s)}}return n});e._zod.parse=(r,o)=>{const a=r.value;if(!m(a))return r.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),r;const i=s.value.get(a?.[t.discriminator]);return i?i._zod.run(r,o):t.unionFallback?n(r,o):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),r)}}),bt=t("$ZodIntersection",(e,t)=>{Ne.init(e,t),e._zod.parse=(e,n)=>{const s=e.value,r=t.left._zod.run({value:s,issues:[]},n),o=t.right._zod.run({value:s,issues:[]},n);return r instanceof Promise||o instanceof Promise?Promise.all([r,o]).then(([t,n])=>kt(e,t,n)):kt(e,r,o)}});function $t(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(_(e)&&_(t)){const n=Object.keys(t),s=Object.keys(e).filter(e=>-1!==n.indexOf(e)),r={...e,...t};for(const n of s){const s=$t(e[n],t[n]);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r[n]=s.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let s=0;s<e.length;s++){const r=$t(e[s],t[s]);if(!r.valid)return{valid:!1,mergeErrorPath:[s,...r.mergeErrorPath]};n.push(r.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function kt(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),k(e))return e;const s=$t(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const St=t("$ZodRecord",(e,t)=>{Ne.init(e,t),e._zod.parse=(n,s)=>{const r=n.value;if(!_(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;const o=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;n.value={};for(const e of a)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){const a=t.valueType._zod.run({value:r[e],issues:[]},s);a instanceof Promise?o.push(a.then(t=>{t.issues.length&&n.issues.push(...S(e,t.issues)),n.value[e]=t.value})):(a.issues.length&&n.issues.push(...S(e,a.issues)),n.value[e]=a.value)}let i;for(const e in r)a.has(e)||(i=i??[],i.push(e));i&&i.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:i})}else{n.value={};for(const i of Reflect.ownKeys(r)){if("__proto__"===i)continue;const c=t.keyType._zod.run({value:i,issues:[]},s);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:c.issues.map(e=>E(e,s,a())),input:i,path:[i],inst:e}),n.value[c.value]=c.value;continue}const l=t.valueType._zod.run({value:r[i],issues:[]},s);l instanceof Promise?o.push(l.then(e=>{e.issues.length&&n.issues.push(...S(i,e.issues)),n.value[c.value]=e.value})):(l.issues.length&&n.issues.push(...S(i,l.issues)),n.value[c.value]=l.value)}}return o.length?Promise.all(o).then(()=>n):n}}),xt=t("$ZodEnum",(e,t)=>{Ne.init(e,t);const n=function(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(e=>y.has(typeof e)).map(e=>"string"==typeof e?w(e):e.toString()).join("|")})$`),e._zod.parse=(t,s)=>{const r=t.value;return e._zod.values.has(r)||t.issues.push({code:"invalid_value",values:n,input:r,inst:e}),t}}),Et=t("$ZodLiteral",(e,t)=>{Ne.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?w(e):e?e.toString():String(e)).join("|")})$`),e._zod.parse=(n,s)=>{const r=n.value;return e._zod.values.has(r)||n.issues.push({code:"invalid_value",values:t.values,input:r,inst:e}),n}}),Tt=t("$ZodTransform",(e,t)=>{Ne.init(e,t),e._zod.parse=(e,n)=>{const s=t.transform(e.value,e);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(t=>(e.value=t,e));if(s instanceof Promise)throw new r;return e.value=s,e}}),It=t("$ZodOptional",(e,t)=>{Ne.init(e,t),e._zod.optin="optional",e._zod.optout="optional",d(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),d(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${u(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>"optional"===t.innerType._zod.optin?t.innerType._zod.run(e,n):void 0===e.value?e:t.innerType._zod.run(e,n)}),Ct=t("$ZodNullable",(e,t)=>{Ne.init(e,t),d(e._zod,"optin",()=>t.innerType._zod.optin),d(e._zod,"optout",()=>t.innerType._zod.optout),d(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${u(e.source)}|null)$`):void 0}),d(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),Pt=t("$ZodDefault",(e,t)=>{Ne.init(e,t),e._zod.optin="optional",d(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(void 0===e.value)return e.value=t.defaultValue,e;const s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(e=>Rt(e,t)):Rt(s,t)}});function Rt(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const At=t("$ZodPrefault",(e,t)=>{Ne.init(e,t),e._zod.optin="optional",d(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Nt=t("$ZodNonOptional",(e,t)=>{Ne.init(e,t),d(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,s)=>{const r=t.innerType._zod.run(n,s);return r instanceof Promise?r.then(t=>Ot(t,e)):Ot(r,e)}});function Ot(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const jt=t("$ZodCatch",(e,t)=>{Ne.init(e,t),e._zod.optin="optional",d(e._zod,"optout",()=>t.innerType._zod.optout),d(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{const s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(s=>(e.value=s.value,s.issues.length&&(e.value=t.catchValue({...e,error:{issues:s.issues.map(e=>E(e,n,a()))},input:e.value}),e.issues=[]),e)):(e.value=s.value,s.issues.length&&(e.value=t.catchValue({...e,error:{issues:s.issues.map(e=>E(e,n,a()))},input:e.value}),e.issues=[]),e)}}),Mt=t("$ZodPipe",(e,t)=>{Ne.init(e,t),d(e._zod,"values",()=>t.in._zod.values),d(e._zod,"optin",()=>t.in._zod.optin),d(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(e,n)=>{const s=t.in._zod.run(e,n);return s instanceof Promise?s.then(e=>zt(e,t,n)):zt(s,t,n)}});function zt(e,t,n){return k(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const Dt=t("$ZodReadonly",(e,t)=>{Ne.init(e,t),d(e._zod,"propValues",()=>t.innerType._zod.propValues),d(e._zod,"values",()=>t.innerType._zod.values),d(e._zod,"optin",()=>t.innerType._zod.optin),d(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{const s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(Lt):Lt(s)}});function Lt(e){return e.value=Object.freeze(e.value),e}const Ut=t("$ZodCustom",(e,t)=>{fe.init(e,t),Ne.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const s=n.value,r=t.fn(s);if(r instanceof Promise)return r.then(t=>qt(t,n,s,e));qt(r,n,s,e)}});function qt(e,t,n,s){if(!e){const e={code:"custom",input:n,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(e.params=s._zod.def.params),t.issues.push(I(e))}}Symbol("ZodOutput"),Symbol("ZodInput");class Ft{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const n=t[0];if(this._map.set(e,n),n&&"object"==typeof n&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function Ht(){return new Ft}const Vt=Ht();function Wt(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...b(t)})}function Bt(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...b(t)})}function Zt(e,t){return new ge({check:"less_than",...b(t),value:e,inclusive:!1})}function Gt(e,t){return new ge({check:"less_than",...b(t),value:e,inclusive:!0})}function Kt(e,t){return new _e({check:"greater_than",...b(t),value:e,inclusive:!1})}function Jt(e,t){return new _e({check:"greater_than",...b(t),value:e,inclusive:!0})}function Xt(e,t){return new ye({check:"multiple_of",...b(t),value:e})}function Yt(e,t){return new ve({check:"max_length",...b(t),maximum:e})}function Qt(e,t){return new be({check:"min_length",...b(t),minimum:e})}function en(e,t){return new $e({check:"length_equals",...b(t),length:e})}function tn(e){return new Pe({check:"overwrite",tx:e})}const nn=t("ZodISODateTime",(e,t)=>{Ze.init(e,t),wn.init(e,t)});function sn(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...b(t)})}(nn,e)}const rn=t("ZodISODate",(e,t)=>{Ge.init(e,t),wn.init(e,t)});const on=t("ZodISOTime",(e,t)=>{Ke.init(e,t),wn.init(e,t)});const an=t("ZodISODuration",(e,t)=>{Je.init(e,t),wn.init(e,t)});const cn=(e,t)=>{P.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t){const n=t||function(e){return e.message},s={_errors:[]},r=e=>{for(const t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>r({issues:e}));else if("invalid_key"===t.code)r({issues:t.issues});else if("invalid_element"===t.code)r({issues:t.issues});else if(0===t.path.length)s._errors.push(n(t));else{let e=s,r=0;for(;r<t.path.length;){const s=t.path[r];r===t.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(n(t))):e[s]=e[s]||{_errors:[]},e=e[s],r++}}};return r(e),s}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},s=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):s.push(t(r));return{formErrors:s,fieldErrors:n}}(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get:()=>0===e.issues.length}})},ln=(t("ZodError",cn),t("ZodError",cn,{Parent:Error})),un=A(ln),dn=N(ln),hn=O(ln),pn=M(ln),fn=t("ZodType",(e,t)=>(Ne.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,n)=>v(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>un(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>hn(e,t,n),e.parseAsync=async(t,n)=>dn(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>pn(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...b(n)})}(Is,e,t)}(t,n)),e.superRefine=t=>e.check(function(e){const t=function(e){const t=new fe({check:"custom"});return t._zod.check=e,t}(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(I(e,n.value,t._zod.def));else{const s=e;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),s.continue??(s.continue=!t._zod.def.abort),n.issues.push(I(s))}},e(n.value,n)));return t}(t)),e.overwrite=t=>e.check(tn(t)),e.optional=()=>ys(e),e.nullable=()=>vs(e),e.nullish=()=>ys(vs(e)),e.nonoptional=t=>function(e,t){return new ks({type:"nonoptional",innerType:e,...b(t)})}(e,t),e.array=()=>Qn(e),e.or=t=>rs([e,t]),e.and=t=>cs(e,t),e.transform=t=>Es(e,gs(t)),e.default=t=>{return n=t,new bs({type:"default",innerType:e,get defaultValue(){return"function"==typeof n?n():n}});var n},e.prefault=t=>{return n=t,new $s({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof n?n():n}});var n},e.catch=t=>{return new Ss({type:"catch",innerType:e,catchValue:"function"==typeof(n=t)?n:()=>n});var n},e.pipe=t=>Es(e,t),e.readonly=()=>new Ts({type:"readonly",innerType:e}),e.describe=t=>{const n=e.clone();return Vt.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>Vt.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Vt.get(e);const n=e.clone();return Vt.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),mn=t("_ZodString",(e,t)=>{Oe.init(e,t),fn.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new Se({check:"string_format",format:"regex",...b(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new Te({check:"string_format",format:"includes",...b(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new Ie({check:"string_format",format:"starts_with",...b(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new Ce({check:"string_format",format:"ends_with",...b(t),suffix:e})}(...t)),e.min=(...t)=>e.check(Qt(...t)),e.max=(...t)=>e.check(Yt(...t)),e.length=(...t)=>e.check(en(...t)),e.nonempty=(...t)=>e.check(Qt(1,...t)),e.lowercase=t=>e.check(function(e){return new xe({check:"string_format",format:"lowercase",...b(e)})}(t)),e.uppercase=t=>e.check(function(e){return new Ee({check:"string_format",format:"uppercase",...b(e)})}(t)),e.trim=()=>e.check(tn(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return tn(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(tn(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(tn(e=>e.toUpperCase()))}),gn=t("ZodString",(e,t)=>{Oe.init(e,t),mn.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...b(t)})}(vn,t)),e.url=t=>e.check(Bt(kn,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...b(t)})}(Dn,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...b(t)})}(Sn,t)),e.guid=t=>e.check(Wt(bn,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...b(t)})}($n,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...b(t)})}($n,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...b(t)})}($n,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...b(t)})}($n,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...b(t)})}(xn,t)),e.guid=t=>e.check(Wt(bn,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...b(t)})}(En,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...b(t)})}(Tn,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...b(t)})}(In,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...b(t)})}(jn,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...b(t)})}(Mn,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...b(t)})}(Cn,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...b(t)})}(Pn,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...b(t)})}(Rn,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...b(t)})}(An,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...b(t)})}(Nn,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...b(t)})}(On,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...b(t)})}(zn,t)),e.datetime=t=>e.check(sn(t)),e.date=t=>e.check(function(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...b(t)})}(rn,e)}(t)),e.time=t=>e.check(function(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...b(t)})}(on,e)}(t)),e.duration=t=>e.check(function(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...b(t)})}(an,e)}(t))});function yn(e){return function(e,t){return new e({type:"string",...b(t)})}(gn,e)}const wn=t("ZodStringFormat",(e,t)=>{je.init(e,t),mn.init(e,t)}),vn=t("ZodEmail",(e,t)=>{De.init(e,t),wn.init(e,t)}),bn=t("ZodGUID",(e,t)=>{Me.init(e,t),wn.init(e,t)}),$n=t("ZodUUID",(e,t)=>{ze.init(e,t),wn.init(e,t)}),kn=t("ZodURL",(e,t)=>{Le.init(e,t),wn.init(e,t)}),Sn=t("ZodEmoji",(e,t)=>{Ue.init(e,t),wn.init(e,t)}),xn=t("ZodNanoID",(e,t)=>{qe.init(e,t),wn.init(e,t)}),En=t("ZodCUID",(e,t)=>{Fe.init(e,t),wn.init(e,t)}),Tn=t("ZodCUID2",(e,t)=>{He.init(e,t),wn.init(e,t)}),In=t("ZodULID",(e,t)=>{Ve.init(e,t),wn.init(e,t)}),Cn=t("ZodXID",(e,t)=>{We.init(e,t),wn.init(e,t)}),Pn=t("ZodKSUID",(e,t)=>{Be.init(e,t),wn.init(e,t)}),Rn=t("ZodIPv4",(e,t)=>{Xe.init(e,t),wn.init(e,t)}),An=t("ZodIPv6",(e,t)=>{Ye.init(e,t),wn.init(e,t)}),Nn=t("ZodCIDRv4",(e,t)=>{Qe.init(e,t),wn.init(e,t)}),On=t("ZodCIDRv6",(e,t)=>{et.init(e,t),wn.init(e,t)}),jn=t("ZodBase64",(e,t)=>{nt.init(e,t),wn.init(e,t)}),Mn=t("ZodBase64URL",(e,t)=>{st.init(e,t),wn.init(e,t)}),zn=t("ZodE164",(e,t)=>{rt.init(e,t),wn.init(e,t)}),Dn=t("ZodJWT",(e,t)=>{ot.init(e,t),wn.init(e,t)}),Ln=t("ZodNumber",(e,t)=>{at.init(e,t),fn.init(e,t),e.gt=(t,n)=>e.check(Kt(t,n)),e.gte=(t,n)=>e.check(Jt(t,n)),e.min=(t,n)=>e.check(Jt(t,n)),e.lt=(t,n)=>e.check(Zt(t,n)),e.lte=(t,n)=>e.check(Gt(t,n)),e.max=(t,n)=>e.check(Gt(t,n)),e.int=t=>e.check(Fn(t)),e.safe=t=>e.check(Fn(t)),e.positive=t=>e.check(Kt(0,t)),e.nonnegative=t=>e.check(Jt(0,t)),e.negative=t=>e.check(Zt(0,t)),e.nonpositive=t=>e.check(Gt(0,t)),e.multipleOf=(t,n)=>e.check(Xt(t,n)),e.step=(t,n)=>e.check(Xt(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Un(e){return function(e,t){return new e({type:"number",checks:[],...b(t)})}(Ln,e)}const qn=t("ZodNumberFormat",(e,t)=>{it.init(e,t),Ln.init(e,t)});function Fn(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...b(t)})}(qn,e)}const Hn=t("ZodBoolean",(e,t)=>{ct.init(e,t),fn.init(e,t)});function Vn(e){return function(e,t){return new e({type:"boolean",...b(t)})}(Hn,e)}const Wn=t("ZodNull",(e,t)=>{lt.init(e,t),fn.init(e,t)});function Bn(e){return function(e,t){return new e({type:"null",...b(t)})}(Wn,e)}const Zn=t("ZodAny",(e,t)=>{ut.init(e,t),fn.init(e,t)}),Gn=t("ZodUnknown",(e,t)=>{dt.init(e,t),fn.init(e,t)});function Kn(){return new Gn({type:"unknown"})}const Jn=t("ZodNever",(e,t)=>{ht.init(e,t),fn.init(e,t)});function Xn(e){return function(e,t){return new e({type:"never",...b(t)})}(Jn,e)}const Yn=t("ZodArray",(e,t)=>{ft.init(e,t),fn.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(Qt(t,n)),e.nonempty=t=>e.check(Qt(1,t)),e.max=(t,n)=>e.check(Yt(t,n)),e.length=(t,n)=>e.check(en(t,n)),e.unwrap=()=>e.element});function Qn(e,t){return function(e,t,n){return new e({type:"array",element:t,...b(n)})}(Yn,e,t)}const es=t("ZodObject",(e,t)=>{_t.init(e,t),fn.init(e,t),d(e,"shape",()=>t.shape),e.keyof=()=>hs(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Kn()}),e.loose=()=>e.clone({...e._zod.def,catchall:Kn()}),e.strict=()=>e.clone({...e._zod.def,catchall:Xn()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!_(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const n={...e._zod.def.shape,...t};return h(this,"shape",n),n},checks:[]};return v(e,n)}(e,t),e.merge=t=>{return s=t,v(n=e,{...n._zod.def,get shape(){const e={...n._zod.def.shape,...s._zod.def.shape};return h(this,"shape",e),e},catchall:s._zod.def.catchall,checks:[]});var n,s},e.pick=t=>function(e,t){const n={},s=e._zod.def;for(const e in t){if(!(e in s.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&(n[e]=s.shape[e])}return v(e,{...e._zod.def,shape:n,checks:[]})}(e,t),e.omit=t=>function(e,t){const n={...e._zod.def.shape},s=e._zod.def;for(const e in t){if(!(e in s.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return v(e,{...e._zod.def,shape:n,checks:[]})}(e,t),e.partial=(...t)=>function(e,t,n){const s=t._zod.def.shape,r={...s};if(n)for(const t in n){if(!(t in s))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(r[t]=e?new e({type:"optional",innerType:s[t]}):s[t])}else for(const t in s)r[t]=e?new e({type:"optional",innerType:s[t]}):s[t];return v(t,{...t._zod.def,shape:r,checks:[]})}(_s,e,t[0]),e.required=(...t)=>function(e,t,n){const s=t._zod.def.shape,r={...s};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(r[t]=new e({type:"nonoptional",innerType:s[t]}))}else for(const t in s)r[t]=new e({type:"nonoptional",innerType:s[t]});return v(t,{...t._zod.def,shape:r,checks:[]})}(ks,e,t[0])});function ts(e,t){const n={type:"object",get shape(){return h(this,"shape",{...e}),this.shape},...b(t)};return new es(n)}function ns(e,t){return new es({type:"object",get shape(){return h(this,"shape",{...e}),this.shape},catchall:Kn(),...b(t)})}const ss=t("ZodUnion",(e,t)=>{wt.init(e,t),fn.init(e,t),e.options=t.options});function rs(e,t){return new ss({type:"union",options:e,...b(t)})}const os=t("ZodDiscriminatedUnion",(e,t)=>{ss.init(e,t),vt.init(e,t)});function as(e,t,n){return new os({type:"union",options:t,discriminator:e,...b(n)})}const is=t("ZodIntersection",(e,t)=>{bt.init(e,t),fn.init(e,t)});function cs(e,t){return new is({type:"intersection",left:e,right:t})}const ls=t("ZodRecord",(e,t)=>{St.init(e,t),fn.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function us(e,t,n){return new ls({type:"record",keyType:e,valueType:t,...b(n)})}const ds=t("ZodEnum",(e,t)=>{xt.init(e,t),fn.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,s)=>{const r={};for(const s of e){if(!n.has(s))throw new Error(`Key ${s} not found in enum`);r[s]=t.entries[s]}return new ds({...t,checks:[],...b(s),entries:r})},e.exclude=(e,s)=>{const r={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete r[t]}return new ds({...t,checks:[],...b(s),entries:r})}});function hs(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ds({type:"enum",entries:n,...b(t)})}const ps=t("ZodLiteral",(e,t)=>{Et.init(e,t),fn.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function fs(e,t){return new ps({type:"literal",values:Array.isArray(e)?e:[e],...b(t)})}const ms=t("ZodTransform",(e,t)=>{Tt.init(e,t),fn.init(e,t),e._zod.parse=(n,s)=>{n.addIssue=s=>{if("string"==typeof s)n.issues.push(I(s,n.value,t));else{const t=s;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),t.continue??(t.continue=!0),n.issues.push(I(t))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(e=>(n.value=e,n)):(n.value=r,n)}});function gs(e){return new ms({type:"transform",transform:e})}const _s=t("ZodOptional",(e,t)=>{It.init(e,t),fn.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ys(e){return new _s({type:"optional",innerType:e})}const ws=t("ZodNullable",(e,t)=>{Ct.init(e,t),fn.init(e,t),e.unwrap=()=>e._zod.def.innerType});function vs(e){return new ws({type:"nullable",innerType:e})}const bs=t("ZodDefault",(e,t)=>{Pt.init(e,t),fn.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),$s=t("ZodPrefault",(e,t)=>{At.init(e,t),fn.init(e,t),e.unwrap=()=>e._zod.def.innerType}),ks=t("ZodNonOptional",(e,t)=>{Nt.init(e,t),fn.init(e,t),e.unwrap=()=>e._zod.def.innerType}),Ss=t("ZodCatch",(e,t)=>{jt.init(e,t),fn.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),xs=t("ZodPipe",(e,t)=>{Mt.init(e,t),fn.init(e,t),e.in=t.in,e.out=t.out});function Es(e,t){return new xs({type:"pipe",in:e,out:t})}const Ts=t("ZodReadonly",(e,t)=>{Dt.init(e,t),fn.init(e,t)}),Is=t("ZodCustom",(e,t)=>{Ut.init(e,t),fn.init(e,t)});function Cs(e,t){return Es(gs(e),t)}const Ps="2025-11-25",Rs=[Ps,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],As="io.modelcontextprotocol/related-task",Ns="2.0",Os=function(e,t,n){const s=b(n);return s.abort??(s.abort=!0),new e({type:"custom",check:"custom",fn:(e=>null!==e&&("object"==typeof e||"function"==typeof e))??(()=>!0),...s})}(Is,0,void 0);const js=rs([yn(),Un().int()]),Ms=yn(),zs=(ns({ttl:rs([Un(),Bn()]).optional(),pollInterval:Un().optional()}),ts({ttl:Un().optional()})),Ds=ts({taskId:yn()}),Ls=ns({progressToken:js.optional(),[As]:Ds.optional()}),Us=ts({_meta:Ls.optional()}),qs=Us.extend({task:zs.optional()}),Fs=ts({method:yn(),params:Us.loose().optional()}),Hs=ts({_meta:Ls.optional()}),Vs=ts({method:yn(),params:Hs.loose().optional()}),Ws=ns({_meta:Ls.optional()}),Bs=rs([yn(),Un().int()]),Zs=ts({jsonrpc:fs(Ns),id:Bs,...Fs.shape}).strict(),Gs=e=>Zs.safeParse(e).success,Ks=ts({jsonrpc:fs(Ns),...Vs.shape}).strict(),Js=ts({jsonrpc:fs(Ns),id:Bs,result:Ws}).strict(),Xs=e=>Js.safeParse(e).success;var Ys;!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"}(Ys||(Ys={}));const Qs=ts({jsonrpc:fs(Ns),id:Bs.optional(),error:ts({code:Un().int(),message:yn(),data:Kn().optional()})}).strict(),er=rs([Zs,Ks,Js,Qs]),tr=(rs([Js,Qs]),Ws.strict()),nr=Hs.extend({requestId:Bs.optional(),reason:yn().optional()}),sr=Vs.extend({method:fs("notifications/cancelled"),params:nr}),rr=ts({src:yn(),mimeType:yn().optional(),sizes:Qn(yn()).optional(),theme:hs(["light","dark"]).optional()}),or=ts({icons:Qn(rr).optional()}),ar=ts({name:yn(),title:yn().optional()}),ir=ar.extend({...ar.shape,...or.shape,version:yn(),websiteUrl:yn().optional(),description:yn().optional()}),cr=cs(ts({applyDefaults:Vn().optional()}),us(yn(),Kn())),lr=Cs(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,cs(ts({form:cr.optional(),url:Os.optional()}),us(yn(),Kn()).optional())),ur=ns({list:Os.optional(),cancel:Os.optional(),requests:ns({sampling:ns({createMessage:Os.optional()}).optional(),elicitation:ns({create:Os.optional()}).optional()}).optional()}),dr=ns({list:Os.optional(),cancel:Os.optional(),requests:ns({tools:ns({call:Os.optional()}).optional()}).optional()}),hr=ts({experimental:us(yn(),Os).optional(),sampling:ts({context:Os.optional(),tools:Os.optional()}).optional(),elicitation:lr.optional(),roots:ts({listChanged:Vn().optional()}).optional(),tasks:ur.optional()}),pr=Us.extend({protocolVersion:yn(),capabilities:hr,clientInfo:ir}),fr=Fs.extend({method:fs("initialize"),params:pr}),mr=ts({experimental:us(yn(),Os).optional(),logging:Os.optional(),completions:Os.optional(),prompts:ts({listChanged:Vn().optional()}).optional(),resources:ts({subscribe:Vn().optional(),listChanged:Vn().optional()}).optional(),tools:ts({listChanged:Vn().optional()}).optional(),tasks:dr.optional()}),gr=Ws.extend({protocolVersion:yn(),capabilities:mr,serverInfo:ir,instructions:yn().optional()}),_r=Vs.extend({method:fs("notifications/initialized"),params:Hs.optional()}),yr=Fs.extend({method:fs("ping"),params:Us.optional()}),wr=ts({progress:Un(),total:ys(Un()),message:ys(yn())}),vr=ts({...Hs.shape,...wr.shape,progressToken:js}),br=Vs.extend({method:fs("notifications/progress"),params:vr}),$r=Us.extend({cursor:Ms.optional()}),kr=Fs.extend({params:$r.optional()}),Sr=Ws.extend({nextCursor:Ms.optional()}),xr=hs(["working","input_required","completed","failed","cancelled"]),Er=ts({taskId:yn(),status:xr,ttl:rs([Un(),Bn()]),createdAt:yn(),lastUpdatedAt:yn(),pollInterval:ys(Un()),statusMessage:ys(yn())}),Tr=Ws.extend({task:Er}),Ir=Hs.merge(Er),Cr=Vs.extend({method:fs("notifications/tasks/status"),params:Ir}),Pr=Fs.extend({method:fs("tasks/get"),params:Us.extend({taskId:yn()})}),Rr=Ws.merge(Er),Ar=Fs.extend({method:fs("tasks/result"),params:Us.extend({taskId:yn()})}),Nr=(Ws.loose(),kr.extend({method:fs("tasks/list")})),Or=Sr.extend({tasks:Qn(Er)}),jr=Fs.extend({method:fs("tasks/cancel"),params:Us.extend({taskId:yn()})}),Mr=Ws.merge(Er),zr=ts({uri:yn(),mimeType:ys(yn()),_meta:us(yn(),Kn()).optional()}),Dr=zr.extend({text:yn()}),Lr=yn().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ur=zr.extend({blob:Lr}),qr=hs(["user","assistant"]),Fr=ts({audience:Qn(qr).optional(),priority:Un().min(0).max(1).optional(),lastModified:sn({offset:!0}).optional()}),Hr=ts({...ar.shape,...or.shape,uri:yn(),description:ys(yn()),mimeType:ys(yn()),annotations:Fr.optional(),_meta:ys(ns({}))}),Vr=ts({...ar.shape,...or.shape,uriTemplate:yn(),description:ys(yn()),mimeType:ys(yn()),annotations:Fr.optional(),_meta:ys(ns({}))}),Wr=kr.extend({method:fs("resources/list")}),Br=Sr.extend({resources:Qn(Hr)}),Zr=kr.extend({method:fs("resources/templates/list")}),Gr=Sr.extend({resourceTemplates:Qn(Vr)}),Kr=Us.extend({uri:yn()}),Jr=Kr,Xr=Fs.extend({method:fs("resources/read"),params:Jr}),Yr=Ws.extend({contents:Qn(rs([Dr,Ur]))}),Qr=Vs.extend({method:fs("notifications/resources/list_changed"),params:Hs.optional()}),eo=Kr,to=Fs.extend({method:fs("resources/subscribe"),params:eo}),no=Kr,so=Fs.extend({method:fs("resources/unsubscribe"),params:no}),ro=Hs.extend({uri:yn()}),oo=Vs.extend({method:fs("notifications/resources/updated"),params:ro}),ao=ts({name:yn(),description:ys(yn()),required:ys(Vn())}),io=ts({...ar.shape,...or.shape,description:ys(yn()),arguments:ys(Qn(ao)),_meta:ys(ns({}))}),co=kr.extend({method:fs("prompts/list")}),lo=Sr.extend({prompts:Qn(io)}),uo=Us.extend({name:yn(),arguments:us(yn(),yn()).optional()}),ho=Fs.extend({method:fs("prompts/get"),params:uo}),po=ts({type:fs("text"),text:yn(),annotations:Fr.optional(),_meta:us(yn(),Kn()).optional()}),fo=ts({type:fs("image"),data:Lr,mimeType:yn(),annotations:Fr.optional(),_meta:us(yn(),Kn()).optional()}),mo=ts({type:fs("audio"),data:Lr,mimeType:yn(),annotations:Fr.optional(),_meta:us(yn(),Kn()).optional()}),go=ts({type:fs("tool_use"),name:yn(),id:yn(),input:us(yn(),Kn()),_meta:us(yn(),Kn()).optional()}),_o=ts({type:fs("resource"),resource:rs([Dr,Ur]),annotations:Fr.optional(),_meta:us(yn(),Kn()).optional()}),yo=rs([po,fo,mo,Hr.extend({type:fs("resource_link")}),_o]),wo=ts({role:qr,content:yo}),vo=Ws.extend({description:yn().optional(),messages:Qn(wo)}),bo=Vs.extend({method:fs("notifications/prompts/list_changed"),params:Hs.optional()}),$o=ts({title:yn().optional(),readOnlyHint:Vn().optional(),destructiveHint:Vn().optional(),idempotentHint:Vn().optional(),openWorldHint:Vn().optional()}),ko=ts({taskSupport:hs(["required","optional","forbidden"]).optional()}),So=ts({...ar.shape,...or.shape,description:yn().optional(),inputSchema:ts({type:fs("object"),properties:us(yn(),Os).optional(),required:Qn(yn()).optional()}).catchall(Kn()),outputSchema:ts({type:fs("object"),properties:us(yn(),Os).optional(),required:Qn(yn()).optional()}).catchall(Kn()).optional(),annotations:$o.optional(),execution:ko.optional(),_meta:us(yn(),Kn()).optional()}),xo=kr.extend({method:fs("tools/list")}),Eo=Sr.extend({tools:Qn(So)}),To=Ws.extend({content:Qn(yo).default([]),structuredContent:us(yn(),Kn()).optional(),isError:Vn().optional()}),Io=(To.or(Ws.extend({toolResult:Kn()})),qs.extend({name:yn(),arguments:us(yn(),Kn()).optional()})),Co=Fs.extend({method:fs("tools/call"),params:Io}),Po=Vs.extend({method:fs("notifications/tools/list_changed"),params:Hs.optional()}),Ro=ts({autoRefresh:Vn().default(!0),debounceMs:Un().int().nonnegative().default(300)}),Ao=hs(["debug","info","notice","warning","error","critical","alert","emergency"]),No=Us.extend({level:Ao}),Oo=Fs.extend({method:fs("logging/setLevel"),params:No}),jo=Hs.extend({level:Ao,logger:yn().optional(),data:Kn()}),Mo=Vs.extend({method:fs("notifications/message"),params:jo}),zo=ts({name:yn().optional()}),Do=ts({hints:Qn(zo).optional(),costPriority:Un().min(0).max(1).optional(),speedPriority:Un().min(0).max(1).optional(),intelligencePriority:Un().min(0).max(1).optional()}),Lo=ts({mode:hs(["auto","required","none"]).optional()}),Uo=ts({type:fs("tool_result"),toolUseId:yn().describe("The unique identifier for the corresponding tool call."),content:Qn(yo).default([]),structuredContent:ts({}).loose().optional(),isError:Vn().optional(),_meta:us(yn(),Kn()).optional()}),qo=as("type",[po,fo,mo]),Fo=as("type",[po,fo,mo,go,Uo]),Ho=ts({role:qr,content:rs([Fo,Qn(Fo)]),_meta:us(yn(),Kn()).optional()}),Vo=qs.extend({messages:Qn(Ho),modelPreferences:Do.optional(),systemPrompt:yn().optional(),includeContext:hs(["none","thisServer","allServers"]).optional(),temperature:Un().optional(),maxTokens:Un().int(),stopSequences:Qn(yn()).optional(),metadata:Os.optional(),tools:Qn(So).optional(),toolChoice:Lo.optional()}),Wo=Fs.extend({method:fs("sampling/createMessage"),params:Vo}),Bo=Ws.extend({model:yn(),stopReason:ys(hs(["endTurn","stopSequence","maxTokens"]).or(yn())),role:qr,content:qo}),Zo=Ws.extend({model:yn(),stopReason:ys(hs(["endTurn","stopSequence","maxTokens","toolUse"]).or(yn())),role:qr,content:rs([Fo,Qn(Fo)])}),Go=ts({type:fs("boolean"),title:yn().optional(),description:yn().optional(),default:Vn().optional()}),Ko=ts({type:fs("string"),title:yn().optional(),description:yn().optional(),minLength:Un().optional(),maxLength:Un().optional(),format:hs(["email","uri","date","date-time"]).optional(),default:yn().optional()}),Jo=ts({type:hs(["number","integer"]),title:yn().optional(),description:yn().optional(),minimum:Un().optional(),maximum:Un().optional(),default:Un().optional()}),Xo=ts({type:fs("string"),title:yn().optional(),description:yn().optional(),enum:Qn(yn()),default:yn().optional()}),Yo=ts({type:fs("string"),title:yn().optional(),description:yn().optional(),oneOf:Qn(ts({const:yn(),title:yn()})),default:yn().optional()}),Qo=ts({type:fs("string"),title:yn().optional(),description:yn().optional(),enum:Qn(yn()),enumNames:Qn(yn()).optional(),default:yn().optional()}),ea=rs([Xo,Yo]),ta=rs([ts({type:fs("array"),title:yn().optional(),description:yn().optional(),minItems:Un().optional(),maxItems:Un().optional(),items:ts({type:fs("string"),enum:Qn(yn())}),default:Qn(yn()).optional()}),ts({type:fs("array"),title:yn().optional(),description:yn().optional(),minItems:Un().optional(),maxItems:Un().optional(),items:ts({anyOf:Qn(ts({const:yn(),title:yn()}))}),default:Qn(yn()).optional()})]),na=rs([Qo,ea,ta]),sa=rs([na,Go,Ko,Jo]),ra=rs([qs.extend({mode:fs("form").optional(),message:yn(),requestedSchema:ts({type:fs("object"),properties:us(yn(),sa),required:Qn(yn()).optional()})}),qs.extend({mode:fs("url"),message:yn(),elicitationId:yn(),url:yn().url()})]),oa=Fs.extend({method:fs("elicitation/create"),params:ra}),aa=Hs.extend({elicitationId:yn()}),ia=Vs.extend({method:fs("notifications/elicitation/complete"),params:aa}),ca=Ws.extend({action:hs(["accept","decline","cancel"]),content:Cs(e=>null===e?void 0:e,us(yn(),rs([yn(),Un(),Vn(),Qn(yn())])).optional())}),la=ts({type:fs("ref/resource"),uri:yn()}),ua=ts({type:fs("ref/prompt"),name:yn()}),da=Us.extend({ref:rs([ua,la]),argument:ts({name:yn(),value:yn()}),context:ts({arguments:us(yn(),yn()).optional()}).optional()}),ha=Fs.extend({method:fs("completion/complete"),params:da}),pa=Ws.extend({completion:ns({values:Qn(yn()).max(100),total:ys(Un().int()),hasMore:ys(Vn())})}),fa=ts({uri:yn().startsWith("file://"),name:yn().optional(),_meta:us(yn(),Kn()).optional()}),ma=Fs.extend({method:fs("roots/list"),params:Us.optional()}),ga=Ws.extend({roots:Qn(fa)}),_a=Vs.extend({method:fs("notifications/roots/list_changed"),params:Hs.optional()});rs([yr,fr,ha,Oo,ho,co,Wr,Zr,Xr,to,so,Co,xo,Pr,Ar,Nr,jr]),rs([sr,br,_r,_a,Cr]),rs([tr,Bo,Zo,ca,ga,Rr,Or,Tr]),rs([yr,Wo,oa,ma,Pr,Ar,Nr,jr]),rs([sr,br,Mo,oo,Qr,Po,bo,Cr,ia]),rs([tr,gr,pa,vo,lo,Br,Gr,Yr,To,Eo,Rr,Or,Tr]);class ya extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===Ys.UrlElicitationRequired&&n){const e=n;if(e.elicitations)return new wa(e.elicitations,t)}return new ya(e,t,n)}}class wa extends ya{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Ys.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function va(e){return"completed"===e||"failed"===e||"cancelled"===e}function ba(e){const t=U(e),n=t?.method;if(!n)throw new Error("Schema is missing a method literal");const s=function(e){if(D(e)){const t=e,n=t._zod?.def;if(n){if(void 0!==n.value)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}}const t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}const n=e.value;if(void 0!==n)return n}(n);if("string"!=typeof s)throw new Error("Schema method literal must be a string");return s}function $a(e,t){const n=L(e,t);if(!n.success)throw n.error;return n.data}Symbol("Let zodToJsonSchema decide on which parser to use"),new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");class ka{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(sr,e=>{this._oncancel(e)}),this.setNotificationHandler(br,e=>{this._onprogress(e)}),this.setRequestHandler(yr,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Pr,async(e,t)=>{const n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new ya(Ys.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Ar,async(e,t)=>{const n=async()=>{const s=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(s,t.sessionId);){if("response"===e.type||"error"===e.type){const t=e.message,n=t.id,s=this._requestResolvers.get(n);if(s)if(this._requestResolvers.delete(n),"response"===e.type)s(t);else{const e=t;s(new ya(e.error.code,e.error.message,e.error.data))}else{const t="response"===e.type?"Response":"Error";this._onerror(new Error(`${t} handler missing for request ${n}`))}continue}await(this._transport?.send(e.message,{relatedRequestId:t.requestId}))}}const r=await this._taskStore.getTask(s,t.sessionId);if(!r)throw new ya(Ys.InvalidParams,`Task not found: ${s}`);if(!va(r.status))return await this._waitForTaskUpdate(s,t.signal),await n();if(va(r.status)){const e=await this._taskStore.getTaskResult(s,t.sessionId);return this._clearTaskQueue(s),{...e,_meta:{...e._meta,[As]:{taskId:s}}}}return await n()};return await n()}),this.setRequestHandler(Nr,async(e,t)=>{try{const{tasks:n,nextCursor:s}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:s,_meta:{}}}catch(e){throw new ya(Ys.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(jr,async(e,t)=>{try{const n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new ya(Ys.InvalidParams,`Task not found: ${e.params.taskId}`);if(va(n.status))throw new ya(Ys.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId);const s=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!s)throw new ya(Ys.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...s}}catch(e){if(e instanceof ya)throw e;throw new ya(Ys.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const t=this._requestHandlerAbortControllers.get(e.params.requestId);t?.abort(e.params.reason)}_setupTimeout(e,t,n,s,r=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:r,onTimeout:s})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),ya.fromError(Ys.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new 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;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};const s=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{var n;s?.(e,t),Xs(e)||(e=>Qs.safeParse(e).success)(e)?this._onresponse(e):Gs(e)?this._onrequest(e,t):(n=e,Ks.safeParse(n).success?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`)))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();const t=ya.fromError(Ys.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){const n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,r=e.params?._meta?.[As]?.taskId;if(void 0===n){const t={jsonrpc:"2.0",id:e.id,error:{code:Ys.MethodNotFound,message:"Method not found"}};return void(r&&this._taskMessageQueue?this._enqueueTaskMessage(r,{type:"error",message:t,timestamp:Date.now()},s?.sessionId).catch(e=>this._onerror(new Error(`Failed to enqueue error response: ${e}`))):s?.send(t).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`))))}const o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);const a=(i=e.params,qs.safeParse(i).success?e.params.task:void 0);var i;const c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,l={signal:o.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(o.signal.aborted)return;const n={relatedRequestId:e.id};r&&(n.relatedTask={taskId:r}),await this.notification(t,n)},sendRequest:async(t,n,s)=>{if(o.signal.aborted)throw new ya(Ys.ConnectionClosed,"Request was cancelled");const a={...s,relatedRequestId:e.id};r&&!a.relatedTask&&(a.relatedTask={taskId:r});const i=a.relatedTask?.taskId??r;return i&&c&&await c.updateTaskStatus(i,"input_required"),await this.request(t,n,a)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:r,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async t=>{if(o.signal.aborted)return;const n={result:t,jsonrpc:"2.0",id:e.id};r&&this._taskMessageQueue?await this._enqueueTaskMessage(r,{type:"response",message:n,timestamp:Date.now()},s?.sessionId):await(s?.send(n))},async t=>{if(o.signal.aborted)return;const n={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Ys.InternalError,message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};r&&this._taskMessageQueue?await this._enqueueTaskMessage(r,{type:"error",message:n,timestamp:Date.now()},s?.sessionId):await(s?.send(n))}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...n}=e.params,s=Number(t),r=this._progressHandlers.get(s);if(!r)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const o=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&o&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(e){return this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),void o(e)}r(n)}_onresponse(e){const t=Number(e.id),n=this._requestResolvers.get(t);if(n)return this._requestResolvers.delete(t),void(Xs(e)?n(e):n(new ya(e.error.code,e.error.message,e.error.data)));const s=this._responseHandlers.get(t);if(void 0===s)return void this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let r=!1;if(Xs(e)&&e.result&&"object"==typeof e.result){const n=e.result;if(n.task&&"object"==typeof n.task){const e=n.task;"string"==typeof e.taskId&&(r=!0,this._taskProgressTokens.set(e.taskId,t))}}r||this._progressHandlers.delete(t),Xs(e)?s(e):s(ya.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,n){const{task:s}=n??{};if(!s){try{const s=await this.request(e,t,n);yield{type:"result",result:s}}catch(e){yield{type:"error",error:e instanceof ya?e:new ya(Ys.InternalError,String(e))}}return}let r;try{const s=await this.request(e,Tr,n);if(!s.task)throw new ya(Ys.InternalError,"Task creation did not return a task");for(r=s.task.taskId,yield{type:"taskCreated",task:s.task};;){const e=await this.getTask({taskId:r},n);if(yield{type:"taskStatus",task:e},va(e.status)){if("completed"===e.status){const e=await this.getTaskResult({taskId:r},t,n);yield{type:"result",result:e}}else"failed"===e.status?yield{type:"error",error:new ya(Ys.InternalError,`Task ${r} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new ya(Ys.InternalError,`Task ${r} was cancelled`)});return}if("input_required"===e.status){const e=await this.getTaskResult({taskId:r},t,n);return void(yield{type:"result",result:e})}const s=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,s)),n?.signal?.throwIfAborted()}}catch(e){yield{type:"error",error:e instanceof ya?e:new ya(Ys.InternalError,String(e))}}}request(e,t,n){const{relatedRequestId:s,resumptionToken:r,onresumptiontoken:o,task:a,relatedTask:i}=n??{};return new Promise((c,l)=>{const u=e=>{l(e)};if(!this._transport)return void u(new Error("Not connected"));if(!0===this._options?.enforceStrictCapabilities)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(e){return void u(e)}n?.signal?.throwIfAborted();const d=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),a&&(h.params={...h.params,task:a}),i&&(h.params={...h.params,_meta:{...h.params?._meta||{},[As]:i}});const p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(e)}},{relatedRequestId:s,resumptionToken:r,onresumptiontoken:o}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)));const t=e instanceof ya?e:new ya(Ys.RequestTimeout,String(e));l(t)};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{const n=L(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});const f=n?.timeout??6e4;this._setupTimeout(d,f,n?.maxTotalTimeout,()=>p(ya.fromError(Ys.RequestTimeout,"Request timed out",{timeout:f})),n?.resetTimeoutOnProgress??!1);const m=i?.taskId;if(m){const e=e=>{const t=this._responseHandlers.get(d);t?t(e):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,e),this._enqueueTaskMessage(m,{type:"request",message:h,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})}else this._transport.send(h,{relatedRequestId:s,resumptionToken:r,onresumptiontoken:o}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Rr,t)}async getTaskResult(e,t,n){return this.request({method:"tasks/result",params:e},t,n)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},Or,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},Mr,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const n=t?.relatedTask?.taskId;if(n){const s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[As]:t.relatedTask}}};return void await this._enqueueTaskMessage(n,{type:"notification",message:s,timestamp:Date.now()})}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:"2.0"};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[As]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))})}let s={...e,jsonrpc:"2.0"};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[As]:t.relatedTask}}}),await this._transport.send(s,t)}setRequestHandler(e,t){const n=ba(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,s)=>{const r=$a(e,n);return Promise.resolve(t(r,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){const n=ba(e);this._notificationHandlers.set(n,n=>{const s=$a(e,n);return Promise.resolve(t(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,s)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(e,t);for(const t of n)if("request"===t.type&&Gs(t.message)){const n=t.message.id,s=this._requestResolvers.get(n);s?(s(new ya(Ys.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(n)):this._onerror(new Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{const t=await(this._taskStore?.getTask(e));t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,s)=>{if(t.aborted)return void s(new ya(Ys.InvalidRequest,"Request cancelled"));const r=setTimeout(e,n);t.addEventListener("abort",()=>{clearTimeout(r),s(new ya(Ys.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{const s=await n.getTask(e,t);if(!s)throw new ya(Ys.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(e,s,r)=>{await n.storeTaskResult(e,s,r,t);const o=await n.getTask(e,t);if(o){const t=Cr.parse({method:"notifications/tasks/status",params:o});await this.notification(t),va(o.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,s,r)=>{const o=await n.getTask(e,t);if(!o)throw new ya(Ys.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(va(o.status))throw new ya(Ys.InvalidParams,`Cannot update task "${e}" from terminal status "${o.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,s,r,t);const a=await n.getTask(e,t);if(a){const t=Cr.parse({method:"notifications/tasks/status",params:a});await this.notification(t),va(a.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}}function Sa(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}var xa=n(3282),Ea=n(8182);class Ta{constructor(e){this._ajv=e??function(){const e=new xa({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Ea(e),e}()}getValidator(e){const t="$id"in e&&"string"==typeof e.$id?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}class Ia{constructor(e){this._client=e}async*callToolStream(e,t=To,n){const s=this._client,r={...n,task:n?.task??(s.isToolTask(e.name)?{}:void 0)},o=s.requestStream({method:"tools/call",params:e},t,r),a=s.getToolOutputValidator(e.name);for await(const t of o){if("result"===t.type&&a){const n=t.result;if(!n.structuredContent&&!n.isError)return void(yield{type:"error",error:new ya(Ys.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)});if(n.structuredContent)try{const e=a(n.structuredContent);if(!e.valid)return void(yield{type:"error",error:new ya(Ys.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)})}catch(e){return e instanceof ya?void(yield{type:"error",error:e}):void(yield{type:"error",error:new ya(Ys.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)})}}yield t}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._client.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,n){return this._client.requestStream(e,t,n)}}function Ca(e,t){if(e&&null!==t&&"object"==typeof t){if("object"===e.type&&e.properties&&"object"==typeof e.properties){const n=t,s=e.properties;for(const e of Object.keys(s)){const t=s[e];void 0===n[e]&&Object.prototype.hasOwnProperty.call(t,"default")&&(n[e]=t.default),void 0!==n[e]&&Ca(t,n[e])}}if(Array.isArray(e.anyOf))for(const n of e.anyOf)"boolean"!=typeof n&&Ca(n,t);if(Array.isArray(e.oneOf))for(const n of e.oneOf)"boolean"!=typeof n&&Ca(n,t)}}class Pa extends ka{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new Ta,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Po,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",bo,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Qr,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Ia(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=function(e,t){const n={...e};for(const e in t){const s=e,r=t[s];if(void 0===r)continue;const o=n[s];Sa(o)&&Sa(r)?n[s]={...o,...r}:n[s]=r}return n}(this._capabilities,e)}setRequestHandler(e,t){const n=U(e),s=n?.method;if(!s)throw new Error("Schema is missing a method literal");let r;if(D(s)){const e=s,t=e._zod?.def;r=t?.value??e.value}else{const e=s,t=e._def;r=t?.value??e.value}if("string"!=typeof r)throw new Error("Schema method literal must be a string");const o=r;if("elicitation/create"===o){const n=async(e,n)=>{const s=L(oa,e);if(!s.success){const e=s.error instanceof Error?s.error.message:String(s.error);throw new ya(Ys.InvalidParams,`Invalid elicitation request: ${e}`)}const{params:r}=s.data;r.mode=r.mode??"form";const{supportsFormMode:o,supportsUrlMode:a}=function(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=void 0!==e.form,n=void 0!==e.url;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}(this._capabilities.elicitation);if("form"===r.mode&&!o)throw new ya(Ys.InvalidParams,"Client does not support form-mode elicitation requests");if("url"===r.mode&&!a)throw new ya(Ys.InvalidParams,"Client does not support URL-mode elicitation requests");const i=await Promise.resolve(t(e,n));if(r.task){const e=L(Tr,i);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new ya(Ys.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const c=L(ca,i);if(!c.success){const e=c.error instanceof Error?c.error.message:String(c.error);throw new ya(Ys.InvalidParams,`Invalid elicitation result: ${e}`)}const l=c.data,u="form"===r.mode?r.requestedSchema:void 0;if("form"===r.mode&&"accept"===l.action&&l.content&&u&&this._capabilities.elicitation?.form?.applyDefaults)try{Ca(u,l.content)}catch{}return l};return super.setRequestHandler(e,n)}if("sampling/createMessage"===o){const n=async(e,n)=>{const s=L(Wo,e);if(!s.success){const e=s.error instanceof Error?s.error.message:String(s.error);throw new ya(Ys.InvalidParams,`Invalid sampling request: ${e}`)}const{params:r}=s.data,o=await Promise.resolve(t(e,n));if(r.task){const e=L(Tr,o);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new ya(Ys.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const a=L(r.tools||r.toolChoice?Zo:Bo,o);if(!a.success){const e=a.error instanceof Error?a.error.message:String(a.error);throw new ya(Ys.InvalidParams,`Invalid sampling result: ${e}`)}return a.data};return super.setRequestHandler(e,n)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),void 0===e.sessionId)try{const n=await this.request({method:"initialize",params:{protocolVersion:Ps,capabilities:this._capabilities,clientInfo:this._clientInfo}},gr,t);if(void 0===n)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Rs.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if("notifications/roots/list_changed"===e&&!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){!function(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${t})`)}(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&function(e,t,n){if(!e)throw new Error(`${n} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},tr,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},pa,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},tr,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},vo,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},lo,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},Br,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},Gr,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},Yr,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},tr,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},tr,t)}async callTool(e,t=To,n){if(this.isToolTaskRequired(e.name))throw new ya(Ys.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const s=await this.request({method:"tools/call",params:e},t,n),r=this.getToolOutputValidator(e.name);if(r){if(!s.structuredContent&&!s.isError)throw new ya(Ys.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent)try{const e=r(s.structuredContent);if(!e.valid)throw new ya(Ys.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){if(e instanceof ya)throw e;throw new ya(Ys.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return s}isToolTask(e){return!!this._serverCapabilities?.tasks?.requests?.tools?.call&&this._cachedKnownTaskTools.has(e)}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}const e=t.execution?.taskSupport;"required"!==e&&"optional"!==e||this._cachedKnownTaskTools.add(t.name),"required"===e&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const n=await this.request({method:"tools/list",params:e},Eo,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,s){const r=Ro.safeParse(n);if(!r.success)throw new Error(`Invalid ${e} listChanged options: ${r.error.message}`);if("function"!=typeof n.onChanged)throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:o,debounceMs:a}=r.data,{onChanged:i}=n,c=async()=>{if(o)try{const e=await s();i(null,e)}catch(e){const t=e instanceof Error?e:new Error(String(e));i(t,null)}else i(null,null)};this.setNotificationHandler(t,()=>{if(a){const t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);const n=setTimeout(c,a);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}function Ra(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}let Aa;async function Na(e){return(await Aa).getRandomValues(new Uint8Array(e))}async function Oa(e){const t=await(await Aa).subtle.digest("SHA-256",(new TextEncoder).encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}Aa=globalThis.crypto;const ja=Bt(kn,void 0).superRefine((t,n)=>{if(!URL.canParse(t))return n.addIssue({code:"custom",message:"URL must be parseable",fatal:!0}),e}).refine(e=>{const t=new URL(e);return"javascript:"!==t.protocol&&"data:"!==t.protocol&&"vbscript:"!==t.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"});const Ma=ns({resource:yn().url(),authorization_servers:Qn(ja).optional(),jwks_uri:yn().url().optional(),scopes_supported:Qn(yn()).optional(),bearer_methods_supported:Qn(yn()).optional(),resource_signing_alg_values_supported:Qn(yn()).optional(),resource_name:yn().optional(),resource_documentation:yn().optional(),resource_policy_uri:yn().url().optional(),resource_tos_uri:yn().url().optional(),tls_client_certificate_bound_access_tokens:Vn().optional(),authorization_details_types_supported:Qn(yn()).optional(),dpop_signing_alg_values_supported:Qn(yn()).optional(),dpop_bound_access_tokens_required:Vn().optional()}),za=ns({issuer:yn(),authorization_endpoint:ja,token_endpoint:ja,registration_endpoint:ja.optional(),scopes_supported:Qn(yn()).optional(),response_types_supported:Qn(yn()),response_modes_supported:Qn(yn()).optional(),grant_types_supported:Qn(yn()).optional(),token_endpoint_auth_methods_supported:Qn(yn()).optional(),token_endpoint_auth_signing_alg_values_supported:Qn(yn()).optional(),service_documentation:ja.optional(),revocation_endpoint:ja.optional(),revocation_endpoint_auth_methods_supported:Qn(yn()).optional(),revocation_endpoint_auth_signing_alg_values_supported:Qn(yn()).optional(),introspection_endpoint:yn().optional(),introspection_endpoint_auth_methods_supported:Qn(yn()).optional(),introspection_endpoint_auth_signing_alg_values_supported:Qn(yn()).optional(),code_challenge_methods_supported:Qn(yn()).optional(),client_id_metadata_document_supported:Vn().optional()}),Da=ts({...ns({issuer:yn(),authorization_endpoint:ja,token_endpoint:ja,userinfo_endpoint:ja.optional(),jwks_uri:ja,registration_endpoint:ja.optional(),scopes_supported:Qn(yn()).optional(),response_types_supported:Qn(yn()),response_modes_supported:Qn(yn()).optional(),grant_types_supported:Qn(yn()).optional(),acr_values_supported:Qn(yn()).optional(),subject_types_supported:Qn(yn()),id_token_signing_alg_values_supported:Qn(yn()),id_token_encryption_alg_values_supported:Qn(yn()).optional(),id_token_encryption_enc_values_supported:Qn(yn()).optional(),userinfo_signing_alg_values_supported:Qn(yn()).optional(),userinfo_encryption_alg_values_supported:Qn(yn()).optional(),userinfo_encryption_enc_values_supported:Qn(yn()).optional(),request_object_signing_alg_values_supported:Qn(yn()).optional(),request_object_encryption_alg_values_supported:Qn(yn()).optional(),request_object_encryption_enc_values_supported:Qn(yn()).optional(),token_endpoint_auth_methods_supported:Qn(yn()).optional(),token_endpoint_auth_signing_alg_values_supported:Qn(yn()).optional(),display_values_supported:Qn(yn()).optional(),claim_types_supported:Qn(yn()).optional(),claims_supported:Qn(yn()).optional(),service_documentation:yn().optional(),claims_locales_supported:Qn(yn()).optional(),ui_locales_supported:Qn(yn()).optional(),claims_parameter_supported:Vn().optional(),request_parameter_supported:Vn().optional(),request_uri_parameter_supported:Vn().optional(),require_request_uri_registration:Vn().optional(),op_policy_uri:ja.optional(),op_tos_uri:ja.optional(),client_id_metadata_document_supported:Vn().optional()}).shape,...za.pick({code_challenge_methods_supported:!0}).shape}),La=ts({access_token:yn(),id_token:yn().optional(),token_type:yn(),expires_in:function(e){return new e({type:"number",coerce:!0,checks:[],...b(void 0)})}(Ln,void 0).optional(),scope:yn().optional(),refresh_token:yn().optional()}).strip(),Ua=ts({error:yn(),error_description:yn().optional(),error_uri:yn().optional()}),qa=ja.optional().or(fs("").transform(()=>{})),Fa=ts({redirect_uris:Qn(ja),token_endpoint_auth_method:yn().optional(),grant_types:Qn(yn()).optional(),response_types:Qn(yn()).optional(),client_name:yn().optional(),client_uri:ja.optional(),logo_uri:qa,scope:yn().optional(),contacts:Qn(yn()).optional(),tos_uri:qa,policy_uri:yn().optional(),jwks_uri:ja.optional(),jwks:(Wa=Zn,new Wa({type:"any"})).optional(),software_id:yn().optional(),software_version:yn().optional(),software_statement:yn().optional()}).strip(),Ha=ts({client_id:yn(),client_secret:yn().optional(),client_id_issued_at:Un().optional(),client_secret_expires_at:Un().optional()}).strip(),Va=Fa.merge(Ha);var Wa;ts({error:yn(),error_description:yn().optional()}).strip(),ts({token:yn(),token_type_hint:yn().optional()}).strip();class Ba extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class Za extends Ba{}Za.errorCode="invalid_request";class Ga extends Ba{}Ga.errorCode="invalid_client";class Ka extends Ba{}Ka.errorCode="invalid_grant";class Ja extends Ba{}Ja.errorCode="unauthorized_client";class Xa extends Ba{}Xa.errorCode="unsupported_grant_type";class Ya extends Ba{}Ya.errorCode="invalid_scope";class Qa extends Ba{}Qa.errorCode="access_denied";class ei extends Ba{}ei.errorCode="server_error";class ti extends Ba{}ti.errorCode="temporarily_unavailable";class ni extends Ba{}ni.errorCode="unsupported_response_type";class si extends Ba{}si.errorCode="unsupported_token_type";class ri extends Ba{}ri.errorCode="invalid_token";class oi extends Ba{}oi.errorCode="method_not_allowed";class ai extends Ba{}ai.errorCode="too_many_requests";class ii extends Ba{}ii.errorCode="invalid_client_metadata";class ci extends Ba{}ci.errorCode="insufficient_scope";class li extends Ba{}li.errorCode="invalid_target";const ui={[Za.errorCode]:Za,[Ga.errorCode]:Ga,[Ka.errorCode]:Ka,[Ja.errorCode]:Ja,[Xa.errorCode]:Xa,[Ya.errorCode]:Ya,[Qa.errorCode]:Qa,[ei.errorCode]:ei,[ti.errorCode]:ti,[ni.errorCode]:ni,[si.errorCode]:si,[ri.errorCode]:ri,[oi.errorCode]:oi,[ai.errorCode]:ai,[ii.errorCode]:ii,[ci.errorCode]:ci,[li.errorCode]:li};class di extends Error{constructor(e){super(e??"Unauthorized")}}const hi="code",pi="S256";async function fi(e){const t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const e=Ua.parse(JSON.parse(n)),{error:t,error_description:s,error_uri:r}=e;return new(ui[t]||ei)(s||"",r)}catch(e){return new ei(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${n}`)}}async function mi(e,t){try{return await gi(e,t)}catch(n){if(n instanceof Ga||n instanceof Ja)return await(e.invalidateCredentials?.("all")),await gi(e,t);if(n instanceof Ka)return await(e.invalidateCredentials?.("tokens")),await gi(e,t);throw n}}async function gi(e,{serverUrl:t,authorizationCode:n,scope:s,resourceMetadataUrl:r,fetchFn:o}){let a,i;try{a=await async function(e,t,n=fetch){const s=await async function(e,t,n,s){const r=new URL(e),o=s?.protocolVersion??Ps;let a;if(s?.metadataUrl)a=new URL(s.metadataUrl);else{const e=function(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,r.pathname);a=new URL(e,s?.metadataServerUrl??r),a.search=r.search}let i=await vi(a,o,n);if(!s?.metadataUrl&&function(e,t){return!e||e.status>=400&&e.status<500&&"/"!==t}(i,r.pathname)){const e=new URL(`/.well-known/${t}`,r);i=await vi(e,o,n)}return i}(e,"oauth-protected-resource",n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!s||404===s.status)throw await(s?.body?.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!s.ok)throw await(s.body?.cancel()),new Error(`HTTP ${s.status} trying to load well-known OAuth protected resource metadata.`);return Ma.parse(await s.json())}(t,{resourceMetadataUrl:r},o),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",t));const c=await async function(e,t,n){const s=function(e){const t="string"==typeof e?new URL(e):new URL(e.href);return t.hash="",t}(e);if(t.validateResourceURL)return await t.validateResourceURL(s,n?.resource);if(n){if(!function({requestedResource:e,configuredResource:t}){const n="string"==typeof e?new URL(e):new URL(e.href),s="string"==typeof t?new URL(t):new URL(t.href);if(n.origin!==s.origin)return!1;if(n.pathname.length<s.pathname.length)return!1;const r=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",o=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return r.startsWith(o)}({requestedResource:s,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${s} (or origin)`);return new URL(n.resource)}}(t,e,a),l=await async function(e,{fetchFn:t=fetch,protocolVersion:n=Ps}={}){const s={"MCP-Protocol-Version":n,Accept:"application/json"},r=function(e){const t="string"==typeof e?new URL(e):e,n=[];if(!("/"!==t.pathname))return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let s=t.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${s}`,t.origin),type:"oidc"}),n.push({url:new URL(`${s}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}(e);for(const{url:e,type:n}of r){const r=await wi(e,s,t);if(r){if(!r.ok){if(await(r.body?.cancel()),r.status>=400&&r.status<500)continue;throw new Error(`HTTP ${r.status} trying to load ${"oauth"===n?"OAuth":"OpenID provider"} metadata from ${e}`)}return"oauth"===n?za.parse(await r.json()):Da.parse(await r.json())}}}(i,{fetchFn:o});let u=await Promise.resolve(e.clientInformation());if(!u){if(void 0!==n)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const t=!0===l?.client_id_metadata_document_supported,s=e.clientMetadataUrl;if(s&&!function(e){if(!e)return!1;try{const t=new URL(e);return"https:"===t.protocol&&"/"!==t.pathname}catch{return!1}}(s))throw new ii(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${s}`);if(t&&s)u={client_id:s},await(e.saveClientInformation?.(u));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const t=await async function(e,{metadata:t,clientMetadata:n,fetchFn:s}){let r;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");r=new URL(t.registration_endpoint)}else r=new URL("/register",e);const o=await(s??fetch)(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw await fi(o);return Va.parse(await o.json())}(i,{metadata:l,clientMetadata:e.clientMetadata,fetchFn:o});await e.saveClientInformation(t),u=t}}const d=!e.redirectUrl;if(void 0!==n||d){const t=await async function(e,t,{metadata:n,resource:s,authorizationCode:r,fetchFn:o}={}){const a=e.clientMetadata.scope;let i;if(e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a)),!i){if(!r)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");i=function(e,t,n){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(n)})}(r,await e.codeVerifier(),e.redirectUrl)}return bi(t,{metadata:n,tokenRequestParams:i,clientInformation:await e.clientInformation()??void 0,addClientAuthentication:e.addClientAuthentication,resource:s,fetchFn:o})}(e,i,{metadata:l,resource:c,authorizationCode:n,fetchFn:o});return await e.saveTokens(t),"AUTHORIZED"}const h=await e.tokens();if(h?.refresh_token)try{const t=await async function(e,{metadata:t,clientInformation:n,refreshToken:s,resource:r,addClientAuthentication:o,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:s});return{refresh_token:s,...await bi(e,{metadata:t,tokenRequestParams:i,clientInformation:n,addClientAuthentication:o,resource:r,fetchFn:a})}}(i,{metadata:l,clientInformation:u,refreshToken:h.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(e instanceof Ba&&!(e instanceof ei))throw e}const p=e.state?await e.state():void 0,{authorizationUrl:f,codeVerifier:m}=await async function(e,{metadata:t,clientInformation:n,redirectUrl:s,scope:r,state:o,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(hi))throw new Error(`Incompatible auth server: does not support response type ${hi}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(pi))throw new Error(`Incompatible auth server: does not support code challenge method ${pi}`)}else i=new URL("/authorize",e);const c=await async function(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await async function(e){return await async function(e){const t=Math.pow(2,8)-Math.pow(2,8)%66;let n="";for(;n.length<e;){const s=await Na(e-n.length);for(const e of s)e<t&&(n+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[e%66])}return n}(e)}(e);return{code_verifier:t,code_challenge:await Oa(t)}}(),l=c.code_verifier,u=c.code_challenge;return i.searchParams.set("response_type",hi),i.searchParams.set("client_id",n.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",pi),i.searchParams.set("redirect_uri",String(s)),o&&i.searchParams.set("state",o),r&&i.searchParams.set("scope",r),r?.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:l}}(i,{metadata:l,clientInformation:u,state:p,redirectUrl:e.redirectUrl,scope:s||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(m),await e.redirectToAuthorization(f),"REDIRECT"}function _i(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[n,s]=t.split(" ");if("bearer"!==n.toLowerCase()||!s)return{};const r=yi(e,"resource_metadata")||void 0;let o;if(r)try{o=new URL(r)}catch{}return{resourceMetadataUrl:o,scope:yi(e,"scope")||void 0,error:yi(e,"error")||void 0}}function yi(e,t){const n=e.headers.get("WWW-Authenticate");if(!n)return null;const s=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),r=n.match(s);return r?r[1]||r[2]:null}async function wi(e,t,n=fetch){try{return await n(e,{headers:t})}catch(s){if(s instanceof TypeError)return t?wi(e,void 0,n):void 0;throw s}}async function vi(e,t,n=fetch){const s={"MCP-Protocol-Version":t};return await wi(e,s,n)}async function bi(e,{metadata:t,tokenRequestParams:n,clientInformation:s,addClientAuthentication:r,resource:o,fetchFn:a}){const i=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(o&&n.set("resource",o.href),r)await r(c,n,i,t);else if(s){const e=function(e,t){const n=void 0!==e.client_secret;return 0===t.length?n?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&(s=e.token_endpoint_auth_method,["client_secret_basic","client_secret_post","none"].includes(s))&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:n&&t.includes("client_secret_basic")?"client_secret_basic":n&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":n?"client_secret_post":"none";var s}(s,t?.token_endpoint_auth_methods_supported??[]);!function(e,t,n,s){const{client_id:r,client_secret:o}=t;switch(e){case"client_secret_basic":return void function(e,t,n){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const s=btoa(`${e}:${t}`);n.set("Authorization",`Basic ${s}`)}(r,o,n);case"client_secret_post":return void function(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}(r,o,s);case"none":return void function(e,t){t.set("client_id",e)}(r,s);default:throw new Error(`Unsupported client authentication method: ${e}`)}}(e,s,c,n)}const l=await(a??fetch)(i,{method:"POST",headers:c,body:n});if(!l.ok)throw await fi(l);return La.parse(await l.json())}class $i extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function ki(e){}class Si extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let s;super({start(r){s=function(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=ki,onError:n=ki,onRetry:s=ki,onComment:r}=e;let o,a="",i=!0,c="",l="";function u(e){if(""===e)return c.length>0&&t({id:o,event:l||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),o=void 0,c="",void(l="");if(e.startsWith(":"))return void(r&&r(e.slice(e.startsWith(": ")?2:1)));const n=e.indexOf(":");if(-1!==n){const t=e.slice(0,n),s=" "===e[n+1]?2:1;return void d(t,e.slice(n+s),e)}d(e,"",e)}function d(e,t,r){switch(e){case"event":l=t;break;case"data":c=`${c}${t}\n`;break;case"id":o=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?s(parseInt(t,10)):n(new $i(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:r}));break;default:n(new $i(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:r}))}}return{feed:function(e){const t=i?e.replace(/^\xEF\xBB\xBF/,""):e,[n,s]=function(e){const t=[];let n="",s=0;for(;s<e.length;){const r=e.indexOf("\r",s),o=e.indexOf("\n",s);let a=-1;if(-1!==r&&-1!==o?a=Math.min(r,o):-1!==r?a=r===e.length-1?-1:r:-1!==o&&(a=o),-1===a){n=e.slice(s);break}{const n=e.slice(s,a);t.push(n),s=a+1,"\r"===e[s-1]&&"\n"===e[s]&&s++}}return[t,n]}(`${a}${t}`);for(const e of n)u(e);a=s,i=!1},reset:function(e={}){a&&e.consume&&u(a),i=!0,o=void 0,c="",l="",a=""}}}({onEvent:e=>{r.enqueue(e)},onError(t){"terminate"===e?r.error(t):"function"==typeof e&&e(t)},onRetry:t,onComment:n})},transform(e){s.feed(e)}})}}const xi={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Ei extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class Ti{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=function(e=fetch,t){return t?async(n,s)=>{const r={...t,...s,headers:s?.headers?{...Ra(t.headers),...Ra(s.headers)}:t.headers};return e(n,r)}:e}(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??xi}async _authThenStart(){if(!this._authProvider)throw new di("No auth provider");let e;try{e=await mi(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new di;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=Ra(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){const{resumptionToken:t}=e;try{const n=await this._commonHeaders();n.set("Accept","text/event-stream"),t&&n.set("last-event-id",t);const s=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!s.ok){if(await(s.body?.cancel()),401===s.status&&this._authProvider)return await this._authThenStart();if(405===s.status)return;throw new Ei(s.status,`Failed to open SSE stream: ${s.statusText}`)}this._handleSseStream(s.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(void 0!==this._serverRetryMs)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,s=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(n,e),s)}_scheduleReconnection(e,t=0){const n=this._reconnectionOptions.maxRetries;if(t>=n)return void this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));const s=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},s)}_handleSseStream(e,t,n){if(!e)return;const{onresumptiontoken:s,replayMessageId:r}=t;let o,a=!1,i=!1;(async()=>{try{const t=e.pipeThrough(new TextDecoderStream).pipeThrough(new Si({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){const{value:e,done:n}=await t.read();if(n)break;if(e.id&&(o=e.id,a=!0,s?.(e.id)),e.data&&(!e.event||"message"===e.event))try{const t=er.parse(JSON.parse(e.data));Xs(t)&&(i=!0,void 0!==r&&(t.id=r)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||a)&&!i&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:o,onresumptiontoken:s,replayMessageId:r},0)}catch(e){if(this.onerror?.(new Error(`SSE stream disconnected: ${e}`)),(n||a)&&!i&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:s,replayMessageId:r},0)}catch(e){this.onerror?.(new Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new di("No auth provider");if("AUTHORIZED"!==await mi(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new di("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{const{resumptionToken:s,onresumptiontoken:r}=t||{};if(s)return void this._startOrAuthSse({resumptionToken:s,replayMessageId:Gs(e)?e.id:void 0}).catch(e=>this.onerror?.(e));const o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),c=i.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!i.ok){const t=await i.text().catch(()=>null);if(401===i.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ei(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:t,scope:n}=_i(i);if(this._resourceMetadataUrl=t,this._scope=n,"AUTHORIZED"!==await mi(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new di;return this._hasCompletedAuthFlow=!0,this.send(e)}if(403===i.status&&this._authProvider){const{resourceMetadataUrl:t,scope:n,error:s}=_i(i);if("insufficient_scope"===s){const s=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===s)throw new Ei(403,"Server returned 403 after trying upscoping");if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=s??void 0,"AUTHORIZED"!==await mi(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch}))throw new di;return this.send(e)}}throw new Ei(i.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,202===i.status)return await(i.body?.cancel()),n=e,void(_r.safeParse(n).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e)));const l=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,u=i.headers.get("content-type");if(l)if(u?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:r},!1);else{if(!u?.includes("application/json"))throw await(i.body?.cancel()),new Ei(-1,`Unexpected content type: ${u}`);{const e=await i.json(),t=Array.isArray(e)?e.map(e=>er.parse(e)):[er.parse(e)];for(const e of t)this.onmessage?.(e)}}else await(i.body?.cancel())}catch(e){throw this.onerror?.(e),e}var n}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await(n.body?.cancel()),!n.ok&&405!==n.status)throw new Ei(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}class Ii extends Error{constructor(e,t=null,n=null){super(e),this.name="MCPError",this.code=t,this.details=n}}class Ci{constructor(e={}){this.configKey=e.configKey||"nfdAIChat",this.client=null,this.transport=null,this.connected=!1,this.tools=[],this.resources=[],this.eventListeners=new Map}getConfig(){const e="undefined"!=typeof window&&window[this.configKey]||{};return{nonce:e.nonce||"",restUrl:e.restUrl||"/wp-json/",mcpUrl:e.mcpUrl||`${e.restUrl||"/wp-json/"}mcp/mcp-adapter-default-server`,homeUrl:e.homeUrl||""}}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}off(e,t){const n=this.eventListeners.get(e);n&&n.delete(t)}emit(e){const t=this.eventListeners.get(e.type);t&&t.forEach(t=>{try{t(e)}catch(e){console.error("Error in MCP event listener:",e)}})}async connect(e=null){try{const t=this.getConfig(),n=e||t.mcpUrl;if(!n)throw new Ii("MCP endpoint URL not configured");this.client=new Pa({name:"nfd-ai-chat-client",version:"1.0.0"},{capabilities:{}}),this.transport=new Ti(new URL(n),{requestInit:{headers:{"X-WP-Nonce":t.nonce,"Content-Type":"application/json"}}}),await this.client.connect(this.transport),this.connected=!0,this.emit({type:"connected"})}catch(e){const t=e instanceof Ii?e:new Ii(`Connection failed: ${e.message}`);throw this.emit({type:"error",data:t}),t}}async initialize(){if(!this.connected)throw new Ii("Not connected to MCP server");try{await Promise.all([this.loadTools(),this.loadResources()]);const e={protocolVersion:"2025-06-18",capabilities:{tools:{},resources:{},prompts:{}},serverInfo:{name:"WordPress MCP Server",version:"1.0.0"}};return this.emit({type:"initialized",data:e}),e}catch(e){const t=e instanceof Ii?e:new Ii(`Initialization failed: ${e.message}`);throw this.emit({type:"error",data:t}),t}}normalizeInputSchema(e){return!e||Array.isArray(e)||"object"!=typeof e||0===Object.keys(e).length?{type:"object",properties:{},required:[]}:{type:e.type||"object",properties:e.properties||{},required:Array.isArray(e.required)?e.required:[]}}async loadTools(){try{const e=await this.client.listTools();this.tools=e.tools.map(e=>({name:e.name,description:e.description||"",inputSchema:this.normalizeInputSchema(e.inputSchema),annotations:e.annotations||{}})),this.emit({type:"tools_updated",data:this.tools})}catch(e){console.error("Failed to load tools via SDK:",e),this.tools=[]}}async loadResources(){try{const e=await this.client.listResources();this.resources=e.resources.map(e=>({uri:e.uri,name:e.name||"",description:e.description,mimeType:e.mimeType})),this.emit({type:"resources_updated",data:this.resources})}catch(e){console.error("Failed to load resources via SDK:",e),this.resources=[]}}async listTools(){if(!this.connected)throw new Ii("Not connected to MCP server");return this.tools}async callTool(e,t={}){if(!this.connected)throw new Ii("Not connected to MCP server");try{const n=await this.client.callTool({name:e,arguments:t});return{content:Array.isArray(n.content)?n.content:[],isError:Boolean(n.isError),meta:n.meta||{}}}catch(t){console.error(`Tool "${e}" call failed:`,t);const n=t instanceof Ii?t:new Ii(`Tool call failed: ${t.message}`);throw this.emit({type:"error",data:n}),n}}async listResources(){if(!this.connected)throw new Ii("Not connected to MCP server");return this.resources}async readResource(e){if(!this.connected)throw new Ii("Not connected to MCP server");try{return await this.client.readResource({uri:e})}catch(t){console.error(`Resource "${e}" read failed:`,t);const n=t instanceof Ii?t:new Ii(`Resource read failed: ${t.message}`);throw this.emit({type:"error",data:n}),n}}async disconnect(){try{this.transport&&(await this.client.close(),this.transport=null),this.connected=!1,this.tools=[],this.resources=[],this.emit({type:"disconnected"})}catch(e){console.error("Error during SDK disconnect:",e)}}isConnected(){return this.connected}getTools(){return[...this.tools]}getResources(){return[...this.resources]}isToolReadOnly(e){const t=this.tools.find(t=>t.name===e);return!t||!0===t.annotations?.readonly||!0===t.annotations?.readOnlyHint}getToolsForOpenAI(){return this.tools.map(e=>{const t=this.normalizeInputSchema(e.inputSchema);return{type:"function",function:{name:e.name,description:e.description||"",parameters:t}}})}}const Pi=(e={})=>new Ci(e),Ri=new Ci,Ai="RFC3986",Ni={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},Oi=(Object.prototype.hasOwnProperty,Array.isArray),ji=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),Mi=1024;function zi(e,t){if(Oi(e)){const n=[];for(let s=0;s<e.length;s+=1)n.push(t(e[s]));return n}return t(e)}const Di=Object.prototype.hasOwnProperty,Li={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},Ui=Array.isArray,qi=Array.prototype.push,Fi=function(e,t){qi.apply(e,Ui(t)?t:[t])},Hi=Date.prototype.toISOString,Vi={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,n,s,r)=>{if(0===e.length)return e;let o=e;if("symbol"==typeof e?o=Symbol.prototype.toString.call(e):"string"!=typeof e&&(o=String(e)),"iso-8859-1"===n)return escape(o).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});let a="";for(let e=0;e<o.length;e+=Mi){const t=o.length>=Mi?o.slice(e,e+Mi):o,n=[];for(let e=0;e<t.length;++e){let s=t.charCodeAt(e);45===s||46===s||95===s||126===s||s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||"RFC1738"===r&&(40===s||41===s)?n[n.length]=t.charAt(e):s<128?n[n.length]=ji[s]:s<2048?n[n.length]=ji[192|s>>6]+ji[128|63&s]:s<55296||s>=57344?n[n.length]=ji[224|s>>12]+ji[128|s>>6&63]+ji[128|63&s]:(e+=1,s=65536+((1023&s)<<10|1023&t.charCodeAt(e)),n[n.length]=ji[240|s>>18]+ji[128|s>>12&63]+ji[128|s>>6&63]+ji[128|63&s])}a+=n.join("")}return a},encodeValuesOnly:!1,format:Ai,formatter:Ni[Ai],indices:!1,serializeDate:e=>Hi.call(e),skipNulls:!1,strictNullHandling:!1},Wi={};function Bi(e,t,n,s,r,o,a,i,c,l,u,d,h,p,f,m,g,_){let y=e,w=_,v=0,b=!1;for(;void 0!==(w=w.get(Wi))&&!b;){const t=w.get(e);if(v+=1,void 0!==t){if(t===v)throw new RangeError("Cyclic object value");b=!0}void 0===w.get(Wi)&&(v=0)}if("function"==typeof l?y=l(t,y):y instanceof Date?y=h?.(y):"comma"===n&&Ui(y)&&(y=zi(y,function(e){return e instanceof Date?h?.(e):e})),null===y){if(o)return c&&!m?c(t,Vi.encoder,g,"key",p):t;y=""}if("string"==typeof($=y)||"number"==typeof $||"boolean"==typeof $||"symbol"==typeof $||"bigint"==typeof $||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(y)){if(c){const e=m?t:c(t,Vi.encoder,g,"key",p);return[f?.(e)+"="+f?.(c(y,Vi.encoder,g,"value",p))]}return[f?.(t)+"="+f?.(String(y))]}var $;const k=[];if(void 0===y)return k;let S;if("comma"===n&&Ui(y))m&&c&&(y=zi(y,c)),S=[{value:y.length>0?y.join(",")||null:void 0}];else if(Ui(l))S=l;else{const e=Object.keys(y);S=u?e.sort(u):e}const x=i?String(t).replace(/\./g,"%2E"):String(t),E=s&&Ui(y)&&1===y.length?x+"[]":x;if(r&&Ui(y)&&0===y.length)return E+"[]";for(let t=0;t<S.length;++t){const w=S[t],b="object"==typeof w&&void 0!==w.value?w.value:y[w];if(a&&null===b)continue;const $=d&&i?w.replace(/\./g,"%2E"):w,x=Ui(y)?"function"==typeof n?n(E,$):E:E+(d?"."+$:"["+$+"]");_.set(e,v);const T=new WeakMap;T.set(Wi,_),Fi(k,Bi(b,x,n,s,r,o,a,i,"comma"===n&&m&&Ui(y)?null:c,l,u,d,h,p,f,m,g,T))}return k}const Zi="4.104.0";let Gi,Ki,Ji,Xi,Yi,Qi,ec,tc,nc,sc=!1,rc=null,oc=null,ac=null,ic=null;class cc{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}const lc=()=>{Gi||function(e,t={auto:!1}){if(sc)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(Gi)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${Gi}'\``);sc=t.auto,Gi=e.kind,Ki=e.fetch,rc=e.Request,oc=e.Response,ac=e.Headers,Ji=e.FormData,ic=e.Blob,Xi=e.File,Yi=e.ReadableStream,Qi=e.getMultipartRequestOptions,ec=e.getDefaultAgent,tc=e.fileFromPath,nc=e.isFsReadStream}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let n,s,r,o;try{n=fetch,s=Request,r=Response,o=Headers}catch(e){throw new Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${t}`)}return{kind:"web",fetch:n,Request:s,Response:r,Headers:o,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new cc(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0})};lc();class uc extends Error{}class dc extends uc{constructor(e,t,n,s){super(`${dc.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.request_id=s?.["x-request-id"],this.error=t;const r=t;this.code=r?.code,this.param=r?.param,this.type=r?.type}static makeMessage(e,t,n){const s=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new pc({message:n,cause:ll(t)});const r=t?.error;return 400===e?new mc(e,r,n,s):401===e?new gc(e,r,n,s):403===e?new _c(e,r,n,s):404===e?new yc(e,r,n,s):409===e?new wc(e,r,n,s):422===e?new vc(e,r,n,s):429===e?new bc(e,r,n,s):e>=500?new $c(e,r,n,s):new dc(e,r,n,s)}}class hc extends dc{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class pc extends dc{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class fc extends pc{constructor({message:e}={}){super({message:e??"Request timed out."})}}class mc extends dc{}class gc extends dc{}class _c extends dc{}class yc extends dc{}class wc extends dc{}class vc extends dc{}class bc extends dc{}class $c extends dc{}class kc extends uc{constructor(){super("Could not parse response content as the length limit was reached")}}class Sc extends uc{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var xc,Ec=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},Tc=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class Ic{constructor(){xc.set(this,void 0),this.buffer=new Uint8Array,Ec(this,xc,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?(new TextEncoder).encode(e):e;let n=new Uint8Array(this.buffer.length+t.length);n.set(this.buffer),n.set(t,this.buffer.length),this.buffer=n;const s=[];let r;for(;null!=(r=Cc(this.buffer,Tc(this,xc,"f")));){if(r.carriage&&null==Tc(this,xc,"f")){Ec(this,xc,r.index,"f");continue}if(null!=Tc(this,xc,"f")&&(r.index!==Tc(this,xc,"f")+1||r.carriage)){s.push(this.decodeText(this.buffer.slice(0,Tc(this,xc,"f")-1))),this.buffer=this.buffer.slice(Tc(this,xc,"f")),Ec(this,xc,null,"f");continue}const e=null!==Tc(this,xc,"f")?r.preceding-1:r.preceding,t=this.decodeText(this.buffer.slice(0,e));s.push(t),this.buffer=this.buffer.slice(r.index),Ec(this,xc,null,"f")}return s}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new uc(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new uc(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new uc("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode("\n"):[]}}function Cc(e,t){for(let n=t??0;n<e.length;n++){if(10===e[n])return{preceding:n,index:n+1,carriage:!1};if(13===e[n])return{preceding:n,index:n+1,carriage:!0}}return null}function Pc(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1])return t+2;if(13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return-1}function Rc(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}xc=new WeakMap,Ic.NEWLINE_CHARS=new Set(["\n","\r"]),Ic.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class Ac{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;return new Ac(async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const n of async function*(e,t){if(!e.body)throw t.abort(),new uc("Attempted to iterate over a response with no body");const n=new Nc,s=new Ic,r=Rc(e.body);for await(const e of async function*(e){let t=new Uint8Array;for await(const n of e){if(null==n)continue;const e=n instanceof ArrayBuffer?new Uint8Array(n):"string"==typeof n?(new TextEncoder).encode(n):n;let s,r=new Uint8Array(t.length+e.length);for(r.set(t),r.set(e,t.length),t=r;-1!==(s=Pc(t));)yield t.slice(0,s),t=t.slice(s)}t.length>0&&(yield t)}(r))for(const t of s.decode(e)){const e=n.decode(t);e&&(yield e)}for(const e of s.flush()){const t=n.decode(e);t&&(yield t)}}(e,t))if(!s)if(n.data.startsWith("[DONE]"))s=!0;else if(null===n.event||n.event.startsWith("response.")||n.event.startsWith("transcript.")){let t;try{t=JSON.parse(n.data)}catch(e){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),e}if(t&&t.error)throw new dc(void 0,t.error,void 0,Xc(e.headers));yield t}else{let e;try{e=JSON.parse(n.data)}catch(e){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),e}if("error"==n.event)throw new dc(void 0,e.error,e.message,void 0);yield{event:n.event,data:e}}s=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{s||t.abort()}},t)}static fromReadableStream(e,t){let n=!1;return new Ac(async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const t of async function*(){const t=new Ic,n=Rc(e);for await(const e of n)for(const n of t.decode(e))yield n;for(const e of t.flush())yield e}())s||t&&(yield JSON.parse(t));s=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{s||t.abort()}},t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=s=>({next:()=>{if(0===s.length){const s=n.next();e.push(s),t.push(s)}return s.shift()}});return[new Ac(()=>s(e),this.controller),new Ac(()=>s(t),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new Yi({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:s,done:r}=await t.next();if(r)return e.close();const o=n.encode(JSON.stringify(s)+"\n");e.enqueue(o)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class Nc{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=function(e){const t=e.indexOf(":");return-1!==t?[e.substring(0,t),":",e.substring(t+1)]:[e,"",""]}(e);return s.startsWith(" ")&&(s=s.substring(1)),"event"===t?this.event=s:"data"===t&&this.data.push(s),null}}const Oc=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,jc=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&Mc(e),Mc=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function zc(e,t,n){if(e=await e,jc(e))return e;if(Oc(e)){const s=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const r=Mc(s)?[await s.arrayBuffer()]:[s];return new Xi(r,t,n)}const s=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Mc(e))t.push(await e.arrayBuffer());else{if(!Lc(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){return`[${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(", ")}]`}(e)}`);for await(const n of e)t.push(n)}return t}(e);if(t||(t=function(e){return Dc(e.name)||Dc(e.filename)||Dc(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!n?.type){const e=s[0]?.type;"string"==typeof e&&(n={...n,type:e})}return new Xi(s,t,n)}const Dc=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,Lc=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],Uc=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],qc=async e=>{const t=await Fc(e.body);return Qi(t,e)},Fc=async e=>{const t=new Ji;return await Promise.all(Object.entries(e||{}).map(([e,n])=>Hc(t,e,n))),t},Hc=async(e,t,n)=>{if(void 0!==n){if(null==n)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)e.append(t,String(n));else if((e=>jc(e)||Oc(e)||nc(e))(n)){const s=await zc(n);e.append(t,s)}else if(Array.isArray(n))await Promise.all(n.map(n=>Hc(e,t+"[]",n)));else{if("object"!=typeof n)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`);await Promise.all(Object.entries(n).map(([n,s])=>Hc(e,`${t}[${n}]`,s)))}}};var Vc;async function Wc(e){const{response:t}=e;if(e.options.stream)return ml("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):Ac.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const n=t.headers.get("content-type"),s=n?.split(";")[0]?.trim();if(s?.includes("application/json")||s?.endsWith("+json")){const e=await t.json();return ml("response",t.status,t.url,t.headers,e),Bc(e,t)}const r=await t.text();return ml("response",t.status,t.url,t.headers,r),r}function Bc(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}lc();class Zc extends Promise{constructor(e,t=Wc){super(e=>{e(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new Zc(this.responsePromise,async t=>Bc(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class Gc{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:r}){this.baseURL=e,this.maxRetries=cl("maxRetries",t),this.timeout=cl("timeout",n),this.httpAgent=s,this.fetch=r??Ki}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...sl(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${gl()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(async n=>{const s=n&&Mc(n?.body)?new DataView(await n.body.arrayBuffer()):n?.body instanceof DataView?n.body:n?.body instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n?.body)?new DataView(n.body.buffer):n?.body;return{method:e,path:t,...n,body:s}}))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:s,path:r,query:o,headers:a={}}=n,i=ArrayBuffer.isView(n.body)||n.__binaryRequest&&"string"==typeof n.body?n.body:Uc(n.body)?n.body.body:n.body?JSON.stringify(n.body,null,2):null,c=this.calculateContentLength(i),l=this.buildURL(r,o);"timeout"in n&&cl("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const u=n.httpAgent??this.httpAgent??ec(l),d=n.timeout+1e3;return"number"==typeof u?.options?.timeout&&d>(u.options.timeout??0)&&(u.options.timeout=d),this.idempotencyHeader&&"get"!==s&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey),{req:{method:s,...i&&{body:i},headers:this.buildHeaders({options:n,headers:a,contentLength:c,retryCount:t}),...u&&{agent:u},signal:n.signal??null},url:l,timeout:n.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){const r={};n&&(r["content-length"]=n);const o=this.defaultHeaders(e);return pl(r,o),pl(r,t),Uc(e.body)&&"node"!==Gi&&delete r["content-type"],void 0===_l(o,"x-stainless-retry-count")&&void 0===_l(t,"x-stainless-retry-count")&&(r["x-stainless-retry-count"]=String(s)),void 0===_l(o,"x-stainless-timeout")&&void 0===_l(t,"x-stainless-timeout")&&e.timeout&&(r["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(r,t),r}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(e=>[...e])):{...e}:{}}makeStatusError(e,t,n,s){return dc.generate(e,t,n,s)}request(e,t=null){return new Zc(this.makeRequest(e,t))}async makeRequest(e,t){const n=await e,s=n.maxRetries??this.maxRetries;null==t&&(t=s),await this.prepareOptions(n);const{req:r,url:o,timeout:a}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(r,{url:o,options:n}),ml("request",o,n,r.headers),n.signal?.aborted)throw new hc;const i=new AbortController,c=await this.fetchWithTimeout(o,r,a,i).catch(ll);if(c instanceof Error){if(n.signal?.aborted)throw new hc;if(t)return this.retryRequest(n,t);if("AbortError"===c.name)throw new fc;throw new pc({cause:c})}const l=Xc(c.headers);if(!c.ok){if(t&&this.shouldRetry(c))return ml(`response (error; retrying, ${t} attempts remaining)`,c.status,o,l),this.retryRequest(n,t,l);const e=await c.text().catch(e=>ll(e).message),s=rl(e),r=s?void 0:e;throw ml(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,c.status,o,l,r),this.makeStatusError(c.status,s,r,l)}return{response:c,options:n,controller:i}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new Jc(this,n,e)}buildURL(e,t){const n=al(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return dl(s)||(t={...s,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new uc(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,n,s){const{signal:r,...o}=t||{};r&&r.addEventListener("abort",()=>s.abort());const a=setTimeout(()=>s.abort(),n),i={signal:s.signal,...o};return i.method&&(i.method=i.method.toUpperCase()),this.fetch.call(void 0,e,i).finally(()=>{clearTimeout(a)})}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||e.status>=500)}async retryRequest(e,t,n){let s;const r=n?.["retry-after-ms"];if(r){const e=parseFloat(r);Number.isNaN(e)||(s=e)}const o=n?.["retry-after"];if(o&&!s){const e=parseFloat(o);s=Number.isNaN(e)?Date.parse(o)-Date.now():1e3*e}if(!(s&&0<=s&&s<6e4)){const n=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,n)}return await il(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const n=t-e;return Math.min(.5*Math.pow(2,n),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${Zi}`}}class Kc{constructor(e,t,n,s){Vc.set(this,void 0),function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===s?r.call(e,n):r?r.value=n:t.set(e,n)}(this,Vc,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new uc("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){const n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,s]of n)e.url.searchParams.set(t,s);t.query=void 0,t.path=e.url.toString()}return await function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)}(this,Vc,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Vc=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Jc extends Zc{constructor(e,t,n){super(t,async t=>new n(e,t.response,await Wc(t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const Xc=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),Yc={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},Qc=e=>"object"==typeof e&&null!==e&&!dl(e)&&Object.keys(e).every(e=>hl(Yc,e)),el=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",tl=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let nl;const sl=()=>nl??(nl=(()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zi,"X-Stainless-OS":tl(Deno.build.os),"X-Stainless-Arch":el(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zi,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zi,"X-Stainless-OS":tl(process.platform),"X-Stainless-Arch":el(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:n}of e){const e=n.exec(navigator.userAgent);if(e)return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zi,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zi,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}})()),rl=e=>{try{return JSON.parse(e)}catch(e){return}},ol=/^[a-z][a-z0-9+.-]*:/i,al=e=>ol.test(e),il=e=>new Promise(t=>setTimeout(t,e)),cl=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new uc(`${e} must be an integer`);if(t<0)throw new uc(`${e} must be a positive integer`);return t},ll=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return new Error(JSON.stringify(e))}catch{}return new Error(e)},ul=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function dl(e){if(!e)return!0;for(const t in e)return!1;return!0}function hl(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function pl(e,t){for(const n in t){if(!hl(t,n))continue;const s=n.toLowerCase();if(!s)continue;const r=t[n];null===r?delete e[s]:void 0!==r&&(e[s]=r)}}const fl=new Set(["authorization","api-key"]);function ml(e,...t){if("undefined"!=typeof process&&"true"===process?.env?.DEBUG){const n=t.map(e=>{if(!e)return e;if(e.headers){const t={...e,headers:{...e.headers}};for(const n in e.headers)fl.has(n.toLowerCase())&&(t.headers[n]="REDACTED");return t}let t=null;for(const n in e)fl.has(n.toLowerCase())&&(t??(t={...e}),t[n]="REDACTED");return t??e});console.log(`OpenAI:DEBUG:${e}`,...n)}}const gl=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),_l=(e,t)=>{const n=t.toLowerCase();if((e=>"function"==typeof e?.get)(e)){const s=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,(e,t,n)=>t+n.toUpperCase());for(const r of[t,n,t.toUpperCase(),s]){const t=e.get(r);if(t)return t}}for(const[s,r]of Object.entries(e))if(s.toLowerCase()===n)return Array.isArray(r)?(r.length<=1||console.warn(`Received ${r.length} entries for the ${t} header, using the first entry.`),r[0]):r};function yl(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class wl{constructor(e){this._client=e}}class vl extends wl{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class bl extends wl{list(e,t={},n){return Qc(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,El,{query:t,...n})}}class $l extends Kc{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class kl extends Kc{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){const e=this.getPaginatedItems();if(!e.length)return null;const t=e[e.length-1]?.id;return t?{params:{after:t}}:null}}class Sl extends wl{constructor(){super(...arguments),this.messages=new bl(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return Qc(e)?this.list({},e):this._client.getAPIList("/chat/completions",xl,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}}class xl extends kl{}class El extends kl{}Sl.ChatCompletionsPage=xl,Sl.Messages=bl;class Tl extends wl{constructor(){super(...arguments),this.completions=new Sl(this._client)}}Tl.Completions=Sl,Tl.ChatCompletionsPage=xl;class Il extends wl{create(e,t){const n=!!e.encoding_format;let s=n?e.encoding_format:"base64";n&&ml("Request","User defined encoding_format:",e.encoding_format);const r=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?r:(ml("response","Decoding base64 embeddings to float32 array"),r._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{const t=e.embedding;e.embedding=(e=>{if("undefined"!=typeof Buffer){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{const t=atob(e),n=t.length,s=new Uint8Array(n);for(let e=0;e<n;e++)s[e]=t.charCodeAt(e);return Array.from(new Float32Array(s.buffer))}})(t)}),e)))}}class Cl extends wl{create(e,t){return this._client.post("/files",qc({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return Qc(e)?this.list({},e):this._client.getAPIList("/files",Pl,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,t)}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=18e5}={}){const s=new Set(["processed","error","deleted"]),r=Date.now();let o=await this.retrieve(e);for(;!o.status||!s.has(o.status);)if(await il(t),o=await this.retrieve(e),Date.now()-r>n)throw new fc({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return o}}class Pl extends kl{}Cl.FileObjectsPage=Pl;class Rl extends wl{createVariation(e,t){return this._client.post("/images/variations",qc({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",qc({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class Al extends wl{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}}class Nl extends wl{create(e,t){return this._client.post("/audio/transcriptions",qc({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class Ol extends wl{create(e,t){return this._client.post("/audio/translations",qc({body:e,...t,__metadata:{model:e.model}}))}}class jl extends wl{constructor(){super(...arguments),this.transcriptions=new Nl(this._client),this.translations=new Ol(this._client),this.speech=new Al(this._client)}}jl.Transcriptions=Nl,jl.Translations=Ol,jl.Speech=Al;class Ml extends wl{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class zl extends wl{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Dl,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class Dl extends $l{}zl.ModelsPage=Dl;class Ll extends wl{}class Ul extends wl{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}}class ql extends wl{constructor(){super(...arguments),this.graders=new Ul(this._client)}}ql.Graders=Ul;class Fl extends wl{create(e,t,n){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Hl,{body:t,method:"post",...n})}retrieve(e,t={},n){return Qc(t)?this.retrieve(e,{},t):this._client.get(`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}del(e,t,n){return this._client.delete(`/fine_tuning/checkpoints/${e}/permissions/${t}`,n)}}class Hl extends $l{}Fl.PermissionCreateResponsesPage=Hl;class Vl extends wl{constructor(){super(...arguments),this.permissions=new Fl(this._client)}}Vl.Permissions=Fl,Vl.PermissionCreateResponsesPage=Hl;class Wl extends wl{list(e,t={},n){return Qc(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,Bl,{query:t,...n})}}class Bl extends kl{}Wl.FineTuningJobCheckpointsPage=Bl;class Zl extends wl{constructor(){super(...arguments),this.checkpoints=new Wl(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return Qc(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Gl,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return Qc(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,Kl,{query:t,...n})}pause(e,t){return this._client.post(`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(`/fine_tuning/jobs/${e}/resume`,t)}}class Gl extends kl{}class Kl extends kl{}Zl.FineTuningJobsPage=Gl,Zl.FineTuningJobEventsPage=Kl,Zl.Checkpoints=Wl,Zl.FineTuningJobCheckpointsPage=Bl;class Jl extends wl{constructor(){super(...arguments),this.methods=new Ll(this._client),this.jobs=new Zl(this._client),this.checkpoints=new Vl(this._client),this.alpha=new ql(this._client)}}Jl.Methods=Ll,Jl.Jobs=Zl,Jl.FineTuningJobsPage=Gl,Jl.FineTuningJobEventsPage=Kl,Jl.Checkpoints=Vl,Jl.Alpha=ql;class Xl extends wl{}class Yl extends wl{constructor(){super(...arguments),this.graderModels=new Xl(this._client)}}Yl.GraderModels=Xl;class Ql extends wl{create(e,t,n){return this._client.post(`/vector_stores/${e}/files`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return Qc(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,eu,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t,n){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const r=await this.retrieve(e,t,{...n,headers:s}).withResponse(),o=r.data;switch(o.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=r.response.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await il(e);break;case"failed":case"completed":return o}}}async upload(e,t,n){const s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){const s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,tu,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class eu extends kl{}class tu extends $l{}Ql.VectorStoreFilesPage=eu,Ql.FileContentResponsesPage=tu;class nu extends wl{create(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n={},s){return Qc(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,eu,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:r,response:o}=await this.retrieve(e,t,{...n,headers:s}).withResponse();switch(r.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await il(e);break;case"failed":case"cancelled":case"completed":return r}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const r=s?.maxConcurrency??5,o=Math.min(r,t.length),a=this._client,i=t.values(),c=[...n],l=Array(o).fill(i).map(async function(e){for(let t of e){const e=await a.files.create({file:t,purpose:"assistants"},s);c.push(e.id)}});return await(async e=>{const t=await Promise.allSettled(e),n=t.filter(e=>"rejected"===e.status);if(n.length){for(const e of n)console.error(e.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const s=[];for(const e of t)"fulfilled"===e.status&&s.push(e.value);return s})(l),await this.createAndPoll(e,{file_ids:c})}}class su extends wl{constructor(){super(...arguments),this.files=new Ql(this._client),this.fileBatches=new nu(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/vector_stores/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e={},t){return Qc(e)?this.list({},e):this._client.getAPIList("/vector_stores",ru,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}search(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/search`,ou,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class ru extends kl{}class ou extends $l{}su.VectorStoresPage=ru,su.VectorStoreSearchResponsesPage=ou,su.Files=Ql,su.VectorStoreFilesPage=eu,su.FileContentResponsesPage=tu,su.FileBatches=nu;class au extends wl{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/assistants/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e={},t){return Qc(e)?this.list({},e):this._client.getAPIList("/assistants",iu,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class iu extends kl{}function cu(e){return"function"==typeof e.parse}au.AssistantsPage=iu;const lu=e=>"assistant"===e?.role,uu=e=>"function"===e?.role,du=e=>"tool"===e?.role;var hu,pu,fu,mu,gu,_u,yu,wu,vu,bu,$u,ku,Su,xu=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},Eu=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class Tu{constructor(){hu.add(this),this.controller=new AbortController,pu.set(this,void 0),fu.set(this,()=>{}),mu.set(this,()=>{}),gu.set(this,void 0),_u.set(this,()=>{}),yu.set(this,()=>{}),wu.set(this,{}),vu.set(this,!1),bu.set(this,!1),$u.set(this,!1),ku.set(this,!1),xu(this,pu,new Promise((e,t)=>{xu(this,fu,e,"f"),xu(this,mu,t,"f")}),"f"),xu(this,gu,new Promise((e,t)=>{xu(this,_u,e,"f"),xu(this,yu,t,"f")}),"f"),Eu(this,pu,"f").catch(()=>{}),Eu(this,gu,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},Eu(this,hu,"m",Su).bind(this))},0)}_connected(){this.ended||(Eu(this,fu,"f").call(this),this._emit("connect"))}get ended(){return Eu(this,vu,"f")}get errored(){return Eu(this,bu,"f")}get aborted(){return Eu(this,$u,"f")}abort(){this.controller.abort()}on(e,t){return(Eu(this,wu,"f")[e]||(Eu(this,wu,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=Eu(this,wu,"f")[e];if(!n)return this;const s=n.findIndex(e=>e.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(Eu(this,wu,"f")[e]||(Eu(this,wu,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{xu(this,ku,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)})}async done(){xu(this,ku,!0,"f"),await Eu(this,gu,"f")}_emit(e,...t){if(Eu(this,vu,"f"))return;"end"===e&&(xu(this,vu,!0,"f"),Eu(this,_u,"f").call(this));const n=Eu(this,wu,"f")[e];if(n&&(Eu(this,wu,"f")[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return Eu(this,ku,"f")||n?.length||Promise.reject(e),Eu(this,mu,"f").call(this,e),Eu(this,yu,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];Eu(this,ku,"f")||n?.length||Promise.reject(e),Eu(this,mu,"f").call(this,e),Eu(this,yu,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function Iu(e){return"auto-parseable-response-format"===e?.$brand}function Cu(e){return"auto-parseable-tool"===e?.$brand}function Pu(e,t){const n=e.choices.map(e=>{if("length"===e.finish_reason)throw new kc;if("content_filter"===e.finish_reason)throw new Sc;return{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>function(e,t){const n=e.tools?.find(e=>e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Cu(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?Ru(t,e.message.content):null}}});return{...e,choices:n}}function Ru(e,t){return"json_schema"!==e.response_format?.type?null:"json_schema"===e.response_format?.type?"$parseRaw"in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function Au(e,t){if(!e)return!1;const n=e.tools?.find(e=>e.function?.name===t.function.name);return Cu(n)||n?.function.strict||!1}function Nu(e){return!!Iu(e.response_format)||(e.tools?.some(e=>Cu(e)||"function"===e.type&&!0===e.function.strict)??!1)}pu=new WeakMap,fu=new WeakMap,mu=new WeakMap,gu=new WeakMap,_u=new WeakMap,yu=new WeakMap,wu=new WeakMap,vu=new WeakMap,bu=new WeakMap,$u=new WeakMap,ku=new WeakMap,hu=new WeakSet,Su=function(e){if(xu(this,bu,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new hc),e instanceof hc)return xu(this,$u,!0,"f"),this._emit("abort",e);if(e instanceof uc)return this._emit("error",e);if(e instanceof Error){const t=new uc(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new uc(String(e)))};var Ou,ju,Mu,zu,Du,Lu,Uu,qu,Fu=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};const Hu=10;class Vu extends Tu{constructor(){super(...arguments),Ou.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t)if(this._emit("message",e),(uu(e)||du(e))&&e.content)this._emit("functionCallResult",e.content);else if(lu(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(lu(e)&&e.tool_calls)for(const t of e.tool_calls)"function"===t.type&&this._emit("functionCall",t.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new uc("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Fu(this,Ou,"m",ju).call(this)}async finalMessage(){return await this.done(),Fu(this,Ou,"m",Mu).call(this)}async finalFunctionCall(){return await this.done(),Fu(this,Ou,"m",zu).call(this)}async finalFunctionCallResult(){return await this.done(),Fu(this,Ou,"m",Du).call(this)}async totalUsage(){return await this.done(),Fu(this,Ou,"m",Lu).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=Fu(this,Ou,"m",Mu).call(this);t&&this._emit("finalMessage",t);const n=Fu(this,Ou,"m",ju).call(this);n&&this._emit("finalContent",n);const s=Fu(this,Ou,"m",zu).call(this);s&&this._emit("finalFunctionCall",s);const r=Fu(this,Ou,"m",Du).call(this);null!=r&&this._emit("finalFunctionCallResult",r),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",Fu(this,Ou,"m",Lu).call(this))}async _createChatCompletion(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),Fu(this,Ou,"m",Uu).call(this,t);const r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Pu(r,t))}async _runChatCompletion(e,t,n){for(const e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runFunctions(e,t,n){const s="function",{function_call:r="auto",stream:o,...a}=t,i="string"!=typeof r&&r?.name,{maxChatCompletions:c=Hu}=n||{},l={};for(const e of t.functions)l[e.name||e.function.name]=e;const u=t.functions.map(e=>({name:e.name||e.function.name,parameters:e.parameters,description:e.description}));for(const e of t.messages)this._addMessage(e,!1);for(let t=0;t<c;++t){const t=await this._createChatCompletion(e,{...a,function_call:r,functions:u,messages:[...this.messages]},n),o=t.choices[0]?.message;if(!o)throw new uc("missing message in ChatCompletion response");if(!o.function_call)return;const{name:c,arguments:d}=o.function_call,h=l[c];if(!h){const e=`Invalid function_call: ${JSON.stringify(c)}. Available options are: ${u.map(e=>JSON.stringify(e.name)).join(", ")}. Please try again`;this._addMessage({role:s,name:c,content:e});continue}if(i&&i!==c){const e=`Invalid function_call: ${JSON.stringify(c)}. ${JSON.stringify(i)} requested. Please try again`;this._addMessage({role:s,name:c,content:e});continue}let p;try{p=cu(h)?await h.parse(d):d}catch(e){this._addMessage({role:s,name:c,content:e instanceof Error?e.message:String(e)});continue}const f=await h.function(p,this),m=Fu(this,Ou,"m",qu).call(this,f);if(this._addMessage({role:s,name:c,content:m}),i)return}}async _runTools(e,t,n){const s="tool",{tool_choice:r="auto",stream:o,...a}=t,i="string"!=typeof r&&r?.function?.name,{maxChatCompletions:c=Hu}=n||{},l=t.tools.map(e=>{if(Cu(e)){if(!e.$callback)throw new uc("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),u={};for(const e of l)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);const d="tools"in t?l.map(e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(const e of t.messages)this._addMessage(e,!1);for(let t=0;t<c;++t){const t=await this._createChatCompletion(e,{...a,tool_choice:r,tools:d,messages:[...this.messages]},n),o=t.choices[0]?.message;if(!o)throw new uc("missing message in ChatCompletion response");if(!o.tool_calls?.length)return;for(const e of o.tool_calls){if("function"!==e.type)continue;const t=e.id,{name:n,arguments:r}=e.function,o=u[n];if(!o){const e=`Invalid tool_call: ${JSON.stringify(n)}. Available options are: ${Object.keys(u).map(e=>JSON.stringify(e)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:t,content:e});continue}if(i&&i!==n){const e=`Invalid tool_call: ${JSON.stringify(n)}. ${JSON.stringify(i)} requested. Please try again`;this._addMessage({role:s,tool_call_id:t,content:e});continue}let a;try{a=cu(o)?await o.parse(r):r}catch(e){const n=e instanceof Error?e.message:String(e);this._addMessage({role:s,tool_call_id:t,content:n});continue}const c=await o.function(a,this),l=Fu(this,Ou,"m",qu).call(this,c);if(this._addMessage({role:s,tool_call_id:t,content:l}),i)return}}}}Ou=new WeakSet,ju=function(){return Fu(this,Ou,"m",Mu).call(this).content??null},Mu=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(lu(t)){const{function_call:e,...n}=t,s={...n,content:t.content??null,refusal:t.refusal??null};return e&&(s.function_call=e),s}}throw new uc("stream ended without producing a ChatCompletionMessage with role=assistant")},zu=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(lu(t)&&t?.function_call)return t.function_call;if(lu(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},Du=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(uu(t)&&null!=t.content)return t.content;if(du(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some(e=>"assistant"===e.role&&e.tool_calls?.some(e=>"function"===e.type&&e.id===t.tool_call_id)))return t.content}},Lu=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Uu=function(e){if(null!=e.n&&e.n>1)throw new uc("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},qu=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class Wu extends Vu{static runFunctions(e,t,n){const s=new Wu,r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,r)),s}static runTools(e,t,n){const s=new Wu,r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,r)),s}_addMessage(e,t=!0){super._addMessage(e,t),lu(e)&&e.content&&this._emit("content",e.content)}}class Bu extends Error{}class Zu extends Error{}const Gu=e=>function(e,t=511){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return((e,t)=>{const n=e.length;let s=0;const r=e=>{throw new Bu(`${e} at position ${s}`)},o=e=>{throw new Zu(`${e} at position ${s}`)},a=()=>(d(),s>=n&&r("Unexpected end of input"),'"'===e[s]?i():"{"===e[s]?c():"["===e[s]?l():"null"===e.substring(s,s+4)||16&t&&n-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):"true"===e.substring(s,s+4)||32&t&&n-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):"false"===e.substring(s,s+5)||32&t&&n-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):"Infinity"===e.substring(s,s+8)||128&t&&n-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):"-Infinity"===e.substring(s,s+9)||256&t&&1<n-s&&n-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):"NaN"===e.substring(s,s+3)||64&t&&n-s<3&&"NaN".startsWith(e.substring(s))?(s+=3,NaN):u()),i=()=>{const a=s;let i=!1;for(s++;s<n&&('"'!==e[s]||i&&"\\"===e[s-1]);)i="\\"===e[s]&&!i,s++;if('"'==e.charAt(s))try{return JSON.parse(e.substring(a,++s-Number(i)))}catch(e){o(String(e))}else if(1&t)try{return JSON.parse(e.substring(a,s-Number(i))+'"')}catch(t){return JSON.parse(e.substring(a,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{s++,d();const o={};try{for(;"}"!==e[s];){if(d(),s>=n&&8&t)return o;const r=i();d(),s++;try{const e=a();Object.defineProperty(o,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(8&t)return o;throw e}d(),","===e[s]&&s++}}catch(e){if(8&t)return o;r("Expected '}' at end of object")}return s++,o},l=()=>{s++;const n=[];try{for(;"]"!==e[s];)n.push(a()),d(),","===e[s]&&s++}catch(e){if(4&t)return n;r("Expected ']' at end of array")}return s++,n},u=()=>{if(0===s){"-"===e&&2&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(n){if(2&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(e){}o(String(n))}}const a=s;for("-"===e[s]&&s++;e[s]&&!",]}".includes(e[s]);)s++;s!=n||2&t||r("Unterminated number literal");try{return JSON.parse(e.substring(a,s))}catch(n){"-"===e.substring(a,s)&&2&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(a,e.lastIndexOf("e")))}catch(e){o(String(e))}}},d=()=>{for(;s<n&&" \n\r\t".includes(e[s]);)s++};return a()})(e.trim(),t)}(e,509);var Ku,Ju,Xu,Yu,Qu,ed,td,nd,sd,rd,od,ad,id=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},cd=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class ld extends Vu{constructor(e){super(),Ku.add(this),Ju.set(this,void 0),Xu.set(this,void 0),Yu.set(this,void 0),id(this,Ju,e,"f"),id(this,Xu,[],"f")}get currentChatCompletionSnapshot(){return cd(this,Yu,"f")}static fromReadableStream(e){const t=new ld(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const s=new ld(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,n){super._createChatCompletion;const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),cd(this,Ku,"m",Qu).call(this);const r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const e of r)cd(this,Ku,"m",td).call(this,e);if(r.controller.signal?.aborted)throw new hc;return this._addChatCompletion(cd(this,Ku,"m",rd).call(this))}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),cd(this,Ku,"m",Qu).call(this),this._connected();const s=Ac.fromReadableStream(e,this.controller);let r;for await(const e of s)r&&r!==e.id&&this._addChatCompletion(cd(this,Ku,"m",rd).call(this)),cd(this,Ku,"m",td).call(this,e),r=e.id;if(s.controller.signal?.aborted)throw new hc;return this._addChatCompletion(cd(this,Ku,"m",rd).call(this))}[(Ju=new WeakMap,Xu=new WeakMap,Yu=new WeakMap,Ku=new WeakSet,Qu=function(){this.ended||id(this,Yu,void 0,"f")},ed=function(e){let t=cd(this,Xu,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},cd(this,Xu,"f")[e.index]=t,t)},td=function(e){if(this.ended)return;const t=cd(this,Ku,"m",ad).call(this,e);this._emit("chunk",e,t);for(const n of e.choices){const e=t.choices[n.index];null!=n.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",n.delta.content,e.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=n.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:e.message.refusal}),null!=n.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=n.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const s=cd(this,Ku,"m",ed).call(this,e);e.finish_reason&&(cd(this,Ku,"m",sd).call(this,e),null!=s.current_tool_call_index&&cd(this,Ku,"m",nd).call(this,e,s.current_tool_call_index));for(const t of n.delta.tool_calls??[])s.current_tool_call_index!==t.index&&(cd(this,Ku,"m",sd).call(this,e),null!=s.current_tool_call_index&&cd(this,Ku,"m",nd).call(this,e,s.current_tool_call_index)),s.current_tool_call_index=t.index;for(const t of n.delta.tool_calls??[]){const n=e.message.tool_calls?.[t.index];n?.type&&("function"===n?.type?this._emit("tool_calls.function.arguments.delta",{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??""}):hd())}}},nd=function(e,t){if(cd(this,Ku,"m",ed).call(this,e).done_tool_calls.has(t))return;const n=e.message.tool_calls?.[t];if(!n)throw new Error("no tool call snapshot");if(!n.type)throw new Error("tool call snapshot missing `type`");if("function"===n.type){const e=cd(this,Ju,"f")?.tools?.find(e=>"function"===e.type&&e.function.name===n.function.name);this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:Cu(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},sd=function(e){const t=cd(this,Ku,"m",ed).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const n=cd(this,Ku,"m",od).call(this);this._emit("content.done",{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},rd=function(){if(this.ended)throw new uc("stream has ended, this shouldn't happen");const e=cd(this,Yu,"f");if(!e)throw new uc("request ended without sending any chunks");return id(this,Yu,void 0,"f"),id(this,Xu,[],"f"),function(e,t){const{id:n,choices:s,created:r,model:o,system_fingerprint:a,...i}=e,c={...i,id:n,choices:s.map(({message:t,finish_reason:n,index:s,logprobs:r,...o})=>{if(!n)throw new uc(`missing finish_reason for choice ${s}`);const{content:a=null,function_call:i,tool_calls:c,...l}=t,u=t.role;if(!u)throw new uc(`missing role for choice ${s}`);if(i){const{arguments:e,name:c}=i;if(null==e)throw new uc(`missing function_call.arguments for choice ${s}`);if(!c)throw new uc(`missing function_call.name for choice ${s}`);return{...o,message:{content:a,function_call:{arguments:e,name:c},role:u,refusal:t.refusal??null},finish_reason:n,index:s,logprobs:r}}return c?{...o,index:s,finish_reason:n,logprobs:r,message:{...l,role:u,content:a,refusal:t.refusal??null,tool_calls:c.map((t,n)=>{const{function:r,type:o,id:a,...i}=t,{arguments:c,name:l,...u}=r||{};if(null==a)throw new uc(`missing choices[${s}].tool_calls[${n}].id\n${ud(e)}`);if(null==o)throw new uc(`missing choices[${s}].tool_calls[${n}].type\n${ud(e)}`);if(null==l)throw new uc(`missing choices[${s}].tool_calls[${n}].function.name\n${ud(e)}`);if(null==c)throw new uc(`missing choices[${s}].tool_calls[${n}].function.arguments\n${ud(e)}`);return{...i,id:a,type:o,function:{...u,name:l,arguments:c}}})}}:{...o,message:{...l,content:a,role:u,refusal:t.refusal??null},finish_reason:n,index:s,logprobs:r}}),created:r,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return function(e,t){return t&&Nu(t)?Pu(e,t):{...e,choices:e.choices.map(e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}}(c,t)}(e,cd(this,Ju,"f"))},od=function(){const e=cd(this,Ju,"f")?.response_format;return Iu(e)?e:null},ad=function(e){var t,n,s,r;let o=cd(this,Yu,"f");const{choices:a,...i}=e;o?Object.assign(o,i):o=id(this,Yu,{...i,choices:[]},"f");for(const{delta:a,finish_reason:i,index:c,logprobs:l=null,...u}of e.choices){let e=o.choices[c];if(e||(e=o.choices[c]={finish_reason:i,index:c,message:{},logprobs:l,...u}),l)if(e.logprobs){const{content:s,refusal:r,...o}=l;dd(),Object.assign(e.logprobs,o),s&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...s)),r&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...r))}else e.logprobs=Object.assign({},l);if(i&&(e.finish_reason=i,cd(this,Ju,"f")&&Nu(cd(this,Ju,"f")))){if("length"===i)throw new kc;if("content_filter"===i)throw new Sc}if(Object.assign(e,u),!a)continue;const{content:d,refusal:h,function_call:p,role:f,tool_calls:m,...g}=a;if(dd(),Object.assign(e.message,g),h&&(e.message.refusal=(e.message.refusal||"")+h),f&&(e.message.role=f),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((s=e.message.function_call).arguments??(s.arguments=""),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),d&&(e.message.content=(e.message.content||"")+d,!e.message.refusal&&cd(this,Ku,"m",od).call(this)&&(e.message.parsed=Gu(e.message.content))),m){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:n,type:s,function:o,...a}of m){const i=(r=e.message.tool_calls)[t]??(r[t]={});Object.assign(i,a),n&&(i.id=n),s&&(i.type=s),o&&(i.function??(i.function={name:o.name??"",arguments:""})),o?.name&&(i.function.name=o.name),o?.arguments&&(i.function.arguments+=o.arguments,Au(cd(this,Ju,"f"),i)&&(i.function.parsed_arguments=Gu(i.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",n=>{const s=t.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Ac(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ud(e){return JSON.stringify(e)}function dd(e){}function hd(_x){}class pd extends ld{static fromReadableStream(e){const t=new pd(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,n){const s=new pd(null),r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,r)),s}static runTools(e,t,n){const s=new pd(t),r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,r)),s}}class fd extends wl{parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new uc(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new uc(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(t=>Pu(t,e))}runFunctions(e,t){return e.stream?pd.runFunctions(this._client,e,t):Wu.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?pd.runTools(this._client,e,t):Wu.runTools(this._client,e,t)}stream(e,t){return ld.createChatCompletion(this._client,e,t)}}class md extends wl{constructor(){super(...arguments),this.completions=new fd(this._client)}}!function(e){e.Completions=fd}(md||(md={}));class gd extends wl{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class _d extends wl{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class yd extends wl{constructor(){super(...arguments),this.sessions=new gd(this._client),this.transcriptionSessions=new _d(this._client)}}yd.Sessions=gd,yd.TranscriptionSessions=_d;var wd,vd,bd,$d,kd,Sd,xd,Ed,Td,Id,Cd,Pd,Rd,Ad,Nd,Od,jd,Md,zd,Dd,Ld,Ud,qd=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)},Fd=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n};class Hd extends Tu{constructor(){super(...arguments),wd.add(this),vd.set(this,[]),bd.set(this,{}),$d.set(this,{}),kd.set(this,void 0),Sd.set(this,void 0),xd.set(this,void 0),Ed.set(this,void 0),Td.set(this,void 0),Id.set(this,void 0),Cd.set(this,void 0),Pd.set(this,void 0),Rd.set(this,void 0)}[(vd=new WeakMap,bd=new WeakMap,$d=new WeakMap,kd=new WeakMap,Sd=new WeakMap,xd=new WeakMap,Ed=new WeakMap,Td=new WeakMap,Id=new WeakMap,Cd=new WeakMap,Pd=new WeakMap,Rd=new WeakMap,wd=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",n=>{const s=t.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new Hd;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=Ac.fromReadableStream(e,this.controller);for await(const e of s)qd(this,wd,"m",Ad).call(this,e);if(s.controller.signal?.aborted)throw new hc;return this._addRun(qd(this,wd,"m",Nd).call(this))}toReadableStream(){return new Ac(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,r){const o=new Hd;return o._run(()=>o._runToolAssistantStream(e,t,n,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,n,s,r){const o=r?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},i=await e.submitToolOutputs(t,n,a,{...r,signal:this.controller.signal});this._connected();for await(const e of i)qd(this,wd,"m",Ad).call(this,e);if(i.controller.signal?.aborted)throw new hc;return this._addRun(qd(this,wd,"m",Nd).call(this))}static createThreadAssistantStream(e,t,n){const s=new Hd;return s._run(()=>s._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,n,s){const r=new Hd;return r._run(()=>r._runAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}currentEvent(){return qd(this,Cd,"f")}currentRun(){return qd(this,Pd,"f")}currentMessageSnapshot(){return qd(this,kd,"f")}currentRunStepSnapshot(){return qd(this,Rd,"f")}async finalRunSteps(){return await this.done(),Object.values(qd(this,bd,"f"))}async finalMessages(){return await this.done(),Object.values(qd(this,$d,"f"))}async finalRun(){if(await this.done(),!qd(this,Sd,"f"))throw Error("Final run was not received.");return qd(this,Sd,"f")}async _createThreadAssistantStream(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const r={...t,stream:!0},o=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(const e of o)qd(this,wd,"m",Ad).call(this,e);if(o.controller.signal?.aborted)throw new hc;return this._addRun(qd(this,wd,"m",Nd).call(this))}async _createAssistantStream(e,t,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const o={...n,stream:!0},a=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(const e of a)qd(this,wd,"m",Ad).call(this,e);if(a.controller.signal?.aborted)throw new hc;return this._addRun(qd(this,wd,"m",Nd).call(this))}static accumulateDelta(e,t){for(const[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let t=e[n];if(null!=t)if("index"!==n&&"type"!==n){if("string"==typeof t&&"string"==typeof s)t+=s;else if("number"==typeof t&&"number"==typeof s)t+=s;else{if(!yl(t)||!yl(s)){if(Array.isArray(t)&&Array.isArray(s)){if(t.every(e=>"string"==typeof e||"number"==typeof e)){t.push(...s);continue}for(const e of s){if(!yl(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const n=e.index;if(null==n)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof n)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);const s=t[n];null==s?t.push(e):t[n]=this.accumulateDelta(s,e)}continue}throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${t}`)}t=this.accumulateDelta(t,s)}e[n]=t}else e[n]=s;else e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s,r){return await this._createToolAssistantStream(n,e,t,s,r)}}Ad=function(e){if(!this.ended)switch(Fd(this,Cd,e,"f"),qd(this,wd,"m",Md).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":qd(this,wd,"m",Ud).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":qd(this,wd,"m",jd).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":qd(this,wd,"m",Od).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Nd=function(){if(this.ended)throw new uc("stream has ended, this shouldn't happen");if(!qd(this,Sd,"f"))throw Error("Final run has not been received");return qd(this,Sd,"f")},Od=function(e){const[t,n]=qd(this,wd,"m",Dd).call(this,e,qd(this,kd,"f"));Fd(this,kd,t,"f"),qd(this,$d,"f")[t.id]=t;for(const e of n){const n=t.content[e.index];"text"==n?.type&&this._emit("textCreated",n.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const n of e.data.delta.content){if("text"==n.type&&n.text){let e=n.text,s=t.content[n.index];if(!s||"text"!=s.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,s.text)}if(n.index!=qd(this,xd,"f")){if(qd(this,Ed,"f"))switch(qd(this,Ed,"f").type){case"text":this._emit("textDone",qd(this,Ed,"f").text,qd(this,kd,"f"));break;case"image_file":this._emit("imageFileDone",qd(this,Ed,"f").image_file,qd(this,kd,"f"))}Fd(this,xd,n.index,"f")}Fd(this,Ed,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==qd(this,xd,"f")){const t=e.data.content[qd(this,xd,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,qd(this,kd,"f"));break;case"text":this._emit("textDone",t.text,qd(this,kd,"f"))}}qd(this,kd,"f")&&this._emit("messageDone",e.data),Fd(this,kd,void 0,"f")}},jd=function(e){const t=qd(this,wd,"m",zd).call(this,e);switch(Fd(this,Rd,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&"tool_calls"==n.step_details.type&&n.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of n.step_details.tool_calls)e.index==qd(this,Td,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(qd(this,Id,"f")&&this._emit("toolCallDone",qd(this,Id,"f")),Fd(this,Td,e.index,"f"),Fd(this,Id,t.step_details.tool_calls[e.index],"f"),qd(this,Id,"f")&&this._emit("toolCallCreated",qd(this,Id,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Fd(this,Rd,void 0,"f"),"tool_calls"==e.data.step_details.type&&qd(this,Id,"f")&&(this._emit("toolCallDone",qd(this,Id,"f")),Fd(this,Id,void 0,"f")),this._emit("runStepDone",e.data,t)}},Md=function(e){qd(this,vd,"f").push(e),this._emit("event",e)},zd=function(e){switch(e.event){case"thread.run.step.created":return qd(this,bd,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=qd(this,bd,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){const s=Hd.accumulateDelta(t,n.delta);qd(this,bd,"f")[e.data.id]=s}return qd(this,bd,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":qd(this,bd,"f")[e.data.id]=e.data}if(qd(this,bd,"f")[e.data.id])return qd(this,bd,"f")[e.data.id];throw new Error("No snapshot available")},Dd=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const e of s.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=qd(this,wd,"m",Ld).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Ld=function(e,t){return Hd.accumulateDelta(t,e)},Ud=function(e){switch(Fd(this,Pd,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.cancelling":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":Fd(this,Sd,e.data,"f"),qd(this,Id,"f")&&(this._emit("toolCallDone",qd(this,Id,"f")),Fd(this,Id,void 0,"f"))}};class Vd extends wl{create(e,t,n){return this._client.post(`/threads/${e}/messages`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/messages/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return Qc(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Wd,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t,n){return this._client.delete(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class Wd extends kl{}Vd.MessagesPage=Wd;class Bd extends wl{retrieve(e,t,n,s={},r){return Qc(s)?this.retrieve(e,t,n,{},s):this._client.get(`/threads/${e}/runs/${t}/steps/${n}`,{query:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t,n={},s){return Qc(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Zd,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}}class Zd extends kl{}Bd.RunStepsPage=Zd;class Gd extends wl{constructor(){super(...arguments),this.steps=new Bd(this._client)}create(e,t,n){const{include:s,...r}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:s},body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:t.stream??!1})}retrieve(e,t,n){return this._client.get(`/threads/${e}/runs/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return Qc(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Kd,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(e,t,n){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}createAndStream(e,t,n){return Hd.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:r,response:o}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...s}}).withResponse();switch(r.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await il(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,n){return Hd.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers},stream:n.stream??!1})}async submitToolOutputsAndPoll(e,t,n,s){const r=await this.submitToolOutputs(e,t,n,s);return await this.poll(e,r.id,s)}submitToolOutputsStream(e,t,n,s){return Hd.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}}class Kd extends kl{}Gd.RunsPage=Kd,Gd.Steps=Bd,Gd.RunStepsPage=Zd;class Jd extends wl{constructor(){super(...arguments),this.runs=new Gd(this._client),this.messages=new Vd(this._client)}create(e={},t){return Qc(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/threads/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const n=await this.createAndRun(e,t);return await this.runs.poll(n.thread_id,n.id,t)}createAndRunStream(e,t){return Hd.createThreadAssistantStream(e,this._client.beta.threads,t)}}Jd.Runs=Gd,Jd.RunsPage=Kd,Jd.Messages=Vd,Jd.MessagesPage=Wd;class Xd extends wl{constructor(){super(...arguments),this.realtime=new yd(this._client),this.chat=new md(this._client),this.assistants=new au(this._client),this.threads=new Jd(this._client)}}Xd.Realtime=yd,Xd.Assistants=au,Xd.AssistantsPage=iu,Xd.Threads=Jd;class Yd extends wl{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return Qc(e)?this.list({},e):this._client.getAPIList("/batches",Qd,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class Qd extends kl{}Yd.BatchesPage=Qd;class eh extends wl{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,qc({body:t,...n}))}}class th extends wl{constructor(){super(...arguments),this.parts=new eh(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(`/uploads/${e}/complete`,{body:t,...n})}}function nh(e,t){const n=e.output.map(e=>{if("function_call"===e.type)return{...e,parsed_arguments:rh(t,e)};if("message"===e.type){const n=e.content.map(e=>"output_text"===e.type?{...e,parsed:sh(t,e.text)}:e);return{...e,content:n}}return e}),s=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||oh(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const e of s.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),s}function sh(e,t){if("json_schema"!==e.text?.format?.type)return null;if("$parseRaw"in e.text?.format){const n=e.text?.format;return n.$parseRaw(t)}return JSON.parse(t)}function rh(e,t){const n=(s=e.tools??[],r=t.name,s.find(e=>"function"===e.type&&e.name===r));var s,r,o;return{...t,...t,parsed_arguments:(o=n,"auto-parseable-tool"===o?.$brand?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null)}}function oh(e){const t=[];for(const n of e.output)if("message"===n.type)for(const e of n.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}th.Parts=eh;class ah extends wl{list(e,t={},n){return Qc(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,vh,{query:t,...n})}}var ih,ch,lh,uh,dh,hh,ph,fh,mh,gh=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},_h=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class yh extends Tu{constructor(e){super(),ih.add(this),ch.set(this,void 0),lh.set(this,void 0),uh.set(this,void 0),gh(this,ch,e,"f")}static createResponse(e,t,n){const s=new yh(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,n){const s=n?.signal;let r;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),_h(this,ih,"m",dh).call(this);let o=null;"response_id"in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const e of r)_h(this,ih,"m",hh).call(this,e,o);if(r.controller.signal?.aborted)throw new hc;return _h(this,ih,"m",ph).call(this)}[(ch=new WeakMap,lh=new WeakMap,uh=new WeakMap,ih=new WeakSet,dh=function(){this.ended||gh(this,lh,void 0,"f")},hh=function(e,t){if(this.ended)return;const n=(e,n)=>{(null==t||n.sequence_number>t)&&this._emit(e,n)},s=_h(this,ih,"m",fh).call(this,e);switch(n("event",e),e.type){case"response.output_text.delta":{const t=s.output[e.output_index];if(!t)throw new uc(`missing output at index ${e.output_index}`);if("message"===t.type){const s=t.content[e.content_index];if(!s)throw new uc(`missing content at index ${e.content_index}`);if("output_text"!==s.type)throw new uc(`expected content to be 'output_text', got ${s.type}`);n("response.output_text.delta",{...e,snapshot:s.text})}break}case"response.function_call_arguments.delta":{const t=s.output[e.output_index];if(!t)throw new uc(`missing output at index ${e.output_index}`);"function_call"===t.type&&n("response.function_call_arguments.delta",{...e,snapshot:t.arguments});break}default:n(e.type,e)}},ph=function(){if(this.ended)throw new uc("stream has ended, this shouldn't happen");const e=_h(this,lh,"f");if(!e)throw new uc("request ended without sending any events");gh(this,lh,void 0,"f");const t=function(e,t){return function(e,t){return t&&function(e){return!!Iu(e.text?.format)}(t)?nh(e,t):{...e,output_parsed:null,output:e.output.map(e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}}(e,t)}(e,_h(this,ch,"f"));return gh(this,uh,t,"f"),t},fh=function(e){let t=_h(this,lh,"f");if(!t){if("response.created"!==e.type)throw new uc(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=gh(this,lh,e.response,"f"),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const n=t.output[e.output_index];if(!n)throw new uc(`missing output at index ${e.output_index}`);"message"===n.type&&n.content.push(e.part);break}case"response.output_text.delta":{const n=t.output[e.output_index];if(!n)throw new uc(`missing output at index ${e.output_index}`);if("message"===n.type){const t=n.content[e.content_index];if(!t)throw new uc(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new uc(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const n=t.output[e.output_index];if(!n)throw new uc(`missing output at index ${e.output_index}`);"function_call"===n.type&&(n.arguments+=e.delta);break}case"response.completed":gh(this,lh,e.response,"f")}return t},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",n=>{const s=t.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=_h(this,uh,"f");if(!e)throw new uc("stream ended without producing a ChatCompletion");return e}}class wh extends wl{constructor(){super(...arguments),this.inputItems=new ah(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&oh(e),e))}retrieve(e,t={},n){return this._client.get(`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>nh(t,e))}stream(e,t){return yh.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(`/responses/${e}/cancel`,{...t,headers:{Accept:"*/*",...t?.headers}})}}class vh extends kl{}wh.InputItems=ah;class bh extends wl{retrieve(e,t,n,s){return this._client.get(`/evals/${e}/runs/${t}/output_items/${n}`,s)}list(e,t,n={},s){return Qc(n)?this.list(e,t,{},n):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,$h,{query:n,...s})}}class $h extends kl{}bh.OutputItemListResponsesPage=$h;class kh extends wl{constructor(){super(...arguments),this.outputItems=new bh(this._client)}create(e,t,n){return this._client.post(`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){return this._client.get(`/evals/${e}/runs/${t}`,n)}list(e,t={},n){return Qc(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,Sh,{query:t,...n})}del(e,t,n){return this._client.delete(`/evals/${e}/runs/${t}`,n)}cancel(e,t,n){return this._client.post(`/evals/${e}/runs/${t}`,n)}}class Sh extends kl{}kh.RunListResponsesPage=Sh,kh.OutputItems=bh,kh.OutputItemListResponsesPage=$h;class xh extends wl{constructor(){super(...arguments),this.runs=new kh(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(`/evals/${e}`,t)}update(e,t,n){return this._client.post(`/evals/${e}`,{body:t,...n})}list(e={},t){return Qc(e)?this.list({},e):this._client.getAPIList("/evals",Eh,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}}class Eh extends kl{}xh.EvalListResponsesPage=Eh,xh.Runs=kh,xh.RunListResponsesPage=Sh;class Th extends wl{retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}/content`,{...n,headers:{Accept:"application/binary",...n?.headers},__binaryResponse:!0})}}class Ih extends wl{constructor(){super(...arguments),this.content=new Th(this._client)}create(e,t,n){return this._client.post(`/containers/${e}/files`,qc({body:t,...n}))}retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}`,n)}list(e,t={},n){return Qc(t)?this.list(e,{},t):this._client.getAPIList(`/containers/${e}/files`,Ch,{query:t,...n})}del(e,t,n){return this._client.delete(`/containers/${e}/files/${t}`,{...n,headers:{Accept:"*/*",...n?.headers}})}}class Ch extends kl{}Ih.FileListResponsesPage=Ch,Ih.Content=Th;class Ph extends wl{constructor(){super(...arguments),this.files=new Ih(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(`/containers/${e}`,t)}list(e={},t){return Qc(e)?this.list({},e):this._client.getAPIList("/containers",Rh,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}}class Rh extends kl{}Ph.ContainerListResponsesPage=Rh,Ph.Files=Ih,Ph.FileListResponsesPage=Ch;class Ah extends Gc{constructor({baseURL:e=ul("OPENAI_BASE_URL"),apiKey:t=ul("OPENAI_API_KEY"),organization:n=ul("OPENAI_ORG_ID")??null,project:s=ul("OPENAI_PROJECT_ID")??null,...r}={}){if(void 0===t)throw new uc("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const o={apiKey:t,organization:n,project:s,...r,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new uc("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:o.baseURL,timeout:o.timeout??6e5,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new vl(this),this.chat=new Tl(this),this.embeddings=new Il(this),this.files=new Cl(this),this.images=new Rl(this),this.audio=new jl(this),this.moderations=new Ml(this),this.models=new zl(this),this.fineTuning=new Jl(this),this.graders=new Yl(this),this.vectorStores=new su(this),this.beta=new Xd(this),this.batches=new Yd(this),this.uploads=new th(this),this.responses=new wh(this),this.evals=new xh(this),this.containers=new Ph(this),this._options=o,this.apiKey=t,this.organization=n,this.project=s}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return function(e,t={}){let n=e;const s=function(e=Vi){if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");const t=e.charset||Vi.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=Ai;if(void 0!==e.format){if(!Di.call(Ni,e.format))throw new TypeError("Unknown format option provided.");n=e.format}const s=Ni[n];let r,o=Vi.filter;if(("function"==typeof e.filter||Ui(e.filter))&&(o=e.filter),r=e.arrayFormat&&e.arrayFormat in Li?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":Vi.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=void 0===e.allowDots?1==!!e.encodeDotInKeys||Vi.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Vi.addQueryPrefix,allowDots:a,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:Vi.allowEmptyArrays,arrayFormat:r,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Vi.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?Vi.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Vi.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:Vi.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:Vi.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Vi.encodeValuesOnly,filter:o,format:n,formatter:s,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Vi.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Vi.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Vi.strictNullHandling}}(t);let r,o;"function"==typeof s.filter?(o=s.filter,n=o("",n)):Ui(s.filter)&&(o=s.filter,r=o);const a=[];if("object"!=typeof n||null===n)return"";const i=Li[s.arrayFormat],c="comma"===i&&s.commaRoundTrip;r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);const l=new WeakMap;for(let e=0;e<r.length;++e){const t=r[e];s.skipNulls&&null===n[t]||Fi(a,Bi(n[t],t,i,c,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,l))}const u=a.join(s.delimiter);let d=!0===s.addQueryPrefix?"?":"";return s.charsetSentinel&&("iso-8859-1"===s.charset?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}(e,{arrayFormat:"brackets"})}}mh=Ah,Ah.OpenAI=mh,Ah.DEFAULT_TIMEOUT=6e5,Ah.OpenAIError=uc,Ah.APIError=dc,Ah.APIConnectionError=pc,Ah.APIConnectionTimeoutError=fc,Ah.APIUserAbortError=hc,Ah.NotFoundError=yc,Ah.ConflictError=wc,Ah.RateLimitError=bc,Ah.BadRequestError=mc,Ah.AuthenticationError=gc,Ah.InternalServerError=$c,Ah.PermissionDeniedError=_c,Ah.UnprocessableEntityError=vc,Ah.toFile=zc,Ah.fileFromPath=tc,Ah.Completions=vl,Ah.Chat=Tl,Ah.ChatCompletionsPage=xl,Ah.Embeddings=Il,Ah.Files=Cl,Ah.FileObjectsPage=Pl,Ah.Images=Rl,Ah.Audio=jl,Ah.Moderations=Ml,Ah.Models=zl,Ah.ModelsPage=Dl,Ah.FineTuning=Jl,Ah.Graders=Yl,Ah.VectorStores=su,Ah.VectorStoresPage=ru,Ah.VectorStoreSearchResponsesPage=ou,Ah.Beta=Xd,Ah.Batches=Yd,Ah.BatchesPage=Qd,Ah.Uploads=th,Ah.Responses=wh,Ah.Evals=xh,Ah.EvalListResponsesPage=Eh,Ah.Containers=Ph,Ah.ContainerListResponsesPage=Rh,new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/images/edits"]);const Nh=Ah,Oh="gpt-4o-mini";class jh extends Error{constructor(e,t=null,n=null){super(e),this.name="OpenAIError",this.status=t,this.code=n}}class Mh{constructor(e={}){this.configKey=e.configKey||"nfdAIChat",this.apiPath=e.apiPath||"ai",this.mode=e.mode||"help",this.openai=null,this.config=null}getConfig(){return this.config||("undefined"!=typeof window&&window[this.configKey]?this.config={nonce:window[this.configKey].nonce,restUrl:window[this.configKey].restUrl,homeUrl:window[this.configKey].homeUrl}:this.config={nonce:"",restUrl:"",homeUrl:""}),this.config}getOpenAIClient(){if(this.openai)return this.openai;const e=this.getConfig();return this.openai=new Nh({apiKey:"proxy",baseURL:`${e.restUrl}${this.apiPath}`,dangerouslyAllowBrowser:!0,defaultHeaders:{"X-WP-Nonce":e.nonce}}),this.openai}async createChatCompletion(e){try{const t=this.getOpenAIClient();return await t.chat.completions.create({model:e.model||Oh,messages:e.messages,tools:e.tools,tool_choice:e.tool_choice,stream:!1,max_tokens:e.max_tokens,temperature:e.temperature,mode:e.mode||this.mode})}catch(e){throw new jh(e.message||"OpenAI API request failed",e.status,e.code)}}async createStreamingCompletion(e,t,n,s){try{const s=this.getOpenAIClient(),r=await s.chat.completions.create({...e,messages:e.messages,stream:!0,stream_options:{include_usage:!0},mode:e.mode||this.mode});let o="",a=null;const i={};let c=null;for await(const e of r){const n=e.choices[0]?.delta;if(n?.reasoning&&t({type:"reasoning",content:n.reasoning}),n?.content&&(o+=n.content,t({type:"content",content:n.content})),n?.tool_calls){for(const e of n.tool_calls){const t=e.index;i[t]||(i[t]={id:e.id||"",type:"function",function:{name:e.function?.name||"",arguments:""}}),e.id&&(i[t].id=e.id),e.function?.name&&(i[t].function.name=e.function.name),e.function?.arguments&&(i[t].function.arguments+=e.function.arguments)}t({type:"tool_calls",tool_calls:Object.values(i)})}e.choices[0]?.finish_reason&&(c=e.choices[0].finish_reason),e.usage&&(a=e.usage,console.log(`[Token Usage] prompt: ${a.prompt_tokens} | completion: ${a.completion_tokens} | total: ${a.total_tokens}`))}if(!a&&r.usage&&(a=r.usage),a&&console.log(`[Token Usage] prompt: ${a.prompt_tokens} | completion: ${a.completion_tokens} | total: ${a.total_tokens}`),c){const e=Object.values(i).map(e=>({id:e.id,name:e.function.name,arguments:e.function.arguments?JSON.parse(e.function.arguments):{}}));await n(o,e.length>0?e:null,a)}}catch(e){s(new jh(e.message||"Streaming request failed",e.status,e.code))}}convertMessagesToOpenAI(e){const t=[];for(const n of e)if("system"===n.role||"user"===n.role)t.push({role:n.role,content:n.content??""});else if("assistant"===n.role){const e=n.toolCalls&&n.toolCalls.length>0;if((null===n.content||void 0===n.content||""===n.content)&&!e){console.warn("Skipping invalid assistant message with no content and no tool calls");continue}let s=n.content??"";e&&s.length>200&&(s=s.substring(0,200)+"...");const r={role:"assistant",content:e?s||null:s};if(e&&(r.tool_calls=n.toolCalls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:"string"==typeof e.arguments?e.arguments:JSON.stringify(e.arguments)}}))),t.push(r),e&&n.toolResults&&n.toolResults.length>0)for(const e of n.toolResults)if(n.toolCalls.some(t=>t.id===e.id)){const n=e.error?`Error: ${e.error.substring(0,100)}`:"Success";t.push({role:"tool",content:n,tool_call_id:e.id})}}return t}convertMCPToolsToOpenAI(e){return e.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.inputSchema}}))}processToolCalls(e){return e.map(e=>({id:e.id,name:e.function.name,arguments:JSON.parse(e.function.arguments||"{}")}))}async sendMessage(e,t=[],n=[]){const s=this.convertMessagesToOpenAI([...t,{id:`user-${Date.now()}`,role:"user",content:e,timestamp:new Date}]),r={model:Oh,messages:s,tools:n.length>0?this.convertMCPToolsToOpenAI(n):void 0,tool_choice:n.length>0?"auto":void 0,temperature:.1,max_tokens:4e3};try{const e=(await this.createChatCompletion(r)).choices[0];if(!e)throw new jh("No response from OpenAI");const t={message:e.message.content||""};return e.message.tool_calls&&(t.toolCalls=this.processToolCalls(e.message.tool_calls)),t}catch(e){if(e instanceof jh)throw e;throw new jh(`Failed to send message: ${e}`)}}}const zh=(e={})=>new Mh(e),Dh=new Mh,Lh=window.wp.element,Uh=e=>{if(!e||"string"!=typeof e)return"0";let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n),t|=0;return(t>>>0).toString(16)},qh=()=>crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`,Fh=(e,t)=>{let n;return function(...s){clearTimeout(n),n=setTimeout(()=>{clearTimeout(n),e(...s)},t)}},Hh={IDLE:"idle",RECEIVED:"received",GENERATING:"generating",TOOL_CALL:"tool_call",SUMMARIZING:"summarizing",COMPLETED:"completed",FAILED:"failed"},Vh=({mcpClient:e=null,openaiClient:t=null,systemPrompt:n="You are a helpful AI assistant. Be concise and helpful in your responses.",onToolCall:s=null,onToolResult:r=null,onMessageComplete:o=null,onError:a=null,autoInitialize:i=!0}={})=>{const[c,l]=(0,Lh.useState)([]),[u,d]=(0,Lh.useState)(!1),[h,p]=(0,Lh.useState)(null),[f,m]=(0,Lh.useState)(Hh.IDLE),[g,_]=(0,Lh.useState)(()=>qh()),[y,w]=(0,Lh.useState)(null),[v,b]=(0,Lh.useState)([]),[$,k]=(0,Lh.useState)([]),[S,x]=(0,Lh.useState)(null),[E,T]=(0,Lh.useState)(!1),[I,C]=(0,Lh.useState)([]),P=(0,Lh.useRef)(!1),R=(0,Lh.useRef)(null),A=(0,Lh.useCallback)(async()=>{if(!e)return!1;try{return e.isConnected()||await e.connect(),await e.initialize(),C(e.getTools()),T(!0),!0}catch(e){return console.error("Failed to initialize MCP:",e),p(`Failed to initialize MCP: ${e.message}`),a?.(e),!1}},[e,a]);(0,Lh.useEffect)(()=>{i&&e&&A();const t=R.current;return()=>{t&&t.abort()}},[i,e,A]);const N=(0,Lh.useCallback)((e,t,n={})=>({id:`${e}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,role:e,type:e,content:t,timestamp:new Date,...n}),[]),O=(0,Lh.useCallback)(async t=>{if(!e)throw new Error("MCP client not available");const{name:n,arguments:o}=t;if(s){const e=await s(t);if(e&&e.intercepted){const s=e.result||{content:[],isError:!1};return r&&await r(t,s),{id:t.id,name:n,result:s,isError:s.isError||!1,hasChanges:s.hasChanges||!1,undoData:e.undoData}}}try{const s=await e.callTool(n,o);return r&&await r(t,s),{id:t.id,name:n,result:s,isError:s.isError||!1}}catch(e){return{id:t.id,name:n,error:e.message,isError:!0}}},[e,s,r]),j=(0,Lh.useCallback)(async e=>{const t=[];k(e.slice(1));for(let n=0;n<e.length;n++){const s=e[n];w({...s,index:n+1,total:e.length});const r=await O(s);t.push(r),b(e=>[...e,{...s,...r}]),k(e.slice(n+2))}return w(null),k([]),t},[O]),M=(0,Lh.useCallback)(async s=>{if(!t)return void p("OpenAI client not configured");if(P.current)return;P.current=!0,d(!0),p(null),m(Hh.RECEIVED),b([]);const r=N("user",s);l(e=>[...e,r]);try{const r=[{role:"system",content:n},...c.map(e=>({role:"user"===e.role?"user":"assistant",content:e.content,toolCalls:e.toolCalls,toolResults:e.toolResults})),{role:"user",content:s}],a=E&&e?e.getToolsForOpenAI():[];m(Hh.GENERATING);let i=null,u=[];if(await t.createStreamingCompletion({messages:t.convertMessagesToOpenAI(r),tools:a.length>0?a:void 0,tool_choice:a.length>0?"auto":void 0},()=>{},async(e,n)=>{if(n&&n.length>0){m(Hh.TOOL_CALL);const s=await j(n);u=s,m(Hh.SUMMARIZING);const o=[...r,{role:"assistant",content:e||null,toolCalls:n,toolResults:s.map(e=>({id:e.id,result:e.result,error:e.error}))}],a=await t.createChatCompletion({messages:t.convertMessagesToOpenAI(o)});i=a.choices?.[0]?.message?.content||""}else i=e},e=>{throw e}),i){const e=N("assistant",i,{toolCalls:u.length>0?u:void 0,executedTools:u.length>0?u:void 0});l(t=>[...t,e]),o?.(e)}m(Hh.COMPLETED)}catch(e){console.error("Chat error:",e),p(e.message),m(Hh.FAILED),a?.(e)}finally{P.current=!1,d(!1),w(null),b([]),k([])}},[t,e,E,c,n,N,j,o,a]),z=(0,Lh.useCallback)(()=>{R.current&&R.current.abort(),P.current=!1,d(!1),m(Hh.IDLE),w(null)},[]),D=(0,Lh.useCallback)(()=>{l([]),p(null),m(Hh.IDLE),_(qh())},[]),L=(0,Lh.useCallback)((e,t,n={})=>{const s=N(e,t,n);return l(e=>[...e,s]),s},[N]);return{messages:c,isLoading:u,error:h,status:f,sessionId:g,activeToolCall:y,executedTools:v,pendingTools:$,toolProgress:S,mcpConnected:E,mcpTools:I,sendMessage:M,stopRequest:z,clearMessages:D,addMessage:L,initializeMCP:A,setError:p,setToolProgress:x}},Wh=window.wp.i18n,Bh={MAX_RECONNECT_ATTEMPTS:5,RECONNECT_DELAY:1e3,TYPING_TIMEOUT:6e4,WS_CLOSE_AUTH_FAILED:4e3,WS_CLOSE_MISSING_TOKEN:4001,JWT_REFRESH_BUFFER_MS:3e5,JWT_REFRESH_MIN_DELAY_MS:3e5,JWT_PROACTIVE_REFRESH_COOLDOWN_MS:36e5,AUTH_REFRESH_COOLDOWN_MS:18e4,JWT_EXPIRED_BUFFER_MS:6e4,JWT_PROACTIVE_REFRESH_DEFER_MS:3e4};function Zh(e){if(!e||"string"!=typeof e)return null;const t=e.split(".");if(3!==t.length)return null;try{const e=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const n=t.length%4;n&&(t+="===".slice(0,4-n));try{return decodeURIComponent(atob(t).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}catch(e){return atob(t)}}(t[1]),n=JSON.parse(e),s=n?.exp;return"number"==typeof s&&Number.isFinite(s)?1e3*s:null}catch(e){return null}}const Gh="nfd-ai-chat-site-id",Kh={history:"history",conversationId:"conversation-id",sessionId:"session-id",archive:"archive"},Jh=()=>{try{return localStorage.getItem(Gh)||""}catch{return""}},Xh=(e,t)=>e?`nfd-ai-chat-${e}-${t}`:`nfd-ai-chat-${t}`,Yh=e=>{const t=Xh(Jh(),e),n={};for(const[e,s]of Object.entries(Kh))n[e]=`${t}-${s}`;return n},Qh=e=>e&&"string"==typeof e?e.startsWith("http://")?e.replace("http://","ws://"):e.startsWith("https://")?e.replace("https://","wss://"):e.startsWith("ws://")||e.startsWith("wss://")?e:ep(e)?`ws://${e}`:`wss://${e}`:e,ep=e=>{if(!e||"string"!=typeof e)return!1;const t=e.toLowerCase();return t.includes("localhost")||t.includes("127.0.0.1")},tp=(e,t,n)=>{const s=Qh(e.gateway_url),r=("nfd-agents"===e.agent_type?"blu":e.agent_type)||"blu",o=`wordpress_${n}`,a=e.huapi_token??e.jarvis_jwt??"";let i=`${s}/${e.brand_id}/agents/${r}/v1/ws?session_id=${t}&token=${encodeURIComponent(a)}&consumer=${encodeURIComponent(o)}`;return e.site_url&&"string"==typeof e.site_url&&e.site_url.trim()&&(i+=`&site_url=${encodeURIComponent(e.site_url.trim())}`),i},np=e=>e&&"string"==typeof e?e.match(/^https?:\/\//)?e:ep(e)?`http://${e}`:`https://${e}`:e,sp={PROCESSING:"processing",CONNECTING:"connecting",WS_CONNECTING:"ws_connecting",TOOL_CALL:"tool_call",WORKING:"working",RECEIVED:"received",GENERATING:"generating",SUMMARIZING:"summarizing",COMPLETED:"completed",FAILED:"failed"};function rp(e){return{typing_start:sp.PROCESSING,handoff_request:sp.CONNECTING,handoff_accept:sp.CONNECTING,tool_call:sp.TOOL_CALL,tool_result:sp.WORKING,typing_stop:null}[e]??null}const op=e=>{if(!e||"string"!=typeof e)return!1;const t=e.toLowerCase().trim(),n=[/^hello!?\s+how\s+can\s+i\s+assist\s+you/i,/^hi!?\s+how\s+can\s+i\s+help/i,/^hello!?\s+how\s+can\s+i\s+help/i,/^hi\s+there!?\s+how\s+can/i,/^greetings!?\s+how\s+can/i,/^how\s+can\s+i\s+assist\s+you\s+today/i,/^how\s+can\s+i\s+help\s+you\s+today/i,/^hello!?\s+how\s+can\s+i\s+assist\s+you\s+today/i,/^hello!?\s+how\s+can\s+i\s+assist\s+you.*feel\s+free/i].some(e=>e.test(t)),s=t.includes("hello")&&(t.includes("assist")||t.includes("help"))&&(t.includes("today")||t.includes("feel free")||t.includes("ask")),r=t.length<150&&(t.includes("hello")&&(t.includes("assist")||t.includes("help"))||t.includes("hi")&&t.includes("help"));return n||s||r},ap=(e,t)=>{const n=e?.trim();return n&&"No content provided"!==n&&"sales_requested"!==n&&"sales_requested"!==n.toLowerCase()?!t&&n.length<150&&op(n)?null:n:null},ip=e=>{e.current&&(clearTimeout(e.current),e.current=null)},cp=({setIsTyping:e,setStatus:t,setCurrentResponse:n,typingTimeoutRef:s})=>{e(!1),t(null),n(""),ip(s)},lp=(e,t,n="")=>{e(e=>[...e,{id:`msg-${Date.now()}${n}`,role:"assistant",type:"assistant",content:t,timestamp:new Date,animateTyping:!0}])},up=window.wp.apiFetch;var dp=n.n(up);async function hp({configEndpoint:e,consumer:t}){try{let n=e,s="undefined"==typeof window?"":(window.nfdAIChat||{}).homeUrl||window.location.origin,r=!1,o="";if(e.startsWith("http://")||e.startsWith("https://")){const t=new URL(e);if(t.searchParams.has("rest_route"))n=t.searchParams.get("rest_route");else if(t.pathname.includes("/wp-json/")){n=t.pathname.replace(/^\/wp-json\//,"").replace(/^\/wp-json/,""),r=!0;const e=t.pathname.split("/wp-json")[0].replace(/\/$/,"");o=t.origin+(e||"/")}else n=t.pathname.replace(/^\//,"");if(!r)if(t.pathname.includes("/wp-json")){const e=t.pathname.split("/wp-json")[0].replace(/\/$/,"");s=t.origin+(e||"/")}else s=t.origin+(t.pathname||"/")}const a=n.replace(/^\//,"");let i;if(r)i=((e,t="")=>{if(e.includes("rest_route="))return e;const n=e.match(/\/wp-json\/(.+)$/);if(!n)return e;const s=n[1];t||"undefined"==typeof window||(t=window.location.origin);const r=t.replace(/\/wp-json\/?$/,""),o=r.includes("?")?"&":"?";return`${r}${o}rest_route=/${s}`})(e,o);else{const e=a.lastIndexOf("/"),t=-1===e?"":a.slice(0,e);i=((e,t,n="")=>{const s=((e="")=>{if(e&&e.includes("rest_route="))return e;e||"undefined"==typeof window||(e=window.location.origin);const t=e.includes("?")?"&":"?";return`${e}${t}rest_route=/`})(n),r=`${e}/${t}`;if(s.includes("rest_route="))return s.replace("rest_route=/",`rest_route=/${r}`);const o=s.includes("?")?"&":"?";return`${s}${o}rest_route=/${r}`})(t,-1===e?a:a.slice(e+1),s)}return i=`${i}&consumer=${encodeURIComponent(t)}`,await dp()({url:i,parse:!0})}catch(e){console.error("[AI Chat] Failed to fetch config:",e),console.error("[AI Chat] Error details:",{message:e.message,code:e.code,data:e.data,status:e.data?.status,statusText:e.data?.statusText});let t=e.message||(0,Wh.__)("Failed to connect","wp-module-ai-chat");throw e.data?.message?t=e.data.message:e.message&&"Could not get a valid response from the server."!==e.message&&(t=e.message),"rest_forbidden"===e.code||403===e.data?.status?t=(0,Wh.__)("Access denied. Please check your capabilities.","wp-module-ai-chat"):"rest_no_route"===e.code||404===e.data?.status?t=(0,Wh.__)("Config endpoint not found. Please ensure the backend is deployed.","wp-module-ai-chat"):"gateway_url_not_configured"===e.code?t=(0,Wh.__)("Gateway URL not configured. Set NFD_AGENTS_CHAT_GATEWAY_URL in wp-config.php.","wp-module-ai-chat"):"jarvis_jwt_fetch_failed"===e.code||"huapi_token_fetch_failed"===e.code?t=(0,Wh.__)("Failed to fetch authentication token from Hiive. Check your connection or set NFD_AGENTS_CHAT_DEBUG_TOKEN for local development.","wp-module-ai-chat"):e.data?.status&&(t=(0,Wh.sprintf)(/* translators: %1$s: HTTP status, %2$s: status text */ /* translators: %1$s: HTTP status, %2$s: status text */
|
|
8
|
-
(0,Wh.__)("Failed to fetch config: %1$s %2$s","wp-module-ai-chat"),e.data.status,e.data.statusText||t)),new Error(t)}}const pp=e=>Array.isArray(e)&&e.some(e=>("user"===e.role||"user"===e.type)&&e.content&&String(e.content).trim()),fp=(e,t,n)=>{try{const s=localStorage.getItem(e),r=localStorage.getItem(t),o=localStorage.getItem(n);if(s){const e=JSON.parse(s);if(Array.isArray(e)&&e.length>0)return{messages:e.map(e=>({...e,timestamp:e.timestamp?new Date(e.timestamp):new Date,animateTyping:!1})),conversationId:r||null,sessionId:o||null}}}catch(e){console.warn("[AI Chat] Failed to restore chat history from localStorage:",e)}return{messages:[],conversationId:null,sessionId:null}},mp=(e,t)=>{try{pp(t)?localStorage.setItem(e,JSON.stringify(t)):localStorage.removeItem(e)}catch(e){console.warn("[AI Chat] Failed to save messages to localStorage:",e)}},gp=({configEndpoint:e,consumer:t,autoConnect:n=!1,consumerType:s="editor_chat",autoLoadHistory:r=!0,getConnectionFailedFallbackMessage:o}={})=>{const a=Yh(t),i=a.history,c=a.conversationId,l=a.sessionId,u=i.replace(/-history$/,""),[d,h]=(0,Lh.useState)(()=>r?fp(i,c,l).messages:[]),[p,f]=(0,Lh.useState)(()=>r?fp(i,c,l).conversationId:null),[m,g]=(0,Lh.useState)(!1),[_,y]=(0,Lh.useState)(!1),[w,v]=(0,Lh.useState)(null),[b,$]=(0,Lh.useState)(!1),[k,S]=(0,Lh.useState)(null),[x,E]=(0,Lh.useState)(""),[T,I]=(0,Lh.useState)(null),[C,P]=(0,Lh.useState)(()=>{try{if("1"===sessionStorage.getItem(`${u}-connection-failed`))return"failed"}catch(e){}return"disconnected"}),[R,A]=(0,Lh.useState)(0),N=(0,Lh.useRef)(null),O=(0,Lh.useRef)(null),j=(0,Lh.useRef)(0),M=(0,Lh.useRef)(null),z=(0,Lh.useRef)(null),D=(0,Lh.useRef)(null),L=(0,Lh.useRef)(null),U=(0,Lh.useRef)(null),q=(0,Lh.useRef)(null),F=(0,Lh.useRef)(null),H=(0,Lh.useRef)(!1),V=(0,Lh.useRef)(()=>r?fp(i,c,l).sessionId:null);"function"==typeof V.current&&(V.current=V.current());const W=(0,Lh.useRef)(!1),B=(0,Lh.useRef)(!1),Z=(0,Lh.useRef)(!1),G=(0,Lh.useRef)(null),K=(0,Lh.useRef)(!0),J=(0,Lh.useRef)([]),X=(0,Lh.useRef)(C),Y=(0,Lh.useRef)(C),Q=Bh.MAX_RECONNECT_ATTEMPTS,ee=Bh.RECONNECT_DELAY,te=Bh.TYPING_TIMEOUT,ne=Bh.JWT_REFRESH_BUFFER_MS,se=Bh.JWT_REFRESH_MIN_DELAY_MS,re=Bh.JWT_PROACTIVE_REFRESH_COOLDOWN_MS,oe=Bh.AUTH_REFRESH_COOLDOWN_MS,ae=Bh.JWT_EXPIRED_BUFFER_MS,ie=Bh.JWT_PROACTIVE_REFRESH_DEFER_MS,ce=(0,Lh.useCallback)(e=>{V.current=e;try{localStorage.setItem(l,e)}catch(e){console.warn("[AI Chat] Failed to save session ID to localStorage:",e)}},[l]),le=(0,Lh.useCallback)(e=>{try{localStorage.setItem(c,e)}catch(e){console.warn("[AI Chat] Failed to save conversation ID to localStorage:",e)}},[c]),ue=(0,Lh.useCallback)(async()=>{if(N.current?.readyState!==WebSocket.OPEN&&N.current?.readyState!==WebSocket.CONNECTING&&!H.current){try{sessionStorage.removeItem(`${u}-connection-failed`)}catch(e){}H.current=!0,y(!0),P("connecting"),v(null);try{M.current||(M.current=await hp({configEndpoint:e,consumer:t}));let n=M.current;if(!n)throw new Error((0,Wh.__)("No configuration available","wp-module-ai-chat"));let r=!1;for(;n?.jarvis_jwt;){const s=Zh(n.jarvis_jwt);if(null==s)break;if(s>=Date.now()+ae)break;if(r)throw new Error((0,Wh.__)("Token expired, please refresh the page.","wp-module-ai-chat"));if(M.current=null,M.current=await hp({configEndpoint:e,consumer:t}),n=M.current,r=!0,!n)throw new Error((0,Wh.__)("No configuration available","wp-module-ai-chat"))}if(n.site_id){const e=Jh();e!==n.site_id&&((e=>{try{localStorage.setItem(Gh,e)}catch{}})(n.site_id),((e,t,n)=>{const s=Xh(e,n),r=Xh(t,n);try{for(const e of Object.values(Kh)){const t=`${s}-${e}`,n=`${r}-${e}`,o=localStorage.getItem(t);o&&!localStorage.getItem(n)&&localStorage.setItem(n,o),o&&localStorage.removeItem(t)}}catch{}})(e,n.site_id,t))}if(V.current||(V.current=qh()),n.jarvis_jwt){z.current&&(clearTimeout(z.current),z.current=null);const e=Zh(n.jarvis_jwt);if(null!=e){let t=e-ne;t=Math.max(t,Date.now()+se);const n=Date.now();if(!(null!=D.current&&t<D.current+re)){const e=Math.max(0,t-n),s=()=>{Z.current?z.current=setTimeout(s,ie):(z.current=null,D.current=Date.now(),M.current=null,q.current&&q.current(),U.current&&U.current())};z.current=setTimeout(s,e)}}}const o=tp(n,V.current,s),a=new WebSocket(o);N.current=a,a.onopen=()=>{H.current=!1,g(!0),y(!1),P("connected"),A(0),v(null),j.current=0,W.current=J.current&&J.current.length>0,B.current=!1,E("")};const i=function(e){const{isStoppedRef:t,hasUserMessageRef:n,typingTimeoutRef:s,typingTimeout:r,setIsTyping:o,setStatus:a,setCurrentResponse:i,setMessages:c,setConversationId:l,setError:u,saveSessionId:d,saveConversationId:h}=e;return function(p){if(!t.current||"session_established"===p.type)if("session_established"!==p.type){if("typing_start"===p.type)return o(!0),a(rp("typing_start")),void ip(s);if("typing_stop"===p.type)return o(!1),a(null),i(""),void ip(s);if("streaming_chunk"===p.type||"chunk"===p.type){if(t.current)return;const e=p.content||p.chunk||p.text||"";return void(e&&i(t=>{const i=t+e;return!n.current&&i.length<100&&op(i)?"":(o(!0),s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{o(!1),a(null),s.current=null},r),i)}))}if("structured_output"===p.type){const t=p.response_content?.content?.human_input_request;if(t&&"APPROVAL_REQUEST"===(t.input_type||t.inputType||"").toUpperCase()){if(p.conversation_id||p.conversationId){const e=p.conversation_id||p.conversationId;l(e),h(e)}return}const s=p.message||p.response_content?.message,r=ap(s,n.current);return void(r&&(i(e=>(e&&lp(c,e,"-streaming"),"")),lp(c,r),cp(e)))}if("tool_call"!==p.type){if("tool_result"!==p.type){if("message"===p.type||"complete"===p.type){let t=!1;if(i(e=>{if(e){const s=e.trim();if("No content provided"===s||"sales_requested"===s||"sales_requested"===s.toLowerCase())return"";if(!n.current&&e.length<150&&op(e))return"";c(t=>[...t,{id:`msg-${Date.now()}`,role:"assistant",type:"assistant",content:e,timestamp:new Date,animateTyping:!0}]),t=!0}return""}),!t){const e=p.message||p.response_content?.message,s=ap(e,n.current);s&&(lp(c,s),t=!0)}return void(t&&cp(e))}if("handoff_accept"!==p.type){if("handoff_request"===p.type){a(rp("handoff_request"));const t=p.message||p.response_content?.message,s=ap(t,n.current);return s?(lp(c,s),void cp(e)):void i("")}if("error"===p.type)return u(p.message||p.error||"An error occurred"),o(!1),a(null),void i("");if(p.message||p.response_content?.message){const t=p.message||p.response_content?.message,s=ap(t,n.current);if(!s)return void i("");lp(c,s),cp(e)}}else a(rp("handoff_accept"))}else if(a(rp("tool_result")),p.conversation_id||p.conversationId){const e=p.conversation_id||p.conversationId;l(e),h(e)}}else a(rp("tool_call"))}else p.session_id&&d(p.session_id)}}({isStoppedRef:B,hasUserMessageRef:W,typingTimeoutRef:G,typingTimeout:te,setIsTyping:$,setStatus:S,setCurrentResponse:E,setMessages:h,setConversationId:f,setError:v,saveSessionId:ce,saveConversationId:le});a.onmessage=e=>{try{const t=JSON.parse(e.data);i(t)}catch(e){console.error("[AI Chat] Error parsing WebSocket message:",e)}},a.onerror=()=>{H.current=!1,y(!1)},a.onclose=e=>{H.current=!1,g(!1),y(!1),$(!1),S(null),N.current===a&&(N.current=null);const t=4e3===e.code||4001===e.code,n=M.current?.jarvis_jwt,s=n?Zh(n):null,r=null!=s&&s<Date.now()+ae;if(t||r){const e=Date.now();(null==L.current||e-L.current>=oe)&&(M.current=null,j.current=0,L.current=e)}if(1e3!==e.code&&j.current<Q){j.current++,A(j.current),P("reconnecting");const e=ee*Math.pow(2,j.current-1);O.current=setTimeout(()=>{ue()},e)}else if(j.current>=Q){P("failed");try{sessionStorage.setItem(`${u}-connection-failed`,"1")}catch(e){}}else P("disconnected")}}catch(e){H.current=!1,"undefined"!=typeof console&&console.warn&&console.warn("[AI Chat] Connection failed:",e?.message||e),y(!1),P("failed");try{sessionStorage.setItem(`${u}-connection-failed`,"1")}catch(e){}}}},[e,t,s,u,ce,le,Q,ee,te,ne,se,re,oe,ae,ie]);(0,Lh.useEffect)(()=>{J.current=d},[d]),(0,Lh.useEffect)(()=>{X.current=C},[C]),(0,Lh.useEffect)(()=>{Z.current=b},[b]),(0,Lh.useEffect)(()=>()=>{O.current&&(clearTimeout(O.current),O.current=null),z.current&&(clearTimeout(z.current),z.current=null)},[]),(0,Lh.useEffect)(()=>{if("failed"!==C||"failed"===Y.current)return void(Y.current=C);Y.current=C;const e=(0,Wh.__)("Sorry, we couldn't connect. Please try again later or contact support.","wp-module-ai-chat");h(t=>{const n=t.length>0?t[t.length-1]:null,s=n&&("user"===n.role||"user"===n.type),r="function"==typeof o?o(s?n.content:""):e;return[...t,{id:`msg-${Date.now()}-fallback`,role:"assistant",type:"assistant",content:r,timestamp:new Date}]}),v(null),E(""),$(!1),S(null),G.current&&(clearTimeout(G.current),G.current=null)},[C,o]);const de=(0,Lh.useCallback)((e,t=null)=>{if(B.current=!1,W.current=!0,("failed"===X.current||j.current>=Q&&(!N.current||N.current.readyState!==WebSocket.OPEN))&&!t){const t={id:`msg-${Date.now()}`,role:"user",type:"user",content:e,timestamp:new Date,sessionId:V.current},n="function"==typeof o?o(e):(0,Wh.__)("Sorry, we couldn't connect. Please try again later or contact support.","wp-module-ai-chat");return h(e=>[...e,t,{id:`msg-${Date.now()}-fallback`,role:"assistant",type:"assistant",content:n,timestamp:new Date}]),v(null),E(""),$(!1),void S(null)}if(!N.current||N.current.readyState!==WebSocket.OPEN){if(!t){const t={id:`msg-${Date.now()}`,role:"user",type:"user",content:e,timestamp:new Date,sessionId:V.current};h(e=>[...e,t])}return void ue()}if(!t){const t={id:`msg-${Date.now()}`,role:"user",type:"user",content:e,timestamp:new Date,sessionId:V.current};h(e=>[...e,t]),E(""),$(!0),G.current&&clearTimeout(G.current),G.current=setTimeout(()=>{$(!1),S(null),G.current=null},te)}const n={type:"chat",message:e};t?n.conversationId=t:p&&(n.conversationId=p),N.current.send(JSON.stringify(n))},[p,ue,o,Q,te]),he=(0,Lh.useCallback)(e=>{if(!N.current||N.current.readyState!==WebSocket.OPEN)return void console.warn("[AI Chat] Cannot send system message - not connected");const t={type:"chat",message:e};p&&(t.conversationId=p),$(!0),E(""),G.current&&clearTimeout(G.current),G.current=setTimeout(()=>{$(!1),S(null),G.current=null},te),N.current.send(JSON.stringify(t))},[p,te]),pe=(0,Lh.useCallback)(()=>{O.current&&(clearTimeout(O.current),O.current=null),z.current&&(clearTimeout(z.current),z.current=null),G.current&&(clearTimeout(G.current),G.current=null),N.current&&(N.current.close(1e3,"User disconnected"),N.current=null),g(!1),y(!1),P("disconnected")},[]);(0,Lh.useEffect)(()=>{U.current=ue},[ue]),(0,Lh.useEffect)(()=>{q.current=pe},[pe]);const fe=(0,Lh.useCallback)(e=>{V.current=e??null},[]),me=(0,Lh.useCallback)(()=>V.current??null,[]),ge=(0,Lh.useCallback)((e,t,n)=>{if(Array.isArray(e)){const t=e.map(e=>({...e,timestamp:e.timestamp?new Date(e.timestamp):new Date,animateTyping:!1}));h(t)}if(f(t??null),V.current=n??null,v(null),$(!1),S(null),E(""),null!=n&&N.current?.readyState===WebSocket.OPEN){try{localStorage.setItem(l,n),null!=t&&localStorage.setItem(c,t)}catch(e){console.warn("[AI Chat] Failed to persist session for history load:",e)}pe(),ue()}},[ue,pe,l,c]),_e=(0,Lh.useCallback)(()=>{B.current=!0,$(!1),S(null),E(""),G.current&&(clearTimeout(G.current),G.current=null)},[]),ye=(0,Lh.useCallback)(()=>{I(null)},[]),we=(0,Lh.useCallback)(()=>{$(!1),S(null),G.current&&(clearTimeout(G.current),G.current=null)},[]),ve=(0,Lh.useCallback)(e=>{let t;if(null==e)t=(0,Wh.__)("No content provided.","wp-module-ai-chat");else if("object"==typeof e)try{t=JSON.stringify(e,null,2)}catch(n){console.warn("[useNfdAgentsWebSocket] Failed to stringify content object:",n),t=String(e)}else t=String(e);h(e=>[...e,{id:`msg-${Date.now()}`,role:"assistant",type:"assistant",content:t,timestamp:new Date}]),$(!1),S(null),G.current&&(clearTimeout(G.current),G.current=null)},[]),be=(0,Lh.useCallback)((e,t)=>{h(n=>n.map(n=>("function"==typeof e?e(n):n.id===e)?t(n):n))},[]),$e=(0,Lh.useCallback)(()=>{try{((e,t,n)=>{try{localStorage.removeItem(e),localStorage.removeItem(t),localStorage.removeItem(n)}catch(e){console.warn("[AI Chat] Failed to clear chat storage:",e)}})(i,c,l),h([]),f(null),I(null),$(!1),S(null),E(""),v(null),V.current=null,N.current&&(N.current.close(),N.current=null,g(!1)),W.current=!1,B.current=!1,G.current&&(clearTimeout(G.current),G.current=null),O.current&&(clearTimeout(O.current),O.current=null),z.current&&(clearTimeout(z.current),z.current=null),j.current=0}catch(e){console.warn("[AI Chat] Failed to clear chat history:",e)}},[i,c,l]),ke=(0,Lh.useCallback)(()=>{j.current=0,A(0),v(null),ue()},[ue]);return(0,Lh.useEffect)(()=>{const e=F.current;if(null===e)return F.current=n,void(n&&"failed"!==C&&!H.current&&(!N.current||N.current.readyState!==WebSocket.OPEN&&N.current.readyState!==WebSocket.CONNECTING)&&ue());e!==n&&(F.current=n,n?H.current||N.current&&(N.current.readyState===WebSocket.OPEN||N.current.readyState===WebSocket.CONNECTING)||ue():pe())},[n,C]),(0,Lh.useEffect)(()=>{if(K.current)return K.current=!1,void(d.length>0&&pp(d)&&mp(i,d));mp(i,d)},[d,i]),(0,Lh.useEffect)(()=>{((e,t)=>{try{t?localStorage.setItem(e,t):localStorage.removeItem(e)}catch(e){console.warn("[AI Chat] Failed to save conversation ID to localStorage:",e)}})(c,p)},[p,c]),{messages:d,setMessages:h,setConversationId:f,setSessionId:fe,loadConversation:ge,getSessionId:me,sendMessage:de,sendSystemMessage:he,isConnected:m,isConnecting:_,error:w,isTyping:b,status:k,currentResponse:x,approvalRequest:T,conversationId:p,clearApprovalRequest:ye,clearTyping:we,addAssistantMessage:ve,updateMessage:be,connect:ue,disconnect:pe,stopRequest:_e,clearChatHistory:$e,brandId:M.current?.brand_id||null,connectionState:C,retryAttempt:R,maxRetries:Q,manualRetry:ke}},_p=["Would","If","Like","And","But","Or","So","Maybe","Perhaps","Well","Yes","No","When","Where","How","Why","It","To","We","Do","Be","As","An","The","You","In","On","At","By","Is"],yp=new RegExp(`\\b(${_p.join("|")})(https?:\\/\\/)`,"gi"),wp=new RegExp(`^((${_p.join("|")})\\s+)+(.+)$`,"i"),vp=new RegExp(`\\/(${_p.join("|")})$`,"i"),bp=new RegExp(`(\\d)(${_p.join("|")})$`,"i"),$p=/^https?:\/\/[^\s<>"]+$/;function kp(e){return!(!e||"string"!=typeof e)&&[/^#{1,6}\s/m,/\*\*[^*]+\*\*/,/\*[^*]+\*/,/__[^_]+__/,/_[^_]+_/,/`[^`]+`/,/```[\s\S]*?```/,/^\s*[-*+]\s/m,/^\s*\d+\.\s/m,/\[([^\]]+)\]\(([^)]+)\)/].some(t=>t.test(e))}function Sp(e){if(!e||"string"!=typeof e)return"";let t=e;t=t.replace(/&(?![\w#]+;)/g,"&").replace(/<(?![a-zA-Z/])/g,"<").replace(/(?<![a-zA-Z"])>/g,">"),t=t.replace(/```(\w*)\n?([\s\S]*?)```/g,(e,t,n)=>`<pre><code class="language-${t||"plaintext"}">${n.trim().replace(/</g,"<").replace(/>/g,">")}</code></pre>`),t=t.replace(/`([^`]+)`/g,'<code class="inline-code">$1</code>'),t=t.replace(/^######\s+(.+)$/gm,'<h6 class="chat-h6">$1</h6>'),t=t.replace(/^#####\s+(.+)$/gm,'<h5 class="chat-h5">$1</h5>'),t=t.replace(/^####\s+(.+)$/gm,'<h4 class="chat-h4">$1</h4>'),t=t.replace(/^###\s+(.+)$/gm,'<h3 class="chat-h3">$1</h3>'),t=t.replace(/^##\s+(.+)$/gm,'<h2 class="chat-h2">$1</h2>'),t=t.replace(/^#\s+(.+)$/gm,'<h1 class="chat-h1">$1</h1>'),t=t.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),t=t.replace(/__([^_]+)__/g,"<strong>$1</strong>"),t=t.replace(/(?<![*_])\*(?!\*)([^*\n]+)(?<!\*)\*(?!\*)/g,"<em>$1</em>"),t=t.replace(/(?<![_*])_(?!_)([^_\n]+)(?<!_)_(?!_)/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(e,t,n)=>{const s=t.trim().match(wp),r=s?s[3].trim():"",o=r&&($p.test(r)||/^https?:\/\//.test(r)),a=n.replace(/"/g,""");return s&&o?`${s[1]}<a href="${a}" target="_blank" rel="noopener noreferrer">${r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}</a>`:`<a href="${a}" target="_blank" rel="noopener noreferrer">${t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}</a>`}),t=t.replace(/^(\s*)[-*+]\s+(.+)$/gm,(e,t,n)=>`<li class="chat-li" data-level="${Math.floor(t.length/2)}">${n}</li>`),t=t.replace(/((?:<li[^>]*>.*?<\/li>\s*)+)/g,e=>`<ul class="chat-ul">${e.replace(/(<\/li>)\s+(<li)/g,"$1$2")}</ul>`),t=t.replace(/^(\s*)\d+\.\s+(.+)$/gm,(e,t,n)=>`<oli class="chat-oli" data-level="${Math.floor(t.length/2)}">${n}</oli>`),t=t.replace(/((?:<oli[^>]*>.*?<\/oli>\s*)+)/g,e=>`<ol class="chat-ol">${e.replace(/(<\/oli>)\s+(<oli)/g,"$1$2").replace(/<\/?oli/g,e=>e.replace("oli","li"))}</ol>`),t=t.replace(/^---+$/gm,'<hr class="chat-hr" />'),t=t.replace(/^>\s+(.+)$/gm,'<blockquote class="chat-blockquote">$1</blockquote>');const n=t.split(/\n\n+/);return t=n.map(e=>{const t=e.trim();return t.startsWith("<h")||t.startsWith("<ul")||t.startsWith("<ol")||t.startsWith("<pre")||t.startsWith("<blockquote")||t.startsWith("<hr")||t.startsWith("<p")?t:t?`<p class="chat-p">${t}</p>`:""}).filter(Boolean).join(""),t=t.replace(/<p([^>]*)>([\s\S]*?)<\/p>/g,(e,t,n)=>`<p${t}>${n.trim().replace(/\n/g,"<br>")}</p>`),t=t.replace(/<br\s*\/?>\s*(<\/?(ul|ol|li|p|h[1-6]|pre|blockquote|hr))/gi,"$1"),t=t.replace(/(<\/(ul|ol|li|p|h[1-6]|pre|blockquote)>)\s*<br\s*\/?>/gi,"$1"),t=t.replace(/<p[^>]*>\s*<\/p>/g,""),t=t.replace(/(<br\s*\/?>){2,}/g,"<br>"),t=function(e){return e&&"string"==typeof e?e.replace(/>([^<]*)</g,(e,t)=>">"+xp(t)+"<"):""}(t),t}function xp(e){return e&&"string"==typeof e?e.replace(yp,"$1 $2").replace(/(^|[\s(\["'])(https?:\/\/[^\s<>"]*(?:\n[^\s<>"]*)*)/g,(e,t,n)=>{let s=n.replace(/\s+/g,"").trim().replace(/[.,;:!?)\]]+$/,""),r="";const o=s.match(vp);o&&(r=o[1],s=s.replace(vp,""));const a=s.match(bp);return a&&(r=a[2],s=s.replace(bp,"$1")),s?`${t??""}<a href="${s.replace(/"/g,""")}" target="_blank" rel="noopener noreferrer">${s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}</a>${r?" "+r:""}`:e}):""}const{entries:Ep,setPrototypeOf:Tp,isFrozen:Ip,getPrototypeOf:Cp,getOwnPropertyDescriptor:Pp}=Object;let{freeze:Rp,seal:Ap,create:Np}=Object,{apply:Op,construct:jp}="undefined"!=typeof Reflect&&Reflect;Rp||(Rp=function(e){return e}),Ap||(Ap=function(e){return e}),Op||(Op=function(e,t){for(var n=arguments.length,s=new Array(n>2?n-2:0),r=2;r<n;r++)s[r-2]=arguments[r];return e.apply(t,s)}),jp||(jp=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return new e(...n)});const Mp=Xp(Array.prototype.forEach),zp=Xp(Array.prototype.lastIndexOf),Dp=Xp(Array.prototype.pop),Lp=Xp(Array.prototype.push),Up=Xp(Array.prototype.splice),qp=Xp(String.prototype.toLowerCase),Fp=Xp(String.prototype.toString),Hp=Xp(String.prototype.match),Vp=Xp(String.prototype.replace),Wp=Xp(String.prototype.indexOf),Bp=Xp(String.prototype.trim),Zp=Xp(Object.prototype.hasOwnProperty),Gp=Xp(RegExp.prototype.test),Kp=(Jp=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return jp(Jp,t)});var Jp;function Xp(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,s=new Array(n>1?n-1:0),r=1;r<n;r++)s[r-1]=arguments[r];return Op(e,t,s)}}function Yp(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:qp;Tp&&Tp(e,null);let s=t.length;for(;s--;){let r=t[s];if("string"==typeof r){const e=n(r);e!==r&&(Ip(t)||(t[s]=e),r=e)}e[r]=!0}return e}function Qp(e){for(let t=0;t<e.length;t++)Zp(e,t)||(e[t]=null);return e}function ef(e){const t=Np(null);for(const[n,s]of Ep(e))Zp(e,n)&&(Array.isArray(s)?t[n]=Qp(s):s&&"object"==typeof s&&s.constructor===Object?t[n]=ef(s):t[n]=s);return t}function tf(e,t){for(;null!==e;){const n=Pp(e,t);if(n){if(n.get)return Xp(n.get);if("function"==typeof n.value)return Xp(n.value)}e=Cp(e)}return function(){return null}}const nf=Rp(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),sf=Rp(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),rf=Rp(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),of=Rp(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),af=Rp(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),cf=Rp(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),lf=Rp(["#text"]),uf=Rp(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),df=Rp(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),hf=Rp(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),pf=Rp(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),ff=Ap(/\{\{[\w\W]*|[\w\W]*\}\}/gm),mf=Ap(/<%[\w\W]*|[\w\W]*%>/gm),gf=Ap(/\$\{[\w\W]*/gm),_f=Ap(/^data-[\-\w.\u00B7-\uFFFF]+$/),yf=Ap(/^aria-[\-\w]+$/),wf=Ap(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),vf=Ap(/^(?:\w+script|data):/i),bf=Ap(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),$f=Ap(/^html$/i),kf=Ap(/^[a-z][.\w]*(-[.\w]+)+$/i);var Sf=Object.freeze({__proto__:null,ARIA_ATTR:yf,ATTR_WHITESPACE:bf,CUSTOM_ELEMENT:kf,DATA_ATTR:_f,DOCTYPE_NAME:$f,ERB_EXPR:mf,IS_ALLOWED_URI:wf,IS_SCRIPT_OR_DATA:vf,MUSTACHE_EXPR:ff,TMPLIT_EXPR:gf});const xf=function(){return"undefined"==typeof window?null:window};var Ef=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:xf();const n=t=>e(t);if(n.version="3.3.1",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let{document:s}=t;const r=s,o=r.currentScript,{DocumentFragment:a,HTMLTemplateElement:i,Node:c,Element:l,NodeFilter:u,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:h,DOMParser:p,trustedTypes:f}=t,m=l.prototype,g=tf(m,"cloneNode"),_=tf(m,"remove"),y=tf(m,"nextSibling"),w=tf(m,"childNodes"),v=tf(m,"parentNode");if("function"==typeof i){const e=s.createElement("template");e.content&&e.content.ownerDocument&&(s=e.content.ownerDocument)}let b,$="";const{implementation:k,createNodeIterator:S,createDocumentFragment:x,getElementsByTagName:E}=s,{importNode:T}=r;let I={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof Ep&&"function"==typeof v&&k&&void 0!==k.createHTMLDocument;const{MUSTACHE_EXPR:C,ERB_EXPR:P,TMPLIT_EXPR:R,DATA_ATTR:A,ARIA_ATTR:N,IS_SCRIPT_OR_DATA:O,ATTR_WHITESPACE:j,CUSTOM_ELEMENT:M}=Sf;let{IS_ALLOWED_URI:z}=Sf,D=null;const L=Yp({},[...nf,...sf,...rf,...af,...lf]);let U=null;const q=Yp({},[...uf,...df,...hf,...pf]);let F=Object.seal(Np(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),H=null,V=null;const W=Object.seal(Np(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let B=!0,Z=!0,G=!1,K=!0,J=!1,X=!0,Y=!1,Q=!1,ee=!1,te=!1,ne=!1,se=!1,re=!0,oe=!1,ae=!0,ie=!1,ce={},le=null;const ue=Yp({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let de=null;const he=Yp({},["audio","video","img","source","image","track"]);let pe=null;const fe=Yp({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),me="http://www.w3.org/1998/Math/MathML",ge="http://www.w3.org/2000/svg",_e="http://www.w3.org/1999/xhtml";let ye=_e,we=!1,ve=null;const be=Yp({},[me,ge,_e],Fp);let $e=Yp({},["mi","mo","mn","ms","mtext"]),ke=Yp({},["annotation-xml"]);const Se=Yp({},["title","style","font","a","script"]);let xe=null;const Ee=["application/xhtml+xml","text/html"];let Te=null,Ie=null;const Ce=s.createElement("form"),Pe=function(e){return e instanceof RegExp||e instanceof Function},Re=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!Ie||Ie!==e){if(e&&"object"==typeof e||(e={}),e=ef(e),xe=-1===Ee.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Te="application/xhtml+xml"===xe?Fp:qp,D=Zp(e,"ALLOWED_TAGS")?Yp({},e.ALLOWED_TAGS,Te):L,U=Zp(e,"ALLOWED_ATTR")?Yp({},e.ALLOWED_ATTR,Te):q,ve=Zp(e,"ALLOWED_NAMESPACES")?Yp({},e.ALLOWED_NAMESPACES,Fp):be,pe=Zp(e,"ADD_URI_SAFE_ATTR")?Yp(ef(fe),e.ADD_URI_SAFE_ATTR,Te):fe,de=Zp(e,"ADD_DATA_URI_TAGS")?Yp(ef(he),e.ADD_DATA_URI_TAGS,Te):he,le=Zp(e,"FORBID_CONTENTS")?Yp({},e.FORBID_CONTENTS,Te):ue,H=Zp(e,"FORBID_TAGS")?Yp({},e.FORBID_TAGS,Te):ef({}),V=Zp(e,"FORBID_ATTR")?Yp({},e.FORBID_ATTR,Te):ef({}),ce=!!Zp(e,"USE_PROFILES")&&e.USE_PROFILES,B=!1!==e.ALLOW_ARIA_ATTR,Z=!1!==e.ALLOW_DATA_ATTR,G=e.ALLOW_UNKNOWN_PROTOCOLS||!1,K=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,J=e.SAFE_FOR_TEMPLATES||!1,X=!1!==e.SAFE_FOR_XML,Y=e.WHOLE_DOCUMENT||!1,te=e.RETURN_DOM||!1,ne=e.RETURN_DOM_FRAGMENT||!1,se=e.RETURN_TRUSTED_TYPE||!1,ee=e.FORCE_BODY||!1,re=!1!==e.SANITIZE_DOM,oe=e.SANITIZE_NAMED_PROPS||!1,ae=!1!==e.KEEP_CONTENT,ie=e.IN_PLACE||!1,z=e.ALLOWED_URI_REGEXP||wf,ye=e.NAMESPACE||_e,$e=e.MATHML_TEXT_INTEGRATION_POINTS||$e,ke=e.HTML_INTEGRATION_POINTS||ke,F=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Pe(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(F.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Pe(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(F.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(F.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),J&&(Z=!1),ne&&(te=!0),ce&&(D=Yp({},lf),U=[],!0===ce.html&&(Yp(D,nf),Yp(U,uf)),!0===ce.svg&&(Yp(D,sf),Yp(U,df),Yp(U,pf)),!0===ce.svgFilters&&(Yp(D,rf),Yp(U,df),Yp(U,pf)),!0===ce.mathMl&&(Yp(D,af),Yp(U,hf),Yp(U,pf))),e.ADD_TAGS&&("function"==typeof e.ADD_TAGS?W.tagCheck=e.ADD_TAGS:(D===L&&(D=ef(D)),Yp(D,e.ADD_TAGS,Te))),e.ADD_ATTR&&("function"==typeof e.ADD_ATTR?W.attributeCheck=e.ADD_ATTR:(U===q&&(U=ef(U)),Yp(U,e.ADD_ATTR,Te))),e.ADD_URI_SAFE_ATTR&&Yp(pe,e.ADD_URI_SAFE_ATTR,Te),e.FORBID_CONTENTS&&(le===ue&&(le=ef(le)),Yp(le,e.FORBID_CONTENTS,Te)),e.ADD_FORBID_CONTENTS&&(le===ue&&(le=ef(le)),Yp(le,e.ADD_FORBID_CONTENTS,Te)),ae&&(D["#text"]=!0),Y&&Yp(D,["html","head","body"]),D.table&&(Yp(D,["tbody"]),delete H.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Kp('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Kp('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');b=e.TRUSTED_TYPES_POLICY,$=b.createHTML("")}else void 0===b&&(b=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const s="data-tt-policy-suffix";t&&t.hasAttribute(s)&&(n=t.getAttribute(s));const r="dompurify"+(n?"#"+n:"");try{return e.createPolicy(r,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+r+" could not be created."),null}}(f,o)),null!==b&&"string"==typeof $&&($=b.createHTML(""));Rp&&Rp(e),Ie=e}},Ae=Yp({},[...sf,...rf,...of]),Ne=Yp({},[...af,...cf]),Oe=function(e){Lp(n.removed,{element:e});try{v(e).removeChild(e)}catch(t){_(e)}},je=function(e,t){try{Lp(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){Lp(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(te||ne)try{Oe(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Me=function(e){let t=null,n=null;if(ee)e="<remove></remove>"+e;else{const t=Hp(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===xe&&ye===_e&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const r=b?b.createHTML(e):e;if(ye===_e)try{t=(new p).parseFromString(r,xe)}catch(e){}if(!t||!t.documentElement){t=k.createDocument(ye,"template",null);try{t.documentElement.innerHTML=we?$:r}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(s.createTextNode(n),o.childNodes[0]||null),ye===_e?E.call(t,Y?"html":"body")[0]:Y?t.documentElement:o},ze=function(e){return S.call(e.ownerDocument||e,e,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},De=function(e){return e instanceof h&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof d)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},Le=function(e){return"function"==typeof c&&e instanceof c};function Ue(e,t,s){Mp(e,e=>{e.call(n,t,s,Ie)})}const qe=function(e){let t=null;if(Ue(I.beforeSanitizeElements,e,null),De(e))return Oe(e),!0;const s=Te(e.nodeName);if(Ue(I.uponSanitizeElement,e,{tagName:s,allowedTags:D}),X&&e.hasChildNodes()&&!Le(e.firstElementChild)&&Gp(/<[/\w!]/g,e.innerHTML)&&Gp(/<[/\w!]/g,e.textContent))return Oe(e),!0;if(7===e.nodeType)return Oe(e),!0;if(X&&8===e.nodeType&&Gp(/<[/\w]/g,e.data))return Oe(e),!0;if(!(W.tagCheck instanceof Function&&W.tagCheck(s))&&(!D[s]||H[s])){if(!H[s]&&He(s)){if(F.tagNameCheck instanceof RegExp&&Gp(F.tagNameCheck,s))return!1;if(F.tagNameCheck instanceof Function&&F.tagNameCheck(s))return!1}if(ae&&!le[s]){const t=v(e)||e.parentNode,n=w(e)||e.childNodes;if(n&&t)for(let s=n.length-1;s>=0;--s){const r=g(n[s],!0);r.__removalCount=(e.__removalCount||0)+1,t.insertBefore(r,y(e))}}return Oe(e),!0}return e instanceof l&&!function(e){let t=v(e);t&&t.tagName||(t={namespaceURI:ye,tagName:"template"});const n=qp(e.tagName),s=qp(t.tagName);return!!ve[e.namespaceURI]&&(e.namespaceURI===ge?t.namespaceURI===_e?"svg"===n:t.namespaceURI===me?"svg"===n&&("annotation-xml"===s||$e[s]):Boolean(Ae[n]):e.namespaceURI===me?t.namespaceURI===_e?"math"===n:t.namespaceURI===ge?"math"===n&&ke[s]:Boolean(Ne[n]):e.namespaceURI===_e?!(t.namespaceURI===ge&&!ke[s])&&!(t.namespaceURI===me&&!$e[s])&&!Ne[n]&&(Se[n]||!Ae[n]):!("application/xhtml+xml"!==xe||!ve[e.namespaceURI]))}(e)?(Oe(e),!0):"noscript"!==s&&"noembed"!==s&&"noframes"!==s||!Gp(/<\/no(script|embed|frames)/i,e.innerHTML)?(J&&3===e.nodeType&&(t=e.textContent,Mp([C,P,R],e=>{t=Vp(t,e," ")}),e.textContent!==t&&(Lp(n.removed,{element:e.cloneNode()}),e.textContent=t)),Ue(I.afterSanitizeElements,e,null),!1):(Oe(e),!0)},Fe=function(e,t,n){if(re&&("id"===t||"name"===t)&&(n in s||n in Ce))return!1;if(Z&&!V[t]&&Gp(A,t));else if(B&&Gp(N,t));else if(W.attributeCheck instanceof Function&&W.attributeCheck(t,e));else if(!U[t]||V[t]){if(!(He(e)&&(F.tagNameCheck instanceof RegExp&&Gp(F.tagNameCheck,e)||F.tagNameCheck instanceof Function&&F.tagNameCheck(e))&&(F.attributeNameCheck instanceof RegExp&&Gp(F.attributeNameCheck,t)||F.attributeNameCheck instanceof Function&&F.attributeNameCheck(t,e))||"is"===t&&F.allowCustomizedBuiltInElements&&(F.tagNameCheck instanceof RegExp&&Gp(F.tagNameCheck,n)||F.tagNameCheck instanceof Function&&F.tagNameCheck(n))))return!1}else if(pe[t]);else if(Gp(z,Vp(n,j,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Wp(n,"data:")||!de[e])if(G&&!Gp(O,Vp(n,j,"")));else if(n)return!1;return!0},He=function(e){return"annotation-xml"!==e&&Hp(e,M)},Ve=function(e){Ue(I.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||De(e))return;const s={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:U,forceKeepAttr:void 0};let r=t.length;for(;r--;){const o=t[r],{name:a,namespaceURI:i,value:c}=o,l=Te(a),u=c;let d="value"===a?u:Bp(u);if(s.attrName=l,s.attrValue=d,s.keepAttr=!0,s.forceKeepAttr=void 0,Ue(I.uponSanitizeAttribute,e,s),d=s.attrValue,!oe||"id"!==l&&"name"!==l||(je(a,e),d="user-content-"+d),X&&Gp(/((--!?|])>)|<\/(style|title|textarea)/i,d)){je(a,e);continue}if("attributename"===l&&Hp(d,"href")){je(a,e);continue}if(s.forceKeepAttr)continue;if(!s.keepAttr){je(a,e);continue}if(!K&&Gp(/\/>/i,d)){je(a,e);continue}J&&Mp([C,P,R],e=>{d=Vp(d,e," ")});const h=Te(e.nodeName);if(Fe(h,l,d)){if(b&&"object"==typeof f&&"function"==typeof f.getAttributeType)if(i);else switch(f.getAttributeType(h,l)){case"TrustedHTML":d=b.createHTML(d);break;case"TrustedScriptURL":d=b.createScriptURL(d)}if(d!==u)try{i?e.setAttributeNS(i,a,d):e.setAttribute(a,d),De(e)?Oe(e):Dp(n.removed)}catch(t){je(a,e)}}else je(a,e)}Ue(I.afterSanitizeAttributes,e,null)},We=function e(t){let n=null;const s=ze(t);for(Ue(I.beforeSanitizeShadowDOM,t,null);n=s.nextNode();)Ue(I.uponSanitizeShadowNode,n,null),qe(n),Ve(n),n.content instanceof a&&e(n.content);Ue(I.afterSanitizeShadowDOM,t,null)};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=null,o=null,i=null,l=null;if(we=!e,we&&(e="\x3c!--\x3e"),"string"!=typeof e&&!Le(e)){if("function"!=typeof e.toString)throw Kp("toString is not a function");if("string"!=typeof(e=e.toString()))throw Kp("dirty is not a string, aborting")}if(!n.isSupported)return e;if(Q||Re(t),n.removed=[],"string"==typeof e&&(ie=!1),ie){if(e.nodeName){const t=Te(e.nodeName);if(!D[t]||H[t])throw Kp("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof c)s=Me("\x3c!----\x3e"),o=s.ownerDocument.importNode(e,!0),1===o.nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?s=o:s.appendChild(o);else{if(!te&&!J&&!Y&&-1===e.indexOf("<"))return b&&se?b.createHTML(e):e;if(s=Me(e),!s)return te?null:se?$:""}s&&ee&&Oe(s.firstChild);const u=ze(ie?e:s);for(;i=u.nextNode();)qe(i),Ve(i),i.content instanceof a&&We(i.content);if(ie)return e;if(te){if(ne)for(l=x.call(s.ownerDocument);s.firstChild;)l.appendChild(s.firstChild);else l=s;return(U.shadowroot||U.shadowrootmode)&&(l=T.call(r,l,!0)),l}let d=Y?s.outerHTML:s.innerHTML;return Y&&D["!doctype"]&&s.ownerDocument&&s.ownerDocument.doctype&&s.ownerDocument.doctype.name&&Gp($f,s.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+s.ownerDocument.doctype.name+">\n"+d),J&&Mp([C,P,R],e=>{d=Vp(d,e," ")}),b&&se?b.createHTML(d):d},n.setConfig=function(){Re(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Q=!0},n.clearConfig=function(){Ie=null,Q=!1},n.isValidAttribute=function(e,t,n){Ie||Re({});const s=Te(e),r=Te(t);return Fe(s,r,n)},n.addHook=function(e,t){"function"==typeof t&&Lp(I[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=zp(I[e],t);return-1===n?void 0:Up(I[e],n,1)[0]}return Dp(I[e])},n.removeHooks=function(e){I[e]=[]},n.removeAllHooks=function(){I={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();const Tf=e=>Ef.sanitize(e,{ALLOWED_TAGS:["section","div","h1","h2","h3","h4","h5","h6","p","span","strong","em","b","i","u","s","mark","small","sub","sup","a","br","ul","ol","li","dl","dt","dd","blockquote","code","pre","table","thead","tbody","tr","th","td","hr","address","time"],ALLOWED_ATTR:["style","class","id","href","datetime","target","rel"],ALLOW_DATA_ATTR:!1,FORBID_TAGS:["script","object","embed","iframe","form","fieldset","legend","label","input","textarea","select","option","button","details","summary","progress","meter"],FORBID_ATTR:["onerror","onload","onclick","onmouseover","onfocus","onblur"]}),If=e=>/<[a-z][\s\S]*>/i.test(e),Cf={MAX_HEIGHT:200,FOCUS_DELAY:100,STOP_DEBOUNCE:500};var Pf=n(6942),Rf=n.n(Pf);const Af=window.React,Nf=(...e)=>e.filter((e,t,n)=>Boolean(e)&&""!==e.trim()&&n.indexOf(e)===t).join(" ").trim();var Of={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const jf=(0,Af.forwardRef)(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:s,className:r="",children:o,iconNode:a,...i},c)=>(0,Af.createElement)("svg",{ref:c,...Of,width:t,height:t,stroke:e,strokeWidth:s?24*Number(n)/Number(t):n,className:Nf("lucide",r),...i},[...a.map(([e,t])=>(0,Af.createElement)(e,t)),...Array.isArray(o)?o:[o]])),Mf=(e,t)=>{const n=(0,Af.forwardRef)(({className:n,...s},r)=>{return(0,Af.createElement)(jf,{ref:r,iconNode:t,className:Nf(`lucide-${o=e,o.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,n),...s});var o});return n.displayName=`${e}`,n},zf=Mf("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]),Df=Mf("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]),Lf=Mf("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]),Uf=Mf("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);function qf(e){const t={"nfd-agents/get-global-styles":{title:(0,Wh.__)("Reading Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Fetching current color palette and typography settings","wp-module-ai-chat")},"nfd-agents/update-global-palette":{title:(0,Wh.__)("Updating Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Applying new colors to global styles","wp-module-ai-chat")},"newfold-agents/get-global-styles":{title:(0,Wh.__)("Reading Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Fetching current color palette and typography settings","wp-module-ai-chat")},"newfold-agents/update-global-palette":{title:(0,Wh.__)("Updating Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Applying new colors to global styles","wp-module-ai-chat")},"blu/get-global-styles":{title:(0,Wh.__)("Reading Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Fetching current color palette and typography settings","wp-module-ai-chat")},"blu/update-global-palette":{title:(0,Wh.__)("Updating Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Applying new colors to global styles","wp-module-ai-chat")},"blu-get-global-styles":{title:(0,Wh.__)("Reading Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Fetching current color palette and typography settings","wp-module-ai-chat")},"blu/get-active-global-styles":{title:(0,Wh.__)("Reading Active Styles","wp-module-ai-chat"),description:(0,Wh.__)("Fetching active global styles","wp-module-ai-chat")},"blu-get-active-global-styles":{title:(0,Wh.__)("Reading Active Styles","wp-module-ai-chat"),description:(0,Wh.__)("Fetching active global styles","wp-module-ai-chat")},"blu/get-active-global-styles-id":{title:(0,Wh.__)("Getting Styles ID","wp-module-ai-chat"),description:(0,Wh.__)("Fetching active styles ID","wp-module-ai-chat")},"blu-get-active-global-styles-id":{title:(0,Wh.__)("Getting Styles ID","wp-module-ai-chat"),description:(0,Wh.__)("Fetching active styles ID","wp-module-ai-chat")},"blu/update-global-styles":{title:(0,Wh.__)("Updating Site Styles","wp-module-ai-chat"),description:(0,Wh.__)("Applying new styles to global styles","wp-module-ai-chat")},"blu-update-global-styles":{title:(0,Wh.__)("Updating Site Styles","wp-module-ai-chat"),description:(0,Wh.__)("Applying new styles to global styles","wp-module-ai-chat")},"blu-update-global-palette":{title:(0,Wh.__)("Updating Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Applying new colors to global styles","wp-module-ai-chat")},"blu/edit-block":{title:(0,Wh.__)("Editing Block Content","wp-module-ai-chat"),description:(0,Wh.__)("Editing block content","wp-module-ai-chat")},"blu-edit-block":{title:(0,Wh.__)("Editing Block Content","wp-module-ai-chat"),description:(0,Wh.__)("Editing block content","wp-module-ai-chat")},"blu/add-section":{title:(0,Wh.__)("Adding New Section","wp-module-ai-chat"),description:(0,Wh.__)("Adding new section","wp-module-ai-chat")},"blu-add-section":{title:(0,Wh.__)("Adding New Section","wp-module-ai-chat"),description:(0,Wh.__)("Adding new section","wp-module-ai-chat")},"blu/delete-block":{title:(0,Wh.__)("Removing Block","wp-module-ai-chat"),description:(0,Wh.__)("Removing block","wp-module-ai-chat")},"blu-delete-block":{title:(0,Wh.__)("Removing Block","wp-module-ai-chat"),description:(0,Wh.__)("Removing block","wp-module-ai-chat")},"blu/move-block":{title:(0,Wh.__)("Moving Block","wp-module-ai-chat"),description:(0,Wh.__)("Moving block","wp-module-ai-chat")},"blu-move-block":{title:(0,Wh.__)("Moving Block","wp-module-ai-chat"),description:(0,Wh.__)("Moving block","wp-module-ai-chat")},"mcp-adapter-discover-abilities":{title:(0,Wh.__)("Discovering Actions","wp-module-ai-chat"),description:(0,Wh.__)("Finding available WordPress abilities","wp-module-ai-chat")},"mcp-adapter-get-ability-info":{title:(0,Wh.__)("Getting Ability Info","wp-module-ai-chat"),description:(0,Wh.__)("Fetching ability details","wp-module-ai-chat")},"mcp-adapter-execute-ability":{title:(0,Wh.__)("Executing Action","wp-module-ai-chat"),description:(0,Wh.__)("Running WordPress ability","wp-module-ai-chat")}};return t[e]?t[e]:"preparing-changes"===e?{title:(0,Wh.__)("Preparing changes","wp-module-ai-chat"),description:(0,Wh.__)("Building block markup","wp-module-ai-chat")}:{title:e?.replace(/[-_\/]/g," ").replace(/\b\w/g,e=>e.toUpperCase())||(0,Wh.__)("Executing","wp-module-ai-chat"),description:(0,Wh.__)("Running action","wp-module-ai-chat")}}function Ff(e,t={}){if("mcp-adapter-execute-ability"===e){const e=t?.ability_name||"unknown",n=qf(e);let s=null;if(("nfd-agents/update-global-palette"===e||"newfold-agents/update-global-palette"===e||"blu/update-global-palette"===e||"blu-update-global-palette"===e||"blu/update-global-styles"===e||"blu-update-global-styles"===e)&&t?.parameters?.colors){const e=t.parameters.colors.length;s=`${e} color${1!==e?"s":""}`}return{...n,params:s}}return qf(e)}const Hf=window.ReactJSXRuntime,Vf=({tool:e,isError:t,result:n})=>{const s=Ff(e.name,e.arguments),r=((e,t)=>{if(!e||e.isError)return n=e?.error,null==n?null:"string"==typeof n?n:"number"==typeof n||"boolean"==typeof n?String(n):null;var n;try{let n=e.result;if(Array.isArray(n)&&n.length>0&&n[0].text?n=JSON.parse(n[0].text):"string"==typeof n&&(n=JSON.parse(n)),!n||"object"!=typeof n)return null;if(t?.includes("update")){if(n.updatedColors&&Array.isArray(n.updatedColors)){const e=n.updatedColors;return e.length<=3?e.map(e=>`${e.name||e.slug}: ${e.color}`).join(", "):`${e.length} colors updated`}if(n.message&&"string"==typeof n.message)return n.message}if(t?.includes("edit-block")||t?.includes("edit_block"))return n.message&&"string"==typeof n.message?n.message:n.success?"Block updated":"Update failed";if(t?.includes("add-section")||t?.includes("add_section"))return n.message&&"string"==typeof n.message?n.message:n.success?"Section added":"Add failed";if(t?.includes("delete-block")||t?.includes("delete_block"))return n.message&&"string"==typeof n.message?n.message:n.success?"Block removed":"Delete failed";if(t?.includes("move-block")||t?.includes("move_block"))return n.message&&"string"==typeof n.message?n.message:n.success?"Block moved":"Move failed";if(t?.includes("get")||t?.includes("read")){if(n.color?.palette){const e=n.color.palette,t=e.custom?.length||0,s=e.theme?.length||0;if(t||s)return`Found ${t+s} colors`}if(n.typography){const e=n.typography.fontFamilies?.length||0,t=n.typography.fontSizes?.length||0,s=[];if(e&&s.push(`${e} font families`),t&&s.push(`${t} sizes`),s.length)return s.join(", ")}if(n.message&&"string"==typeof n.message)return n.message}return n.id&&t?.includes("id")?`ID: ${n.id}`:null}catch{return null}})(n,e.name);return(0,Hf.jsxs)("div",{className:Rf()("nfd-ai-chat-tool-execution__item",{"nfd-ai-chat-tool-execution__item--complete":!t,"nfd-ai-chat-tool-execution__item--error":t}),children:[(0,Hf.jsxs)("div",{className:"nfd-ai-chat-tool-execution__item-header",children:[t?(0,Hf.jsx)(zf,{className:"nfd-ai-chat-tool-execution__icon nfd-ai-chat-tool-execution__icon--error",size:12}):(0,Hf.jsx)(Df,{className:"nfd-ai-chat-tool-execution__icon nfd-ai-chat-tool-execution__icon--success",size:12}),(0,Hf.jsx)("span",{className:"nfd-ai-chat-tool-execution__item-title",children:s.title}),s.params&&(0,Hf.jsx)("span",{className:"nfd-ai-chat-tool-execution__item-params",children:s.params})]}),r&&(0,Hf.jsx)("div",{className:"nfd-ai-chat-tool-execution__item-summary",children:r})]})},Wf=({executedTools:e=[],toolResults:t=[]})=>{const[n,s]=(0,Lh.useState)(!1);if(!e||0===e.length)return null;const r=new Map;t&&Array.isArray(t)&&t.forEach(e=>{e.id&&r.set(e.id,e)});const o=e.some(e=>e.isError),a=e.length;return(0,Hf.jsxs)("div",{className:Rf()("nfd-ai-chat-tool-execution",{"nfd-ai-chat-tool-execution--collapsed":!n}),children:[(0,Hf.jsxs)("button",{type:"button",className:"nfd-ai-chat-tool-execution__header",onClick:()=>s(!n),"aria-expanded":n?"true":"false",children:[n?(0,Hf.jsx)(Lf,{className:"nfd-ai-chat-tool-execution__chevron",size:12}):(0,Hf.jsx)(Uf,{className:"nfd-ai-chat-tool-execution__chevron",size:12}),(0,Hf.jsx)("span",{children:o?(0,Wh.__)("Some actions failed","wp-module-ai-chat"):(0,Wh.__)("Actions completed","wp-module-ai-chat")}),(0,Hf.jsxs)("span",{className:"nfd-ai-chat-tool-execution__header-count",children:["(",a,")"]})]}),n&&(0,Hf.jsx)("div",{className:"nfd-ai-chat-tool-execution__list",children:e.map((e,t)=>(0,Hf.jsx)(Vf,{tool:e,isError:e.isError,result:r.get(e.id)},e.id||`tool-${t}`))})]})},Bf=({message:e,type:t="assistant",animateTyping:n=!1,onContentGrow:s,executedTools:r=[],toolResults:o=[]})=>{const a="approval_request"===t?"assistant":t,i="user"===a,c=(e||"").length,[l,u]=(0,Lh.useState)(()=>n?0:c),d=(0,Lh.useRef)(null);(0,Lh.useEffect)(()=>{if(n)return d.current=setInterval(()=>{u(e=>e>=c?(d.current&&(clearInterval(d.current),d.current=null),e):Math.min(e+2,c))},35),()=>{d.current&&(clearInterval(d.current),d.current=null)};u(c)},[n,c]);const h=(0,Lh.useRef)(0);(0,Lh.useEffect)(()=>{if(!s||!n||0===l)return;const e=Date.now();e-h.current<80||(h.current=e,s())},[l,n,s]);const p=n?(e||"").slice(0,l):e||"",{content:f,isRichContent:m}=(0,Lh.useMemo)(()=>{if(!p)return{content:"",isRichContent:!1};const e=(t=p)&&"string"==typeof t?t.replace(/\\"/g,'"').replace(/\\'/g,"'"):t;var t;if(i)return{content:e,isRichContent:!1};if(If(e))return{content:Tf(e),isRichContent:!0};if(kp(e)){const t=Sp(e);return{content:Tf(t),isRichContent:!0}}const n=xp(e);if(n!==e){const e=n.replace(/\n/g,"<br>");return{content:Tf(e),isRichContent:!0}}return{content:e,isRichContent:!1}},[p,i]);if(!(f||r&&0!==r.length))return null;const g=Rf()("nfd-ai-chat-message",`nfd-ai-chat-message--${a}`);return(0,Hf.jsxs)("div",{className:g,children:[f&&(m?(0,Hf.jsx)(Hf.Fragment,{children:(0,Hf.jsx)("div",{className:"nfd-ai-chat-message__content nfd-ai-chat-message__content--rich",dangerouslySetInnerHTML:{__html:f}})}):(0,Hf.jsx)("div",{className:"nfd-ai-chat-message__content nfd-ai-chat-message__content--pre-wrap",style:{whiteSpace:"pre-wrap"},children:f})),r&&r.length>0&&(0,Hf.jsx)(Wf,{executedTools:r,toolResults:o})]})},Zf=({message:e,className:t=""})=>(0,Hf.jsxs)("div",{className:`nfd-ai-chat-error-alert ${t}`,children:[(0,Hf.jsx)("div",{className:"nfd-ai-chat-error-alert__icon",children:(0,Hf.jsx)(zf,{width:16,height:16})}),(0,Hf.jsx)("div",{className:"nfd-ai-chat-error-alert__content",children:(0,Hf.jsx)("div",{className:"nfd-ai-chat-error-alert__message",children:e})})]}),Gf=Mf("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),Kf=Mf("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]),Jf={[sp.PROCESSING]:(0,Wh.__)("Processing…","wp-module-ai-chat"),[sp.CONNECTING]:(0,Wh.__)("Getting your site ready…","wp-module-ai-chat"),[sp.WS_CONNECTING]:(0,Wh.__)("Connecting…","wp-module-ai-chat"),[sp.TOOL_CALL]:(0,Wh.__)("Looking this up…","wp-module-ai-chat"),[sp.WORKING]:(0,Wh.__)("Almost there…","wp-module-ai-chat"),[sp.RECEIVED]:(0,Wh.__)("Message received","wp-module-ai-chat"),[sp.GENERATING]:(0,Wh.__)("Thinking…","wp-module-ai-chat"),[sp.SUMMARIZING]:(0,Wh.__)("Summarizing results","wp-module-ai-chat"),[sp.COMPLETED]:(0,Wh.__)("Processing","wp-module-ai-chat"),[sp.FAILED]:(0,Wh.__)("Error occurred","wp-module-ai-chat")},Xf=({tool:e,isActive:t,progress:n,isComplete:s,isError:r})=>{const o=Ff(e.name,e.arguments);return(0,Hf.jsxs)("div",{className:Rf()("nfd-ai-chat-tool-execution__item",{"nfd-ai-chat-tool-execution__item--active":t,"nfd-ai-chat-tool-execution__item--complete":s,"nfd-ai-chat-tool-execution__item--error":r}),children:[(0,Hf.jsxs)("div",{className:"nfd-ai-chat-tool-execution__item-header",children:[r?(0,Hf.jsx)(zf,{className:"nfd-ai-chat-tool-execution__icon nfd-ai-chat-tool-execution__icon--error",size:12}):s?(0,Hf.jsx)(Df,{className:"nfd-ai-chat-tool-execution__icon nfd-ai-chat-tool-execution__icon--success",size:12}):t?(0,Hf.jsx)(Gf,{className:"nfd-ai-chat-tool-execution__icon nfd-ai-chat-tool-execution__icon--active",size:12}):(0,Hf.jsx)(Kf,{className:"nfd-ai-chat-tool-execution__icon nfd-ai-chat-tool-execution__icon--pending",size:12}),(0,Hf.jsx)("span",{className:"nfd-ai-chat-tool-execution__item-title",children:o.title}),o.params&&(0,Hf.jsx)("span",{className:"nfd-ai-chat-tool-execution__item-params",children:o.params})]}),t&&n&&(0,Hf.jsx)("div",{className:"nfd-ai-chat-tool-execution__item-progress",children:n})]})},Yf=({status:e=null,activeToolCall:t=null,toolProgress:n=null,executedTools:s=[],pendingTools:r=[]})=>{const[o,a]=(0,Lh.useState)(!0),i=!!t,c=!i&&e===sp.SUMMARIZING&&s.length>0;(0,Lh.useEffect)(()=>{(i||c)&&a(!0)},[i,c]);const l=t||s.length>0||r.length>0,u=s.length+(t?1:0)+r.length;return l?(0,Hf.jsx)("div",{className:"nfd-ai-chat-message nfd-ai-chat-message--assistant",children:(0,Hf.jsx)("div",{className:"nfd-ai-chat-message__content",children:(0,Hf.jsxs)("div",{className:Rf()("nfd-ai-chat-tool-execution",{"nfd-ai-chat-tool-execution--collapsed":!o}),children:[(0,Hf.jsxs)("button",{type:"button",className:"nfd-ai-chat-tool-execution__header",onClick:()=>a(!o),"aria-expanded":o?"true":"false",children:[o?(0,Hf.jsx)(Lf,{className:"nfd-ai-chat-tool-execution__chevron",size:12}):(0,Hf.jsx)(Uf,{className:"nfd-ai-chat-tool-execution__chevron",size:12}),i?(0,Hf.jsxs)(Hf.Fragment,{children:[(0,Hf.jsx)("span",{children:(0,Wh.__)("Executing actions","wp-module-ai-chat")}),t.total>1&&(0,Hf.jsxs)("span",{className:"nfd-ai-chat-tool-execution__header-count",children:["(",t.index,"/",t.total,")"]})]}):c?(0,Hf.jsxs)(Hf.Fragment,{children:[(0,Hf.jsx)(Gf,{className:"nfd-ai-chat-tool-execution__icon nfd-ai-chat-tool-execution__icon--active",size:12}),(0,Hf.jsx)("span",{children:(0,Wh.__)("Processing","wp-module-ai-chat")}),(0,Hf.jsxs)("span",{className:"nfd-ai-chat-tool-execution__header-count",children:["(",s.length,")"]})]}):(0,Hf.jsxs)(Hf.Fragment,{children:[(0,Hf.jsx)("span",{children:(0,Wh.__)("Actions completed","wp-module-ai-chat")}),(0,Hf.jsxs)("span",{className:"nfd-ai-chat-tool-execution__header-count",children:["(",u,")"]})]})]}),o&&(0,Hf.jsxs)("div",{className:"nfd-ai-chat-tool-execution__list",children:[s.map((e,t)=>(0,Hf.jsx)(Xf,{tool:e,isActive:!1,isComplete:!e.isError,isError:e.isError,progress:null},e.id||`executed-${t}`)),t&&(0,Hf.jsx)(Xf,{tool:t,isActive:!0,isComplete:!1,isError:!1,progress:n},t.id||"active"),c&&(0,Hf.jsx)(Xf,{tool:{name:"preparing-changes"},isActive:!0,isComplete:!1,isError:!1,progress:null},"preparing"),r.map((e,t)=>(0,Hf.jsx)(Xf,{tool:e,isActive:!1,isComplete:!1,isError:!1,progress:null},e.id||`pending-${t}`))]})]})})}):(0,Hf.jsx)("div",{className:"nfd-ai-chat-message nfd-ai-chat-message--assistant",children:(0,Hf.jsx)("div",{className:"nfd-ai-chat-message__content",children:(0,Hf.jsxs)("div",{className:"nfd-ai-chat-typing-indicator",children:[(0,Hf.jsxs)("span",{className:"nfd-ai-chat-typing-indicator__dots","aria-hidden":"true",children:[(0,Hf.jsx)("span",{}),(0,Hf.jsx)("span",{}),(0,Hf.jsx)("span",{})]}),(0,Hf.jsx)("span",{className:"nfd-ai-chat-typing-indicator__text",children:Jf[e]??(0,Wh.__)("Thinking…","wp-module-ai-chat")})]})})})},Qf=({messages:e=[],isLoading:t=!1,error:n=null,status:s=null,activeToolCall:r=null,toolProgress:o=null,executedTools:a=[],pendingTools:i=[],onRetry:c,connectionFailed:l=!1,isConnectingOrReconnecting:u=!1,messageBubbleStyle:d="bubbles"})=>{const h=(0,Lh.useRef)(null),[p,f]=(0,Lh.useState)(0),m=(0,Lh.useCallback)(()=>{const e=h.current;e&&e.scrollTo({top:e.scrollHeight-e.clientHeight,behavior:"smooth"})},[]);(0,Lh.useEffect)(()=>{m()},[e,t,o,p,m]);const g=(0,Lh.useCallback)(()=>{f(e=>e+1)},[]),_=r||a.length>0||i.length>0,y=Rf()("nfd-ai-chat-messages",{"nfd-ai-chat-messages--minimal":"minimal"===d});return(0,Hf.jsxs)("div",{ref:h,className:y,children:[e.length>0&&e.map((t,n)=>{const s=n===e.length-1&&("assistant"===t.type||"assistant"===t.role);return(0,Hf.jsx)(Bf,{message:t.content,type:t.type,animateTyping:s&&!0===t.animateTyping,onContentGrow:s?g:void 0,executedTools:t.executedTools,toolResults:t.toolResults},t.id||n)}),u&&!l&&(0,Hf.jsx)("div",{className:"nfd-ai-chat-message nfd-ai-chat-message--assistant",children:(0,Hf.jsx)("div",{className:"nfd-ai-chat-message__content",children:(0,Hf.jsxs)("div",{className:"nfd-ai-chat-typing-indicator",children:[(0,Hf.jsxs)("span",{className:"nfd-ai-chat-typing-indicator__dots","aria-hidden":"true",children:[(0,Hf.jsx)("span",{}),(0,Hf.jsx)("span",{}),(0,Hf.jsx)("span",{})]}),(0,Hf.jsx)("span",{className:"nfd-ai-chat-typing-indicator__text",children:(0,Wh.__)("Connecting....","wp-module-ai-chat")})]})})}),n&&(0,Hf.jsx)(Zf,{message:n}),c&&(n||l)&&(0,Hf.jsx)("p",{className:"nfd-ai-chat-messages__retry",children:(0,Hf.jsx)("button",{type:"button",className:"nfd-ai-chat-messages__retry-button",onClick:c,children:(0,Wh.__)("Retry","wp-module-ai-chat")})}),t&&(0,Hf.jsx)(Yf,{status:s,activeToolCall:r,toolProgress:o,executedTools:_?a:[],pendingTools:i})]})},em=window.wp.components,tm=Mf("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]]),nm=Mf("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]),sm=({onSendMessage:e,onStopRequest:t,disabled:n=!1,showStopButton:s,placeholder:r,contextComponent:o=null,showTopBorder:a=!0})=>{const i=!0===s,[c,l]=(0,Lh.useState)(""),[u,d]=(0,Lh.useState)(!1),h=(0,Lh.useRef)(null),p=(0,Wh.__)("How can I help you today?","wp-module-ai-chat");(0,Lh.useEffect)(()=>{if(h.current){h.current.style.height="auto";const e=h.current.scrollHeight,t=Math.min(e,Cf.MAX_HEIGHT);h.current.style.height=`${t}px`,e>Cf.MAX_HEIGHT?h.current.style.overflowY="auto":h.current.style.overflowY="hidden"}},[c]),(0,Lh.useEffect)(()=>{!n&&h.current&&setTimeout(()=>{h.current.focus()},Cf.FOCUS_DELAY)},[n]);const f=(0,Lh.useCallback)(()=>{c.trim()&&!n&&(e(c),l(""),h.current&&(h.current.style.height="auto",h.current.style.overflowY="hidden",h.current.focus()))},[c,n,e]),m=(0,Lh.useCallback)(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),f())},[f]),g=(0,Lh.useCallback)(()=>{u||(d(!0),t&&t(),setTimeout(()=>{d(!1)},Cf.STOP_DEBOUNCE))},[u,t]),_=Rf()("nfd-ai-chat-input",{"nfd-ai-chat-input--no-top-border":!a});return(0,Hf.jsxs)("div",{className:_,children:[(0,Hf.jsxs)("div",{className:"nfd-ai-chat-input__container",children:[(0,Hf.jsx)("textarea",{name:"nfd-ai-chat-input",ref:h,value:c,onChange:e=>l(e.target.value),onKeyDown:m,placeholder:r||p,className:"nfd-ai-chat-input__textarea",rows:1,disabled:n}),(0,Hf.jsxs)("div",{className:"nfd-ai-chat-input__actions",children:[o,i?(0,Hf.jsx)(em.Button,{icon:(0,Hf.jsx)(tm,{width:16,height:16}),label:(0,Wh.__)("Stop generating","wp-module-ai-chat"),onClick:g,className:"nfd-ai-chat-input__stop",disabled:u,"aria-busy":u}):(0,Hf.jsx)(em.Button,{icon:(0,Hf.jsx)(nm,{width:16,height:16}),label:(0,Wh.__)("Send message","wp-module-ai-chat"),onClick:f,className:"nfd-ai-chat-input__submit",disabled:!c.trim()||n})]})]}),(0,Hf.jsx)("div",{className:"nfd-ai-chat-input__disclaimer",children:(0,Wh.__)("AI-generated content is not guaranteed for accuracy.","wp-module-ai-chat")})]})},rm=e=>(0,Hf.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",focusable:"false",...e,children:(0,Hf.jsx)("path",{d:"M18 6L6 18M6 6l12 12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),om=e=>(0,Hf.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",...e,children:[(0,Hf.jsx)("path",{d:"m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"}),(0,Hf.jsx)("path",{d:"M5 3v4"}),(0,Hf.jsx)("path",{d:"M19 17v4"}),(0,Hf.jsx)("path",{d:"M3 5h4"}),(0,Hf.jsx)("path",{d:"M17 19h4"})]}),am=()=>(0,Hf.jsx)("span",{className:"nfd-ai-chat-blu-beta-badge",children:(0,Wh.__)("BETA","wp-module-ai-chat")}),im=({title:e,badge:t,logo:n,leftActions:s,rightActions:r,className:o=""})=>(0,Hf.jsxs)("div",{className:`nfd-ai-chat-header ${o}`.trim(),role:"banner",children:[(0,Hf.jsxs)("div",{className:"nfd-ai-chat-header__brand",children:[n,null!=e&&(0,Hf.jsx)("span",{className:"nfd-ai-chat-header__title",children:e}),t]}),(s||r)&&(0,Hf.jsxs)("div",{className:"nfd-ai-chat-header__actions",children:[s,r]})]}),cm=({title:e,onNewChat:t,onClose:n,extraActions:s,newChatDisabled:r=!1})=>(0,Hf.jsx)(im,{logo:(0,Hf.jsx)(om,{width:20,height:20}),title:e||(0,Wh.__)("Blu Chat","wp-module-ai-chat"),badge:(0,Hf.jsx)(am,{}),rightActions:(0,Hf.jsxs)(Hf.Fragment,{children:["function"==typeof t&&(0,Hf.jsx)("button",{type:"button",className:"nfd-ai-chat-header__btn nfd-ai-chat-header__btn--new",onClick:r?void 0:t,disabled:r,"aria-label":(0,Wh.__)("New chat","wp-module-ai-chat"),title:(0,Wh.__)("New chat","wp-module-ai-chat"),children:"+"}),s,"function"==typeof n&&(0,Hf.jsx)("button",{type:"button",className:"nfd-ai-chat-header__btn nfd-ai-chat-header__btn--close",onClick:n,"aria-label":(0,Wh.__)("Close","wp-module-ai-chat"),title:(0,Wh.__)("Close","wp-module-ai-chat"),children:(0,Hf.jsx)(rm,{})})]})}),lm=({width:e=24,height:t=24,...n})=>(0,Hf.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 30 30",width:e,height:t,...n,children:[(0,Hf.jsx)("path",{d:"M14.217,19.707l-1.112,2.547c-0.427,0.979-1.782,0.979-2.21,0l-1.112-2.547c-0.99-2.267-2.771-4.071-4.993-5.057L1.73,13.292c-0.973-0.432-0.973-1.848,0-2.28l2.965-1.316C6.974,8.684,8.787,6.813,9.76,4.47l1.126-2.714c0.418-1.007,1.81-1.007,2.228,0L14.24,4.47c0.973,2.344,2.786,4.215,5.065,5.226l2.965,1.316c0.973,0.432,0.973,1.848,0,2.28l-3.061,1.359C16.988,15.637,15.206,17.441,14.217,19.707z"}),(0,Hf.jsx)("path",{d:"M24.481,27.796l-0.339,0.777c-0.248,0.569-1.036,0.569-1.284,0l-0.339-0.777c-0.604-1.385-1.693-2.488-3.051-3.092l-1.044-0.464c-0.565-0.251-0.565-1.072,0-1.323l0.986-0.438c1.393-0.619,2.501-1.763,3.095-3.195l0.348-0.84c0.243-0.585,1.052-0.585,1.294,0l0.348,0.84c0.594,1.432,1.702,2.576,3.095,3.195l0.986,0.438c0.565,0.251,0.565,1.072,0,1.323l-1.044,0.464C26.174,25.308,25.085,26.411,24.481,27.796z"})]}),um=({width:e=24,height:t=24})=>(0,Hf.jsx)("div",{className:"nfd-ai-chat-avatar",style:{width:e,height:t},children:(0,Hf.jsx)(lm,{width:.625*e,height:.625*t})}),dm=({icon:e,text:t,onClick:n,className:s=""})=>(0,Hf.jsxs)(em.Button,{className:`nfd-ai-chat-suggestion ${s}`,onClick:n,children:[(0,Hf.jsx)("div",{className:"nfd-ai-chat-suggestion__icon",children:e}),(0,Hf.jsx)("div",{className:"nfd-ai-chat-suggestion__text",children:t})]}),hm=({onSendMessage:e,title:t,subtitle:n,suggestions:s=[],showSuggestions:r=!1,animateWelcome:o=!1})=>{const a=(0,Wh.__)("Hi, I'm your AI assistant.","wp-module-ai-chat"),i=(0,Wh.__)("How can I help you today?","wp-module-ai-chat"),c=t||a,l=n||i,u=`${c} ${l}`,[d,h]=(0,Lh.useState)(0),p=(0,Lh.useRef)(null);(0,Lh.useEffect)(()=>{if(!o)return void h(u.length);h(0);const e=()=>{h(t=>t>=u.length?t:(p.current=setTimeout(e,40),t+1))};return p.current=setTimeout(e,40),()=>{p.current&&clearTimeout(p.current)}},[o,u]);const f=o&&d<u.length,m=f&&d<=c.length?c.slice(0,d):c;let g=l;return f&&d>c.length?g=l.slice(0,d-c.length-1):f&&(g=""),(0,Hf.jsxs)("div",{className:"nfd-ai-chat-welcome",children:[(0,Hf.jsxs)("div",{className:"nfd-ai-chat-welcome__content",children:[(0,Hf.jsx)("div",{className:"nfd-ai-chat-welcome__avatar",children:(0,Hf.jsx)(um,{width:64,height:64})}),(0,Hf.jsxs)("div",{className:"nfd-ai-chat-welcome__message",children:[(0,Hf.jsx)("div",{className:"nfd-ai-chat-welcome__title",children:m}),(0,Hf.jsxs)("div",{className:"nfd-ai-chat-welcome__subtitle",children:[g,f&&d<u.length&&(0,Hf.jsx)("span",{className:"nfd-ai-chat-welcome__cursor","aria-hidden":"true"})]})]})]}),r&&s.length>0&&(0,Hf.jsx)("div",{className:"nfd-ai-chat-suggestions",children:s.map((t,n)=>(0,Hf.jsx)(dm,{icon:t.icon,text:t.text,onClick:()=>e(t.action||t.text)},t.action??t.text??n))})]})};function pm(e,t,n,s,r={}){if(!e||0===e.length)return;if(!e.some(e=>("user"===e.role||"user"===e.type)&&e.content&&String(e.content).trim()))return;if(null===t&&null===n)return;const o=r.maxHistoryItems??3,a=Yh(s);try{const s=JSON.parse(window.localStorage.getItem(a.archive)||"[]"),r={sessionId:t,conversationId:n,messages:e.map(e=>({...e,timestamp:e.timestamp instanceof Date?e.timestamp.toISOString():e.timestamp})),archivedAt:(new Date).toISOString()},i=null!=n?s.filter(e=>e.conversationId!==n):s.filter(e=>e.sessionId!==t);i.unshift(r),window.localStorage.setItem(a.archive,JSON.stringify(i.slice(0,o)))}catch(e){console.warn("[Chat History] Failed to archive conversation:",e)}}function fm(e,t,n){const s=Yh(n);try{const n=JSON.parse(window.localStorage.getItem(s.archive)||"[]"),r=n.filter(n=>n.conversationId!==e||n.sessionId!==t);r.length!==n.length&&window.localStorage.setItem(s.archive,JSON.stringify(r))}catch(e){console.warn("[Chat History] Failed to remove conversation from archive:",e)}}const mm=Mf("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]),gm=Mf("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);function _m(e){const t=e.messages||e;return Array.isArray(t)&&t.some(e=>("user"===e.role||"user"===e.type)&&e.content&&String(e.content).trim())}const ym=({consumer:e,onSelectConversation:t,refreshTrigger:n=0,disabled:s=!1,emptyMessage:r=null,maxHistoryItems:o=3})=>{const[a,i]=(0,Lh.useState)([]),c=Yh(e);(0,Lh.useEffect)(()=>{try{const e=window.localStorage.getItem(c.archive);if(e){const t=JSON.parse(e);if(Array.isArray(t)&&t.length>0){const e=t.slice(0,o);e.length<t.length&&window.localStorage.setItem(c.archive,JSON.stringify(e));const n=e.map(e=>{const t=(e.messages||[]).map(e=>({...e,timestamp:e.timestamp?new Date(e.timestamp):new Date})),n=e.archivedAt?new Date(e.archivedAt):null;return{sessionId:e.sessionId??null,conversationId:e.conversationId??null,messages:t,archivedAt:n}}).filter(_m);return void i(n)}}const t=window.localStorage.getItem(c.history);if(t){const e=JSON.parse(t);if(Array.isArray(e)&&e.length>0){const t=function(e,t){if(!Array.isArray(e)||0===e.length)return[];const n={},s=[];e.forEach(e=>{if(e.sessionId){n[e.sessionId]||(n[e.sessionId]={sessionId:e.sessionId,messages:[],timestamp:e.timestamp?new Date(e.timestamp).getTime():0}),n[e.sessionId].messages.push(e);const t=e.timestamp?new Date(e.timestamp).getTime():0;t>n[e.sessionId].timestamp&&(n[e.sessionId].timestamp=t)}else s.push(e)});let r=Object.values(n).sort((e,t)=>t.timestamp-e.timestamp).map(e=>({sessionId:e.sessionId,messages:e.messages}));if(s.length>0&&r.length<t){const e=function(e){const t=[];let n=[],s=null;return e.forEach(e=>{const r=e.timestamp?new Date(e.timestamp).getTime():Date.now();s&&r-s>3e5&&n.length>0&&(t.push({sessionId:null,messages:[...n]}),n=[]),n.push(e),s=r}),n.length>0&&t.push({sessionId:null,messages:n}),t.reverse()}(s);r=[...r,...e]}return r=r.filter(_m),r.slice(0,t)}(e.map(e=>({...e,timestamp:e.timestamp?new Date(e.timestamp):new Date})),o);i(t)}}}catch(e){console.warn("[Chat History] Failed to load chat history:",e)}},[e,n,o,c.archive,c.history]);const l=(0,Lh.useCallback)(e=>{if(!s)try{const n=(e.messages||e).map(e=>({...e,timestamp:e.timestamp instanceof Date?e.timestamp.toISOString():e.timestamp}));window.localStorage.setItem(c.history,JSON.stringify(n)),e.sessionId&&window.localStorage.setItem(c.sessionId,e.sessionId),e.conversationId&&window.localStorage.setItem(c.conversationId,e.conversationId),t&&t(e)}catch(e){console.warn("[Chat History] Failed to restore conversation:",e)}},[s,c,t]),u=(0,Lh.useCallback)((e,t)=>{if(e.stopPropagation(),e.preventDefault(),!s)try{const e=window.localStorage.getItem(c.archive);if(e){const n=JSON.parse(e).filter((e,n)=>n!==t);window.localStorage.setItem(c.archive,JSON.stringify(n))}i(e=>e.filter((e,n)=>n!==t))}catch(e){console.warn("[Chat History] Failed to delete conversation:",e)}},[s,c]);return 0===a.length?r?(0,Hf.jsx)("div",{className:"nfd-ai-chat-history-list nfd-ai-chat-history-list--empty",children:r}):null:(0,Hf.jsx)("div",{className:"nfd-ai-chat-history-list",children:a.map((e,t)=>{const n=(e=>{const t=(e.messages||e).find(e=>"user"===e.role||"user"===e.type);if(t&&t.content){const e=t.content;return e.length>50?e.substring(0,50)+"...":e}return(0,Wh.__)("Previous conversation","wp-module-ai-chat")})(e),r=e.sessionId||`legacy-${t}`,o=e.archivedAt||function(e){const t=e.messages||e;if(!Array.isArray(t)||0===t.length)return null;let n=0;return t.forEach(e=>{const t=e.timestamp?new Date(e.timestamp).getTime():0;t>n&&(n=t)}),n?new Date(n):null}(e)||null,a=o?(e=>{const t=e instanceof Date?e:new Date(e),n=Date.now()-t.getTime(),s=Math.floor(n/6e4);if(s<1)return(0,Wh.__)("Just now","wp-module-ai-chat");if(s<60)return`${s}m`;const r=Math.floor(n/36e5);if(r<24)return`${r}h`;const o=Math.floor(n/864e5);return o<7?`${o}d`:t.toLocaleDateString(void 0,{month:"short",day:"numeric"})})(o):null;return(0,Hf.jsxs)("div",{className:"nfd-ai-chat-history-item"+(s?" nfd-ai-chat-history-item--disabled":""),role:"button",tabIndex:s?-1:0,"aria-disabled":s,onClick:()=>l(e),onKeyDown:t=>{s||"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),l(e))},children:[(0,Hf.jsx)(mm,{width:14,height:14,"aria-hidden":!0}),(0,Hf.jsxs)("div",{className:"nfd-ai-chat-history-item__content",children:[(0,Hf.jsx)("span",{className:"nfd-ai-chat-history-item__title",children:n}),(0,Hf.jsxs)("div",{className:"nfd-ai-chat-history-item__meta",children:[a&&(0,Hf.jsx)("span",{className:"nfd-ai-chat-history-item__time",children:a}),(0,Hf.jsx)("button",{type:"button",className:"nfd-ai-chat-history-item__delete",onClick:e=>u(e,t),"aria-label":(0,Wh.__)("Delete conversation","wp-module-ai-chat"),title:(0,Wh.__)("Delete","wp-module-ai-chat"),children:(0,Hf.jsx)(gm,{width:14,height:14,className:"nfd-ai-chat-history-item__delete-icon","aria-hidden":!0})})]})]})]},r)})})},wm=e=>(0,Hf.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",focusable:"false",...e,children:[(0,Hf.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2"}),(0,Hf.jsx)("path",{d:"M12 7v5l3 3",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),vm=({consumer:e,open:t,onOpenChange:n,onSelectConversation:s,refreshTrigger:r=0,disabled:o=!1,maxHistoryItems:a})=>{const i=(0,Lh.useRef)(null),c=(0,Lh.useRef)(null),[l,u]=(0,Lh.useState)({top:0,left:0,openUp:!1}),d=(0,Lh.useCallback)(()=>{if(!i.current)return;const e=i.current.getBoundingClientRect(),t=window.innerHeight-e.bottom,n=t<240&&e.top>t;u({top:n?e.top:e.bottom,left:e.right,openUp:n})},[]);(0,Lh.useLayoutEffect)(()=>{t&&d()},[t,d]),(0,Lh.useEffect)(()=>{if(!t)return;const e=()=>d();return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[t,d]),(0,Lh.useEffect)(()=>{if(!t)return;const e=e=>{i.current?.contains(e.target)||c.current?.contains(e.target)||n(!1)},s=e=>{"Escape"===e.key&&n(!1)};return document.addEventListener("mousedown",e),document.addEventListener("keydown",s),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",s)}},[t,n]);const h=(0,Lh.useCallback)(e=>{s(e),n(!1)},[s,n]),p=(0,Lh.useCallback)(()=>{o||n(!t)},[o,t,n]),f=(0,Hf.jsx)("div",{ref:c,className:"nfd-ai-chat-history-dropdown",role:"dialog","aria-label":(0,Wh.__)("Chat history","wp-module-ai-chat"),style:{position:"fixed",top:l.openUp?"auto":l.top,bottom:l.openUp?window.innerHeight-l.top:"auto",left:"auto",right:window.innerWidth-l.left,zIndex:1e5},children:(0,Hf.jsx)("div",{className:"nfd-ai-chat-history-dropdown-inner",children:(0,Hf.jsx)(ym,{consumer:e,onSelectConversation:h,disabled:o,refreshTrigger:t?r:0,emptyMessage:(0,Wh.__)("No conversations yet.","wp-module-ai-chat"),maxHistoryItems:a})})});return(0,Hf.jsxs)("div",{className:"nfd-ai-chat-history-dropdown-wrapper",children:[(0,Hf.jsx)("button",{ref:i,type:"button",className:"nfd-ai-chat-history-dropdown-trigger "+(t?"is-open":""),onClick:p,disabled:o,"aria-expanded":t,"aria-haspopup":"true","aria-label":(0,Wh.__)("Chat history","wp-module-ai-chat"),title:(0,Wh.__)("Chat history","wp-module-ai-chat"),children:(0,Hf.jsx)(wm,{})}),t&&(0,Lh.createPortal)(f,document.body)]})}})(),module.exports=s})();
|
|
8
|
+
(0,Wh.__)("Failed to fetch config: %1$s %2$s","wp-module-ai-chat"),e.data.status,e.data.statusText||t)),new Error(t)}}const pp=e=>Array.isArray(e)&&e.some(e=>("user"===e.role||"user"===e.type)&&e.content&&String(e.content).trim()),fp=(e,t,n)=>{try{const s=localStorage.getItem(e),r=localStorage.getItem(t),o=localStorage.getItem(n);if(s){const e=JSON.parse(s);if(Array.isArray(e)&&e.length>0)return{messages:e.map(e=>({...e,timestamp:e.timestamp?new Date(e.timestamp):new Date,animateTyping:!1})),conversationId:r||null,sessionId:o||null}}}catch(e){console.warn("[AI Chat] Failed to restore chat history from localStorage:",e)}return{messages:[],conversationId:null,sessionId:null}},mp=(e,t)=>{try{pp(t)?localStorage.setItem(e,JSON.stringify(t)):localStorage.removeItem(e)}catch(e){console.warn("[AI Chat] Failed to save messages to localStorage:",e)}},gp=({configEndpoint:e,consumer:t,autoConnect:n=!1,consumerType:s="editor_chat",autoLoadHistory:r=!0,getConnectionFailedFallbackMessage:o}={})=>{const a=Yh(t),i=a.history,c=a.conversationId,l=a.sessionId,u=i.replace(/-history$/,""),[d,h]=(0,Lh.useState)(()=>r?fp(i,c,l).messages:[]),[p,f]=(0,Lh.useState)(()=>r?fp(i,c,l).conversationId:null),[m,g]=(0,Lh.useState)(!1),[_,y]=(0,Lh.useState)(!1),[w,v]=(0,Lh.useState)(null),[b,$]=(0,Lh.useState)(!1),[k,S]=(0,Lh.useState)(null),[x,E]=(0,Lh.useState)(""),[T,I]=(0,Lh.useState)(null),[C,P]=(0,Lh.useState)(()=>{try{if("1"===sessionStorage.getItem(`${u}-connection-failed`))return"failed"}catch(e){}return"disconnected"}),[R,A]=(0,Lh.useState)(0),N=(0,Lh.useRef)(null),O=(0,Lh.useRef)(null),j=(0,Lh.useRef)(0),M=(0,Lh.useRef)(null),z=(0,Lh.useRef)(null),D=(0,Lh.useRef)(null),L=(0,Lh.useRef)(!1),U=(0,Lh.useRef)(null),q=(0,Lh.useRef)(null),F=(0,Lh.useRef)(null),H=(0,Lh.useRef)(null),V=(0,Lh.useRef)(!1),W=(0,Lh.useRef)(()=>r?fp(i,c,l).sessionId:null);"function"==typeof W.current&&(W.current=W.current());const B=(0,Lh.useRef)(!1),Z=(0,Lh.useRef)(!1),G=(0,Lh.useRef)(!1),K=(0,Lh.useRef)(null),J=(0,Lh.useRef)(!0),X=(0,Lh.useRef)([]),Y=(0,Lh.useRef)(C),Q=(0,Lh.useRef)(C),ee=Bh.MAX_RECONNECT_ATTEMPTS,te=Bh.RECONNECT_DELAY,ne=Bh.TYPING_TIMEOUT,se=Bh.JWT_REFRESH_BUFFER_MS,re=Bh.JWT_REFRESH_MIN_DELAY_MS,oe=Bh.JWT_PROACTIVE_REFRESH_COOLDOWN_MS,ae=Bh.AUTH_REFRESH_COOLDOWN_MS,ie=Bh.JWT_EXPIRED_BUFFER_MS,ce=Bh.JWT_PROACTIVE_REFRESH_DEFER_MS,le=(0,Lh.useCallback)(e=>{W.current=e;try{localStorage.setItem(l,e)}catch(e){console.warn("[AI Chat] Failed to save session ID to localStorage:",e)}},[l]),ue=(0,Lh.useCallback)(e=>{try{localStorage.setItem(c,e)}catch(e){console.warn("[AI Chat] Failed to save conversation ID to localStorage:",e)}},[c]),de=(0,Lh.useCallback)(async()=>{if(N.current?.readyState!==WebSocket.OPEN&&N.current?.readyState!==WebSocket.CONNECTING&&!V.current){try{sessionStorage.removeItem(`${u}-connection-failed`)}catch(e){}V.current=!0,y(!0),P("connecting"),v(null);try{M.current||(M.current=await hp({configEndpoint:e,consumer:t}));let n=M.current;if(!n)throw new Error((0,Wh.__)("No configuration available","wp-module-ai-chat"));let r=!1;for(;n?.jarvis_jwt;){const s=Zh(n.jarvis_jwt);if(null==s)break;if(s>=Date.now()+ie)break;if(r)throw new Error((0,Wh.__)("Token expired, please refresh the page.","wp-module-ai-chat"));if(M.current=null,M.current=await hp({configEndpoint:e,consumer:t}),n=M.current,r=!0,!n)throw new Error((0,Wh.__)("No configuration available","wp-module-ai-chat"))}if(n.site_id){const e=Jh();e!==n.site_id&&((e=>{try{localStorage.setItem(Gh,e)}catch{}})(n.site_id),((e,t,n)=>{const s=Xh(e,n),r=Xh(t,n);try{for(const e of Object.values(Kh)){const t=`${s}-${e}`,n=`${r}-${e}`,o=localStorage.getItem(t);o&&!localStorage.getItem(n)&&localStorage.setItem(n,o),o&&localStorage.removeItem(t)}}catch{}})(e,n.site_id,t))}if(W.current||(W.current=qh()),n.jarvis_jwt){z.current&&(clearTimeout(z.current),z.current=null);const e=Zh(n.jarvis_jwt);if(null!=e){let t=e-se;t=Math.max(t,Date.now()+re);const n=Date.now(),s=null!=D.current&&t<D.current+oe,r=L.current;if(r&&(L.current=!1),!s||r){const e=Math.max(0,t-n),s=()=>{G.current?z.current=setTimeout(s,ce):(z.current=null,D.current=Date.now(),L.current=!0,M.current=null,F.current&&F.current(),q.current&&q.current())};z.current=setTimeout(s,e)}}}const o=tp(n,W.current,s),a=new WebSocket(o);N.current=a,a.onopen=()=>{V.current=!1,g(!0),y(!1),P("connected"),A(0),v(null),j.current=0,B.current=X.current&&X.current.length>0,Z.current=!1,E("")};const i=function(e){const{isStoppedRef:t,hasUserMessageRef:n,typingTimeoutRef:s,typingTimeout:r,setIsTyping:o,setStatus:a,setCurrentResponse:i,setMessages:c,setConversationId:l,setError:u,saveSessionId:d,saveConversationId:h}=e;return function(p){if(!t.current||"session_established"===p.type)if("session_established"!==p.type){if("typing_start"===p.type)return o(!0),a(rp("typing_start")),void ip(s);if("typing_stop"===p.type)return o(!1),a(null),i(""),void ip(s);if("streaming_chunk"===p.type||"chunk"===p.type){if(t.current)return;const e=p.content||p.chunk||p.text||"";return void(e&&i(t=>{const i=t+e;return!n.current&&i.length<100&&op(i)?"":(o(!0),s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{o(!1),a(null),s.current=null},r),i)}))}if("structured_output"===p.type){const t=p.response_content?.content?.human_input_request;if(t&&"APPROVAL_REQUEST"===(t.input_type||t.inputType||"").toUpperCase()){if(p.conversation_id||p.conversationId){const e=p.conversation_id||p.conversationId;l(e),h(e)}return}const s=p.message||p.response_content?.message,r=ap(s,n.current);return void(r&&(i(e=>(e&&lp(c,e,"-streaming"),"")),lp(c,r),cp(e)))}if("tool_call"!==p.type){if("tool_result"!==p.type){if("message"===p.type||"complete"===p.type){let t=!1;if(i(e=>{if(e){const s=e.trim();if("No content provided"===s||"sales_requested"===s||"sales_requested"===s.toLowerCase())return"";if(!n.current&&e.length<150&&op(e))return"";c(t=>[...t,{id:`msg-${Date.now()}`,role:"assistant",type:"assistant",content:e,timestamp:new Date,animateTyping:!0}]),t=!0}return""}),!t){const e=p.message||p.response_content?.message,s=ap(e,n.current);s&&(lp(c,s),t=!0)}return void(t&&cp(e))}if("handoff_accept"!==p.type){if("handoff_request"===p.type){a(rp("handoff_request"));const t=p.message||p.response_content?.message,s=ap(t,n.current);return s?(lp(c,s),void cp(e)):void i("")}if("error"===p.type)return u(p.message||p.error||"An error occurred"),o(!1),a(null),void i("");if(p.message||p.response_content?.message){const t=p.message||p.response_content?.message,s=ap(t,n.current);if(!s)return void i("");lp(c,s),cp(e)}}else a(rp("handoff_accept"))}else if(a(rp("tool_result")),p.conversation_id||p.conversationId){const e=p.conversation_id||p.conversationId;l(e),h(e)}}else a(rp("tool_call"))}else p.session_id&&d(p.session_id)}}({isStoppedRef:Z,hasUserMessageRef:B,typingTimeoutRef:K,typingTimeout:ne,setIsTyping:$,setStatus:S,setCurrentResponse:E,setMessages:h,setConversationId:f,setError:v,saveSessionId:le,saveConversationId:ue});a.onmessage=e=>{try{const t=JSON.parse(e.data);i(t)}catch(e){console.error("[AI Chat] Error parsing WebSocket message:",e)}},a.onerror=()=>{V.current=!1,y(!1)},a.onclose=e=>{V.current=!1,g(!1),y(!1),$(!1),S(null),N.current===a&&(N.current=null);const t=4e3===e.code||4001===e.code,n=M.current?.jarvis_jwt,s=n?Zh(n):null,r=null!=s&&s<Date.now()+ie;if(t||r){const e=Date.now();(null==U.current||e-U.current>=ae)&&(M.current=null,j.current=0,U.current=e)}if(1e3!==e.code&&j.current<ee){j.current++,A(j.current),P("reconnecting");const e=te*Math.pow(2,j.current-1);O.current=setTimeout(()=>{de()},e)}else if(j.current>=ee){P("failed");try{sessionStorage.setItem(`${u}-connection-failed`,"1")}catch(e){}}else P("disconnected")}}catch(e){V.current=!1,"undefined"!=typeof console&&console.warn&&console.warn("[AI Chat] Connection failed:",e?.message||e),y(!1),P("failed");try{sessionStorage.setItem(`${u}-connection-failed`,"1")}catch(e){}}}},[e,t,s,u,le,ue,ee,te,ne,se,re,oe,ae,ie,ce]);(0,Lh.useEffect)(()=>{X.current=d},[d]),(0,Lh.useEffect)(()=>{Y.current=C},[C]),(0,Lh.useEffect)(()=>{G.current=b},[b]),(0,Lh.useEffect)(()=>()=>{O.current&&(clearTimeout(O.current),O.current=null),z.current&&(clearTimeout(z.current),z.current=null)},[]),(0,Lh.useEffect)(()=>{if("failed"!==C||"failed"===Q.current)return void(Q.current=C);Q.current=C;const e=(0,Wh.__)("Sorry, we couldn't connect. Please try again later or contact support.","wp-module-ai-chat");h(t=>{const n=t.length>0?t[t.length-1]:null,s=n&&("user"===n.role||"user"===n.type),r="function"==typeof o?o(s?n.content:""):e;return[...t,{id:`msg-${Date.now()}-fallback`,role:"assistant",type:"assistant",content:r,timestamp:new Date}]}),v(null),E(""),$(!1),S(null),K.current&&(clearTimeout(K.current),K.current=null)},[C,o]);const he=(0,Lh.useCallback)((e,t=null)=>{if(Z.current=!1,B.current=!0,("failed"===Y.current||j.current>=ee&&(!N.current||N.current.readyState!==WebSocket.OPEN))&&!t){const t={id:`msg-${Date.now()}`,role:"user",type:"user",content:e,timestamp:new Date,sessionId:W.current},n="function"==typeof o?o(e):(0,Wh.__)("Sorry, we couldn't connect. Please try again later or contact support.","wp-module-ai-chat");return h(e=>[...e,t,{id:`msg-${Date.now()}-fallback`,role:"assistant",type:"assistant",content:n,timestamp:new Date}]),v(null),E(""),$(!1),void S(null)}if(!N.current||N.current.readyState!==WebSocket.OPEN){if(!t){const t={id:`msg-${Date.now()}`,role:"user",type:"user",content:e,timestamp:new Date,sessionId:W.current};h(e=>[...e,t])}return void de()}if(!t){const t={id:`msg-${Date.now()}`,role:"user",type:"user",content:e,timestamp:new Date,sessionId:W.current};h(e=>[...e,t]),E(""),$(!0),K.current&&clearTimeout(K.current),K.current=setTimeout(()=>{$(!1),S(null),K.current=null},ne)}const n={type:"chat",message:e};t?n.conversationId=t:p&&(n.conversationId=p),N.current.send(JSON.stringify(n))},[p,de,o,ee,ne]),pe=(0,Lh.useCallback)(e=>{if(!N.current||N.current.readyState!==WebSocket.OPEN)return void console.warn("[AI Chat] Cannot send system message - not connected");const t={type:"chat",message:e};p&&(t.conversationId=p),$(!0),E(""),K.current&&clearTimeout(K.current),K.current=setTimeout(()=>{$(!1),S(null),K.current=null},ne),N.current.send(JSON.stringify(t))},[p,ne]),fe=(0,Lh.useCallback)(()=>{O.current&&(clearTimeout(O.current),O.current=null),z.current&&(clearTimeout(z.current),z.current=null),K.current&&(clearTimeout(K.current),K.current=null),N.current&&(N.current.close(1e3,"User disconnected"),N.current=null),g(!1),y(!1),P("disconnected")},[]);(0,Lh.useEffect)(()=>{q.current=de},[de]),(0,Lh.useEffect)(()=>{F.current=fe},[fe]);const me=(0,Lh.useCallback)(e=>{W.current=e??null},[]),ge=(0,Lh.useCallback)(()=>W.current??null,[]),_e=(0,Lh.useCallback)((e,t,n)=>{if(Array.isArray(e)){const t=e.map(e=>({...e,timestamp:e.timestamp?new Date(e.timestamp):new Date,animateTyping:!1}));h(t)}if(f(t??null),W.current=n??null,v(null),$(!1),S(null),E(""),null!=n&&N.current?.readyState===WebSocket.OPEN){try{localStorage.setItem(l,n),null!=t&&localStorage.setItem(c,t)}catch(e){console.warn("[AI Chat] Failed to persist session for history load:",e)}fe(),de()}},[de,fe,l,c]),ye=(0,Lh.useCallback)(()=>{Z.current=!0,$(!1),S(null),E(""),K.current&&(clearTimeout(K.current),K.current=null)},[]),we=(0,Lh.useCallback)(()=>{I(null)},[]),ve=(0,Lh.useCallback)(()=>{$(!1),S(null),K.current&&(clearTimeout(K.current),K.current=null)},[]),be=(0,Lh.useCallback)(e=>{let t;if(null==e)t=(0,Wh.__)("No content provided.","wp-module-ai-chat");else if("object"==typeof e)try{t=JSON.stringify(e,null,2)}catch(n){console.warn("[useNfdAgentsWebSocket] Failed to stringify content object:",n),t=String(e)}else t=String(e);h(e=>[...e,{id:`msg-${Date.now()}`,role:"assistant",type:"assistant",content:t,timestamp:new Date}]),$(!1),S(null),K.current&&(clearTimeout(K.current),K.current=null)},[]),$e=(0,Lh.useCallback)((e,t)=>{h(n=>n.map(n=>("function"==typeof e?e(n):n.id===e)?t(n):n))},[]),ke=(0,Lh.useCallback)(()=>{try{((e,t,n)=>{try{localStorage.removeItem(e),localStorage.removeItem(t),localStorage.removeItem(n)}catch(e){console.warn("[AI Chat] Failed to clear chat storage:",e)}})(i,c,l),h([]),f(null),I(null),$(!1),S(null),E(""),v(null),W.current=null,N.current&&(N.current.close(),N.current=null,g(!1)),B.current=!1,Z.current=!1,K.current&&(clearTimeout(K.current),K.current=null),O.current&&(clearTimeout(O.current),O.current=null),z.current&&(clearTimeout(z.current),z.current=null),j.current=0}catch(e){console.warn("[AI Chat] Failed to clear chat history:",e)}},[i,c,l]),Se=(0,Lh.useCallback)(()=>{j.current=0,A(0),v(null),de()},[de]);return(0,Lh.useEffect)(()=>{const e=H.current;if(null===e)return H.current=n,void(n&&"failed"!==C&&!V.current&&(!N.current||N.current.readyState!==WebSocket.OPEN&&N.current.readyState!==WebSocket.CONNECTING)&&de());e!==n&&(H.current=n,n?V.current||N.current&&(N.current.readyState===WebSocket.OPEN||N.current.readyState===WebSocket.CONNECTING)||de():fe())},[n,C]),(0,Lh.useEffect)(()=>{if(J.current)return J.current=!1,void(d.length>0&&pp(d)&&mp(i,d));mp(i,d)},[d,i]),(0,Lh.useEffect)(()=>{((e,t)=>{try{t?localStorage.setItem(e,t):localStorage.removeItem(e)}catch(e){console.warn("[AI Chat] Failed to save conversation ID to localStorage:",e)}})(c,p)},[p,c]),{messages:d,setMessages:h,setConversationId:f,setSessionId:me,loadConversation:_e,getSessionId:ge,sendMessage:he,sendSystemMessage:pe,isConnected:m,isConnecting:_,error:w,isTyping:b,status:k,currentResponse:x,approvalRequest:T,conversationId:p,clearApprovalRequest:we,clearTyping:ve,addAssistantMessage:be,updateMessage:$e,connect:de,disconnect:fe,stopRequest:ye,clearChatHistory:ke,brandId:M.current?.brand_id||null,connectionState:C,retryAttempt:R,maxRetries:ee,manualRetry:Se}},_p=["Would","If","Like","And","But","Or","So","Maybe","Perhaps","Well","Yes","No","When","Where","How","Why","It","To","We","Do","Be","As","An","The","You","In","On","At","By","Is"],yp=new RegExp(`\\b(${_p.join("|")})(https?:\\/\\/)`,"gi"),wp=new RegExp(`^((${_p.join("|")})\\s+)+(.+)$`,"i"),vp=new RegExp(`\\/(${_p.join("|")})$`,"i"),bp=new RegExp(`(\\d)(${_p.join("|")})$`,"i"),$p=/^https?:\/\/[^\s<>"]+$/;function kp(e){return!(!e||"string"!=typeof e)&&[/^#{1,6}\s/m,/\*\*[^*]+\*\*/,/\*[^*]+\*/,/__[^_]+__/,/_[^_]+_/,/`[^`]+`/,/```[\s\S]*?```/,/^\s*[-*+]\s/m,/^\s*\d+\.\s/m,/\[([^\]]+)\]\(([^)]+)\)/].some(t=>t.test(e))}function Sp(e){if(!e||"string"!=typeof e)return"";let t=e;t=t.replace(/&(?![\w#]+;)/g,"&").replace(/<(?![a-zA-Z/])/g,"<").replace(/(?<![a-zA-Z"])>/g,">"),t=t.replace(/```(\w*)\n?([\s\S]*?)```/g,(e,t,n)=>`<pre><code class="language-${t||"plaintext"}">${n.trim().replace(/</g,"<").replace(/>/g,">")}</code></pre>`),t=t.replace(/`([^`]+)`/g,'<code class="inline-code">$1</code>'),t=t.replace(/^######\s+(.+)$/gm,'<h6 class="chat-h6">$1</h6>'),t=t.replace(/^#####\s+(.+)$/gm,'<h5 class="chat-h5">$1</h5>'),t=t.replace(/^####\s+(.+)$/gm,'<h4 class="chat-h4">$1</h4>'),t=t.replace(/^###\s+(.+)$/gm,'<h3 class="chat-h3">$1</h3>'),t=t.replace(/^##\s+(.+)$/gm,'<h2 class="chat-h2">$1</h2>'),t=t.replace(/^#\s+(.+)$/gm,'<h1 class="chat-h1">$1</h1>'),t=t.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),t=t.replace(/__([^_]+)__/g,"<strong>$1</strong>"),t=t.replace(/(?<![*_])\*(?!\*)([^*\n]+)(?<!\*)\*(?!\*)/g,"<em>$1</em>"),t=t.replace(/(?<![_*])_(?!_)([^_\n]+)(?<!_)_(?!_)/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(e,t,n)=>{const s=t.trim().match(wp),r=s?s[3].trim():"",o=r&&($p.test(r)||/^https?:\/\//.test(r)),a=n.replace(/"/g,""");return s&&o?`${s[1]}<a href="${a}" target="_blank" rel="noopener noreferrer">${r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}</a>`:`<a href="${a}" target="_blank" rel="noopener noreferrer">${t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}</a>`}),t=t.replace(/^(\s*)[-*+]\s+(.+)$/gm,(e,t,n)=>`<li class="chat-li" data-level="${Math.floor(t.length/2)}">${n}</li>`),t=t.replace(/((?:<li[^>]*>.*?<\/li>\s*)+)/g,e=>`<ul class="chat-ul">${e.replace(/(<\/li>)\s+(<li)/g,"$1$2")}</ul>`),t=t.replace(/^(\s*)\d+\.\s+(.+)$/gm,(e,t,n)=>`<oli class="chat-oli" data-level="${Math.floor(t.length/2)}">${n}</oli>`),t=t.replace(/((?:<oli[^>]*>.*?<\/oli>\s*)+)/g,e=>`<ol class="chat-ol">${e.replace(/(<\/oli>)\s+(<oli)/g,"$1$2").replace(/<\/?oli/g,e=>e.replace("oli","li"))}</ol>`),t=t.replace(/^---+$/gm,'<hr class="chat-hr" />'),t=t.replace(/^>\s+(.+)$/gm,'<blockquote class="chat-blockquote">$1</blockquote>');const n=t.split(/\n\n+/);return t=n.map(e=>{const t=e.trim();return t.startsWith("<h")||t.startsWith("<ul")||t.startsWith("<ol")||t.startsWith("<pre")||t.startsWith("<blockquote")||t.startsWith("<hr")||t.startsWith("<p")?t:t?`<p class="chat-p">${t}</p>`:""}).filter(Boolean).join(""),t=t.replace(/<p([^>]*)>([\s\S]*?)<\/p>/g,(e,t,n)=>`<p${t}>${n.trim().replace(/\n/g,"<br>")}</p>`),t=t.replace(/<br\s*\/?>\s*(<\/?(ul|ol|li|p|h[1-6]|pre|blockquote|hr))/gi,"$1"),t=t.replace(/(<\/(ul|ol|li|p|h[1-6]|pre|blockquote)>)\s*<br\s*\/?>/gi,"$1"),t=t.replace(/<p[^>]*>\s*<\/p>/g,""),t=t.replace(/(<br\s*\/?>){2,}/g,"<br>"),t=function(e){return e&&"string"==typeof e?e.replace(/>([^<]*)</g,(e,t)=>">"+xp(t)+"<"):""}(t),t}function xp(e){return e&&"string"==typeof e?e.replace(yp,"$1 $2").replace(/(^|[\s(\["'])(https?:\/\/[^\s<>"]*(?:\n[^\s<>"]*)*)/g,(e,t,n)=>{let s=n.replace(/\s+/g,"").trim().replace(/[.,;:!?)\]]+$/,""),r="";const o=s.match(vp);o&&(r=o[1],s=s.replace(vp,""));const a=s.match(bp);return a&&(r=a[2],s=s.replace(bp,"$1")),s?`${t??""}<a href="${s.replace(/"/g,""")}" target="_blank" rel="noopener noreferrer">${s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}</a>${r?" "+r:""}`:e}):""}const{entries:Ep,setPrototypeOf:Tp,isFrozen:Ip,getPrototypeOf:Cp,getOwnPropertyDescriptor:Pp}=Object;let{freeze:Rp,seal:Ap,create:Np}=Object,{apply:Op,construct:jp}="undefined"!=typeof Reflect&&Reflect;Rp||(Rp=function(e){return e}),Ap||(Ap=function(e){return e}),Op||(Op=function(e,t){for(var n=arguments.length,s=new Array(n>2?n-2:0),r=2;r<n;r++)s[r-2]=arguments[r];return e.apply(t,s)}),jp||(jp=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return new e(...n)});const Mp=Xp(Array.prototype.forEach),zp=Xp(Array.prototype.lastIndexOf),Dp=Xp(Array.prototype.pop),Lp=Xp(Array.prototype.push),Up=Xp(Array.prototype.splice),qp=Xp(String.prototype.toLowerCase),Fp=Xp(String.prototype.toString),Hp=Xp(String.prototype.match),Vp=Xp(String.prototype.replace),Wp=Xp(String.prototype.indexOf),Bp=Xp(String.prototype.trim),Zp=Xp(Object.prototype.hasOwnProperty),Gp=Xp(RegExp.prototype.test),Kp=(Jp=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return jp(Jp,t)});var Jp;function Xp(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,s=new Array(n>1?n-1:0),r=1;r<n;r++)s[r-1]=arguments[r];return Op(e,t,s)}}function Yp(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:qp;Tp&&Tp(e,null);let s=t.length;for(;s--;){let r=t[s];if("string"==typeof r){const e=n(r);e!==r&&(Ip(t)||(t[s]=e),r=e)}e[r]=!0}return e}function Qp(e){for(let t=0;t<e.length;t++)Zp(e,t)||(e[t]=null);return e}function ef(e){const t=Np(null);for(const[n,s]of Ep(e))Zp(e,n)&&(Array.isArray(s)?t[n]=Qp(s):s&&"object"==typeof s&&s.constructor===Object?t[n]=ef(s):t[n]=s);return t}function tf(e,t){for(;null!==e;){const n=Pp(e,t);if(n){if(n.get)return Xp(n.get);if("function"==typeof n.value)return Xp(n.value)}e=Cp(e)}return function(){return null}}const nf=Rp(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),sf=Rp(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),rf=Rp(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),of=Rp(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),af=Rp(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),cf=Rp(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),lf=Rp(["#text"]),uf=Rp(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),df=Rp(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),hf=Rp(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),pf=Rp(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),ff=Ap(/\{\{[\w\W]*|[\w\W]*\}\}/gm),mf=Ap(/<%[\w\W]*|[\w\W]*%>/gm),gf=Ap(/\$\{[\w\W]*/gm),_f=Ap(/^data-[\-\w.\u00B7-\uFFFF]+$/),yf=Ap(/^aria-[\-\w]+$/),wf=Ap(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),vf=Ap(/^(?:\w+script|data):/i),bf=Ap(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),$f=Ap(/^html$/i),kf=Ap(/^[a-z][.\w]*(-[.\w]+)+$/i);var Sf=Object.freeze({__proto__:null,ARIA_ATTR:yf,ATTR_WHITESPACE:bf,CUSTOM_ELEMENT:kf,DATA_ATTR:_f,DOCTYPE_NAME:$f,ERB_EXPR:mf,IS_ALLOWED_URI:wf,IS_SCRIPT_OR_DATA:vf,MUSTACHE_EXPR:ff,TMPLIT_EXPR:gf});const xf=function(){return"undefined"==typeof window?null:window};var Ef=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:xf();const n=t=>e(t);if(n.version="3.3.1",n.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return n.isSupported=!1,n;let{document:s}=t;const r=s,o=r.currentScript,{DocumentFragment:a,HTMLTemplateElement:i,Node:c,Element:l,NodeFilter:u,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:h,DOMParser:p,trustedTypes:f}=t,m=l.prototype,g=tf(m,"cloneNode"),_=tf(m,"remove"),y=tf(m,"nextSibling"),w=tf(m,"childNodes"),v=tf(m,"parentNode");if("function"==typeof i){const e=s.createElement("template");e.content&&e.content.ownerDocument&&(s=e.content.ownerDocument)}let b,$="";const{implementation:k,createNodeIterator:S,createDocumentFragment:x,getElementsByTagName:E}=s,{importNode:T}=r;let I={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};n.isSupported="function"==typeof Ep&&"function"==typeof v&&k&&void 0!==k.createHTMLDocument;const{MUSTACHE_EXPR:C,ERB_EXPR:P,TMPLIT_EXPR:R,DATA_ATTR:A,ARIA_ATTR:N,IS_SCRIPT_OR_DATA:O,ATTR_WHITESPACE:j,CUSTOM_ELEMENT:M}=Sf;let{IS_ALLOWED_URI:z}=Sf,D=null;const L=Yp({},[...nf,...sf,...rf,...af,...lf]);let U=null;const q=Yp({},[...uf,...df,...hf,...pf]);let F=Object.seal(Np(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),H=null,V=null;const W=Object.seal(Np(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let B=!0,Z=!0,G=!1,K=!0,J=!1,X=!0,Y=!1,Q=!1,ee=!1,te=!1,ne=!1,se=!1,re=!0,oe=!1,ae=!0,ie=!1,ce={},le=null;const ue=Yp({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let de=null;const he=Yp({},["audio","video","img","source","image","track"]);let pe=null;const fe=Yp({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),me="http://www.w3.org/1998/Math/MathML",ge="http://www.w3.org/2000/svg",_e="http://www.w3.org/1999/xhtml";let ye=_e,we=!1,ve=null;const be=Yp({},[me,ge,_e],Fp);let $e=Yp({},["mi","mo","mn","ms","mtext"]),ke=Yp({},["annotation-xml"]);const Se=Yp({},["title","style","font","a","script"]);let xe=null;const Ee=["application/xhtml+xml","text/html"];let Te=null,Ie=null;const Ce=s.createElement("form"),Pe=function(e){return e instanceof RegExp||e instanceof Function},Re=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!Ie||Ie!==e){if(e&&"object"==typeof e||(e={}),e=ef(e),xe=-1===Ee.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Te="application/xhtml+xml"===xe?Fp:qp,D=Zp(e,"ALLOWED_TAGS")?Yp({},e.ALLOWED_TAGS,Te):L,U=Zp(e,"ALLOWED_ATTR")?Yp({},e.ALLOWED_ATTR,Te):q,ve=Zp(e,"ALLOWED_NAMESPACES")?Yp({},e.ALLOWED_NAMESPACES,Fp):be,pe=Zp(e,"ADD_URI_SAFE_ATTR")?Yp(ef(fe),e.ADD_URI_SAFE_ATTR,Te):fe,de=Zp(e,"ADD_DATA_URI_TAGS")?Yp(ef(he),e.ADD_DATA_URI_TAGS,Te):he,le=Zp(e,"FORBID_CONTENTS")?Yp({},e.FORBID_CONTENTS,Te):ue,H=Zp(e,"FORBID_TAGS")?Yp({},e.FORBID_TAGS,Te):ef({}),V=Zp(e,"FORBID_ATTR")?Yp({},e.FORBID_ATTR,Te):ef({}),ce=!!Zp(e,"USE_PROFILES")&&e.USE_PROFILES,B=!1!==e.ALLOW_ARIA_ATTR,Z=!1!==e.ALLOW_DATA_ATTR,G=e.ALLOW_UNKNOWN_PROTOCOLS||!1,K=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,J=e.SAFE_FOR_TEMPLATES||!1,X=!1!==e.SAFE_FOR_XML,Y=e.WHOLE_DOCUMENT||!1,te=e.RETURN_DOM||!1,ne=e.RETURN_DOM_FRAGMENT||!1,se=e.RETURN_TRUSTED_TYPE||!1,ee=e.FORCE_BODY||!1,re=!1!==e.SANITIZE_DOM,oe=e.SANITIZE_NAMED_PROPS||!1,ae=!1!==e.KEEP_CONTENT,ie=e.IN_PLACE||!1,z=e.ALLOWED_URI_REGEXP||wf,ye=e.NAMESPACE||_e,$e=e.MATHML_TEXT_INTEGRATION_POINTS||$e,ke=e.HTML_INTEGRATION_POINTS||ke,F=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Pe(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(F.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Pe(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(F.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(F.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),J&&(Z=!1),ne&&(te=!0),ce&&(D=Yp({},lf),U=[],!0===ce.html&&(Yp(D,nf),Yp(U,uf)),!0===ce.svg&&(Yp(D,sf),Yp(U,df),Yp(U,pf)),!0===ce.svgFilters&&(Yp(D,rf),Yp(U,df),Yp(U,pf)),!0===ce.mathMl&&(Yp(D,af),Yp(U,hf),Yp(U,pf))),e.ADD_TAGS&&("function"==typeof e.ADD_TAGS?W.tagCheck=e.ADD_TAGS:(D===L&&(D=ef(D)),Yp(D,e.ADD_TAGS,Te))),e.ADD_ATTR&&("function"==typeof e.ADD_ATTR?W.attributeCheck=e.ADD_ATTR:(U===q&&(U=ef(U)),Yp(U,e.ADD_ATTR,Te))),e.ADD_URI_SAFE_ATTR&&Yp(pe,e.ADD_URI_SAFE_ATTR,Te),e.FORBID_CONTENTS&&(le===ue&&(le=ef(le)),Yp(le,e.FORBID_CONTENTS,Te)),e.ADD_FORBID_CONTENTS&&(le===ue&&(le=ef(le)),Yp(le,e.ADD_FORBID_CONTENTS,Te)),ae&&(D["#text"]=!0),Y&&Yp(D,["html","head","body"]),D.table&&(Yp(D,["tbody"]),delete H.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Kp('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Kp('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');b=e.TRUSTED_TYPES_POLICY,$=b.createHTML("")}else void 0===b&&(b=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const s="data-tt-policy-suffix";t&&t.hasAttribute(s)&&(n=t.getAttribute(s));const r="dompurify"+(n?"#"+n:"");try{return e.createPolicy(r,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+r+" could not be created."),null}}(f,o)),null!==b&&"string"==typeof $&&($=b.createHTML(""));Rp&&Rp(e),Ie=e}},Ae=Yp({},[...sf,...rf,...of]),Ne=Yp({},[...af,...cf]),Oe=function(e){Lp(n.removed,{element:e});try{v(e).removeChild(e)}catch(t){_(e)}},je=function(e,t){try{Lp(n.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){Lp(n.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(te||ne)try{Oe(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Me=function(e){let t=null,n=null;if(ee)e="<remove></remove>"+e;else{const t=Hp(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===xe&&ye===_e&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const r=b?b.createHTML(e):e;if(ye===_e)try{t=(new p).parseFromString(r,xe)}catch(e){}if(!t||!t.documentElement){t=k.createDocument(ye,"template",null);try{t.documentElement.innerHTML=we?$:r}catch(e){}}const o=t.body||t.documentElement;return e&&n&&o.insertBefore(s.createTextNode(n),o.childNodes[0]||null),ye===_e?E.call(t,Y?"html":"body")[0]:Y?t.documentElement:o},ze=function(e){return S.call(e.ownerDocument||e,e,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},De=function(e){return e instanceof h&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof d)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},Le=function(e){return"function"==typeof c&&e instanceof c};function Ue(e,t,s){Mp(e,e=>{e.call(n,t,s,Ie)})}const qe=function(e){let t=null;if(Ue(I.beforeSanitizeElements,e,null),De(e))return Oe(e),!0;const s=Te(e.nodeName);if(Ue(I.uponSanitizeElement,e,{tagName:s,allowedTags:D}),X&&e.hasChildNodes()&&!Le(e.firstElementChild)&&Gp(/<[/\w!]/g,e.innerHTML)&&Gp(/<[/\w!]/g,e.textContent))return Oe(e),!0;if(7===e.nodeType)return Oe(e),!0;if(X&&8===e.nodeType&&Gp(/<[/\w]/g,e.data))return Oe(e),!0;if(!(W.tagCheck instanceof Function&&W.tagCheck(s))&&(!D[s]||H[s])){if(!H[s]&&He(s)){if(F.tagNameCheck instanceof RegExp&&Gp(F.tagNameCheck,s))return!1;if(F.tagNameCheck instanceof Function&&F.tagNameCheck(s))return!1}if(ae&&!le[s]){const t=v(e)||e.parentNode,n=w(e)||e.childNodes;if(n&&t)for(let s=n.length-1;s>=0;--s){const r=g(n[s],!0);r.__removalCount=(e.__removalCount||0)+1,t.insertBefore(r,y(e))}}return Oe(e),!0}return e instanceof l&&!function(e){let t=v(e);t&&t.tagName||(t={namespaceURI:ye,tagName:"template"});const n=qp(e.tagName),s=qp(t.tagName);return!!ve[e.namespaceURI]&&(e.namespaceURI===ge?t.namespaceURI===_e?"svg"===n:t.namespaceURI===me?"svg"===n&&("annotation-xml"===s||$e[s]):Boolean(Ae[n]):e.namespaceURI===me?t.namespaceURI===_e?"math"===n:t.namespaceURI===ge?"math"===n&&ke[s]:Boolean(Ne[n]):e.namespaceURI===_e?!(t.namespaceURI===ge&&!ke[s])&&!(t.namespaceURI===me&&!$e[s])&&!Ne[n]&&(Se[n]||!Ae[n]):!("application/xhtml+xml"!==xe||!ve[e.namespaceURI]))}(e)?(Oe(e),!0):"noscript"!==s&&"noembed"!==s&&"noframes"!==s||!Gp(/<\/no(script|embed|frames)/i,e.innerHTML)?(J&&3===e.nodeType&&(t=e.textContent,Mp([C,P,R],e=>{t=Vp(t,e," ")}),e.textContent!==t&&(Lp(n.removed,{element:e.cloneNode()}),e.textContent=t)),Ue(I.afterSanitizeElements,e,null),!1):(Oe(e),!0)},Fe=function(e,t,n){if(re&&("id"===t||"name"===t)&&(n in s||n in Ce))return!1;if(Z&&!V[t]&&Gp(A,t));else if(B&&Gp(N,t));else if(W.attributeCheck instanceof Function&&W.attributeCheck(t,e));else if(!U[t]||V[t]){if(!(He(e)&&(F.tagNameCheck instanceof RegExp&&Gp(F.tagNameCheck,e)||F.tagNameCheck instanceof Function&&F.tagNameCheck(e))&&(F.attributeNameCheck instanceof RegExp&&Gp(F.attributeNameCheck,t)||F.attributeNameCheck instanceof Function&&F.attributeNameCheck(t,e))||"is"===t&&F.allowCustomizedBuiltInElements&&(F.tagNameCheck instanceof RegExp&&Gp(F.tagNameCheck,n)||F.tagNameCheck instanceof Function&&F.tagNameCheck(n))))return!1}else if(pe[t]);else if(Gp(z,Vp(n,j,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Wp(n,"data:")||!de[e])if(G&&!Gp(O,Vp(n,j,"")));else if(n)return!1;return!0},He=function(e){return"annotation-xml"!==e&&Hp(e,M)},Ve=function(e){Ue(I.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||De(e))return;const s={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:U,forceKeepAttr:void 0};let r=t.length;for(;r--;){const o=t[r],{name:a,namespaceURI:i,value:c}=o,l=Te(a),u=c;let d="value"===a?u:Bp(u);if(s.attrName=l,s.attrValue=d,s.keepAttr=!0,s.forceKeepAttr=void 0,Ue(I.uponSanitizeAttribute,e,s),d=s.attrValue,!oe||"id"!==l&&"name"!==l||(je(a,e),d="user-content-"+d),X&&Gp(/((--!?|])>)|<\/(style|title|textarea)/i,d)){je(a,e);continue}if("attributename"===l&&Hp(d,"href")){je(a,e);continue}if(s.forceKeepAttr)continue;if(!s.keepAttr){je(a,e);continue}if(!K&&Gp(/\/>/i,d)){je(a,e);continue}J&&Mp([C,P,R],e=>{d=Vp(d,e," ")});const h=Te(e.nodeName);if(Fe(h,l,d)){if(b&&"object"==typeof f&&"function"==typeof f.getAttributeType)if(i);else switch(f.getAttributeType(h,l)){case"TrustedHTML":d=b.createHTML(d);break;case"TrustedScriptURL":d=b.createScriptURL(d)}if(d!==u)try{i?e.setAttributeNS(i,a,d):e.setAttribute(a,d),De(e)?Oe(e):Dp(n.removed)}catch(t){je(a,e)}}else je(a,e)}Ue(I.afterSanitizeAttributes,e,null)},We=function e(t){let n=null;const s=ze(t);for(Ue(I.beforeSanitizeShadowDOM,t,null);n=s.nextNode();)Ue(I.uponSanitizeShadowNode,n,null),qe(n),Ve(n),n.content instanceof a&&e(n.content);Ue(I.afterSanitizeShadowDOM,t,null)};return n.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=null,o=null,i=null,l=null;if(we=!e,we&&(e="\x3c!--\x3e"),"string"!=typeof e&&!Le(e)){if("function"!=typeof e.toString)throw Kp("toString is not a function");if("string"!=typeof(e=e.toString()))throw Kp("dirty is not a string, aborting")}if(!n.isSupported)return e;if(Q||Re(t),n.removed=[],"string"==typeof e&&(ie=!1),ie){if(e.nodeName){const t=Te(e.nodeName);if(!D[t]||H[t])throw Kp("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof c)s=Me("\x3c!----\x3e"),o=s.ownerDocument.importNode(e,!0),1===o.nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?s=o:s.appendChild(o);else{if(!te&&!J&&!Y&&-1===e.indexOf("<"))return b&&se?b.createHTML(e):e;if(s=Me(e),!s)return te?null:se?$:""}s&&ee&&Oe(s.firstChild);const u=ze(ie?e:s);for(;i=u.nextNode();)qe(i),Ve(i),i.content instanceof a&&We(i.content);if(ie)return e;if(te){if(ne)for(l=x.call(s.ownerDocument);s.firstChild;)l.appendChild(s.firstChild);else l=s;return(U.shadowroot||U.shadowrootmode)&&(l=T.call(r,l,!0)),l}let d=Y?s.outerHTML:s.innerHTML;return Y&&D["!doctype"]&&s.ownerDocument&&s.ownerDocument.doctype&&s.ownerDocument.doctype.name&&Gp($f,s.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+s.ownerDocument.doctype.name+">\n"+d),J&&Mp([C,P,R],e=>{d=Vp(d,e," ")}),b&&se?b.createHTML(d):d},n.setConfig=function(){Re(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Q=!0},n.clearConfig=function(){Ie=null,Q=!1},n.isValidAttribute=function(e,t,n){Ie||Re({});const s=Te(e),r=Te(t);return Fe(s,r,n)},n.addHook=function(e,t){"function"==typeof t&&Lp(I[e],t)},n.removeHook=function(e,t){if(void 0!==t){const n=zp(I[e],t);return-1===n?void 0:Up(I[e],n,1)[0]}return Dp(I[e])},n.removeHooks=function(e){I[e]=[]},n.removeAllHooks=function(){I={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},n}();const Tf=e=>Ef.sanitize(e,{ALLOWED_TAGS:["section","div","h1","h2","h3","h4","h5","h6","p","span","strong","em","b","i","u","s","mark","small","sub","sup","a","br","ul","ol","li","dl","dt","dd","blockquote","code","pre","table","thead","tbody","tr","th","td","hr","address","time"],ALLOWED_ATTR:["style","class","id","href","datetime","target","rel"],ALLOW_DATA_ATTR:!1,FORBID_TAGS:["script","object","embed","iframe","form","fieldset","legend","label","input","textarea","select","option","button","details","summary","progress","meter"],FORBID_ATTR:["onerror","onload","onclick","onmouseover","onfocus","onblur"]}),If=e=>/<[a-z][\s\S]*>/i.test(e),Cf={MAX_HEIGHT:200,FOCUS_DELAY:100,STOP_DEBOUNCE:500};var Pf=n(6942),Rf=n.n(Pf);const Af=window.React,Nf=(...e)=>e.filter((e,t,n)=>Boolean(e)&&""!==e.trim()&&n.indexOf(e)===t).join(" ").trim();var Of={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const jf=(0,Af.forwardRef)(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:s,className:r="",children:o,iconNode:a,...i},c)=>(0,Af.createElement)("svg",{ref:c,...Of,width:t,height:t,stroke:e,strokeWidth:s?24*Number(n)/Number(t):n,className:Nf("lucide",r),...i},[...a.map(([e,t])=>(0,Af.createElement)(e,t)),...Array.isArray(o)?o:[o]])),Mf=(e,t)=>{const n=(0,Af.forwardRef)(({className:n,...s},r)=>{return(0,Af.createElement)(jf,{ref:r,iconNode:t,className:Nf(`lucide-${o=e,o.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,n),...s});var o});return n.displayName=`${e}`,n},zf=Mf("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]),Df=Mf("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]),Lf=Mf("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]),Uf=Mf("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);function qf(e){const t={"nfd-agents/get-global-styles":{title:(0,Wh.__)("Reading Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Fetching current color palette and typography settings","wp-module-ai-chat")},"nfd-agents/update-global-palette":{title:(0,Wh.__)("Updating Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Applying new colors to global styles","wp-module-ai-chat")},"newfold-agents/get-global-styles":{title:(0,Wh.__)("Reading Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Fetching current color palette and typography settings","wp-module-ai-chat")},"newfold-agents/update-global-palette":{title:(0,Wh.__)("Updating Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Applying new colors to global styles","wp-module-ai-chat")},"blu/get-global-styles":{title:(0,Wh.__)("Reading Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Fetching current color palette and typography settings","wp-module-ai-chat")},"blu/update-global-palette":{title:(0,Wh.__)("Updating Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Applying new colors to global styles","wp-module-ai-chat")},"blu-get-global-styles":{title:(0,Wh.__)("Reading Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Fetching current color palette and typography settings","wp-module-ai-chat")},"blu/get-active-global-styles":{title:(0,Wh.__)("Reading Active Styles","wp-module-ai-chat"),description:(0,Wh.__)("Fetching active global styles","wp-module-ai-chat")},"blu-get-active-global-styles":{title:(0,Wh.__)("Reading Active Styles","wp-module-ai-chat"),description:(0,Wh.__)("Fetching active global styles","wp-module-ai-chat")},"blu/get-active-global-styles-id":{title:(0,Wh.__)("Getting Styles ID","wp-module-ai-chat"),description:(0,Wh.__)("Fetching active styles ID","wp-module-ai-chat")},"blu-get-active-global-styles-id":{title:(0,Wh.__)("Getting Styles ID","wp-module-ai-chat"),description:(0,Wh.__)("Fetching active styles ID","wp-module-ai-chat")},"blu/update-global-styles":{title:(0,Wh.__)("Updating Site Styles","wp-module-ai-chat"),description:(0,Wh.__)("Applying new styles to global styles","wp-module-ai-chat")},"blu-update-global-styles":{title:(0,Wh.__)("Updating Site Styles","wp-module-ai-chat"),description:(0,Wh.__)("Applying new styles to global styles","wp-module-ai-chat")},"blu-update-global-palette":{title:(0,Wh.__)("Updating Site Colors","wp-module-ai-chat"),description:(0,Wh.__)("Applying new colors to global styles","wp-module-ai-chat")},"blu/edit-block":{title:(0,Wh.__)("Editing Block Content","wp-module-ai-chat"),description:(0,Wh.__)("Editing block content","wp-module-ai-chat")},"blu-edit-block":{title:(0,Wh.__)("Editing Block Content","wp-module-ai-chat"),description:(0,Wh.__)("Editing block content","wp-module-ai-chat")},"blu/add-section":{title:(0,Wh.__)("Adding New Section","wp-module-ai-chat"),description:(0,Wh.__)("Adding new section","wp-module-ai-chat")},"blu-add-section":{title:(0,Wh.__)("Adding New Section","wp-module-ai-chat"),description:(0,Wh.__)("Adding new section","wp-module-ai-chat")},"blu/delete-block":{title:(0,Wh.__)("Removing Block","wp-module-ai-chat"),description:(0,Wh.__)("Removing block","wp-module-ai-chat")},"blu-delete-block":{title:(0,Wh.__)("Removing Block","wp-module-ai-chat"),description:(0,Wh.__)("Removing block","wp-module-ai-chat")},"blu/move-block":{title:(0,Wh.__)("Moving Block","wp-module-ai-chat"),description:(0,Wh.__)("Moving block","wp-module-ai-chat")},"blu-move-block":{title:(0,Wh.__)("Moving Block","wp-module-ai-chat"),description:(0,Wh.__)("Moving block","wp-module-ai-chat")},"mcp-adapter-discover-abilities":{title:(0,Wh.__)("Discovering Actions","wp-module-ai-chat"),description:(0,Wh.__)("Finding available WordPress abilities","wp-module-ai-chat")},"mcp-adapter-get-ability-info":{title:(0,Wh.__)("Getting Ability Info","wp-module-ai-chat"),description:(0,Wh.__)("Fetching ability details","wp-module-ai-chat")},"mcp-adapter-execute-ability":{title:(0,Wh.__)("Executing Action","wp-module-ai-chat"),description:(0,Wh.__)("Running WordPress ability","wp-module-ai-chat")}};return t[e]?t[e]:"preparing-changes"===e?{title:(0,Wh.__)("Preparing changes","wp-module-ai-chat"),description:(0,Wh.__)("Building block markup","wp-module-ai-chat")}:{title:e?.replace(/[-_\/]/g," ").replace(/\b\w/g,e=>e.toUpperCase())||(0,Wh.__)("Executing","wp-module-ai-chat"),description:(0,Wh.__)("Running action","wp-module-ai-chat")}}function Ff(e,t={}){if("mcp-adapter-execute-ability"===e){const e=t?.ability_name||"unknown",n=qf(e);let s=null;if(("nfd-agents/update-global-palette"===e||"newfold-agents/update-global-palette"===e||"blu/update-global-palette"===e||"blu-update-global-palette"===e||"blu/update-global-styles"===e||"blu-update-global-styles"===e)&&t?.parameters?.colors){const e=t.parameters.colors.length;s=`${e} color${1!==e?"s":""}`}return{...n,params:s}}return qf(e)}const Hf=window.ReactJSXRuntime,Vf=({tool:e,isError:t,result:n})=>{const s=Ff(e.name,e.arguments),r=((e,t)=>{if(!e||e.isError)return n=e?.error,null==n?null:"string"==typeof n?n:"number"==typeof n||"boolean"==typeof n?String(n):null;var n;try{let n=e.result;if(Array.isArray(n)&&n.length>0&&n[0].text?n=JSON.parse(n[0].text):"string"==typeof n&&(n=JSON.parse(n)),!n||"object"!=typeof n)return null;if(t?.includes("update")){if(n.updatedColors&&Array.isArray(n.updatedColors)){const e=n.updatedColors;return e.length<=3?e.map(e=>`${e.name||e.slug}: ${e.color}`).join(", "):`${e.length} colors updated`}if(n.message&&"string"==typeof n.message)return n.message}if(t?.includes("edit-block")||t?.includes("edit_block"))return n.message&&"string"==typeof n.message?n.message:n.success?"Block updated":"Update failed";if(t?.includes("add-section")||t?.includes("add_section"))return n.message&&"string"==typeof n.message?n.message:n.success?"Section added":"Add failed";if(t?.includes("delete-block")||t?.includes("delete_block"))return n.message&&"string"==typeof n.message?n.message:n.success?"Block removed":"Delete failed";if(t?.includes("move-block")||t?.includes("move_block"))return n.message&&"string"==typeof n.message?n.message:n.success?"Block moved":"Move failed";if(t?.includes("get")||t?.includes("read")){if(n.color?.palette){const e=n.color.palette,t=e.custom?.length||0,s=e.theme?.length||0;if(t||s)return`Found ${t+s} colors`}if(n.typography){const e=n.typography.fontFamilies?.length||0,t=n.typography.fontSizes?.length||0,s=[];if(e&&s.push(`${e} font families`),t&&s.push(`${t} sizes`),s.length)return s.join(", ")}if(n.message&&"string"==typeof n.message)return n.message}return n.id&&t?.includes("id")?`ID: ${n.id}`:null}catch{return null}})(n,e.name);return(0,Hf.jsxs)("div",{className:Rf()("nfd-ai-chat-tool-execution__item",{"nfd-ai-chat-tool-execution__item--complete":!t,"nfd-ai-chat-tool-execution__item--error":t}),children:[(0,Hf.jsxs)("div",{className:"nfd-ai-chat-tool-execution__item-header",children:[t?(0,Hf.jsx)(zf,{className:"nfd-ai-chat-tool-execution__icon nfd-ai-chat-tool-execution__icon--error",size:12}):(0,Hf.jsx)(Df,{className:"nfd-ai-chat-tool-execution__icon nfd-ai-chat-tool-execution__icon--success",size:12}),(0,Hf.jsx)("span",{className:"nfd-ai-chat-tool-execution__item-title",children:s.title}),s.params&&(0,Hf.jsx)("span",{className:"nfd-ai-chat-tool-execution__item-params",children:s.params})]}),r&&(0,Hf.jsx)("div",{className:"nfd-ai-chat-tool-execution__item-summary",children:r})]})},Wf=({executedTools:e=[],toolResults:t=[]})=>{const[n,s]=(0,Lh.useState)(!1);if(!e||0===e.length)return null;const r=new Map;t&&Array.isArray(t)&&t.forEach(e=>{e.id&&r.set(e.id,e)});const o=e.some(e=>e.isError),a=e.length;return(0,Hf.jsxs)("div",{className:Rf()("nfd-ai-chat-tool-execution",{"nfd-ai-chat-tool-execution--collapsed":!n}),children:[(0,Hf.jsxs)("button",{type:"button",className:"nfd-ai-chat-tool-execution__header",onClick:()=>s(!n),"aria-expanded":n?"true":"false",children:[n?(0,Hf.jsx)(Lf,{className:"nfd-ai-chat-tool-execution__chevron",size:12}):(0,Hf.jsx)(Uf,{className:"nfd-ai-chat-tool-execution__chevron",size:12}),(0,Hf.jsx)("span",{children:o?(0,Wh.__)("Some actions failed","wp-module-ai-chat"):(0,Wh.__)("Actions completed","wp-module-ai-chat")}),(0,Hf.jsxs)("span",{className:"nfd-ai-chat-tool-execution__header-count",children:["(",a,")"]})]}),n&&(0,Hf.jsx)("div",{className:"nfd-ai-chat-tool-execution__list",children:e.map((e,t)=>(0,Hf.jsx)(Vf,{tool:e,isError:e.isError,result:r.get(e.id)},e.id||`tool-${t}`))})]})},Bf=({message:e,type:t="assistant",animateTyping:n=!1,onContentGrow:s,executedTools:r=[],toolResults:o=[]})=>{const a="approval_request"===t?"assistant":t,i="user"===a,c=(e||"").length,[l,u]=(0,Lh.useState)(()=>n?0:c),d=(0,Lh.useRef)(null);(0,Lh.useEffect)(()=>{if(n)return d.current=setInterval(()=>{u(e=>e>=c?(d.current&&(clearInterval(d.current),d.current=null),e):Math.min(e+2,c))},35),()=>{d.current&&(clearInterval(d.current),d.current=null)};u(c)},[n,c]);const h=(0,Lh.useRef)(0);(0,Lh.useEffect)(()=>{if(!s||!n||0===l)return;const e=Date.now();e-h.current<80||(h.current=e,s())},[l,n,s]);const p=n?(e||"").slice(0,l):e||"",{content:f,isRichContent:m}=(0,Lh.useMemo)(()=>{if(!p)return{content:"",isRichContent:!1};const e=(t=p)&&"string"==typeof t?t.replace(/\\"/g,'"').replace(/\\'/g,"'"):t;var t;if(i)return{content:e,isRichContent:!1};if(If(e))return{content:Tf(e),isRichContent:!0};if(kp(e)){const t=Sp(e);return{content:Tf(t),isRichContent:!0}}const n=xp(e);if(n!==e){const e=n.replace(/\n/g,"<br>");return{content:Tf(e),isRichContent:!0}}return{content:e,isRichContent:!1}},[p,i]);if(!(f||r&&0!==r.length))return null;const g=Rf()("nfd-ai-chat-message",`nfd-ai-chat-message--${a}`);return(0,Hf.jsxs)("div",{className:g,children:[f&&(m?(0,Hf.jsx)(Hf.Fragment,{children:(0,Hf.jsx)("div",{className:"nfd-ai-chat-message__content nfd-ai-chat-message__content--rich",dangerouslySetInnerHTML:{__html:f}})}):(0,Hf.jsx)("div",{className:"nfd-ai-chat-message__content nfd-ai-chat-message__content--pre-wrap",style:{whiteSpace:"pre-wrap"},children:f})),r&&r.length>0&&(0,Hf.jsx)(Wf,{executedTools:r,toolResults:o})]})},Zf=({message:e,className:t=""})=>(0,Hf.jsxs)("div",{className:`nfd-ai-chat-error-alert ${t}`,children:[(0,Hf.jsx)("div",{className:"nfd-ai-chat-error-alert__icon",children:(0,Hf.jsx)(zf,{width:16,height:16})}),(0,Hf.jsx)("div",{className:"nfd-ai-chat-error-alert__content",children:(0,Hf.jsx)("div",{className:"nfd-ai-chat-error-alert__message",children:e})})]}),Gf=Mf("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),Kf=Mf("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]),Jf={[sp.PROCESSING]:(0,Wh.__)("Processing…","wp-module-ai-chat"),[sp.CONNECTING]:(0,Wh.__)("Getting your site ready…","wp-module-ai-chat"),[sp.WS_CONNECTING]:(0,Wh.__)("Connecting…","wp-module-ai-chat"),[sp.TOOL_CALL]:(0,Wh.__)("Looking this up…","wp-module-ai-chat"),[sp.WORKING]:(0,Wh.__)("Almost there…","wp-module-ai-chat"),[sp.RECEIVED]:(0,Wh.__)("Message received","wp-module-ai-chat"),[sp.GENERATING]:(0,Wh.__)("Thinking…","wp-module-ai-chat"),[sp.SUMMARIZING]:(0,Wh.__)("Summarizing results","wp-module-ai-chat"),[sp.COMPLETED]:(0,Wh.__)("Processing","wp-module-ai-chat"),[sp.FAILED]:(0,Wh.__)("Error occurred","wp-module-ai-chat")},Xf=({tool:e,isActive:t,progress:n,isComplete:s,isError:r})=>{const o=Ff(e.name,e.arguments);return(0,Hf.jsxs)("div",{className:Rf()("nfd-ai-chat-tool-execution__item",{"nfd-ai-chat-tool-execution__item--active":t,"nfd-ai-chat-tool-execution__item--complete":s,"nfd-ai-chat-tool-execution__item--error":r}),children:[(0,Hf.jsxs)("div",{className:"nfd-ai-chat-tool-execution__item-header",children:[r?(0,Hf.jsx)(zf,{className:"nfd-ai-chat-tool-execution__icon nfd-ai-chat-tool-execution__icon--error",size:12}):s?(0,Hf.jsx)(Df,{className:"nfd-ai-chat-tool-execution__icon nfd-ai-chat-tool-execution__icon--success",size:12}):t?(0,Hf.jsx)(Gf,{className:"nfd-ai-chat-tool-execution__icon nfd-ai-chat-tool-execution__icon--active",size:12}):(0,Hf.jsx)(Kf,{className:"nfd-ai-chat-tool-execution__icon nfd-ai-chat-tool-execution__icon--pending",size:12}),(0,Hf.jsx)("span",{className:"nfd-ai-chat-tool-execution__item-title",children:o.title}),o.params&&(0,Hf.jsx)("span",{className:"nfd-ai-chat-tool-execution__item-params",children:o.params})]}),t&&n&&(0,Hf.jsx)("div",{className:"nfd-ai-chat-tool-execution__item-progress",children:n})]})},Yf=({status:e=null,activeToolCall:t=null,toolProgress:n=null,executedTools:s=[],pendingTools:r=[]})=>{const[o,a]=(0,Lh.useState)(!0),i=!!t,c=!i&&e===sp.SUMMARIZING&&s.length>0;(0,Lh.useEffect)(()=>{(i||c)&&a(!0)},[i,c]);const l=t||s.length>0||r.length>0,u=s.length+(t?1:0)+r.length;return l?(0,Hf.jsx)("div",{className:"nfd-ai-chat-message nfd-ai-chat-message--assistant",children:(0,Hf.jsx)("div",{className:"nfd-ai-chat-message__content",children:(0,Hf.jsxs)("div",{className:Rf()("nfd-ai-chat-tool-execution",{"nfd-ai-chat-tool-execution--collapsed":!o}),children:[(0,Hf.jsxs)("button",{type:"button",className:"nfd-ai-chat-tool-execution__header",onClick:()=>a(!o),"aria-expanded":o?"true":"false",children:[o?(0,Hf.jsx)(Lf,{className:"nfd-ai-chat-tool-execution__chevron",size:12}):(0,Hf.jsx)(Uf,{className:"nfd-ai-chat-tool-execution__chevron",size:12}),i?(0,Hf.jsxs)(Hf.Fragment,{children:[(0,Hf.jsx)("span",{children:(0,Wh.__)("Executing actions","wp-module-ai-chat")}),t.total>1&&(0,Hf.jsxs)("span",{className:"nfd-ai-chat-tool-execution__header-count",children:["(",t.index,"/",t.total,")"]})]}):c?(0,Hf.jsxs)(Hf.Fragment,{children:[(0,Hf.jsx)(Gf,{className:"nfd-ai-chat-tool-execution__icon nfd-ai-chat-tool-execution__icon--active",size:12}),(0,Hf.jsx)("span",{children:(0,Wh.__)("Processing","wp-module-ai-chat")}),(0,Hf.jsxs)("span",{className:"nfd-ai-chat-tool-execution__header-count",children:["(",s.length,")"]})]}):(0,Hf.jsxs)(Hf.Fragment,{children:[(0,Hf.jsx)("span",{children:(0,Wh.__)("Actions completed","wp-module-ai-chat")}),(0,Hf.jsxs)("span",{className:"nfd-ai-chat-tool-execution__header-count",children:["(",u,")"]})]})]}),o&&(0,Hf.jsxs)("div",{className:"nfd-ai-chat-tool-execution__list",children:[s.map((e,t)=>(0,Hf.jsx)(Xf,{tool:e,isActive:!1,isComplete:!e.isError,isError:e.isError,progress:null},e.id||`executed-${t}`)),t&&(0,Hf.jsx)(Xf,{tool:t,isActive:!0,isComplete:!1,isError:!1,progress:n},t.id||"active"),c&&(0,Hf.jsx)(Xf,{tool:{name:"preparing-changes"},isActive:!0,isComplete:!1,isError:!1,progress:null},"preparing"),r.map((e,t)=>(0,Hf.jsx)(Xf,{tool:e,isActive:!1,isComplete:!1,isError:!1,progress:null},e.id||`pending-${t}`))]})]})})}):(0,Hf.jsx)("div",{className:"nfd-ai-chat-message nfd-ai-chat-message--assistant",children:(0,Hf.jsx)("div",{className:"nfd-ai-chat-message__content",children:(0,Hf.jsxs)("div",{className:"nfd-ai-chat-typing-indicator",children:[(0,Hf.jsxs)("span",{className:"nfd-ai-chat-typing-indicator__dots","aria-hidden":"true",children:[(0,Hf.jsx)("span",{}),(0,Hf.jsx)("span",{}),(0,Hf.jsx)("span",{})]}),(0,Hf.jsx)("span",{className:"nfd-ai-chat-typing-indicator__text",children:Jf[e]??(0,Wh.__)("Thinking…","wp-module-ai-chat")})]})})})},Qf=({messages:e=[],isLoading:t=!1,error:n=null,status:s=null,activeToolCall:r=null,toolProgress:o=null,executedTools:a=[],pendingTools:i=[],onRetry:c,connectionFailed:l=!1,isConnectingOrReconnecting:u=!1,messageBubbleStyle:d="bubbles"})=>{const h=(0,Lh.useRef)(null),[p,f]=(0,Lh.useState)(0),m=(0,Lh.useCallback)(()=>{const e=h.current;e&&e.scrollTo({top:e.scrollHeight-e.clientHeight,behavior:"smooth"})},[]);(0,Lh.useEffect)(()=>{m()},[e,t,o,p,m]);const g=(0,Lh.useCallback)(()=>{f(e=>e+1)},[]),_=r||a.length>0||i.length>0,y=Rf()("nfd-ai-chat-messages",{"nfd-ai-chat-messages--minimal":"minimal"===d});return(0,Hf.jsxs)("div",{ref:h,className:y,children:[e.length>0&&e.map((t,n)=>{const s=n===e.length-1&&("assistant"===t.type||"assistant"===t.role);return(0,Hf.jsx)(Bf,{message:t.content,type:t.type,animateTyping:s&&!0===t.animateTyping,onContentGrow:s?g:void 0,executedTools:t.executedTools,toolResults:t.toolResults},t.id||n)}),u&&!l&&(0,Hf.jsx)("div",{className:"nfd-ai-chat-message nfd-ai-chat-message--assistant",children:(0,Hf.jsx)("div",{className:"nfd-ai-chat-message__content",children:(0,Hf.jsxs)("div",{className:"nfd-ai-chat-typing-indicator",children:[(0,Hf.jsxs)("span",{className:"nfd-ai-chat-typing-indicator__dots","aria-hidden":"true",children:[(0,Hf.jsx)("span",{}),(0,Hf.jsx)("span",{}),(0,Hf.jsx)("span",{})]}),(0,Hf.jsx)("span",{className:"nfd-ai-chat-typing-indicator__text",children:(0,Wh.__)("Connecting....","wp-module-ai-chat")})]})})}),n&&(0,Hf.jsx)(Zf,{message:n}),c&&(n||l)&&(0,Hf.jsx)("p",{className:"nfd-ai-chat-messages__retry",children:(0,Hf.jsx)("button",{type:"button",className:"nfd-ai-chat-messages__retry-button",onClick:c,children:(0,Wh.__)("Retry","wp-module-ai-chat")})}),t&&(0,Hf.jsx)(Yf,{status:s,activeToolCall:r,toolProgress:o,executedTools:_?a:[],pendingTools:i})]})},em=window.wp.components,tm=Mf("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]]),nm=Mf("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]),sm=({onSendMessage:e,onStopRequest:t,disabled:n=!1,showStopButton:s,placeholder:r,contextComponent:o=null,showTopBorder:a=!0})=>{const i=!0===s,[c,l]=(0,Lh.useState)(""),[u,d]=(0,Lh.useState)(!1),h=(0,Lh.useRef)(null),p=(0,Wh.__)("How can I help you today?","wp-module-ai-chat");(0,Lh.useEffect)(()=>{if(h.current){h.current.style.height="auto";const e=h.current.scrollHeight,t=Math.min(e,Cf.MAX_HEIGHT);h.current.style.height=`${t}px`,e>Cf.MAX_HEIGHT?h.current.style.overflowY="auto":h.current.style.overflowY="hidden"}},[c]),(0,Lh.useEffect)(()=>{!n&&h.current&&setTimeout(()=>{h.current.focus()},Cf.FOCUS_DELAY)},[n]);const f=(0,Lh.useCallback)(()=>{c.trim()&&!n&&(e(c),l(""),h.current&&(h.current.style.height="auto",h.current.style.overflowY="hidden",h.current.focus()))},[c,n,e]),m=(0,Lh.useCallback)(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),f())},[f]),g=(0,Lh.useCallback)(()=>{u||(d(!0),t&&t(),setTimeout(()=>{d(!1)},Cf.STOP_DEBOUNCE))},[u,t]),_=Rf()("nfd-ai-chat-input",{"nfd-ai-chat-input--no-top-border":!a});return(0,Hf.jsxs)("div",{className:_,children:[(0,Hf.jsxs)("div",{className:"nfd-ai-chat-input__container",children:[(0,Hf.jsx)("textarea",{name:"nfd-ai-chat-input",ref:h,value:c,onChange:e=>l(e.target.value),onKeyDown:m,placeholder:r||p,className:"nfd-ai-chat-input__textarea",rows:1,disabled:n}),(0,Hf.jsxs)("div",{className:"nfd-ai-chat-input__actions",children:[o,i?(0,Hf.jsx)(em.Button,{icon:(0,Hf.jsx)(tm,{width:16,height:16}),label:(0,Wh.__)("Stop generating","wp-module-ai-chat"),onClick:g,className:"nfd-ai-chat-input__stop",disabled:u,"aria-busy":u}):(0,Hf.jsx)(em.Button,{icon:(0,Hf.jsx)(nm,{width:16,height:16}),label:(0,Wh.__)("Send message","wp-module-ai-chat"),onClick:f,className:"nfd-ai-chat-input__submit",disabled:!c.trim()||n})]})]}),(0,Hf.jsx)("div",{className:"nfd-ai-chat-input__disclaimer",children:(0,Wh.__)("AI-generated content is not guaranteed for accuracy.","wp-module-ai-chat")})]})},rm=e=>(0,Hf.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",focusable:"false",...e,children:(0,Hf.jsx)("path",{d:"M18 6L6 18M6 6l12 12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),om=e=>(0,Hf.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",...e,children:[(0,Hf.jsx)("path",{d:"m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"}),(0,Hf.jsx)("path",{d:"M5 3v4"}),(0,Hf.jsx)("path",{d:"M19 17v4"}),(0,Hf.jsx)("path",{d:"M3 5h4"}),(0,Hf.jsx)("path",{d:"M17 19h4"})]}),am=()=>(0,Hf.jsx)("span",{className:"nfd-ai-chat-blu-beta-badge",children:(0,Wh.__)("BETA","wp-module-ai-chat")}),im=({title:e,badge:t,logo:n,leftActions:s,rightActions:r,className:o=""})=>(0,Hf.jsxs)("div",{className:`nfd-ai-chat-header ${o}`.trim(),role:"banner",children:[(0,Hf.jsxs)("div",{className:"nfd-ai-chat-header__brand",children:[n,null!=e&&(0,Hf.jsx)("span",{className:"nfd-ai-chat-header__title",children:e}),t]}),(s||r)&&(0,Hf.jsxs)("div",{className:"nfd-ai-chat-header__actions",children:[s,r]})]}),cm=({title:e,onNewChat:t,onClose:n,extraActions:s,newChatDisabled:r=!1})=>(0,Hf.jsx)(im,{logo:(0,Hf.jsx)(om,{width:20,height:20}),title:e||(0,Wh.__)("Blu Chat","wp-module-ai-chat"),badge:(0,Hf.jsx)(am,{}),rightActions:(0,Hf.jsxs)(Hf.Fragment,{children:["function"==typeof t&&(0,Hf.jsx)("button",{type:"button",className:"nfd-ai-chat-header__btn nfd-ai-chat-header__btn--new",onClick:r?void 0:t,disabled:r,"aria-label":(0,Wh.__)("New chat","wp-module-ai-chat"),title:(0,Wh.__)("New chat","wp-module-ai-chat"),children:"+"}),s,"function"==typeof n&&(0,Hf.jsx)("button",{type:"button",className:"nfd-ai-chat-header__btn nfd-ai-chat-header__btn--close",onClick:n,"aria-label":(0,Wh.__)("Close","wp-module-ai-chat"),title:(0,Wh.__)("Close","wp-module-ai-chat"),children:(0,Hf.jsx)(rm,{})})]})}),lm=({width:e=24,height:t=24,...n})=>(0,Hf.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 30 30",width:e,height:t,...n,children:[(0,Hf.jsx)("path",{d:"M14.217,19.707l-1.112,2.547c-0.427,0.979-1.782,0.979-2.21,0l-1.112-2.547c-0.99-2.267-2.771-4.071-4.993-5.057L1.73,13.292c-0.973-0.432-0.973-1.848,0-2.28l2.965-1.316C6.974,8.684,8.787,6.813,9.76,4.47l1.126-2.714c0.418-1.007,1.81-1.007,2.228,0L14.24,4.47c0.973,2.344,2.786,4.215,5.065,5.226l2.965,1.316c0.973,0.432,0.973,1.848,0,2.28l-3.061,1.359C16.988,15.637,15.206,17.441,14.217,19.707z"}),(0,Hf.jsx)("path",{d:"M24.481,27.796l-0.339,0.777c-0.248,0.569-1.036,0.569-1.284,0l-0.339-0.777c-0.604-1.385-1.693-2.488-3.051-3.092l-1.044-0.464c-0.565-0.251-0.565-1.072,0-1.323l0.986-0.438c1.393-0.619,2.501-1.763,3.095-3.195l0.348-0.84c0.243-0.585,1.052-0.585,1.294,0l0.348,0.84c0.594,1.432,1.702,2.576,3.095,3.195l0.986,0.438c0.565,0.251,0.565,1.072,0,1.323l-1.044,0.464C26.174,25.308,25.085,26.411,24.481,27.796z"})]}),um=({width:e=24,height:t=24})=>(0,Hf.jsx)("div",{className:"nfd-ai-chat-avatar",style:{width:e,height:t},children:(0,Hf.jsx)(lm,{width:.625*e,height:.625*t})}),dm=({icon:e,text:t,onClick:n,className:s=""})=>(0,Hf.jsxs)(em.Button,{className:`nfd-ai-chat-suggestion ${s}`,onClick:n,children:[(0,Hf.jsx)("div",{className:"nfd-ai-chat-suggestion__icon",children:e}),(0,Hf.jsx)("div",{className:"nfd-ai-chat-suggestion__text",children:t})]}),hm=({onSendMessage:e,title:t,subtitle:n,suggestions:s=[],showSuggestions:r=!1,animateWelcome:o=!1})=>{const a=(0,Wh.__)("Hi, I'm your AI assistant.","wp-module-ai-chat"),i=(0,Wh.__)("How can I help you today?","wp-module-ai-chat"),c=t||a,l=n||i,u=`${c} ${l}`,[d,h]=(0,Lh.useState)(0),p=(0,Lh.useRef)(null);(0,Lh.useEffect)(()=>{if(!o)return void h(u.length);h(0);const e=()=>{h(t=>t>=u.length?t:(p.current=setTimeout(e,40),t+1))};return p.current=setTimeout(e,40),()=>{p.current&&clearTimeout(p.current)}},[o,u]);const f=o&&d<u.length,m=f&&d<=c.length?c.slice(0,d):c;let g=l;return f&&d>c.length?g=l.slice(0,d-c.length-1):f&&(g=""),(0,Hf.jsxs)("div",{className:"nfd-ai-chat-welcome",children:[(0,Hf.jsxs)("div",{className:"nfd-ai-chat-welcome__content",children:[(0,Hf.jsx)("div",{className:"nfd-ai-chat-welcome__avatar",children:(0,Hf.jsx)(um,{width:64,height:64})}),(0,Hf.jsxs)("div",{className:"nfd-ai-chat-welcome__message",children:[(0,Hf.jsx)("div",{className:"nfd-ai-chat-welcome__title",children:m}),(0,Hf.jsxs)("div",{className:"nfd-ai-chat-welcome__subtitle",children:[g,f&&d<u.length&&(0,Hf.jsx)("span",{className:"nfd-ai-chat-welcome__cursor","aria-hidden":"true"})]})]})]}),r&&s.length>0&&(0,Hf.jsx)("div",{className:"nfd-ai-chat-suggestions",children:s.map((t,n)=>(0,Hf.jsx)(dm,{icon:t.icon,text:t.text,onClick:()=>e(t.action||t.text)},t.action??t.text??n))})]})};function pm(e,t,n,s,r={}){if(!e||0===e.length)return;if(!e.some(e=>("user"===e.role||"user"===e.type)&&e.content&&String(e.content).trim()))return;if(null===t&&null===n)return;const o=r.maxHistoryItems??3,a=Yh(s);try{const s=JSON.parse(window.localStorage.getItem(a.archive)||"[]"),r={sessionId:t,conversationId:n,messages:e.map(e=>({...e,timestamp:e.timestamp instanceof Date?e.timestamp.toISOString():e.timestamp})),archivedAt:(new Date).toISOString()},i=null!=n?s.filter(e=>e.conversationId!==n):s.filter(e=>e.sessionId!==t);i.unshift(r),window.localStorage.setItem(a.archive,JSON.stringify(i.slice(0,o)))}catch(e){console.warn("[Chat History] Failed to archive conversation:",e)}}function fm(e,t,n){const s=Yh(n);try{const n=JSON.parse(window.localStorage.getItem(s.archive)||"[]"),r=n.filter(n=>n.conversationId!==e||n.sessionId!==t);r.length!==n.length&&window.localStorage.setItem(s.archive,JSON.stringify(r))}catch(e){console.warn("[Chat History] Failed to remove conversation from archive:",e)}}const mm=Mf("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]),gm=Mf("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);function _m(e){const t=e.messages||e;return Array.isArray(t)&&t.some(e=>("user"===e.role||"user"===e.type)&&e.content&&String(e.content).trim())}const ym=({consumer:e,onSelectConversation:t,refreshTrigger:n=0,disabled:s=!1,emptyMessage:r=null,maxHistoryItems:o=3})=>{const[a,i]=(0,Lh.useState)([]),c=Yh(e);(0,Lh.useEffect)(()=>{try{const e=window.localStorage.getItem(c.archive);if(e){const t=JSON.parse(e);if(Array.isArray(t)&&t.length>0){const e=t.slice(0,o);e.length<t.length&&window.localStorage.setItem(c.archive,JSON.stringify(e));const n=e.map(e=>{const t=(e.messages||[]).map(e=>({...e,timestamp:e.timestamp?new Date(e.timestamp):new Date})),n=e.archivedAt?new Date(e.archivedAt):null;return{sessionId:e.sessionId??null,conversationId:e.conversationId??null,messages:t,archivedAt:n}}).filter(_m);return void i(n)}}const t=window.localStorage.getItem(c.history);if(t){const e=JSON.parse(t);if(Array.isArray(e)&&e.length>0){const t=function(e,t){if(!Array.isArray(e)||0===e.length)return[];const n={},s=[];e.forEach(e=>{if(e.sessionId){n[e.sessionId]||(n[e.sessionId]={sessionId:e.sessionId,messages:[],timestamp:e.timestamp?new Date(e.timestamp).getTime():0}),n[e.sessionId].messages.push(e);const t=e.timestamp?new Date(e.timestamp).getTime():0;t>n[e.sessionId].timestamp&&(n[e.sessionId].timestamp=t)}else s.push(e)});let r=Object.values(n).sort((e,t)=>t.timestamp-e.timestamp).map(e=>({sessionId:e.sessionId,messages:e.messages}));if(s.length>0&&r.length<t){const e=function(e){const t=[];let n=[],s=null;return e.forEach(e=>{const r=e.timestamp?new Date(e.timestamp).getTime():Date.now();s&&r-s>3e5&&n.length>0&&(t.push({sessionId:null,messages:[...n]}),n=[]),n.push(e),s=r}),n.length>0&&t.push({sessionId:null,messages:n}),t.reverse()}(s);r=[...r,...e]}return r=r.filter(_m),r.slice(0,t)}(e.map(e=>({...e,timestamp:e.timestamp?new Date(e.timestamp):new Date})),o);i(t)}}}catch(e){console.warn("[Chat History] Failed to load chat history:",e)}},[e,n,o,c.archive,c.history]);const l=(0,Lh.useCallback)(e=>{if(!s)try{const n=(e.messages||e).map(e=>({...e,timestamp:e.timestamp instanceof Date?e.timestamp.toISOString():e.timestamp}));window.localStorage.setItem(c.history,JSON.stringify(n)),e.sessionId&&window.localStorage.setItem(c.sessionId,e.sessionId),e.conversationId&&window.localStorage.setItem(c.conversationId,e.conversationId),t&&t(e)}catch(e){console.warn("[Chat History] Failed to restore conversation:",e)}},[s,c,t]),u=(0,Lh.useCallback)((e,t)=>{if(e.stopPropagation(),e.preventDefault(),!s)try{const e=window.localStorage.getItem(c.archive);if(e){const n=JSON.parse(e).filter((e,n)=>n!==t);window.localStorage.setItem(c.archive,JSON.stringify(n))}i(e=>e.filter((e,n)=>n!==t))}catch(e){console.warn("[Chat History] Failed to delete conversation:",e)}},[s,c]);return 0===a.length?r?(0,Hf.jsx)("div",{className:"nfd-ai-chat-history-list nfd-ai-chat-history-list--empty",children:r}):null:(0,Hf.jsx)("div",{className:"nfd-ai-chat-history-list",children:a.map((e,t)=>{const n=(e=>{const t=(e.messages||e).find(e=>"user"===e.role||"user"===e.type);if(t&&t.content){const e=t.content;return e.length>50?e.substring(0,50)+"...":e}return(0,Wh.__)("Previous conversation","wp-module-ai-chat")})(e),r=e.sessionId||`legacy-${t}`,o=e.archivedAt||function(e){const t=e.messages||e;if(!Array.isArray(t)||0===t.length)return null;let n=0;return t.forEach(e=>{const t=e.timestamp?new Date(e.timestamp).getTime():0;t>n&&(n=t)}),n?new Date(n):null}(e)||null,a=o?(e=>{const t=e instanceof Date?e:new Date(e),n=Date.now()-t.getTime(),s=Math.floor(n/6e4);if(s<1)return(0,Wh.__)("Just now","wp-module-ai-chat");if(s<60)return`${s}m`;const r=Math.floor(n/36e5);if(r<24)return`${r}h`;const o=Math.floor(n/864e5);return o<7?`${o}d`:t.toLocaleDateString(void 0,{month:"short",day:"numeric"})})(o):null;return(0,Hf.jsxs)("div",{className:"nfd-ai-chat-history-item"+(s?" nfd-ai-chat-history-item--disabled":""),role:"button",tabIndex:s?-1:0,"aria-disabled":s,onClick:()=>l(e),onKeyDown:t=>{s||"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),l(e))},children:[(0,Hf.jsx)(mm,{width:14,height:14,"aria-hidden":!0}),(0,Hf.jsxs)("div",{className:"nfd-ai-chat-history-item__content",children:[(0,Hf.jsx)("span",{className:"nfd-ai-chat-history-item__title",children:n}),(0,Hf.jsxs)("div",{className:"nfd-ai-chat-history-item__meta",children:[a&&(0,Hf.jsx)("span",{className:"nfd-ai-chat-history-item__time",children:a}),(0,Hf.jsx)("button",{type:"button",className:"nfd-ai-chat-history-item__delete",onClick:e=>u(e,t),"aria-label":(0,Wh.__)("Delete conversation","wp-module-ai-chat"),title:(0,Wh.__)("Delete","wp-module-ai-chat"),children:(0,Hf.jsx)(gm,{width:14,height:14,className:"nfd-ai-chat-history-item__delete-icon","aria-hidden":!0})})]})]})]},r)})})},wm=e=>(0,Hf.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",focusable:"false",...e,children:[(0,Hf.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2"}),(0,Hf.jsx)("path",{d:"M12 7v5l3 3",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),vm=({consumer:e,open:t,onOpenChange:n,onSelectConversation:s,refreshTrigger:r=0,disabled:o=!1,maxHistoryItems:a})=>{const i=(0,Lh.useRef)(null),c=(0,Lh.useRef)(null),[l,u]=(0,Lh.useState)({top:0,left:0,openUp:!1}),d=(0,Lh.useCallback)(()=>{if(!i.current)return;const e=i.current.getBoundingClientRect(),t=window.innerHeight-e.bottom,n=t<240&&e.top>t;u({top:n?e.top:e.bottom,left:e.right,openUp:n})},[]);(0,Lh.useLayoutEffect)(()=>{t&&d()},[t,d]),(0,Lh.useEffect)(()=>{if(!t)return;const e=()=>d();return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[t,d]),(0,Lh.useEffect)(()=>{if(!t)return;const e=e=>{i.current?.contains(e.target)||c.current?.contains(e.target)||n(!1)},s=e=>{"Escape"===e.key&&n(!1)};return document.addEventListener("mousedown",e),document.addEventListener("keydown",s),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",s)}},[t,n]);const h=(0,Lh.useCallback)(e=>{s(e),n(!1)},[s,n]),p=(0,Lh.useCallback)(()=>{o||n(!t)},[o,t,n]),f=(0,Hf.jsx)("div",{ref:c,className:"nfd-ai-chat-history-dropdown",role:"dialog","aria-label":(0,Wh.__)("Chat history","wp-module-ai-chat"),style:{position:"fixed",top:l.openUp?"auto":l.top,bottom:l.openUp?window.innerHeight-l.top:"auto",left:"auto",right:window.innerWidth-l.left,zIndex:1e5},children:(0,Hf.jsx)("div",{className:"nfd-ai-chat-history-dropdown-inner",children:(0,Hf.jsx)(ym,{consumer:e,onSelectConversation:h,disabled:o,refreshTrigger:t?r:0,emptyMessage:(0,Wh.__)("No conversations yet.","wp-module-ai-chat"),maxHistoryItems:a})})});return(0,Hf.jsxs)("div",{className:"nfd-ai-chat-history-dropdown-wrapper",children:[(0,Hf.jsx)("button",{ref:i,type:"button",className:"nfd-ai-chat-history-dropdown-trigger "+(t?"is-open":""),onClick:p,disabled:o,"aria-expanded":t,"aria-haspopup":"true","aria-label":(0,Wh.__)("Chat history","wp-module-ai-chat"),title:(0,Wh.__)("Chat history","wp-module-ai-chat"),children:(0,Hf.jsx)(wm,{})}),t&&(0,Lh.createPortal)(f,document.body)]})}})(),module.exports=s})();
|