@countriesdb/widget 0.1.32 → 0.1.33

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,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).CountriesWidget=t()}(this,function(){"use strict";class e{static async fetchCountries(e){const{apiKey:t,backendUrl:n,shouldUseGeoIP:i=!0,isoCountryNames:a=!1,languageHeaders:o={}}=e,s=`${n}/api/countries`,r=[];i||r.push("no_geoip=1"),a&&r.push("country_name_source=iso");const l=r.length?`${s}?${r.join("&")}`:s;return this.fetchFromApi(l,t,o)}static async fetchSubdivisions(e){const{apiKey:t,backendUrl:n,countryCode:i,shouldUseGeoIP:a=!0,preferOfficial:o=!1,subdivisionRomanizationPreference:s,preferLocalVariant:r=!1,languageHeaders:l={}}=e;if(!i)return{data:[],language:null};const d=`${n}/api/countries/${i}/subdivisions`,u=[];a||u.push("no_geoip=1"),s&&u.push(`subdivision_romanization_preference=${encodeURIComponent(s)}`),r&&u.push("prefer_local_variant=1"),o&&u.push("prefer_official=1");const c=u.length?`${d}?${u.join("&")}`:d;return this.fetchFromApi(c,t,l)}static async fetchFromApi(e,t,n){try{const i=await fetch(e,{headers:{...n,"X-API-KEY":t,"Content-Type":"application/json"}});if(!i.ok){let e=`HTTP Error: ${i.status}`;try{const t=await i.json();t.error&&(e=t.error)}catch{}throw new Error(e)}const a=await i.json();return{data:a,language:i.headers.get("X-Selected-Language")||null}}catch(t){throw console.error(`Failed to fetch data from ${e}:`,t),t}}static getLanguageHeaders(e,t){const n={};return e&&(n["X-Forced-Language"]=e),t&&(n["X-Default-Language"]=t),"undefined"!=typeof navigator&&navigator.language?n["Accept-Language"]=navigator.language:n["Accept-Language"]="en",n}}function t(e,n,i,a,o,s,r){let l="";const d=e.map(e=>{let t=e[a]||e.name;const n=e.code?e.code.split("-")[0]:null;if(r&&"function"==typeof r){const i=r(e.code,t,o,n,e);if(!1===i)return null;null!=i&&(t=i)}return{...e,_displayName:t}}).filter(e=>null!==e),u=r&&"function"==typeof r&&o?o:void 0;d.sort((e,t)=>u?e._displayName.localeCompare(t._displayName,u,{sensitivity:"accent",ignorePunctuation:!1}):e._displayName.localeCompare(t._displayName));const c=n>0?i[n]??"&nbsp;".repeat(2*n):"",f=`subdivision-level-${n}`;for(const e of d){const d=e.children&&e.children.length>0,u=`${c}${e._displayName}`;d?(l+=s?`<option value="${e.code}" class="${f}">${u}</option>`:`<option disabled value="${e.code}" class="${f}">${u}</option>`,l+=t(e.children,n+1,i,a,o,s,r)):l+=`<option value="${e.code}" class="${f}">${u}</option>`}return l}function n(e,t="Not Applicable",n=!1){if(e.hasAttribute("multiple"))e.innerHTML="",void 0!==e.dataset.label&&delete e.dataset.label,void 0!==e.dataset.defaultValue&&delete e.dataset.defaultValue;else{const n=e.dataset.label,i=e.dataset.defaultValue,a=n||t,o=i??"";e.innerHTML=`<option value="${o}">${a}</option>`,void 0!==n&&(e.dataset.label=n),void 0!==i&&(e.dataset.defaultValue=i)}n&&(e.disabled=!0)}function i(e,t,n,i){let a=function(e,t,n){return t&&"function"==typeof t?e.map(e=>{const i=t(e.iso_alpha_2,e.name,n,e);if(!1===i)return null;const a=null!=i?i:e.name;return{...e,_displayName:a}}).filter(e=>null!==e):e.map(e=>({...e,_displayName:e.name}))}(t,i,n);i&&(a=function(e,t){const n=t;return[...e].sort((e,t)=>e._displayName.localeCompare(t._displayName,n,{sensitivity:"accent",ignorePunctuation:!1}))}(a,n));if(e.hasAttribute("multiple")||e.multiple)e.innerHTML="";else{const t=e.querySelector('option[value=""]')||(e.dataset.defaultValue?e.querySelector(`option[value="${e.dataset.defaultValue}"]`):null),n=e.dataset.defaultValue??"";e.innerHTML=t?t.outerHTML:`<option value="${n}">${e.dataset.label||"&mdash;"}</option>`}a.forEach(t=>{const n=document.createElement("option");n.value=t.iso_alpha_2,n.textContent=t._displayName,e.appendChild(n)})}function a(e,n,i,a,o,s){const r=function(e){const t={},n=[];return e.forEach(e=>{t[e.id]={...e,children:[]}}),e.forEach(e=>{const i=t[e.id];e.parent_id&&t[e.parent_id]?t[e.parent_id].children.push(i):n.push(i)}),n}(e),l={};for(let e=1;e<=10;e++){const t=`nested${e}Prefix`,i=n.dataset[t];if(void 0===i)break;l[`nested${e}Prefix`]=i}const d=function(e){const t={};for(let n=1;n<=10;n++){const i=e[`nested${n}Prefix`];if(void 0===i)break;t[n]=i}return t}(l),u=a?"full_name":"name";let c="";if(!n.hasAttribute("multiple")){const e=n.dataset.label||"&mdash;";c=`<option value="${n.dataset.defaultValue??""}">${e}</option>`}return c+=t(r,0,d,u,i,o,s),c}function o(e,t){const n=e.dataset._widgetTempPreselect,i=e.getAttribute("data-preselected")||e.dataset.preselected,a=null!=n&&""!==String(n).trim()?n:i;if(!a||"string"==typeof a&&""===a.trim())return;const o=String(a);if(e.hasAttribute("multiple")){const t=o.split(",").map(e=>e.trim()).filter(e=>""!==e);Array.from(e.options).forEach(e=>{e.selected=t.includes(e.value)})}else e.value=o;void 0!==e.dataset._widgetTempPreselect&&delete e.dataset._widgetTempPreselect}function s(e,t,n=!1){const i=t instanceof Error?t.message:t,a=e.dataset.defaultValue??"",o=i.startsWith("Error: ")?i:`Error: ${i}`;n?e.innerHTML=`<option value="${a}" disabled>${o}</option>`:e.innerHTML+=`<option value="${a}" disabled>${o}</option>`}function r(e,t={}){let n=[];n=e.multiple?Array.from(e.selectedOptions||[]).map(e=>e.value).filter(e=>""!==e):e.value?[e.value]:[];const i=new CustomEvent("countriesWidget:update",{bubbles:!0,detail:{value:e.value||"",selectedValues:n,name:e.dataset.name||null,country:e.dataset.country||null,isSubdivision:e.classList.contains("subdivision-selection"),...t}});e.dispatchEvent(i)}function l(e,t={}){const n=e.multiple?Array.from(e.selectedOptions||[]).map(e=>e.value).filter(e=>""!==e):e.value?[e.value]:[],i=new CustomEvent("countriesWidget:ready",{bubbles:!0,detail:{value:e.value||"",selectedValues:n,name:e.dataset.name||null,country:e.dataset.country||null,isSubdivision:e.classList.contains("subdivision-selection"),type:e.classList.contains("subdivision-selection")?"subdivision":"country",phase:"initial",...t}});e.dispatchEvent(i)}function d(e){return!0===e.isWidgetInitiated}async function u(e,t,n,i,a,o,s,l){if(!a&&!o)return;const d=document.querySelector(`.country-selection[data-name="${e.dataset.country}"]`);if(!d||d.multiple)return;const u=i.subdivisionsMap.get(e);if(!u)return;if(o&&e.multiple)return;const c=e.value;if(!c)return;const f=u.find(e=>e.code===c);if(f){if(a&&f.related_country_code){const e=f.related_country_code,n=f.related_subdivision_code,i=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);i&&n&&(i.dataset._widgetTempPreselect=n),d.value!==e?(d.value=e,r(d,{type:"country",reason:"regular"}),l?await l(d,t):i&&await s(i,t,e)):i&&n&&await s(i,t,e)}if(o&&f.is_subdivision_of){const e=f.is_subdivision_of.parent_country_code,n=f.is_subdivision_of.subdivision_code;if(n){const e=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);e&&!e.multiple&&(e.dataset._widgetTempPreselect=n)}if(d.value!==e)if(d.value=e,r(d,{type:"country",reason:"regular"}),l)await l(d,t);else{const n=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);n&&await s(n,t,e)}else if(n){const n=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);n&&!n.multiple&&await s(n,t,e)}}}}async function c(e,t,n,i,a,o){if(!a)return;const s=document.querySelector(`.country-selection[data-name="${e.dataset.country}"]`);if(!s||s.multiple)return;const l=i.subdivisionsMap.get(e);if(!l)return;const d=e.multiple?e.selectedOptions[0]?.value||null:e.value;if(!d)return;const u=l.find(e=>e.code===d);if(!u||!u.related_country_code)return;const c=u.related_country_code,f=u.related_subdivision_code,p=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);p&&f&&(p.dataset.preselected=f),s.value!==c?(s.value=c,r(s,{type:"country",reason:"regular"}),p&&await o(p,t,c)):p&&f&&await o(p,t,c)}async function f(e,t,n,i,a,o){if(!a)return;if(e.multiple)return;const s=document.querySelector(`.country-selection[data-name="${e.dataset.country}"]`);if(!s||s.multiple)return;const l=i.subdivisionsMap.get(e);if(!l)return;const d=e.value;if(!d)return;const u=l.find(e=>e.code===d);if(!u||!u.is_subdivision_of)return;const c=u.is_subdivision_of.parent_country_code,f=u.is_subdivision_of.subdivision_code;if(f){const e=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);e&&(e.dataset.preselected=f)}if(s.value!==c){s.value=c,r(s,{type:"country",reason:"follow"});const e=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);e&&await o(e,t,c)}else if(f){const e=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);e&&await o(e,t,c)}}async function p(e,t,n,i,a,o){if(!a||e.multiple)return;const s=i.countriesMap.get(e);if(!s)return;const l=e.value;if(!l)return;const d=s.find(e=>e.iso_alpha_2===l);if(!d||!d.is_subdivision_of)return;const u=d.is_subdivision_of.parent_country_code,c=d.is_subdivision_of.subdivision_code;if(e.value!==u){if(c){const t=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of t)e.multiple||(e.dataset.preselected=c)}e.value=u,r(e,{type:"country",reason:"regular"});const n=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of n)await o(e,t,u)}else if(c){const n=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of n)e.multiple||await o(e,t,u)}}async function m(t,i,d,c,f,p){const v=t.getAttribute("data-preselected")||t.dataset.preselected,g=c.subdivisionsMap.has(t);n(t,"&mdash;",!0),c.isInitializing.add(t);let w=p;if(w||(w=t.dataset.countryCode||""),w){let n=!1;try{const s=null==v,l=!!t.hasAttribute("data-prefer-official")||f.preferOfficialSubdivisions,p=e.getLanguageHeaders(f.forcedLanguage,f.defaultLanguage),g=await e.fetchSubdivisions({apiKey:i,backendUrl:d,countryCode:w,shouldUseGeoIP:s,preferOfficial:l,subdivisionRomanizationPreference:f.subdivisionRomanizationPreference,preferLocalVariant:f.preferLocalVariant,languageHeaders:p}),b=g.data,h=g.language||"en";if(c.subdivisionsMap.set(t,b),c.subdivisionsLanguageMap.set(t,h),b.length>0){t.disabled=!1;const e=t.hasAttribute("multiple"),l=e?void 0:t.dataset.label,p=e?void 0:t.dataset.defaultValue,v=t.value,g=t.dataset.defaultValue||"",w=v&&v!==g&&""!==v.trim();t.innerHTML=a(b,t,h,f.showSubdivisionType,f.allowParentSelection,f.subdivisionNameFilter),e||(void 0!==l&&(t.dataset.label=l),void 0!==p&&(t.dataset.defaultValue=p));let _=!1;if(w&&!e){Array.from(t.options).some(e=>e.value===v)&&(t.value=v,_=!0)}if(!_){if(void 0!==(t.getAttribute("data-preselected")||t.dataset.preselected||t.dataset._widgetTempPreselect))o(t),r(t,{type:"subdivision",reason:"preselected"}),n=!0,await u(t,i,0,c,f.followRelated,f.followUpward,(e,t,n)=>m(e,t,d,c,f,n),(e,t)=>y(e,t,d,c,f));else if(s){const e=b.find(e=>e.preselected);if(e){if(t.hasAttribute("multiple")){const n=Array.from(t.options).find(t=>t.value===e.code);n&&(n.selected=!0)}else t.value=e.code;r(t,{type:"subdivision",reason:"geoip"}),n=!0,await u(t,i,0,c,f.followRelated,f.followUpward,(e,t,n)=>m(e,t,d,c,f,n),(e,t)=>y(e,t,d,c,f))}}}}else t.disabled=!0}catch(e){console.error("Failed to fetch subdivisions:",e),s(t,e)}finally{c.isInitializing.delete(t),l(t,{type:"subdivision",phase:g?"reload":"initial"}),g&&!n&&r(t,{type:"subdivision",reason:"reload"})}}else if(!t.dataset.country||!document.querySelector(`.country-selection[data-name="${t.dataset.country}"]`)){const e=t.dataset.defaultValue??"";t.innerHTML+=`<option value="${e}" disabled>Error: No country select present</option>`}}function v(e,t){const n="undefined"!=typeof window&&window.CountriesDBConfig?window.CountriesDBConfig:null;return{followRelated:n?.followRelated||!1,followUpward:n?.followUpward||!1,showSubdivisionType:!1!==n?.showSubdivisionType,allowParentSelection:n?.allowParentSelection||!1,preferOfficialSubdivisions:n?.preferOfficialSubdivisions||!1,subdivisionRomanizationPreference:n?.subdivisionRomanizationPreference,preferLocalVariant:n?.preferLocalVariant||!1,forcedLanguage:n?.forcedLanguage,defaultLanguage:n?.defaultLanguage,subdivisionNameFilter:n?.subdivisionNameFilter}}async function y(e,t,n,i,a){if(e.hasAttribute("multiple"))return;const o=e.value,s=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of s)await m(e,t,n,i,a,o)}const g="__CountriesWidgetNS__";async function w(t={}){window[g]||(window[g]={initialized:!1,initPromise:null,version:0,eventHandlers:new WeakMap});const a=window[g];a.eventHandlers||(a.eventHandlers=new WeakMap);return!0===t.reload&&(a.initialized=!1,a.initPromise=null),a.initPromise=(async()=>{"loading"===document.readyState&&await new Promise(e=>{document.addEventListener("DOMContentLoaded",()=>e(),{once:!0})});const u=function(e){const t="undefined"!=typeof window&&window.CountriesDBConfig?window.CountriesDBConfig:null;let n=null;try{let e=null;if(document.currentScript&&document.currentScript instanceof HTMLScriptElement){const t=document.currentScript.src;t&&(t.includes("@countriesdb/widget")||t.includes("widget/dist/index.js"))&&(e=document.currentScript)}if(!e){e=Array.from(document.getElementsByTagName("script")).find(e=>e.src&&(e.src.includes("@countriesdb/widget")||e.src.includes("widget/dist/index.js")))||null}e&&e.src&&(n=new URL(e.src))}catch{}const i={publicKey:e.publicKey??t?.publicKey??n?.searchParams.get("public_key")??"",backendUrl:e.backendUrl??t?.backendUrl??n?.searchParams.get("backend_url")??"https://api.countriesdb.com",defaultLanguage:e.defaultLanguage??t?.defaultLanguage??n?.searchParams.get("default_language")??void 0,forcedLanguage:e.forcedLanguage??t?.forcedLanguage??n?.searchParams.get("forced_language")??void 0,showSubdivisionType:void 0!==e.showSubdivisionType?e.showSubdivisionType:void 0!==t?.showSubdivisionType?t.showSubdivisionType:b(n?.searchParams.get("show_subdivision_type")??"1"),followRelated:void 0!==e.followRelated?e.followRelated:void 0!==t?.followRelated?t.followRelated:b(n?.searchParams.get("follow_related")??"false"),followUpward:void 0!==e.followUpward?e.followUpward:void 0!==t?.followUpward?t.followUpward:b(n?.searchParams.get("follow_upward")??"false"),allowParentSelection:void 0!==e.allowParentSelection?e.allowParentSelection:void 0!==t?.allowParentSelection?t.allowParentSelection:b(n?.searchParams.get("allow_parent_selection")??"false"),isoCountryNames:void 0!==e.isoCountryNames?e.isoCountryNames:void 0!==t?.isoCountryNames?t.isoCountryNames:b(n?.searchParams.get("iso_country_names")??"false"),subdivisionRomanizationPreference:e.subdivisionRomanizationPreference||t?.subdivisionRomanizationPreference||n?.searchParams.get("subdivision_romanization_preference")||void 0,preferLocalVariant:void 0!==e.preferLocalVariant?e.preferLocalVariant:void 0!==t?.preferLocalVariant?t.preferLocalVariant:b(n?.searchParams.get("prefer_local_variant")??"false"),preferOfficialSubdivisions:void 0!==e.preferOfficialSubdivisions?e.preferOfficialSubdivisions:void 0!==t?.preferOfficialSubdivisions?t.preferOfficialSubdivisions:b(n?.searchParams.get("prefer_official")??"false"),countryNameFilter:e.countryNameFilter??t?.countryNameFilter,subdivisionNameFilter:e.subdivisionNameFilter??t?.subdivisionNameFilter,autoInit:void 0!==e.autoInit?e.autoInit:void 0!==t?.autoInit?t.autoInit:b(n?.searchParams.get("auto_init")??"true")};if(n){const e=n.searchParams.get("countryNameFilter");if(e&&"undefined"!=typeof window){const t=window[e];"function"==typeof t&&(i.countryNameFilter=t)}const t=n.searchParams.get("subdivisionNameFilter");if(t&&"undefined"!=typeof window){const e=window[t];"function"==typeof e&&(i.subdivisionNameFilter=e)}}return i}(t);if(function(){const e=Array.from(document.querySelectorAll(".country-selection"));for(const t of e)t.classList.contains("subdivision-selection")&&(t.classList.remove("subdivision-selection"),t.classList.add("subdivision-selection-removed"))}(),u.followRelated&&u.followUpward)return function(){const e="Error: Cannot enable both follow_related and follow_upward",t=Array.from(document.querySelectorAll(".country-selection"));for(const n of t)n.innerHTML=`<option value="${n.dataset.defaultValue??""}" disabled>${e}</option>`;const n=Array.from(document.querySelectorAll(".subdivision-selection"));for(const t of n)t.innerHTML=`<option value="${t.dataset.defaultValue??""}" disabled>${e}</option>`}(),!1;const g={countriesMap:new WeakMap,subdivisionsMap:new WeakMap,subdivisionsLanguageMap:new WeakMap,isInitializing:new Set,eventHandlers:a.eventHandlers},w=u.publicKey||"";await async function(e,t,i,a){const o=Array.from(document.querySelectorAll(".subdivision-selection"));for(const s of o){n(s,"&mdash;",!0);const o=s.dataset.country,l=o?document.querySelector(`.country-selection[data-name="${o}"]`):null;if(l&&l.hasAttribute("multiple")){const e=s.dataset.defaultValue??"";s.innerHTML=`<option value="${e}" disabled>Error: Cannot link to multi-select country. Use data-country-code instead.</option>`;continue}if(!o||!l)if(s.hasAttribute("data-country-code")&&s.dataset.countryCode)await m(s,e,t,i,a,s.dataset.countryCode);else{const e=s.dataset.defaultValue??"";s.innerHTML+=`<option value="${e}" disabled>Error: No country select present</option>`}const u=i.eventHandlers.get(s);u&&(u.update&&s.removeEventListener("change",u.update),u.followRelated&&s.removeEventListener("change",u.followRelated),u.followUpward&&s.removeEventListener("change",u.followUpward));const p={update:e=>{d(e)||r(s,{type:"subdivision",reason:"regular"})}};s.addEventListener("change",p.update),p.followRelated=async n=>{d(n)||await c(s,e,0,i,a.followRelated,(e,n,o)=>m(e,n,t,i,a,o))},s.addEventListener("change",p.followRelated),p.followUpward=async n=>{d(n)||await f(s,e,0,i,a.followUpward,(e,n,o)=>m(e,n,t,i,a,o))},s.addEventListener("change",p.followUpward),i.eventHandlers.set(s,p)}}(w,u.backendUrl,g,{followRelated:u.followRelated||!1,followUpward:u.followUpward||!1,showSubdivisionType:!1!==u.showSubdivisionType,allowParentSelection:u.allowParentSelection||!1,preferOfficialSubdivisions:u.preferOfficialSubdivisions||!1,subdivisionRomanizationPreference:u.subdivisionRomanizationPreference,preferLocalVariant:u.preferLocalVariant||!1,subdivisionNameFilter:u.subdivisionNameFilter});const h={followRelated:u.followRelated||!1,followUpward:u.followUpward||!1,showSubdivisionType:!1!==u.showSubdivisionType,allowParentSelection:u.allowParentSelection||!1,preferOfficialSubdivisions:u.preferOfficialSubdivisions||!1,subdivisionRomanizationPreference:u.subdivisionRomanizationPreference,preferLocalVariant:u.preferLocalVariant||!1,forcedLanguage:u.forcedLanguage,defaultLanguage:u.defaultLanguage,subdivisionNameFilter:u.subdivisionNameFilter};await async function(t,a,u,c){const f=Array.from(document.querySelectorAll(".country-selection")),g={};for(const w of f){const f=w.dataset.name;if(f&&g[f]){w.removeAttribute("data-name"),n(w,"&mdash;");const e=w.dataset.defaultValue??"";w.innerHTML+=`<option value="${e}" disabled>Error: Duplicate field</option>`;continue}f&&(g[f]=!0),n(w,"&mdash;"),u.isInitializing.add(w);let b=!1,h=!1;try{const n=null==(w.getAttribute("data-preselected")||w.dataset.preselected),s=e.getLanguageHeaders(c.forcedLanguage,c.defaultLanguage),l=await e.fetchCountries({apiKey:t,backendUrl:a,shouldUseGeoIP:n,isoCountryNames:c.isoCountryNames,languageHeaders:s}),f=l.data,g=l.language||"en";if(u.countriesMap.set(w,f),i(w,f,g,c.countryNameFilter),void 0!==(w.getAttribute("data-preselected")||w.dataset.preselected||w.dataset._widgetTempPreselect)&&(o(w),r(w,{type:"country",reason:"preselected"}),b=!0,w.value&&(w.value,w.dataset.defaultValue)),n){const e=f.find(e=>e.preselected);e&&(w.value=e.iso_alpha_2,r(w,{type:"country",reason:"geoip"}),b=!0)}!h&&w.value&&w.value!==(w.dataset.defaultValue||"")&&(h=!0);const _=u.eventHandlers.get(w);_?.countryChange&&w.removeEventListener("change",_.countryChange);const L=async e=>{if(d(e))return;r(w,{type:"country",reason:"regular"});const n=v(),i="undefined"!=typeof window&&window.CountriesDBConfig?window.CountriesDBConfig:c;await y(w,t,a,u,n);const o=w.value;if(!o)return;const s=(u.countriesMap.get(w)||[]).find(e=>e.iso_alpha_2===o);if(!s)return;const l=i?.followUpward||!1;l&&!w.multiple&&s.is_subdivision_of&&await p(w,t,0,u,l,(e,t,i)=>m(e,t,a,u,n,i))},S=u.eventHandlers.get(w)||{};S.countryChange=L,u.eventHandlers.set(w,S),w.addEventListener("change",L)}catch(e){if(console.error("Failed to fetch countries:",e),s(w,e),w.dataset.name){const t=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${w.dataset.name}"]`));for(const i of t)n(i,"&mdash;"),s(i,e)}}finally{u.isInitializing.delete(w),l(w,{type:"country",phase:"initial"}),b||r(w,{type:"country",reason:"regular"})}}}(w,u.backendUrl,g,{defaultLanguage:u.defaultLanguage,forcedLanguage:u.forcedLanguage,isoCountryNames:u.isoCountryNames||!1,followRelated:u.followRelated||!1,followUpward:u.followUpward||!1,countryNameFilter:u.countryNameFilter});const _=Array.from(document.querySelectorAll(".country-selection"));for(const e of _)e.value&&e.value!==(e.dataset.defaultValue||"")&&await y(e,w,u.backendUrl,g,h);return a.initialized=!0,!0})(),a.initPromise}function b(e){if(null==e)return!1;const t=String(e).trim().toLowerCase();return!("0"===t||"false"===t)}return"undefined"!=typeof window&&(window.CountriesWidgetLoad=w,function e(){if("loading"===document.readyState)return void document.addEventListener("DOMContentLoaded",e,{once:!0});let t=null;if(document.currentScript&&document.currentScript instanceof HTMLScriptElement){const e=document.currentScript.src;e&&(e.includes("@countriesdb/widget")||e.includes("widget/dist/index.js"))&&(t=document.currentScript)}if(!t){t=Array.from(document.getElementsByTagName("script")).find(e=>e.src&&(e.src.includes("@countriesdb/widget")||e.src.includes("widget/dist/index.js")))||null}let n=!0;const i="undefined"!=typeof window&&window.CountriesDBConfig||null;if(i&&void 0!==i.autoInit)n=!!i.autoInit;else if(t&&t.src)try{const e=new URL(t.src).searchParams.get("auto_init");n=null===e||"true"===e||"1"===e}catch{n=!0}n&&setTimeout(()=>{w().catch(console.error)},0)}()),w});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).CountriesWidget=t()}(this,function(){"use strict";class e{static async fetchCountries(e){const{apiKey:t,backendUrl:a,shouldUseGeoIP:i=!0,isoCountryNames:n=!1,languageHeaders:o={}}=e,s=`${a}/api/countries`,r=[];i||r.push("no_geoip=1"),n&&r.push("country_name_source=iso");const l=r.length?`${s}?${r.join("&")}`:s;return this.fetchFromApi(l,t,o)}static async fetchSubdivisions(e){const{apiKey:t,backendUrl:a,countryCode:i,shouldUseGeoIP:n=!0,preferOfficial:o=!1,subdivisionRomanizationPreference:s,preferLocalVariant:r=!1,languageHeaders:l={}}=e;if(!i)return{data:[],language:null};const d=`${a}/api/countries/${i}/subdivisions`,u=[];n||u.push("no_geoip=1"),s&&u.push(`subdivision_romanization_preference=${encodeURIComponent(s)}`),r&&u.push("prefer_local_variant=1"),o&&u.push("prefer_official=1");const c=u.length?`${d}?${u.join("&")}`:d;return this.fetchFromApi(c,t,l)}static async fetchFromApi(e,t,a){try{const i=await fetch(e,{headers:{...a,"X-API-KEY":t,"Content-Type":"application/json"}});if(!i.ok){let e=`HTTP Error: ${i.status}`;try{const t=await i.json();t.error&&(e=t.error)}catch{}throw new Error(e)}const n=await i.json();return{data:n,language:i.headers.get("X-Selected-Language")||null}}catch(t){throw console.error(`Failed to fetch data from ${e}:`,t),t}}static getLanguageHeaders(e,t){const a={};return e&&(a["X-Forced-Language"]=e),t&&(a["X-Default-Language"]=t),"undefined"!=typeof navigator&&navigator.language?a["Accept-Language"]=navigator.language:a["Accept-Language"]="en",a}}function t(e,a,i,n,o,s,r){let l="";const d=e.map(e=>{let t=e[n]||e.name;const a=e.code?e.code.split("-")[0]:null;if(r&&"function"==typeof r){const i=r(e.code,t,o,a,e);if(!1===i)return null;null!=i&&(t=i)}return{...e,_displayName:t}}).filter(e=>null!==e),u=r&&"function"==typeof r&&o?o:void 0;d.sort((e,t)=>u?e._displayName.localeCompare(t._displayName,u,{sensitivity:"accent",ignorePunctuation:!1}):e._displayName.localeCompare(t._displayName));const c=a>0?i[a]??"&nbsp;".repeat(2*a):"",f=`subdivision-level-${a}`;for(const e of d){const d=e.children&&e.children.length>0,u=`${c}${e._displayName}`;d?(l+=s?`<option value="${e.code}" class="${f}">${u}</option>`:`<option disabled value="${e.code}" class="${f}">${u}</option>`,l+=t(e.children,a+1,i,n,o,s,r)):l+=`<option value="${e.code}" class="${f}">${u}</option>`}return l}function a(e,t="Not Applicable",a=!1){if(e.hasAttribute("multiple"))e.innerHTML="",void 0!==e.dataset.label&&delete e.dataset.label,void 0!==e.dataset.defaultValue&&delete e.dataset.defaultValue;else{const a=e.dataset.label,i=e.dataset.defaultValue,n=a||t,o=i??"";e.innerHTML=`<option value="${o}">${n}</option>`,void 0!==a&&(e.dataset.label=a),void 0!==i&&(e.dataset.defaultValue=i)}a&&(e.disabled=!0)}function i(e,t,a,i){let n=function(e,t,a){return t&&"function"==typeof t?e.map(e=>{const i=t(e.iso_alpha_2,e.name,a,e);if(!1===i)return null;const n=null!=i?i:e.name;return{...e,_displayName:n}}).filter(e=>null!==e):e.map(e=>({...e,_displayName:e.name}))}(t,i,a);i&&(n=function(e,t){const a=t;return[...e].sort((e,t)=>e._displayName.localeCompare(t._displayName,a,{sensitivity:"accent",ignorePunctuation:!1}))}(n,a));if(e.hasAttribute("multiple")||e.multiple)e.innerHTML="";else{const t=e.querySelector('option[value=""]')||(e.dataset.defaultValue?e.querySelector(`option[value="${e.dataset.defaultValue}"]`):null),a=e.dataset.defaultValue??"";e.innerHTML=t?t.outerHTML:`<option value="${a}">${e.dataset.label||"&mdash;"}</option>`}n.forEach(t=>{const a=document.createElement("option");a.value=t.iso_alpha_2,a.textContent=t._displayName,e.appendChild(a)})}function n(e,a,i,n,o,s){const r=function(e){const t={},a=[];return e.forEach(e=>{t[e.id]={...e,children:[]}}),e.forEach(e=>{const i=t[e.id];e.parent_id&&t[e.parent_id]?t[e.parent_id].children.push(i):a.push(i)}),a}(e),l={};for(let e=1;e<=10;e++){const t=`nested${e}Prefix`,i=a.dataset[t];if(void 0===i)break;l[`nested${e}Prefix`]=i}const d=function(e){const t={};for(let a=1;a<=10;a++){const i=e[`nested${a}Prefix`];if(void 0===i)break;t[a]=i}return t}(l),u=n?"full_name":"name";let c="";if(!a.hasAttribute("multiple")){const e=a.dataset.label||"&mdash;";c=`<option value="${a.dataset.defaultValue??""}">${e}</option>`}return c+=t(r,0,d,u,i,o,s),c}function o(e,t){const a=e.dataset._widgetTempPreselect,i=e.getAttribute("data-preselected")||e.dataset.preselected,n=null!=a&&""!==String(a).trim()?a:i;if(!n||"string"==typeof n&&""===n.trim())return;const o=String(n);if(e.hasAttribute("multiple")){const t=o.split(",").map(e=>e.trim()).filter(e=>""!==e);Array.from(e.options).forEach(e=>{e.selected=t.includes(e.value)})}else e.value=o;void 0!==e.dataset._widgetTempPreselect&&delete e.dataset._widgetTempPreselect}function s(e,t,a=!1){const i=t instanceof Error?t.message:t,n=e.dataset.defaultValue??"",o=i.startsWith("Error: ")?i:`Error: ${i}`;a?e.innerHTML=`<option value="${n}" disabled>${o}</option>`:e.innerHTML+=`<option value="${n}" disabled>${o}</option>`}function r(e,t={}){let a=[];a=e.multiple?Array.from(e.selectedOptions||[]).map(e=>e.value).filter(e=>""!==e):e.value?[e.value]:[];const i=new CustomEvent("countriesWidget:update",{bubbles:!0,detail:{value:e.value||"",selectedValues:a,name:e.dataset.name||null,country:e.dataset.country||null,isSubdivision:e.classList.contains("subdivision-selection"),...t}});e.dispatchEvent(i)}function l(e,t={}){const a=e.multiple?Array.from(e.selectedOptions||[]).map(e=>e.value).filter(e=>""!==e):e.value?[e.value]:[],i=new CustomEvent("countriesWidget:ready",{bubbles:!0,detail:{value:e.value||"",selectedValues:a,name:e.dataset.name||null,country:e.dataset.country||null,isSubdivision:e.classList.contains("subdivision-selection"),type:e.classList.contains("subdivision-selection")?"subdivision":"country",phase:"initial",...t}});e.dispatchEvent(i)}function d(e){return!0===e.isWidgetInitiated}async function u(e,t,a,i,n,o,s,l){if(!n&&!o)return;const d=document.querySelector(`.country-selection[data-name="${e.dataset.country}"]`);if(!d||d.multiple)return;const u=i.subdivisionsMap.get(e);if(!u)return;if(o&&e.multiple)return;const c=e.value;if(!c)return;const f=u.find(e=>e.code===c);if(f){if(n&&f.related_country_code){const e=f.related_country_code,a=f.related_subdivision_code,i=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);i&&a&&(i.dataset._widgetTempPreselect=a),d.value!==e?(d.value=e,r(d,{type:"country",reason:"regular"}),l?await l(d,t):i&&await s(i,t,e)):i&&a&&await s(i,t,e)}if(o&&f.is_subdivision_of){const e=f.is_subdivision_of.parent_country_code,a=f.is_subdivision_of.subdivision_code;if(a){const e=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);e&&!e.multiple&&(e.dataset._widgetTempPreselect=a)}if(d.value!==e)if(d.value=e,r(d,{type:"country",reason:"regular"}),l)await l(d,t);else{const a=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);a&&await s(a,t,e)}else if(a){const a=document.querySelector(`.subdivision-selection[data-country="${d.dataset.name}"]`);a&&!a.multiple&&await s(a,t,e)}}}}async function c(e,t,a,i,n,o){if(!n)return;const s=document.querySelector(`.country-selection[data-name="${e.dataset.country}"]`);if(!s||s.multiple)return;const l=i.subdivisionsMap.get(e);if(!l)return;const d=e.multiple?e.selectedOptions[0]?.value||null:e.value;if(!d)return;const u=l.find(e=>e.code===d);if(!u||!u.related_country_code)return;const c=u.related_country_code,f=u.related_subdivision_code,p=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);p&&f&&(p.dataset.preselected=f),s.value!==c?(s.value=c,r(s,{type:"country",reason:"regular"}),p&&await o(p,t,c)):p&&f&&await o(p,t,c)}async function f(e,t,a,i,n,o){if(!n)return;if(e.multiple)return;const s=document.querySelector(`.country-selection[data-name="${e.dataset.country}"]`);if(!s||s.multiple)return;const l=i.subdivisionsMap.get(e);if(!l)return;const d=e.value;if(!d)return;const u=l.find(e=>e.code===d);if(!u||!u.is_subdivision_of)return;const c=u.is_subdivision_of.parent_country_code,f=u.is_subdivision_of.subdivision_code;if(f){const e=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);e&&(e.dataset.preselected=f)}if(s.value!==c){s.value=c,r(s,{type:"country",reason:"follow"});const e=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);e&&await o(e,t,c)}else if(f){const e=document.querySelector(`.subdivision-selection[data-country="${s.dataset.name}"]`);e&&await o(e,t,c)}}async function p(e,t,a,i,n,o){if(!n||e.multiple)return;const s=i.countriesMap.get(e);if(!s)return;const l=e.value;if(!l)return;const d=s.find(e=>e.iso_alpha_2===l);if(!d||!d.is_subdivision_of)return;const u=d.is_subdivision_of.parent_country_code,c=d.is_subdivision_of.subdivision_code;if(e.value!==u){if(c){const t=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of t)e.multiple||(e.dataset.preselected=c)}e.value=u,r(e,{type:"country",reason:"regular"});const a=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of a)await o(e,t,u)}else if(c){const a=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of a)e.multiple||await o(e,t,u)}}async function m(t,i,d,c,f,p){const v=t.getAttribute("data-preselected")||t.dataset.preselected,g=c.subdivisionsMap.has(t);a(t,"&mdash;",!0),c.isInitializing.add(t);let w=p;if(w||(w=t.dataset.countryCode||""),w){let a=!1;try{const s=null==v,l=!!t.hasAttribute("data-prefer-official")||f.preferOfficialSubdivisions,p=e.getLanguageHeaders(f.forcedLanguage,f.defaultLanguage),g=await e.fetchSubdivisions({apiKey:i,backendUrl:d,countryCode:w,shouldUseGeoIP:s,preferOfficial:l,subdivisionRomanizationPreference:f.subdivisionRomanizationPreference,preferLocalVariant:f.preferLocalVariant,languageHeaders:p}),b=g.data,h=g.language||"en";if(c.subdivisionsMap.set(t,b),c.subdivisionsLanguageMap.set(t,h),b.length>0){t.disabled=!1;const e=t.hasAttribute("multiple"),l=e?void 0:t.dataset.label,p=e?void 0:t.dataset.defaultValue,v=t.value,g=t.dataset.defaultValue||"",w=v&&v!==g&&""!==v.trim();t.innerHTML=n(b,t,h,f.showSubdivisionType,f.allowParentSelection,f.subdivisionNameFilter),e||(void 0!==l&&(t.dataset.label=l),void 0!==p&&(t.dataset.defaultValue=p));let _=!1;if(w&&!e){Array.from(t.options).some(e=>e.value===v)&&(t.value=v,_=!0)}if(!_){if(void 0!==(t.getAttribute("data-preselected")||t.dataset.preselected||t.dataset._widgetTempPreselect))o(t),r(t,{type:"subdivision",reason:"preselected"}),a=!0,await u(t,i,0,c,f.followRelated,f.followUpward,(e,t,a)=>m(e,t,d,c,f,a),(e,t)=>y(e,t,d,c,f));else if(s){const e=b.find(e=>e.preselected);if(e){if(t.hasAttribute("multiple")){const a=Array.from(t.options).find(t=>t.value===e.code);a&&(a.selected=!0)}else t.value=e.code;r(t,{type:"subdivision",reason:"geoip"}),a=!0,await u(t,i,0,c,f.followRelated,f.followUpward,(e,t,a)=>m(e,t,d,c,f,a),(e,t)=>y(e,t,d,c,f))}}}}else t.disabled=!0}catch(e){console.error("Failed to fetch subdivisions:",e),s(t,e)}finally{c.isInitializing.delete(t),l(t,{type:"subdivision",phase:g?"reload":"initial"}),g&&!a&&r(t,{type:"subdivision",reason:"reload"})}}else if(!t.dataset.country||!document.querySelector(`.country-selection[data-name="${t.dataset.country}"]`)){const e=t.dataset.defaultValue??"";t.innerHTML+=`<option value="${e}" disabled>Error: No country select present</option>`}}function v(e,t){const a="undefined"!=typeof window&&window.CountriesDBConfig?window.CountriesDBConfig:null;let i=null;try{const e=Array.from(document.getElementsByTagName("script")).find(e=>e.src&&(e.src.includes("@countriesdb/widget")||e.src.includes("widget/dist/index.js")))||null;e&&e.src&&(i=new URL(e.src))}catch{}const n=e=>{if(null==e)return!1;const t=String(e).trim().toLowerCase();return!("0"===t||"false"===t)};return{followRelated:void 0!==a?.followRelated?a.followRelated:n(i?.searchParams.get("follow_related")??"false"),followUpward:void 0!==a?.followUpward?a.followUpward:n(i?.searchParams.get("follow_upward")??"false"),showSubdivisionType:void 0!==a?.showSubdivisionType?a.showSubdivisionType:n(i?.searchParams.get("show_subdivision_type")??"1"),allowParentSelection:void 0!==a?.allowParentSelection?a.allowParentSelection:n(i?.searchParams.get("allow_parent_selection")??"false"),preferOfficialSubdivisions:void 0!==a?.preferOfficialSubdivisions?a.preferOfficialSubdivisions:n(i?.searchParams.get("prefer_official")??"false"),subdivisionRomanizationPreference:a?.subdivisionRomanizationPreference||i?.searchParams.get("subdivision_romanization_preference")||void 0,preferLocalVariant:void 0!==a?.preferLocalVariant?a.preferLocalVariant:n(i?.searchParams.get("prefer_local_variant")??"false"),forcedLanguage:a?.forcedLanguage||i?.searchParams.get("forced_language")||void 0,defaultLanguage:a?.defaultLanguage||i?.searchParams.get("default_language")||void 0,subdivisionNameFilter:a?.subdivisionNameFilter}}async function y(e,t,a,i,n){if(e.hasAttribute("multiple"))return;const o=e.value,s=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${e.dataset.name}"]`));for(const e of s)await m(e,t,a,i,n,o)}const g="__CountriesWidgetNS__";async function w(t={}){window[g]||(window[g]={initialized:!1,initPromise:null,version:0,eventHandlers:new WeakMap});const n=window[g];n.eventHandlers||(n.eventHandlers=new WeakMap);return!0===t.reload&&(n.initialized=!1,n.initPromise=null),n.initPromise=(async()=>{"loading"===document.readyState&&await new Promise(e=>{document.addEventListener("DOMContentLoaded",()=>e(),{once:!0})});const u=function(e){const t="undefined"!=typeof window&&window.CountriesDBConfig?window.CountriesDBConfig:null;let a=null;try{let e=null;if(document.currentScript&&document.currentScript instanceof HTMLScriptElement){const t=document.currentScript.src;t&&(t.includes("@countriesdb/widget")||t.includes("widget/dist/index.js"))&&(e=document.currentScript)}if(!e){e=Array.from(document.getElementsByTagName("script")).find(e=>e.src&&(e.src.includes("@countriesdb/widget")||e.src.includes("widget/dist/index.js")))||null}e&&e.src&&(a=new URL(e.src))}catch{}const i={publicKey:e.publicKey??t?.publicKey??a?.searchParams.get("public_key")??"",backendUrl:e.backendUrl??t?.backendUrl??a?.searchParams.get("backend_url")??"https://api.countriesdb.com",defaultLanguage:e.defaultLanguage??t?.defaultLanguage??a?.searchParams.get("default_language")??void 0,forcedLanguage:e.forcedLanguage??t?.forcedLanguage??a?.searchParams.get("forced_language")??void 0,showSubdivisionType:void 0!==e.showSubdivisionType?e.showSubdivisionType:void 0!==t?.showSubdivisionType?t.showSubdivisionType:b(a?.searchParams.get("show_subdivision_type")??"1"),followRelated:void 0!==e.followRelated?e.followRelated:void 0!==t?.followRelated?t.followRelated:b(a?.searchParams.get("follow_related")??"false"),followUpward:void 0!==e.followUpward?e.followUpward:void 0!==t?.followUpward?t.followUpward:b(a?.searchParams.get("follow_upward")??"false"),allowParentSelection:void 0!==e.allowParentSelection?e.allowParentSelection:void 0!==t?.allowParentSelection?t.allowParentSelection:b(a?.searchParams.get("allow_parent_selection")??"false"),isoCountryNames:void 0!==e.isoCountryNames?e.isoCountryNames:void 0!==t?.isoCountryNames?t.isoCountryNames:b(a?.searchParams.get("iso_country_names")??"false"),subdivisionRomanizationPreference:e.subdivisionRomanizationPreference||t?.subdivisionRomanizationPreference||a?.searchParams.get("subdivision_romanization_preference")||void 0,preferLocalVariant:void 0!==e.preferLocalVariant?e.preferLocalVariant:void 0!==t?.preferLocalVariant?t.preferLocalVariant:b(a?.searchParams.get("prefer_local_variant")??"false"),preferOfficialSubdivisions:void 0!==e.preferOfficialSubdivisions?e.preferOfficialSubdivisions:void 0!==t?.preferOfficialSubdivisions?t.preferOfficialSubdivisions:b(a?.searchParams.get("prefer_official")??"false"),countryNameFilter:e.countryNameFilter??t?.countryNameFilter,subdivisionNameFilter:e.subdivisionNameFilter??t?.subdivisionNameFilter,autoInit:void 0!==e.autoInit?e.autoInit:void 0!==t?.autoInit?t.autoInit:b(a?.searchParams.get("auto_init")??"true")};if(a){const e=a.searchParams.get("countryNameFilter");if(e&&"undefined"!=typeof window){const t=window[e];"function"==typeof t&&(i.countryNameFilter=t)}const t=a.searchParams.get("subdivisionNameFilter");if(t&&"undefined"!=typeof window){const e=window[t];"function"==typeof e&&(i.subdivisionNameFilter=e)}}return i}(t);if(function(){const e=Array.from(document.querySelectorAll(".country-selection"));for(const t of e)t.classList.contains("subdivision-selection")&&(t.classList.remove("subdivision-selection"),t.classList.add("subdivision-selection-removed"))}(),u.followRelated&&u.followUpward)return function(){const e="Error: Cannot enable both follow_related and follow_upward",t=Array.from(document.querySelectorAll(".country-selection"));for(const a of t)a.innerHTML=`<option value="${a.dataset.defaultValue??""}" disabled>${e}</option>`;const a=Array.from(document.querySelectorAll(".subdivision-selection"));for(const t of a)t.innerHTML=`<option value="${t.dataset.defaultValue??""}" disabled>${e}</option>`}(),!1;const g={countriesMap:new WeakMap,subdivisionsMap:new WeakMap,subdivisionsLanguageMap:new WeakMap,isInitializing:new Set,eventHandlers:n.eventHandlers},w=u.publicKey||"";await async function(e,t,i,n){const o=Array.from(document.querySelectorAll(".subdivision-selection"));for(const s of o){a(s,"&mdash;",!0);const o=s.dataset.country,l=o?document.querySelector(`.country-selection[data-name="${o}"]`):null;if(l&&l.hasAttribute("multiple")){const e=s.dataset.defaultValue??"";s.innerHTML=`<option value="${e}" disabled>Error: Cannot link to multi-select country. Use data-country-code instead.</option>`;continue}if(!o||!l)if(s.hasAttribute("data-country-code")&&s.dataset.countryCode)await m(s,e,t,i,n,s.dataset.countryCode);else{const e=s.dataset.defaultValue??"";s.innerHTML+=`<option value="${e}" disabled>Error: No country select present</option>`}const u=i.eventHandlers.get(s);u&&(u.update&&s.removeEventListener("change",u.update),u.followRelated&&s.removeEventListener("change",u.followRelated),u.followUpward&&s.removeEventListener("change",u.followUpward));const p={update:e=>{d(e)||r(s,{type:"subdivision",reason:"regular"})}};s.addEventListener("change",p.update),p.followRelated=async a=>{d(a)||await c(s,e,0,i,n.followRelated,(e,a,o)=>m(e,a,t,i,n,o))},s.addEventListener("change",p.followRelated),p.followUpward=async a=>{d(a)||await f(s,e,0,i,n.followUpward,(e,a,o)=>m(e,a,t,i,n,o))},s.addEventListener("change",p.followUpward),i.eventHandlers.set(s,p)}}(w,u.backendUrl,g,{followRelated:u.followRelated||!1,followUpward:u.followUpward||!1,showSubdivisionType:!1!==u.showSubdivisionType,allowParentSelection:u.allowParentSelection||!1,preferOfficialSubdivisions:u.preferOfficialSubdivisions||!1,subdivisionRomanizationPreference:u.subdivisionRomanizationPreference,preferLocalVariant:u.preferLocalVariant||!1,subdivisionNameFilter:u.subdivisionNameFilter});const h={followRelated:u.followRelated||!1,followUpward:u.followUpward||!1,showSubdivisionType:!1!==u.showSubdivisionType,allowParentSelection:u.allowParentSelection||!1,preferOfficialSubdivisions:u.preferOfficialSubdivisions||!1,subdivisionRomanizationPreference:u.subdivisionRomanizationPreference,preferLocalVariant:u.preferLocalVariant||!1,forcedLanguage:u.forcedLanguage,defaultLanguage:u.defaultLanguage,subdivisionNameFilter:u.subdivisionNameFilter};await async function(t,n,u,c){const f=Array.from(document.querySelectorAll(".country-selection")),g={};for(const w of f){const f=w.dataset.name;if(f&&g[f]){w.removeAttribute("data-name"),a(w,"&mdash;");const e=w.dataset.defaultValue??"";w.innerHTML+=`<option value="${e}" disabled>Error: Duplicate field</option>`;continue}f&&(g[f]=!0),a(w,"&mdash;"),u.isInitializing.add(w);let b=!1,h=!1;try{const a=null==(w.getAttribute("data-preselected")||w.dataset.preselected),s=e.getLanguageHeaders(c.forcedLanguage,c.defaultLanguage),l=await e.fetchCountries({apiKey:t,backendUrl:n,shouldUseGeoIP:a,isoCountryNames:c.isoCountryNames,languageHeaders:s}),f=l.data,g=l.language||"en";if(u.countriesMap.set(w,f),i(w,f,g,c.countryNameFilter),void 0!==(w.getAttribute("data-preselected")||w.dataset.preselected||w.dataset._widgetTempPreselect)&&(o(w),r(w,{type:"country",reason:"preselected"}),b=!0,w.value&&(w.value,w.dataset.defaultValue)),a){const e=f.find(e=>e.preselected);e&&(w.value=e.iso_alpha_2,r(w,{type:"country",reason:"geoip"}),b=!0)}!h&&w.value&&w.value!==(w.dataset.defaultValue||"")&&(h=!0);const _=u.eventHandlers.get(w);_?.countryChange&&w.removeEventListener("change",_.countryChange);const S=async e=>{if(d(e))return;r(w,{type:"country",reason:"regular"});const a=v(),i="undefined"!=typeof window&&window.CountriesDBConfig?window.CountriesDBConfig:c;await y(w,t,n,u,a);const o=w.value;if(!o)return;const s=(u.countriesMap.get(w)||[]).find(e=>e.iso_alpha_2===o);if(!s)return;const l=i?.followUpward||!1;l&&!w.multiple&&s.is_subdivision_of&&await p(w,t,0,u,l,(e,t,i)=>m(e,t,n,u,a,i))},L=u.eventHandlers.get(w)||{};L.countryChange=S,u.eventHandlers.set(w,L),w.addEventListener("change",S)}catch(e){if(console.error("Failed to fetch countries:",e),s(w,e),w.dataset.name){const t=Array.from(document.querySelectorAll(`.subdivision-selection[data-country="${w.dataset.name}"]`));for(const i of t)a(i,"&mdash;"),s(i,e)}}finally{u.isInitializing.delete(w),l(w,{type:"country",phase:"initial"}),b||r(w,{type:"country",reason:"regular"})}}}(w,u.backendUrl,g,{defaultLanguage:u.defaultLanguage,forcedLanguage:u.forcedLanguage,isoCountryNames:u.isoCountryNames||!1,followRelated:u.followRelated||!1,followUpward:u.followUpward||!1,countryNameFilter:u.countryNameFilter});const _=Array.from(document.querySelectorAll(".country-selection"));for(const e of _)e.value&&e.value!==(e.dataset.defaultValue||"")&&await y(e,w,u.backendUrl,g,h);return n.initialized=!0,!0})(),n.initPromise}function b(e){if(null==e)return!1;const t=String(e).trim().toLowerCase();return!("0"===t||"false"===t)}return"undefined"!=typeof window&&(window.CountriesWidgetLoad=w,function e(){if("loading"===document.readyState)return void document.addEventListener("DOMContentLoaded",e,{once:!0});let t=null;if(document.currentScript&&document.currentScript instanceof HTMLScriptElement){const e=document.currentScript.src;e&&(e.includes("@countriesdb/widget")||e.includes("widget/dist/index.js"))&&(t=document.currentScript)}if(!t){t=Array.from(document.getElementsByTagName("script")).find(e=>e.src&&(e.src.includes("@countriesdb/widget")||e.src.includes("widget/dist/index.js")))||null}let a=!0;const i="undefined"!=typeof window&&window.CountriesDBConfig||null;if(i&&void 0!==i.autoInit)a=!!i.autoInit;else if(t&&t.src)try{const e=new URL(t.src).searchParams.get("auto_init");a=null===e||"true"===e||"1"===e}catch{a=!0}a&&setTimeout(()=>{w().catch(console.error)},0)}()),w});
2
2
  //# sourceMappingURL=index.js.map