@easyling/sanity-connector 1.2.0 → 1.3.0-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{jsx as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__,jsxs as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__}from"react/jsx-runtime";import{definePlugin as __WEBPACK_EXTERNAL_MODULE_sanity_definePlugin__,set as __WEBPACK_EXTERNAL_MODULE_sanity_set__,unset as __WEBPACK_EXTERNAL_MODULE_sanity_unset__,useClient as __WEBPACK_EXTERNAL_MODULE_sanity_useClient__,useFormValue as __WEBPACK_EXTERNAL_MODULE_sanity_useFormValue__}from"sanity";import{createContext as __WEBPACK_EXTERNAL_MODULE_react_createContext__,default as __WEBPACK_EXTERNAL_MODULE_react_default__,useCallback as __WEBPACK_EXTERNAL_MODULE_react_useCallback__,useContext as __WEBPACK_EXTERNAL_MODULE_react_useContext__,useEffect as __WEBPACK_EXTERNAL_MODULE_react_useEffect__,useMemo as __WEBPACK_EXTERNAL_MODULE_react_useMemo__,useRef as __WEBPACK_EXTERNAL_MODULE_react_useRef__,useState as __WEBPACK_EXTERNAL_MODULE_react_useState__}from"react";import{BlockElementIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_BlockElementIcon__,CheckmarkCircleIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CheckmarkCircleIcon__,CheckmarkIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CheckmarkIcon__,ChevronDownIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_ChevronDownIcon__,ChevronRightIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_ChevronRightIcon__,CloseIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CloseIcon__,ErrorOutlineIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_ErrorOutlineIcon__,RefreshIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_RefreshIcon__,SearchIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_SearchIcon__,TranslateIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_TranslateIcon__,WarningOutlineIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_WarningOutlineIcon__}from"@sanity/icons";import{Badge as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,Box as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,Button as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,Card as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,Checkbox as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Checkbox__,Code as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Code__,Dialog as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Dialog__,Flex as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,Radio as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Radio__,Spinner as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Spinner__,Stack as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,Text as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,TextInput as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_TextInput__,Tooltip as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Tooltip__}from"@sanity/ui";var __webpack_modules__={45:e=>{e.exports=function(e,t){for(var n=new Array(arguments.length-1),_=0,a=2,r=!0;a<arguments.length;)n[_++]=arguments[a++];return new Promise(function(a,i){n[_]=function(e){if(r)if(r=!1,e)i(e);else{for(var t=new Array(arguments.length-1),n=0;n<t.length;)t[n++]=arguments[n];a.apply(null,t)}};try{e.apply(t||null,n)}catch(e){r&&(r=!1,i(e))}})}},47:(e,t,n)=>{t.Service=n(595)},153:module=>{function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},158:(e,t,n)=>{e.exports=r;var _=n(237);(r.prototype=Object.create(_.prototype)).constructor=r;var a=n(610);function r(e){_.call(this,e)}r._configure=function(){a.Buffer&&(r.prototype._slice=a.Buffer.prototype.slice)},r.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},r._configure()},230:function(e,t,n){var _=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Metadata=t.TranslatableField=t.Content_FieldsEntry=t.Content=t.TranslationRequestPayload=t.protobufPackage=void 0;const a=_(n(946));function r(e){return null!=e}t.protobufPackage="hu.skawa.pagetranslate.server.model.protobuffers",t.TranslationRequestPayload={encode:(e,n=a.default.Writer.create())=>(void 0!==e.content&&t.Content.encode(e.content,n.uint32(10).fork()).ldelim(),""!==e.project&&n.uint32(34).string(e.project),""!==e.format&&n.uint32(18).string(e.format),void 0!==e.metadata&&t.Metadata.encode(e.metadata,n.uint32(26).fork()).ldelim(),n),decode(e,n){const _=e instanceof a.default.Reader?e:a.default.Reader.create(e);let r=void 0===n?_.len:_.pos+n;const i={content:void 0,project:"",format:"",metadata:void 0};for(;_.pos<r;){const e=_.uint32();switch(e>>>3){case 1:if(10!==e)break;i.content=t.Content.decode(_,_.uint32());continue;case 4:if(34!==e)break;i.project=_.string();continue;case 2:if(18!==e)break;i.format=_.string();continue;case 3:if(26!==e)break;i.metadata=t.Metadata.decode(_,_.uint32());continue}if(4==(7&e)||0===e)break;_.skipType(7&e)}return i},fromJSON:e=>({content:r(e.content)?t.Content.fromJSON(e.content):void 0,project:r(e.project)?globalThis.String(e.project):"",format:r(e.format)?globalThis.String(e.format):"",metadata:r(e.metadata)?t.Metadata.fromJSON(e.metadata):void 0}),toJSON(e){const n={};return void 0!==e.content&&(n.content=t.Content.toJSON(e.content)),""!==e.project&&(n.project=e.project),""!==e.format&&(n.format=e.format),void 0!==e.metadata&&(n.metadata=t.Metadata.toJSON(e.metadata)),n},create:e=>t.TranslationRequestPayload.fromPartial(e??{}),fromPartial(e){const n={content:void 0,project:"",format:"",metadata:void 0};return n.content=void 0!==e.content&&null!==e.content?t.Content.fromPartial(e.content):void 0,n.project=e.project??"",n.format=e.format??"",n.metadata=void 0!==e.metadata&&null!==e.metadata?t.Metadata.fromPartial(e.metadata):void 0,n}},t.Content={encode:(e,n=a.default.Writer.create())=>(""!==e.body&&n.uint32(10).string(e.body),""!==e.title&&n.uint32(18).string(e.title),""!==e.slug&&n.uint32(26).string(e.slug),Object.entries(e.fields).forEach(([e,_])=>{t.Content_FieldsEntry.encode({key:e,value:_},n.uint32(34).fork()).ldelim()}),n),decode(e,n){const _=e instanceof a.default.Reader?e:a.default.Reader.create(e);let r=void 0===n?_.len:_.pos+n;const i={body:"",title:"",slug:"",fields:{}};for(;_.pos<r;){const e=_.uint32();switch(e>>>3){case 1:if(10!==e)break;i.body=_.string();continue;case 2:if(18!==e)break;i.title=_.string();continue;case 3:if(26!==e)break;i.slug=_.string();continue;case 4:if(34!==e)break;const n=t.Content_FieldsEntry.decode(_,_.uint32());void 0!==n.value&&(i.fields[n.key]=n.value);continue}if(4==(7&e)||0===e)break;_.skipType(7&e)}return i},fromJSON(e){return{body:r(e.body)?globalThis.String(e.body):"",title:r(e.title)?globalThis.String(e.title):"",slug:r(e.slug)?globalThis.String(e.slug):"",fields:(n=e.fields,"object"==typeof n&&null!==n?Object.entries(e.fields).reduce((e,[n,_])=>(e[n]=t.TranslatableField.fromJSON(_),e),{}):{})};var n},toJSON(e){const n={};if(""!==e.body&&(n.body=e.body),""!==e.title&&(n.title=e.title),""!==e.slug&&(n.slug=e.slug),e.fields){const _=Object.entries(e.fields);_.length>0&&(n.fields={},_.forEach(([e,_])=>{n.fields[e]=t.TranslatableField.toJSON(_)}))}return n},create:e=>t.Content.fromPartial(e??{}),fromPartial(e){const n={body:"",title:"",slug:"",fields:{}};return n.body=e.body??"",n.title=e.title??"",n.slug=e.slug??"",n.fields=Object.entries(e.fields??{}).reduce((e,[n,_])=>(void 0!==_&&(e[n]=t.TranslatableField.fromPartial(_)),e),{}),n}},t.Content_FieldsEntry={encode:(e,n=a.default.Writer.create())=>(""!==e.key&&n.uint32(10).string(e.key),void 0!==e.value&&t.TranslatableField.encode(e.value,n.uint32(18).fork()).ldelim(),n),decode(e,n){const _=e instanceof a.default.Reader?e:a.default.Reader.create(e);let r=void 0===n?_.len:_.pos+n;const i={key:"",value:void 0};for(;_.pos<r;){const e=_.uint32();switch(e>>>3){case 1:if(10!==e)break;i.key=_.string();continue;case 2:if(18!==e)break;i.value=t.TranslatableField.decode(_,_.uint32());continue}if(4==(7&e)||0===e)break;_.skipType(7&e)}return i},fromJSON:e=>({key:r(e.key)?globalThis.String(e.key):"",value:r(e.value)?t.TranslatableField.fromJSON(e.value):void 0}),toJSON(e){const n={};return""!==e.key&&(n.key=e.key),void 0!==e.value&&(n.value=t.TranslatableField.toJSON(e.value)),n},create:e=>t.Content_FieldsEntry.fromPartial(e??{}),fromPartial(e){const n={key:"",value:void 0};return n.key=e.key??"",n.value=void 0!==e.value&&null!==e.value?t.TranslatableField.fromPartial(e.value):void 0,n}},t.TranslatableField={encode:(e,t=a.default.Writer.create())=>(""!==e.value&&t.uint32(10).string(e.value),!1!==e.dnt&&t.uint32(16).bool(e.dnt),""!==e.type&&t.uint32(26).string(e.type),t),decode(e,t){const n=e instanceof a.default.Reader?e:a.default.Reader.create(e);let _=void 0===t?n.len:n.pos+t;const r={value:"",dnt:!1,type:""};for(;n.pos<_;){const e=n.uint32();switch(e>>>3){case 1:if(10!==e)break;r.value=n.string();continue;case 2:if(16!==e)break;r.dnt=n.bool();continue;case 3:if(26!==e)break;r.type=n.string();continue}if(4==(7&e)||0===e)break;n.skipType(7&e)}return r},fromJSON:e=>({value:r(e.value)?globalThis.String(e.value):"",dnt:!!r(e.dnt)&&globalThis.Boolean(e.dnt),type:r(e.type)?globalThis.String(e.type):""}),toJSON(e){const t={};return""!==e.value&&(t.value=e.value),!1!==e.dnt&&(t.dnt=e.dnt),""!==e.type&&(t.type=e.type),t},create:e=>t.TranslatableField.fromPartial(e??{}),fromPartial(e){const t={value:"",dnt:!1,type:""};return t.value=e.value??"",t.dnt=e.dnt??!1,t.type=e.type??"",t}},t.Metadata={encode(e,t=a.default.Writer.create()){""!==e.documentId&&t.uint32(10).string(e.documentId),""!==e.documentType&&t.uint32(18).string(e.documentType),""!==e.title&&t.uint32(26).string(e.title),""!==e.sourceLanguage&&t.uint32(34).string(e.sourceLanguage),""!==e.targetLanguage&&t.uint32(42).string(e.targetLanguage);for(const n of e.targetLocales)t.uint32(50).string(n);return t},decode(e,t){const n=e instanceof a.default.Reader?e:a.default.Reader.create(e);let _=void 0===t?n.len:n.pos+t;const r={documentId:"",documentType:"",title:"",sourceLanguage:"",targetLanguage:"",targetLocales:[]};for(;n.pos<_;){const e=n.uint32();switch(e>>>3){case 1:if(10!==e)break;r.documentId=n.string();continue;case 2:if(18!==e)break;r.documentType=n.string();continue;case 3:if(26!==e)break;r.title=n.string();continue;case 4:if(34!==e)break;r.sourceLanguage=n.string();continue;case 5:if(42!==e)break;r.targetLanguage=n.string();continue;case 6:if(50!==e)break;r.targetLocales.push(n.string());continue}if(4==(7&e)||0===e)break;n.skipType(7&e)}return r},fromJSON:e=>({documentId:r(e.documentId)?globalThis.String(e.documentId):"",documentType:r(e.documentType)?globalThis.String(e.documentType):"",title:r(e.title)?globalThis.String(e.title):"",sourceLanguage:r(e.sourceLanguage)?globalThis.String(e.sourceLanguage):"",targetLanguage:r(e.targetLanguage)?globalThis.String(e.targetLanguage):"",targetLocales:globalThis.Array.isArray(e?.targetLocales)?e.targetLocales.map(e=>globalThis.String(e)):[]}),toJSON(e){const t={};return""!==e.documentId&&(t.documentId=e.documentId),""!==e.documentType&&(t.documentType=e.documentType),""!==e.title&&(t.title=e.title),""!==e.sourceLanguage&&(t.sourceLanguage=e.sourceLanguage),""!==e.targetLanguage&&(t.targetLanguage=e.targetLanguage),e.targetLocales?.length&&(t.targetLocales=e.targetLocales),t},create:e=>t.Metadata.fromPartial(e??{}),fromPartial(e){const t={documentId:"",documentType:"",title:"",sourceLanguage:"",targetLanguage:"",targetLocales:[]};return t.documentId=e.documentId??"",t.documentType=e.documentType??"",t.title=e.title??"",t.sourceLanguage=e.sourceLanguage??"",t.targetLanguage=e.targetLanguage??"",t.targetLocales=e.targetLocales?.map(e=>e)||[],t}}},237:(e,t,n)=>{e.exports=o;var _,a=n(610),r=a.LongBits,i=a.utf8;function s(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function o(e){this.buf=e,this.pos=0,this.len=e.length}var c,l="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new o(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new o(e);throw Error("illegal buffer")},u=function(){return a.Buffer?function(e){return(o.create=function(e){return a.Buffer.isBuffer(e)?new _(e):l(e)})(e)}:l};function d(){var e=new r(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw s(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw s(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function E(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw s(this,8);return new r(E(this.buf,this.pos+=4),E(this.buf,this.pos+=4))}o.create=u(),o.prototype._slice=a.Array.prototype.subarray||a.Array.prototype.slice,o.prototype.uint32=(c=4294967295,function(){if(c=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return c;if((this.pos+=5)>this.len)throw this.pos=this.len,s(this,10);return c}),o.prototype.int32=function(){return 0|this.uint32()},o.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},o.prototype.bool=function(){return 0!==this.uint32()},o.prototype.fixed32=function(){if(this.pos+4>this.len)throw s(this,4);return E(this.buf,this.pos+=4)},o.prototype.sfixed32=function(){if(this.pos+4>this.len)throw s(this,4);return 0|E(this.buf,this.pos+=4)},o.prototype.float=function(){if(this.pos+4>this.len)throw s(this,4);var e=a.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},o.prototype.double=function(){if(this.pos+8>this.len)throw s(this,4);var e=a.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},o.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw s(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,n);if(t===n){var _=a.Buffer;return _?_.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,n)},o.prototype.string=function(){var e=this.bytes();return i.read(e,0,e.length)},o.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw s(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw s(this)}while(128&this.buf[this.pos++]);return this},o.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},o._configure=function(e){_=e,o.create=u(),_._configure();var t=a.Long?"toLong":"toNumber";a.merge(o.prototype,{int64:function(){return d.call(this)[t](!1)},uint64:function(){return d.call(this)[t](!0)},sint64:function(){return d.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},239:(e,t,n)=>{e.exports=a;var _=n(610);function a(e,t){this.lo=e>>>0,this.hi=t>>>0}var r=a.zero=new a(0,0);r.toNumber=function(){return 0},r.zzEncode=r.zzDecode=function(){return this},r.length=function(){return 1};var i=a.zeroHash="\0\0\0\0\0\0\0\0";a.fromNumber=function(e){if(0===e)return r;var t=e<0;t&&(e=-e);var n=e>>>0,_=(e-n)/4294967296>>>0;return t&&(_=~_>>>0,n=~n>>>0,++n>4294967295&&(n=0,++_>4294967295&&(_=0))),new a(n,_)},a.from=function(e){if("number"==typeof e)return a.fromNumber(e);if(_.isString(e)){if(!_.Long)return a.fromNumber(parseInt(e,10));e=_.Long.fromString(e)}return e.low||e.high?new a(e.low>>>0,e.high>>>0):r},a.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+4294967296*n)}return this.lo+4294967296*this.hi},a.prototype.toLong=function(e){return _.Long?new _.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var s=String.prototype.charCodeAt;a.fromHash=function(e){return e===i?r:new a((s.call(e,0)|s.call(e,1)<<8|s.call(e,2)<<16|s.call(e,3)<<24)>>>0,(s.call(e,4)|s.call(e,5)<<8|s.call(e,6)<<16|s.call(e,7)<<24)>>>0)},a.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},a.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},a.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},a.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}},358:e=>{function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var n=this._listeners[e],_=0;_<n.length;)n[_].fn===t?n.splice(_,1):++_;return this},t.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var n=[],_=1;_<arguments.length;)n.push(arguments[_++]);for(_=0;_<t.length;)t[_].fn.apply(t[_++].ctx,n)}return this}},390:e=>{e.exports=function(e,t,n){var _=n||8192,a=_>>>1,r=null,i=_;return function(n){if(n<1||n>a)return e(n);i+n>_&&(r=e(_),i=0);var s=t.call(r,i,i+=n);return 7&i&&(i=1+(7|i)),s}}},394:(e,t,n)=>{var _=t;function a(){_.util._configure(),_.Writer._configure(_.BufferWriter),_.Reader._configure(_.BufferReader)}_.build="minimal",_.Writer=n(449),_.BufferWriter=n(818),_.Reader=n(237),_.BufferReader=n(158),_.util=n(610),_.rpc=n(47),_.roots=n(529),_.configure=a,a()},410:e=>{function t(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),n=new Uint8Array(t.buffer),_=128===n[3];function a(e,_,a){t[0]=e,_[a]=n[0],_[a+1]=n[1],_[a+2]=n[2],_[a+3]=n[3]}function r(e,_,a){t[0]=e,_[a]=n[3],_[a+1]=n[2],_[a+2]=n[1],_[a+3]=n[0]}function i(e,_){return n[0]=e[_],n[1]=e[_+1],n[2]=e[_+2],n[3]=e[_+3],t[0]}function s(e,_){return n[3]=e[_],n[2]=e[_+1],n[1]=e[_+2],n[0]=e[_+3],t[0]}e.writeFloatLE=_?a:r,e.writeFloatBE=_?r:a,e.readFloatLE=_?i:s,e.readFloatBE=_?s:i}():function(){function t(e,t,n,_){var a=t<0?1:0;if(a&&(t=-t),0===t)e(1/t>0?0:2147483648,n,_);else if(isNaN(t))e(2143289344,n,_);else if(t>34028234663852886e22)e((a<<31|2139095040)>>>0,n,_);else if(t<11754943508222875e-54)e((a<<31|Math.round(t/1401298464324817e-60))>>>0,n,_);else{var r=Math.floor(Math.log(t)/Math.LN2);e((a<<31|r+127<<23|8388607&Math.round(t*Math.pow(2,-r)*8388608))>>>0,n,_)}}function i(e,t,n){var _=e(t,n),a=2*(_>>31)+1,r=_>>>23&255,i=8388607&_;return 255===r?i?NaN:a*(1/0):0===r?1401298464324817e-60*a*i:a*Math.pow(2,r-150)*(i+8388608)}e.writeFloatLE=t.bind(null,n),e.writeFloatBE=t.bind(null,_),e.readFloatLE=i.bind(null,a),e.readFloatBE=i.bind(null,r)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),n=new Uint8Array(t.buffer),_=128===n[7];function a(e,_,a){t[0]=e,_[a]=n[0],_[a+1]=n[1],_[a+2]=n[2],_[a+3]=n[3],_[a+4]=n[4],_[a+5]=n[5],_[a+6]=n[6],_[a+7]=n[7]}function r(e,_,a){t[0]=e,_[a]=n[7],_[a+1]=n[6],_[a+2]=n[5],_[a+3]=n[4],_[a+4]=n[3],_[a+5]=n[2],_[a+6]=n[1],_[a+7]=n[0]}function i(e,_){return n[0]=e[_],n[1]=e[_+1],n[2]=e[_+2],n[3]=e[_+3],n[4]=e[_+4],n[5]=e[_+5],n[6]=e[_+6],n[7]=e[_+7],t[0]}function s(e,_){return n[7]=e[_],n[6]=e[_+1],n[5]=e[_+2],n[4]=e[_+3],n[3]=e[_+4],n[2]=e[_+5],n[1]=e[_+6],n[0]=e[_+7],t[0]}e.writeDoubleLE=_?a:r,e.writeDoubleBE=_?r:a,e.readDoubleLE=_?i:s,e.readDoubleBE=_?s:i}():function(){function t(e,t,n,_,a,r){var i=_<0?1:0;if(i&&(_=-_),0===_)e(0,a,r+t),e(1/_>0?0:2147483648,a,r+n);else if(isNaN(_))e(0,a,r+t),e(2146959360,a,r+n);else if(_>17976931348623157e292)e(0,a,r+t),e((i<<31|2146435072)>>>0,a,r+n);else{var s;if(_<22250738585072014e-324)e((s=_/5e-324)>>>0,a,r+t),e((i<<31|s/4294967296)>>>0,a,r+n);else{var o=Math.floor(Math.log(_)/Math.LN2);1024===o&&(o=1023),e(4503599627370496*(s=_*Math.pow(2,-o))>>>0,a,r+t),e((i<<31|o+1023<<20|1048576*s&1048575)>>>0,a,r+n)}}}function i(e,t,n,_,a){var r=e(_,a+t),i=e(_,a+n),s=2*(i>>31)+1,o=i>>>20&2047,c=4294967296*(1048575&i)+r;return 2047===o?c?NaN:s*(1/0):0===o?5e-324*s*c:s*Math.pow(2,o-1075)*(c+4503599627370496)}e.writeDoubleLE=t.bind(null,n,0,4),e.writeDoubleBE=t.bind(null,_,4,0),e.readDoubleLE=i.bind(null,a,0,4),e.readDoubleBE=i.bind(null,r,4,0)}(),e}function n(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function _(e,t,n){t[n]=e>>>24,t[n+1]=e>>>16&255,t[n+2]=e>>>8&255,t[n+3]=255&e}function a(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function r(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},424:function(e,t,n){var _=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.TranslatedDocument_FieldsEntry=t.TranslatedDocument=t.TranslationResponse=t.protobufPackage=void 0;const a=_(n(946)),r=n(230);function i(e){return null!=e}t.protobufPackage="hu.skawa.pagetranslate.server.model.protobuffers",t.TranslationResponse={encode(e,n=a.default.Writer.create()){!1!==e.success&&n.uint32(8).bool(e.success);for(const _ of e.translatedDocuments)t.TranslatedDocument.encode(_,n.uint32(18).fork()).ldelim();return""!==e.sourceLocale&&n.uint32(26).string(e.sourceLocale),""!==e.error&&n.uint32(34).string(e.error),""!==e.requestId&&n.uint32(42).string(e.requestId),n},decode(e,n){const _=e instanceof a.default.Reader?e:a.default.Reader.create(e);let r=void 0===n?_.len:_.pos+n;const i={success:!1,translatedDocuments:[],sourceLocale:"",error:"",requestId:""};for(;_.pos<r;){const e=_.uint32();switch(e>>>3){case 1:if(8!==e)break;i.success=_.bool();continue;case 2:if(18!==e)break;i.translatedDocuments.push(t.TranslatedDocument.decode(_,_.uint32()));continue;case 3:if(26!==e)break;i.sourceLocale=_.string();continue;case 4:if(34!==e)break;i.error=_.string();continue;case 5:if(42!==e)break;i.requestId=_.string();continue}if(4==(7&e)||0===e)break;_.skipType(7&e)}return i},fromJSON:e=>({success:!!i(e.success)&&globalThis.Boolean(e.success),translatedDocuments:globalThis.Array.isArray(e?.translatedDocuments)?e.translatedDocuments.map(e=>t.TranslatedDocument.fromJSON(e)):[],sourceLocale:i(e.sourceLocale)?globalThis.String(e.sourceLocale):"",error:i(e.error)?globalThis.String(e.error):"",requestId:i(e.requestId)?globalThis.String(e.requestId):""}),toJSON(e){const n={};return!1!==e.success&&(n.success=e.success),e.translatedDocuments?.length&&(n.translatedDocuments=e.translatedDocuments.map(e=>t.TranslatedDocument.toJSON(e))),""!==e.sourceLocale&&(n.sourceLocale=e.sourceLocale),""!==e.error&&(n.error=e.error),""!==e.requestId&&(n.requestId=e.requestId),n},create:e=>t.TranslationResponse.fromPartial(e??{}),fromPartial(e){const n={success:!1,translatedDocuments:[],sourceLocale:"",error:"",requestId:""};return n.success=e.success??!1,n.translatedDocuments=e.translatedDocuments?.map(e=>t.TranslatedDocument.fromPartial(e))||[],n.sourceLocale=e.sourceLocale??"",n.error=e.error??"",n.requestId=e.requestId??"",n}},t.TranslatedDocument={encode:(e,n=a.default.Writer.create())=>(""!==e.body&&n.uint32(10).string(e.body),""!==e.title&&n.uint32(18).string(e.title),""!==e.slug&&n.uint32(26).string(e.slug),Object.entries(e.fields).forEach(([e,_])=>{t.TranslatedDocument_FieldsEntry.encode({key:e,value:_},n.uint32(34).fork()).ldelim()}),""!==e.locale&&n.uint32(42).string(e.locale),n),decode(e,n){const _=e instanceof a.default.Reader?e:a.default.Reader.create(e);let r=void 0===n?_.len:_.pos+n;const i={body:"",title:"",slug:"",fields:{},locale:""};for(;_.pos<r;){const e=_.uint32();switch(e>>>3){case 1:if(10!==e)break;i.body=_.string();continue;case 2:if(18!==e)break;i.title=_.string();continue;case 3:if(26!==e)break;i.slug=_.string();continue;case 4:if(34!==e)break;const n=t.TranslatedDocument_FieldsEntry.decode(_,_.uint32());void 0!==n.value&&(i.fields[n.key]=n.value);continue;case 5:if(42!==e)break;i.locale=_.string();continue}if(4==(7&e)||0===e)break;_.skipType(7&e)}return i},fromJSON(e){return{body:i(e.body)?globalThis.String(e.body):"",title:i(e.title)?globalThis.String(e.title):"",slug:i(e.slug)?globalThis.String(e.slug):"",fields:(t=e.fields,"object"==typeof t&&null!==t?Object.entries(e.fields).reduce((e,[t,n])=>(e[t]=r.TranslatableField.fromJSON(n),e),{}):{}),locale:i(e.locale)?globalThis.String(e.locale):""};var t},toJSON(e){const t={};if(""!==e.body&&(t.body=e.body),""!==e.title&&(t.title=e.title),""!==e.slug&&(t.slug=e.slug),e.fields){const n=Object.entries(e.fields);n.length>0&&(t.fields={},n.forEach(([e,n])=>{t.fields[e]=r.TranslatableField.toJSON(n)}))}return""!==e.locale&&(t.locale=e.locale),t},create:e=>t.TranslatedDocument.fromPartial(e??{}),fromPartial(e){const t={body:"",title:"",slug:"",fields:{},locale:""};return t.body=e.body??"",t.title=e.title??"",t.slug=e.slug??"",t.fields=Object.entries(e.fields??{}).reduce((e,[t,n])=>(void 0!==n&&(e[t]=r.TranslatableField.fromPartial(n)),e),{}),t.locale=e.locale??"",t}},t.TranslatedDocument_FieldsEntry={encode:(e,t=a.default.Writer.create())=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&r.TranslatableField.encode(e.value,t.uint32(18).fork()).ldelim(),t),decode(e,t){const n=e instanceof a.default.Reader?e:a.default.Reader.create(e);let _=void 0===t?n.len:n.pos+t;const i={key:"",value:void 0};for(;n.pos<_;){const e=n.uint32();switch(e>>>3){case 1:if(10!==e)break;i.key=n.string();continue;case 2:if(18!==e)break;i.value=r.TranslatableField.decode(n,n.uint32());continue}if(4==(7&e)||0===e)break;n.skipType(7&e)}return i},fromJSON:e=>({key:i(e.key)?globalThis.String(e.key):"",value:i(e.value)?r.TranslatableField.fromJSON(e.value):void 0}),toJSON(e){const t={};return""!==e.key&&(t.key=e.key),void 0!==e.value&&(t.value=r.TranslatableField.toJSON(e.value)),t},create:e=>t.TranslatedDocument_FieldsEntry.fromPartial(e??{}),fromPartial(e){const t={key:"",value:void 0};return t.key=e.key??"",t.value=void 0!==e.value&&null!==e.value?r.TranslatableField.fromPartial(e.value):void 0,t}}},447:(e,t)=>{var n=t;n.length=function(e){for(var t=0,n=0,_=0;_<e.length;++_)(n=e.charCodeAt(_))<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(_+1))?(++_,t+=4):t+=3;return t},n.read=function(e,t,n){if(n-t<1)return"";for(var _,a=null,r=[],i=0;t<n;)(_=e[t++])<128?r[i++]=_:_>191&&_<224?r[i++]=(31&_)<<6|63&e[t++]:_>239&&_<365?(_=((7&_)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,r[i++]=55296+(_>>10),r[i++]=56320+(1023&_)):r[i++]=(15&_)<<12|(63&e[t++])<<6|63&e[t++],i>8191&&((a||(a=[])).push(String.fromCharCode.apply(String,r)),i=0);return a?(i&&a.push(String.fromCharCode.apply(String,r.slice(0,i))),a.join("")):String.fromCharCode.apply(String,r.slice(0,i))},n.write=function(e,t,n){for(var _,a,r=n,i=0;i<e.length;++i)(_=e.charCodeAt(i))<128?t[n++]=_:_<2048?(t[n++]=_>>6|192,t[n++]=63&_|128):55296==(64512&_)&&56320==(64512&(a=e.charCodeAt(i+1)))?(_=65536+((1023&_)<<10)+(1023&a),++i,t[n++]=_>>18|240,t[n++]=_>>12&63|128,t[n++]=_>>6&63|128,t[n++]=63&_|128):(t[n++]=_>>12|224,t[n++]=_>>6&63|128,t[n++]=63&_|128);return n-r}},449:(e,t,n)=>{e.exports=u;var _,a=n(610),r=a.LongBits,i=a.base64,s=a.utf8;function o(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}function c(){}function l(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function u(){this.len=0,this.head=new o(c,0,0),this.tail=this.head,this.states=null}var d=function(){return a.Buffer?function(){return(u.create=function(){return new _})()}:function(){return new u}};function E(e,t,n){t[n]=255&e}function f(e,t){this.len=e,this.next=void 0,this.val=t}function h(e,t,n){for(;e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function g(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}u.create=d(),u.alloc=function(e){return new a.Array(e)},a.Array!==Array&&(u.alloc=a.pool(u.alloc,a.Array.prototype.subarray)),u.prototype._push=function(e,t,n){return this.tail=this.tail.next=new o(e,t,n),this.len+=t,this},f.prototype=Object.create(o.prototype),f.prototype.fn=function(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e},u.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new f((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},u.prototype.int32=function(e){return e<0?this._push(h,10,r.fromNumber(e)):this.uint32(e)},u.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},u.prototype.uint64=function(e){var t=r.from(e);return this._push(h,t.length(),t)},u.prototype.int64=u.prototype.uint64,u.prototype.sint64=function(e){var t=r.from(e).zzEncode();return this._push(h,t.length(),t)},u.prototype.bool=function(e){return this._push(E,1,e?1:0)},u.prototype.fixed32=function(e){return this._push(g,4,e>>>0)},u.prototype.sfixed32=u.prototype.fixed32,u.prototype.fixed64=function(e){var t=r.from(e);return this._push(g,4,t.lo)._push(g,4,t.hi)},u.prototype.sfixed64=u.prototype.fixed64,u.prototype.float=function(e){return this._push(a.float.writeFloatLE,4,e)},u.prototype.double=function(e){return this._push(a.float.writeDoubleLE,8,e)};var p=a.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var _=0;_<e.length;++_)t[n+_]=e[_]};u.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(E,1,0);if(a.isString(e)){var n=u.alloc(t=i.length(e));i.decode(e,n,0),e=n}return this.uint32(t)._push(p,t,e)},u.prototype.string=function(e){var t=s.length(e);return t?this.uint32(t)._push(s.write,t,e):this._push(E,1,0)},u.prototype.fork=function(){return this.states=new l(this),this.head=this.tail=new o(c,0,0),this.len=0,this},u.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new o(c,0,0),this.len=0),this},u.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this},u.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t},u._configure=function(e){_=e,u.create=d(),_._configure()}},529:e=>{e.exports={}},595:(e,t,n)=>{e.exports=a;var _=n(610);function a(e,t,n){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");_.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(n)}(a.prototype=Object.create(_.EventEmitter.prototype)).constructor=a,a.prototype.rpcCall=function e(t,n,a,r,i){if(!r)throw TypeError("request must be specified");var s=this;if(!i)return _.asPromise(e,s,t,n,a,r);if(s.rpcImpl)try{return s.rpcImpl(t,n[s.requestDelimited?"encodeDelimited":"encode"](r).finish(),function(e,n){if(e)return s.emit("error",e,t),i(e);if(null!==n){if(!(n instanceof a))try{n=a[s.responseDelimited?"decodeDelimited":"decode"](n)}catch(e){return s.emit("error",e,t),i(e)}return s.emit("data",n,t),i(null,n)}s.end(!0)})}catch(e){return s.emit("error",e,t),void setTimeout(function(){i(e)},0)}else setTimeout(function(){i(Error("already ended"))},0)},a.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},610:function(e,t,n){var _=t;function a(e,t,n){for(var _=Object.keys(t),a=0;a<_.length;++a)void 0!==e[_[a]]&&n||(e[_[a]]=t[_[a]]);return e}function r(e){function t(e,n){if(!(this instanceof t))return new t(e,n);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),n&&a(this,n)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}_.asPromise=n(45),_.base64=n(839),_.EventEmitter=n(358),_.float=n(410),_.inquire=n(153),_.utf8=n(447),_.pool=n(390),_.LongBits=n(239),_.isNode=Boolean("undefined"!=typeof globalThis&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node),_.global=_.isNode&&globalThis||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,_.emptyArray=Object.freeze?Object.freeze([]):[],_.emptyObject=Object.freeze?Object.freeze({}):{},_.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},_.isString=function(e){return"string"==typeof e||e instanceof String},_.isObject=function(e){return e&&"object"==typeof e},_.isset=_.isSet=function(e,t){var n=e[t];return!(null==n||!e.hasOwnProperty(t))&&("object"!=typeof n||(Array.isArray(n)?n.length:Object.keys(n).length)>0)},_.Buffer=function(){try{var e=_.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),_._Buffer_from=null,_._Buffer_allocUnsafe=null,_.newBuffer=function(e){return"number"==typeof e?_.Buffer?_._Buffer_allocUnsafe(e):new _.Array(e):_.Buffer?_._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},_.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,_.Long=_.global.dcodeIO&&_.global.dcodeIO.Long||_.global.Long||_.inquire("long"),_.key2Re=/^true|false|0|1$/,_.key32Re=/^-?(?:0|[1-9][0-9]*)$/,_.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,_.longToHash=function(e){return e?_.LongBits.from(e).toHash():_.LongBits.zeroHash},_.longFromHash=function(e,t){var n=_.LongBits.fromHash(e);return _.Long?_.Long.fromBits(n.lo,n.hi,t):n.toNumber(Boolean(t))},_.merge=a,_.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},_.newError=r,_.ProtocolError=r("ProtocolError"),_.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=1;return function(){for(var e=Object.keys(this),n=e.length-1;n>-1;--n)if(1===t[e[n]]&&void 0!==this[e[n]]&&null!==this[e[n]])return e[n]}},_.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n)e[n]!==t&&delete this[e[n]]}},_.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},_._configure=function(){var e=_.Buffer;e?(_._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,n){return new e(t,n)},_._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):_._Buffer_from=_._Buffer_allocUnsafe=null}},818:(e,t,n)=>{e.exports=r;var _=n(449);(r.prototype=Object.create(_.prototype)).constructor=r;var a=n(610);function r(){_.call(this)}function i(e,t,n){e.length<40?a.utf8.write(e,t,n):t.utf8Write?t.utf8Write(e,n):t.write(e,n)}r._configure=function(){r.alloc=a._Buffer_allocUnsafe,r.writeBytesBuffer=a.Buffer&&a.Buffer.prototype instanceof Uint8Array&&"set"===a.Buffer.prototype.set.name?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var _=0;_<e.length;)t[n++]=e[_++]}},r.prototype.bytes=function(e){a.isString(e)&&(e=a._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(r.writeBytesBuffer,t,e),this},r.prototype.string=function(e){var t=a.Buffer.byteLength(e);return this.uint32(t),t&&this._push(i,t,e),this},r._configure()},839:(e,t)=>{var n=t;n.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&"="===e.charAt(t);)++n;return Math.ceil(3*e.length)/4-n};for(var _=new Array(64),a=new Array(123),r=0;r<64;)a[_[r]=r<26?r+65:r<52?r+71:r<62?r-4:r-59|43]=r++;n.encode=function(e,t,n){for(var a,r=null,i=[],s=0,o=0;t<n;){var c=e[t++];switch(o){case 0:i[s++]=_[c>>2],a=(3&c)<<4,o=1;break;case 1:i[s++]=_[a|c>>4],a=(15&c)<<2,o=2;break;case 2:i[s++]=_[a|c>>6],i[s++]=_[63&c],o=0}s>8191&&((r||(r=[])).push(String.fromCharCode.apply(String,i)),s=0)}return o&&(i[s++]=_[a],i[s++]=61,1===o&&(i[s++]=61)),r?(s&&r.push(String.fromCharCode.apply(String,i.slice(0,s))),r.join("")):String.fromCharCode.apply(String,i.slice(0,s))};var i="invalid encoding";n.decode=function(e,t,n){for(var _,r=n,s=0,o=0;o<e.length;){var c=e.charCodeAt(o++);if(61===c&&s>1)break;if(void 0===(c=a[c]))throw Error(i);switch(s){case 0:_=c,s=1;break;case 1:t[n++]=_<<2|(48&c)>>4,_=c,s=2;break;case 2:t[n++]=(15&_)<<4|(60&c)>>2,_=c,s=3;break;case 3:t[n++]=(3&_)<<6|c,s=0}}if(1===s)throw Error(i);return n-r},n.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},946:(e,t,n)=>{e.exports=n(394)}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(n.exports,n,n.exports,__webpack_require__),n.exports}__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var __webpack_exports__={};class DNTStorageAdapter{constructor(e){this.configStorage=e}async getFieldsForType(e){try{return await this.configStorage.getDNTFieldsForType(e)}catch(t){return console.error(`Failed to get DNT fields for type ${e}:`,t),{}}}async setFieldDNT(e,t,n){try{await this.configStorage.setDNTField(e,t,n),console.log(`Set DNT=${n} for ${e}.${t} (applies to all ${e} documents)`)}catch(n){throw console.error(`Failed to set DNT for ${e}.${t}:`,n),n}}async toggleFieldDNT(e,t){try{const n=await this.configStorage.toggleDNTField(e,t);return console.log(`Toggled DNT to ${n} for ${e}.${t} (applies to all ${e} documents)`),n}catch(n){throw console.error(`Failed to toggle DNT for ${e}.${t}:`,n),n}}async getFieldDNT(e,t){try{return await this.configStorage.getDNTFieldStatus(e,t)}catch(n){return console.error(`Failed to get DNT status for ${e}.${t}:`,n),!1}}async clearFieldsForType(e){try{await this.configStorage.clearDNTFieldsForType(e),console.log(`Cleared all DNT fields for type ${e}`)}catch(t){throw console.error(`Failed to clear DNT fields for type ${e}:`,t),t}}async getAllDNTFields(){try{return await this.configStorage.getAllDNTFields()}catch(e){return console.error("Failed to get all DNT fields:",e),{}}}async getPreferences(e){return console.warn("getPreferences(documentId) is deprecated. Use getFieldsForType(documentType) instead."),null}async savePreferences(e){console.warn("savePreferences is deprecated. Use setFieldDNT instead.");for(const[t,n]of Object.entries(e.fields))await this.setFieldDNT(e.documentType,t,n)}async clearPreferences(e){console.warn("clearPreferences(documentId) is deprecated. Use clearFieldsForType(documentType) instead.")}}class LegacyDNTStorageAdapter{getStorageKey(e){return`${LegacyDNTStorageAdapter.STORAGE_KEY_PREFIX}${e}`}async getPreferences(e){try{const t=this.getStorageKey(e),n=localStorage.getItem(t);return n?JSON.parse(n):null}catch(t){return console.error(`Failed to get legacy DNT preferences for ${e}:`,t),null}}async savePreferences(e){try{const t=this.getStorageKey(e.documentId),n={...e,updatedAt:(new Date).toISOString()};localStorage.setItem(t,JSON.stringify(n))}catch(e){throw console.error("Failed to save legacy DNT preferences:",e),e}}async clearPreferences(e){try{const t=this.getStorageKey(e);localStorage.removeItem(t)}catch(e){throw console.error("Failed to clear legacy DNT preferences:",e),e}}async migrateToUnified(e,t,n){const _=await this.getPreferences(t);if(_){console.log(`Migrating DNT preferences for ${t} (${n}) to unified config...`);for(const[t,a]of Object.entries(_.fields))await e.setDNTField(n,t,a);await this.clearPreferences(t),console.log(`Migration complete for ${t}`)}}}LegacyDNTStorageAdapter.STORAGE_KEY_PREFIX="sanity-translation-dnt-";const UNIFIED_CONFIG_DOC_ID="sanity-translation-plugin.config",UNIFIED_CONFIG_DOC_TYPE="EL_PluginConfiguration";class UnifiedConfigStorage{constructor(e){this.client=e}convertDNTArrayToMap(e){if(!e||!Array.isArray(e))return{};const t={};for(const n of e)if(n.documentType&&n.fields){t[n.documentType]={};for(const e of n.fields)e.fieldPath&&(t[n.documentType][e.fieldPath]=!1!==e.dnt)}return t}convertDNTMapToArray(e){if(!e||"object"!=typeof e)return[];const t=[];for(const[n,_]of Object.entries(e)){const e=Object.entries(_).map(([e,t])=>({_key:`${n}-${e}`.replace(/[^a-zA-Z0-9-_]/g,"-"),fieldPath:e,dnt:t}));t.push({documentType:n,fields:e})}return t}async load(){try{const e=await this.client.fetch("*[_id == $id][0]",{id:UNIFIED_CONFIG_DOC_ID});if(!e)return console.log("No unified configuration found in Sanity"),null;let t={};e.dntFieldConfigurations?t=this.convertDNTArrayToMap(e.dntFieldConfigurations):e.dntFieldMap&&(t=e.dntFieldMap);const n={projectId:e.projectId,accessToken:e.accessToken,translationApiEndpoint:e.translationApiEndpoint,requestContentType:e.requestContentType,responseAcceptHeader:e.responseAcceptHeader,defaultDocumentCreationMode:e.defaultDocumentCreationMode,locales:e.locales||[],defaultLocale:e.defaultLocale,dntFieldMap:t,version:e.version||"1.0.0",lastUpdated:e.lastUpdated};return console.log("Loaded unified configuration from Sanity"),n}catch(e){throw console.error("Failed to load unified configuration from Sanity:",e),e}}async save(e){try{const t=this.convertDNTMapToArray(e.dntFieldMap),n={_id:UNIFIED_CONFIG_DOC_ID,_type:UNIFIED_CONFIG_DOC_TYPE,projectId:e.projectId,accessToken:e.accessToken,translationApiEndpoint:e.translationApiEndpoint,requestContentType:e.requestContentType,responseAcceptHeader:e.responseAcceptHeader,defaultDocumentCreationMode:e.defaultDocumentCreationMode,locales:e.locales,defaultLocale:e.defaultLocale,dntFieldConfigurations:t,version:e.version,lastUpdated:(new Date).toISOString()};await this.client.createOrReplace(n),console.log("Saved unified configuration to Sanity")}catch(e){throw console.error("Failed to save unified configuration to Sanity:",e),e}}async update(e){try{const t={...await this.load()||{},...e,lastUpdated:(new Date).toISOString()};await this.save(t)}catch(e){throw console.error("Failed to update unified configuration:",e),e}}async delete(){try{await this.client.delete(UNIFIED_CONFIG_DOC_ID),console.log("Deleted unified configuration from Sanity")}catch(e){throw console.error("Failed to delete unified configuration from Sanity:",e),e}}async loadOAuth(){const e=await this.load();return e&&e.projectId&&e.accessToken?{projectId:e.projectId,accessToken:e.accessToken}:null}async saveOAuth(e){await this.update({projectId:e.projectId,accessToken:e.accessToken})}async loadLocale(){const e=await this.load();return e?{locales:e.locales||[],defaultLocale:e.defaultLocale,version:e.version||"1.0.0",lastUpdated:e.lastUpdated||(new Date).toISOString()}:null}async saveLocale(e){await this.update({locales:e.locales,defaultLocale:e.defaultLocale})}async getDNTFieldsForType(e){const t=await this.load();return t?.dntFieldMap?.[e]||{}}async setDNTField(e,t,n){const _=(await this.load()||{}).dntFieldMap||{};_[e]||(_[e]={}),_[e][t]=n,await this.update({dntFieldMap:_})}async toggleDNTField(e,t){const n=(await this.load()||{}).dntFieldMap||{};n[e]||(n[e]={});const _=n[e][t]||!1;return n[e][t]=!_,await this.update({dntFieldMap:n}),n[e][t]}async getDNTFieldStatus(e,t){return(await this.getDNTFieldsForType(e))[t]||!1}async clearDNTFieldsForType(e){const t=(await this.load()||{}).dntFieldMap||{};delete t[e],await this.update({dntFieldMap:t})}async getAllDNTFields(){const e=await this.load();return e?.dntFieldMap||{}}async getTranslationEndpoint(){const e=await this.load();return e?.translationApiEndpoint||"https://app.easyling.com/_el/ext/direct/sanity"}async getRequestContentType(){const e=await this.load();return e?.requestContentType||"application/json"}async getResponseAcceptHeader(){const e=await this.load();return e?.responseAcceptHeader||"application/json"}async getDefaultDocumentCreationMode(){const e=await this.load();return e?.defaultDocumentCreationMode||"draft"}}class DNTServiceManager{constructor(){this.dntStorage=null,this.client=null}static getInstance(e){return DNTServiceManager.instance||(DNTServiceManager.instance=new DNTServiceManager),e&&!DNTServiceManager.instance.client&&DNTServiceManager.instance.initialize(e),DNTServiceManager.instance}initialize(e){if(this.client&&this.dntStorage)return;this.client=e;const t=new UnifiedConfigStorage(e);this.dntStorage=new DNTStorageAdapter(t),console.log("DNT Service Manager initialized")}getDNTStorage(){if(!this.dntStorage)throw new Error("DNT Service Manager not initialized. Call initialize() with a SanityClient first.");return this.dntStorage}isInitialized(){return null!==this.dntStorage}static reset(){DNTServiceManager.instance=null}}function getDNTStorage(){return DNTServiceManager.getInstance().getDNTStorage()}DNTServiceManager.instance=null;class ContentExtractor{inferSanityType(e){if(null==e)return"undefined";if("object"==typeof e&&!Array.isArray(e)){const t=e;if(t._type)return t._type}return"string"==typeof e?"string":"number"==typeof e?"number":"boolean"==typeof e?"boolean":Array.isArray(e)?"array":"object"==typeof e?"object":"unknown"}async extractDocumentContent(e){if(!e||!e._id)throw new Error("Invalid document provided");return this.convertToHtml(e)}convertToHtml(e){if(!e)return"";let t="";for(const[n,_]of Object.entries(e))n.startsWith("_")||_&&(t+=this.processField(n,_));return t.trim()}async extractStructuredContent(e){if(!e||!e._id)throw new Error("Invalid document provided");const t=this.extractTitle(e),n=this.extractSlug(e),{bodyContent:_,fields:a}=this.separateContentAndFields(e),r=e._type||"document",i=await this.applyDNTPreferences(r,a);return{documentId:e._id,title:t,htmlContent:_,slug:n,fields:i}}async applyDNTPreferences(e,t){try{const n=getDNTStorage(),_=await n.getFieldsForType(e);if(!_||0===Object.keys(_).length)return t;const a={};for(const[e,n]of Object.entries(t)){const t=_[e]||!1;if(n&&"object"==typeof n&&"value"in n){const _=n;a[e]={..._,dnt:t}}else a[e]={value:n,dnt:t,type:this.inferSanityType(n)}}return a}catch(n){return console.warn(`Failed to apply DNT preferences for document type ${e}:`,n),t}}async extractBulkContent(e){const t=[];for(const n of e)try{const e=await this.extractDocumentContent(n),_=this.extractTitle(n);t.push({documentId:n._id,title:_,htmlContent:e})}catch(e){console.warn(`Failed to extract content from document ${n._id}:`,e)}return t}async extractBulkStructuredContent(e){const t=[];for(const n of e)try{const e=await this.extractStructuredContent(n);t.push(e)}catch(e){console.warn(`Failed to extract structured content from document ${n?._id||"unknown"}:`,e)}return t}processField(e,t){return null==t?"":Array.isArray(t)?this.processArray(e,t):"object"==typeof t?this.processObject(e,t):"string"==typeof t||"number"==typeof t?this.wrapInHtml(e,String(t)):""}processArray(e,t){let n="";if(t.every(e=>e&&"object"==typeof e&&"block"===e._type&&("bullet"===e.listItem||"number"===e.listItem))){const e="number"===t[0]?.listItem?"ol":"ul";n+=`<${e}>`;for(const e of t)"block"===e._type&&(n+=`<li>${this.processPortableTextBlockContent(e)}</li>`);n+=`</${e}>`}else for(const _ of t)_&&"object"==typeof _?"block"===_._type?n+=this.processPortableTextBlock(_):n+=this.processObject(e,_):n+=this.wrapInHtml("item",String(_));return n}processPortableTextBlock(e){const t=this.processPortableTextBlockContent(e);switch(e.style||"normal"){case"h1":return`<h1>${t}</h1>`;case"h2":return`<h2>${t}</h2>`;case"h3":return`<h3>${t}</h3>`;case"h4":return`<h4>${t}</h4>`;case"h5":return`<h5>${t}</h5>`;case"h6":return`<h6>${t}</h6>`;case"blockquote":return`<blockquote>${t}</blockquote>`;default:return`<p>${t}</p>`}}processPortableTextBlockContent(e){if(!e.children||!Array.isArray(e.children))return"";let t="";for(const n of e.children)if("span"===n._type&&n.text){let e=n.text;if(n.marks&&Array.isArray(n.marks))for(const t of n.marks)if("string"==typeof t)switch(t){case"strong":e=`<strong>${e}</strong>`;break;case"em":e=`<em>${e}</em>`;break;case"underline":e=`<u>${e}</u>`;break;case"code":e=`<code>${e}</code>`}else if("object"==typeof t&&"link"===t._type){const n=t.href||"#";e=`<a href="${this.escapeHtml(n)}">${e}</a>`}t+=e}return t}processObject(e,t){let n="";if("reference"===t._type&&t._ref)return`<span data-reference="${t._ref}">Referenced content</span>`;if("image"===t._type){const e=t.alt||"Image",n=t.caption||"";return`<figure><img alt="${this.escapeHtml(e)}" />${n?`<figcaption>${this.escapeHtml(n)}</figcaption>`:""}</figure>`}if("file"===t._type){const e=t.title||"File";return`<a href="#" data-file-ref="${t.asset?._ref||""}">${this.escapeHtml(e)}</a>`}if("url"===t._type){const e=t.href||"#",n=t.text||e;return`<a href="${this.escapeHtml(e)}">${this.escapeHtml(n)}</a>`}if("geopoint"===t._type){const e=t.lat||0,n=t.lng||0,_=t.alt||"";return`<span data-geopoint data-lat="${e}" data-lng="${n}" ${_?`data-alt="${_}"`:""}>Location: ${e}, ${n}</span>`}if("slug"===t._type){const e=t.current||"";return`<span data-slug="${this.escapeHtml(e)}">${this.escapeHtml(e)}</span>`}if("date"===t._type||"datetime"===t._type){const e=t.value||t;if("string"==typeof e)return`<time datetime="${e}">${new Date(e).toLocaleDateString()}</time>`}if("color"===t._type){const e=t.hex||"#000000";return`<span data-color="${e}" data-alpha="${void 0!==t.alpha?t.alpha:1}" style="color: ${e}">Color: ${e}</span>`}if("span"===t._type&&t.marks&&Array.isArray(t.marks)){let e=t.text||"";for(const n of t.marks)if("string"==typeof n)switch(n){case"strong":e=`<strong>${e}</strong>`;break;case"em":e=`<em>${e}</em>`;break;case"underline":e=`<u>${e}</u>`;break;case"code":e=`<code>${e}</code>`}else if("object"==typeof n&&"link"===n._type){const t=n.href||"#";e=`<a href="${this.escapeHtml(t)}">${e}</a>`}return e}for(const[e,_]of Object.entries(t))!e.startsWith("_")&&_&&(n+=this.processField(e,_));return n}wrapInHtml(e,t){return`<div class="field-${e.replace(/[^a-zA-Z0-9-_]/g,"")}">${this.escapeHtml(t)}</div>`}separateContentAndFields(e){const t=["body","content","text","description","excerpt"],n=["title","slug","_id","_type","_createdAt","_updatedAt","_rev"];let _="";const a={};for(const[n,r]of Object.entries(e))if(!n.startsWith("_")&&"title"!==n&&"slug"!==n&&r)if(t.includes(n))_+=this.processField(n,r);else{let e,t;"object"==typeof r&&null!==r&&"_type"in r&&"slug"===r._type?(e=r.current||"",t="slug"):"object"!=typeof r||null===r||!("_type"in r)||"date"!==r._type&&"datetime"!==r._type?Array.isArray(r)&&r.every(e=>e&&"object"==typeof e&&"block"===e._type)?(e=this.processArray(n,r),t="block"):(e=r,t=this.inferSanityType(r)):(e=r.value||r,t=r._type),a[n]={value:e,dnt:!1,type:t}}if(!_.trim())for(const[t,a]of Object.entries(e))t.startsWith("_")||n.includes(t)||!a||(_+=this.processField(t,a));return{bodyContent:_.trim(),fields:a}}extractSlug(e){if(e.slug){if("object"==typeof e.slug&&null!==e.slug&&"_type"in e.slug&&"slug"===e.slug._type)return e.slug.current||"";if("string"==typeof e.slug)return e.slug}const t=["slug","path","url","permalink"];for(const n of t)if(e[n]){if("object"==typeof e[n]&&null!==e[n]&&"_type"in e[n]&&"slug"===e[n]._type)return e[n].current||"";if("string"==typeof e[n])return e[n]}return""}extractTitle(e){const t=["title","name","heading","label"];for(const n of t)if(e[n]&&"string"==typeof e[n])return e[n];return`${e._type} (${e._id})`}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}class DocumentCreationService{constructor(e,t){this.defaultCreationMode="draft",this.client=e,t&&(this.defaultCreationMode=t)}setDefaultCreationMode(e){this.defaultCreationMode=e}async createDocumentFromTranslation(e,t,n={}){try{const _=this.validateInputsForDocumentCreation(e,t,n);if(!_.isValid)return{success:!1,error:`Input validation failed: ${_.errors.join(", ")}`};const a=t.translatedDocuments?.[0]||t.translatedContent;if(!t.success||!a)return{success:!1,error:"Translation response does not contain valid translated content"};const r=this.validateTranslationResponseForCreation(t);if(!r.isValid)return{success:!1,error:`Translation response validation failed: ${r.errors.join(", ")}`};const i=await this.mergeTranslatedContent(e,a,n),s=this.validateDocumentStructure(i);if(!s.isValid)return{success:!1,error:`Document validation failed: ${s.errors.join(", ")}`};const o=this.validateBusinessRules(i,e);if(!o.isValid)return{success:!1,error:`Business rule validation failed: ${o.errors.join(", ")}`};let c;if(o.slugNeedsFallback){const t=n.targetLanguage||"translated",_="object"==typeof e.slug?e.slug.current:e.slug,a=`${_}_${t}`;"object"==typeof i.slug&&null!==i.slug&&"_type"in i.slug?i.slug={_type:"slug",current:a}:i.slug=a,c={documentId:i._id,originalSlug:_,fallbackSlug:a,locale:t,reason:"Translation did not produce a different slug - locale suffix applied"},console.log(`[Slug Fallback Applied] Document ${i._id}: "${_}" → "${a}"`)}const l=n.creationMode||this.defaultCreationMode;try{let e;if("draft"===l){const t=i._id.startsWith("drafts.")?i._id:`drafts.${i._id}`;console.log("Creating draft document in Sanity:",t),e=await this.client.create({...i,_id:t}),console.log("Draft document created successfully:",e._id)}else{const t=i._id.startsWith("drafts.")?i._id.replace(/^drafts\./,""):i._id;console.log("Creating published document in Sanity:",t),e=await this.client.create({...i,_id:t}),console.log("Published document created successfully:",e._id)}return{success:!0,documentId:e._id,document:e,slugFallback:c}}catch(e){return console.error("Failed to create document in Sanity:",e),{success:!1,error:`Failed to save document to Sanity: ${e instanceof Error?e.message:"Unknown Sanity error"}`}}}catch(t){return{success:!1,error:this.formatErrorMessage(t,e._id)}}}validateInputsForDocumentCreation(e,t,n){const _=[];return e?(e._id||_.push("Original document must have an _id"),e._type||_.push("Original document must have a _type"),t?(n.targetLanguage&&"string"!=typeof n.targetLanguage&&_.push("Target language must be a string"),n.sourceLanguage&&"string"!=typeof n.sourceLanguage&&_.push("Source language must be a string"),void 0!==n.createAsVariant&&"boolean"!=typeof n.createAsVariant&&_.push("createAsVariant must be a boolean"),n.parentDocumentId&&"string"!=typeof n.parentDocumentId&&_.push("parentDocumentId must be a string"),{isValid:0===_.length,errors:_}):(_.push("Translation response is required"),{isValid:!1,errors:_})):(_.push("Original document is required"),{isValid:!1,errors:_})}validateBusinessRules(e,t){const n=[];let _=!1;if(e._id===t._id&&n.push("New document ID must be different from original document ID"),e._type!==t._type&&n.push(`New document type (${e._type}) must match original document type (${t._type})`),this.documentHasContent(e)||n.push("New document must contain some translatable content"),e.slug&&t.slug){const n="object"==typeof e.slug?e.slug.current:e.slug;n===("object"==typeof t.slug?t.slug.current:t.slug)&&(console.warn(`[Slug Fallback] Document ${e._id}: Slug "${n}" is same as original. Will apply locale suffix.`),_=!0)}return{isValid:0===n.length,errors:n,slugNeedsFallback:_}}documentHasContent(e){if(e.title&&"string"==typeof e.title&&e.title.trim().length>0)return!0;const t=["body","content","text","description"];for(const n of t)if(e[n]){if("string"==typeof e[n]&&e[n].trim().length>0)return!0;if(Array.isArray(e[n])&&e[n].length>0)return!0}return!1}formatErrorMessage(e,t){const n=e instanceof Error?e.message:"Unknown error occurred during document creation",_=t?` (Document ID: ${t})`:"";if(e instanceof Error){if(e.message.includes("validation"))return`Document validation error${_}: ${e.message}`;if(e.message.includes("network")||e.message.includes("fetch"))return`Network error during document creation${_}: ${e.message}`;if(e.message.includes("permission")||e.message.includes("unauthorized"))return`Permission error during document creation${_}: ${e.message}`}return`Document creation error${_}: ${n}`}async createBulkDocumentsFromTranslations(e,t,n={}){const _={totalDocuments:e.length,successfulCreations:0,failedCreations:0,results:[],errors:[],rollbackInfo:{canRollback:!0,createdDocumentIds:[],rollbackInstructions:[]},slugFallbacks:[]},a=this.validateBulkTranslationResponses(e,t);if(a.length>0){_.errors.push(...a),_.failedCreations=e.length,_.rollbackInfo.canRollback=!1,_.rollbackInfo.rollbackInstructions.push("No documents were created due to validation failures");for(let t=0;t<e.length;t++)_.results.push({success:!1,error:"Bulk validation failed - no documents created"});return _}const r=[];for(let a=0;a<e.length;a++){const i=e[a],s=t[a];if(!s){const e=`No translation response found for document ${i._id}`;_.results.push({success:!1,error:e}),_.errors.push(e),_.failedCreations++;continue}try{const e=this.validateTranslationResponseForCreation(s);if(!e.isValid){const t=`Pre-creation validation failed for ${i._id}: ${e.errors.join(", ")}`;_.results.push({success:!1,error:t}),_.errors.push(t),_.failedCreations++;continue}const t=s.translatedDocuments||(s.translatedContent?[s.translatedContent]:[]);if(0===t.length){const e=`No translated documents found in response for ${i._id}`;_.results.push({success:!1,error:e}),_.errors.push(e),_.failedCreations++;continue}for(let e=0;e<t.length;e++){const a=t[e],o=a.locale||n.targetLanguage||"translated";console.log(`Creating document for ${i._id} with target locale: ${o}`);const c={...s,translatedDocuments:[a],translatedContent:a},l=await this.createDocumentFromTranslation(i,c,{...n,targetLanguage:o});_.results.push(l),l.success&&l.documentId?(_.successfulCreations++,r.push({documentId:l.documentId,originalId:i._id}),_.rollbackInfo.createdDocumentIds.push(l.documentId),l.slugFallback&&_.slugFallbacks.push(l.slugFallback)):(_.failedCreations++,l.error&&_.errors.push(l.error))}}catch(e){const t=e instanceof Error?e.message:"Unknown error occurred";_.results.push({success:!1,error:t}),_.errors.push(t),_.failedCreations++}}return _.successfulCreations>0?_.rollbackInfo.rollbackInstructions=[`${_.successfulCreations} documents were successfully created.`,"To rollback these changes, you would need to delete the following document IDs:",..._.rollbackInfo.createdDocumentIds.map(e=>`- ${e}`),"Note: This plugin does not automatically delete documents for safety reasons.","Manual deletion through Sanity Studio or API calls would be required."]:_.rollbackInfo.rollbackInstructions=["No documents were created, no rollback needed."],_.slugFallbacks.length>0&&(console.log(`[Slug Fallback Summary] ${_.slugFallbacks.length} document(s) had slug fallback applied:`),_.slugFallbacks.forEach(e=>{console.log(` - ${e.documentId}: "${e.originalSlug}" → "${e.fallbackSlug}" (locale: ${e.locale})`)})),_}validateBulkTranslationResponses(e,t){const n=[];if(e.length!==t.length)return n.push(`Mismatch between original documents (${e.length}) and translation responses (${t.length})`),n;for(let _=0;_<e.length;_++){const a=e[_],r=t[_];a?a._id?a._type?r?r.success&&(0!==(r.translatedDocuments||(r.translatedContent?[r.translatedContent]:[])).length||n.push(`Translation response at index ${_} missing translatedDocuments/translatedContent despite success=true`)):n.push(`Translation response at index ${_} is null or undefined`):n.push(`Original document at index ${_} missing _type`):n.push(`Original document at index ${_} missing _id`):n.push(`Original document at index ${_} is null or undefined`)}return n}validateTranslationResponseForCreation(e){const t=[];if(!e.success)return t.push("Translation response indicates failure"),{isValid:!1,errors:t};const n=e.translatedDocuments||(e.translatedContent?[e.translatedContent]:[]);if(0===n.length)return t.push("Translation response missing translatedDocuments/translatedContent"),{isValid:!1,errors:t};for(let e=0;e<n.length;e++){const _=n[e];"object"==typeof _&&null!==_?(_.body||_.title||_.fields||t.push(`Translated document at index ${e} must contain at least one of: body, title, or fields`),void 0!==_.body&&("string"!=typeof _.body?t.push(`Translated document at index ${e} body must be a string`):0===_.body.trim().length&&t.push(`Translated document at index ${e} body cannot be empty`)),void 0!==_.title&&("string"!=typeof _.title?t.push(`Translated document at index ${e} title must be a string`):0===_.title.trim().length&&t.push(`Translated document at index ${e} title cannot be empty`)),void 0!==_.slug&&("string"!=typeof _.slug?t.push(`Translated document at index ${e} slug must be a string`):0===_.slug.trim().length?t.push(`Translated document at index ${e} slug cannot be empty`):/^[a-z0-9-_]+$/.test(_.slug)||t.push(`Translated document at index ${e} slug must contain only lowercase letters, numbers, hyphens, and underscores`)),void 0!==_.fields&&("object"!=typeof _.fields||null===_.fields||Array.isArray(_.fields))&&t.push(`Translated document at index ${e} fields must be an object`)):t.push(`Translated document at index ${e} must be an object`)}return{isValid:0===t.length,errors:t}}createRollbackPlan(e){return 0===e.length?{canRollback:!0,createdDocumentIds:[],rollbackInstructions:["No documents were created, no rollback needed."]}:{canRollback:!0,createdDocumentIds:[...e],rollbackInstructions:[`Rollback plan for ${e.length} created documents:`,"","1. Manual deletion required (for safety):",...e.map(e=>` - Delete document: ${e}`),"","2. Alternative: Use Sanity CLI or API:"," sanity documents delete <document-id>","","3. Or via Sanity Client API:"," client.delete(documentId)","","WARNING: This plugin does not provide automatic rollback to prevent","accidental data loss. Please review each document before deletion."]}}async mergeTranslatedContent(e,t,n){const _=n.targetLanguage||t.locale,a={...e,_id:this.generateNewDocumentId(e._id,_),_rev:void 0,_createdAt:void 0,_updatedAt:void 0};if(t.title&&t.title.trim()&&(a.title=t.title),t.slug&&t.slug.trim()&&("object"==typeof e.slug&&null!==e.slug&&"_type"in e.slug?a.slug={_type:"slug",current:t.slug}:a.slug=t.slug),t.body&&t.body.trim()){const n=this.convertHtmlToPortableText(t.body),_=["body","content","text","description"];for(const t of _)if(e[t]){a[t]=n;break}_.some(t=>e[t])||(a.body=n)}if(t.fields&&"object"==typeof t.fields)for(const[n,_]of Object.entries(t.fields)){if("title"===n||"slug"===n||void 0===_)continue;const t=this.processTranslatedField(n,_,e[n]);void 0!==t&&(a[n]=t)}_&&(e.locale&&"object"==typeof e.locale&&"value"in e.locale?a.locale={...e.locale,value:_}:a.locale&&"object"==typeof a.locale&&"value"in a.locale?a.locale={...a.locale,value:_}:void 0!==e.locale&&(a.locale=_));const r=Object.keys(a);for(const e of r)null===a[e]&&delete a[e];return n.createAsVariant&&n.parentDocumentId&&(a.parentDocument={_type:"reference",_ref:n.parentDocumentId}),a}processTranslatedField(e,t,n){if(null==t)return t;let _=t,a=!1;if(t&&"object"==typeof t&&"value"in t&&(_=t.value,a=t.dnt||!1),a&&void 0!==n)return n;if(n&&"object"==typeof n&&null!==n){if("dnt"in n&&"value"in n){let e=_;return t&&"object"==typeof t&&"value"in t&&(e=t.value),null!=e&&""!==e||null===n.value||void 0===n.value||""===n.value?{dnt:a,value:e}:n}if("_type"in n&&"slug"===n._type)return{_type:"slug",current:"string"==typeof _?_:String(_)};if("_type"in n&&("date"===n._type||"datetime"===n._type))return{_type:n._type,value:_};if("_type"in n&&"reference"===n._type)return n}return"string"==typeof _&&this.isHtmlContent(_)?this.convertHtmlToPortableText(_):_}convertHtmlToPortableText(e){if(!e||!e.trim())return[];const t=[],n=/<(h[1-6]|p|div|blockquote|li)([^>]*)>(.*?)<\/\1>/gi;let _,a=0;for(;null!==(_=n.exec(e));){const[e,n,r,i]=_;if(!i.trim())continue;const s={_type:"block",_key:this.generateBlockKey(),style:this.getBlockStyle(n.toLowerCase()),children:this.parseInlineContent(i),markDefs:[]};"li"===n.toLowerCase()&&(s.listItem="bullet"),t.push(s),a=_.index+e.length}const r=e.substring(a).trim();if(r){const e=r.replace(/<[^>]+>/g,"").trim();e&&t.push({_type:"block",_key:this.generateBlockKey(),style:"normal",children:this.parseInlineContent(e),markDefs:[]})}if(0===t.length&&e.trim()){const n=e.replace(/<[^>]+>/g,"").trim();n&&t.push({_type:"block",_key:this.generateBlockKey(),style:"normal",children:this.parseInlineContent(n),markDefs:[]})}return t}parseInlineContent(e){const t=[],n=e.replace(/<strong[^>]*>(.*?)<\/strong>/gi,"**$1**").replace(/<em[^>]*>(.*?)<\/em>/gi,"*$1*").replace(/<u[^>]*>(.*?)<\/u>/gi,"_$1_").replace(/<code[^>]*>(.*?)<\/code>/gi,"`$1`").replace(/<[^>]+>/g,"").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'");return n.trim()&&t.push({_type:"span",_key:this.generateSpanKey(),text:n,marks:[]}),t}getBlockStyle(e){return{h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",blockquote:"blockquote",p:"normal",div:"normal",li:"normal"}[e]||"normal"}isHtmlContent(e){return/<[^>]+>/.test(e)}generateNewDocumentId(e,t){return`${e.startsWith("drafts.")?e.replace(/^drafts\./,""):e}${t?`-${t}`:"-translated"}-${Date.now()}`}generateBlockKey(){return Math.random().toString(36).substr(2,9)}generateSpanKey(){return Math.random().toString(36).substr(2,9)}validateDocumentStructure(e){const t=[];e._id||t.push("Document must have an _id"),e._type||t.push("Document must have a _type");const n=["body","content","text","description"];for(const _ of n)if(e[_]&&Array.isArray(e[_])){const n=this.validatePortableTextArray(e[_],_);n.isValid||t.push(...n.errors)}if(e.slug&&"object"==typeof e.slug&&null!==e.slug&&"_type"in e.slug){const n=e.slug;"slug"!==n._type&&t.push('Slug object must have _type of "slug"'),n.current||t.push("Slug object must have a current value")}return{isValid:0===t.length,errors:t}}validatePortableTextArray(e,t){const n=[];if(!Array.isArray(e))return n.push(`${t} must be an array`),{isValid:!1,errors:n};for(let _=0;_<e.length;_++){const a=e[_];if(!a||"object"!=typeof a){n.push(`${t}[${_}] must be an object`);continue}const r=a;if(r._type||n.push(`${t}[${_}] must have a _type`),r._key||n.push(`${t}[${_}] must have a _key`),"block"===r._type)if(Array.isArray(r.children)){const e=r.children;for(let a=0;a<e.length;a++){const r=e[a];if(!r||"object"!=typeof r){n.push(`${t}[${_}].children[${a}] must be an object`);continue}const i=r;i._type||n.push(`${t}[${_}].children[${a}] must have a _type`),i._key||n.push(`${t}[${_}].children[${a}] must have a _key`)}}else n.push(`${t}[${_}] block must have children array`)}return{isValid:0===n.length,errors:n}}}const LOCALE_CODE_REGEX=/^[a-z]{2}-[A-Z]{2}$/;function validateLocaleCode(e){return!(!e||"string"!=typeof e)&&LOCALE_CODE_REGEX.test(e)}function validateLocaleDefinition(e){const t=[],n=[];return e.code?validateLocaleCode(e.code)||t.push("Locale code must be in format: xx-XX (e.g., en-US, fr-FR)"):t.push("Locale code is required"),e.displayName?0===e.displayName.trim().length?t.push("Display name cannot be empty"):e.displayName.length>100&&n.push("Display name is very long (over 100 characters)"):t.push("Display name is required"),void 0!==e.enabled&&"boolean"!=typeof e.enabled&&t.push("Enabled flag must be a boolean value"),e.createdAt&&!isValidISODate(e.createdAt)&&t.push("createdAt must be a valid ISO 8601 date string"),e.updatedAt&&!isValidISODate(e.updatedAt)&&t.push("updatedAt must be a valid ISO 8601 date string"),{isValid:0===t.length,errors:t,warnings:n}}function validateLocaleConfig(e){const t=[],n=[];if(e.locales)if(Array.isArray(e.locales)){const _=new Set;e.locales.forEach((e,a)=>{const r=validateLocaleDefinition(e);r.isValid||t.push(`Locale at index ${a}: ${r.errors.join(", ")}`),r.warnings.length>0&&n.push(`Locale at index ${a}: ${r.warnings.join(", ")}`),e.code&&(_.has(e.code)&&t.push(`Duplicate locale code: ${e.code}`),_.add(e.code))}),0===e.locales.length&&n.push("No locales configured - users will not be able to translate content")}else t.push("Locales must be an array");else t.push("Locales array is required");return e.defaultLocale&&(validateLocaleCode(e.defaultLocale)?e.locales&&Array.isArray(e.locales)&&(e.locales.some(t=>t.code===e.defaultLocale)||n.push("Default locale is not in the configured locales list")):t.push("Default locale must be in format: xx-XX (e.g., en-US)")),e.version?"string"!=typeof e.version&&t.push("Configuration version must be a string"):t.push("Configuration version is required"),e.lastUpdated?isValidISODate(e.lastUpdated)||t.push("lastUpdated must be a valid ISO 8601 date string"):t.push("lastUpdated timestamp is required"),{isValid:0===t.length,errors:t,warnings:n}}function localeExists(e,t){return e.locales.some(e=>e.code===t)}function getEnabledLocales(e){return e.locales.filter(e=>e.enabled)}function findLocaleByCode(e,t){return e.locales.find(e=>e.code===t)}function isValidISODate(e){if(!e||"string"!=typeof e)return!1;const t=new Date(e);return t instanceof Date&&!isNaN(t.getTime())&&t.toISOString()===e}const RadioWithDefault=e=>{const{value:t,onChange:n,defaultValue:_,renderDefault:a}=e;return __WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{null!=t&&""!==t||n(__WEBPACK_EXTERNAL_MODULE_sanity_set__(_))},[t,_,n]),a({...e,value:null!=t&&""!==t?t:_})};RadioWithDefault.displayName="RadioWithDefault";const createPluginConfigSchema=e=>({name:"EL_PluginConfiguration",title:"Easyling Translation Plugin Configuration",type:"document",fields:[{name:"projectId",title:"Project ID",type:"string",description:"Easyling project identifier",group:"oauth"},{name:"accessToken",title:"Access Token",type:"string",description:"Easyling API access token (hidden for security)",group:"oauth",...e&&{components:{input:e}}},{name:"translationApiEndpoint",title:"Translation API Endpoint",type:"string",description:"The URL where translation requests will be sent (defaults to https://app.easyling.com/_el/ext/direct/sanity if not set)",initialValue:"https://app.easyling.com/_el/ext/direct/sanity",placeholder:"https://app.easyling.com/_el/ext/direct/sanity",group:"translation",validation:e=>e.custom(e=>{if(!e||""===e.trim())return!0;try{const t=new URL(e.trim());return!!["http:","https:"].includes(t.protocol)||"Must be a valid HTTP or HTTPS URL"}catch(e){return"Must be a valid HTTP or HTTPS URL"}})},{name:"defaultDocumentCreationMode",title:"Default Document Creation Mode",type:"string",description:"Whether translated documents should be created as drafts or published by default",initialValue:"draft",group:"translation",options:{list:[{title:"Draft",value:"draft"},{title:"Published",value:"published"}],layout:"radio"},components:{input:e=>RadioWithDefault({...e,defaultValue:"draft"})}},{name:"requestContentType",title:"Request Content-Type",type:"string",description:"Serialization format for translation request payloads",initialValue:"application/json",group:"advanced",options:{list:[{title:"JSON",value:"application/json"},{title:"Protocol Buffer",value:"application/x-protobuf"}],layout:"radio"},components:{input:e=>RadioWithDefault({...e,defaultValue:"application/json"})}},{name:"responseAcceptHeader",title:"Response Accept Header",type:"string",description:"Preferred format for translation response (content negotiation)",initialValue:"application/json",group:"advanced",options:{list:[{title:"JSON",value:"application/json"},{title:"Protocol Buffer",value:"application/x-protobuf"}],layout:"radio"},components:{input:e=>RadioWithDefault({...e,defaultValue:"application/json"})}},{name:"locales",title:"Available Locales",type:"array",description:"Configure the locales available for translation",group:"locales",of:[{type:"object",name:"localeItem",title:"Locale",fields:[{name:"code",title:"Locale Code",type:"string",description:"Locale code in ISO 639-1 + ISO 3166-1 format (e.g., en-US, fr-FR)",validation:e=>e.required().regex(/^[a-z]{2}-[A-Z]{2}$/,{name:"locale-code",invert:!1}).error("Locale code must be in format: xx-XX (e.g., en-US, fr-FR)")},{name:"displayName",title:"Display Name",type:"string",description:"Human-readable name for this locale (e.g., English (United States))",validation:e=>e.required().min(1).error("Display name is required")},{name:"enabled",title:"Enabled",type:"boolean",description:"Whether this locale is available for translation",initialValue:!0},{name:"createdAt",title:"Created At",type:"string",hidden:!0},{name:"updatedAt",title:"Updated At",type:"string",hidden:!0}],preview:{select:{title:"displayName",subtitle:"code",enabled:"enabled"},prepare:({title:e,subtitle:t,enabled:n})=>({title:e||"Unnamed Locale",subtitle:t?`${t}${!1===n?" (Disabled)":""}`:""})}}]},{name:"defaultLocale",title:"Default Locale",type:"string",description:"Default locale code to use when none is specified",group:"locales",validation:e=>e.regex(/^[a-z]{2}-[A-Z]{2}$/,{name:"locale-code",invert:!1}).error("Default locale must be in format: xx-XX (e.g., en-US)")},{name:"dntFieldConfigurations",title:"DNT Field Configurations",type:"array",description:"Document type DNT (Do Not Translate) field configurations. When you mark a field as DNT for a document type, it applies to all documents of that type. This is automatically managed when you toggle DNT badges in documents.",group:"dnt",readOnly:!0,of:[{type:"object",name:"dntTypeConfig",title:"Document Type DNT Configuration",fields:[{name:"documentType",title:"Document Type",type:"string",description:'The document type (e.g., "product", "article")',validation:e=>e.required()},{name:"fields",title:"DNT Fields",type:"array",description:"Fields marked as Do Not Translate",of:[{type:"object",name:"dntField",fields:[{name:"fieldPath",title:"Field Path",type:"string",description:'The field path (e.g., "sku", "price")',validation:e=>e.required()},{name:"dnt",title:"Do Not Translate",type:"boolean",description:"Whether this field should not be translated",initialValue:!0}],preview:{select:{fieldPath:"fieldPath",dnt:"dnt"},prepare:({fieldPath:e,dnt:t})=>({title:e||"Unknown field",subtitle:t?"Do Not Translate":"Translatable"})}}]}],preview:{select:{documentType:"documentType",fields:"fields"},prepare:({documentType:e,fields:t})=>({title:e||"Unknown type",subtitle:t?`${t.length} DNT field${1!==t.length?"s":""}`:"No DNT fields"})}}]},{name:"version",title:"Configuration Version",type:"string",description:"Internal version for configuration migration",initialValue:"1.0.0",readOnly:!0,hidden:!0},{name:"lastUpdated",title:"Last Updated",type:"datetime",description:"When this configuration was last modified",readOnly:!0,hidden:!0}],groups:[{name:"oauth",title:"Authentication",default:!0},{name:"translation",title:"Translation Settings"},{name:"locales",title:"Locales"},{name:"dnt",title:"DNT Field Configuration",description:"View DNT (Do Not Translate) settings for all document types"},{name:"advanced",title:"☢️ CAUTION ☢️ Dangerous Advanced Settings",description:"Advanced developer settings for request/response serialization. Changing these settings may break compatibility with your translation service."}],preview:{prepare:()=>({title:"Easyling Translation Plugin Configuration",subtitle:"OAuth, Translation Settings, Locales, and DNT field settings"})}}),pluginConfigSchema=createPluginConfigSchema(),legacyLocaleConfigSchema={name:"EL_translation-plugin-config",title:"Translation Plugin Configuration (Legacy)",type:"object",fields:[{name:"locales",title:"Available Locales",type:"array",description:"Configure the locales available for translation",of:[{type:"object",title:"Locale",fields:[{name:"code",title:"Locale Code",type:"string",description:"Locale code in ISO 639-1 + ISO 3166-1 format (e.g., en-US, fr-FR)",validation:e=>e.required().regex(/^[a-z]{2}-[A-Z]{2}$/,{name:"locale-code",invert:!1}).error("Locale code must be in format: xx-XX (e.g., en-US, fr-FR)")},{name:"displayName",title:"Display Name",type:"string",description:"Human-readable name for this locale (e.g., English (United States))",validation:e=>e.required().min(1).error("Display name is required")},{name:"enabled",title:"Enabled",type:"boolean",description:"Whether this locale is available for translation",initialValue:!0}],preview:{select:{title:"displayName",subtitle:"code",enabled:"enabled"},prepare:({title:e,subtitle:t,enabled:n})=>({title:e||"Unnamed Locale",subtitle:`${t}${n?"":" (Disabled)"}`,media:n?"🌐":"🚫"})}}]},{name:"defaultLocale",title:"Default Locale",type:"string",description:"Default locale code to use when none is specified",validation:e=>e.regex(/^[a-z]{2}-[A-Z]{2}$/,{name:"locale-code",invert:!1}).error("Default locale must be in format: xx-XX (e.g., en-US)")},{name:"version",title:"Configuration Version",type:"string",description:"Internal version for configuration migration",initialValue:"1.0.0",readOnly:!0}]},defaultLocaleConfig={locales:[],version:"1.0.0",lastUpdated:(new Date).toISOString()},commonLocales=[{code:"en-US",displayName:"English (United States)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"en-GB",displayName:"English (United Kingdom)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"es-ES",displayName:"Spanish (Spain)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"es-MX",displayName:"Spanish (Mexico)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"fr-FR",displayName:"French (France)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"de-DE",displayName:"German (Germany)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"it-IT",displayName:"Italian (Italy)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"pt-BR",displayName:"Portuguese (Brazil)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"ja-JP",displayName:"Japanese (Japan)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"ko-KR",displayName:"Korean (South Korea)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"zh-CN",displayName:"Chinese (Simplified)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"zh-TW",displayName:"Chinese (Traditional)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}];function pluginConfig_validateLocaleCode(e){return/^[a-z]{2}-[A-Z]{2}$/.test(e)}function createLocaleDefinition(e,t,n=!0){const _=(new Date).toISOString();return{code:e,displayName:t,enabled:n,createdAt:_,updatedAt:_}}function updateLocaleDefinition(e,t){return{...e,...t,updatedAt:(new Date).toISOString()}}class LocaleServiceError extends Error{constructor(e,t,n){super(e),this.code=t,this.details=n,this.name="LocaleServiceError"}}class LocaleService{constructor(e=null,t){this.storageAdapter=e,this.config=t||{...defaultLocaleConfig,locales:[...defaultLocaleConfig.locales]}}async loadConfig(){try{if(!this.storageAdapter)return this.config;const e=await this.storageAdapter.load();if(e){const t=validateLocaleConfig(e);if(!t.isValid)throw console.error("Loaded configuration is invalid:",t.errors),new LocaleServiceError("Configuration is corrupted and cannot be loaded","CONFIG_CORRUPTED",{errors:t.errors});return this.config=e,this.config}return this.config={...defaultLocaleConfig},this.config}catch(e){if(e instanceof LocaleServiceError)throw e;throw new LocaleServiceError("Failed to load locale configuration","LOAD_FAILED",{originalError:e})}}async saveConfig(e){try{const t=e||this.config,n=validateLocaleConfig(t);if(!n.isValid)throw new LocaleServiceError("Cannot save invalid configuration","INVALID_CONFIG",{errors:n.errors});t.lastUpdated=(new Date).toISOString(),this.storageAdapter&&await this.storageAdapter.save(t),this.config=t}catch(e){if(e instanceof LocaleServiceError)throw e;throw new LocaleServiceError("Failed to save locale configuration","SAVE_FAILED",{originalError:e})}}getConfig(){return{...this.config}}getAllLocales(){return[...this.config.locales]}getEnabledLocales(){return this.config.locales.filter(e=>e.enabled)}getLocaleByCode(e){return findLocaleByCode(this.config,e)}hasLocale(e){return localeExists(this.config,e)}async addLocale(e){const t=(new Date).toISOString(),n={...e,createdAt:t,updatedAt:t},_=validateLocaleDefinition(n);if(!_.isValid)throw new LocaleServiceError("Cannot add invalid locale","INVALID_LOCALE",{errors:_.errors});if(this.hasLocale(e.code))throw new LocaleServiceError(`Locale with code '${e.code}' already exists`,"DUPLICATE_LOCALE",{code:e.code});return this.config.locales.push(n),await this.saveConfig(),_}async updateLocale(e,t){const n=this.config.locales.findIndex(t=>t.code===e);if(-1===n)throw new LocaleServiceError(`Locale with code '${e}' not found`,"LOCALE_NOT_FOUND",{code:e});const _=this.config.locales[n],a={..._,...t,code:_.code,createdAt:_.createdAt,updatedAt:(new Date).toISOString()},r=validateLocaleDefinition(a);if(!r.isValid)throw new LocaleServiceError("Cannot update locale with invalid data","INVALID_LOCALE",{errors:r.errors});return this.config.locales[n]=a,await this.saveConfig(),r}async removeLocale(e){const t=this.config.locales.findIndex(t=>t.code===e);if(-1===t)throw new LocaleServiceError(`Locale with code '${e}' not found`,"LOCALE_NOT_FOUND",{code:e});this.config.locales.splice(t,1),this.config.defaultLocale===e&&(this.config.defaultLocale=void 0),await this.saveConfig()}async setDefaultLocale(e){if(!this.hasLocale(e))throw new LocaleServiceError(`Cannot set default locale: locale with code '${e}' not found`,"LOCALE_NOT_FOUND",{code:e});this.config.defaultLocale=e,await this.saveConfig()}async clearDefaultLocale(){this.config.defaultLocale=void 0,await this.saveConfig()}validateCurrentConfig(){return validateLocaleConfig(this.config)}async resetToDefault(){this.config={...defaultLocaleConfig},await this.saveConfig()}async importConfig(e){const t=validateLocaleConfig(e);if(!t.isValid)throw new LocaleServiceError("Cannot import invalid configuration","INVALID_CONFIG",{errors:t.errors});return this.config={...e},await this.saveConfig(),t}exportConfig(){return{...this.config}}}const LEGACY_LOCALE_CONFIG_DOC_ID="sanity-translation-plugin.locale-config",LEGACY_LOCALE_CONFIG_DOC_TYPE="EL_translation-plugin-config";class SanityLocaleStorageAdapter{constructor(e){this.client=e,this.unifiedStorage=new UnifiedConfigStorage(e)}async load(){try{const e=await this.unifiedStorage.loadLocale();if(e&&e.locales&&e.locales.length>0)return console.log("Loaded locale configuration from unified storage"),e;const t=await this.loadLegacy();return t?(console.log("Migrating locale configuration from legacy storage..."),await this.save(t),await this.deleteLegacy(),console.log("Locale configuration migration complete"),t):(console.log("No locale configuration found"),null)}catch(e){throw console.error("Failed to load locale configuration:",e),e}}async save(e){try{await this.unifiedStorage.saveLocale(e),console.log("Saved locale configuration to unified storage")}catch(e){throw console.error("Failed to save locale configuration:",e),e}}async loadLegacy(){try{const e=await this.client.fetch("*[_id == $id][0]",{id:LEGACY_LOCALE_CONFIG_DOC_ID});return e?{locales:e.locales||[],defaultLocale:e.defaultLocale,version:e.version||"1.0.0",lastUpdated:e.lastUpdated||(new Date).toISOString()}:null}catch(e){return console.error("Failed to load legacy locale configuration:",e),null}}async deleteLegacy(){try{await this.client.delete(LEGACY_LOCALE_CONFIG_DOC_ID),console.log("Deleted legacy locale configuration document")}catch(e){console.warn("Failed to delete legacy locale document:",e)}}}const ConfirmationDialog=({open:e,title:t,message:n,details:_,confirmText:a="Confirm",cancelText:r="Cancel",tone:i="primary",closable:s=!0,onConfirm:o,onCancel:c})=>{const l=__WEBPACK_EXTERNAL_MODULE_react_useRef__(null);return __WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{e&&l.current&&setTimeout(()=>{l.current?.focus()},100)},[e]),e?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Dialog__,{id:"confirmation-dialog",header:t,onClose:s?c:void 0,onClickOutside:s?c:void 0,width:1,role:"alertdialog","aria-labelledby":"confirmation-dialog-title","aria-describedby":"confirmation-dialog-description",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:4,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:4,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{id:"confirmation-dialog-description",size:2,weight:"regular",children:n}),_&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:_})]})})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{ref:l,text:a,tone:i,onClick:o,mode:"default","aria-label":`${a} action`}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:r,tone:"default",onClick:c,mode:"ghost","aria-label":`${r} action`})]})]})})}):null},SuccessDialog=({open:e,title:t,message:n,details:_,autoCloseTimeout:a,closable:r=!0,onClose:i})=>{const s=__WEBPACK_EXTERNAL_MODULE_react_useRef__(null);return __WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{e&&s.current&&setTimeout(()=>{s.current?.focus()},100)},[e]),__WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{if(!e||!a)return;const t=setTimeout(()=>{i()},a);return()=>clearTimeout(t)},[e,a,i]),e?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Dialog__,{id:"success-dialog",header:t,onClose:r?i:void 0,onClickOutside:r?i:void 0,width:1,role:"dialog","aria-labelledby":"success-dialog-title","aria-describedby":"success-dialog-description",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:4,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:4,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{tone:"positive",padding:3,radius:2,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CheckmarkCircleIcon__,{})})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{id:"success-dialog-description",size:2,weight:"regular",children:n}),_&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:_})]})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{ref:s,text:"Close",tone:"positive",onClick:i,mode:"default","aria-label":"Close success dialog"})]})})}):null},ErrorDialog=({open:e,title:t,message:n,error:_,showRetry:a=!1,retryText:r="Retry",closable:i=!0,onClose:s,onRetry:o})=>{const c=__WEBPACK_EXTERNAL_MODULE_react_useRef__(null);return __WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{e&&c.current&&setTimeout(()=>{c.current?.focus()},100)},[e]),e?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Dialog__,{id:"error-dialog",header:t,onClose:i?s:void 0,onClickOutside:i?s:void 0,width:1,role:"alertdialog","aria-labelledby":"error-dialog-title","aria-describedby":"error-dialog-description",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:4,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:4,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{tone:"critical",padding:3,radius:2,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_ErrorOutlineIcon__,{})})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{id:"error-dialog-description",size:2,weight:"regular",children:n}),_&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{marginTop:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Code__,{size:1,language:"text",children:_.message}),_.stack&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{marginTop:2,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__("details",{children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__("summary",{children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"Stack trace"})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{marginTop:2,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Code__,{size:0,language:"text",children:_.stack})})]})})]})]})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[a&&o&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{ref:c,text:r,tone:"critical",onClick:o,mode:"default","aria-label":`${r} action`}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{ref:a?void 0:c,text:"Close",tone:"default",onClick:s,mode:a?"ghost":"default","aria-label":"Close error dialog"})]})]})})}):null},LocaleSelectionDialog=({open:e,title:t,message:n,availableLocales:_,selectedLocales:a,selectedDocuments:r=[],mode:i,allowMultiple:s=!0,required:o=!0,showCreationModeOption:c=!1,defaultCreationMode:l="draft",onConfirm:u,onCancel:d})=>{const[E,f]=__WEBPACK_EXTERNAL_MODULE_react_useState__(new Set(a)),[h,g]=__WEBPACK_EXTERNAL_MODULE_react_useState__(l),[p,A]=__WEBPACK_EXTERNAL_MODULE_react_useState__(""),[m,L]=__WEBPACK_EXTERNAL_MODULE_react_useState__(null),y=__WEBPACK_EXTERNAL_MODULE_react_useRef__(null),b=__WEBPACK_EXTERNAL_MODULE_react_useRef__(null);__WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{e&&(f(new Set(a)),g(l),A(""),L(null),setTimeout(()=>{y.current?.focus()},100))},[e,a,l]);const T=__WEBPACK_EXTERNAL_MODULE_react_useMemo__(()=>{if(!p.trim())return _.filter(e=>e.enabled);const e=p.toLowerCase();return _.filter(e=>e.enabled).filter(t=>t.code.toLowerCase().includes(e)||t.displayName.toLowerCase().includes(e))},[_,p]),D=e=>{L(null);const t=new Set(E);t.has(e)?t.delete(e):(s||t.clear(),t.add(e)),f(t)},C=()=>{o&&0===E.size?L("Please select at least one locale"):u(Array.from(E),c?h:void 0)};if(__WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{if(!e)return;const t=e=>{"Escape"===e.key?(e.preventDefault(),d()):"Enter"===e.key&&e.ctrlKey&&(e.preventDefault(),C())};return document.addEventListener("keydown",t),()=>{document.removeEventListener("keydown",t)}},[e,E,d]),!e)return null;const O=r.length||1,N=!o||E.size>0;return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Dialog__,{id:"locale-selection-dialog",header:t,onClose:d,onClickOutside:d,width:1,role:"dialog","aria-labelledby":"locale-selection-dialog-title","aria-describedby":"locale-selection-dialog-description",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:4,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:4,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{id:"locale-selection-dialog-description",size:2,weight:"regular",children:n}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"bulk"===i?`Translating ${O} document${1!==O?"s":""}`:"Translating 1 document"})]})})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_TextInput__,{ref:y,icon:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_SearchIcon__,placeholder:"Search locales by code or name...",value:p,onChange:e=>A(e.currentTarget.value),"aria-label":"Search locales"})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{border:!0,padding:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[s&&T.length>1&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{justify:"space-between",align:"center",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"semibold",children:[E.size," of ",T.length," selected"]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:"Select All",mode:"ghost",fontSize:1,padding:2,onClick:()=>{L(null);const e=new Set(T.map(e=>e.code));f(e)},disabled:E.size===T.length}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:"Clear All",mode:"ghost",fontSize:1,padding:2,onClick:()=>{L(null),f(new Set)},disabled:0===E.size})]})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{style:{maxHeight:"300px",overflowY:"auto"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:0===T.length?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,align:"center",children:p?"No locales match your search":"No locales available. Please configure locales first."})}):T.map(e=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,radius:2,shadow:1,style:{cursor:"pointer"},onClick:()=>D(e.code),role:"checkbox","aria-checked":E.has(e.code),tabIndex:0,onKeyDown:t=>{"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),D(e.code))},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Checkbox__,{checked:E.has(e.code),readOnly:!0,"aria-label":`Select ${e.displayName}`}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,flex:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:2,weight:"medium",children:e.displayName}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:e.code})]})]})},e.code))})})]})}),c&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{border:!0,padding:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"semibold",children:"Document Creation Mode"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"Choose whether to create translated documents as drafts or publish them immediately."}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,radius:2,tone:"draft"===h?"primary":"default",style:{cursor:"pointer"},onClick:()=>g("draft"),children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Radio__,{checked:"draft"===h,readOnly:!0,"aria-label":"Create as draft"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,flex:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:2,weight:"medium",children:"Draft"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"Create documents as drafts that need to be published manually"})]})]})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,radius:2,tone:"published"===h?"primary":"default",style:{cursor:"pointer"},onClick:()=>g("published"),children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Radio__,{checked:"published"===h,readOnly:!0,"aria-label":"Create as published"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,flex:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:2,weight:"medium",children:"Published"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"Create and publish documents immediately"})]})]})})]})]})}),m&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{tone:"critical",padding:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,style:{color:"var(--card-fg-color)"},children:m})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{ref:b,text:`Translate to ${E.size} locale${1!==E.size?"s":""}`,tone:"primary",onClick:C,disabled:!N||0===T.length,mode:"default","aria-label":"Confirm locale selection and start translation"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:"Cancel",tone:"default",onClick:d,mode:"ghost","aria-label":"Cancel locale selection"})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,align:"center",children:"Press Ctrl+Enter to confirm, Esc to cancel"})]})})})},DialogContext=__WEBPACK_EXTERNAL_MODULE_react_createContext__(null),useDialogService=()=>{const e=__WEBPACK_EXTERNAL_MODULE_react_useContext__(DialogContext);if(!e)throw new Error("useDialogService must be used within a DialogProvider");return e},DialogProvider=({children:e})=>{const[t,n]=__WEBPACK_EXTERNAL_MODULE_react_useState__(null),[_,a]=__WEBPACK_EXTERNAL_MODULE_react_useState__([]),r=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{a(e=>{if(0===e.length)return n(null),e;const[t,..._]=e;return n(t),_})},[]),i=__WEBPACK_EXTERNAL_MODULE_react_useCallback__((e,_)=>new Promise((r,i)=>{const s={id:`dialog-${Date.now()}-${Math.random()}`,type:e,options:_,resolve:r,reject:i};a(e=>t||0!==e.length?[...e,s]:(n(s),[]))}),[t]),s=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(e=>{t?.resolve&&t.resolve(e),r()},[t,r]),o=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(e=>i("confirmation",e),[i]),c=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(e=>i("localeSelection",e),[i]),l=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(e=>{i("success",e).catch(()=>{})},[i]),u=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(e=>i("error",e),[i]),d=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{t?.reject&&t.reject(new Error("Dialog closed")),_.forEach(e=>{e.reject&&e.reject(new Error("Dialog closed"))}),n(null),a([])},[t,_]),E=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{s(!0)},[s]),f=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{s(!1)},[s]),h=__WEBPACK_EXTERNAL_MODULE_react_useCallback__((e,t)=>{s({locales:e,creationMode:t})},[s]),g=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{s({locales:[]})},[s]),p=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{s(!0)},[s]),A=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{s(!1)},[s]),m=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{s(!0)},[s]),L={currentDialog:t,dialogQueue:_,showConfirmation:o,showLocaleSelection:c,showSuccess:l,showError:u,closeAll:d};return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(DialogContext.Provider,{value:L,children:[e,"confirmation"===t?.type&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(ConfirmationDialog,{open:!0,...t.options,onConfirm:E,onCancel:f}),"localeSelection"===t?.type&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(LocaleSelectionDialog,{open:!0,...t.options,onConfirm:h,onCancel:g}),"success"===t?.type&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(SuccessDialog,{open:!0,...t.options,onClose:p}),"error"===t?.type&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(ErrorDialog,{open:!0,...t.options,onClose:A,onRetry:t.options.showRetry?m:void 0})]})};class DialogService{constructor(){this.contextRef=null}static getInstance(){return DialogService.instance||(DialogService.instance=new DialogService),DialogService.instance}setContext(e){this.contextRef=e}async showConfirmation(e){if(!this.contextRef)throw new Error("DialogService not initialized. Ensure DialogProvider is mounted.");return this.contextRef.showConfirmation(e)}async showLocaleSelection(e){if(!this.contextRef)throw new Error("DialogService not initialized. Ensure DialogProvider is mounted.");return this.contextRef.showLocaleSelection(e)}showSuccess(e){if(!this.contextRef)throw new Error("DialogService not initialized. Ensure DialogProvider is mounted.");this.contextRef.showSuccess(e)}async showError(e){if(!this.contextRef)throw new Error("DialogService not initialized. Ensure DialogProvider is mounted.");return this.contextRef.showError(e)}closeAll(){if(!this.contextRef)throw new Error("DialogService not initialized. Ensure DialogProvider is mounted.");this.contextRef.closeAll()}}const dialogService=DialogService.getInstance();var OAuthErrorType;!function(e){e.INVALID_CONFIG="invalid_config",e.NETWORK_ERROR="network_error",e.AUTH_FAILED="auth_failed",e.STORAGE_ERROR="storage_error"}(OAuthErrorType||(OAuthErrorType={}));class OAuthError extends Error{constructor(e,t,n){super(t),this.name="OAuthError",this.type=e,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,OAuthError)}getUserMessage(){switch(this.type){case OAuthErrorType.INVALID_CONFIG:return"Configuration is invalid. Please check your access token and project ID.";case OAuthErrorType.NETWORK_ERROR:return"Network error. Please check your connection.";case OAuthErrorType.AUTH_FAILED:return"Authentication failed. Please check your access token.";case OAuthErrorType.STORAGE_ERROR:return"Failed to save authentication data. Please try again.";default:return"An unexpected error occurred. Please try again."}}isRecoverable(){return[OAuthErrorType.NETWORK_ERROR,OAuthErrorType.STORAGE_ERROR].includes(this.type)}}class OAuthService{constructor(e){this.validateConfig(e),this.config=e,console.log("Easyling Authentication Service initialized",{projectId:e.projectId,hasAccessToken:!!e.accessToken})}validateConfig(e){const t=[];if(e.accessToken&&""!==e.accessToken.trim()||t.push("accessToken is required"),e.projectId&&""!==e.projectId.trim()||t.push("projectId is required"),t.length>0)throw new OAuthError(OAuthErrorType.INVALID_CONFIG,`Invalid configuration: ${t.join(", ")}`)}getAccessToken(){return this.config.accessToken}getProjectId(){return this.config.projectId}getConfig(){return{...this.config}}}const AUTH_DATA_STORAGE_KEY="sanity-translation-plugin:oauth:auth-data";class TokenStorage{async storeAuthData(e){try{if(!e.accessToken||!e.projectId)throw new OAuthError(OAuthErrorType.STORAGE_ERROR,"Invalid auth data: missing required fields (accessToken or projectId)");const t={...e,storedAt:Date.now()},n=JSON.stringify(t);localStorage.setItem(AUTH_DATA_STORAGE_KEY,n),console.log("Auth data stored successfully",{projectId:e.projectId})}catch(e){if(e instanceof OAuthError)throw e;throw new OAuthError(OAuthErrorType.STORAGE_ERROR,"Failed to store authentication data",e)}}async getAuthData(){try{const e=localStorage.getItem(AUTH_DATA_STORAGE_KEY);if(!e)return null;const t=JSON.parse(e);return t.accessToken&&t.projectId?t:(console.warn("Stored auth data is corrupted, clearing storage"),await this.clearAuthData(),null)}catch(e){if(e instanceof SyntaxError)return console.warn("Failed to parse stored auth data, clearing storage"),await this.clearAuthData(),null;throw new OAuthError(OAuthErrorType.STORAGE_ERROR,"Failed to retrieve authentication data",e)}}async clearAuthData(){try{localStorage.removeItem(AUTH_DATA_STORAGE_KEY),console.log("Auth data cleared successfully")}catch(e){throw new OAuthError(OAuthErrorType.STORAGE_ERROR,"Failed to clear authentication data",e)}}async isTokenExpired(){try{return!await this.getAuthData()}catch(e){return console.error("Error checking token:",e),!0}}async getValidAccessToken(){try{const e=await this.getAuthData();return e?e.accessToken:null}catch(e){return console.error("Error getting valid access token:",e),null}}}const VALID_TRANSITIONS={unauthenticated:["authenticated","error"],authenticated:["unauthenticated","error"],error:["unauthenticated","authenticated"]};class AuthStateManager{constructor(e){this.tokenStorage=e,this.subscribers=new Set,this.currentState={state:"unauthenticated"},console.log("AuthStateManager initialized")}isValidTransition(e,t){return e===t||VALID_TRANSITIONS[e].includes(t)}getState(){return{...this.currentState}}setState(e,t){if(!this.isValidTransition(this.currentState.state,e))throw new OAuthError(OAuthErrorType.INVALID_CONFIG,`Invalid state transition from ${this.currentState.state} to ${e}`);const n={state:e,...t};"error"===this.currentState.state&&"error"!==e&&delete n.error,"unauthenticated"===e&&(delete n.projectId,delete n.projectName,delete n.error),console.log("Auth state changed",{from:this.currentState.state,to:e,projectId:n.projectId}),this.currentState=n,this.notifySubscribers()}notifySubscribers(){const e=this.getState();this.subscribers.forEach(t=>{try{t(e)}catch(e){console.error("Error in state change subscriber:",e)}})}subscribe(e){this.subscribers.add(e);try{e(this.getState())}catch(e){console.error("Error in initial state callback:",e)}return()=>{this.subscribers.delete(e)}}async initialize(){try{console.log("Initializing auth state from storage");const e=await this.tokenStorage.getAuthData();if(!e)return console.log("No stored auth data found, remaining unauthenticated"),void this.setState("unauthenticated");if(await this.tokenStorage.isTokenExpired())return console.log("No valid token found"),void this.setState("unauthenticated");console.log("Valid token found, setting authenticated state"),this.setState("authenticated",{projectId:e.projectId,projectName:e.projectName})}catch(e){console.error("Error initializing auth state:",e),this.setState("error",{error:"Failed to initialize authentication state"})}}async logout(){try{console.log("Logging out"),await this.tokenStorage.clearAuthData(),this.setState("unauthenticated"),console.log("Logout complete")}catch(e){throw console.error("Error during logout:",e),this.setState("unauthenticated"),new OAuthError(OAuthErrorType.STORAGE_ERROR,"Failed to clear authentication data during logout",e)}}}var translation_request=__webpack_require__(230),translation_response=__webpack_require__(424);class TranslationService{constructor(e="http://localhost:8275/translate",t="application/json",n="application/json"){this.placeholderEndpoint=e,this.requestContentType=t,this.responseAcceptHeader=n}inferSanityType(e){if(null==e)return"undefined";if("object"==typeof e&&!Array.isArray(e)){const t=e;if(t._type)return t._type}return"string"==typeof e?"string":"number"==typeof e?"number":"boolean"==typeof e?"boolean":Array.isArray(e)?"array":"object"==typeof e?"object":"unknown"}setAuthToken(e,t){this.accessToken=e,this.projectId=t}clearAuth(){this.accessToken=void 0,this.projectId=void 0}setConfiguration(e,t,n){void 0!==e&&(this.placeholderEndpoint=e),void 0!==t&&(this.requestContentType=t),void 0!==n&&(this.responseAcceptHeader=n)}convertPayloadToProtobuf(e){const t={};for(const[n,_]of Object.entries(e.content.fields))if(_&&"object"==typeof _&&"value"in _){const e=_;let a=e.type;a||(console.warn(`Field '${n}' missing type in protobuf conversion, inferring from value`),a=this.inferSanityType(e.value)),t[n]={value:"string"==typeof e.value?e.value:JSON.stringify(e.value),dnt:e.dnt||!1,type:a}}else console.warn(`Field '${n}' not in TranslatableField format, wrapping with inferred type`),t[n]={value:"string"==typeof _?_:JSON.stringify(_),dnt:!1,type:this.inferSanityType(_)};const n=translation_request.TranslationRequestPayload.create({content:{body:e.content.body,title:e.content.title,slug:e.content.slug,fields:t},project:this.projectId||"",format:e.format,metadata:{documentId:e.metadata.documentId,documentType:e.metadata.documentType,title:e.metadata.title,sourceLanguage:e.metadata.sourceLanguage||"",targetLanguage:e.metadata.targetLanguage||"",targetLocales:e.metadata.targetLocales||[]}});return translation_request.TranslationRequestPayload.encode(n).finish()}convertPayloadToProtobufJSON(e){const t={};for(const[n,_]of Object.entries(e.content.fields))if(_&&"object"==typeof _&&"value"in _){const e=_;t[n]={value:"string"==typeof e.value?e.value:JSON.stringify(e.value),dnt:e.dnt||!1,type:e.type||"unknown"}}else t[n]={value:"string"==typeof _?_:JSON.stringify(_),dnt:!1,type:"unknown"};const n=translation_request.TranslationRequestPayload.create({content:{body:e.content.body,title:e.content.title,slug:e.content.slug,fields:t},project:this.projectId||"",format:e.format,metadata:{documentId:e.metadata.documentId,documentType:e.metadata.documentType,title:e.metadata.title,sourceLanguage:e.metadata.sourceLanguage||"",targetLanguage:e.metadata.targetLanguage||"",targetLocales:e.metadata.targetLocales||[]}});return translation_request.TranslationRequestPayload.toJSON(n)}normalizeTranslatedFields(e){const t={};if(!e||"object"!=typeof e)return t;for(const[n,_]of Object.entries(e))t[n]=_&&"object"==typeof _&&"value"in _?{value:_.value,dnt:_.dnt||!1,type:_.type||this.inferSanityType(_.value)}:{value:_,dnt:!1,type:this.inferSanityType(_)};return t}convertProtobufBinaryToResponse(e){const t=translation_response.TranslationResponse.decode(e),n=t.translatedDocuments.map(e=>{const t={};if(e.fields&&"object"==typeof e.fields)for(const[n,_]of Object.entries(e.fields))if(_&&"object"==typeof _&&"value"in _){const e=_.value,a=_.type;try{const r=JSON.parse(e);t[n]={value:r,dnt:_.dnt||!1,type:a||this.inferSanityType(r)}}catch{t[n]={value:e,dnt:_.dnt||!1,type:a||this.inferSanityType(e)}}}return{body:e.body,title:e.title,slug:e.slug,fields:t,locale:e.locale}});return{success:t.success,translatedDocuments:n,sourceLocale:t.sourceLocale,error:t.error,requestId:t.requestId}}convertProtobufJSONToResponse(e){const t=translation_response.TranslationResponse.fromJSON(e),n=t.translatedDocuments.map((t,n)=>{const _=e.translatedDocuments?.[n],a={};if(t.fields&&"object"==typeof t.fields)for(const[e,n]of Object.entries(t.fields)){const t=_?.fields?.[e];if(n&&"object"==typeof n&&"value"in n){const _=n.value,r=n.type;if(""!==_&&void 0!==_||void 0===t||""===t)try{const t=JSON.parse(_);a[e]={value:t,dnt:n.dnt||!1,type:r||this.inferSanityType(t)}}catch{a[e]={value:_,dnt:n.dnt||!1,type:r||this.inferSanityType(_)}}else a[e]=t}else a[e]=void 0===t||n&&""!==n?n:t}if(_?.fields&&"object"==typeof _.fields)for(const[e,t]of Object.entries(_.fields))e in a||(a[e]=t);const r=this.normalizeTranslatedFields(a);return{body:t.body,title:t.title,slug:t.slug,fields:r,locale:t.locale}});return{success:t.success,translatedDocuments:n,sourceLocale:t.sourceLocale,error:t.error,requestId:t.requestId}}prepareTranslationRequest(e,t="document",n,_,a){if(!e||!e.documentId||!e.htmlContent)throw new Error("Invalid document content provided");const r={};if(e.fields)for(const[t,n]of Object.entries(e.fields))if(n&&"object"==typeof n&&"value"in n){const e=n;e.type||console.warn(`Field '${t}' missing type, inferring from value`),r[t]={...e,type:e.type||this.inferSanityType(e.value)}}else console.warn(`Field '${t}' not in TranslatableField format, converting`),r[t]={value:n,dnt:!1,type:this.inferSanityType(n)};const i={content:{body:e.htmlContent,title:e.title||`Document ${e.documentId}`,slug:e.slug||"",fields:r},format:"html",metadata:{documentId:e.documentId,documentType:t,title:e.title||`Document ${e.documentId}`,...n&&{sourceLanguage:n},..._&&{targetLanguage:_},...a&&a.length>0&&{targetLocales:a}}};return{documentId:e.documentId,endpoint:this.placeholderEndpoint,payload:i}}async translateDocument(e,t="document",n,_,a){const r=this.prepareTranslationRequest(e,t,n,_,a);return this.sendTranslationRequest(r)}async sendTranslationRequest(e){try{this.logTranslationRequest(e);const t={"Content-Type":this.requestContentType,Accept:this.responseAcceptHeader};let n;if(this.accessToken&&(t.Authorization=`Bearer ${this.accessToken}`),"application/x-protobuf"===this.requestContentType)n=this.convertPayloadToProtobuf(e.payload);else{const t=this.convertPayloadToProtobufJSON(e.payload);n=JSON.stringify(t)}const _=await fetch(e.endpoint,{method:"POST",headers:t,body:n});if(!_.ok){if(401===_.status)return{success:!1,error:"Authentication failed. Please check your access token in the Easyling Configuration."};throw new Error(`HTTP error! status: ${_.status}`)}if("application/x-protobuf"===this.responseAcceptHeader){const e=await _.arrayBuffer(),t=new Uint8Array(e);return this.convertProtobufBinaryToResponse(t)}const a=await _.json();try{if(void 0!==a.success&&(a.translatedDocuments||a.error))return this.convertProtobufJSONToResponse(a)}catch(e){console.warn("Failed to parse response as protobuf format, falling back to legacy handling:",e)}if(a.translatedDocuments&&Array.isArray(a.translatedDocuments))return{success:!0,translatedDocuments:a.translatedDocuments.map(e=>({...e,fields:this.normalizeTranslatedFields(e.fields||{})})),sourceLocale:a.sourceLocale,requestId:a.requestId};if(a.translations){const e=[];for(const[t,n]of Object.entries(a.translations))if(n&&"object"==typeof n&&"content"in n){const _=n.content;e.push({..._,fields:this.normalizeTranslatedFields(_.fields||{}),locale:t})}return{success:!0,translatedDocuments:e,sourceLocale:a.sourceLocale,requestId:a.requestId,translations:a.translations}}if(a.translatedContent){const t=e.payload.metadata.targetLanguage||e.payload.metadata.targetLocales?.[0];return{success:!0,translatedDocuments:[{...a.translatedContent,fields:this.normalizeTranslatedFields(a.translatedContent.fields||{}),locale:t}],sourceLocale:e.payload.metadata.sourceLanguage,requestId:a.requestId,translatedContent:a.translatedContent}}if(a.content){const t=e.payload.metadata.targetLanguage||e.payload.metadata.targetLocales?.[0];return{success:!0,translatedDocuments:[{...a.content,fields:this.normalizeTranslatedFields(a.content.fields||{}),locale:t}],sourceLocale:e.payload.metadata.sourceLanguage,requestId:a.requestId,translatedContent:a.content}}throw new Error("Invalid response format: missing translatedDocuments, translations, or translatedContent")}catch(t){return console.error(`Translation request failed for document ${e.documentId}:`,t),{success:!1,error:t instanceof Error?t.message:"Unknown error occurred"}}}logTranslationRequest(e){console.log("Translation Request:",{timestamp:(new Date).toISOString(),documentId:e.documentId,endpoint:e.endpoint,payload:e.payload})}async processBulkTranslation(e,t="document",n,_,a){const r={totalDocuments:e.length,processedDocuments:0,failedDocuments:0,requests:[],responses:[]},i=a?.length||1;console.log(`Starting bulk translation for ${e.length} documents to ${i} locale(s)`);for(const i of e)try{const e=this.prepareTranslationRequest(i,t,n,_,a),s=await this.sendTranslationRequest(e);r.requests.push(e),r.responses.push(s),s.success?r.processedDocuments++:r.failedDocuments++}catch(e){console.error(`Failed to process document ${i.documentId}:`,e),r.failedDocuments++,r.responses.push({success:!1,error:e instanceof Error?e.message:"Unknown error occurred"})}return this.logBulkTranslationSummary(r),r}logBulkTranslationSummary(e){console.log("Bulk Translation Summary:",{timestamp:(new Date).toISOString(),totalDocuments:e.totalDocuments,processedDocuments:e.processedDocuments,failedDocuments:e.failedDocuments,successRate:e.totalDocuments>0?(e.processedDocuments/e.totalDocuments*100).toFixed(2)+"%":"0%"})}setEndpoint(e){this.placeholderEndpoint=e}getEndpoint(){return this.placeholderEndpoint}}const LEGACY_OAUTH_CONFIG_DOC_ID="sanity-translation-plugin.oauth-config",LEGACY_OAUTH_CONFIG_DOC_TYPE="EL_oauth-config";class OAuthConfigStorage{constructor(e){this.client=e,this.unifiedStorage=new UnifiedConfigStorage(e)}async load(){try{const e=await this.unifiedStorage.loadOAuth();if(e)return console.log("Loaded OAuth configuration from unified storage"),e;const t=await this.loadLegacy();return t?(console.log("Migrating OAuth configuration from legacy storage..."),await this.save(t),await this.deleteLegacy(),console.log("OAuth configuration migration complete"),t):(console.log("No OAuth configuration found"),null)}catch(e){throw console.error("Failed to load OAuth configuration:",e),e}}async save(e){try{await this.unifiedStorage.saveOAuth(e),console.log("Saved OAuth configuration to unified storage")}catch(e){throw console.error("Failed to save OAuth configuration:",e),e}}async delete(){try{await this.unifiedStorage.update({projectId:void 0,accessToken:void 0}),console.log("Deleted OAuth configuration")}catch(e){throw console.error("Failed to delete OAuth configuration:",e),e}}async loadLegacy(){try{const e=await this.client.fetch("*[_id == $id][0]",{id:LEGACY_OAUTH_CONFIG_DOC_ID});return e?{projectId:e.projectId,accessToken:e.accessToken}:null}catch(e){return console.error("Failed to load legacy OAuth configuration:",e),null}}async deleteLegacy(){try{await this.client.delete(LEGACY_OAUTH_CONFIG_DOC_ID),console.log("Deleted legacy OAuth configuration document")}catch(e){console.warn("Failed to delete legacy OAuth document:",e)}}}class OAuthServiceManager{constructor(e){this.oauthService=null,this.initialized=!1,this.client=e,this.tokenStorage=new TokenStorage,this.authStateManager=new AuthStateManager(this.tokenStorage),this.translationService=new TranslationService,this.oauthConfigStorage=new OAuthConfigStorage(e),this.unifiedConfigStorage=new UnifiedConfigStorage(e),console.log("OAuthServiceManager created")}static getInstance(e){return OAuthServiceManager.instance||(OAuthServiceManager.instance=new OAuthServiceManager(e)),OAuthServiceManager.instance}static resetInstance(){OAuthServiceManager.instance=null}async initialize(){if(this.initialized)console.log("OAuthServiceManager already initialized");else try{console.log("Initializing OAuth services..."),this.setupConfigListener();const e=await this.loadOAuthConfig();e?(this.oauthService=new OAuthService(e),console.log("OAuth service initialized with configuration")):console.log("No OAuth configuration found, OAuth features will be disabled"),await this.authStateManager.initialize(),console.log("Authentication state initialized"),await this.setupTranslationServiceAuth(),this.initialized=!0,console.log("OAuth services initialization complete")}catch(e){console.error("Error initializing OAuth services:",e),this.initialized=!0}}setupConfigListener(){this.client.listen('*[_id == "sanity-translation-plugin.config"]').subscribe(async e=>{console.log("Configuration updated, reloading services...");let t=null;e.result?(console.log("Using updated document from listener event"),t={projectId:e.result.projectId,accessToken:e.result.accessToken}):(console.log("Fetching updated configuration"),t=await this.loadOAuthConfig()),t&&t.accessToken&&t.projectId&&(console.log("Applying new OAuth configuration from update"),this.oauthService=new OAuthService(t),await this.saveAuth(t.accessToken,t.projectId)),await this.setupTranslationServiceEndpoint(),console.log("Services reloaded from configuration update")})}async loadOAuthConfig(){try{return await this.oauthConfigStorage.load()}catch(e){return console.error("Failed to load OAuth configuration:",e),null}}async setupTranslationServiceAuth(){try{await this.setupTranslationServiceEndpoint();const e=await this.loadOAuthConfig();if(e&&e.accessToken&&e.projectId)console.log("Found configuration in Sanity, syncing to localStorage"),await this.tokenStorage.storeAuthData({accessToken:e.accessToken,projectId:e.projectId,storedAt:Date.now()}),this.authStateManager.setState("authenticated",{projectId:e.projectId}),this.translationService.setAuthToken(e.accessToken,e.projectId),console.log("Translation service configured with Easyling authentication from Sanity config");else{const e=await this.tokenStorage.getAuthData();e?(this.translationService.setAuthToken(e.accessToken,e.projectId),console.log("Translation service configured with Easyling authentication from localStorage")):console.log("No authentication data available, translation service will use legacy mode")}await this.setupTranslationServiceEndpoint()}catch(e){console.error("Error setting up translation service authentication:",e),console.log("Translation service will fall back to legacy mode");try{await this.setupTranslationServiceEndpoint()}catch(e){console.error("Error setting up translation service endpoint:",e)}}}async setupTranslationServiceEndpoint(){try{const e=await this.unifiedConfigStorage.getTranslationEndpoint(),t=await this.unifiedConfigStorage.getRequestContentType(),n=await this.unifiedConfigStorage.getResponseAcceptHeader();this.translationService.setConfiguration(e,t,n),console.log("Translation service configured:",{endpoint:e,requestContentType:t,responseAcceptHeader:n})}catch(e){console.error("Error loading translation service configuration:",e)}}getOAuthService(){return this.oauthService}getTokenStorage(){return this.tokenStorage}getAuthStateManager(){return this.authStateManager}getTranslationService(){return this.translationService}getOAuthConfigStorage(){return this.oauthConfigStorage}isOAuthConfigured(){return null!==this.oauthService}getAuthenticationMode(){return this.isOAuthConfigured()?"oauth":"legacy"}async isOAuthAuthenticated(){return!!this.isOAuthConfigured()&&(!!await this.tokenStorage.getAuthData()&&!await this.tokenStorage.isTokenExpired())}async getAuthenticationStatus(){const e=this.getAuthenticationMode(),t=this.isOAuthConfigured(),n=await this.isOAuthAuthenticated();return{mode:e,isOAuthConfigured:t,isAuthenticated:n,requiresAuthentication:"oauth"===e&&!n}}isInitialized(){return this.initialized}async saveAuth(e,t){try{await this.tokenStorage.storeAuthData({accessToken:e,projectId:t,storedAt:Date.now()}),this.authStateManager.setState("authenticated",{projectId:t}),this.translationService.setAuthToken(e,t),console.log("Authentication saved successfully")}catch(e){throw console.error("Failed to save authentication:",e),this.authStateManager.setState("error",{error:e instanceof Error?e.message:"Failed to save authentication"}),e}}async logout(){this.translationService.clearAuth(),await this.authStateManager.logout(),console.log("Logged out successfully")}async refreshConfiguration(){try{console.log("Refreshing configuration from Sanity..."),await this.setupTranslationServiceEndpoint(),console.log("Configuration refreshed successfully")}catch(e){throw console.error("Error refreshing configuration:",e),e}}}OAuthServiceManager.instance=null;let isTranslating=!1;const translateDocumentAction=e=>{console.log("translateDocumentAction called with props:",{id:e.id,type:e.type,hasDraft:!!e.draft,hasPublished:!!e.published});const{draft:t,published:n,id:_,type:a,onComplete:r}=e,i=__WEBPACK_EXTERNAL_MODULE_sanity_useClient__({apiVersion:"2023-01-01"}),s=useDialogService(),o=t||n;if(!o)return console.log("no document found"),null;if(["EL_PluginConfiguration","EL_oauth-config","EL_translation-plugin-config"].includes(a))return console.log("Excluding translate action for plugin configuration type:",a),null;console.log("translateDocumentAction returning action for document:",_);const c={label:isTranslating?"Translating...":"Translate",icon:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_TranslateIcon__,onHandle:async()=>{if(!isTranslating){isTranslating=!0;try{const e=new ContentExtractor,t=new DocumentCreationService(i),n=new SanityLocaleStorageAdapter(i),_=new LocaleService(n),c=OAuthServiceManager.getInstance(i);await c.refreshConfiguration();const l=c.getTranslationService(),u=c.getAuthStateManager().getState();if(c.isOAuthConfigured()&&"authenticated"!==u.state)return void await s.showError({title:"Authentication Required",message:"You need to configure your Easyling credentials to use translation services.",error:new Error("Please go to the Easyling Configuration tool to enter your access token and project ID.")});await _.loadConfig();const d=_.getEnabledLocales();if(0===d.length)return void await s.showError({title:"No Locales Configured",message:"Please configure target locales before translating documents.",error:new Error("No translation locales have been configured. Please use the Locale Configuration tool to add target languages.")});const E=await e.extractStructuredContent(o);if(!E.htmlContent||0===E.htmlContent.trim().length)return void await s.showError({title:"Translation Failed",message:"No translatable content found in this document.",error:new Error("The document does not contain any translatable content.")});const f=await s.showLocaleSelection({title:"Select Target Locales",message:`Choose the languages to translate "${E.title}" into:`,availableLocales:d,selectedLocales:[],selectedDocuments:[o],mode:"single",allowMultiple:!0,required:!0,showCreationModeOption:!0,defaultCreationMode:"draft"});if(!f||!f.locales||0===f.locales.length)return;const h=f.locales,g=f.creationMode||"draft";if(!await s.showConfirmation({title:"Confirm Translation",message:`Translate "${E.title}" to ${h.length} locale(s)?`,details:`This will:\n• Send the translation request for ${h.length} locale(s)\n• Create new documents with translated content\n• Preserve the original document structure`,confirmText:"Translate & Create Documents",cancelText:"Cancel",tone:"primary"}))return;console.log(`Sending translation request for "${E.title}" to ${h.length} locale(s)...`),console.log("Selected locales:",h);const p=await l.translateDocument(E,a,void 0,void 0,h);if(!p.success)throw console.error(`Translation failed for "${E.title}":`,p.error),new Error(p.error||"Translation request failed");{console.log(`Translation completed successfully for "${E.title}"`),console.log("Translated documents:",p.translatedDocuments),p.requestId&&console.log("Request ID:",p.requestId);const e=p.translatedDocuments||(p.translatedContent?[p.translatedContent]:[]);if(e.length>0){console.log(`Creating ${e.length} new translated document(s)...`);const n=[];let _=0,a=0;for(let r=0;r<e.length;r++){const i=e[r],s=i.locale||h[r]||h[0];console.log(`Creating document ${r+1}/${e.length} for locale: ${s}`);const c={...p,translatedDocuments:[i],translatedContent:i},l=await t.createDocumentFromTranslation(o,c,{targetLanguage:s,createAsVariant:!0,parentDocumentId:o._id,creationMode:g});n.push(l),l.success?(_++,console.log(`Document ${r+1} created successfully with ID: ${l.documentId}`),console.log("New document structure:",l.document)):(a++,console.error(`Failed to create document ${r+1}:`,l.error))}const r=n.filter(e=>e.success&&e.slugFallback).map(e=>e.slugFallback),i=r.length>0?`\n\n⚠️ Slug fallbacks: ${r.length} document(s) had locale suffix added to slugs (translation did not produce different slugs):\n${r.map(e=>` • "${e.originalSlug}" → "${e.fallbackSlug}"`).join("\n")}`:"";if(_===e.length){const e=n.filter(e=>e.success).map(e=>e.documentId).join("\n");s.showSuccess({title:"Translation Completed",message:`Successfully translated "${E.title}" to ${_} locale(s)`,details:`Created ${_} new document(s):\n${e}\n\nTarget locale(s): ${h.join(", ")}${i}`})}else if(_>0){const t=n.filter(e=>e.success).map(e=>e.documentId).join("\n"),r=n.filter(e=>!e.success).map(e=>e.error).join("\n");await s.showError({title:"Partial Translation Success",message:`Created ${_} of ${e.length} documents. ${a} failed.`,error:new Error(`Successfully created:\n${t}\n\nErrors:\n${r}${i}`)})}else{const e=n.map(e=>e.error).join("\n");await s.showError({title:"Document Creation Failed",message:"Translation completed, but failed to create any documents.",error:new Error(e||"Unknown error during document creation")})}}}r&&r()}catch(e){console.error("Translation failed:",e);const t=e instanceof Error?e.message:"An unexpected error occurred";console.error(`Failed to translate document: ${t}`),await s.showError({title:"Translation Failed",message:"An error occurred during translation.",error:e instanceof Error?e:new Error(t),showRetry:!0})}finally{isTranslating=!1}}},tone:"primary",disabled:isTranslating};return console.log("translateDocumentAction returning action:",c),c},BulkTranslateTool=()=>{const e=__WEBPACK_EXTERNAL_MODULE_sanity_useClient__(),t=useDialogService(),[n,_]=__WEBPACK_EXTERNAL_MODULE_react_useState__({isProcessing:!1,isLoadingDocuments:!1,selectedDocuments:[],availableDocuments:{},selectedTypes:new Set,selectedDocumentIds:new Set,expandedTypes:new Set,summary:null,error:null,processingStatus:[],currentProcessingIndex:-1,createDocuments:!1,documentCreationResult:null,selectedLocales:null}),a=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(async()=>{_(e=>({...e,isLoadingDocuments:!0,error:null}));try{const t='*[!(_id in path("_.**")) && !(_type match "sanity.**") && !(_type match "EL_*")] | order(_createdAt desc) {\n _id,\n _type,\n _createdAt,\n _updatedAt,\n _rev,\n title,\n name,\n heading,\n label,\n ...\n }';console.log("Fetching documents from Sanity...");const n=await e.fetch(t);console.log(`Fetched ${n.length} documents`);const a={};n.forEach(e=>{a[e._type]||(a[e._type]=[]),a[e._type].push(e)}),Object.keys(a).forEach(e=>{console.log(`Type "${e}": ${a[e].length} documents`)}),_(e=>({...e,availableDocuments:a,isLoadingDocuments:!1}))}catch(e){console.error("Failed to fetch documents:",e),_(t=>({...t,error:e instanceof Error?e.message:"Failed to fetch documents",isLoadingDocuments:!1}))}},[e]);__WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{a()},[a]);const r=__WEBPACK_EXTERNAL_MODULE_react_useCallback__((e,t)=>{_(n=>{const _=new Set(n.selectedTypes),a=new Set(n.selectedDocumentIds);t?(_.add(e),n.availableDocuments[e]&&n.availableDocuments[e].forEach(e=>{a.add(e._id)})):(_.delete(e),n.availableDocuments[e]&&n.availableDocuments[e].forEach(e=>{a.delete(e._id)}));const r=Object.values(n.availableDocuments).flat().filter(e=>a.has(e._id)),i=r.map(e=>({documentId:e._id,title:l(e),status:"pending"}));return{...n,selectedTypes:_,selectedDocumentIds:a,selectedDocuments:r,processingStatus:i,summary:null,error:null,currentProcessingIndex:-1}})},[]),i=__WEBPACK_EXTERNAL_MODULE_react_useCallback__((e,t)=>{_(n=>{const _=new Set(n.selectedDocumentIds),a=new Set(n.selectedTypes);t?_.add(e._id):(_.delete(e._id),(n.availableDocuments[e._type]||[]).some(t=>t._id!==e._id&&_.has(t._id))||a.delete(e._type));const r=n.availableDocuments[e._type]||[];r.every(e=>_.has(e._id))&&r.length>0&&a.add(e._type);const i=Object.values(n.availableDocuments).flat().filter(e=>_.has(e._id)),s=i.map(e=>({documentId:e._id,title:l(e),status:"pending"}));return{...n,selectedTypes:a,selectedDocumentIds:_,selectedDocuments:i,processingStatus:s,summary:null,error:null,currentProcessingIndex:-1}})},[]),s=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(e=>{_(t=>{const n=new Set(t.expandedTypes);return n.has(e)?n.delete(e):n.add(e),{...t,expandedTypes:n}})},[]),o=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{const e=Object.keys(n.availableDocuments),t=Object.values(n.availableDocuments).flat(),a=new Set(t.map(e=>e._id)),r=t.map(e=>({documentId:e._id,title:l(e),status:"pending"}));_(n=>({...n,selectedTypes:new Set(e),selectedDocumentIds:a,selectedDocuments:t,processingStatus:r,summary:null,error:null,currentProcessingIndex:-1,documentCreationResult:null}))},[n.availableDocuments]),c=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{_(e=>({...e,selectedTypes:new Set,selectedDocumentIds:new Set,selectedDocuments:[],processingStatus:[],summary:null,error:null,currentProcessingIndex:-1,documentCreationResult:null}))},[]),l=e=>{const t=["title","name","heading","label"];for(const n of t)if(e[n]&&"string"==typeof e[n])return e[n];return`${e._type} (${e._id})`},u=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(async()=>{if(0!==n.selectedDocuments.length)try{const a=OAuthServiceManager.getInstance(e),r=a.getAuthStateManager().getState();if(a.isOAuthConfigured()&&"authenticated"!==r.state)return void await t.showError({title:"Authentication Required",message:"You need to configure your Easyling credentials to use translation services.",error:new Error("Please go to the Easyling Configuration tool to enter your access token and project ID.")});const i=new SanityLocaleStorageAdapter(e),s=new LocaleService(i);await s.loadConfig();const o=s.getEnabledLocales();if(0===o.length)return void await t.showError({title:"No Locales Configured",message:"Please configure target locales before translating documents.",error:new Error("No translation locales have been configured. Please use the Locale Configuration tool to add target languages.")});const c=await t.showLocaleSelection({title:"Select Target Locales",message:`Choose the languages to translate ${n.selectedDocuments.length} document${1!==n.selectedDocuments.length?"s":""} into:`,availableLocales:o,selectedLocales:[],selectedDocuments:n.selectedDocuments,mode:"bulk",allowMultiple:!0,required:!0,showCreationModeOption:!0,defaultCreationMode:"draft"});if(!c||!c.locales||0===c.locales.length)return;const l=c.locales,u=c.creationMode||"draft",d=await t.showConfirmation({title:"Confirm Bulk Translation",message:`Translate ${n.selectedDocuments.length} document${1!==n.selectedDocuments.length?"s":""} to ${l.length} locale${1!==l.length?"s":""}?`,details:`This will:\n• Send translation requests for all selected documents\n• Create new documents with translated content for successful translations\n• Preserve the original document structures\n\nTarget locales: ${l.join(", ")}`,confirmText:"Translate & Create Documents",cancelText:"Cancel",tone:"primary"});if(!d)return;_(e=>({...e,isProcessing:!0,error:null,summary:null,currentProcessingIndex:0,createDocuments:d,documentCreationResult:null,selectedLocales:l}));const E=new ContentExtractor,f=a.getTranslationService(),h=new DocumentCreationService(e);console.log(`Starting bulk translation for ${n.selectedDocuments.length} documents`);const g=(await E.extractBulkStructuredContent(n.selectedDocuments)).filter(e=>{const t=e.htmlContent&&e.htmlContent.trim().length>0;return t||_(t=>({...t,processingStatus:t.processingStatus.map(t=>t.documentId===e.documentId?{...t,status:"failed",error:"No translatable content found"}:t)})),t});if(0===g.length)throw new Error("No translatable content found in selected documents");console.log(`Processing ${g.length} documents with valid content`);const p={totalDocuments:n.selectedDocuments.length,processedDocuments:0,failedDocuments:0,requests:[],responses:[]};for(let e=0;e<g.length;e++){const t=g[e];_(n=>({...n,currentProcessingIndex:e,processingStatus:n.processingStatus.map(e=>e.documentId===t.documentId?{...e,status:"processing"}:e)}));try{const e=f.prepareTranslationRequest(t,void 0,void 0,void 0,l),n=await f.sendTranslationRequest(e);p.requests.push(e),p.responses.push(n),n.success?(p.processedDocuments++,_(e=>({...e,processingStatus:e.processingStatus.map(e=>e.documentId===t.documentId?{...e,status:"completed",response:n}:e)}))):(p.failedDocuments++,_(e=>({...e,processingStatus:e.processingStatus.map(e=>e.documentId===t.documentId?{...e,status:"failed",error:n.error,response:n}:e)}))),await new Promise(e=>setTimeout(e,500))}catch(e){console.error(`Failed to process document ${t.documentId}:`,e),p.failedDocuments++;const n=e instanceof Error?e.message:"Unknown error occurred";p.responses.push({success:!1,error:n}),_(e=>({...e,processingStatus:e.processingStatus.map(e=>e.documentId===t.documentId?{...e,status:"failed",error:n}:e)}))}}let A=null;if(d&&p.processedDocuments>0){console.log("Creating new documents from successful translations...");const e=p.responses.filter(e=>e.success),t=n.selectedDocuments.filter(e=>{const t=p.responses.findIndex((t,n)=>{const _=p.requests[n];return _&&_.documentId===e._id});return t>=0&&p.responses[t].success});t.length>0&&e.length>0&&(A=await h.createBulkDocumentsFromTranslations(t,e,{targetLanguage:"translated",createAsVariant:!0,creationMode:u}),console.log("Document Creation Summary:",{totalDocuments:A.totalDocuments,successfulCreations:A.successfulCreations,failedCreations:A.failedCreations,errors:A.errors,slugFallbacks:A.slugFallbacks}))}if(console.log("Bulk Translation Summary:",{timestamp:(new Date).toISOString(),totalDocuments:p.totalDocuments,processedDocuments:p.processedDocuments,failedDocuments:p.failedDocuments,successRate:p.totalDocuments>0?(p.processedDocuments/p.totalDocuments*100).toFixed(2)+"%":"0%"}),_(e=>({...e,summary:p,documentCreationResult:A,isProcessing:!1,currentProcessingIndex:-1})),console.log("Bulk translation completed:",p),d&&A){const e=A.slugFallbacks&&A.slugFallbacks.length>0?`\n\n⚠️ Slug fallbacks: ${A.slugFallbacks.length} document(s) had locale suffix added to slugs (translation did not produce different slugs).`:"";t.showSuccess({title:"Bulk Translation Completed",message:`Successfully translated ${p.processedDocuments} of ${p.totalDocuments} documents to ${l.length} locale${1!==l.length?"s":""}`,details:`Translations: ${p.processedDocuments}/${p.totalDocuments} successful\nDocuments created: ${A.successfulCreations}/${A.totalDocuments} successful\nTarget locales: ${l.join(", ")}${e}\n\nCheck the console for detailed results and new document structures.`})}else t.showSuccess({title:"Bulk Translation Completed",message:`Successfully translated ${p.processedDocuments} of ${p.totalDocuments} documents`,details:`Translations: ${p.processedDocuments}/${p.totalDocuments} successful\nTarget locales: ${l.join(", ")}\n\nTranslation responses have been logged to the console for verification.`})}catch(e){console.error("Bulk translation failed:",e),await t.showError({title:"Bulk Translation Failed",message:"An error occurred during bulk translation.",error:e instanceof Error?e:new Error("An unexpected error occurred")}),_(t=>({...t,error:e instanceof Error?e.message:"An unexpected error occurred",isProcessing:!1,currentProcessingIndex:-1}))}else await t.showError({title:"No Documents Selected",message:"Please select at least one document to translate.",error:new Error("No documents selected for translation")})},[n.selectedDocuments,e,t]);return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:4,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:4,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:2,weight:"semibold",children:"Bulk Document Translation"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"Select multiple documents to translate them in batch. Translation requests will be logged to the console for verification."}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Document Selection"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:"Refresh",icon:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_RefreshIcon__,onClick:a,disabled:n.isLoadingDocuments,mode:"ghost",fontSize:1}),n.selectedDocuments.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:"Clear All",tone:"critical",mode:"ghost",onClick:c,fontSize:1})]})]}),n.isLoadingDocuments?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Spinner__,{size:1}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"Loading documents..."})]}):0===Object.keys(n.availableDocuments).length?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"No documents found"}):__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:["Selected: ",n.selectedDocuments.length," documents from ",n.selectedTypes.size," types"]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:"Select All Types",onClick:o,mode:"ghost",fontSize:1})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Document Types"}),Object.entries(n.availableDocuments).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>{const _=n.expandedTypes.has(e),a=t.filter(e=>n.selectedDocumentIds.has(e._id)).length,o=a>0&&a<t.length,c=a===t.length;return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Checkbox__,{checked:c,indeterminate:o,onChange:t=>r(e,t.currentTarget.checked)}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{icon:_?__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_ChevronDownIcon__:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_ChevronRightIcon__,mode:"ghost",onClick:()=>s(e),style:{minWidth:"auto",padding:"4px"}}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:e}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:[a,"/",t.length," selected • Latest: ",new Date(t[0]._createdAt).toLocaleDateString()]})]})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:a>0?"positive":"primary",fontSize:0,children:a>0?`${a}/${t.length}`:t.length})]}),_&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{style:{marginLeft:"32px"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,children:t.map(e=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,tone:"transparent",border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Checkbox__,{checked:n.selectedDocumentIds.has(e._id),onChange:t=>i(e,t.currentTarget.checked)}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:l(e)}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:[e._id," • ",new Date(e._createdAt).toLocaleDateString()]})]})]}),n.selectedDocumentIds.has(e._id)&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"positive",fontSize:0,children:"Selected"})]})},e._id))})})]})},e)})]}),n.selectedDocuments.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:["Selected Documents (",n.selectedDocuments.length,")"]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{style:{maxHeight:"200px",overflowY:"auto"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,children:[n.selectedDocuments.slice(0,10).map(e=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,tone:"primary",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:l(e)}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:[e._type," • ",new Date(e._createdAt).toLocaleDateString()]})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"primary",fontSize:0,children:e._type})]})},e._id)),n.selectedDocuments.length>10&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,style:{textAlign:"center",padding:"8px"},children:["... and ",n.selectedDocuments.length-10," more documents"]})]})})]})]})]})}),n.selectedDocuments.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Translation Action"}),n.selectedLocales&&n.selectedLocales.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,tone:"primary",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:["Target Locales: ",n.selectedLocales.join(", ")]})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:n.isProcessing?"Processing...":`Translate ${n.selectedDocuments.length} Documents`,icon:n.isProcessing?__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Spinner__:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_TranslateIcon__,onClick:u,tone:"primary",disabled:n.isProcessing})]})}),n.isProcessing&&n.processingStatus.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Translation Progress"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:["Overall Progress: ",n.currentProcessingIndex+1," of ",n.selectedDocuments.length]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:n.currentProcessingIndex>=0?`${Math.round((n.currentProcessingIndex+1)/n.selectedDocuments.length*100)}%`:"0%"})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{style:{width:"100%",height:"8px",backgroundColor:"#e0e0e0",borderRadius:"4px",overflow:"hidden"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{style:{width:(n.currentProcessingIndex>=0?(n.currentProcessingIndex+1)/n.selectedDocuments.length*100:0)+"%",height:"100%",backgroundColor:"#0066cc",transition:"width 0.3s ease"}})})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Document Status"}),n.processingStatus.map(e=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{flex:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:e.title}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:["ID: ",e.documentId]}),e.error&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,style:{color:"red"},children:["Error: ",e.error]})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:["pending"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"default",fontSize:0,children:"Pending"}),"processing"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"primary",fontSize:0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Spinner__,{size:0}),"Processing"]})}),"completed"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"positive",fontSize:0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CheckmarkIcon__,{}),"Completed"]})}),"failed"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"critical",fontSize:0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CloseIcon__,{}),"Failed"]})})]})]})},e.documentId))]})]})}),n.error&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,tone:"critical",border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:["Error: ",n.error]})}),n.summary&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,tone:0===n.summary.failedDocuments?"positive":"caution",border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[0===n.summary.failedDocuments?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CheckmarkIcon__,{style:{color:"green"}}):__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_WarningOutlineIcon__,{style:{color:"orange"}}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Translation Summary"})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Total Documents:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"primary",children:n.summary.totalDocuments})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Successfully Processed:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"positive",children:n.summary.processedDocuments})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Failed:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"critical",children:n.summary.failedDocuments})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Success Rate:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:0===n.summary.failedDocuments?"positive":"caution",children:n.summary.totalDocuments>0?`${(n.summary.processedDocuments/n.summary.totalDocuments*100).toFixed(1)}%`:"0%"})]})]}),n.processingStatus.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Detailed Results"}),n.processingStatus.map(e=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{flex:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:e.title}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:["ID: ",e.documentId]}),e.error&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,style:{color:"red"},children:["Error: ",e.error]})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:["pending"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"default",fontSize:0,children:"Pending"}),"processing"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"primary",fontSize:0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Spinner__,{size:0}),"Processing"]})}),"completed"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"positive",fontSize:0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CheckmarkIcon__,{}),"Completed"]})}),"failed"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"critical",fontSize:0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CloseIcon__,{}),"Failed"]})})]})]})},e.documentId))]})]})}),n.documentCreationResult&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,tone:0===n.documentCreationResult.failedCreations?"positive":"caution",border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[0===n.documentCreationResult.failedCreations?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CheckmarkIcon__,{style:{color:"green"}}):__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_WarningOutlineIcon__,{style:{color:"orange"}}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Document Creation Summary"})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Documents to Create:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"primary",children:n.documentCreationResult.totalDocuments})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Successfully Created:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"positive",children:n.documentCreationResult.successfulCreations})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Failed to Create:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"critical",children:n.documentCreationResult.failedCreations})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Creation Success Rate:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:0===n.documentCreationResult.failedCreations?"positive":"caution",children:n.documentCreationResult.totalDocuments>0?`${(n.documentCreationResult.successfulCreations/n.documentCreationResult.totalDocuments*100).toFixed(1)}%`:"0%"})]})]}),n.documentCreationResult.errors.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Creation Errors"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{style:{maxHeight:"150px",overflowY:"auto"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,children:n.documentCreationResult.errors.map((e,t)=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,tone:"critical",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,style:{color:"red"},children:e})},t))})})]}),n.documentCreationResult.slugFallbacks&&n.documentCreationResult.slugFallbacks.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_WarningOutlineIcon__,{style:{color:"#f5a623"}}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:["Slug Fallbacks Applied (",n.documentCreationResult.slugFallbacks.length,")"]})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:"The following documents had unchanged slugs from translation. Locale suffix was automatically applied to avoid conflicts."}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{style:{maxHeight:"200px",overflowY:"auto"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,children:n.documentCreationResult.slugFallbacks.map((e,t)=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,tone:"caution",border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:e.documentId}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"default",fontSize:0,children:e.originalSlug}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,children:"→"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"positive",fontSize:0,children:e.fallbackSlug})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:["Locale: ",e.locale]})]})},t))})})]})]})})]})})},bulkTranslateTool={name:"bulk-translate",title:"Bulk Translate",icon:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_TranslateIcon__,component:BulkTranslateTool},manageDNTFieldsAction=e=>{const{id:t,type:n,draft:_,published:a}=e,r=useDialogService(),[i,s]=__WEBPACK_EXTERNAL_MODULE_react_useState__(!1),o=_||a,c=t;if(["EL_PluginConfiguration","EL_oauth-config","EL_translation-plugin-config"].includes(n))return{label:"Manage Translation Fields",icon:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_BlockElementIcon__,disabled:!0,hidden:!0};const l=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(async()=>{if(!o)return void await r.showError({title:"No Document",message:"Cannot manage DNT fields: No document available"});const e=[],t=(n,_="")=>{if(n&&"object"==typeof n)for(const[a,r]of Object.entries(n)){if(a.startsWith("_"))continue;const n=_?`${_}.${a}`:a;"string"==typeof r||"number"==typeof r||Array.isArray(r)?e.push({path:n,value:r,type:typeof r}):r&&"object"==typeof r&&t(r,n)}};t(o);const _=getDNTStorage(),a=await _.getFieldsForType(n),i=e.map(e=>({...e,isDNT:a[e.path]||!1})),s=i.length>0?`Found ${i.length} translatable fields in this ${n} document. Use the field badges to toggle DNT status. Settings apply to ALL ${n} documents.`:"No translatable fields found in this document.";await r.showConfirmation({title:"Manage Translation Fields",message:s,confirmText:i.length>0?`Clear All DNT Settings for ${n}`:"OK",cancelText:"Close",tone:"primary"})&&i.length>0&&(await _.clearFieldsForType(n),await r.showSuccess({title:"DNT Settings Cleared",message:`All fields in ${n} documents are now marked as translatable.`}))},[o,c,r]);return{label:"Manage Translation Fields",icon:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_BlockElementIcon__,onHandle:l,disabled:!o}},PasswordInput=e=>{const{elementProps:t,onChange:n,value:_=""}=e,a=__WEBPACK_EXTERNAL_MODULE_react_default__.useCallback(e=>{const t=e.currentTarget.value;n(t?__WEBPACK_EXTERNAL_MODULE_sanity_set__(t):__WEBPACK_EXTERNAL_MODULE_sanity_unset__())},[n]);return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_TextInput__,{...t,type:"password",value:_,onChange:a})};function DNTFieldBadge(e){const{documentId:t,documentType:n,fieldPath:_,fieldTitle:a}=e,[r,i]=__WEBPACK_EXTERNAL_MODULE_react_useState__(!1),[s,o]=__WEBPACK_EXTERNAL_MODULE_react_useState__(!0);__WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{n&&_&&(async()=>{try{o(!0);const e=getDNTStorage(),t=await e.getFieldDNT(n,_);i(t)}catch(e){console.error("Failed to load DNT status:",e)}finally{o(!1)}})()},[n,_]);const c=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(async()=>{try{const e=getDNTStorage(),t=await e.toggleFieldDNT(n,_);i(t)}catch(e){console.error("Failed to toggle DNT status:",e)}},[n,_]);if(s)return null;const l=r?`This field will NOT be translated for ALL ${n} documents. Click to make it translatable.`:`This field will be translated. Click to mark as "Do Not Translate" for ALL ${n} documents.`;return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Tooltip__,{content:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{padding:2,direction:"column",gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__("div",{style:{fontWeight:"bold"},children:a||_}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__("div",{children:l})]}),placement:"top",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{mode:"bleed",padding:2,onClick:c,style:{minHeight:"auto"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:r?"critical":"positive",mode:r?"default":"outline",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(r?__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_BlockElementIcon__:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_TranslateIcon__,{}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__("span",{style:{fontSize:"0.75rem"},children:r?"DNT":"Translate"})]})})})})}function withDNTBadge(e){return function(t){const{documentId:n,documentType:_,...a}=t,r=a,i=r.path?.join(".")||"",s=r.schemaType?.title;return n&&i?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(e,{...r}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__("div",{style:{marginTop:"0.25rem"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(DNTFieldBadge,{documentId:n,documentType:_||"document",fieldPath:i,fieldTitle:s})})]}):__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(e,{...r})}}function DNTFieldInput(e){const{renderDefault:t,schemaType:n,path:_}=e,a=__WEBPACK_EXTERNAL_MODULE_sanity_useFormValue__([]),r=a?._id,i=a?._type,s=_?.join(".")||"",o=n?.title||s;if(i&&["EL_PluginConfiguration","EL_oauth-config","EL_translation-plugin-config"].includes(i))return t(e);const[c,l]=__WEBPACK_EXTERNAL_MODULE_react_useState__(!1),[u,d]=__WEBPACK_EXTERNAL_MODULE_react_useState__(!0);__WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{i&&s?(async()=>{try{const e=getDNTStorage(),t=await e.getFieldDNT(i,s);l(t)}catch(e){console.error("Failed to load DNT status:",e)}finally{d(!1)}})():d(!1)},[i,s]);const E=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(async()=>{if(i&&s)try{const e=getDNTStorage(),t=await e.toggleFieldDNT(i,s);l(t)}catch(e){console.error("Failed to toggle DNT:",e)}},[i,s]);if(!r||!s||s.startsWith("_"))return t(e);const f=c?`This field will NOT be translated for ALL ${i} documents. Click to make it translatable.`:`This field will be translated. Click to mark as "Do Not Translate" for ALL ${i} documents.`;return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:t(e)}),!u&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,paddingTop:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Tooltip__,{content:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:2,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:f})}),placement:"top",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{mode:"ghost",tone:c?"critical":"positive",padding:2,fontSize:1,onClick:E,icon:c?__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_BlockElementIcon__:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_TranslateIcon__,text:c?"Do Not Translate":"Will Translate"})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{muted:!0,size:1,children:["Translation: ",__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__("strong",{children:c?"Disabled":"Enabled"})," for ",o]})]})]})}console.log("Loading sanity-translation-plugin...");const legacyOAuthConfigSchema={name:"EL_oauth-config",title:"Easyling Configuration (Legacy)",type:"document",hidden:!0,fields:[{name:"projectId",title:"Project ID",type:"string",description:"Your Easyling project ID",validation:e=>e.required()},{name:"accessToken",title:"Access Token",type:"string",description:"Long-lived access token provided by Easyling (hidden for security)",validation:e=>e.required(),components:{input:PasswordInput}},{name:"lastUpdated",title:"Last Updated",type:"datetime",readOnly:!0}]};function StudioLayout(e){const t=__WEBPACK_EXTERNAL_MODULE_sanity_useClient__({apiVersion:"2023-01-01"}),[n,_]=__WEBPACK_EXTERNAL_MODULE_react_default__.useState(!1);return __WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{(async()=>{try{const e=OAuthServiceManager.getInstance(t);await e.initialize(),DNTServiceManager.getInstance(t).initialize(t),console.log("Services initialized successfully"),_(!0)}catch(e){console.error("Failed to initialize services:",e),_(!0)}})()},[t]),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(DialogProvider,{children:e.renderDefault(e)})}const src_plugin=__WEBPACK_EXTERNAL_MODULE_sanity_definePlugin__({name:"sanity-translation-plugin",studio:{components:{layout:StudioLayout}},document:{actions:e=>{console.log("Document actions being registered, previous actions:",e.length);const t=[...e,translateDocumentAction,manageDNTFieldsAction];return console.log("New actions array length:",t.length),t}},form:{components:{field:e=>{const t=e.schemaType?.type?.name,n=e.schemaType?.name,_=e.path?.join("."),a=["locale","_type","_id","_rev","_createdAt","_updatedAt"],r=a.includes(n||"")||a.some(e=>_?.includes(e)),i=t&&["date","datetime","image","file","reference","boolean","object","document","slug"].includes(t);return t&&["string","text","number","url","email","array"].includes(t)&&!r&&!i?DNTFieldInput(e):e.renderDefault(e)}}},tools:e=>{console.log("Tools being registered, previous tools:",e.length);const t=[...e,bulkTranslateTool];return console.log("New tools array length:",t.length),t},schema:{types:[createPluginConfigSchema(PasswordInput),legacyLocaleConfigSchema,legacyOAuthConfigSchema]}});export{DNTFieldBadge,DNTFieldInput,DNTServiceManager,DNTStorageAdapter,LegacyDNTStorageAdapter,UnifiedConfigStorage,createPluginConfigSchema,src_plugin as default,getDNTStorage,pluginConfigSchema,withDNTBadge};
1
+ import{jsx as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__,jsxs as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__}from"react/jsx-runtime";import{definePlugin as __WEBPACK_EXTERNAL_MODULE_sanity_definePlugin__,set as __WEBPACK_EXTERNAL_MODULE_sanity_set__,unset as __WEBPACK_EXTERNAL_MODULE_sanity_unset__,useClient as __WEBPACK_EXTERNAL_MODULE_sanity_useClient__,useFormValue as __WEBPACK_EXTERNAL_MODULE_sanity_useFormValue__}from"sanity";import{createContext as __WEBPACK_EXTERNAL_MODULE_react_createContext__,default as __WEBPACK_EXTERNAL_MODULE_react_default__,useCallback as __WEBPACK_EXTERNAL_MODULE_react_useCallback__,useContext as __WEBPACK_EXTERNAL_MODULE_react_useContext__,useEffect as __WEBPACK_EXTERNAL_MODULE_react_useEffect__,useMemo as __WEBPACK_EXTERNAL_MODULE_react_useMemo__,useRef as __WEBPACK_EXTERNAL_MODULE_react_useRef__,useState as __WEBPACK_EXTERNAL_MODULE_react_useState__}from"react";import{BlockElementIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_BlockElementIcon__,CheckmarkCircleIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CheckmarkCircleIcon__,CheckmarkIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CheckmarkIcon__,ChevronDownIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_ChevronDownIcon__,ChevronRightIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_ChevronRightIcon__,CloseIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CloseIcon__,ErrorOutlineIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_ErrorOutlineIcon__,InfoOutlineIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_InfoOutlineIcon__,RefreshIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_RefreshIcon__,SearchIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_SearchIcon__,TranslateIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_TranslateIcon__,WarningOutlineIcon as __WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_WarningOutlineIcon__}from"@sanity/icons";import{Badge as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,Box as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,Button as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,Card as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,Checkbox as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Checkbox__,Code as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Code__,Dialog as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Dialog__,Flex as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,Radio as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Radio__,Spinner as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Spinner__,Stack as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,Text as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,TextInput as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_TextInput__,Tooltip as __WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Tooltip__}from"@sanity/ui";var __webpack_modules__={45:e=>{e.exports=function(e,t){for(var n=new Array(arguments.length-1),_=0,a=2,i=!0;a<arguments.length;)n[_++]=arguments[a++];return new Promise(function(a,r){n[_]=function(e){if(i)if(i=!1,e)r(e);else{for(var t=new Array(arguments.length-1),n=0;n<t.length;)t[n++]=arguments[n];a.apply(null,t)}};try{e.apply(t||null,n)}catch(e){i&&(i=!1,r(e))}})}},47:(e,t,n)=>{t.Service=n(595)},153:module=>{function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},158:(e,t,n)=>{e.exports=i;var _=n(237);(i.prototype=Object.create(_.prototype)).constructor=i;var a=n(610);function i(e){_.call(this,e)}i._configure=function(){a.Buffer&&(i.prototype._slice=a.Buffer.prototype.slice)},i.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},i._configure()},230:function(e,t,n){var _=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Metadata=t.TranslatableField=t.Content_FieldsEntry=t.Content=t.TranslationRequestPayload=t.protobufPackage=void 0;const a=_(n(946));function i(e){return null!=e}t.protobufPackage="hu.skawa.pagetranslate.server.model.protobuffers",t.TranslationRequestPayload={encode:(e,n=a.default.Writer.create())=>(void 0!==e.content&&t.Content.encode(e.content,n.uint32(10).fork()).ldelim(),""!==e.project&&n.uint32(34).string(e.project),""!==e.format&&n.uint32(18).string(e.format),void 0!==e.metadata&&t.Metadata.encode(e.metadata,n.uint32(26).fork()).ldelim(),n),decode(e,n){const _=e instanceof a.default.Reader?e:a.default.Reader.create(e);let i=void 0===n?_.len:_.pos+n;const r={content:void 0,project:"",format:"",metadata:void 0};for(;_.pos<i;){const e=_.uint32();switch(e>>>3){case 1:if(10!==e)break;r.content=t.Content.decode(_,_.uint32());continue;case 4:if(34!==e)break;r.project=_.string();continue;case 2:if(18!==e)break;r.format=_.string();continue;case 3:if(26!==e)break;r.metadata=t.Metadata.decode(_,_.uint32());continue}if(4==(7&e)||0===e)break;_.skipType(7&e)}return r},fromJSON:e=>({content:i(e.content)?t.Content.fromJSON(e.content):void 0,project:i(e.project)?globalThis.String(e.project):"",format:i(e.format)?globalThis.String(e.format):"",metadata:i(e.metadata)?t.Metadata.fromJSON(e.metadata):void 0}),toJSON(e){const n={};return void 0!==e.content&&(n.content=t.Content.toJSON(e.content)),""!==e.project&&(n.project=e.project),""!==e.format&&(n.format=e.format),void 0!==e.metadata&&(n.metadata=t.Metadata.toJSON(e.metadata)),n},create:e=>t.TranslationRequestPayload.fromPartial(e??{}),fromPartial(e){const n={content:void 0,project:"",format:"",metadata:void 0};return n.content=void 0!==e.content&&null!==e.content?t.Content.fromPartial(e.content):void 0,n.project=e.project??"",n.format=e.format??"",n.metadata=void 0!==e.metadata&&null!==e.metadata?t.Metadata.fromPartial(e.metadata):void 0,n}},t.Content={encode:(e,n=a.default.Writer.create())=>(""!==e.body&&n.uint32(10).string(e.body),""!==e.title&&n.uint32(18).string(e.title),""!==e.slug&&n.uint32(26).string(e.slug),Object.entries(e.fields).forEach(([e,_])=>{t.Content_FieldsEntry.encode({key:e,value:_},n.uint32(34).fork()).ldelim()}),n),decode(e,n){const _=e instanceof a.default.Reader?e:a.default.Reader.create(e);let i=void 0===n?_.len:_.pos+n;const r={body:"",title:"",slug:"",fields:{}};for(;_.pos<i;){const e=_.uint32();switch(e>>>3){case 1:if(10!==e)break;r.body=_.string();continue;case 2:if(18!==e)break;r.title=_.string();continue;case 3:if(26!==e)break;r.slug=_.string();continue;case 4:if(34!==e)break;const n=t.Content_FieldsEntry.decode(_,_.uint32());void 0!==n.value&&(r.fields[n.key]=n.value);continue}if(4==(7&e)||0===e)break;_.skipType(7&e)}return r},fromJSON(e){return{body:i(e.body)?globalThis.String(e.body):"",title:i(e.title)?globalThis.String(e.title):"",slug:i(e.slug)?globalThis.String(e.slug):"",fields:(n=e.fields,"object"==typeof n&&null!==n?Object.entries(e.fields).reduce((e,[n,_])=>(e[n]=t.TranslatableField.fromJSON(_),e),{}):{})};var n},toJSON(e){const n={};if(""!==e.body&&(n.body=e.body),""!==e.title&&(n.title=e.title),""!==e.slug&&(n.slug=e.slug),e.fields){const _=Object.entries(e.fields);_.length>0&&(n.fields={},_.forEach(([e,_])=>{n.fields[e]=t.TranslatableField.toJSON(_)}))}return n},create:e=>t.Content.fromPartial(e??{}),fromPartial(e){const n={body:"",title:"",slug:"",fields:{}};return n.body=e.body??"",n.title=e.title??"",n.slug=e.slug??"",n.fields=Object.entries(e.fields??{}).reduce((e,[n,_])=>(void 0!==_&&(e[n]=t.TranslatableField.fromPartial(_)),e),{}),n}},t.Content_FieldsEntry={encode:(e,n=a.default.Writer.create())=>(""!==e.key&&n.uint32(10).string(e.key),void 0!==e.value&&t.TranslatableField.encode(e.value,n.uint32(18).fork()).ldelim(),n),decode(e,n){const _=e instanceof a.default.Reader?e:a.default.Reader.create(e);let i=void 0===n?_.len:_.pos+n;const r={key:"",value:void 0};for(;_.pos<i;){const e=_.uint32();switch(e>>>3){case 1:if(10!==e)break;r.key=_.string();continue;case 2:if(18!==e)break;r.value=t.TranslatableField.decode(_,_.uint32());continue}if(4==(7&e)||0===e)break;_.skipType(7&e)}return r},fromJSON:e=>({key:i(e.key)?globalThis.String(e.key):"",value:i(e.value)?t.TranslatableField.fromJSON(e.value):void 0}),toJSON(e){const n={};return""!==e.key&&(n.key=e.key),void 0!==e.value&&(n.value=t.TranslatableField.toJSON(e.value)),n},create:e=>t.Content_FieldsEntry.fromPartial(e??{}),fromPartial(e){const n={key:"",value:void 0};return n.key=e.key??"",n.value=void 0!==e.value&&null!==e.value?t.TranslatableField.fromPartial(e.value):void 0,n}},t.TranslatableField={encode:(e,t=a.default.Writer.create())=>(""!==e.value&&t.uint32(10).string(e.value),!1!==e.dnt&&t.uint32(16).bool(e.dnt),""!==e.type&&t.uint32(26).string(e.type),""!==e.path&&t.uint32(34).string(e.path),t),decode(e,t){const n=e instanceof a.default.Reader?e:a.default.Reader.create(e);let _=void 0===t?n.len:n.pos+t;const i={value:"",dnt:!1,type:"",path:""};for(;n.pos<_;){const e=n.uint32();switch(e>>>3){case 1:if(10!==e)break;i.value=n.string();continue;case 2:if(16!==e)break;i.dnt=n.bool();continue;case 3:if(26!==e)break;i.type=n.string();continue;case 4:if(34!==e)break;i.path=n.string();continue}if(4==(7&e)||0===e)break;n.skipType(7&e)}return i},fromJSON:e=>({value:i(e.value)?globalThis.String(e.value):"",dnt:!!i(e.dnt)&&globalThis.Boolean(e.dnt),type:i(e.type)?globalThis.String(e.type):"",path:i(e.path)?globalThis.String(e.path):""}),toJSON(e){const t={};return""!==e.value&&(t.value=e.value),!1!==e.dnt&&(t.dnt=e.dnt),""!==e.type&&(t.type=e.type),""!==e.path&&(t.path=e.path),t},create:e=>t.TranslatableField.fromPartial(e??{}),fromPartial(e){const t={value:"",dnt:!1,type:"",path:""};return t.value=e.value??"",t.dnt=e.dnt??!1,t.type=e.type??"",t.path=e.path??"",t}},t.Metadata={encode(e,t=a.default.Writer.create()){""!==e.documentId&&t.uint32(10).string(e.documentId),""!==e.documentType&&t.uint32(18).string(e.documentType),""!==e.title&&t.uint32(26).string(e.title),""!==e.sourceLanguage&&t.uint32(34).string(e.sourceLanguage),""!==e.targetLanguage&&t.uint32(42).string(e.targetLanguage);for(const n of e.targetLocales)t.uint32(50).string(n);return t},decode(e,t){const n=e instanceof a.default.Reader?e:a.default.Reader.create(e);let _=void 0===t?n.len:n.pos+t;const i={documentId:"",documentType:"",title:"",sourceLanguage:"",targetLanguage:"",targetLocales:[]};for(;n.pos<_;){const e=n.uint32();switch(e>>>3){case 1:if(10!==e)break;i.documentId=n.string();continue;case 2:if(18!==e)break;i.documentType=n.string();continue;case 3:if(26!==e)break;i.title=n.string();continue;case 4:if(34!==e)break;i.sourceLanguage=n.string();continue;case 5:if(42!==e)break;i.targetLanguage=n.string();continue;case 6:if(50!==e)break;i.targetLocales.push(n.string());continue}if(4==(7&e)||0===e)break;n.skipType(7&e)}return i},fromJSON:e=>({documentId:i(e.documentId)?globalThis.String(e.documentId):"",documentType:i(e.documentType)?globalThis.String(e.documentType):"",title:i(e.title)?globalThis.String(e.title):"",sourceLanguage:i(e.sourceLanguage)?globalThis.String(e.sourceLanguage):"",targetLanguage:i(e.targetLanguage)?globalThis.String(e.targetLanguage):"",targetLocales:globalThis.Array.isArray(e?.targetLocales)?e.targetLocales.map(e=>globalThis.String(e)):[]}),toJSON(e){const t={};return""!==e.documentId&&(t.documentId=e.documentId),""!==e.documentType&&(t.documentType=e.documentType),""!==e.title&&(t.title=e.title),""!==e.sourceLanguage&&(t.sourceLanguage=e.sourceLanguage),""!==e.targetLanguage&&(t.targetLanguage=e.targetLanguage),e.targetLocales?.length&&(t.targetLocales=e.targetLocales),t},create:e=>t.Metadata.fromPartial(e??{}),fromPartial(e){const t={documentId:"",documentType:"",title:"",sourceLanguage:"",targetLanguage:"",targetLocales:[]};return t.documentId=e.documentId??"",t.documentType=e.documentType??"",t.title=e.title??"",t.sourceLanguage=e.sourceLanguage??"",t.targetLanguage=e.targetLanguage??"",t.targetLocales=e.targetLocales?.map(e=>e)||[],t}}},237:(e,t,n)=>{e.exports=s;var _,a=n(610),i=a.LongBits,r=a.utf8;function o(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function s(e){this.buf=e,this.pos=0,this.len=e.length}var c,l="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new s(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new s(e);throw Error("illegal buffer")},u=function(){return a.Buffer?function(e){return(s.create=function(e){return a.Buffer.isBuffer(e)?new _(e):l(e)})(e)}:l};function d(){var e=new i(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw o(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw o(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function E(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw o(this,8);return new i(E(this.buf,this.pos+=4),E(this.buf,this.pos+=4))}s.create=u(),s.prototype._slice=a.Array.prototype.subarray||a.Array.prototype.slice,s.prototype.uint32=(c=4294967295,function(){if(c=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return c;if((this.pos+=5)>this.len)throw this.pos=this.len,o(this,10);return c}),s.prototype.int32=function(){return 0|this.uint32()},s.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},s.prototype.bool=function(){return 0!==this.uint32()},s.prototype.fixed32=function(){if(this.pos+4>this.len)throw o(this,4);return E(this.buf,this.pos+=4)},s.prototype.sfixed32=function(){if(this.pos+4>this.len)throw o(this,4);return 0|E(this.buf,this.pos+=4)},s.prototype.float=function(){if(this.pos+4>this.len)throw o(this,4);var e=a.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},s.prototype.double=function(){if(this.pos+8>this.len)throw o(this,4);var e=a.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},s.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw o(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,n);if(t===n){var _=a.Buffer;return _?_.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,n)},s.prototype.string=function(){var e=this.bytes();return r.read(e,0,e.length)},s.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw o(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw o(this)}while(128&this.buf[this.pos++]);return this},s.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},s._configure=function(e){_=e,s.create=u(),_._configure();var t=a.Long?"toLong":"toNumber";a.merge(s.prototype,{int64:function(){return d.call(this)[t](!1)},uint64:function(){return d.call(this)[t](!0)},sint64:function(){return d.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},239:(e,t,n)=>{e.exports=a;var _=n(610);function a(e,t){this.lo=e>>>0,this.hi=t>>>0}var i=a.zero=new a(0,0);i.toNumber=function(){return 0},i.zzEncode=i.zzDecode=function(){return this},i.length=function(){return 1};var r=a.zeroHash="\0\0\0\0\0\0\0\0";a.fromNumber=function(e){if(0===e)return i;var t=e<0;t&&(e=-e);var n=e>>>0,_=(e-n)/4294967296>>>0;return t&&(_=~_>>>0,n=~n>>>0,++n>4294967295&&(n=0,++_>4294967295&&(_=0))),new a(n,_)},a.from=function(e){if("number"==typeof e)return a.fromNumber(e);if(_.isString(e)){if(!_.Long)return a.fromNumber(parseInt(e,10));e=_.Long.fromString(e)}return e.low||e.high?new a(e.low>>>0,e.high>>>0):i},a.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+4294967296*n)}return this.lo+4294967296*this.hi},a.prototype.toLong=function(e){return _.Long?new _.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var o=String.prototype.charCodeAt;a.fromHash=function(e){return e===r?i:new a((o.call(e,0)|o.call(e,1)<<8|o.call(e,2)<<16|o.call(e,3)<<24)>>>0,(o.call(e,4)|o.call(e,5)<<8|o.call(e,6)<<16|o.call(e,7)<<24)>>>0)},a.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},a.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},a.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},a.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}},358:e=>{function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var n=this._listeners[e],_=0;_<n.length;)n[_].fn===t?n.splice(_,1):++_;return this},t.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var n=[],_=1;_<arguments.length;)n.push(arguments[_++]);for(_=0;_<t.length;)t[_].fn.apply(t[_++].ctx,n)}return this}},390:e=>{e.exports=function(e,t,n){var _=n||8192,a=_>>>1,i=null,r=_;return function(n){if(n<1||n>a)return e(n);r+n>_&&(i=e(_),r=0);var o=t.call(i,r,r+=n);return 7&r&&(r=1+(7|r)),o}}},394:(e,t,n)=>{var _=t;function a(){_.util._configure(),_.Writer._configure(_.BufferWriter),_.Reader._configure(_.BufferReader)}_.build="minimal",_.Writer=n(449),_.BufferWriter=n(818),_.Reader=n(237),_.BufferReader=n(158),_.util=n(610),_.rpc=n(47),_.roots=n(529),_.configure=a,a()},410:e=>{function t(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),n=new Uint8Array(t.buffer),_=128===n[3];function a(e,_,a){t[0]=e,_[a]=n[0],_[a+1]=n[1],_[a+2]=n[2],_[a+3]=n[3]}function i(e,_,a){t[0]=e,_[a]=n[3],_[a+1]=n[2],_[a+2]=n[1],_[a+3]=n[0]}function r(e,_){return n[0]=e[_],n[1]=e[_+1],n[2]=e[_+2],n[3]=e[_+3],t[0]}function o(e,_){return n[3]=e[_],n[2]=e[_+1],n[1]=e[_+2],n[0]=e[_+3],t[0]}e.writeFloatLE=_?a:i,e.writeFloatBE=_?i:a,e.readFloatLE=_?r:o,e.readFloatBE=_?o:r}():function(){function t(e,t,n,_){var a=t<0?1:0;if(a&&(t=-t),0===t)e(1/t>0?0:2147483648,n,_);else if(isNaN(t))e(2143289344,n,_);else if(t>34028234663852886e22)e((a<<31|2139095040)>>>0,n,_);else if(t<11754943508222875e-54)e((a<<31|Math.round(t/1401298464324817e-60))>>>0,n,_);else{var i=Math.floor(Math.log(t)/Math.LN2);e((a<<31|i+127<<23|8388607&Math.round(t*Math.pow(2,-i)*8388608))>>>0,n,_)}}function r(e,t,n){var _=e(t,n),a=2*(_>>31)+1,i=_>>>23&255,r=8388607&_;return 255===i?r?NaN:a*(1/0):0===i?1401298464324817e-60*a*r:a*Math.pow(2,i-150)*(r+8388608)}e.writeFloatLE=t.bind(null,n),e.writeFloatBE=t.bind(null,_),e.readFloatLE=r.bind(null,a),e.readFloatBE=r.bind(null,i)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),n=new Uint8Array(t.buffer),_=128===n[7];function a(e,_,a){t[0]=e,_[a]=n[0],_[a+1]=n[1],_[a+2]=n[2],_[a+3]=n[3],_[a+4]=n[4],_[a+5]=n[5],_[a+6]=n[6],_[a+7]=n[7]}function i(e,_,a){t[0]=e,_[a]=n[7],_[a+1]=n[6],_[a+2]=n[5],_[a+3]=n[4],_[a+4]=n[3],_[a+5]=n[2],_[a+6]=n[1],_[a+7]=n[0]}function r(e,_){return n[0]=e[_],n[1]=e[_+1],n[2]=e[_+2],n[3]=e[_+3],n[4]=e[_+4],n[5]=e[_+5],n[6]=e[_+6],n[7]=e[_+7],t[0]}function o(e,_){return n[7]=e[_],n[6]=e[_+1],n[5]=e[_+2],n[4]=e[_+3],n[3]=e[_+4],n[2]=e[_+5],n[1]=e[_+6],n[0]=e[_+7],t[0]}e.writeDoubleLE=_?a:i,e.writeDoubleBE=_?i:a,e.readDoubleLE=_?r:o,e.readDoubleBE=_?o:r}():function(){function t(e,t,n,_,a,i){var r=_<0?1:0;if(r&&(_=-_),0===_)e(0,a,i+t),e(1/_>0?0:2147483648,a,i+n);else if(isNaN(_))e(0,a,i+t),e(2146959360,a,i+n);else if(_>17976931348623157e292)e(0,a,i+t),e((r<<31|2146435072)>>>0,a,i+n);else{var o;if(_<22250738585072014e-324)e((o=_/5e-324)>>>0,a,i+t),e((r<<31|o/4294967296)>>>0,a,i+n);else{var s=Math.floor(Math.log(_)/Math.LN2);1024===s&&(s=1023),e(4503599627370496*(o=_*Math.pow(2,-s))>>>0,a,i+t),e((r<<31|s+1023<<20|1048576*o&1048575)>>>0,a,i+n)}}}function r(e,t,n,_,a){var i=e(_,a+t),r=e(_,a+n),o=2*(r>>31)+1,s=r>>>20&2047,c=4294967296*(1048575&r)+i;return 2047===s?c?NaN:o*(1/0):0===s?5e-324*o*c:o*Math.pow(2,s-1075)*(c+4503599627370496)}e.writeDoubleLE=t.bind(null,n,0,4),e.writeDoubleBE=t.bind(null,_,4,0),e.readDoubleLE=r.bind(null,a,0,4),e.readDoubleBE=r.bind(null,i,4,0)}(),e}function n(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function _(e,t,n){t[n]=e>>>24,t[n+1]=e>>>16&255,t[n+2]=e>>>8&255,t[n+3]=255&e}function a(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function i(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},424:function(e,t,n){var _=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.TranslatedDocument_FieldsEntry=t.TranslatedDocument=t.TranslationResponse=t.protobufPackage=void 0;const a=_(n(946)),i=n(230);function r(e){return null!=e}t.protobufPackage="hu.skawa.pagetranslate.server.model.protobuffers",t.TranslationResponse={encode(e,n=a.default.Writer.create()){!1!==e.success&&n.uint32(8).bool(e.success);for(const _ of e.translatedDocuments)t.TranslatedDocument.encode(_,n.uint32(18).fork()).ldelim();return""!==e.sourceLocale&&n.uint32(26).string(e.sourceLocale),""!==e.error&&n.uint32(34).string(e.error),""!==e.requestId&&n.uint32(42).string(e.requestId),n},decode(e,n){const _=e instanceof a.default.Reader?e:a.default.Reader.create(e);let i=void 0===n?_.len:_.pos+n;const r={success:!1,translatedDocuments:[],sourceLocale:"",error:"",requestId:""};for(;_.pos<i;){const e=_.uint32();switch(e>>>3){case 1:if(8!==e)break;r.success=_.bool();continue;case 2:if(18!==e)break;r.translatedDocuments.push(t.TranslatedDocument.decode(_,_.uint32()));continue;case 3:if(26!==e)break;r.sourceLocale=_.string();continue;case 4:if(34!==e)break;r.error=_.string();continue;case 5:if(42!==e)break;r.requestId=_.string();continue}if(4==(7&e)||0===e)break;_.skipType(7&e)}return r},fromJSON:e=>({success:!!r(e.success)&&globalThis.Boolean(e.success),translatedDocuments:globalThis.Array.isArray(e?.translatedDocuments)?e.translatedDocuments.map(e=>t.TranslatedDocument.fromJSON(e)):[],sourceLocale:r(e.sourceLocale)?globalThis.String(e.sourceLocale):"",error:r(e.error)?globalThis.String(e.error):"",requestId:r(e.requestId)?globalThis.String(e.requestId):""}),toJSON(e){const n={};return!1!==e.success&&(n.success=e.success),e.translatedDocuments?.length&&(n.translatedDocuments=e.translatedDocuments.map(e=>t.TranslatedDocument.toJSON(e))),""!==e.sourceLocale&&(n.sourceLocale=e.sourceLocale),""!==e.error&&(n.error=e.error),""!==e.requestId&&(n.requestId=e.requestId),n},create:e=>t.TranslationResponse.fromPartial(e??{}),fromPartial(e){const n={success:!1,translatedDocuments:[],sourceLocale:"",error:"",requestId:""};return n.success=e.success??!1,n.translatedDocuments=e.translatedDocuments?.map(e=>t.TranslatedDocument.fromPartial(e))||[],n.sourceLocale=e.sourceLocale??"",n.error=e.error??"",n.requestId=e.requestId??"",n}},t.TranslatedDocument={encode:(e,n=a.default.Writer.create())=>(""!==e.body&&n.uint32(10).string(e.body),""!==e.title&&n.uint32(18).string(e.title),""!==e.slug&&n.uint32(26).string(e.slug),Object.entries(e.fields).forEach(([e,_])=>{t.TranslatedDocument_FieldsEntry.encode({key:e,value:_},n.uint32(34).fork()).ldelim()}),""!==e.locale&&n.uint32(42).string(e.locale),n),decode(e,n){const _=e instanceof a.default.Reader?e:a.default.Reader.create(e);let i=void 0===n?_.len:_.pos+n;const r={body:"",title:"",slug:"",fields:{},locale:""};for(;_.pos<i;){const e=_.uint32();switch(e>>>3){case 1:if(10!==e)break;r.body=_.string();continue;case 2:if(18!==e)break;r.title=_.string();continue;case 3:if(26!==e)break;r.slug=_.string();continue;case 4:if(34!==e)break;const n=t.TranslatedDocument_FieldsEntry.decode(_,_.uint32());void 0!==n.value&&(r.fields[n.key]=n.value);continue;case 5:if(42!==e)break;r.locale=_.string();continue}if(4==(7&e)||0===e)break;_.skipType(7&e)}return r},fromJSON(e){return{body:r(e.body)?globalThis.String(e.body):"",title:r(e.title)?globalThis.String(e.title):"",slug:r(e.slug)?globalThis.String(e.slug):"",fields:(t=e.fields,"object"==typeof t&&null!==t?Object.entries(e.fields).reduce((e,[t,n])=>(e[t]=i.TranslatableField.fromJSON(n),e),{}):{}),locale:r(e.locale)?globalThis.String(e.locale):""};var t},toJSON(e){const t={};if(""!==e.body&&(t.body=e.body),""!==e.title&&(t.title=e.title),""!==e.slug&&(t.slug=e.slug),e.fields){const n=Object.entries(e.fields);n.length>0&&(t.fields={},n.forEach(([e,n])=>{t.fields[e]=i.TranslatableField.toJSON(n)}))}return""!==e.locale&&(t.locale=e.locale),t},create:e=>t.TranslatedDocument.fromPartial(e??{}),fromPartial(e){const t={body:"",title:"",slug:"",fields:{},locale:""};return t.body=e.body??"",t.title=e.title??"",t.slug=e.slug??"",t.fields=Object.entries(e.fields??{}).reduce((e,[t,n])=>(void 0!==n&&(e[t]=i.TranslatableField.fromPartial(n)),e),{}),t.locale=e.locale??"",t}},t.TranslatedDocument_FieldsEntry={encode:(e,t=a.default.Writer.create())=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&i.TranslatableField.encode(e.value,t.uint32(18).fork()).ldelim(),t),decode(e,t){const n=e instanceof a.default.Reader?e:a.default.Reader.create(e);let _=void 0===t?n.len:n.pos+t;const r={key:"",value:void 0};for(;n.pos<_;){const e=n.uint32();switch(e>>>3){case 1:if(10!==e)break;r.key=n.string();continue;case 2:if(18!==e)break;r.value=i.TranslatableField.decode(n,n.uint32());continue}if(4==(7&e)||0===e)break;n.skipType(7&e)}return r},fromJSON:e=>({key:r(e.key)?globalThis.String(e.key):"",value:r(e.value)?i.TranslatableField.fromJSON(e.value):void 0}),toJSON(e){const t={};return""!==e.key&&(t.key=e.key),void 0!==e.value&&(t.value=i.TranslatableField.toJSON(e.value)),t},create:e=>t.TranslatedDocument_FieldsEntry.fromPartial(e??{}),fromPartial(e){const t={key:"",value:void 0};return t.key=e.key??"",t.value=void 0!==e.value&&null!==e.value?i.TranslatableField.fromPartial(e.value):void 0,t}}},447:(e,t)=>{var n=t;n.length=function(e){for(var t=0,n=0,_=0;_<e.length;++_)(n=e.charCodeAt(_))<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(_+1))?(++_,t+=4):t+=3;return t},n.read=function(e,t,n){if(n-t<1)return"";for(var _,a=null,i=[],r=0;t<n;)(_=e[t++])<128?i[r++]=_:_>191&&_<224?i[r++]=(31&_)<<6|63&e[t++]:_>239&&_<365?(_=((7&_)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[r++]=55296+(_>>10),i[r++]=56320+(1023&_)):i[r++]=(15&_)<<12|(63&e[t++])<<6|63&e[t++],r>8191&&((a||(a=[])).push(String.fromCharCode.apply(String,i)),r=0);return a?(r&&a.push(String.fromCharCode.apply(String,i.slice(0,r))),a.join("")):String.fromCharCode.apply(String,i.slice(0,r))},n.write=function(e,t,n){for(var _,a,i=n,r=0;r<e.length;++r)(_=e.charCodeAt(r))<128?t[n++]=_:_<2048?(t[n++]=_>>6|192,t[n++]=63&_|128):55296==(64512&_)&&56320==(64512&(a=e.charCodeAt(r+1)))?(_=65536+((1023&_)<<10)+(1023&a),++r,t[n++]=_>>18|240,t[n++]=_>>12&63|128,t[n++]=_>>6&63|128,t[n++]=63&_|128):(t[n++]=_>>12|224,t[n++]=_>>6&63|128,t[n++]=63&_|128);return n-i}},449:(e,t,n)=>{e.exports=u;var _,a=n(610),i=a.LongBits,r=a.base64,o=a.utf8;function s(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}function c(){}function l(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function u(){this.len=0,this.head=new s(c,0,0),this.tail=this.head,this.states=null}var d=function(){return a.Buffer?function(){return(u.create=function(){return new _})()}:function(){return new u}};function E(e,t,n){t[n]=255&e}function f(e,t){this.len=e,this.next=void 0,this.val=t}function h(e,t,n){for(;e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function g(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}u.create=d(),u.alloc=function(e){return new a.Array(e)},a.Array!==Array&&(u.alloc=a.pool(u.alloc,a.Array.prototype.subarray)),u.prototype._push=function(e,t,n){return this.tail=this.tail.next=new s(e,t,n),this.len+=t,this},f.prototype=Object.create(s.prototype),f.prototype.fn=function(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e},u.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new f((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},u.prototype.int32=function(e){return e<0?this._push(h,10,i.fromNumber(e)):this.uint32(e)},u.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},u.prototype.uint64=function(e){var t=i.from(e);return this._push(h,t.length(),t)},u.prototype.int64=u.prototype.uint64,u.prototype.sint64=function(e){var t=i.from(e).zzEncode();return this._push(h,t.length(),t)},u.prototype.bool=function(e){return this._push(E,1,e?1:0)},u.prototype.fixed32=function(e){return this._push(g,4,e>>>0)},u.prototype.sfixed32=u.prototype.fixed32,u.prototype.fixed64=function(e){var t=i.from(e);return this._push(g,4,t.lo)._push(g,4,t.hi)},u.prototype.sfixed64=u.prototype.fixed64,u.prototype.float=function(e){return this._push(a.float.writeFloatLE,4,e)},u.prototype.double=function(e){return this._push(a.float.writeDoubleLE,8,e)};var p=a.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var _=0;_<e.length;++_)t[n+_]=e[_]};u.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(E,1,0);if(a.isString(e)){var n=u.alloc(t=r.length(e));r.decode(e,n,0),e=n}return this.uint32(t)._push(p,t,e)},u.prototype.string=function(e){var t=o.length(e);return t?this.uint32(t)._push(o.write,t,e):this._push(E,1,0)},u.prototype.fork=function(){return this.states=new l(this),this.head=this.tail=new s(c,0,0),this.len=0,this},u.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new s(c,0,0),this.len=0),this},u.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this},u.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t},u._configure=function(e){_=e,u.create=d(),_._configure()}},529:e=>{e.exports={}},595:(e,t,n)=>{e.exports=a;var _=n(610);function a(e,t,n){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");_.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(n)}(a.prototype=Object.create(_.EventEmitter.prototype)).constructor=a,a.prototype.rpcCall=function e(t,n,a,i,r){if(!i)throw TypeError("request must be specified");var o=this;if(!r)return _.asPromise(e,o,t,n,a,i);if(o.rpcImpl)try{return o.rpcImpl(t,n[o.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(e,n){if(e)return o.emit("error",e,t),r(e);if(null!==n){if(!(n instanceof a))try{n=a[o.responseDelimited?"decodeDelimited":"decode"](n)}catch(e){return o.emit("error",e,t),r(e)}return o.emit("data",n,t),r(null,n)}o.end(!0)})}catch(e){return o.emit("error",e,t),void setTimeout(function(){r(e)},0)}else setTimeout(function(){r(Error("already ended"))},0)},a.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},610:function(e,t,n){var _=t;function a(e,t,n){for(var _=Object.keys(t),a=0;a<_.length;++a)void 0!==e[_[a]]&&n||(e[_[a]]=t[_[a]]);return e}function i(e){function t(e,n){if(!(this instanceof t))return new t(e,n);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),n&&a(this,n)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}_.asPromise=n(45),_.base64=n(839),_.EventEmitter=n(358),_.float=n(410),_.inquire=n(153),_.utf8=n(447),_.pool=n(390),_.LongBits=n(239),_.isNode=Boolean("undefined"!=typeof globalThis&&globalThis&&globalThis.process&&globalThis.process.versions&&globalThis.process.versions.node),_.global=_.isNode&&globalThis||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,_.emptyArray=Object.freeze?Object.freeze([]):[],_.emptyObject=Object.freeze?Object.freeze({}):{},_.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},_.isString=function(e){return"string"==typeof e||e instanceof String},_.isObject=function(e){return e&&"object"==typeof e},_.isset=_.isSet=function(e,t){var n=e[t];return!(null==n||!e.hasOwnProperty(t))&&("object"!=typeof n||(Array.isArray(n)?n.length:Object.keys(n).length)>0)},_.Buffer=function(){try{var e=_.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),_._Buffer_from=null,_._Buffer_allocUnsafe=null,_.newBuffer=function(e){return"number"==typeof e?_.Buffer?_._Buffer_allocUnsafe(e):new _.Array(e):_.Buffer?_._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},_.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,_.Long=_.global.dcodeIO&&_.global.dcodeIO.Long||_.global.Long||_.inquire("long"),_.key2Re=/^true|false|0|1$/,_.key32Re=/^-?(?:0|[1-9][0-9]*)$/,_.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,_.longToHash=function(e){return e?_.LongBits.from(e).toHash():_.LongBits.zeroHash},_.longFromHash=function(e,t){var n=_.LongBits.fromHash(e);return _.Long?_.Long.fromBits(n.lo,n.hi,t):n.toNumber(Boolean(t))},_.merge=a,_.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},_.newError=i,_.ProtocolError=i("ProtocolError"),_.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=1;return function(){for(var e=Object.keys(this),n=e.length-1;n>-1;--n)if(1===t[e[n]]&&void 0!==this[e[n]]&&null!==this[e[n]])return e[n]}},_.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n)e[n]!==t&&delete this[e[n]]}},_.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},_._configure=function(){var e=_.Buffer;e?(_._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,n){return new e(t,n)},_._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):_._Buffer_from=_._Buffer_allocUnsafe=null}},818:(e,t,n)=>{e.exports=i;var _=n(449);(i.prototype=Object.create(_.prototype)).constructor=i;var a=n(610);function i(){_.call(this)}function r(e,t,n){e.length<40?a.utf8.write(e,t,n):t.utf8Write?t.utf8Write(e,n):t.write(e,n)}i._configure=function(){i.alloc=a._Buffer_allocUnsafe,i.writeBytesBuffer=a.Buffer&&a.Buffer.prototype instanceof Uint8Array&&"set"===a.Buffer.prototype.set.name?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var _=0;_<e.length;)t[n++]=e[_++]}},i.prototype.bytes=function(e){a.isString(e)&&(e=a._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(i.writeBytesBuffer,t,e),this},i.prototype.string=function(e){var t=a.Buffer.byteLength(e);return this.uint32(t),t&&this._push(r,t,e),this},i._configure()},839:(e,t)=>{var n=t;n.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&"="===e.charAt(t);)++n;return Math.ceil(3*e.length)/4-n};for(var _=new Array(64),a=new Array(123),i=0;i<64;)a[_[i]=i<26?i+65:i<52?i+71:i<62?i-4:i-59|43]=i++;n.encode=function(e,t,n){for(var a,i=null,r=[],o=0,s=0;t<n;){var c=e[t++];switch(s){case 0:r[o++]=_[c>>2],a=(3&c)<<4,s=1;break;case 1:r[o++]=_[a|c>>4],a=(15&c)<<2,s=2;break;case 2:r[o++]=_[a|c>>6],r[o++]=_[63&c],s=0}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,r)),o=0)}return s&&(r[o++]=_[a],r[o++]=61,1===s&&(r[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,r.slice(0,o))),i.join("")):String.fromCharCode.apply(String,r.slice(0,o))};var r="invalid encoding";n.decode=function(e,t,n){for(var _,i=n,o=0,s=0;s<e.length;){var c=e.charCodeAt(s++);if(61===c&&o>1)break;if(void 0===(c=a[c]))throw Error(r);switch(o){case 0:_=c,o=1;break;case 1:t[n++]=_<<2|(48&c)>>4,_=c,o=2;break;case 2:t[n++]=(15&_)<<4|(60&c)>>2,_=c,o=3;break;case 3:t[n++]=(3&_)<<6|c,o=0}}if(1===o)throw Error(r);return n-i},n.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},946:(e,t,n)=>{e.exports=n(394)}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(n.exports,n,n.exports,__webpack_require__),n.exports}__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var __webpack_exports__={};class DNTStorageAdapter{constructor(e){this.configStorage=e}async getFieldsForType(e){try{return await this.configStorage.getDNTFieldsForType(e)}catch(t){return console.error(`Failed to get DNT fields for type ${e}:`,t),{}}}async setFieldDNT(e,t,n){try{await this.configStorage.setDNTField(e,t,n),console.log(`Set DNT=${n} for ${e}.${t} (applies to all ${e} documents)`)}catch(n){throw console.error(`Failed to set DNT for ${e}.${t}:`,n),n}}async toggleFieldDNT(e,t){try{const n=await this.configStorage.toggleDNTField(e,t);return console.log(`Toggled DNT to ${n} for ${e}.${t} (applies to all ${e} documents)`),n}catch(n){throw console.error(`Failed to toggle DNT for ${e}.${t}:`,n),n}}async getFieldDNT(e,t){try{return await this.configStorage.getDNTFieldStatus(e,t)}catch(n){return console.error(`Failed to get DNT status for ${e}.${t}:`,n),!1}}async clearFieldsForType(e){try{await this.configStorage.clearDNTFieldsForType(e),console.log(`Cleared all DNT fields for type ${e}`)}catch(t){throw console.error(`Failed to clear DNT fields for type ${e}:`,t),t}}async getAllDNTFields(){try{return await this.configStorage.getAllDNTFields()}catch(e){return console.error("Failed to get all DNT fields:",e),{}}}async getPreferences(e){return console.warn("getPreferences(documentId) is deprecated. Use getFieldsForType(documentType) instead."),null}async savePreferences(e){console.warn("savePreferences is deprecated. Use setFieldDNT instead.");for(const[t,n]of Object.entries(e.fields))await this.setFieldDNT(e.documentType,t,n)}async clearPreferences(e){console.warn("clearPreferences(documentId) is deprecated. Use clearFieldsForType(documentType) instead.")}}class LegacyDNTStorageAdapter{getStorageKey(e){return`${LegacyDNTStorageAdapter.STORAGE_KEY_PREFIX}${e}`}async getPreferences(e){try{const t=this.getStorageKey(e),n=localStorage.getItem(t);return n?JSON.parse(n):null}catch(t){return console.error(`Failed to get legacy DNT preferences for ${e}:`,t),null}}async savePreferences(e){try{const t=this.getStorageKey(e.documentId),n={...e,updatedAt:(new Date).toISOString()};localStorage.setItem(t,JSON.stringify(n))}catch(e){throw console.error("Failed to save legacy DNT preferences:",e),e}}async clearPreferences(e){try{const t=this.getStorageKey(e);localStorage.removeItem(t)}catch(e){throw console.error("Failed to clear legacy DNT preferences:",e),e}}async migrateToUnified(e,t,n){const _=await this.getPreferences(t);if(_){console.log(`Migrating DNT preferences for ${t} (${n}) to unified config...`);for(const[t,a]of Object.entries(_.fields))await e.setDNTField(n,t,a);await this.clearPreferences(t),console.log(`Migration complete for ${t}`)}}}LegacyDNTStorageAdapter.STORAGE_KEY_PREFIX="sanity-translation-dnt-";const UNIFIED_CONFIG_DOC_ID="sanity-translation-plugin.config",UNIFIED_CONFIG_DOC_TYPE="EL_PluginConfiguration";class UnifiedConfigStorage{constructor(e){this.client=e}convertDNTArrayToMap(e){if(!e||!Array.isArray(e))return{};const t={};for(const n of e)if(n.documentType&&n.fields){t[n.documentType]={};for(const e of n.fields)e.fieldPath&&(t[n.documentType][e.fieldPath]=!1!==e.dnt)}return t}convertDNTMapToArray(e){if(!e||"object"!=typeof e)return[];const t=[];for(const[n,_]of Object.entries(e)){const e=Object.entries(_).map(([e,t])=>({_key:`${n}-${e}`.replace(/[^a-zA-Z0-9-_]/g,"-"),fieldPath:e,dnt:t}));t.push({documentType:n,fields:e})}return t}async load(){try{const e=await this.client.fetch("*[_id == $id][0]",{id:UNIFIED_CONFIG_DOC_ID});if(!e)return console.log("No unified configuration found in Sanity"),null;let t={};e.dntFieldConfigurations?t=this.convertDNTArrayToMap(e.dntFieldConfigurations):e.dntFieldMap&&(t=e.dntFieldMap);const n={projectId:e.projectId,accessToken:e.accessToken,translationApiEndpoint:e.translationApiEndpoint,requestContentType:e.requestContentType,responseAcceptHeader:e.responseAcceptHeader,defaultDocumentCreationMode:e.defaultDocumentCreationMode,locales:e.locales||[],defaultLocale:e.defaultLocale,dntFieldMap:t,debugMode:e.debugMode||!1,version:e.version||"1.0.0",lastUpdated:e.lastUpdated};return console.log("Loaded unified configuration from Sanity"),n}catch(e){throw console.error("Failed to load unified configuration from Sanity:",e),e}}async save(e){try{const t=this.convertDNTMapToArray(e.dntFieldMap),n={_id:UNIFIED_CONFIG_DOC_ID,_type:UNIFIED_CONFIG_DOC_TYPE,projectId:e.projectId,accessToken:e.accessToken,translationApiEndpoint:e.translationApiEndpoint,requestContentType:e.requestContentType,responseAcceptHeader:e.responseAcceptHeader,defaultDocumentCreationMode:e.defaultDocumentCreationMode,locales:e.locales,defaultLocale:e.defaultLocale,dntFieldConfigurations:t,debugMode:e.debugMode,version:e.version,lastUpdated:(new Date).toISOString()};await this.client.createOrReplace(n),console.log("Saved unified configuration to Sanity")}catch(e){throw console.error("Failed to save unified configuration to Sanity:",e),e}}async update(e){try{const t={...await this.load()||{},...e,lastUpdated:(new Date).toISOString()};await this.save(t)}catch(e){throw console.error("Failed to update unified configuration:",e),e}}async delete(){try{await this.client.delete(UNIFIED_CONFIG_DOC_ID),console.log("Deleted unified configuration from Sanity")}catch(e){throw console.error("Failed to delete unified configuration from Sanity:",e),e}}async loadOAuth(){const e=await this.load();return e&&e.projectId&&e.accessToken?{projectId:e.projectId,accessToken:e.accessToken}:null}async saveOAuth(e){await this.update({projectId:e.projectId,accessToken:e.accessToken})}async loadLocale(){const e=await this.load();return e?{locales:e.locales||[],defaultLocale:e.defaultLocale,version:e.version||"1.0.0",lastUpdated:e.lastUpdated||(new Date).toISOString()}:null}async saveLocale(e){await this.update({locales:e.locales,defaultLocale:e.defaultLocale})}async getDNTFieldsForType(e){const t=await this.load();return t?.dntFieldMap?.[e]||{}}async setDNTField(e,t,n){const _=(await this.load()||{}).dntFieldMap||{};_[e]||(_[e]={}),_[e][t]=n,await this.update({dntFieldMap:_})}async toggleDNTField(e,t){const n=(await this.load()||{}).dntFieldMap||{};n[e]||(n[e]={});const _=n[e][t]||!1;return n[e][t]=!_,await this.update({dntFieldMap:n}),n[e][t]}async getDNTFieldStatus(e,t){return(await this.getDNTFieldsForType(e))[t]||!1}async clearDNTFieldsForType(e){const t=(await this.load()||{}).dntFieldMap||{};delete t[e],await this.update({dntFieldMap:t})}async getAllDNTFields(){const e=await this.load();return e?.dntFieldMap||{}}async getTranslationEndpoint(){const e=await this.load();return e?.translationApiEndpoint||"https://app.easyling.com/_el/ext/direct/sanity"}async getRequestContentType(){const e=await this.load();return e?.requestContentType||"application/json"}async getResponseAcceptHeader(){const e=await this.load();return e?.responseAcceptHeader||"application/json"}async getDefaultDocumentCreationMode(){const e=await this.load();return e?.defaultDocumentCreationMode||"draft"}async getDebugMode(){const e=await this.load();return e?.debugMode||!1}async setDebugMode(e){await this.update({debugMode:e})}}class DNTServiceManager{constructor(){this.dntStorage=null,this.client=null}static getInstance(e){return DNTServiceManager.instance||(DNTServiceManager.instance=new DNTServiceManager),e&&!DNTServiceManager.instance.client&&DNTServiceManager.instance.initialize(e),DNTServiceManager.instance}initialize(e){if(this.client&&this.dntStorage)return;this.client=e;const t=new UnifiedConfigStorage(e);this.dntStorage=new DNTStorageAdapter(t),console.log("DNT Service Manager initialized")}getDNTStorage(){if(!this.dntStorage)throw new Error("DNT Service Manager not initialized. Call initialize() with a SanityClient first.");return this.dntStorage}isInitialized(){return null!==this.dntStorage}static reset(){DNTServiceManager.instance=null}}function getDNTStorage(){return DNTServiceManager.getInstance().getDNTStorage()}DNTServiceManager.instance=null;const NON_TRANSLATABLE_TYPES=["date","datetime","reference","image","file","geopoint","number","boolean"],DNT_FIELD_NAME_PATTERNS=["author","contributor","date","time","lastModification","lastModified","_key","_ref","_type","_id","_rev","_createdAt","_updatedAt"],DNT_GROUP_NAME_PATTERNS=["date","time"];function isNonTranslatableType(e){return!!e&&NON_TRANSLATABLE_TYPES.includes(e.toLowerCase())}function matchesDNTFieldNamePattern(e){if(!e)return{matches:!1};const t=e.toLowerCase();for(const e of DNT_FIELD_NAME_PATTERNS)if(t.includes(e.toLowerCase()))return{matches:!0,pattern:e};return{matches:!1}}function matchesDNTGroupPattern(e){if(!e)return{matches:!1};const t=e.toLowerCase();for(const e of DNT_GROUP_NAME_PATTERNS)if(t.includes(e.toLowerCase()))return{matches:!0,pattern:e};return{matches:!1}}function computeDNTDefault(e){if(isNonTranslatableType(e.fieldType))return{shouldBeDNT:!0,reason:`Field type "${e.fieldType}" is non-translatable`};const t=matchesDNTFieldNamePattern(e.fieldName);if(t.matches)return{shouldBeDNT:!0,reason:`Field name contains "${t.pattern}" pattern`};const n=matchesDNTGroupPattern(e.groupName);if(n.matches)return{shouldBeDNT:!0,reason:`Field is in group containing "${n.pattern}" pattern`};const _=matchesDNTGroupPattern(e.fieldsetName);return _.matches?{shouldBeDNT:!0,reason:`Field is in fieldset containing "${_.pattern}" pattern`}:{shouldBeDNT:!1,reason:"Field is translatable by default"}}function shouldShowDNTBadge(e){return!!e&&["string","text","url","email","array"].includes(e.toLowerCase())}function getDNTDebugInfo(e,t){const n=computeDNTDefault(e),_=[`Path: ${e.fieldPath}`,`Name: ${e.fieldName}`,`Type: ${e.fieldType||"unknown"}`];return e.groupName&&_.push(`Group: ${e.groupName}`),e.fieldsetName&&_.push(`Fieldset: ${e.fieldsetName}`),_.push(`Default DNT: ${n.shouldBeDNT} (${n.reason})`),void 0!==t&&_.push(`Stored DNT: ${t}`),_.join(" | ")}const ATOMIC_SANITY_TYPES=new Set(["slug","date","datetime","reference","image","file","geopoint","color","block","span"]);function buildGroqPath(e,t){return`*[_type == "${e.documentType}" && _id == $documentId][0].${t}`}class ContentExtractor{inferSanityType(e){if(null==e)return"undefined";if("object"==typeof e&&!Array.isArray(e)){const t=e;if(t._type)return t._type}return"string"==typeof e?"string":"number"==typeof e?"number":"boolean"==typeof e?"boolean":Array.isArray(e)?"array":"object"==typeof e?"object":"unknown"}isSanitySpecialType(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return!(!t._type||!ATOMIC_SANITY_TYPES.has(t._type))}shouldFlattenObject(e){return!(!e||"object"!=typeof e||Array.isArray(e)||this.isSanitySpecialType(e))}flattenObjectToFields(e,t,n,_){for(const[a,i]of Object.entries(e)){if(a.startsWith("_"))continue;const e=t?`${t}.${a}`:a;null!=i&&(Array.isArray(i)?this.flattenArrayToFields(i,e,a,n,_):"object"!=typeof i||!i._type||ATOMIC_SANITY_TYPES.has(i._type)?this.shouldFlattenObject(i)?this.flattenObjectToFields(i,e,n,_):this.addLeafField(a,i,e,n,_):this.flattenObjectToFields(i,e,n,_))}}flattenArrayToFields(e,t,n,_,a){if(e.every(e=>e&&"object"==typeof e&&"block"===e._type)){const i=this.processArray(n,e),r=computeDNTDefault({fieldPath:t,fieldName:n,fieldType:"block"});return void(_[t]={value:i,dnt:r.shouldBeDNT,type:"block",path:buildGroqPath(a,t)})}if(e.every(e=>e&&"object"==typeof e&&"reference"===e._type))return void(_[t]={value:JSON.stringify(e),dnt:!0,type:"array",path:buildGroqPath(a,t)});if(e.every(e=>e&&"object"==typeof e&&e._key)){for(const i of e){const e=`${t}[_key == "${i._key}"]`;i._type&&!ATOMIC_SANITY_TYPES.has(i._type)?this.flattenObjectToFields(i,e,_,a):i._type?this.addLeafField(n,i,e,_,a):this.flattenObjectToFields(i,e,_,a)}return}const i=computeDNTDefault({fieldPath:t,fieldName:n,fieldType:"array"});_[t]={value:JSON.stringify(e),dnt:i.shouldBeDNT,type:"array",path:buildGroqPath(a,t)}}addLeafField(e,t,n,_,a){let i,r;if("object"==typeof t&&null!==t&&"_type"in t&&"slug"===t._type)i=t.current||"",r="slug";else if("object"!=typeof t||null===t||!("_type"in t)||"date"!==t._type&&"datetime"!==t._type)"object"==typeof t?(i=JSON.stringify(t),r=this.inferSanityType(t)):"string"==typeof t?(i=t,r="string"):(i=String(t),r=this.inferSanityType(t));else{const e=t.value||t;i="string"==typeof e?e:JSON.stringify(e),r=t._type}const o=computeDNTDefault({fieldPath:n,fieldName:e,fieldType:r});_[n]={value:i,dnt:o.shouldBeDNT,type:r,path:buildGroqPath(a,n)}}async extractDocumentContent(e){if(!e||!e._id)throw new Error("Invalid document provided");return this.convertToHtml(e)}convertToHtml(e){if(!e)return"";let t="";for(const[n,_]of Object.entries(e))n.startsWith("_")||_&&(t+=this.processField(n,_));return t.trim()}async extractStructuredContent(e){if(!e||!e._id)throw new Error("Invalid document provided");const{title:t,foundAtTopLevel:n}=this.extractTitle(e),_=this.extractSlug(e),{bodyContent:a,fields:i,bodyFoundAtTopLevel:r,bodyFieldName:o}=this.separateContentAndFields(e);console.log("[ContentExtractor] extractStructuredContent:",{documentId:e._id,documentType:e._type,extractedTitle:t,titleFoundAtTopLevel:n,bodyFoundAtTopLevel:r,bodyFieldName:o,documentHasTopLevelTitle:"title"in e,documentHasTopLevelBody:"body"in e||"content"in e});const s=e._type||"document",c=await this.applyDNTPreferences(s,i);return{documentId:e._id,title:t,htmlContent:a,slug:_,fields:c,titleFoundAtTopLevel:n,bodyFoundAtTopLevel:r,bodyFieldName:o}}async applyDNTPreferences(e,t,n){try{const _=getDNTStorage(),a=await _.getFieldsForType(e),i={};for(const[e,_]of Object.entries(t)){const t=e.split(".").pop()||e;let r;_&&"object"==typeof _&&"type"in _&&(r=_.type);const o=n?.[e],s=computeDNTDefault({fieldPath:e,fieldName:t,fieldType:r,groupName:o?.groupName,fieldsetName:o?.fieldsetName}),c=e in a?a[e]:s.shouldBeDNT;if(_&&"object"==typeof _&&"value"in _){const t=_;i[e]={...t,dnt:c}}else i[e]={value:_,dnt:c,type:this.inferSanityType(_)}}return i}catch(n){return console.warn(`Failed to apply DNT preferences for document type ${e}:`,n),t}}async extractBulkContent(e){const t=[];for(const n of e)try{const e=await this.extractDocumentContent(n),{title:_}=this.extractTitle(n);t.push({documentId:n._id,title:_,htmlContent:e})}catch(e){console.warn(`Failed to extract content from document ${n._id}:`,e)}return t}async extractBulkStructuredContent(e){const t=[];for(const n of e)try{const e=await this.extractStructuredContent(n);t.push(e)}catch(e){console.warn(`Failed to extract structured content from document ${n?._id||"unknown"}:`,e)}return t}processField(e,t){return null==t?"":Array.isArray(t)?this.processArray(e,t):"object"==typeof t?this.processObject(e,t):"string"==typeof t||"number"==typeof t?this.wrapInHtml(e,String(t)):""}processArray(e,t){let n="";if(t.every(e=>e&&"object"==typeof e&&"block"===e._type&&("bullet"===e.listItem||"number"===e.listItem))){const e="number"===t[0]?.listItem?"ol":"ul";n+=`<${e}>`;for(const e of t)"block"===e._type&&(n+=`<li>${this.processPortableTextBlockContent(e)}</li>`);n+=`</${e}>`}else for(const _ of t)_&&"object"==typeof _?"block"===_._type?n+=this.processPortableTextBlock(_):n+=this.processObject(e,_):n+=this.wrapInHtml("item",String(_));return n}processPortableTextBlock(e){const t=this.processPortableTextBlockContent(e);switch(e.style||"normal"){case"h1":return`<h1>${t}</h1>`;case"h2":return`<h2>${t}</h2>`;case"h3":return`<h3>${t}</h3>`;case"h4":return`<h4>${t}</h4>`;case"h5":return`<h5>${t}</h5>`;case"h6":return`<h6>${t}</h6>`;case"blockquote":return`<blockquote>${t}</blockquote>`;default:return`<p>${t}</p>`}}processPortableTextBlockContent(e){if(!e.children||!Array.isArray(e.children))return"";let t="";for(const n of e.children)if("span"===n._type&&n.text){let e=n.text;if(n.marks&&Array.isArray(n.marks))for(const t of n.marks)if("string"==typeof t)switch(t){case"strong":e=`<strong>${e}</strong>`;break;case"em":e=`<em>${e}</em>`;break;case"underline":e=`<u>${e}</u>`;break;case"code":e=`<code>${e}</code>`}else if("object"==typeof t&&"link"===t._type){const n=t.href||"#";e=`<a href="${this.escapeHtml(n)}">${e}</a>`}t+=e}return t}processObject(e,t){let n="";if("reference"===t._type&&t._ref)return`<span data-reference="${t._ref}">Referenced content</span>`;if("image"===t._type){const e=t.alt||"Image",n=t.caption||"";return`<figure><img alt="${this.escapeHtml(e)}" />${n?`<figcaption>${this.escapeHtml(n)}</figcaption>`:""}</figure>`}if("file"===t._type){const e=t.title||"File";return`<a href="#" data-file-ref="${t.asset?._ref||""}">${this.escapeHtml(e)}</a>`}if("url"===t._type){const e=t.href||"#",n=t.text||e;return`<a href="${this.escapeHtml(e)}">${this.escapeHtml(n)}</a>`}if("geopoint"===t._type){const e=t.lat||0,n=t.lng||0,_=t.alt||"";return`<span data-geopoint data-lat="${e}" data-lng="${n}" ${_?`data-alt="${_}"`:""}>Location: ${e}, ${n}</span>`}if("slug"===t._type){const e=t.current||"";return`<span data-slug="${this.escapeHtml(e)}">${this.escapeHtml(e)}</span>`}if("date"===t._type||"datetime"===t._type){const e=t.value||t;if("string"==typeof e)return`<time datetime="${e}">${new Date(e).toLocaleDateString()}</time>`}if("color"===t._type){const e=t.hex||"#000000";return`<span data-color="${e}" data-alpha="${void 0!==t.alpha?t.alpha:1}" style="color: ${e}">Color: ${e}</span>`}if("span"===t._type&&t.marks&&Array.isArray(t.marks)){let e=t.text||"";for(const n of t.marks)if("string"==typeof n)switch(n){case"strong":e=`<strong>${e}</strong>`;break;case"em":e=`<em>${e}</em>`;break;case"underline":e=`<u>${e}</u>`;break;case"code":e=`<code>${e}</code>`}else if("object"==typeof n&&"link"===n._type){const t=n.href||"#";e=`<a href="${this.escapeHtml(t)}">${e}</a>`}return e}for(const[e,_]of Object.entries(t))!e.startsWith("_")&&_&&(n+=this.processField(e,_));return n}wrapInHtml(e,t){return`<div class="field-${e.replace(/[^a-zA-Z0-9-_]/g,"")}">${this.escapeHtml(t)}</div>`}separateContentAndFields(e){const t=["body","content"],n=["title","slug","_id","_type","_createdAt","_updatedAt","_rev"];let _,a="",i=!1;const r={},o={documentType:e._type||"document",documentId:e._id};for(const[n,s]of Object.entries(e))n.startsWith("_")||"title"!==n&&"slug"!==n&&s&&(t.includes(n)?(a+=this.processField(n,s),i=!0,_=n):Array.isArray(s)?this.flattenArrayToFields(s,n,n,r,o):"object"==typeof s&&s._type&&!ATOMIC_SANITY_TYPES.has(s._type)||this.shouldFlattenObject(s)?this.flattenObjectToFields(s,n,r,o):this.addLeafField(n,s,n,r,o));if(!a.trim()){const n=this.findBodyInNestedFields(e,t);n&&(a=n.content,i=!1,_=n.fieldPath)}if(!a.trim()){for(const[t,_]of Object.entries(e))t.startsWith("_")||n.includes(t)||!_||(a+=this.processField(t,_));i=!1,_=void 0}return{bodyContent:a.trim(),fields:r,bodyFoundAtTopLevel:i,bodyFieldName:_}}findBodyInNestedFields(e,t,n=""){for(const[_,a]of Object.entries(e)){if(_.startsWith("_"))continue;if(null==a)continue;const e=n?`${n}.${_}`:_;if("object"==typeof a&&!Array.isArray(a)){if(this.isSanitySpecialType(a))continue;for(const n of t)if(a[n]){const t=`${e}.${n}`,_=this.processField(n,a[n]);if(_.trim())return{content:_,fieldPath:t}}const n=this.findBodyInNestedFields(a,t,e);if(n)return n}if(Array.isArray(a))for(const n of a)if(n&&"object"==typeof n&&!this.isSanitySpecialType(n)){for(const _ of t)if(n[_]){const t=n._key?`${e}[_key == "${n._key}"].${_}`:`${e}.${_}`,a=this.processField(_,n[_]);if(a.trim())return{content:a,fieldPath:t}}const _=n._key?`${e}[_key == "${n._key}"]`:e,a=this.findBodyInNestedFields(n,t,_);if(a)return a}}return null}extractSlug(e){if(e.slug){if("object"==typeof e.slug&&null!==e.slug&&"_type"in e.slug&&"slug"===e.slug._type)return e.slug.current||"";if("string"==typeof e.slug)return e.slug}const t=["slug","path","url","permalink"];for(const n of t)if(e[n]){if("object"==typeof e[n]&&null!==e[n]&&"_type"in e[n]&&"slug"===e[n]._type)return e[n].current||"";if("string"==typeof e[n])return e[n]}return""}extractTitle(e){const t=["title","name","heading","label"];for(const n of t)if(e[n]&&"string"==typeof e[n])return{title:e[n],foundAtTopLevel:!0};const n=this.findTitleInNestedFields(e,t);return n?{title:n,foundAtTopLevel:!1}:{title:`${e._type} (${e._id})`,foundAtTopLevel:!1}}findTitleInNestedFields(e,t){for(const[n,_]of Object.entries(e))if(!n.startsWith("_")&&null!=_){if("object"==typeof _&&!Array.isArray(_)){if(this.isSanitySpecialType(_))continue;for(const e of t)if(_[e]&&"string"==typeof _[e])return _[e];const e=this.findTitleInNestedFields(_,t);if(e)return e}if(Array.isArray(_))for(const e of _)if(e&&"object"==typeof e&&!this.isSanitySpecialType(e)){for(const n of t)if(e[n]&&"string"==typeof e[n])return e[n];const n=this.findTitleInNestedFields(e,t);if(n)return n}}return null}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}class DocumentCreationService{constructor(e,t){this.defaultCreationMode="draft",this.client=e,t&&(this.defaultCreationMode=t)}setDefaultCreationMode(e){this.defaultCreationMode=e}async createDocumentFromTranslation(e,t,n={}){try{const _=this.validateInputsForDocumentCreation(e,t,n);if(!_.isValid)return{success:!1,error:`Input validation failed: ${_.errors.join(", ")}`};const a=t.translatedDocuments?.[0]||t.translatedContent;if(console.log("[DocumentCreation] createDocumentFromTranslation:",{titleFoundAtTopLevelFromOptions:n.titleFoundAtTopLevel,translatedContentKeys:a?Object.keys(a):[]}),!t.success||!a)return{success:!1,error:"Translation response does not contain valid translated content"};const i=this.validateTranslationResponseForCreation(t);if(!i.isValid)return{success:!1,error:`Translation response validation failed: ${i.errors.join(", ")}`};const r=await this.mergeTranslatedContent(e,a,n),o=this.validateDocumentStructure(r);if(!o.isValid)return{success:!1,error:`Document validation failed: ${o.errors.join(", ")}`};const s=this.validateBusinessRules(r,e);if(!s.isValid)return{success:!1,error:`Business rule validation failed: ${s.errors.join(", ")}`};let c;if(s.slugNeedsFallback){const t=n.targetLanguage||"translated",_="object"==typeof e.slug?e.slug.current:e.slug,a=`${_}_${t}`;"object"==typeof r.slug&&null!==r.slug&&"_type"in r.slug?r.slug={_type:"slug",current:a}:r.slug=a,c={documentId:r._id,originalSlug:_,fallbackSlug:a,locale:t,reason:"Translation did not produce a different slug - locale suffix applied"},console.log(`[Slug Fallback Applied] Document ${r._id}: "${_}" → "${a}"`)}const l=n.creationMode||this.defaultCreationMode;try{let e;if("draft"===l){const t=r._id.startsWith("drafts.")?r._id:`drafts.${r._id}`;console.log("Creating draft document in Sanity:",t),e=await this.client.create({...r,_id:t}),console.log("Draft document created successfully:",e._id)}else{const t=r._id.startsWith("drafts.")?r._id.replace(/^drafts\./,""):r._id;console.log("Creating published document in Sanity:",t),e=await this.client.create({...r,_id:t}),console.log("Published document created successfully:",e._id)}return{success:!0,documentId:e._id,document:e,slugFallback:c}}catch(e){return console.error("Failed to create document in Sanity:",e),{success:!1,error:`Failed to save document to Sanity: ${e instanceof Error?e.message:"Unknown Sanity error"}`}}}catch(t){return{success:!1,error:this.formatErrorMessage(t,e._id)}}}validateInputsForDocumentCreation(e,t,n){const _=[];return e?(e._id||_.push("Original document must have an _id"),e._type||_.push("Original document must have a _type"),t?(n.targetLanguage&&"string"!=typeof n.targetLanguage&&_.push("Target language must be a string"),n.sourceLanguage&&"string"!=typeof n.sourceLanguage&&_.push("Source language must be a string"),void 0!==n.createAsVariant&&"boolean"!=typeof n.createAsVariant&&_.push("createAsVariant must be a boolean"),n.parentDocumentId&&"string"!=typeof n.parentDocumentId&&_.push("parentDocumentId must be a string"),{isValid:0===_.length,errors:_}):(_.push("Translation response is required"),{isValid:!1,errors:_})):(_.push("Original document is required"),{isValid:!1,errors:_})}validateBusinessRules(e,t){const n=[];let _=!1;if(e._id===t._id&&n.push("New document ID must be different from original document ID"),e._type!==t._type&&n.push(`New document type (${e._type}) must match original document type (${t._type})`),this.documentHasContent(e)||n.push("New document must contain some translatable content"),e.slug&&t.slug){const n="object"==typeof e.slug?e.slug.current:e.slug;n===("object"==typeof t.slug?t.slug.current:t.slug)&&(console.warn(`[Slug Fallback] Document ${e._id}: Slug "${n}" is same as original. Will apply locale suffix.`),_=!0)}return{isValid:0===n.length,errors:n,slugNeedsFallback:_}}documentHasContent(e){const t=["title","name","heading","label"],n=["body","content"];for(const n of t)if(e[n]&&"string"==typeof e[n]&&e[n].trim().length>0)return!0;for(const t of n)if(e[t]){if("string"==typeof e[t]&&e[t].trim().length>0)return!0;if(Array.isArray(e[t])&&e[t].length>0)return!0}return!!this.hasContentInNestedFields(e,t,n)}hasContentInNestedFields(e,t,n){for(const[_,a]of Object.entries(e))if(!_.startsWith("_")&&null!=a){if("object"==typeof a&&!Array.isArray(a)){for(const e of t)if(a[e]&&"string"==typeof a[e]&&a[e].trim().length>0)return!0;for(const e of n)if(a[e]){if("string"==typeof a[e]&&a[e].trim().length>0)return!0;if(Array.isArray(a[e])&&a[e].length>0)return!0}if(this.hasContentInNestedFields(a,t,n))return!0}if(Array.isArray(a))for(const e of a)if(e&&"object"==typeof e){for(const n of t)if(e[n]&&"string"==typeof e[n]&&e[n].trim().length>0)return!0;for(const t of n)if(e[t]){if("string"==typeof e[t]&&e[t].trim().length>0)return!0;if(Array.isArray(e[t])&&e[t].length>0)return!0}if(this.hasContentInNestedFields(e,t,n))return!0}}return!1}formatErrorMessage(e,t){const n=e instanceof Error?e.message:"Unknown error occurred during document creation",_=t?` (Document ID: ${t})`:"";if(e instanceof Error){if(e.message.includes("validation"))return`Document validation error${_}: ${e.message}`;if(e.message.includes("network")||e.message.includes("fetch"))return`Network error during document creation${_}: ${e.message}`;if(e.message.includes("permission")||e.message.includes("unauthorized"))return`Permission error during document creation${_}: ${e.message}`}return`Document creation error${_}: ${n}`}async createBulkDocumentsFromTranslations(e,t,n={}){const _={totalDocuments:e.length,successfulCreations:0,failedCreations:0,results:[],errors:[],rollbackInfo:{canRollback:!0,createdDocumentIds:[],rollbackInstructions:[]},slugFallbacks:[]},a=this.validateBulkTranslationResponses(e,t);if(a.length>0){_.errors.push(...a),_.failedCreations=e.length,_.rollbackInfo.canRollback=!1,_.rollbackInfo.rollbackInstructions.push("No documents were created due to validation failures");for(let t=0;t<e.length;t++)_.results.push({success:!1,error:"Bulk validation failed - no documents created"});return _}const i=[];for(let a=0;a<e.length;a++){const r=e[a],o=t[a];if(!o){const e=`No translation response found for document ${r._id}`;_.results.push({success:!1,error:e}),_.errors.push(e),_.failedCreations++;continue}try{const e=this.validateTranslationResponseForCreation(o);if(!e.isValid){const t=`Pre-creation validation failed for ${r._id}: ${e.errors.join(", ")}`;_.results.push({success:!1,error:t}),_.errors.push(t),_.failedCreations++;continue}const t=o.translatedDocuments||(o.translatedContent?[o.translatedContent]:[]);if(0===t.length){const e=`No translated documents found in response for ${r._id}`;_.results.push({success:!1,error:e}),_.errors.push(e),_.failedCreations++;continue}for(let e=0;e<t.length;e++){const a=t[e],s=a.locale||n.targetLanguage||"translated";console.log(`Creating document for ${r._id} with target locale: ${s}`);const c={...o,translatedDocuments:[a],translatedContent:a},l=await this.createDocumentFromTranslation(r,c,{...n,targetLanguage:s});_.results.push(l),l.success&&l.documentId?(_.successfulCreations++,i.push({documentId:l.documentId,originalId:r._id}),_.rollbackInfo.createdDocumentIds.push(l.documentId),l.slugFallback&&_.slugFallbacks.push(l.slugFallback)):(_.failedCreations++,l.error&&_.errors.push(l.error))}}catch(e){const t=e instanceof Error?e.message:"Unknown error occurred";_.results.push({success:!1,error:t}),_.errors.push(t),_.failedCreations++}}return _.successfulCreations>0?_.rollbackInfo.rollbackInstructions=[`${_.successfulCreations} documents were successfully created.`,"To rollback these changes, you would need to delete the following document IDs:",..._.rollbackInfo.createdDocumentIds.map(e=>`- ${e}`),"Note: This plugin does not automatically delete documents for safety reasons.","Manual deletion through Sanity Studio or API calls would be required."]:_.rollbackInfo.rollbackInstructions=["No documents were created, no rollback needed."],_.slugFallbacks.length>0&&(console.log(`[Slug Fallback Summary] ${_.slugFallbacks.length} document(s) had slug fallback applied:`),_.slugFallbacks.forEach(e=>{console.log(` - ${e.documentId}: "${e.originalSlug}" → "${e.fallbackSlug}" (locale: ${e.locale})`)})),_}validateBulkTranslationResponses(e,t){const n=[];if(e.length!==t.length)return n.push(`Mismatch between original documents (${e.length}) and translation responses (${t.length})`),n;for(let _=0;_<e.length;_++){const a=e[_],i=t[_];a?a._id?a._type?i?i.success&&(0!==(i.translatedDocuments||(i.translatedContent?[i.translatedContent]:[])).length||n.push(`Translation response at index ${_} missing translatedDocuments/translatedContent despite success=true`)):n.push(`Translation response at index ${_} is null or undefined`):n.push(`Original document at index ${_} missing _type`):n.push(`Original document at index ${_} missing _id`):n.push(`Original document at index ${_} is null or undefined`)}return n}validateTranslationResponseForCreation(e){const t=[];if(!e.success)return t.push("Translation response indicates failure"),{isValid:!1,errors:t};const n=e.translatedDocuments||(e.translatedContent?[e.translatedContent]:[]);if(0===n.length)return t.push("Translation response missing translatedDocuments/translatedContent"),{isValid:!1,errors:t};for(let e=0;e<n.length;e++){const _=n[e];"object"==typeof _&&null!==_?(_.body||_.title||_.fields||t.push(`Translated document at index ${e} must contain at least one of: body, title, or fields`),void 0!==_.body&&("string"!=typeof _.body?t.push(`Translated document at index ${e} body must be a string`):0===_.body.trim().length&&t.push(`Translated document at index ${e} body cannot be empty`)),void 0!==_.title&&("string"!=typeof _.title?t.push(`Translated document at index ${e} title must be a string`):0===_.title.trim().length&&t.push(`Translated document at index ${e} title cannot be empty`)),void 0!==_.slug&&("string"!=typeof _.slug?t.push(`Translated document at index ${e} slug must be a string`):0===_.slug.trim().length?t.push(`Translated document at index ${e} slug cannot be empty`):/^[a-z0-9-_]+$/.test(_.slug)||t.push(`Translated document at index ${e} slug must contain only lowercase letters, numbers, hyphens, and underscores`)),void 0!==_.fields&&("object"!=typeof _.fields||null===_.fields||Array.isArray(_.fields))&&t.push(`Translated document at index ${e} fields must be an object`)):t.push(`Translated document at index ${e} must be an object`)}return{isValid:0===t.length,errors:t}}createRollbackPlan(e){return 0===e.length?{canRollback:!0,createdDocumentIds:[],rollbackInstructions:["No documents were created, no rollback needed."]}:{canRollback:!0,createdDocumentIds:[...e],rollbackInstructions:[`Rollback plan for ${e.length} created documents:`,"","1. Manual deletion required (for safety):",...e.map(e=>` - Delete document: ${e}`),"","2. Alternative: Use Sanity CLI or API:"," sanity documents delete <document-id>","","3. Or via Sanity Client API:"," client.delete(documentId)","","WARNING: This plugin does not provide automatic rollback to prevent","accidental data loss. Please review each document before deletion."]}}parseFieldPath(e){const t=[],n=e.match(/^\*\[.*?\]\[0\]\./),_=n?e.substring(n[0].length):e,a=/([^.[]+)(?:\[_key\s*==\s*"([^"]+)"\])?/g;let i;for(;null!==(i=a.exec(_));){const[,e,n]=i;n?t.push({type:"arrayKey",name:e,key:n}):t.push({type:"property",name:e}),"."===_[a.lastIndex]&&a.lastIndex++}return t}unflattenFields(e,t){const n={};for(const[_,a]of Object.entries(e)){const e=a&&"object"==typeof a&&"path"in a?a.path:_,i=this.parseFieldPath(e);if(0===i.length)continue;let r,o=a;if(a&&"object"==typeof a&&"value"in a){if(o=a.value,r=a.type,"string"==typeof o&&(o.startsWith("[")&&o.endsWith("]")||o.startsWith("{")&&o.endsWith("}")))try{o=JSON.parse(o)}catch{}"block"===r&&"string"==typeof o&&this.isHtmlContent(o)&&(o=this.convertHtmlToPortableText(o))}let s=n,c=t;for(let e=0;e<i.length;e++){const t=i[e],n=e===i.length-1;if("arrayKey"===t.type){t.name in s||(c&&Array.isArray(c[t.name])?s[t.name]=JSON.parse(JSON.stringify(c[t.name])):s[t.name]=[]);const e=s[t.name];let _=e.find(e=>e._key===t.key);if(!_){let n=null;c&&Array.isArray(c[t.name])&&(n=c[t.name].find(e=>e._key===t.key)),_=n?JSON.parse(JSON.stringify(n)):{_key:t.key},e.push(_)}n?Object.assign(_,o):(s=_,c=c?.[t.name]?.find(e=>e._key===t.key))}else n?s[t.name]=o:(t.name in s||(c&&"object"==typeof c[t.name]&&null!==c[t.name]?s[t.name]=Array.isArray(c[t.name])?JSON.parse(JSON.stringify(c[t.name])):{...c[t.name]}:s[t.name]={}),s=s[t.name],c=c?.[t.name])}}return n}getOriginalValueByPath(e,t){const n=t.split(".");let _=e;for(const e of n){if(null==_||"object"!=typeof _)return;_=_[e]}return _}async mergeTranslatedContent(e,t,n){const _=n.targetLanguage||t.locale,a={...e,_id:this.generateNewDocumentId(e._id,_),_rev:void 0,_createdAt:void 0,_updatedAt:void 0},i=!1!==n.titleFoundAtTopLevel;console.log("[DocumentCreation] Title handling:",{originalDocumentTitle:e.title,originalDocumentHasTitle:"title"in e,translatedContentTitle:t.title,titleFoundAtTopLevelFromOptions:n.titleFoundAtTopLevel,shouldWriteTopLevelTitle:i,newDocumentTitleBefore:a.title}),t.title&&t.title.trim()&&i?(a.title=t.title,console.log("[DocumentCreation] Writing title to top level:",t.title)):!i&&"title"in a?(console.log("[DocumentCreation] Removing inherited top-level title field"),delete a.title):console.log("[DocumentCreation] NOT writing title. Reason:",{hasTitle:!!t.title,titleNotEmpty:!!t.title?.trim(),shouldWriteTopLevelTitle:i}),t.slug&&t.slug.trim()&&("object"==typeof e.slug&&null!==e.slug&&"_type"in e.slug?a.slug={_type:"slug",current:t.slug}:a.slug=t.slug);const r=!1!==n.bodyFoundAtTopLevel;if(console.log("[DocumentCreation] Body handling:",{hasTranslatedBody:!!t.body,bodyFoundAtTopLevelFromOptions:n.bodyFoundAtTopLevel,bodyFieldNameFromOptions:n.bodyFieldName,shouldWriteTopLevelBody:r,originalHasBody:"body"in e,originalHasContent:"content"in e}),t.body&&t.body.trim()){const _=this.convertHtmlToPortableText(t.body);if(r){const t=["body","content","text","description"];let n=!1;for(const i of t)if(e[i]){a[i]=_,console.log("[DocumentCreation] Writing body to top-level field:",i),n=!0;break}n||(a.body=_,console.log('[DocumentCreation] Writing body to new top-level "body" field'))}else{console.log("[DocumentCreation] NOT writing body to top level (was found in nested field:",n.bodyFieldName,")");const t=["body","content","text","description"];for(const n of t)n in a&&!(n in e)&&(console.log("[DocumentCreation] Removing inherited top-level field:",n),delete a[n])}}if(t.fields&&"object"==typeof t.fields){const n=this.unflattenFields(t.fields,e);for(const[t,_]of Object.entries(n)){if("title"===t||"slug"===t||void 0===_)continue;const n=this.processTranslatedField(t,_,e[t]);void 0!==n&&(a[t]=n)}for(const[_,i]of Object.entries(t.fields))if("title"!==_&&"slug"!==_&&void 0!==i&&_.includes(".")&&!(_.split(".")[0]in n)){const t=this.getOriginalValueByPath(e,_),n=this.processTranslatedField(_,i,t);if(void 0!==n){const e=_.split(".");let t=a;for(let n=0;n<e.length-1;n++){const _=e[n];_ in t&&null!==t[_]&&"object"==typeof t[_]||(t[_]={}),t=t[_]}t[e[e.length-1]]=n}}}_&&(e.locale&&"object"==typeof e.locale&&"value"in e.locale?a.locale={...e.locale,value:_}:a.locale&&"object"==typeof a.locale&&"value"in a.locale?a.locale={...a.locale,value:_}:void 0!==e.locale&&(a.locale=_));const o=Object.keys(a);for(const e of o)null===a[e]&&delete a[e];return n.createAsVariant&&n.parentDocumentId&&(a.parentDocument={_type:"reference",_ref:n.parentDocumentId}),a}processTranslatedField(e,t,n){if(null==t)return t;let _=t,a=!1;if(t&&"object"==typeof t&&"value"in t&&(_=t.value,a=t.dnt||!1),a&&void 0!==n)return n;if(n&&"object"==typeof n&&null!==n){if("dnt"in n&&"value"in n){let e=_;return t&&"object"==typeof t&&"value"in t&&(e=t.value),null!=e&&""!==e||null===n.value||void 0===n.value||""===n.value?{dnt:a,value:e}:n}if("_type"in n&&"slug"===n._type)return{_type:"slug",current:"string"==typeof _?_:String(_)};if("_type"in n&&("date"===n._type||"datetime"===n._type))return{_type:n._type,value:_};if("_type"in n&&"reference"===n._type)return n}return"string"==typeof _&&this.isHtmlContent(_)?this.convertHtmlToPortableText(_):_}convertHtmlToPortableText(e){if(!e||!e.trim())return[];const t=[],n=/<(h[1-6]|p|div|blockquote|li)([^>]*)>(.*?)<\/\1>/gi;let _,a=0;for(;null!==(_=n.exec(e));){const[,e,,n]=_;if(!n.trim())continue;const i={_type:"block",_key:this.generateBlockKey(),style:this.getBlockStyle(e.toLowerCase()),children:this.parseInlineContent(n),markDefs:[]};"li"===e.toLowerCase()&&(i.listItem="bullet"),t.push(i),a=_.index+_[0].length}const i=e.substring(a).trim();if(i){const e=i.replace(/<[^>]+>/g,"").trim();e&&t.push({_type:"block",_key:this.generateBlockKey(),style:"normal",children:this.parseInlineContent(e),markDefs:[]})}if(0===t.length&&e.trim()){const n=e.replace(/<[^>]+>/g,"").trim();n&&t.push({_type:"block",_key:this.generateBlockKey(),style:"normal",children:this.parseInlineContent(n),markDefs:[]})}return t}parseInlineContent(e){const t=[],n=e.replace(/<strong[^>]*>(.*?)<\/strong>/gi,"**$1**").replace(/<em[^>]*>(.*?)<\/em>/gi,"*$1*").replace(/<u[^>]*>(.*?)<\/u>/gi,"_$1_").replace(/<code[^>]*>(.*?)<\/code>/gi,"`$1`").replace(/<[^>]+>/g,"").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&").replace(/&quot;/g,'"').replace(/&#39;/g,"'");return n.trim()&&t.push({_type:"span",_key:this.generateSpanKey(),text:n,marks:[]}),t}getBlockStyle(e){return{h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",blockquote:"blockquote",p:"normal",div:"normal",li:"normal"}[e]||"normal"}isHtmlContent(e){return/<[^>]+>/.test(e)}generateNewDocumentId(e,t){return`${e.startsWith("drafts.")?e.replace(/^drafts\./,""):e}${t?`-${t}`:"-translated"}-${Date.now()}`}generateBlockKey(){return Math.random().toString(36).substr(2,9)}generateSpanKey(){return Math.random().toString(36).substr(2,9)}validateDocumentStructure(e){const t=[];e._id||t.push("Document must have an _id"),e._type||t.push("Document must have a _type");const n=["body","content","text","description"];for(const _ of n)if(e[_]&&Array.isArray(e[_])){const n=this.validatePortableTextArray(e[_],_);n.isValid||t.push(...n.errors)}if(e.slug&&"object"==typeof e.slug&&null!==e.slug&&"_type"in e.slug){const n=e.slug;"slug"!==n._type&&t.push('Slug object must have _type of "slug"'),n.current||t.push("Slug object must have a current value")}return{isValid:0===t.length,errors:t}}validatePortableTextArray(e,t){const n=[];if(!Array.isArray(e))return n.push(`${t} must be an array`),{isValid:!1,errors:n};for(let _=0;_<e.length;_++){const a=e[_];if(!a||"object"!=typeof a){n.push(`${t}[${_}] must be an object`);continue}const i=a;if(i._type||n.push(`${t}[${_}] must have a _type`),i._key||n.push(`${t}[${_}] must have a _key`),"block"===i._type)if(Array.isArray(i.children)){const e=i.children;for(let a=0;a<e.length;a++){const i=e[a];if(!i||"object"!=typeof i){n.push(`${t}[${_}].children[${a}] must be an object`);continue}const r=i;r._type||n.push(`${t}[${_}].children[${a}] must have a _type`),r._key||n.push(`${t}[${_}].children[${a}] must have a _key`)}}else n.push(`${t}[${_}] block must have children array`)}return{isValid:0===n.length,errors:n}}}const LOCALE_CODE_REGEX=/^[a-z]{2}-[A-Z]{2}$/;function validateLocaleCode(e){return!(!e||"string"!=typeof e)&&LOCALE_CODE_REGEX.test(e)}function validateLocaleDefinition(e){const t=[],n=[];return e.code?validateLocaleCode(e.code)||t.push("Locale code must be in format: xx-XX (e.g., en-US, fr-FR)"):t.push("Locale code is required"),e.displayName?0===e.displayName.trim().length?t.push("Display name cannot be empty"):e.displayName.length>100&&n.push("Display name is very long (over 100 characters)"):t.push("Display name is required"),void 0!==e.enabled&&"boolean"!=typeof e.enabled&&t.push("Enabled flag must be a boolean value"),e.createdAt&&!isValidISODate(e.createdAt)&&t.push("createdAt must be a valid ISO 8601 date string"),e.updatedAt&&!isValidISODate(e.updatedAt)&&t.push("updatedAt must be a valid ISO 8601 date string"),{isValid:0===t.length,errors:t,warnings:n}}function validateLocaleConfig(e){const t=[],n=[];if(e.locales)if(Array.isArray(e.locales)){const _=new Set;e.locales.forEach((e,a)=>{const i=validateLocaleDefinition(e);i.isValid||t.push(`Locale at index ${a}: ${i.errors.join(", ")}`),i.warnings.length>0&&n.push(`Locale at index ${a}: ${i.warnings.join(", ")}`),e.code&&(_.has(e.code)&&t.push(`Duplicate locale code: ${e.code}`),_.add(e.code))}),0===e.locales.length&&n.push("No locales configured - users will not be able to translate content")}else t.push("Locales must be an array");else t.push("Locales array is required");return e.defaultLocale&&(validateLocaleCode(e.defaultLocale)?e.locales&&Array.isArray(e.locales)&&(e.locales.some(t=>t.code===e.defaultLocale)||n.push("Default locale is not in the configured locales list")):t.push("Default locale must be in format: xx-XX (e.g., en-US)")),e.version?"string"!=typeof e.version&&t.push("Configuration version must be a string"):t.push("Configuration version is required"),e.lastUpdated?isValidISODate(e.lastUpdated)||t.push("lastUpdated must be a valid ISO 8601 date string"):t.push("lastUpdated timestamp is required"),{isValid:0===t.length,errors:t,warnings:n}}function localeExists(e,t){return e.locales.some(e=>e.code===t)}function getEnabledLocales(e){return e.locales.filter(e=>e.enabled)}function findLocaleByCode(e,t){return e.locales.find(e=>e.code===t)}function isValidISODate(e){if(!e||"string"!=typeof e)return!1;const t=new Date(e);return t instanceof Date&&!isNaN(t.getTime())&&t.toISOString()===e}const RadioWithDefault=e=>{const{value:t,onChange:n,defaultValue:_,renderDefault:a}=e;return __WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{null!=t&&""!==t||n(__WEBPACK_EXTERNAL_MODULE_sanity_set__(_))},[t,_,n]),a({...e,value:null!=t&&""!==t?t:_})};RadioWithDefault.displayName="RadioWithDefault";const createPluginConfigSchema=e=>({name:"EL_PluginConfiguration",title:"Easyling Translation Plugin Configuration",type:"document",fields:[{name:"projectId",title:"Project ID",type:"string",description:"Easyling project identifier",group:"oauth"},{name:"accessToken",title:"Access Token",type:"string",description:"Easyling API access token (hidden for security)",group:"oauth",...e&&{components:{input:e}}},{name:"translationApiEndpoint",title:"Translation API Endpoint",type:"string",description:"The URL where translation requests will be sent (defaults to https://app.easyling.com/_el/ext/direct/sanity if not set)",initialValue:"https://app.easyling.com/_el/ext/direct/sanity",placeholder:"https://app.easyling.com/_el/ext/direct/sanity",group:"translation",validation:e=>e.custom(e=>{if(!e||""===e.trim())return!0;try{const t=new URL(e.trim());return!!["http:","https:"].includes(t.protocol)||"Must be a valid HTTP or HTTPS URL"}catch(e){return"Must be a valid HTTP or HTTPS URL"}})},{name:"defaultDocumentCreationMode",title:"Default Document Creation Mode",type:"string",description:"Whether translated documents should be created as drafts or published by default",initialValue:"draft",group:"translation",options:{list:[{title:"Draft",value:"draft"},{title:"Published",value:"published"}],layout:"radio"},components:{input:e=>RadioWithDefault({...e,defaultValue:"draft"})}},{name:"requestContentType",title:"Request Content-Type",type:"string",description:"Serialization format for translation request payloads",initialValue:"application/json",group:"advanced",options:{list:[{title:"JSON",value:"application/json"},{title:"Protocol Buffer",value:"application/x-protobuf"}],layout:"radio"},components:{input:e=>RadioWithDefault({...e,defaultValue:"application/json"})}},{name:"responseAcceptHeader",title:"Response Accept Header",type:"string",description:"Preferred format for translation response (content negotiation)",initialValue:"application/json",group:"advanced",options:{list:[{title:"JSON",value:"application/json"},{title:"Protocol Buffer",value:"application/x-protobuf"}],layout:"radio"},components:{input:e=>RadioWithDefault({...e,defaultValue:"application/json"})}},{name:"locales",title:"Available Locales",type:"array",description:"Configure the locales available for translation",group:"locales",of:[{type:"object",name:"localeItem",title:"Locale",fields:[{name:"code",title:"Locale Code",type:"string",description:"Locale code in ISO 639-1 + ISO 3166-1 format (e.g., en-US, fr-FR)",validation:e=>e.required().regex(/^[a-z]{2}-[A-Z]{2}$/,{name:"locale-code",invert:!1}).error("Locale code must be in format: xx-XX (e.g., en-US, fr-FR)")},{name:"displayName",title:"Display Name",type:"string",description:"Human-readable name for this locale (e.g., English (United States))",validation:e=>e.required().min(1).error("Display name is required")},{name:"enabled",title:"Enabled",type:"boolean",description:"Whether this locale is available for translation",initialValue:!0},{name:"createdAt",title:"Created At",type:"string",hidden:!0},{name:"updatedAt",title:"Updated At",type:"string",hidden:!0}],preview:{select:{title:"displayName",subtitle:"code",enabled:"enabled"},prepare:({title:e,subtitle:t,enabled:n})=>({title:e||"Unnamed Locale",subtitle:t?`${t}${!1===n?" (Disabled)":""}`:""})}}]},{name:"defaultLocale",title:"Default Locale",type:"string",description:"Default locale code to use when none is specified",group:"locales",validation:e=>e.regex(/^[a-z]{2}-[A-Z]{2}$/,{name:"locale-code",invert:!1}).error("Default locale must be in format: xx-XX (e.g., en-US)")},{name:"debugMode",title:"Debug Mode",type:"boolean",description:"When enabled, displays additional DNT status badges on all fields to help debug translation settings. The debug badge shows the effective DNT status that will be sent in translation requests.",initialValue:!1,group:"advanced"},{name:"dntFieldConfigurations",title:"DNT Field Configurations",type:"array",description:"Document type DNT (Do Not Translate) field configurations. When you mark a field as DNT for a document type, it applies to all documents of that type. This is automatically managed when you toggle DNT badges in documents.",group:"dnt",readOnly:!0,of:[{type:"object",name:"dntTypeConfig",title:"Document Type DNT Configuration",fields:[{name:"documentType",title:"Document Type",type:"string",description:'The document type (e.g., "product", "article")',validation:e=>e.required()},{name:"fields",title:"DNT Fields",type:"array",description:"Fields marked as Do Not Translate",of:[{type:"object",name:"dntField",fields:[{name:"fieldPath",title:"Field Path",type:"string",description:'The field path (e.g., "sku", "price")',validation:e=>e.required()},{name:"dnt",title:"Do Not Translate",type:"boolean",description:"Whether this field should not be translated",initialValue:!0}],preview:{select:{fieldPath:"fieldPath",dnt:"dnt"},prepare:({fieldPath:e,dnt:t})=>({title:e||"Unknown field",subtitle:t?"Do Not Translate":"Translatable"})}}]}],preview:{select:{documentType:"documentType",fields:"fields"},prepare:({documentType:e,fields:t})=>({title:e||"Unknown type",subtitle:t?`${t.length} DNT field${1!==t.length?"s":""}`:"No DNT fields"})}}]},{name:"version",title:"Configuration Version",type:"string",description:"Internal version for configuration migration",initialValue:"1.0.0",readOnly:!0,hidden:!0},{name:"lastUpdated",title:"Last Updated",type:"datetime",description:"When this configuration was last modified",readOnly:!0,hidden:!0}],groups:[{name:"oauth",title:"Authentication",default:!0},{name:"translation",title:"Translation Settings"},{name:"locales",title:"Locales"},{name:"dnt",title:"DNT Field Configuration",description:"View DNT (Do Not Translate) settings for all document types"},{name:"advanced",title:"☢️ CAUTION ☢️ Dangerous Advanced Settings",description:"Advanced developer settings for request/response serialization. Changing these settings may break compatibility with your translation service."}],preview:{prepare:()=>({title:"Easyling Translation Plugin Configuration",subtitle:"OAuth, Translation Settings, Locales, and DNT field settings"})}}),pluginConfigSchema=createPluginConfigSchema(),legacyLocaleConfigSchema={name:"EL_translation-plugin-config",title:"Translation Plugin Configuration (Legacy)",type:"object",fields:[{name:"locales",title:"Available Locales",type:"array",description:"Configure the locales available for translation",of:[{type:"object",title:"Locale",fields:[{name:"code",title:"Locale Code",type:"string",description:"Locale code in ISO 639-1 + ISO 3166-1 format (e.g., en-US, fr-FR)",validation:e=>e.required().regex(/^[a-z]{2}-[A-Z]{2}$/,{name:"locale-code",invert:!1}).error("Locale code must be in format: xx-XX (e.g., en-US, fr-FR)")},{name:"displayName",title:"Display Name",type:"string",description:"Human-readable name for this locale (e.g., English (United States))",validation:e=>e.required().min(1).error("Display name is required")},{name:"enabled",title:"Enabled",type:"boolean",description:"Whether this locale is available for translation",initialValue:!0}],preview:{select:{title:"displayName",subtitle:"code",enabled:"enabled"},prepare:({title:e,subtitle:t,enabled:n})=>({title:e||"Unnamed Locale",subtitle:`${t}${n?"":" (Disabled)"}`,media:n?"🌐":"🚫"})}}]},{name:"defaultLocale",title:"Default Locale",type:"string",description:"Default locale code to use when none is specified",validation:e=>e.regex(/^[a-z]{2}-[A-Z]{2}$/,{name:"locale-code",invert:!1}).error("Default locale must be in format: xx-XX (e.g., en-US)")},{name:"version",title:"Configuration Version",type:"string",description:"Internal version for configuration migration",initialValue:"1.0.0",readOnly:!0}]},defaultLocaleConfig={locales:[],version:"1.0.0",lastUpdated:(new Date).toISOString()},commonLocales=[{code:"en-US",displayName:"English (United States)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"en-GB",displayName:"English (United Kingdom)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"es-ES",displayName:"Spanish (Spain)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"es-MX",displayName:"Spanish (Mexico)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"fr-FR",displayName:"French (France)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"de-DE",displayName:"German (Germany)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"it-IT",displayName:"Italian (Italy)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"pt-BR",displayName:"Portuguese (Brazil)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"ja-JP",displayName:"Japanese (Japan)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"ko-KR",displayName:"Korean (South Korea)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"zh-CN",displayName:"Chinese (Simplified)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()},{code:"zh-TW",displayName:"Chinese (Traditional)",enabled:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}];function pluginConfig_validateLocaleCode(e){return/^[a-z]{2}-[A-Z]{2}$/.test(e)}function createLocaleDefinition(e,t,n=!0){const _=(new Date).toISOString();return{code:e,displayName:t,enabled:n,createdAt:_,updatedAt:_}}function updateLocaleDefinition(e,t){return{...e,...t,updatedAt:(new Date).toISOString()}}class LocaleServiceError extends Error{constructor(e,t,n){super(e),this.code=t,this.details=n,this.name="LocaleServiceError"}}class LocaleService{constructor(e=null,t){this.storageAdapter=e,this.config=t||{...defaultLocaleConfig,locales:[...defaultLocaleConfig.locales]}}async loadConfig(){try{if(!this.storageAdapter)return this.config;const e=await this.storageAdapter.load();if(e){const t=validateLocaleConfig(e);if(!t.isValid)throw console.error("Loaded configuration is invalid:",t.errors),new LocaleServiceError("Configuration is corrupted and cannot be loaded","CONFIG_CORRUPTED",{errors:t.errors});return this.config=e,this.config}return this.config={...defaultLocaleConfig},this.config}catch(e){if(e instanceof LocaleServiceError)throw e;throw new LocaleServiceError("Failed to load locale configuration","LOAD_FAILED",{originalError:e})}}async saveConfig(e){try{const t=e||this.config,n=validateLocaleConfig(t);if(!n.isValid)throw new LocaleServiceError("Cannot save invalid configuration","INVALID_CONFIG",{errors:n.errors});t.lastUpdated=(new Date).toISOString(),this.storageAdapter&&await this.storageAdapter.save(t),this.config=t}catch(e){if(e instanceof LocaleServiceError)throw e;throw new LocaleServiceError("Failed to save locale configuration","SAVE_FAILED",{originalError:e})}}getConfig(){return{...this.config}}getAllLocales(){return[...this.config.locales]}getEnabledLocales(){return this.config.locales.filter(e=>e.enabled)}getLocaleByCode(e){return findLocaleByCode(this.config,e)}hasLocale(e){return localeExists(this.config,e)}async addLocale(e){const t=(new Date).toISOString(),n={...e,createdAt:t,updatedAt:t},_=validateLocaleDefinition(n);if(!_.isValid)throw new LocaleServiceError("Cannot add invalid locale","INVALID_LOCALE",{errors:_.errors});if(this.hasLocale(e.code))throw new LocaleServiceError(`Locale with code '${e.code}' already exists`,"DUPLICATE_LOCALE",{code:e.code});return this.config.locales.push(n),await this.saveConfig(),_}async updateLocale(e,t){const n=this.config.locales.findIndex(t=>t.code===e);if(-1===n)throw new LocaleServiceError(`Locale with code '${e}' not found`,"LOCALE_NOT_FOUND",{code:e});const _=this.config.locales[n],a={..._,...t,code:_.code,createdAt:_.createdAt,updatedAt:(new Date).toISOString()},i=validateLocaleDefinition(a);if(!i.isValid)throw new LocaleServiceError("Cannot update locale with invalid data","INVALID_LOCALE",{errors:i.errors});return this.config.locales[n]=a,await this.saveConfig(),i}async removeLocale(e){const t=this.config.locales.findIndex(t=>t.code===e);if(-1===t)throw new LocaleServiceError(`Locale with code '${e}' not found`,"LOCALE_NOT_FOUND",{code:e});this.config.locales.splice(t,1),this.config.defaultLocale===e&&(this.config.defaultLocale=void 0),await this.saveConfig()}async setDefaultLocale(e){if(!this.hasLocale(e))throw new LocaleServiceError(`Cannot set default locale: locale with code '${e}' not found`,"LOCALE_NOT_FOUND",{code:e});this.config.defaultLocale=e,await this.saveConfig()}async clearDefaultLocale(){this.config.defaultLocale=void 0,await this.saveConfig()}validateCurrentConfig(){return validateLocaleConfig(this.config)}async resetToDefault(){this.config={...defaultLocaleConfig},await this.saveConfig()}async importConfig(e){const t=validateLocaleConfig(e);if(!t.isValid)throw new LocaleServiceError("Cannot import invalid configuration","INVALID_CONFIG",{errors:t.errors});return this.config={...e},await this.saveConfig(),t}exportConfig(){return{...this.config}}}const LEGACY_LOCALE_CONFIG_DOC_ID="sanity-translation-plugin.locale-config";class SanityLocaleStorageAdapter{constructor(e){this.client=e,this.unifiedStorage=new UnifiedConfigStorage(e)}async load(){try{const e=await this.unifiedStorage.loadLocale();if(e&&e.locales&&e.locales.length>0)return console.log("Loaded locale configuration from unified storage"),e;const t=await this.loadLegacy();return t?(console.log("Migrating locale configuration from legacy storage..."),await this.save(t),await this.deleteLegacy(),console.log("Locale configuration migration complete"),t):(console.log("No locale configuration found"),null)}catch(e){throw console.error("Failed to load locale configuration:",e),e}}async save(e){try{await this.unifiedStorage.saveLocale(e),console.log("Saved locale configuration to unified storage")}catch(e){throw console.error("Failed to save locale configuration:",e),e}}async loadLegacy(){try{const e=await this.client.fetch("*[_id == $id][0]",{id:LEGACY_LOCALE_CONFIG_DOC_ID});return e?{locales:e.locales||[],defaultLocale:e.defaultLocale,version:e.version||"1.0.0",lastUpdated:e.lastUpdated||(new Date).toISOString()}:null}catch(e){return console.error("Failed to load legacy locale configuration:",e),null}}async deleteLegacy(){try{await this.client.delete(LEGACY_LOCALE_CONFIG_DOC_ID),console.log("Deleted legacy locale configuration document")}catch(e){console.warn("Failed to delete legacy locale document:",e)}}}const ConfirmationDialog=({open:e,title:t,message:n,details:_,confirmText:a="Confirm",cancelText:i="Cancel",tone:r="primary",closable:o=!0,onConfirm:s,onCancel:c})=>{const l=__WEBPACK_EXTERNAL_MODULE_react_useRef__(null);return __WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{e&&l.current&&setTimeout(()=>{l.current?.focus()},100)},[e]),e?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Dialog__,{id:"confirmation-dialog",header:t,onClose:o?c:void 0,onClickOutside:o?c:void 0,width:1,role:"alertdialog","aria-labelledby":"confirmation-dialog-title","aria-describedby":"confirmation-dialog-description",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:4,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:4,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{id:"confirmation-dialog-description",size:2,weight:"regular",children:n}),_&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:_})]})})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{ref:l,text:a,tone:r,onClick:s,mode:"default","aria-label":`${a} action`}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:i,tone:"default",onClick:c,mode:"ghost","aria-label":`${i} action`})]})]})})}):null},SuccessDialog=({open:e,title:t,message:n,details:_,autoCloseTimeout:a,closable:i=!0,onClose:r})=>{const o=__WEBPACK_EXTERNAL_MODULE_react_useRef__(null);return __WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{e&&o.current&&setTimeout(()=>{o.current?.focus()},100)},[e]),__WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{if(!e||!a)return;const t=setTimeout(()=>{r()},a);return()=>clearTimeout(t)},[e,a,r]),e?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Dialog__,{id:"success-dialog",header:t,onClose:i?r:void 0,onClickOutside:i?r:void 0,width:1,role:"dialog","aria-labelledby":"success-dialog-title","aria-describedby":"success-dialog-description",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:4,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:4,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{tone:"positive",padding:3,radius:2,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CheckmarkCircleIcon__,{})})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{id:"success-dialog-description",size:2,weight:"regular",children:n}),_&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:_})]})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{ref:o,text:"Close",tone:"positive",onClick:r,mode:"default","aria-label":"Close success dialog"})]})})}):null},ErrorDialog=({open:e,title:t,message:n,error:_,showRetry:a=!1,retryText:i="Retry",closable:r=!0,onClose:o,onRetry:s})=>{const c=__WEBPACK_EXTERNAL_MODULE_react_useRef__(null);return __WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{e&&c.current&&setTimeout(()=>{c.current?.focus()},100)},[e]),e?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Dialog__,{id:"error-dialog",header:t,onClose:r?o:void 0,onClickOutside:r?o:void 0,width:1,role:"alertdialog","aria-labelledby":"error-dialog-title","aria-describedby":"error-dialog-description",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:4,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:4,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{tone:"critical",padding:3,radius:2,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_ErrorOutlineIcon__,{})})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{id:"error-dialog-description",size:2,weight:"regular",children:n}),_&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{marginTop:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Code__,{size:1,language:"text",children:_.message}),_.stack&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{marginTop:2,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__("details",{children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__("summary",{children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"Stack trace"})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{marginTop:2,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Code__,{size:0,language:"text",children:_.stack})})]})})]})]})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[a&&s&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{ref:c,text:i,tone:"critical",onClick:s,mode:"default","aria-label":`${i} action`}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{ref:a?void 0:c,text:"Close",tone:"default",onClick:o,mode:a?"ghost":"default","aria-label":"Close error dialog"})]})]})})}):null},LocaleSelectionDialog=({open:e,title:t,message:n,availableLocales:_,selectedLocales:a,selectedDocuments:i=[],mode:r,allowMultiple:o=!0,required:s=!0,showCreationModeOption:c=!1,defaultCreationMode:l="draft",onConfirm:u,onCancel:d})=>{const[E,f]=__WEBPACK_EXTERNAL_MODULE_react_useState__(new Set(a)),[h,g]=__WEBPACK_EXTERNAL_MODULE_react_useState__(l),[p,A]=__WEBPACK_EXTERNAL_MODULE_react_useState__(""),[m,L]=__WEBPACK_EXTERNAL_MODULE_react_useState__(null),y=__WEBPACK_EXTERNAL_MODULE_react_useRef__(null),T=__WEBPACK_EXTERNAL_MODULE_react_useRef__(null);__WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{e&&(f(new Set(a)),g(l),A(""),L(null),setTimeout(()=>{y.current?.focus()},100))},[e,a,l]);const b=__WEBPACK_EXTERNAL_MODULE_react_useMemo__(()=>{if(!p.trim())return _.filter(e=>e.enabled);const e=p.toLowerCase();return _.filter(e=>e.enabled).filter(t=>t.code.toLowerCase().includes(e)||t.displayName.toLowerCase().includes(e))},[_,p]),D=e=>{L(null);const t=new Set(E);t.has(e)?t.delete(e):(o||t.clear(),t.add(e)),f(t)},C=()=>{s&&0===E.size?L("Please select at least one locale"):u(Array.from(E),c?h:void 0)};if(__WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{if(!e)return;const t=e=>{"Escape"===e.key?(e.preventDefault(),d()):"Enter"===e.key&&e.ctrlKey&&(e.preventDefault(),C())};return document.addEventListener("keydown",t),()=>{document.removeEventListener("keydown",t)}},[e,E,d]),!e)return null;const N=i.length||1,O=!s||E.size>0;return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Dialog__,{id:"locale-selection-dialog",header:t,onClose:d,onClickOutside:d,width:1,role:"dialog","aria-labelledby":"locale-selection-dialog-title","aria-describedby":"locale-selection-dialog-description",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:4,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:4,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{id:"locale-selection-dialog-description",size:2,weight:"regular",children:n}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"bulk"===r?`Translating ${N} document${1!==N?"s":""}`:"Translating 1 document"})]})})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_TextInput__,{ref:y,icon:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_SearchIcon__,placeholder:"Search locales by code or name...",value:p,onChange:e=>A(e.currentTarget.value),"aria-label":"Search locales"})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{border:!0,padding:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[o&&b.length>1&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{justify:"space-between",align:"center",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"semibold",children:[E.size," of ",b.length," selected"]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:"Select All",mode:"ghost",fontSize:1,padding:2,onClick:()=>{L(null);const e=new Set(b.map(e=>e.code));f(e)},disabled:E.size===b.length}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:"Clear All",mode:"ghost",fontSize:1,padding:2,onClick:()=>{L(null),f(new Set)},disabled:0===E.size})]})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{style:{maxHeight:"300px",overflowY:"auto"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:0===b.length?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,align:"center",children:p?"No locales match your search":"No locales available. Please configure locales first."})}):b.map(e=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,radius:2,shadow:1,style:{cursor:"pointer"},onClick:()=>D(e.code),role:"checkbox","aria-checked":E.has(e.code),tabIndex:0,onKeyDown:t=>{"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),D(e.code))},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Checkbox__,{checked:E.has(e.code),readOnly:!0,"aria-label":`Select ${e.displayName}`}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,flex:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:2,weight:"medium",children:e.displayName}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:e.code})]})]})},e.code))})})]})}),c&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{border:!0,padding:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"semibold",children:"Document Creation Mode"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"Choose whether to create translated documents as drafts or publish them immediately."}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,radius:2,tone:"draft"===h?"primary":"default",style:{cursor:"pointer"},onClick:()=>g("draft"),children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Radio__,{checked:"draft"===h,readOnly:!0,"aria-label":"Create as draft"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,flex:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:2,weight:"medium",children:"Draft"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"Create documents as drafts that need to be published manually"})]})]})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,radius:2,tone:"published"===h?"primary":"default",style:{cursor:"pointer"},onClick:()=>g("published"),children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Radio__,{checked:"published"===h,readOnly:!0,"aria-label":"Create as published"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,flex:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:2,weight:"medium",children:"Published"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"Create and publish documents immediately"})]})]})})]})]})}),m&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{tone:"critical",padding:3,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,style:{color:"var(--card-fg-color)"},children:m})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{ref:T,text:`Translate to ${E.size} locale${1!==E.size?"s":""}`,tone:"primary",onClick:C,disabled:!O||0===b.length,mode:"default","aria-label":"Confirm locale selection and start translation"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:"Cancel",tone:"default",onClick:d,mode:"ghost","aria-label":"Cancel locale selection"})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,align:"center",children:"Press Ctrl+Enter to confirm, Esc to cancel"})]})})})},DialogContext=__WEBPACK_EXTERNAL_MODULE_react_createContext__(null),useDialogService=()=>{const e=__WEBPACK_EXTERNAL_MODULE_react_useContext__(DialogContext);if(!e)throw new Error("useDialogService must be used within a DialogProvider");return e},DialogProvider=({children:e})=>{const[t,n]=__WEBPACK_EXTERNAL_MODULE_react_useState__(null),[_,a]=__WEBPACK_EXTERNAL_MODULE_react_useState__([]),i=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{a(e=>{if(0===e.length)return n(null),e;const[t,..._]=e;return n(t),_})},[]),r=__WEBPACK_EXTERNAL_MODULE_react_useCallback__((e,_)=>new Promise((i,r)=>{const o={id:`dialog-${Date.now()}-${Math.random()}`,type:e,options:_,resolve:i,reject:r};a(e=>t||0!==e.length?[...e,o]:(n(o),[]))}),[t]),o=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(e=>{t?.resolve&&t.resolve(e),i()},[t,i]),s=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(e=>r("confirmation",e),[r]),c=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(e=>r("localeSelection",e),[r]),l=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(e=>{r("success",e).catch(()=>{})},[r]),u=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(e=>r("error",e),[r]),d=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{t?.reject&&t.reject(new Error("Dialog closed")),_.forEach(e=>{e.reject&&e.reject(new Error("Dialog closed"))}),n(null),a([])},[t,_]),E=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{o(!0)},[o]),f=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{o(!1)},[o]),h=__WEBPACK_EXTERNAL_MODULE_react_useCallback__((e,t)=>{o({locales:e,creationMode:t})},[o]),g=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{o({locales:[]})},[o]),p=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{o(!0)},[o]),A=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{o(!1)},[o]),m=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{o(!0)},[o]),L={currentDialog:t,dialogQueue:_,showConfirmation:s,showLocaleSelection:c,showSuccess:l,showError:u,closeAll:d};return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(DialogContext.Provider,{value:L,children:[e,"confirmation"===t?.type&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(ConfirmationDialog,{open:!0,...t.options,onConfirm:E,onCancel:f}),"localeSelection"===t?.type&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(LocaleSelectionDialog,{open:!0,...t.options,onConfirm:h,onCancel:g}),"success"===t?.type&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(SuccessDialog,{open:!0,...t.options,onClose:p}),"error"===t?.type&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(ErrorDialog,{open:!0,...t.options,onClose:A,onRetry:t.options.showRetry?m:void 0})]})};class DialogService{constructor(){this.contextRef=null}static getInstance(){return DialogService.instance||(DialogService.instance=new DialogService),DialogService.instance}setContext(e){this.contextRef=e}async showConfirmation(e){if(!this.contextRef)throw new Error("DialogService not initialized. Ensure DialogProvider is mounted.");return this.contextRef.showConfirmation(e)}async showLocaleSelection(e){if(!this.contextRef)throw new Error("DialogService not initialized. Ensure DialogProvider is mounted.");return this.contextRef.showLocaleSelection(e)}showSuccess(e){if(!this.contextRef)throw new Error("DialogService not initialized. Ensure DialogProvider is mounted.");this.contextRef.showSuccess(e)}async showError(e){if(!this.contextRef)throw new Error("DialogService not initialized. Ensure DialogProvider is mounted.");return this.contextRef.showError(e)}closeAll(){if(!this.contextRef)throw new Error("DialogService not initialized. Ensure DialogProvider is mounted.");this.contextRef.closeAll()}}const dialogService=DialogService.getInstance();var OAuthErrorType;!function(e){e.INVALID_CONFIG="invalid_config",e.NETWORK_ERROR="network_error",e.AUTH_FAILED="auth_failed",e.STORAGE_ERROR="storage_error"}(OAuthErrorType||(OAuthErrorType={}));class OAuthError extends Error{constructor(e,t,n){super(t),this.name="OAuthError",this.type=e,this.details=n,Error.captureStackTrace&&Error.captureStackTrace(this,OAuthError)}getUserMessage(){switch(this.type){case OAuthErrorType.INVALID_CONFIG:return"Configuration is invalid. Please check your access token and project ID.";case OAuthErrorType.NETWORK_ERROR:return"Network error. Please check your connection.";case OAuthErrorType.AUTH_FAILED:return"Authentication failed. Please check your access token.";case OAuthErrorType.STORAGE_ERROR:return"Failed to save authentication data. Please try again.";default:return"An unexpected error occurred. Please try again."}}isRecoverable(){return[OAuthErrorType.NETWORK_ERROR,OAuthErrorType.STORAGE_ERROR].includes(this.type)}}class OAuthService{constructor(e){this.validateConfig(e),this.config=e,console.log("Easyling Authentication Service initialized",{projectId:e.projectId,hasAccessToken:!!e.accessToken})}validateConfig(e){const t=[];if(e.accessToken&&""!==e.accessToken.trim()||t.push("accessToken is required"),e.projectId&&""!==e.projectId.trim()||t.push("projectId is required"),t.length>0)throw new OAuthError(OAuthErrorType.INVALID_CONFIG,`Invalid configuration: ${t.join(", ")}`)}getAccessToken(){return this.config.accessToken}getProjectId(){return this.config.projectId}getConfig(){return{...this.config}}}const AUTH_DATA_STORAGE_KEY="sanity-translation-plugin:oauth:auth-data";class TokenStorage{async storeAuthData(e){try{if(!e.accessToken||!e.projectId)throw new OAuthError(OAuthErrorType.STORAGE_ERROR,"Invalid auth data: missing required fields (accessToken or projectId)");const t={...e,storedAt:Date.now()},n=JSON.stringify(t);localStorage.setItem(AUTH_DATA_STORAGE_KEY,n),console.log("Auth data stored successfully",{projectId:e.projectId})}catch(e){if(e instanceof OAuthError)throw e;throw new OAuthError(OAuthErrorType.STORAGE_ERROR,"Failed to store authentication data",e)}}async getAuthData(){try{const e=localStorage.getItem(AUTH_DATA_STORAGE_KEY);if(!e)return null;const t=JSON.parse(e);return t.accessToken&&t.projectId?t:(console.warn("Stored auth data is corrupted, clearing storage"),await this.clearAuthData(),null)}catch(e){if(e instanceof SyntaxError)return console.warn("Failed to parse stored auth data, clearing storage"),await this.clearAuthData(),null;throw new OAuthError(OAuthErrorType.STORAGE_ERROR,"Failed to retrieve authentication data",e)}}async clearAuthData(){try{localStorage.removeItem(AUTH_DATA_STORAGE_KEY),console.log("Auth data cleared successfully")}catch(e){throw new OAuthError(OAuthErrorType.STORAGE_ERROR,"Failed to clear authentication data",e)}}async isTokenExpired(){try{return!await this.getAuthData()}catch(e){return console.error("Error checking token:",e),!0}}async getValidAccessToken(){try{const e=await this.getAuthData();return e?e.accessToken:null}catch(e){return console.error("Error getting valid access token:",e),null}}}const VALID_TRANSITIONS={unauthenticated:["authenticated","error"],authenticated:["unauthenticated","error"],error:["unauthenticated","authenticated"]};class AuthStateManager{constructor(e){this.tokenStorage=e,this.subscribers=new Set,this.currentState={state:"unauthenticated"},console.log("AuthStateManager initialized")}isValidTransition(e,t){return e===t||VALID_TRANSITIONS[e].includes(t)}getState(){return{...this.currentState}}setState(e,t){if(!this.isValidTransition(this.currentState.state,e))throw new OAuthError(OAuthErrorType.INVALID_CONFIG,`Invalid state transition from ${this.currentState.state} to ${e}`);const n={state:e,...t};"error"===this.currentState.state&&"error"!==e&&delete n.error,"unauthenticated"===e&&(delete n.projectId,delete n.projectName,delete n.error),console.log("Auth state changed",{from:this.currentState.state,to:e,projectId:n.projectId}),this.currentState=n,this.notifySubscribers()}notifySubscribers(){const e=this.getState();this.subscribers.forEach(t=>{try{t(e)}catch(e){console.error("Error in state change subscriber:",e)}})}subscribe(e){this.subscribers.add(e);try{e(this.getState())}catch(e){console.error("Error in initial state callback:",e)}return()=>{this.subscribers.delete(e)}}async initialize(){try{console.log("Initializing auth state from storage");const e=await this.tokenStorage.getAuthData();if(!e)return console.log("No stored auth data found, remaining unauthenticated"),void this.setState("unauthenticated");if(await this.tokenStorage.isTokenExpired())return console.log("No valid token found"),void this.setState("unauthenticated");console.log("Valid token found, setting authenticated state"),this.setState("authenticated",{projectId:e.projectId,projectName:e.projectName})}catch(e){console.error("Error initializing auth state:",e),this.setState("error",{error:"Failed to initialize authentication state"})}}async logout(){try{console.log("Logging out"),await this.tokenStorage.clearAuthData(),this.setState("unauthenticated"),console.log("Logout complete")}catch(e){throw console.error("Error during logout:",e),this.setState("unauthenticated"),new OAuthError(OAuthErrorType.STORAGE_ERROR,"Failed to clear authentication data during logout",e)}}}var translation_request=__webpack_require__(230),translation_response=__webpack_require__(424);class TranslationService{constructor(e="http://localhost:8275/translate",t="application/json",n="application/json"){this.placeholderEndpoint=e,this.requestContentType=t,this.responseAcceptHeader=n}inferSanityType(e){if(null==e)return"undefined";if("object"==typeof e&&!Array.isArray(e)){const t=e;if(t._type)return t._type}return"string"==typeof e?"string":"number"==typeof e?"number":"boolean"==typeof e?"boolean":Array.isArray(e)?"array":"object"==typeof e?"object":"unknown"}setAuthToken(e,t){this.accessToken=e,this.projectId=t}clearAuth(){this.accessToken=void 0,this.projectId=void 0}setConfiguration(e,t,n){void 0!==e&&(this.placeholderEndpoint=e),void 0!==t&&(this.requestContentType=t),void 0!==n&&(this.responseAcceptHeader=n)}convertPayloadToProtobuf(e){const t={};for(const[n,_]of Object.entries(e.content.fields))if(_&&"object"==typeof _&&"value"in _){const e=_;let a=e.type;a||(console.warn(`Field '${n}' missing type in protobuf conversion, inferring from value`),a=this.inferSanityType(e.value)),t[n]={value:"string"==typeof e.value?e.value:JSON.stringify(e.value),dnt:e.dnt||!1,type:a,path:e.path||""}}else console.warn(`Field '${n}' not in TranslatableField format, wrapping with inferred type`),t[n]={value:"string"==typeof _?_:JSON.stringify(_),dnt:!1,type:this.inferSanityType(_),path:""};const n=translation_request.TranslationRequestPayload.create({content:{body:e.content.body,title:e.content.title,slug:e.content.slug,fields:t},project:this.projectId||"",format:e.format,metadata:{documentId:e.metadata.documentId,documentType:e.metadata.documentType,title:e.metadata.title,sourceLanguage:e.metadata.sourceLanguage||"",targetLanguage:e.metadata.targetLanguage||"",targetLocales:e.metadata.targetLocales||[]}});return translation_request.TranslationRequestPayload.encode(n).finish()}convertPayloadToProtobufJSON(e){const t={};for(const[n,_]of Object.entries(e.content.fields))if(_&&"object"==typeof _&&"value"in _){const e=_;t[n]={value:"string"==typeof e.value?e.value:JSON.stringify(e.value),dnt:e.dnt||!1,type:e.type||"unknown",path:e.path||""}}else t[n]={value:"string"==typeof _?_:JSON.stringify(_),dnt:!1,type:"unknown",path:""};const n=translation_request.TranslationRequestPayload.create({content:{body:e.content.body,title:e.content.title,slug:e.content.slug,fields:t},project:this.projectId||"",format:e.format,metadata:{documentId:e.metadata.documentId,documentType:e.metadata.documentType,title:e.metadata.title,sourceLanguage:e.metadata.sourceLanguage||"",targetLanguage:e.metadata.targetLanguage||"",targetLocales:e.metadata.targetLocales||[]}});return translation_request.TranslationRequestPayload.toJSON(n)}normalizeTranslatedFields(e){const t={};if(!e||"object"!=typeof e)return t;for(const[n,_]of Object.entries(e))t[n]=_&&"object"==typeof _&&"value"in _?{value:_.value,dnt:_.dnt||!1,type:_.type||this.inferSanityType(_.value)}:{value:_,dnt:!1,type:this.inferSanityType(_)};return t}convertProtobufBinaryToResponse(e){const t=translation_response.TranslationResponse.decode(e),n=t.translatedDocuments.map(e=>{const t={};if(e.fields&&"object"==typeof e.fields)for(const[n,_]of Object.entries(e.fields))if(_&&"object"==typeof _&&"value"in _){const e=_.value,a=_.type;try{const i=JSON.parse(e);t[n]={value:i,dnt:_.dnt||!1,type:a||this.inferSanityType(i)}}catch{t[n]={value:e,dnt:_.dnt||!1,type:a||this.inferSanityType(e)}}}return{body:e.body,title:e.title,slug:e.slug,fields:t,locale:e.locale}});return{success:t.success,translatedDocuments:n,sourceLocale:t.sourceLocale,error:t.error,requestId:t.requestId}}convertProtobufJSONToResponse(e){const t=translation_response.TranslationResponse.fromJSON(e),n=t.translatedDocuments.map((t,n)=>{const _=e.translatedDocuments?.[n],a={};if(t.fields&&"object"==typeof t.fields)for(const[e,n]of Object.entries(t.fields)){const t=_?.fields?.[e];if(n&&"object"==typeof n&&"value"in n){const _=n.value,i=n.type;if(""!==_&&void 0!==_||void 0===t||""===t)try{const t=JSON.parse(_);a[e]={value:t,dnt:n.dnt||!1,type:i||this.inferSanityType(t)}}catch{a[e]={value:_,dnt:n.dnt||!1,type:i||this.inferSanityType(_)}}else a[e]=t}else a[e]=void 0===t||n&&""!==n?n:t}if(_?.fields&&"object"==typeof _.fields)for(const[e,t]of Object.entries(_.fields))e in a||(a[e]=t);const i=this.normalizeTranslatedFields(a);return{body:t.body,title:t.title,slug:t.slug,fields:i,locale:t.locale}});return{success:t.success,translatedDocuments:n,sourceLocale:t.sourceLocale,error:t.error,requestId:t.requestId}}prepareTranslationRequest(e,t="document",n,_,a){if(!e||!e.documentId||!e.htmlContent)throw new Error("Invalid document content provided");const i={};if(e.fields)for(const[t,n]of Object.entries(e.fields))if(n&&"object"==typeof n&&"value"in n){const e=n;e.type||console.warn(`Field '${t}' missing type, inferring from value`),i[t]={...e,type:e.type||this.inferSanityType(e.value)}}else console.warn(`Field '${t}' not in TranslatableField format, converting`),i[t]={value:n,dnt:!1,type:this.inferSanityType(n)};console.log("[TranslationService] prepareTranslationRequest - titleFoundAtTopLevel:",{fromContent:e.titleFoundAtTopLevel,willUse:e.titleFoundAtTopLevel??!0});const r={content:{body:e.htmlContent,title:e.title||`Document ${e.documentId}`,slug:e.slug||"",fields:i},format:"html",metadata:{documentId:e.documentId,documentType:t,title:e.title||`Document ${e.documentId}`,...n&&{sourceLanguage:n},..._&&{targetLanguage:_},...a&&a.length>0&&{targetLocales:a},titleFoundAtTopLevel:e.titleFoundAtTopLevel??!0}};return{documentId:e.documentId,endpoint:this.placeholderEndpoint,payload:r}}async translateDocument(e,t="document",n,_,a){const i=this.prepareTranslationRequest(e,t,n,_,a);return this.sendTranslationRequest(i)}async sendTranslationRequest(e){try{this.logTranslationRequest(e);const t={"Content-Type":this.requestContentType,Accept:this.responseAcceptHeader};let n;if(this.accessToken&&(t.Authorization=`Bearer ${this.accessToken}`),"application/x-protobuf"===this.requestContentType)n=this.convertPayloadToProtobuf(e.payload);else{const t=this.convertPayloadToProtobufJSON(e.payload);n=JSON.stringify(t)}const _=await fetch(e.endpoint,{method:"POST",headers:t,body:n});if(!_.ok){if(401===_.status)return{success:!1,error:"Authentication failed. Please check your access token in the Easyling Configuration."};throw new Error(`HTTP error! status: ${_.status}`)}if("application/x-protobuf"===this.responseAcceptHeader){const e=await _.arrayBuffer(),t=new Uint8Array(e);return this.convertProtobufBinaryToResponse(t)}const a=await _.json();try{if(void 0!==a.success&&(a.translatedDocuments||a.error))return this.convertProtobufJSONToResponse(a)}catch(e){console.warn("Failed to parse response as protobuf format, falling back to legacy handling:",e)}if(a.translatedDocuments&&Array.isArray(a.translatedDocuments))return{success:!0,translatedDocuments:a.translatedDocuments.map(e=>({...e,fields:this.normalizeTranslatedFields(e.fields||{})})),sourceLocale:a.sourceLocale,requestId:a.requestId};if(a.translations){const e=[];for(const[t,n]of Object.entries(a.translations))if(n&&"object"==typeof n&&"content"in n){const _=n.content;e.push({..._,fields:this.normalizeTranslatedFields(_.fields||{}),locale:t})}return{success:!0,translatedDocuments:e,sourceLocale:a.sourceLocale,requestId:a.requestId,translations:a.translations}}if(a.translatedContent){const t=e.payload.metadata.targetLanguage||e.payload.metadata.targetLocales?.[0];return{success:!0,translatedDocuments:[{...a.translatedContent,fields:this.normalizeTranslatedFields(a.translatedContent.fields||{}),locale:t}],sourceLocale:e.payload.metadata.sourceLanguage,requestId:a.requestId,translatedContent:a.translatedContent}}if(a.content){const t=e.payload.metadata.targetLanguage||e.payload.metadata.targetLocales?.[0];return{success:!0,translatedDocuments:[{...a.content,fields:this.normalizeTranslatedFields(a.content.fields||{}),locale:t}],sourceLocale:e.payload.metadata.sourceLanguage,requestId:a.requestId,translatedContent:a.content}}throw new Error("Invalid response format: missing translatedDocuments, translations, or translatedContent")}catch(t){return console.error(`Translation request failed for document ${e.documentId}:`,t),{success:!1,error:t instanceof Error?t.message:"Unknown error occurred"}}}logTranslationRequest(e){console.log("Translation Request:",{timestamp:(new Date).toISOString(),documentId:e.documentId,endpoint:e.endpoint,payload:e.payload})}async processBulkTranslation(e,t="document",n,_,a){const i={totalDocuments:e.length,processedDocuments:0,failedDocuments:0,requests:[],responses:[]},r=a?.length||1;console.log(`Starting bulk translation for ${e.length} documents to ${r} locale(s)`);for(const r of e)try{const e=this.prepareTranslationRequest(r,t,n,_,a),o=await this.sendTranslationRequest(e);i.requests.push(e),i.responses.push(o),o.success?i.processedDocuments++:i.failedDocuments++}catch(e){console.error(`Failed to process document ${r.documentId}:`,e),i.failedDocuments++,i.responses.push({success:!1,error:e instanceof Error?e.message:"Unknown error occurred"})}return this.logBulkTranslationSummary(i),i}logBulkTranslationSummary(e){console.log("Bulk Translation Summary:",{timestamp:(new Date).toISOString(),totalDocuments:e.totalDocuments,processedDocuments:e.processedDocuments,failedDocuments:e.failedDocuments,successRate:e.totalDocuments>0?(e.processedDocuments/e.totalDocuments*100).toFixed(2)+"%":"0%"})}setEndpoint(e){this.placeholderEndpoint=e}getEndpoint(){return this.placeholderEndpoint}}const LEGACY_OAUTH_CONFIG_DOC_ID="sanity-translation-plugin.oauth-config";class OAuthConfigStorage{constructor(e){this.client=e,this.unifiedStorage=new UnifiedConfigStorage(e)}async load(){try{const e=await this.unifiedStorage.loadOAuth();if(e)return console.log("Loaded OAuth configuration from unified storage"),e;const t=await this.loadLegacy();return t?(console.log("Migrating OAuth configuration from legacy storage..."),await this.save(t),await this.deleteLegacy(),console.log("OAuth configuration migration complete"),t):(console.log("No OAuth configuration found"),null)}catch(e){throw console.error("Failed to load OAuth configuration:",e),e}}async save(e){try{await this.unifiedStorage.saveOAuth(e),console.log("Saved OAuth configuration to unified storage")}catch(e){throw console.error("Failed to save OAuth configuration:",e),e}}async delete(){try{await this.unifiedStorage.update({projectId:void 0,accessToken:void 0}),console.log("Deleted OAuth configuration")}catch(e){throw console.error("Failed to delete OAuth configuration:",e),e}}async loadLegacy(){try{const e=await this.client.fetch("*[_id == $id][0]",{id:LEGACY_OAUTH_CONFIG_DOC_ID});return e?{projectId:e.projectId,accessToken:e.accessToken}:null}catch(e){return console.error("Failed to load legacy OAuth configuration:",e),null}}async deleteLegacy(){try{await this.client.delete(LEGACY_OAUTH_CONFIG_DOC_ID),console.log("Deleted legacy OAuth configuration document")}catch(e){console.warn("Failed to delete legacy OAuth document:",e)}}}class OAuthServiceManager{constructor(e){this.oauthService=null,this.initialized=!1,this.client=e,this.tokenStorage=new TokenStorage,this.authStateManager=new AuthStateManager(this.tokenStorage),this.translationService=new TranslationService,this.oauthConfigStorage=new OAuthConfigStorage(e),this.unifiedConfigStorage=new UnifiedConfigStorage(e),console.log("OAuthServiceManager created")}static getInstance(e){return OAuthServiceManager.instance||(OAuthServiceManager.instance=new OAuthServiceManager(e)),OAuthServiceManager.instance}static resetInstance(){OAuthServiceManager.instance=null}async initialize(){if(this.initialized)console.log("OAuthServiceManager already initialized");else try{console.log("Initializing OAuth services..."),this.setupConfigListener();const e=await this.loadOAuthConfig();e?(this.oauthService=new OAuthService(e),console.log("OAuth service initialized with configuration")):console.log("No OAuth configuration found, OAuth features will be disabled"),await this.authStateManager.initialize(),console.log("Authentication state initialized"),await this.setupTranslationServiceAuth(),this.initialized=!0,console.log("OAuth services initialization complete")}catch(e){console.error("Error initializing OAuth services:",e),this.initialized=!0}}setupConfigListener(){this.client.listen('*[_id == "sanity-translation-plugin.config"]').subscribe(async e=>{console.log("Configuration updated, reloading services...");let t=null;e.result?(console.log("Using updated document from listener event"),t={projectId:e.result.projectId,accessToken:e.result.accessToken}):(console.log("Fetching updated configuration"),t=await this.loadOAuthConfig()),t&&t.accessToken&&t.projectId&&(console.log("Applying new OAuth configuration from update"),this.oauthService=new OAuthService(t),await this.saveAuth(t.accessToken,t.projectId)),await this.setupTranslationServiceEndpoint(),console.log("Services reloaded from configuration update")})}async loadOAuthConfig(){try{return await this.oauthConfigStorage.load()}catch(e){return console.error("Failed to load OAuth configuration:",e),null}}async setupTranslationServiceAuth(){try{await this.setupTranslationServiceEndpoint();const e=await this.loadOAuthConfig();if(e&&e.accessToken&&e.projectId)console.log("Found configuration in Sanity, syncing to localStorage"),await this.tokenStorage.storeAuthData({accessToken:e.accessToken,projectId:e.projectId,storedAt:Date.now()}),this.authStateManager.setState("authenticated",{projectId:e.projectId}),this.translationService.setAuthToken(e.accessToken,e.projectId),console.log("Translation service configured with Easyling authentication from Sanity config");else{const e=await this.tokenStorage.getAuthData();e?(this.translationService.setAuthToken(e.accessToken,e.projectId),console.log("Translation service configured with Easyling authentication from localStorage")):console.log("No authentication data available, translation service will use legacy mode")}await this.setupTranslationServiceEndpoint()}catch(e){console.error("Error setting up translation service authentication:",e),console.log("Translation service will fall back to legacy mode");try{await this.setupTranslationServiceEndpoint()}catch(e){console.error("Error setting up translation service endpoint:",e)}}}async setupTranslationServiceEndpoint(){try{const e=await this.unifiedConfigStorage.getTranslationEndpoint(),t=await this.unifiedConfigStorage.getRequestContentType(),n=await this.unifiedConfigStorage.getResponseAcceptHeader();this.translationService.setConfiguration(e,t,n),console.log("Translation service configured:",{endpoint:e,requestContentType:t,responseAcceptHeader:n})}catch(e){console.error("Error loading translation service configuration:",e)}}getOAuthService(){return this.oauthService}getTokenStorage(){return this.tokenStorage}getAuthStateManager(){return this.authStateManager}getTranslationService(){return this.translationService}getOAuthConfigStorage(){return this.oauthConfigStorage}isOAuthConfigured(){return null!==this.oauthService}getAuthenticationMode(){return this.isOAuthConfigured()?"oauth":"legacy"}async isOAuthAuthenticated(){return!!this.isOAuthConfigured()&&(!!await this.tokenStorage.getAuthData()&&!await this.tokenStorage.isTokenExpired())}async getAuthenticationStatus(){const e=this.getAuthenticationMode(),t=this.isOAuthConfigured(),n=await this.isOAuthAuthenticated();return{mode:e,isOAuthConfigured:t,isAuthenticated:n,requiresAuthentication:"oauth"===e&&!n}}isInitialized(){return this.initialized}async saveAuth(e,t){try{await this.tokenStorage.storeAuthData({accessToken:e,projectId:t,storedAt:Date.now()}),this.authStateManager.setState("authenticated",{projectId:t}),this.translationService.setAuthToken(e,t),console.log("Authentication saved successfully")}catch(e){throw console.error("Failed to save authentication:",e),this.authStateManager.setState("error",{error:e instanceof Error?e.message:"Failed to save authentication"}),e}}async logout(){this.translationService.clearAuth(),await this.authStateManager.logout(),console.log("Logged out successfully")}async refreshConfiguration(){try{console.log("Refreshing configuration from Sanity..."),await this.setupTranslationServiceEndpoint(),console.log("Configuration refreshed successfully")}catch(e){throw console.error("Error refreshing configuration:",e),e}}}OAuthServiceManager.instance=null;let isTranslating=!1;const translateDocumentAction=e=>{console.log("translateDocumentAction called with props:",{id:e.id,type:e.type,hasDraft:!!e.draft,hasPublished:!!e.published});const{draft:t,published:n,id:_,type:a,onComplete:i}=e,r=__WEBPACK_EXTERNAL_MODULE_sanity_useClient__({apiVersion:"2023-01-01"}),o=useDialogService(),s=t||n;if(!s)return console.log("no document found"),null;if(["EL_PluginConfiguration","EL_oauth-config","EL_translation-plugin-config"].includes(a))return console.log("Excluding translate action for plugin configuration type:",a),null;console.log("translateDocumentAction returning action for document:",_);const c={label:isTranslating?"Translating...":"Translate",icon:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_TranslateIcon__,onHandle:async()=>{if(!isTranslating){isTranslating=!0;try{const e=new ContentExtractor,t=new DocumentCreationService(r),n=new SanityLocaleStorageAdapter(r),_=new LocaleService(n),c=OAuthServiceManager.getInstance(r);await c.refreshConfiguration();const l=c.getTranslationService(),u=c.getAuthStateManager().getState();if(c.isOAuthConfigured()&&"authenticated"!==u.state)return void await o.showError({title:"Authentication Required",message:"You need to configure your Easyling credentials to use translation services.",error:new Error("Please go to the Easyling Configuration tool to enter your access token and project ID.")});await _.loadConfig();const d=_.getEnabledLocales();if(0===d.length)return void await o.showError({title:"No Locales Configured",message:"Please configure target locales before translating documents.",error:new Error("No translation locales have been configured. Please use the Locale Configuration tool to add target languages.")});const E=await e.extractStructuredContent(s);if(!E.htmlContent||0===E.htmlContent.trim().length)return void await o.showError({title:"Translation Failed",message:"No translatable content found in this document.",error:new Error("The document does not contain any translatable content.")});const f=await o.showLocaleSelection({title:"Select Target Locales",message:`Choose the languages to translate "${E.title}" into:`,availableLocales:d,selectedLocales:[],selectedDocuments:[s],mode:"single",allowMultiple:!0,required:!0,showCreationModeOption:!0,defaultCreationMode:"draft"});if(!f||!f.locales||0===f.locales.length)return;const h=f.locales,g=f.creationMode||"draft";if(!await o.showConfirmation({title:"Confirm Translation",message:`Translate "${E.title}" to ${h.length} locale(s)?`,details:`This will:\n• Send the translation request for ${h.length} locale(s)\n• Create new documents with translated content\n• Preserve the original document structure`,confirmText:"Translate & Create Documents",cancelText:"Cancel",tone:"primary"}))return;console.log(`Sending translation request for "${E.title}" to ${h.length} locale(s)...`),console.log("Selected locales:",h);const p=await l.translateDocument(E,a,void 0,void 0,h);if(!p.success)throw console.error(`Translation failed for "${E.title}":`,p.error),new Error(p.error||"Translation request failed");{console.log(`Translation completed successfully for "${E.title}"`),console.log("Translated documents:",p.translatedDocuments),p.requestId&&console.log("Request ID:",p.requestId);const e=p.translatedDocuments||(p.translatedContent?[p.translatedContent]:[]);if(e.length>0){console.log(`Creating ${e.length} new translated document(s)...`);const n=[];let _=0,a=0;for(let i=0;i<e.length;i++){const r=e[i],o=r.locale||h[i]||h[0];console.log(`Creating document ${i+1}/${e.length} for locale: ${o}`);const c={...p,translatedDocuments:[r],translatedContent:r},l=await t.createDocumentFromTranslation(s,c,{targetLanguage:o,createAsVariant:!0,parentDocumentId:s._id,creationMode:g,titleFoundAtTopLevel:E.titleFoundAtTopLevel,bodyFoundAtTopLevel:E.bodyFoundAtTopLevel,bodyFieldName:E.bodyFieldName});n.push(l),l.success?(_++,console.log(`Document ${i+1} created successfully with ID: ${l.documentId}`),console.log("New document structure:",l.document)):(a++,console.error(`Failed to create document ${i+1}:`,l.error))}const i=n.filter(e=>e.success&&e.slugFallback).map(e=>e.slugFallback),r=i.length>0?`\n\n⚠️ Slug fallbacks: ${i.length} document(s) had locale suffix added to slugs (translation did not produce different slugs):\n${i.map(e=>` • "${e.originalSlug}" → "${e.fallbackSlug}"`).join("\n")}`:"";if(_===e.length){const e=n.filter(e=>e.success).map(e=>e.documentId).join("\n");o.showSuccess({title:"Translation Completed",message:`Successfully translated "${E.title}" to ${_} locale(s)`,details:`Created ${_} new document(s):\n${e}\n\nTarget locale(s): ${h.join(", ")}${r}`})}else if(_>0){const t=n.filter(e=>e.success).map(e=>e.documentId).join("\n"),i=n.filter(e=>!e.success).map(e=>e.error).join("\n");await o.showError({title:"Partial Translation Success",message:`Created ${_} of ${e.length} documents. ${a} failed.`,error:new Error(`Successfully created:\n${t}\n\nErrors:\n${i}${r}`)})}else{const e=n.map(e=>e.error).join("\n");await o.showError({title:"Document Creation Failed",message:"Translation completed, but failed to create any documents.",error:new Error(e||"Unknown error during document creation")})}}}i&&i()}catch(e){console.error("Translation failed:",e);const t=e instanceof Error?e.message:"An unexpected error occurred";console.error(`Failed to translate document: ${t}`),await o.showError({title:"Translation Failed",message:"An error occurred during translation.",error:e instanceof Error?e:new Error(t),showRetry:!0})}finally{isTranslating=!1}}},tone:"primary",disabled:isTranslating};return console.log("translateDocumentAction returning action:",c),c},BulkTranslateTool=()=>{const e=__WEBPACK_EXTERNAL_MODULE_sanity_useClient__(),t=useDialogService(),[n,_]=__WEBPACK_EXTERNAL_MODULE_react_useState__({isProcessing:!1,isLoadingDocuments:!1,selectedDocuments:[],availableDocuments:{},selectedTypes:new Set,selectedDocumentIds:new Set,expandedTypes:new Set,summary:null,error:null,processingStatus:[],currentProcessingIndex:-1,createDocuments:!1,documentCreationResult:null,selectedLocales:null}),a=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(async()=>{_(e=>({...e,isLoadingDocuments:!0,error:null}));try{const t='*[!(_id in path("_.**")) && !(_type match "sanity.**") && !(_type match "EL_*")] | order(_createdAt desc) {\n _id,\n _type,\n _createdAt,\n _updatedAt,\n _rev,\n title,\n name,\n heading,\n label,\n ...\n }';console.log("Fetching documents from Sanity...");const n=await e.fetch(t);console.log(`Fetched ${n.length} documents`);const a={};n.forEach(e=>{a[e._type]||(a[e._type]=[]),a[e._type].push(e)}),Object.keys(a).forEach(e=>{console.log(`Type "${e}": ${a[e].length} documents`)}),_(e=>({...e,availableDocuments:a,isLoadingDocuments:!1}))}catch(e){console.error("Failed to fetch documents:",e),_(t=>({...t,error:e instanceof Error?e.message:"Failed to fetch documents",isLoadingDocuments:!1}))}},[e]);__WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{a()},[a]);const i=__WEBPACK_EXTERNAL_MODULE_react_useCallback__((e,t)=>{_(n=>{const _=new Set(n.selectedTypes),a=new Set(n.selectedDocumentIds);t?(_.add(e),n.availableDocuments[e]&&n.availableDocuments[e].forEach(e=>{a.add(e._id)})):(_.delete(e),n.availableDocuments[e]&&n.availableDocuments[e].forEach(e=>{a.delete(e._id)}));const i=Object.values(n.availableDocuments).flat().filter(e=>a.has(e._id)),r=i.map(e=>({documentId:e._id,title:l(e),status:"pending"}));return{...n,selectedTypes:_,selectedDocumentIds:a,selectedDocuments:i,processingStatus:r,summary:null,error:null,currentProcessingIndex:-1}})},[]),r=__WEBPACK_EXTERNAL_MODULE_react_useCallback__((e,t)=>{_(n=>{const _=new Set(n.selectedDocumentIds),a=new Set(n.selectedTypes);t?_.add(e._id):(_.delete(e._id),(n.availableDocuments[e._type]||[]).some(t=>t._id!==e._id&&_.has(t._id))||a.delete(e._type));const i=n.availableDocuments[e._type]||[];i.every(e=>_.has(e._id))&&i.length>0&&a.add(e._type);const r=Object.values(n.availableDocuments).flat().filter(e=>_.has(e._id)),o=r.map(e=>({documentId:e._id,title:l(e),status:"pending"}));return{...n,selectedTypes:a,selectedDocumentIds:_,selectedDocuments:r,processingStatus:o,summary:null,error:null,currentProcessingIndex:-1}})},[]),o=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(e=>{_(t=>{const n=new Set(t.expandedTypes);return n.has(e)?n.delete(e):n.add(e),{...t,expandedTypes:n}})},[]),s=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{const e=Object.keys(n.availableDocuments),t=Object.values(n.availableDocuments).flat(),a=new Set(t.map(e=>e._id)),i=t.map(e=>({documentId:e._id,title:l(e),status:"pending"}));_(n=>({...n,selectedTypes:new Set(e),selectedDocumentIds:a,selectedDocuments:t,processingStatus:i,summary:null,error:null,currentProcessingIndex:-1,documentCreationResult:null}))},[n.availableDocuments]),c=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(()=>{_(e=>({...e,selectedTypes:new Set,selectedDocumentIds:new Set,selectedDocuments:[],processingStatus:[],summary:null,error:null,currentProcessingIndex:-1,documentCreationResult:null}))},[]),l=e=>{const t=["title","name","heading","label"];for(const n of t)if(e[n]&&"string"==typeof e[n])return e[n];return`${e._type} (${e._id})`},u=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(async()=>{if(0!==n.selectedDocuments.length)try{const a=OAuthServiceManager.getInstance(e),i=a.getAuthStateManager().getState();if(a.isOAuthConfigured()&&"authenticated"!==i.state)return void await t.showError({title:"Authentication Required",message:"You need to configure your Easyling credentials to use translation services.",error:new Error("Please go to the Easyling Configuration tool to enter your access token and project ID.")});const r=new SanityLocaleStorageAdapter(e),o=new LocaleService(r);await o.loadConfig();const s=o.getEnabledLocales();if(0===s.length)return void await t.showError({title:"No Locales Configured",message:"Please configure target locales before translating documents.",error:new Error("No translation locales have been configured. Please use the Locale Configuration tool to add target languages.")});const c=await t.showLocaleSelection({title:"Select Target Locales",message:`Choose the languages to translate ${n.selectedDocuments.length} document${1!==n.selectedDocuments.length?"s":""} into:`,availableLocales:s,selectedLocales:[],selectedDocuments:n.selectedDocuments,mode:"bulk",allowMultiple:!0,required:!0,showCreationModeOption:!0,defaultCreationMode:"draft"});if(!c||!c.locales||0===c.locales.length)return;const l=c.locales,u=c.creationMode||"draft",d=await t.showConfirmation({title:"Confirm Bulk Translation",message:`Translate ${n.selectedDocuments.length} document${1!==n.selectedDocuments.length?"s":""} to ${l.length} locale${1!==l.length?"s":""}?`,details:`This will:\n• Send translation requests for all selected documents\n• Create new documents with translated content for successful translations\n• Preserve the original document structures\n\nTarget locales: ${l.join(", ")}`,confirmText:"Translate & Create Documents",cancelText:"Cancel",tone:"primary"});if(!d)return;_(e=>({...e,isProcessing:!0,error:null,summary:null,currentProcessingIndex:0,createDocuments:d,documentCreationResult:null,selectedLocales:l}));const E=new ContentExtractor,f=a.getTranslationService(),h=new DocumentCreationService(e);console.log(`Starting bulk translation for ${n.selectedDocuments.length} documents`);const g=(await E.extractBulkStructuredContent(n.selectedDocuments)).filter(e=>{const t=e.htmlContent&&e.htmlContent.trim().length>0;return t||_(t=>({...t,processingStatus:t.processingStatus.map(t=>t.documentId===e.documentId?{...t,status:"failed",error:"No translatable content found"}:t)})),t});if(0===g.length)throw new Error("No translatable content found in selected documents");console.log(`Processing ${g.length} documents with valid content`);const p={totalDocuments:n.selectedDocuments.length,processedDocuments:0,failedDocuments:0,requests:[],responses:[]};for(let e=0;e<g.length;e++){const t=g[e];_(n=>({...n,currentProcessingIndex:e,processingStatus:n.processingStatus.map(e=>e.documentId===t.documentId?{...e,status:"processing"}:e)}));try{const e=f.prepareTranslationRequest(t,void 0,void 0,void 0,l),n=await f.sendTranslationRequest(e);p.requests.push(e),p.responses.push(n),n.success?(p.processedDocuments++,_(e=>({...e,processingStatus:e.processingStatus.map(e=>e.documentId===t.documentId?{...e,status:"completed",response:n}:e)}))):(p.failedDocuments++,_(e=>({...e,processingStatus:e.processingStatus.map(e=>e.documentId===t.documentId?{...e,status:"failed",error:n.error,response:n}:e)}))),await new Promise(e=>setTimeout(e,500))}catch(e){console.error(`Failed to process document ${t.documentId}:`,e),p.failedDocuments++;const n=e instanceof Error?e.message:"Unknown error occurred";p.responses.push({success:!1,error:n}),_(e=>({...e,processingStatus:e.processingStatus.map(e=>e.documentId===t.documentId?{...e,status:"failed",error:n}:e)}))}}let A=null;if(d&&p.processedDocuments>0){console.log("Creating new documents from successful translations...");const e=p.responses.filter(e=>e.success),t=n.selectedDocuments.filter(e=>{const t=p.responses.findIndex((t,n)=>{const _=p.requests[n];return _&&_.documentId===e._id});return t>=0&&p.responses[t].success});t.length>0&&e.length>0&&(A=await h.createBulkDocumentsFromTranslations(t,e,{targetLanguage:"translated",createAsVariant:!0,creationMode:u}),console.log("Document Creation Summary:",{totalDocuments:A.totalDocuments,successfulCreations:A.successfulCreations,failedCreations:A.failedCreations,errors:A.errors,slugFallbacks:A.slugFallbacks}))}if(console.log("Bulk Translation Summary:",{timestamp:(new Date).toISOString(),totalDocuments:p.totalDocuments,processedDocuments:p.processedDocuments,failedDocuments:p.failedDocuments,successRate:p.totalDocuments>0?(p.processedDocuments/p.totalDocuments*100).toFixed(2)+"%":"0%"}),_(e=>({...e,summary:p,documentCreationResult:A,isProcessing:!1,currentProcessingIndex:-1})),console.log("Bulk translation completed:",p),d&&A){const e=A.slugFallbacks&&A.slugFallbacks.length>0?`\n\n⚠️ Slug fallbacks: ${A.slugFallbacks.length} document(s) had locale suffix added to slugs (translation did not produce different slugs).`:"";t.showSuccess({title:"Bulk Translation Completed",message:`Successfully translated ${p.processedDocuments} of ${p.totalDocuments} documents to ${l.length} locale${1!==l.length?"s":""}`,details:`Translations: ${p.processedDocuments}/${p.totalDocuments} successful\nDocuments created: ${A.successfulCreations}/${A.totalDocuments} successful\nTarget locales: ${l.join(", ")}${e}\n\nCheck the console for detailed results and new document structures.`})}else t.showSuccess({title:"Bulk Translation Completed",message:`Successfully translated ${p.processedDocuments} of ${p.totalDocuments} documents`,details:`Translations: ${p.processedDocuments}/${p.totalDocuments} successful\nTarget locales: ${l.join(", ")}\n\nTranslation responses have been logged to the console for verification.`})}catch(e){console.error("Bulk translation failed:",e),await t.showError({title:"Bulk Translation Failed",message:"An error occurred during bulk translation.",error:e instanceof Error?e:new Error("An unexpected error occurred")}),_(t=>({...t,error:e instanceof Error?e.message:"An unexpected error occurred",isProcessing:!1,currentProcessingIndex:-1}))}else await t.showError({title:"No Documents Selected",message:"Please select at least one document to translate.",error:new Error("No documents selected for translation")})},[n.selectedDocuments,e,t]);return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:4,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:4,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:2,weight:"semibold",children:"Bulk Document Translation"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"Select multiple documents to translate them in batch. Translation requests will be logged to the console for verification."}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Document Selection"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:"Refresh",icon:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_RefreshIcon__,onClick:a,disabled:n.isLoadingDocuments,mode:"ghost",fontSize:1}),n.selectedDocuments.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:"Clear All",tone:"critical",mode:"ghost",onClick:c,fontSize:1})]})]}),n.isLoadingDocuments?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Spinner__,{size:1}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"Loading documents..."})]}):0===Object.keys(n.availableDocuments).length?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:"No documents found"}):__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:["Selected: ",n.selectedDocuments.length," documents from ",n.selectedTypes.size," types"]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:"Select All Types",onClick:s,mode:"ghost",fontSize:1})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Document Types"}),Object.entries(n.availableDocuments).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>{const _=n.expandedTypes.has(e),a=t.filter(e=>n.selectedDocumentIds.has(e._id)).length,s=a>0&&a<t.length,c=a===t.length;return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Checkbox__,{checked:c,indeterminate:s,onChange:t=>i(e,t.currentTarget.checked)}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{icon:_?__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_ChevronDownIcon__:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_ChevronRightIcon__,mode:"ghost",onClick:()=>o(e),style:{minWidth:"auto",padding:"4px"}}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:e}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:[a,"/",t.length," selected • Latest: ",new Date(t[0]._createdAt).toLocaleDateString()]})]})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:a>0?"positive":"primary",fontSize:0,children:a>0?`${a}/${t.length}`:t.length})]}),_&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{style:{marginLeft:"32px"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,children:t.map(e=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,tone:"transparent",border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Checkbox__,{checked:n.selectedDocumentIds.has(e._id),onChange:t=>r(e,t.currentTarget.checked)}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:l(e)}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:[e._id," • ",new Date(e._createdAt).toLocaleDateString()]})]})]}),n.selectedDocumentIds.has(e._id)&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"positive",fontSize:0,children:"Selected"})]})},e._id))})})]})},e)})]}),n.selectedDocuments.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:["Selected Documents (",n.selectedDocuments.length,")"]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{style:{maxHeight:"200px",overflowY:"auto"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,children:[n.selectedDocuments.slice(0,10).map(e=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,tone:"primary",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:l(e)}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:[e._type," • ",new Date(e._createdAt).toLocaleDateString()]})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"primary",fontSize:0,children:e._type})]})},e._id)),n.selectedDocuments.length>10&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,style:{textAlign:"center",padding:"8px"},children:["... and ",n.selectedDocuments.length-10," more documents"]})]})})]})]})]})}),n.selectedDocuments.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Translation Action"}),n.selectedLocales&&n.selectedLocales.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,tone:"primary",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:["Target Locales: ",n.selectedLocales.join(", ")]})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{text:n.isProcessing?"Processing...":`Translate ${n.selectedDocuments.length} Documents`,icon:n.isProcessing?__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Spinner__:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_TranslateIcon__,onClick:u,tone:"primary",disabled:n.isProcessing})]})}),n.isProcessing&&n.processingStatus.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Translation Progress"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:["Overall Progress: ",n.currentProcessingIndex+1," of ",n.selectedDocuments.length]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,muted:!0,children:n.currentProcessingIndex>=0?`${Math.round((n.currentProcessingIndex+1)/n.selectedDocuments.length*100)}%`:"0%"})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{style:{width:"100%",height:"8px",backgroundColor:"#e0e0e0",borderRadius:"4px",overflow:"hidden"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{style:{width:(n.currentProcessingIndex>=0?(n.currentProcessingIndex+1)/n.selectedDocuments.length*100:0)+"%",height:"100%",backgroundColor:"#0066cc",transition:"width 0.3s ease"}})})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Document Status"}),n.processingStatus.map(e=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{flex:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:e.title}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:["ID: ",e.documentId]}),e.error&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,style:{color:"red"},children:["Error: ",e.error]})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:["pending"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"default",fontSize:0,children:"Pending"}),"processing"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"primary",fontSize:0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Spinner__,{size:0}),"Processing"]})}),"completed"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"positive",fontSize:0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CheckmarkIcon__,{}),"Completed"]})}),"failed"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"critical",fontSize:0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CloseIcon__,{}),"Failed"]})})]})]})},e.documentId))]})]})}),n.error&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,tone:"critical",border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:["Error: ",n.error]})}),n.summary&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,tone:0===n.summary.failedDocuments?"positive":"caution",border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[0===n.summary.failedDocuments?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CheckmarkIcon__,{style:{color:"green"}}):__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_WarningOutlineIcon__,{style:{color:"orange"}}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Translation Summary"})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Total Documents:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"primary",children:n.summary.totalDocuments})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Successfully Processed:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"positive",children:n.summary.processedDocuments})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Failed:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"critical",children:n.summary.failedDocuments})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Success Rate:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:0===n.summary.failedDocuments?"positive":"caution",children:n.summary.totalDocuments>0?`${(n.summary.processedDocuments/n.summary.totalDocuments*100).toFixed(1)}%`:"0%"})]})]}),n.processingStatus.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Detailed Results"}),n.processingStatus.map(e=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{flex:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:e.title}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:["ID: ",e.documentId]}),e.error&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,style:{color:"red"},children:["Error: ",e.error]})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:["pending"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"default",fontSize:0,children:"Pending"}),"processing"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"primary",fontSize:0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Spinner__,{size:0}),"Processing"]})}),"completed"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"positive",fontSize:0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CheckmarkIcon__,{}),"Completed"]})}),"failed"===e.status&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"critical",fontSize:0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CloseIcon__,{}),"Failed"]})})]})]})},e.documentId))]})]})}),n.documentCreationResult&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,tone:0===n.documentCreationResult.failedCreations?"positive":"caution",border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:3,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[0===n.documentCreationResult.failedCreations?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_CheckmarkIcon__,{style:{color:"green"}}):__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_WarningOutlineIcon__,{style:{color:"orange"}}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Document Creation Summary"})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Documents to Create:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"primary",children:n.documentCreationResult.totalDocuments})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Successfully Created:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"positive",children:n.documentCreationResult.successfulCreations})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Failed to Create:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"critical",children:n.documentCreationResult.failedCreations})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",justify:"space-between",children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:"Creation Success Rate:"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:0===n.documentCreationResult.failedCreations?"positive":"caution",children:n.documentCreationResult.totalDocuments>0?`${(n.documentCreationResult.successfulCreations/n.documentCreationResult.totalDocuments*100).toFixed(1)}%`:"0%"})]})]}),n.documentCreationResult.errors.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:"Creation Errors"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{style:{maxHeight:"150px",overflowY:"auto"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,children:n.documentCreationResult.errors.map((e,t)=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,tone:"critical",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,style:{color:"red"},children:e})},t))})})]}),n.documentCreationResult.slugFallbacks&&n.documentCreationResult.slugFallbacks.length>0&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_WarningOutlineIcon__,{style:{color:"#f5a623"}}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:["Slug Fallbacks Applied (",n.documentCreationResult.slugFallbacks.length,")"]})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:"The following documents had unchanged slugs from translation. Locale suffix was automatically applied to avoid conflicts."}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{style:{maxHeight:"200px",overflowY:"auto"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,children:n.documentCreationResult.slugFallbacks.map((e,t)=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:2,tone:"caution",border:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,weight:"medium",children:e.documentId}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"default",fontSize:0,children:e.originalSlug}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,children:"→"}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:"positive",fontSize:0,children:e.fallbackSlug})]}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:["Locale: ",e.locale]})]})},t))})})]})]})})]})})},bulkTranslateTool={name:"bulk-translate",title:"Bulk Translate",icon:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_TranslateIcon__,component:BulkTranslateTool},manageDNTFieldsAction=e=>{const{type:t,draft:n,published:_}=e,a=useDialogService(),i=n||_;if(["EL_PluginConfiguration","EL_oauth-config","EL_translation-plugin-config"].includes(t))return{label:"Manage Translation Fields",icon:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_BlockElementIcon__,disabled:!0,hidden:!0};const r=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(async()=>{if(!i)return void await a.showError({title:"No Document",message:"Cannot manage DNT fields: No document available"});const e=[],n=(t,_="")=>{if(t&&"object"==typeof t)for(const[a,i]of Object.entries(t)){if(a.startsWith("_"))continue;const t=_?`${_}.${a}`:a;"string"==typeof i||"number"==typeof i||Array.isArray(i)?e.push({path:t,value:i,type:typeof i}):i&&"object"==typeof i&&n(i,t)}};n(i);const _=getDNTStorage(),r=await _.getFieldsForType(t),o=e.map(e=>({...e,isDNT:r[e.path]||!1})),s=o.length>0?`Found ${o.length} translatable fields in this ${t} document. Use the field badges to toggle DNT status. Settings apply to ALL ${t} documents.`:"No translatable fields found in this document.";await a.showConfirmation({title:"Manage Translation Fields",message:s,confirmText:o.length>0?`Clear All DNT Settings for ${t}`:"OK",cancelText:"Close",tone:"primary"})&&o.length>0&&(await _.clearFieldsForType(t),await a.showSuccess({title:"DNT Settings Cleared",message:`All fields in ${t} documents are now marked as translatable.`}))},[i,t,a]);return{label:"Manage Translation Fields",icon:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_BlockElementIcon__,onHandle:r,disabled:!i}},PasswordInput=e=>{const{elementProps:t,onChange:n,value:_=""}=e,a=__WEBPACK_EXTERNAL_MODULE_react_default__.useCallback(e=>{const t=e.currentTarget.value;n(t?__WEBPACK_EXTERNAL_MODULE_sanity_set__(t):__WEBPACK_EXTERNAL_MODULE_sanity_unset__())},[n]);return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_TextInput__,{...t,type:"password",value:_,onChange:a})};function DNTFieldBadge(e){const{documentType:t,fieldPath:n,fieldTitle:_}=e,[a,i]=__WEBPACK_EXTERNAL_MODULE_react_useState__(!1),[r,o]=__WEBPACK_EXTERNAL_MODULE_react_useState__(!0);__WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{t&&n&&(async()=>{try{o(!0);const e=getDNTStorage(),_=await e.getFieldDNT(t,n);i(_)}catch(e){console.error("Failed to load DNT status:",e)}finally{o(!1)}})()},[t,n]);const s=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(async()=>{try{const e=getDNTStorage(),_=await e.toggleFieldDNT(t,n);i(_)}catch(e){console.error("Failed to toggle DNT status:",e)}},[t,n]);if(r)return null;const c=a?`This field will NOT be translated for ALL ${t} documents. Click to make it translatable.`:`This field will be translated. Click to mark as "Do Not Translate" for ALL ${t} documents.`;return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Tooltip__,{content:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{padding:2,direction:"column",gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__("div",{style:{fontWeight:"bold"},children:_||n}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__("div",{children:c})]}),placement:"top",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{mode:"bleed",padding:2,onClick:s,style:{minHeight:"auto"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:a?"critical":"positive",mode:a?"default":"outline",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(a?__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_BlockElementIcon__:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_TranslateIcon__,{}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__("span",{style:{fontSize:"0.75rem"},children:a?"DNT":"Translate"})]})})})})}function withDNTBadge(e){return function(t){const{documentId:n,documentType:_,...a}=t,i=a,r=i.path?.join(".")||"",o=i.schemaType?.title;return n&&r?__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(e,{...i}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__("div",{style:{marginTop:"0.25rem"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(DNTFieldBadge,{documentId:n,documentType:_||"document",fieldPath:r,fieldTitle:o})})]}):__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(e,{...i})}}function DNTFieldInput(e){const{renderDefault:t,schemaType:n,path:_}=e,a=__WEBPACK_EXTERNAL_MODULE_sanity_useFormValue__([]),i=a?._id,r=a?._type,o=_?.join(".")||"",s=n?.title||o;if(r&&["EL_PluginConfiguration","EL_oauth-config","EL_translation-plugin-config"].includes(r))return t(e);const[c,l]=__WEBPACK_EXTERNAL_MODULE_react_useState__(!1),[u,d]=__WEBPACK_EXTERNAL_MODULE_react_useState__(!0);__WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{r&&o?(async()=>{try{const e=getDNTStorage(),t=await e.getFieldDNT(r,o);l(t)}catch(e){console.error("Failed to load DNT status:",e)}finally{d(!1)}})():d(!1)},[r,o]);const E=__WEBPACK_EXTERNAL_MODULE_react_useCallback__(async()=>{if(r&&o)try{const e=getDNTStorage(),t=await e.toggleFieldDNT(r,o);l(t)}catch(e){console.error("Failed to toggle DNT:",e)}},[r,o]);if(!i||!o||o.startsWith("_"))return t(e);const f=c?`This field will NOT be translated for ALL ${r} documents. Click to make it translatable.`:`This field will be translated. Click to mark as "Do Not Translate" for ALL ${r} documents.`;return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:t(e)}),!u&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,paddingTop:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Tooltip__,{content:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{padding:2,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:1,children:f})}),placement:"top",children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Button__,{mode:"ghost",tone:c?"critical":"positive",padding:2,fontSize:1,onClick:E,icon:c?__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_BlockElementIcon__:__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_TranslateIcon__,text:c?"Do Not Translate":"Will Translate"})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{muted:!0,size:1,children:["Translation: ",__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__("strong",{children:c?"Disabled":"Enabled"})," for ",s]})]})]})}function DebugDNTBadge(e){const{renderDefault:t,schemaType:n,path:_,groupName:a,fieldsetName:i}=e,r=__WEBPACK_EXTERNAL_MODULE_sanity_useFormValue__([]),o=r?._type,s=_?.join(".")||"",c=_?.[_.length-1]?.toString()||s,l=n?.type?.name||n?.jsonType,[u,d]=__WEBPACK_EXTERNAL_MODULE_react_useState__(void 0),[E,f]=__WEBPACK_EXTERNAL_MODULE_react_useState__(!0),h=__WEBPACK_EXTERNAL_MODULE_react_useMemo__(()=>({fieldPath:s,fieldName:c,fieldType:l,groupName:a,fieldsetName:i}),[s,c,l,a,i]),g=__WEBPACK_EXTERNAL_MODULE_react_useMemo__(()=>computeDNTDefault(h),[h]);__WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{o&&s?(async()=>{try{const e=getDNTStorage(),t=await e.getFieldDNT(o,s),n=await e.getFieldsForType(o);d(s in n?t:void 0)}catch(e){console.error("Failed to load DNT status for debug badge:",e)}finally{f(!1)}})():f(!1)},[o,s]);const p=void 0!==u?u:g.shouldBeDNT,A=!isNonTranslatableType(l),m=p?"critical":"positive",L=p?"DNT":"TRANSLATE",y=[`Field: ${s}`,`Type: ${l||"unknown"}`,`Group: ${a||"none"}`,`Fieldset: ${i||"none"}`,"",`Default DNT: ${g.shouldBeDNT}`,`Reason: ${g.reason}`,"",`Stored Setting: ${void 0!==u?u:"none (using default)"}`,`Effective DNT: ${p}`,"","In Payload: "+(A?"Yes":"No (non-translatable type)"),A?`dnt field value: ${p}`:""].filter(Boolean);return __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Box__,{children:t(e)}),!E&&__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{tone:"transparent",padding:2,radius:2,style:{backgroundColor:"rgba(0,0,0,0.03)"},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Tooltip__,{content:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Card__,{padding:3,radius:2,shadow:1,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Stack__,{space:2,children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{weight:"bold",size:1,children:"DNT Debug Info"}),y.map((e,t)=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!e.startsWith("Effective")&&!e.startsWith("In Payload"),children:e||" "},t))]})}),placement:"top",portal:!0,children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Flex__,{align:"center",gap:1,style:{cursor:"help"},children:[__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_icons_947825be_InfoOutlineIcon__,{}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Badge__,{tone:A?m:"default",mode:A?"default":"outline",fontSize:0,children:A?L:"EXCLUDED"})]})}),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsxs__(__WEBPACK_EXTERNAL_MODULE__sanity_ui_ebc2fa3e_Text__,{size:0,muted:!0,children:[A?`Debug: Will ${p?"NOT ":""}be translated`:`Debug: Not in payload (${l} type)`,void 0===u&&A&&" (default)"]})]})})]})}const PluginConfigContext=__WEBPACK_EXTERNAL_MODULE_react_createContext__({debugMode:!1});function usePluginConfig(){return __WEBPACK_EXTERNAL_MODULE_react_useContext__(PluginConfigContext)}console.log("Loading sanity-translation-plugin...");const legacyOAuthConfigSchema={name:"EL_oauth-config",title:"Easyling Configuration (Legacy)",type:"document",hidden:!0,fields:[{name:"projectId",title:"Project ID",type:"string",description:"Your Easyling project ID",validation:e=>e.required()},{name:"accessToken",title:"Access Token",type:"string",description:"Long-lived access token provided by Easyling (hidden for security)",validation:e=>e.required(),components:{input:PasswordInput}},{name:"lastUpdated",title:"Last Updated",type:"datetime",readOnly:!0}]};function StudioLayout(e){const t=__WEBPACK_EXTERNAL_MODULE_sanity_useClient__({apiVersion:"2023-01-01"}),[n,_]=__WEBPACK_EXTERNAL_MODULE_react_useState__(!1),[a,i]=__WEBPACK_EXTERNAL_MODULE_react_useState__(!1);return __WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{(async()=>{try{const e=OAuthServiceManager.getInstance(t);await e.initialize(),DNTServiceManager.getInstance(t).initialize(t);const n=new UnifiedConfigStorage(t),a=await n.getDebugMode();i(a),console.log("Services initialized successfully, debug mode:",a),_(!0)}catch(e){console.error("Failed to initialize services:",e),_(!0)}})()},[t]),__WEBPACK_EXTERNAL_MODULE_react_useEffect__(()=>{if(!n)return;const e=t.listen('*[_id == "sanity-translation-plugin.config"][0]').subscribe(e=>{void 0!==e.result?.debugMode&&(i(e.result.debugMode),console.log("Debug mode updated:",e.result.debugMode))});return()=>e.unsubscribe()},[t,n]),__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(PluginConfigContext.Provider,{value:{debugMode:a},children:__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(DialogProvider,{children:e.renderDefault(e)})})}function FieldWrapper(e){const{debugMode:t}=usePluginConfig(),n=e.schemaType?.type?.name,_=e.schemaType?.name,a=e.path?.join("."),i=e.schemaType?.group,r=e.schemaType?.fieldset,o=["locale","_type","_id","_rev","_createdAt","_updatedAt"],s=o.includes(_||"")||o.some(e=>a?.includes(e)),c=n&&["date","datetime","image","file","reference","boolean","object","document","slug"].includes(n),l=n&&["string","text","number","url","email","array"].includes(n);if(s)return e.renderDefault(e);const u=l&&!c;return t?DebugDNTBadge({...e,groupName:i,fieldsetName:r}):u?DNTFieldInput(e):e.renderDefault(e)}const src_plugin=__WEBPACK_EXTERNAL_MODULE_sanity_definePlugin__({name:"sanity-translation-plugin",studio:{components:{layout:StudioLayout}},document:{actions:e=>{console.log("Document actions being registered, previous actions:",e.length);const t=[...e,translateDocumentAction,manageDNTFieldsAction];return console.log("New actions array length:",t.length),t}},form:{components:{field:e=>__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime_179142b8_jsx__(FieldWrapper,{...e})}},tools:e=>{console.log("Tools being registered, previous tools:",e.length);const t=[...e,bulkTranslateTool];return console.log("New tools array length:",t.length),t},schema:{types:[createPluginConfigSchema(PasswordInput),legacyLocaleConfigSchema,legacyOAuthConfigSchema]}});export{DNTFieldBadge,DNTFieldInput,DNTServiceManager,DNTStorageAdapter,LegacyDNTStorageAdapter,UnifiedConfigStorage,createPluginConfigSchema,src_plugin as default,getDNTStorage,pluginConfigSchema,withDNTBadge};