@countriesdb/widget 0.1.36 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -40,20 +40,15 @@ For detailed documentation, visit [countriesdb.com/docs](https://countriesdb.com
40
40
  ### Script Tag (UMD)
41
41
 
42
42
  ```html
43
- <script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js"></script>
44
- <script>
45
- CountriesWidget.CountriesWidgetLoad({
46
- publicKey: 'YOUR_PUBLIC_KEY',
47
- defaultLanguage: 'en'
48
- });
49
- </script>
43
+ <!-- Widget auto-initializes when script loads -->
44
+ <script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>
50
45
 
51
46
  <!-- Add CSS classes to your select elements -->
52
- <select class="country-selection" name="country">
47
+ <select class="country-selection" data-name="country1" name="country">
53
48
  <option value="">Select Country</option>
54
49
  </select>
55
50
 
56
- <select class="subdivision-selection" name="state" data-country="country">
51
+ <select class="subdivision-selection" name="state" data-country="country1">
57
52
  <option value="">Select State/Province</option>
58
53
  </select>
59
54
  ```
@@ -62,7 +57,10 @@ For detailed documentation, visit [countriesdb.com/docs](https://countriesdb.com
62
57
 
63
58
  ```html
64
59
  <script type="module">
65
- import { CountriesWidgetLoad } from '@countriesdb/widget';
60
+ import CountriesWidgetLoad from '@countriesdb/widget';
61
+
62
+ // Or use auto-init with window.CountriesDBConfig:
63
+ // import '@countriesdb/widget';
66
64
 
67
65
  CountriesWidgetLoad({
68
66
  publicKey: 'YOUR_PUBLIC_KEY',
@@ -74,12 +72,12 @@ For detailed documentation, visit [countriesdb.com/docs](https://countriesdb.com
74
72
  ### Node.js / Bundler
75
73
 
76
74
  ```javascript
77
- import { CountriesWidgetLoad } from '@countriesdb/widget';
75
+ import CountriesWidgetLoad from '@countriesdb/widget';
78
76
 
79
77
  CountriesWidgetLoad({
80
78
  publicKey: 'YOUR_PUBLIC_KEY',
81
- defaultLanguage: 'en',
82
- enableGeolocation: true
79
+ defaultLanguage: 'en'
80
+ // GeoIP is enabled by default unless disabled via data-preselected=""
83
81
  });
84
82
  ```
85
83
 
@@ -101,6 +99,7 @@ CountriesWidgetLoad({
101
99
  - `countryNameFilter` (optional): Custom function to filter/transform country names
102
100
  - `subdivisionNameFilter` (optional): Custom function to filter/transform subdivision names
103
101
  - `autoInit` (optional): Auto-initialize on load (default: `true`)
102
+ - `reload` (optional): Force re-initialization, clearing cached state and reapplying preselected values (default: `false`)
104
103
 
105
104
  ### Data Attributes
106
105
 
@@ -134,7 +133,7 @@ document.addEventListener('countriesWidget:update', (event) => {
134
133
  // value: 'US',
135
134
  // selectedValues: ['US'],
136
135
  // name: 'country1',
137
- // country: null,
136
+ // country: null, // For subdivision selects: linked country select's data-name
138
137
  // isSubdivision: false,
139
138
  // type: 'country',
140
139
  // reason: 'regular' | 'geoip' | 'preselected' | 'reload' | 'follow'
@@ -153,7 +152,7 @@ document.addEventListener('countriesWidget:ready', (event) => {
153
152
  // value: 'US',
154
153
  // selectedValues: ['US'],
155
154
  // name: 'country1',
156
- // country: null,
155
+ // country: null, // For subdivision selects: linked country select's data-name
157
156
  // isSubdivision: false,
158
157
  // type: 'country' | 'subdivision',
159
158
  // phase: 'initial' | 'reload'
@@ -186,7 +185,19 @@ document.addEventListener('countriesWidget:ready', (event) => {
186
185
  ### Custom Name Filter
187
186
 
188
187
  ```javascript
189
- CountriesWidgetLoad({
188
+ // Using window.CountriesDBConfig (before script loads)
189
+ window.CountriesDBConfig = {
190
+ publicKey: 'YOUR_PUBLIC_KEY',
191
+ countryNameFilter: (code, name, language, item) => {
192
+ if (code === 'US') {
193
+ return 'United States of America';
194
+ }
195
+ return name;
196
+ }
197
+ };
198
+
199
+ // Or using window.CountriesWidgetLoad (after script loads)
200
+ window.CountriesWidgetLoad({
190
201
  publicKey: 'YOUR_PUBLIC_KEY',
191
202
  countryNameFilter: (code, name, language, item) => {
192
203
  if (code === 'US') {
@@ -201,7 +212,25 @@ CountriesWidgetLoad({
201
212
 
202
213
  ### `CountriesWidgetLoad(options)`
203
214
 
204
- Main initialization function. Returns a Promise that resolves when initialization is complete.
215
+ Main initialization function. Returns a Promise that resolves to `true` when initialization is complete, or `false` if initialization failed (e.g., due to conflicting parameters like `followRelated` and `followUpward`).
216
+
217
+ **Parameters:**
218
+ - `options` (object): Configuration options (see [Options](#options) above)
219
+
220
+ **Example:**
221
+ ```javascript
222
+ // Basic initialization
223
+ await CountriesWidgetLoad({
224
+ publicKey: 'YOUR_PUBLIC_KEY',
225
+ defaultLanguage: 'en'
226
+ });
227
+
228
+ // Force reload (clears cached state and reapplies preselected values)
229
+ await CountriesWidgetLoad({
230
+ publicKey: 'YOUR_PUBLIC_KEY',
231
+ reload: true
232
+ });
233
+ ```
205
234
 
206
235
  For complete API documentation, visit [countriesdb.com/docs](https://countriesdb.com/docs).
207
236
 
@@ -214,7 +243,7 @@ For complete API documentation, visit [countriesdb.com/docs](https://countriesdb
214
243
 
215
244
  ## License
216
245
 
217
- PROPRIETARY - Copyright (c) NAYEE LLC. See [LICENSE](https://github.com/countriesdb/countriesdb/blob/main/packages/npm/widget/LICENSE) for details.
246
+ PROPRIETARY - Copyright (c) NAYEE LLC.
218
247
 
219
248
  **Developed by [NAYEE LLC](https://nayee.net)**
220
249
 
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: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,null!=i&&""!==String(i).trim()&&(e.dataset._widgetPreselectedConsumed="1")}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),b=await e.fetchSubdivisions({apiKey:i,backendUrl:d,countryCode:w,shouldUseGeoIP:s,preferOfficial:l,subdivisionRomanizationPreference:f.subdivisionRomanizationPreference,preferLocalVariant:f.preferLocalVariant,languageHeaders:p}),h=b.data,_=b.language||"en";if(c.subdivisionsMap.set(t,h),c.subdivisionsLanguageMap.set(t,_),h.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,w=t.dataset.defaultValue||"",b=v&&v!==w&&""!==v.trim();t.innerHTML=n(h,t,_,f.showSubdivisionType,f.allowParentSelection,f.subdivisionNameFilter),e||(void 0!==l&&(t.dataset.label=l),void 0!==p&&(t.dataset.defaultValue=p));let S=!1;if(b&&!e){Array.from(t.options).some(e=>e.value===v)&&(t.value=v,S=!0)}if(!S){const e=void 0!==(t.getAttribute("data-preselected")||t.dataset.preselected||t.dataset._widgetTempPreselect),n="1"===t.dataset._widgetPreselectedConsumed;if(!e||n&&g){if(s){const e=h.find(e=>e.preselected);if(e){const n=t.hasAttribute("multiple");let o=e;if(!f.allowParentSelection&&!n){const a=Array.from(t.options).find(t=>t.value===e.code);if(a?.disabled){const a=h.filter(t=>t.parent_id===e.id);if(a.length>0){const e=a.sort((e,t)=>(e.name||"").localeCompare(t.name||"",_,{sensitivity:"accent"}))[0],i=Array.from(t.options).find(t=>t.value===e.code);if(i?.disabled){const t=h.filter(t=>t.parent_id===e.id);if(t.length>0){const e=t.sort((e,t)=>(e.name||"").localeCompare(t.name||"",_,{sensitivity:"accent"}));o=e[0]}else o=e}else o=e}}}if(n){const e=Array.from(t.options).find(e=>e.value===o.code);e&&(e.selected=!0)}else t.value=o.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 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 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);if(!0===t.reload&&(n.initialized=!1,n.initPromise=null,"undefined"!=typeof document)){document.querySelectorAll(".subdivision-selection").forEach(e=>{e.dataset._widgetPreselectedConsumed&&delete e.dataset._widgetPreselectedConsumed})}return 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});
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.detail?e=t.detail:t.message?e=t.message: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,null!=i&&""!==String(i).trim()&&(e.dataset._widgetPreselectedConsumed="1")}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),b=await e.fetchSubdivisions({apiKey:i,backendUrl:d,countryCode:w,shouldUseGeoIP:s,preferOfficial:l,subdivisionRomanizationPreference:f.subdivisionRomanizationPreference,preferLocalVariant:f.preferLocalVariant,languageHeaders:p}),h=b.data,_=b.language||"en";if(c.subdivisionsMap.set(t,h),c.subdivisionsLanguageMap.set(t,_),h.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,w=t.dataset.defaultValue||"",b=v&&v!==w&&""!==v.trim();t.innerHTML=n(h,t,_,f.showSubdivisionType,f.allowParentSelection,f.subdivisionNameFilter),e||(void 0!==l&&(t.dataset.label=l),void 0!==p&&(t.dataset.defaultValue=p));let S=!1;if(b&&!e){Array.from(t.options).some(e=>e.value===v)&&(t.value=v,S=!0)}if(!S){const e=void 0!==(t.getAttribute("data-preselected")||t.dataset.preselected||t.dataset._widgetTempPreselect),n="1"===t.dataset._widgetPreselectedConsumed;if(!e||n&&g){if(s){const e=h.find(e=>e.preselected);if(e){const n=t.hasAttribute("multiple");let o=e;if(!f.allowParentSelection&&!n){const a=Array.from(t.options).find(t=>t.value===e.code);if(a?.disabled){const a=h.filter(t=>t.parent_id===e.id);if(a.length>0){const e=a.sort((e,t)=>(e.name||"").localeCompare(t.name||"",_,{sensitivity:"accent"}))[0],i=Array.from(t.options).find(t=>t.value===e.code);if(i?.disabled){const t=h.filter(t=>t.parent_id===e.id);if(t.length>0){const e=t.sort((e,t)=>(e.name||"").localeCompare(t.name||"",_,{sensitivity:"accent"}));o=e[0]}else o=e}else o=e}}}if(n){const e=Array.from(t.options).find(e=>e.value===o.code);e&&(e.selected=!0)}else t.value=o.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 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 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);if(!0===t.reload&&(n.initialized=!1,n.initPromise=null,"undefined"!=typeof document)){document.querySelectorAll(".subdivision-selection").forEach(e=>{e.dataset._widgetPreselectedConsumed&&delete e.dataset._widgetPreselectedConsumed})}return 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
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../widget-core/dist/esm/api-client.js","../../widget-core/dist/esm/subdivision-tree.js","../src/dom-manipulation.ts","../../widget-core/dist/esm/filters.js","../src/event-system.ts","../src/follow-logic.ts","../src/initialization.ts","../src/index.ts"],"sourcesContent":["/**\n * API client for CountriesDB API\n */\nexport class CountriesDBClient {\n /**\n * Fetch countries from the API\n */\n static async fetchCountries(options) {\n const { apiKey, backendUrl, shouldUseGeoIP = true, isoCountryNames = false, languageHeaders = {}, } = options;\n const base = `${backendUrl}/api/countries`;\n const params = [];\n if (!shouldUseGeoIP) {\n params.push('no_geoip=1');\n }\n if (isoCountryNames) {\n params.push('country_name_source=iso');\n }\n const url = params.length ? `${base}?${params.join('&')}` : base;\n return this.fetchFromApi(url, apiKey, languageHeaders);\n }\n /**\n * Fetch subdivisions for a specific country\n */\n static async fetchSubdivisions(options) {\n const { apiKey, backendUrl, countryCode, shouldUseGeoIP = true, preferOfficial = false, subdivisionRomanizationPreference, preferLocalVariant = false, languageHeaders = {}, } = options;\n if (!countryCode) {\n return { data: [], language: null };\n }\n const base = `${backendUrl}/api/countries/${countryCode}/subdivisions`;\n const params = [];\n if (!shouldUseGeoIP) {\n params.push('no_geoip=1');\n }\n if (subdivisionRomanizationPreference) {\n params.push(`subdivision_romanization_preference=${encodeURIComponent(subdivisionRomanizationPreference)}`);\n }\n if (preferLocalVariant) {\n params.push('prefer_local_variant=1');\n }\n if (preferOfficial) {\n params.push('prefer_official=1');\n }\n const url = params.length ? `${base}?${params.join('&')}` : base;\n return this.fetchFromApi(url, apiKey, languageHeaders);\n }\n /**\n * Generic API fetch method\n */\n static async fetchFromApi(url, apiKey, languageHeaders) {\n try {\n const response = await fetch(url, {\n headers: {\n ...languageHeaders,\n 'X-API-KEY': apiKey,\n 'Content-Type': 'application/json',\n },\n });\n if (!response.ok) {\n let errorMessage = `HTTP Error: ${response.status}`;\n try {\n const errorData = await response.json();\n if (errorData.error) {\n errorMessage = errorData.error;\n }\n }\n catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n const data = (await response.json());\n const language = response.headers.get('X-Selected-Language') || null;\n return { data, language };\n }\n catch (error) {\n console.error(`Failed to fetch data from ${url}:`, error);\n throw error;\n }\n }\n /**\n * Get language headers from browser and config\n */\n static getLanguageHeaders(forcedLanguage, defaultLanguage) {\n const headers = {};\n if (forcedLanguage) {\n headers['X-Forced-Language'] = forcedLanguage;\n }\n if (defaultLanguage) {\n headers['X-Default-Language'] = defaultLanguage;\n }\n // Use browser's language preference\n if (typeof navigator !== 'undefined' && navigator.language) {\n headers['Accept-Language'] = navigator.language;\n }\n else {\n headers['Accept-Language'] = 'en';\n }\n return headers;\n }\n}\n","/**\n * Utilities for building and working with subdivision trees\n */\n/**\n * Build a tree structure from a flat list of subdivisions\n */\nexport function buildSubdivisionTree(subdivisions) {\n const map = {};\n const roots = [];\n // Create map of all subdivisions\n subdivisions.forEach((item) => {\n map[item.id] = {\n ...item,\n children: [],\n };\n });\n // Build tree structure\n subdivisions.forEach((item) => {\n const node = map[item.id];\n if (item.parent_id && map[item.parent_id]) {\n map[item.parent_id].children.push(node);\n }\n else {\n roots.push(node);\n }\n });\n return roots;\n}\n/**\n * Flatten subdivision tree into HTML options\n */\nexport function flattenSubdivisionOptions(nodes, level, prefixes, labelKey, language, allowParentSelection, subdivisionNameFilter) {\n let html = '';\n // Apply name filter and get display names\n const nodesWithDisplayNames = nodes\n .map((node) => {\n let displayName = node[labelKey] || node.name;\n const countryCode = node.code ? node.code.split('-')[0] : null;\n // Apply subdivisionNameFilter if provided\n if (subdivisionNameFilter && typeof subdivisionNameFilter === 'function') {\n const filteredName = subdivisionNameFilter(node.code, displayName, language, countryCode, node);\n if (filteredName === false) {\n return null; // Mark for filtering - remove this item\n }\n if (filteredName !== null && filteredName !== undefined) {\n displayName = filteredName;\n }\n }\n return { ...node, _displayName: displayName };\n })\n .filter((node) => node !== null);\n // Sort: use Unicode-aware sorting if subdivisionNameFilter was used\n const locale = subdivisionNameFilter && typeof subdivisionNameFilter === 'function' && language\n ? language\n : undefined;\n nodesWithDisplayNames.sort((a, b) => {\n if (locale) {\n return a._displayName.localeCompare(b._displayName, locale, {\n sensitivity: 'accent', // Case-insensitive, accent-sensitive\n ignorePunctuation: false,\n });\n }\n return a._displayName.localeCompare(b._displayName); // Default behavior\n });\n const prefix = level > 0 ? (prefixes[level] ?? '&nbsp;'.repeat(level * 2)) : '';\n const cssClass = `subdivision-level-${level}`;\n for (const node of nodesWithDisplayNames) {\n const hasChildren = node.children && node.children.length > 0;\n const displayName = node._displayName;\n const label = `${prefix}${displayName}`;\n if (hasChildren) {\n if (allowParentSelection) {\n html += `<option value=\"${node.code}\" class=\"${cssClass}\">${label}</option>`;\n }\n else {\n html += `<option disabled value=\"${node.code}\" class=\"${cssClass}\">${label}</option>`;\n }\n html += flattenSubdivisionOptions(node.children, level + 1, prefixes, labelKey, language, allowParentSelection, subdivisionNameFilter);\n }\n else {\n html += `<option value=\"${node.code}\" class=\"${cssClass}\">${label}</option>`;\n }\n }\n return html;\n}\n/**\n * Parse nesting prefixes from data attributes\n */\nexport function parseNestingPrefixes(dataAttributes) {\n const prefixes = {};\n for (let lvl = 1; lvl <= 10; lvl++) {\n const key = `nested${lvl}Prefix`;\n const value = dataAttributes[key];\n if (value !== undefined) {\n prefixes[lvl] = value;\n }\n else {\n break;\n }\n }\n return prefixes;\n}\n","/**\n * DOM manipulation utilities\n */\n\nimport type { SelectElement } from './types';\nimport type { Country, Subdivision } from '@countriesdb/widget-core';\nimport {\n applyCountryNameFilter,\n sortCountries,\n buildSubdivisionTree,\n flattenSubdivisionOptions,\n parseNestingPrefixes,\n} from '@countriesdb/widget-core';\n\n/**\n * Initialize a select element with default option\n */\nexport function initializeSelect(\n select: SelectElement,\n fallbackLabel: string = 'Not Applicable',\n isSubdivision: boolean = false\n): void {\n const isMultiple = select.hasAttribute('multiple');\n\n // For multi-select, don't add default option or use data-label/data-default-value\n if (isMultiple) {\n select.innerHTML = '';\n // Remove data-label and data-default-value for multi-select (they're ignored)\n if (select.dataset.label !== undefined) {\n delete select.dataset.label;\n }\n if (select.dataset.defaultValue !== undefined) {\n delete select.dataset.defaultValue;\n }\n } else {\n const dataLabel = select.dataset.label;\n const dataDefaultValue = select.dataset.defaultValue;\n\n const label = dataLabel || fallbackLabel;\n const defaultValue = dataDefaultValue ?? '';\n select.innerHTML = `<option value=\"${defaultValue}\">${label}</option>`;\n\n if (dataLabel !== undefined) {\n select.dataset.label = dataLabel;\n }\n if (dataDefaultValue !== undefined) {\n select.dataset.defaultValue = dataDefaultValue;\n }\n }\n\n if (isSubdivision) {\n select.disabled = true;\n }\n}\n\n/**\n * Populate a select element with countries\n */\nexport function populateCountrySelect(\n select: SelectElement,\n countries: Country[],\n language: string,\n countryNameFilter?: (code: string, name: string, lang: string, item: Country) => string | false | null | undefined\n): void {\n // Apply filter and get display names\n let filteredCountries = applyCountryNameFilter(countries, countryNameFilter, language);\n \n // Sort if filter was applied\n if (countryNameFilter) {\n filteredCountries = sortCountries(filteredCountries, language);\n }\n\n // Check for multi-select using both attribute and property\n const isMultiple = select.hasAttribute('multiple') || select.multiple;\n \n if (isMultiple) {\n // For multi-select, don't add default option (like old widget)\n select.innerHTML = '';\n } else {\n // Clear existing options (except default)\n const defaultOption = select.querySelector('option[value=\"\"]') || \n (select.dataset.defaultValue ? select.querySelector(`option[value=\"${select.dataset.defaultValue}\"]`) : null);\n const defaultValue = select.dataset.defaultValue ?? '';\n \n // Keep default option if it exists\n select.innerHTML = defaultOption ? defaultOption.outerHTML : `<option value=\"${defaultValue}\">${select.dataset.label || '&mdash;'}</option>`;\n }\n\n // Add country options\n filteredCountries.forEach((country) => {\n const option = document.createElement('option');\n option.value = country.iso_alpha_2;\n option.textContent = country._displayName;\n select.appendChild(option);\n });\n}\n\n/**\n * Populate a select element with subdivisions\n */\nexport function buildSubdivisionOptionsHTML(\n subdivisions: Subdivision[],\n select: SelectElement,\n language: string,\n showSubdivisionType: boolean,\n allowParentSelection: boolean,\n subdivisionNameFilter?: (\n code: string,\n originalName: string,\n language: string,\n countryCode: string | null,\n item: Subdivision\n ) => string | false | null | undefined\n): string {\n const tree = buildSubdivisionTree(subdivisions);\n \n // Parse nesting prefixes from data attributes\n const dataAttributes: Record<string, string | undefined> = {};\n for (let lvl = 1; lvl <= 10; lvl++) {\n const key = `nested${lvl}Prefix`;\n const value = select.dataset[key];\n if (value !== undefined) {\n dataAttributes[`nested${lvl}Prefix`] = value;\n } else {\n break;\n }\n }\n const prefixes = parseNestingPrefixes(dataAttributes);\n \n const isMultiple = select.hasAttribute('multiple');\n const labelKey = showSubdivisionType ? 'full_name' : 'name';\n\n let html = '';\n // For multi-select, don't add default option\n if (!isMultiple) {\n const defaultLabel = select.dataset.label || '&mdash;';\n const defaultValue = select.dataset.defaultValue ?? '';\n html = `<option value=\"${defaultValue}\">${defaultLabel}</option>`;\n }\n\n html += flattenSubdivisionOptions(\n tree,\n 0,\n prefixes,\n labelKey,\n language,\n allowParentSelection,\n subdivisionNameFilter\n );\n \n return html;\n}\n\n/**\n * Apply preselected value to a select element\n * Like old widget, reads the value from the select element itself to get current state\n */\nexport function applyPreselectedValue(\n select: SelectElement,\n apiKey?: string\n): void {\n // Read from select element like old widget (line 740)\n const tempOnce = select.dataset._widgetTempPreselect;\n const permanent = select.getAttribute('data-preselected') || select.dataset.preselected;\n const hasTemp = tempOnce !== undefined && tempOnce !== null && String(tempOnce).trim() !== '';\n const chosen = hasTemp ? tempOnce : permanent;\n \n if (!chosen || (typeof chosen === 'string' && chosen.trim() === '')) {\n return;\n }\n\n const value = String(chosen);\n const isMultiple = select.hasAttribute('multiple');\n\n if (isMultiple) {\n // For multi-select, parse comma-separated values\n const values = value\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v !== '');\n // Select all matching options\n Array.from(select.options).forEach((option) => {\n option.selected = values.includes(option.value);\n });\n } else {\n // Single select: set single value\n select.value = value;\n }\n \n // Consume temp preselect so it's only applied once (like old widget)\n // Note: We keep data-preselected attribute to support reload: true\n if (select.dataset._widgetTempPreselect !== undefined) {\n delete select.dataset._widgetTempPreselect;\n }\n \n // Mark permanent preselect as consumed after first application\n // This prevents it from being reapplied on user-initiated country changes\n // But reload: true will clear this flag to allow reapplication\n if (permanent !== undefined && permanent !== null && String(permanent).trim() !== '') {\n select.dataset._widgetPreselectedConsumed = '1';\n }\n}\n\n/**\n * Handle API error by showing error message in select\n */\nexport function handleApiError(\n select: SelectElement,\n errorMessage: string | Error,\n replace: boolean = false\n): void {\n const message = errorMessage instanceof Error ? errorMessage.message : errorMessage;\n const defaultValue = select.dataset.defaultValue ?? '';\n // Add \"Error: \" prefix to match old widget behavior and test expectations\n const formattedMessage = message.startsWith('Error: ') ? message : `Error: ${message}`;\n if (replace) {\n select.innerHTML = `<option value=\"${defaultValue}\" disabled>${formattedMessage}</option>`;\n } else {\n select.innerHTML += `<option value=\"${defaultValue}\" disabled>${formattedMessage}</option>`;\n }\n}\n\n/**\n * Parse boolean from string value\n */\nexport function parseBoolean(value: string | null | undefined): boolean {\n if (value === null || value === undefined) {\n return false;\n }\n const lowered = String(value).trim().toLowerCase();\n return !(lowered === '0' || lowered === 'false');\n}\n\n","/**\n * Name filtering utilities\n */\n/**\n * Apply country name filter to a list of countries\n */\nexport function applyCountryNameFilter(countries, filter, language) {\n if (!filter || typeof filter !== 'function') {\n return countries.map((c) => ({ ...c, _displayName: c.name }));\n }\n return countries\n .map((country) => {\n const filteredName = filter(country.iso_alpha_2, country.name, language, country);\n if (filteredName === false) {\n return null; // Skip this item\n }\n const displayName = filteredName !== null && filteredName !== undefined\n ? filteredName\n : country.name;\n return { ...country, _displayName: displayName };\n })\n .filter((c) => c !== null);\n}\n/**\n * Sort countries with Unicode-aware sorting\n */\nexport function sortCountries(countries, language) {\n const locale = language || undefined;\n return [...countries].sort((a, b) => {\n if (locale) {\n return a._displayName.localeCompare(b._displayName, locale, {\n sensitivity: 'accent', // Case-insensitive, accent-sensitive\n ignorePunctuation: false,\n });\n }\n return a._displayName.localeCompare(b._displayName);\n });\n}\n/**\n * Apply subdivision name filter to a list of subdivisions\n */\nexport function applySubdivisionNameFilter(subdivisions, filter, language, countryCode) {\n if (!filter || typeof filter !== 'function') {\n return subdivisions.map((s) => ({\n ...s,\n _displayName: s.full_name || s.name,\n }));\n }\n return subdivisions\n .map((subdivision) => {\n const originalName = subdivision.full_name || subdivision.name;\n const filteredName = filter(subdivision.code, originalName, language, countryCode, subdivision);\n if (filteredName === false) {\n return null; // Skip this item\n }\n const displayName = filteredName !== null && filteredName !== undefined\n ? filteredName\n : originalName;\n return { ...subdivision, _displayName: displayName };\n })\n .filter((s) => s !== null);\n}\n","/**\n * Event system for widget updates\n */\n\nimport type {\n ReadyEventDetail,\n SelectElement,\n UpdateEventDetail,\n} from './types';\n\n/**\n * Dispatch a custom update event for widget changes\n */\nexport function dispatchUpdateEvent(\n select: SelectElement,\n detail: Partial<UpdateEventDetail> = {}\n): void {\n let selectedValues: string[] = [];\n \n if (select.multiple) {\n // For multi-select, selectedOptions is a HTMLCollection, convert to array\n selectedValues = Array.from(select.selectedOptions || [])\n .map((opt) => opt.value)\n .filter((v) => v !== '');\n } else {\n // For single-select, use value\n selectedValues = select.value ? [select.value] : [];\n }\n\n const evt = new CustomEvent<UpdateEventDetail>('countriesWidget:update', {\n bubbles: true,\n detail: {\n value: select.value || '',\n selectedValues,\n name: select.dataset.name || null,\n country: select.dataset.country || null,\n isSubdivision: select.classList.contains('subdivision-selection'),\n ...detail,\n },\n });\n \n select.dispatchEvent(evt);\n}\n\n/**\n * Dispatch a custom ready event once a select has been populated.\n */\nexport function dispatchReadyEvent(\n select: SelectElement,\n detail: Partial<ReadyEventDetail> = {}\n): void {\n const selectedValues = select.multiple\n ? Array.from(select.selectedOptions || [])\n .map((opt) => opt.value)\n .filter((v) => v !== '')\n : select.value\n ? [select.value]\n : [];\n\n const evt = new CustomEvent<ReadyEventDetail>('countriesWidget:ready', {\n bubbles: true,\n detail: {\n value: select.value || '',\n selectedValues,\n name: select.dataset.name || null,\n country: select.dataset.country || null,\n isSubdivision: select.classList.contains('subdivision-selection'),\n type: select.classList.contains('subdivision-selection')\n ? 'subdivision'\n : 'country',\n phase: 'initial',\n ...detail,\n },\n });\n\n select.dispatchEvent(evt);\n}\n\n/**\n * Check if an event was initiated by the widget (not user)\n */\nexport function isWidgetInitiatedEvent(event: Event): boolean {\n return (event as any).isWidgetInitiated === true;\n}\n\n/**\n * Mark an event as widget-initiated\n */\nexport function markEventAsWidgetInitiated(event: Event): void {\n (event as any).isWidgetInitiated = true;\n}\n\n","/**\n * Follow logic for related and upward navigation\n */\n\nimport type { SelectElement, WidgetState } from './types';\nimport type { Subdivision } from '@countriesdb/widget-core';\nimport { dispatchUpdateEvent } from './event-system';\nimport { CountriesDBClient } from '@countriesdb/widget-core';\nimport { updateSubdivisionSelect } from './initialization';\n\n/**\n * Trigger follow logic when a subdivision is selected\n */\nexport async function triggerFollowLogic(\n select: SelectElement,\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n followRelated: boolean,\n followUpward: boolean,\n updateSubdivisionSelectFn: (\n select: SelectElement,\n apiKey: string,\n countryCode: string\n ) => Promise<void>,\n updateSubdivisionsFn?: (\n countrySelect: SelectElement,\n apiKey: string\n ) => Promise<void>\n): Promise<void> {\n if (!followRelated && !followUpward) {\n return;\n }\n\n const linkedCountrySelect = document.querySelector<SelectElement>(\n `.country-selection[data-name=\"${select.dataset.country}\"]`\n );\n \n // Only work if country is single-select (never when country is multi)\n if (!linkedCountrySelect || linkedCountrySelect.multiple) {\n return;\n }\n\n const allSubs = state.subdivisionsMap.get(select);\n if (!allSubs) {\n return;\n }\n\n // For follow_upward, only work if subdivision is single-select\n if (followUpward && select.multiple) {\n return;\n }\n\n const selectedCode = select.value;\n if (!selectedCode) {\n return;\n }\n\n const picked = allSubs.find((s) => s.code === selectedCode);\n if (!picked) {\n return;\n }\n\n // follow_related\n if (followRelated && picked.related_country_code) {\n const targetCountry = picked.related_country_code;\n const targetSubdivision = picked.related_subdivision_code;\n\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n \n if (relatedSubsSelect && targetSubdivision) {\n relatedSubsSelect.dataset._widgetTempPreselect = targetSubdivision; // one-time preselect\n }\n\n if (linkedCountrySelect.value !== targetCountry) {\n // Directly set value like old widget did\n linkedCountrySelect.value = targetCountry;\n dispatchUpdateEvent(linkedCountrySelect, { type: 'country', reason: 'regular' });\n // Update all subdivision selects for the new country (like old widget)\n if (updateSubdivisionsFn) {\n await updateSubdivisionsFn(linkedCountrySelect, apiKey);\n } else if (relatedSubsSelect) {\n // Fallback: update just the one subdivision select\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, targetCountry);\n }\n } else {\n if (relatedSubsSelect && targetSubdivision) {\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, targetCountry);\n }\n }\n }\n\n // follow_upward\n if (followUpward && picked.is_subdivision_of) {\n const parentCode = picked.is_subdivision_of.parent_country_code;\n const parentSub = picked.is_subdivision_of.subdivision_code;\n\n if (parentSub) {\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n // Only preselect if subdivision is single-select (follow_upward doesn't work with multi)\n if (relatedSubsSelect && !relatedSubsSelect.multiple) {\n relatedSubsSelect.dataset._widgetTempPreselect = parentSub; // one-time preselect\n }\n }\n\n if (linkedCountrySelect.value !== parentCode) {\n // Directly set value like old widget did\n linkedCountrySelect.value = parentCode;\n dispatchUpdateEvent(linkedCountrySelect, { type: 'country', reason: 'regular' });\n // Update all subdivision selects for the new country (like old widget)\n if (updateSubdivisionsFn) {\n await updateSubdivisionsFn(linkedCountrySelect, apiKey);\n } else {\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n if (relatedSubsSelect) {\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, parentCode);\n }\n }\n } else if (parentSub) {\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n if (relatedSubsSelect && !relatedSubsSelect.multiple) {\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, parentCode);\n }\n }\n }\n}\n\n/**\n * Handle follow_related from subdivision change event\n */\nexport async function handleFollowRelatedFromSubdivision(\n select: SelectElement,\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n followRelated: boolean,\n updateSubdivisionSelectFn: (\n select: SelectElement,\n apiKey: string,\n countryCode: string\n ) => Promise<void>\n): Promise<void> {\n if (!followRelated) {\n return;\n }\n\n const linkedCountrySelect = document.querySelector<SelectElement>(\n `.country-selection[data-name=\"${select.dataset.country}\"]`\n );\n \n // Only work if country is single-select (never when country is multi)\n if (!linkedCountrySelect || linkedCountrySelect.multiple) {\n return;\n }\n\n const allSubs = state.subdivisionsMap.get(select);\n if (!allSubs) {\n return;\n }\n\n // Get selected code (for multi-select, use first selected value)\n const selectedCode = select.multiple\n ? (select.selectedOptions[0]?.value || null)\n : select.value;\n \n if (!selectedCode) {\n return;\n }\n\n const picked = allSubs.find((s) => s.code === selectedCode);\n if (!picked || !picked.related_country_code) {\n return;\n }\n\n const targetCountry = picked.related_country_code;\n const targetSubdivision = picked.related_subdivision_code;\n\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n \n if (relatedSubsSelect && targetSubdivision) {\n relatedSubsSelect.dataset.preselected = targetSubdivision;\n }\n\n if (linkedCountrySelect.value !== targetCountry) {\n // Directly set value like old widget did\n linkedCountrySelect.value = targetCountry;\n dispatchUpdateEvent(linkedCountrySelect, { type: 'country', reason: 'regular' });\n // Update all subdivision selects for the new country (like old widget)\n // Note: updateSubdivisionsFn is not available in handleFollowRelatedFromSubdivision,\n // so we update the subdivision select manually\n if (relatedSubsSelect) {\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, targetCountry);\n }\n } else {\n if (relatedSubsSelect && targetSubdivision) {\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, targetCountry);\n }\n }\n}\n\n/**\n * Handle follow_upward from subdivision change event\n */\nexport async function handleFollowUpwardFromSubdivision(\n select: SelectElement,\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n followUpward: boolean,\n updateSubdivisionSelectFn: (\n select: SelectElement,\n apiKey: string,\n countryCode: string\n ) => Promise<void>\n): Promise<void> {\n if (!followUpward) {\n return;\n }\n \n // Disable for multi-select subdivisions\n if (select.multiple) {\n return;\n }\n\n const linkedCountrySelect = document.querySelector<SelectElement>(\n `.country-selection[data-name=\"${select.dataset.country}\"]`\n );\n \n // Only work if country is single-select (never when country is multi)\n if (!linkedCountrySelect || linkedCountrySelect.multiple) {\n return;\n }\n\n const allSubs = state.subdivisionsMap.get(select);\n if (!allSubs) {\n return;\n }\n\n const selectedCode = select.value;\n if (!selectedCode) {\n return;\n }\n\n const picked = allSubs.find((s) => s.code === selectedCode);\n if (!picked || !picked.is_subdivision_of) {\n return;\n }\n\n const parentCode = picked.is_subdivision_of.parent_country_code;\n const parentSub = picked.is_subdivision_of.subdivision_code;\n\n if (parentSub) {\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n if (relatedSubsSelect) {\n relatedSubsSelect.dataset.preselected = parentSub;\n }\n }\n\n if (linkedCountrySelect.value !== parentCode) {\n // Directly set value like old widget did\n linkedCountrySelect.value = parentCode;\n dispatchUpdateEvent(linkedCountrySelect, { type: 'country', reason: 'follow' });\n // Update all subdivision selects for the new country (like old widget)\n // Note: updateSubdivisionsFn is not available in handleFollowUpwardFromSubdivision,\n // so we update the subdivision select manually\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n if (relatedSubsSelect) {\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, parentCode);\n }\n } else if (parentSub) {\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n if (relatedSubsSelect) {\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, parentCode);\n }\n }\n}\n\n/**\n * Handle follow_upward from country change event\n */\nexport async function handleFollowUpwardFromCountry(\n select: SelectElement,\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n followUpward: boolean,\n updateSubdivisionSelectFn: (\n select: SelectElement,\n apiKey: string,\n countryCode: string\n ) => Promise<void>\n): Promise<void> {\n // Only works when country is single-select (never for multi-select)\n if (!followUpward || select.multiple) {\n return;\n }\n\n const countries = state.countriesMap.get(select);\n if (!countries) {\n return;\n }\n\n const chosen = select.value;\n if (!chosen) {\n return;\n }\n\n const picked = countries.find((c) => c.iso_alpha_2 === chosen);\n if (!picked || !picked.is_subdivision_of) {\n return;\n }\n\n const parentCode = picked.is_subdivision_of.parent_country_code;\n const parentSub = picked.is_subdivision_of.subdivision_code;\n\n if (select.value !== parentCode) {\n if (parentSub) {\n const linkedSubdivisionSelects = Array.from(\n document.querySelectorAll<SelectElement>(\n `.subdivision-selection[data-country=\"${select.dataset.name}\"]`\n )\n );\n for (const s of linkedSubdivisionSelects) {\n // Only preselect if subdivision is single-select (follow_upward doesn't work with multi)\n if (!s.multiple) {\n s.dataset.preselected = parentSub;\n }\n }\n }\n // Directly set value like old widget did\n select.value = parentCode;\n dispatchUpdateEvent(select, { type: 'country', reason: 'regular' });\n // Update all subdivision selects for the new country (like old widget)\n // Note: updateSubdivisionsFn is not available in handleFollowUpwardFromCountry,\n // so we update all subdivision selects manually\n const linkedSubdivisionSelects = Array.from(\n document.querySelectorAll<SelectElement>(\n `.subdivision-selection[data-country=\"${select.dataset.name}\"]`\n )\n );\n for (const s of linkedSubdivisionSelects) {\n await updateSubdivisionSelectFn(s, apiKey, parentCode);\n }\n } else if (parentSub) {\n const linkedSubdivisionSelects = Array.from(\n document.querySelectorAll<SelectElement>(\n `.subdivision-selection[data-country=\"${select.dataset.name}\"]`\n )\n );\n for (const s of linkedSubdivisionSelects) {\n // Only update if subdivision is single-select\n if (!s.multiple) {\n await updateSubdivisionSelectFn(s, apiKey, parentCode);\n }\n }\n }\n}\n\n","/**\n * Widget initialization logic\n */\n\nimport type { SelectElement, WidgetState, EventHandlers } from './types';\nimport type { Country, Subdivision } from '@countriesdb/widget-core';\nimport { CountriesDBClient } from '@countriesdb/widget-core';\nimport {\n initializeSelect,\n populateCountrySelect,\n buildSubdivisionOptionsHTML,\n applyPreselectedValue,\n handleApiError,\n parseBoolean,\n} from './dom-manipulation';\nimport {\n dispatchReadyEvent,\n dispatchUpdateEvent,\n isWidgetInitiatedEvent,\n} from './event-system';\nimport {\n triggerFollowLogic,\n handleFollowRelatedFromSubdivision,\n handleFollowUpwardFromSubdivision,\n handleFollowUpwardFromCountry,\n} from './follow-logic';\n\n/**\n * Setup subdivision selection elements\n */\nexport async function setupSubdivisionSelection(\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n config: {\n followRelated: boolean;\n followUpward: boolean;\n showSubdivisionType: boolean;\n allowParentSelection: boolean;\n preferOfficialSubdivisions: boolean;\n subdivisionRomanizationPreference?: string;\n preferLocalVariant: boolean;\n subdivisionNameFilter?: (\n code: string,\n originalName: string,\n language: string,\n countryCode: string | null,\n item: Subdivision\n ) => string | false | null | undefined;\n }\n): Promise<void> {\n const subdivisionSelects = Array.from(\n document.querySelectorAll<SelectElement>('.subdivision-selection')\n );\n\n for (const select of subdivisionSelects) {\n // Initialize with a default option\n initializeSelect(select, '&mdash;', true);\n\n // Linked country select (if any)\n const countryName = select.dataset.country;\n const linkedCountrySelect = countryName\n ? document.querySelector<SelectElement>(\n `.country-selection[data-name=\"${countryName}\"]`\n )\n : null;\n\n // Check if linked country select is multi-select (not allowed)\n if (linkedCountrySelect && linkedCountrySelect.hasAttribute('multiple')) {\n const defaultValue = select.dataset.defaultValue ?? '';\n select.innerHTML = `<option value=\"${defaultValue}\" disabled>Error: Cannot link to multi-select country. Use data-country-code instead.</option>`;\n continue;\n }\n\n // No direct link → maybe data-country-code\n if (!countryName || !linkedCountrySelect) {\n if (\n select.hasAttribute('data-country-code') &&\n select.dataset.countryCode\n ) {\n await updateSubdivisionSelect(\n select,\n apiKey,\n backendUrl,\n state,\n config,\n select.dataset.countryCode\n );\n } else {\n const defaultValue = select.dataset.defaultValue ?? '';\n select.innerHTML += `<option value=\"${defaultValue}\" disabled>Error: No country select present</option>`;\n }\n }\n\n // Remove old event handlers if they exist (for re-initialization)\n const oldHandlers = state.eventHandlers.get(select);\n if (oldHandlers) {\n if (oldHandlers.update) {\n select.removeEventListener('change', oldHandlers.update);\n }\n if (oldHandlers.followRelated) {\n select.removeEventListener('change', oldHandlers.followRelated);\n }\n if (oldHandlers.followUpward) {\n select.removeEventListener('change', oldHandlers.followUpward);\n }\n }\n\n // Create new event handlers\n const handlers: EventHandlers = {};\n\n // Always dispatch an update event for user-initiated subdivision changes\n handlers.update = (event: Event) => {\n if (isWidgetInitiatedEvent(event)) {\n return;\n }\n dispatchUpdateEvent(select, { type: 'subdivision', reason: 'regular' });\n };\n select.addEventListener('change', handlers.update);\n\n // --- follow_related (forward direction) ---\n handlers.followRelated = async (event: Event) => {\n if (isWidgetInitiatedEvent(event)) {\n return;\n }\n await handleFollowRelatedFromSubdivision(\n select,\n apiKey,\n backendUrl,\n state,\n config.followRelated,\n (s, key, code) =>\n updateSubdivisionSelect(s, key, backendUrl, state, config, code)\n );\n };\n select.addEventListener('change', handlers.followRelated);\n\n // --- follow_upward (reverse direction) ---\n handlers.followUpward = async (event: Event) => {\n if (isWidgetInitiatedEvent(event)) {\n return;\n }\n await handleFollowUpwardFromSubdivision(\n select,\n apiKey,\n backendUrl,\n state,\n config.followUpward,\n (s, key, code) =>\n updateSubdivisionSelect(s, key, backendUrl, state, config, code)\n );\n };\n select.addEventListener('change', handlers.followUpward);\n\n // Store handlers for future cleanup\n state.eventHandlers.set(select, handlers);\n }\n}\n\n/**\n * Update subdivision select with data for a specific country\n */\nexport async function updateSubdivisionSelect(\n select: SelectElement,\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n config: {\n followRelated: boolean;\n followUpward: boolean;\n showSubdivisionType: boolean;\n allowParentSelection: boolean;\n preferOfficialSubdivisions: boolean;\n subdivisionRomanizationPreference?: string;\n preferLocalVariant: boolean;\n forcedLanguage?: string;\n defaultLanguage?: string;\n subdivisionNameFilter?: (\n code: string,\n originalName: string,\n language: string,\n countryCode: string | null,\n item: Subdivision\n ) => string | false | null | undefined;\n },\n countryCode: string\n): Promise<void> {\n const preselectedValue =\n select.getAttribute('data-preselected') || select.dataset.preselected;\n\n // Check if this is a reload (select was already populated before)\n const isReload = state.subdivisionsMap.has(select);\n\n initializeSelect(select, '&mdash;', true);\n\n // Mark as initializing to prevent change events\n state.isInitializing.add(select);\n\n let effectiveCountryCode = countryCode;\n if (!effectiveCountryCode) {\n effectiveCountryCode = select.dataset.countryCode || '';\n }\n\n if (effectiveCountryCode) {\n let valueSetByWidget = false; // Track if a value was set by widget\n try {\n // Use GeoIP only if data-preselected attribute is not set at all\n const shouldUseGeoIP =\n preselectedValue === undefined || preselectedValue === null;\n\n // Check if this subdivision select prefers official subdivisions\n // Use data attribute if present, otherwise use config\n const preferOfficial = select.hasAttribute('data-prefer-official') \n ? true \n : config.preferOfficialSubdivisions;\n\n const languageHeaders = CountriesDBClient.getLanguageHeaders(\n config.forcedLanguage,\n config.defaultLanguage\n );\n\n const subdivisionsResult = await CountriesDBClient.fetchSubdivisions({\n apiKey,\n backendUrl,\n countryCode: effectiveCountryCode,\n shouldUseGeoIP,\n preferOfficial,\n subdivisionRomanizationPreference: config.subdivisionRomanizationPreference,\n preferLocalVariant: config.preferLocalVariant,\n languageHeaders,\n });\n\n const subdivisions = subdivisionsResult.data;\n const subdivisionsLanguage = subdivisionsResult.language || 'en';\n\n // Store in memory\n state.subdivisionsMap.set(select, subdivisions);\n state.subdivisionsLanguageMap.set(select, subdivisionsLanguage);\n\n if (subdivisions.length > 0) {\n // Populate <option>\n select.disabled = false;\n\n // Preserve data attributes before setting innerHTML (only for non-multi-select)\n const isMultiple = select.hasAttribute('multiple');\n const dataLabel = !isMultiple ? select.dataset.label : undefined;\n const dataDefaultValue = !isMultiple\n ? select.dataset.defaultValue\n : undefined;\n\n // Preserve user's current selection before clearing innerHTML\n // This prevents preselected values from overwriting user selections\n const currentValue = select.value;\n const defaultValue = select.dataset.defaultValue || '';\n const hasUserSelection = currentValue && currentValue !== defaultValue && currentValue.trim() !== '';\n\n select.innerHTML = buildSubdivisionOptionsHTML(\n subdivisions,\n select,\n subdivisionsLanguage,\n config.showSubdivisionType,\n config.allowParentSelection,\n config.subdivisionNameFilter\n );\n\n // Restore data attributes after setting innerHTML\n if (!isMultiple) {\n if (dataLabel !== undefined) {\n select.dataset.label = dataLabel;\n }\n if (dataDefaultValue !== undefined) {\n select.dataset.defaultValue = dataDefaultValue;\n }\n }\n\n // Restore user's selection if it exists in the new options (user selection takes priority)\n let userSelectionRestored = false;\n if (hasUserSelection && !isMultiple) {\n const optionExists = Array.from(select.options).some(opt => opt.value === currentValue);\n if (optionExists) {\n select.value = currentValue;\n userSelectionRestored = true;\n // Don't dispatch event here - user already selected it, no need to notify again\n }\n }\n\n // Manual preselection only if user hasn't selected anything\n if (!userSelectionRestored) {\n // Check if preselected value exists (applyPreselectedValue will read it from select element)\n const hasPreselectedValue = \n (select.getAttribute('data-preselected') || select.dataset.preselected || select.dataset._widgetTempPreselect) !== undefined;\n const preselectedConsumed = select.dataset._widgetPreselectedConsumed === '1';\n \n // Only apply preselected if:\n // 1. It exists AND\n // 2. Either it hasn't been consumed yet, OR this is the initial load (not a reload)\n // This prevents reapplying preselected values on user-initiated country changes\n // But allows them on initial load and on reload: true (which clears the consumed flag)\n if (hasPreselectedValue && (!preselectedConsumed || !isReload)) {\n applyPreselectedValue(select, apiKey);\n dispatchUpdateEvent(select, {\n type: 'subdivision',\n reason: 'preselected',\n });\n valueSetByWidget = true;\n await triggerFollowLogic(\n select,\n apiKey,\n backendUrl,\n state,\n config.followRelated,\n config.followUpward,\n (s, key, code) =>\n updateSubdivisionSelect(s, key, backendUrl, state, config, code),\n (countrySelect, key) =>\n updateSubdivisions(countrySelect, key, backendUrl, state, config)\n );\n } else {\n // Try GeoIP preselect (only if user hasn't selected anything)\n if (shouldUseGeoIP) {\n const preselectedSubdivision = subdivisions.find(\n (subdivision) => subdivision.preselected\n );\n if (preselectedSubdivision) {\n const isMultiple = select.hasAttribute('multiple');\n let subdivisionToSelect = preselectedSubdivision;\n \n // If preselected is disabled and allowParentSelection is false, find first enabled child\n if (!config.allowParentSelection && !isMultiple) {\n const preselectedOption = Array.from(select.options).find(\n (opt) => opt.value === preselectedSubdivision.code\n );\n \n if (preselectedOption?.disabled) {\n // Find direct children by parent_id\n const directChildren = subdivisions.filter(\n (sub) => sub.parent_id === preselectedSubdivision.id\n );\n \n if (directChildren.length > 0) {\n // Sort by name and get first child\n const sorted = directChildren.sort((a, b) => {\n return (a.name || '').localeCompare(b.name || '', subdivisionsLanguage, { sensitivity: 'accent' });\n });\n \n const firstChild = sorted[0];\n \n // Check if first child is also disabled (has its own children)\n const firstChildOption = Array.from(select.options).find(\n (opt) => opt.value === firstChild.code\n );\n \n if (firstChildOption?.disabled) {\n // First child is disabled, find its first child (grandchild)\n const grandChildren = subdivisions.filter(\n (sub) => sub.parent_id === firstChild.id\n );\n if (grandChildren.length > 0) {\n const sortedGrandChildren = grandChildren.sort((a, b) => {\n return (a.name || '').localeCompare(b.name || '', subdivisionsLanguage, { sensitivity: 'accent' });\n });\n subdivisionToSelect = sortedGrandChildren[0];\n } else {\n subdivisionToSelect = firstChild;\n }\n } else {\n subdivisionToSelect = firstChild;\n }\n }\n }\n }\n \n if (isMultiple) {\n // For multi-select, find and select the option\n const option = Array.from(select.options).find(\n (opt) => opt.value === subdivisionToSelect.code\n );\n if (option) {\n option.selected = true;\n }\n } else {\n // Single select: set value directly\n select.value = subdivisionToSelect.code;\n }\n dispatchUpdateEvent(select, {\n type: 'subdivision',\n reason: 'geoip',\n });\n valueSetByWidget = true;\n await triggerFollowLogic(\n select,\n apiKey,\n backendUrl,\n state,\n config.followRelated,\n config.followUpward,\n (s, key, code) =>\n updateSubdivisionSelect(s, key, backendUrl, state, config, code),\n (countrySelect, key) =>\n updateSubdivisions(countrySelect, key, backendUrl, state, config)\n );\n }\n }\n }\n }\n } else {\n select.disabled = true;\n }\n } catch (error) {\n console.error('Failed to fetch subdivisions:', error);\n handleApiError(select, error as Error);\n } finally {\n // Mark initialization as complete\n state.isInitializing.delete(select);\n dispatchReadyEvent(select, {\n type: 'subdivision',\n phase: isReload ? 'reload' : 'initial',\n });\n // Only fire 'reload' if this is a reload, not initial load\n if (isReload && !valueSetByWidget) {\n dispatchUpdateEvent(select, {\n type: 'subdivision',\n reason: 'reload',\n });\n }\n }\n } else if (\n !select.dataset.country ||\n !document.querySelector(\n `.country-selection[data-name=\"${select.dataset.country}\"]`\n )\n ) {\n const defaultValue = select.dataset.defaultValue ?? '';\n select.innerHTML += `<option value=\"${defaultValue}\" disabled>Error: No country select present</option>`;\n }\n}\n\n/**\n * Get current subdivision config from window.CountriesDBConfig and script URL\n * This ensures we always use the latest config values, even after widget reload\n */\nfunction getCurrentSubdivisionConfig(apiKey: string, backendUrl: string): {\n followRelated: boolean;\n followUpward: boolean;\n showSubdivisionType: boolean;\n allowParentSelection: boolean;\n preferOfficialSubdivisions: boolean;\n subdivisionRomanizationPreference?: string;\n preferLocalVariant: boolean;\n forcedLanguage?: string;\n defaultLanguage?: string;\n subdivisionNameFilter?: (\n code: string,\n originalName: string,\n language: string,\n countryCode: string | null,\n item: Subdivision\n ) => string | false | null | undefined;\n} {\n const globalConfig = typeof window !== 'undefined' && (window as any).CountriesDBConfig\n ? (window as any).CountriesDBConfig\n : null;\n\n // Also check script URL parameters (for backward compatibility and reload scenarios)\n let scriptUrl: URL | null = null;\n try {\n const scripts = Array.from(document.getElementsByTagName('script'));\n const loaderScript = scripts.find((s) => \n s.src && (\n s.src.includes('@countriesdb/widget') ||\n s.src.includes('widget/dist/index.js')\n )\n ) as HTMLScriptElement || null;\n \n if (loaderScript && loaderScript.src) {\n scriptUrl = new URL(loaderScript.src);\n }\n } catch {\n // Ignore errors\n }\n\n // Import parseBoolean from dom-manipulation\n const parseBoolean = (value: string | null | undefined): boolean => {\n if (value === null || value === undefined) {\n return false;\n }\n const lowered = String(value).trim().toLowerCase();\n return !(lowered === '0' || lowered === 'false');\n };\n\n return {\n followRelated: globalConfig?.followRelated !== undefined\n ? globalConfig.followRelated\n : parseBoolean(scriptUrl?.searchParams.get('follow_related') ?? 'false'),\n followUpward: globalConfig?.followUpward !== undefined\n ? globalConfig.followUpward\n : parseBoolean(scriptUrl?.searchParams.get('follow_upward') ?? 'false'),\n showSubdivisionType: globalConfig?.showSubdivisionType !== undefined\n ? globalConfig.showSubdivisionType\n : parseBoolean(scriptUrl?.searchParams.get('show_subdivision_type') ?? '1'),\n allowParentSelection: globalConfig?.allowParentSelection !== undefined\n ? globalConfig.allowParentSelection\n : parseBoolean(scriptUrl?.searchParams.get('allow_parent_selection') ?? 'false'),\n preferOfficialSubdivisions: globalConfig?.preferOfficialSubdivisions !== undefined\n ? globalConfig.preferOfficialSubdivisions\n : parseBoolean(scriptUrl?.searchParams.get('prefer_official') ?? 'false'),\n subdivisionRomanizationPreference: globalConfig?.subdivisionRomanizationPreference ||\n scriptUrl?.searchParams.get('subdivision_romanization_preference') ||\n undefined,\n preferLocalVariant: globalConfig?.preferLocalVariant !== undefined\n ? globalConfig.preferLocalVariant\n : parseBoolean(scriptUrl?.searchParams.get('prefer_local_variant') ?? 'false'),\n forcedLanguage: globalConfig?.forcedLanguage ||\n scriptUrl?.searchParams.get('forced_language') ||\n undefined,\n defaultLanguage: globalConfig?.defaultLanguage ||\n scriptUrl?.searchParams.get('default_language') ||\n undefined,\n subdivisionNameFilter: globalConfig?.subdivisionNameFilter,\n };\n}\n\n/**\n * Update subdivisions for all linked subdivision selects when country changes\n */\nexport async function updateSubdivisions(\n countrySelect: SelectElement,\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n config: {\n followRelated: boolean;\n followUpward: boolean;\n showSubdivisionType: boolean;\n allowParentSelection: boolean;\n preferOfficialSubdivisions: boolean;\n subdivisionRomanizationPreference?: string;\n preferLocalVariant: boolean;\n forcedLanguage?: string;\n defaultLanguage?: string;\n subdivisionNameFilter?: (\n code: string,\n originalName: string,\n language: string,\n countryCode: string | null,\n item: Subdivision\n ) => string | false | null | undefined;\n }\n): Promise<void> {\n // Don't update subdivisions for multi-select countries (not supported)\n if (countrySelect.hasAttribute('multiple')) {\n return;\n }\n\n const selectedCountry = countrySelect.value;\n const linkedSubdivisionSelects = Array.from(\n document.querySelectorAll<SelectElement>(\n `.subdivision-selection[data-country=\"${countrySelect.dataset.name}\"]`\n )\n );\n\n for (const select of linkedSubdivisionSelects) {\n await updateSubdivisionSelect(\n select,\n apiKey,\n backendUrl,\n state,\n config,\n selectedCountry\n );\n }\n}\n\n/**\n * Setup country selection elements\n */\nexport async function setupCountrySelection(\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n config: {\n defaultLanguage?: string;\n forcedLanguage?: string;\n isoCountryNames: boolean;\n followRelated: boolean;\n followUpward: boolean;\n countryNameFilter?: (\n code: string,\n name: string,\n language: string,\n item: Country\n ) => string | false | null | undefined;\n },\n subdivisionConfig: {\n followRelated: boolean;\n followUpward: boolean;\n showSubdivisionType: boolean;\n allowParentSelection: boolean;\n preferOfficialSubdivisions: boolean;\n subdivisionRomanizationPreference?: string;\n preferLocalVariant: boolean;\n subdivisionNameFilter?: (\n code: string,\n originalName: string,\n language: string,\n countryCode: string | null,\n item: Subdivision\n ) => string | false | null | undefined;\n }\n): Promise<void> {\n const countrySelects = Array.from(\n document.querySelectorAll<SelectElement>('.country-selection')\n );\n const seenNames: Record<string, boolean> = {}; // track data-name to detect duplicates\n\n for (const select of countrySelects) {\n const name = select.dataset.name;\n\n // Duplicates\n if (name && seenNames[name]) {\n select.removeAttribute('data-name');\n initializeSelect(select, '&mdash;');\n const defaultValue = select.dataset.defaultValue ?? '';\n select.innerHTML += `<option value=\"${defaultValue}\" disabled>Error: Duplicate field</option>`;\n continue;\n }\n if (name) {\n seenNames[name] = true;\n }\n\n // Note: Class renaming is now handled earlier in fixMisClassedElements()\n // This check is kept as a safety net but should not be needed\n\n // Initialize\n initializeSelect(select, '&mdash;');\n\n // Mark as initializing to prevent change events\n state.isInitializing.add(select);\n\n let valueSetByWidget = false; // Track if value was set by widget\n let loadedInitialSubdivisions = false; // Track if subdivisions were loaded\n\n try {\n const preselectedValue =\n select.getAttribute('data-preselected') || select.dataset.preselected;\n // Use GeoIP only if data-preselected attribute is not set at all\n const shouldUseGeoIP =\n preselectedValue === undefined || preselectedValue === null;\n\n const languageHeaders = CountriesDBClient.getLanguageHeaders(\n config.forcedLanguage,\n config.defaultLanguage\n );\n\n // Fetch & populate countries\n const countriesResult = await CountriesDBClient.fetchCountries({\n apiKey,\n backendUrl,\n shouldUseGeoIP,\n isoCountryNames: config.isoCountryNames,\n languageHeaders,\n });\n\n const countries = countriesResult.data;\n const countriesLanguage = countriesResult.language || 'en';\n\n state.countriesMap.set(select, countries);\n populateCountrySelect(\n select,\n countries,\n countriesLanguage,\n config.countryNameFilter\n );\n\n // Apply preselected (manual)\n // Check if preselected value exists (applyPreselectedValue will read it from select element)\n const hasPreselectedValue = \n (select.getAttribute('data-preselected') || select.dataset.preselected || select.dataset._widgetTempPreselect) !== undefined;\n if (hasPreselectedValue) {\n applyPreselectedValue(select, apiKey);\n dispatchUpdateEvent(select, { type: 'country', reason: 'preselected' });\n valueSetByWidget = true;\n // Load subdivisions after applying preselected value\n if (\n select.value &&\n select.value !== (select.dataset.defaultValue || '')\n ) {\n // This will be handled by the updateSubdivisions call below\n // We need to pass the config for subdivisions\n }\n }\n\n // GeoIP auto-select\n if (shouldUseGeoIP) {\n const preselectedCountry = countries.find(\n (country) => country.preselected\n );\n if (preselectedCountry) {\n select.value = preselectedCountry.iso_alpha_2;\n dispatchUpdateEvent(select, { type: 'country', reason: 'geoip' });\n valueSetByWidget = true;\n }\n }\n\n // If already chosen, load subdivisions\n if (\n !loadedInitialSubdivisions &&\n select.value &&\n select.value !== (select.dataset.defaultValue || '')\n ) {\n // Subdivisions will be loaded by event handler\n loadedInitialSubdivisions = true;\n }\n\n // Remove old event handlers if they exist (for re-initialization)\n const oldCountryHandlers = state.eventHandlers.get(select);\n if (oldCountryHandlers?.countryChange) {\n select.removeEventListener('change', oldCountryHandlers.countryChange);\n }\n\n // Create new country change handler\n const countryChangeHandler = async (event: Event) => {\n if (isWidgetInitiatedEvent(event)) {\n return;\n }\n\n // Dispatch update event for user-initiated country change\n dispatchUpdateEvent(select, { type: 'country', reason: 'regular' });\n\n // Get current config dynamically to ensure we use the latest values\n const currentSubdivisionConfig = getCurrentSubdivisionConfig(apiKey, backendUrl);\n const currentConfig = typeof window !== 'undefined' && (window as any).CountriesDBConfig\n ? (window as any).CountriesDBConfig\n : config;\n\n // Update subdivisions with current config\n await updateSubdivisions(select, apiKey, backendUrl, state, currentSubdivisionConfig);\n\n const chosen = select.value;\n if (!chosen) {\n return;\n }\n\n const stored = state.countriesMap.get(select) || [];\n const picked = stored.find((c) => c.iso_alpha_2 === chosen);\n if (!picked) {\n return;\n }\n\n // followUpward from country perspective\n // Only works when country is single-select (never for multi-select)\n const currentFollowUpward = currentConfig?.followUpward || false;\n if (currentFollowUpward && !select.multiple && picked.is_subdivision_of) {\n await handleFollowUpwardFromCountry(\n select,\n apiKey,\n backendUrl,\n state,\n currentFollowUpward,\n (s, key, code) =>\n updateSubdivisionSelect(s, key, backendUrl, state, currentSubdivisionConfig, code)\n );\n }\n };\n\n // Store and attach the handler\n const countryHandlers = state.eventHandlers.get(select) || {};\n countryHandlers.countryChange = countryChangeHandler;\n state.eventHandlers.set(select, countryHandlers);\n select.addEventListener('change', countryChangeHandler);\n } catch (error) {\n console.error('Failed to fetch countries:', error);\n handleApiError(select, error as Error);\n // Handle subdivision errors\n if (select.dataset.name) {\n const linkedSubdivisionSelects = Array.from(\n document.querySelectorAll<SelectElement>(\n `.subdivision-selection[data-country=\"${select.dataset.name}\"]`\n )\n );\n for (const s of linkedSubdivisionSelects) {\n initializeSelect(s, '&mdash;');\n handleApiError(s, error as Error);\n }\n }\n } finally {\n // Mark initialization as complete\n state.isInitializing.delete(select);\n dispatchReadyEvent(select, {\n type: 'country',\n phase: 'initial',\n });\n // If no preselected and no geoip selection happened, emit a regular update\n if (!valueSetByWidget) {\n dispatchUpdateEvent(select, { type: 'country', reason: 'regular' });\n }\n }\n }\n}\n\n","/**\n * @countriesdb/widget\n * \n * Plain JavaScript widget for CountriesDB.\n * Provides DOM manipulation and auto-initialization for country/subdivision selects.\n */\n\nimport type { WidgetOptions } from './types';\nimport type { WidgetConfig } from '@countriesdb/widget-core';\nimport { setupCountrySelection, setupSubdivisionSelection, updateSubdivisions } from './initialization';\nimport type { SelectElement, WidgetState, EventHandlers } from './types';\n\n// Global namespace to prevent double initialization\nconst NS_KEY = '__CountriesWidgetNS__';\n\ninterface WidgetNamespace {\n initialized: boolean;\n initPromise: Promise<boolean> | null;\n version: number;\n eventHandlers: WeakMap<SelectElement, EventHandlers>;\n}\n\ndeclare global {\n interface Window {\n [NS_KEY]: WidgetNamespace;\n CountriesWidgetLoad: typeof CountriesWidgetLoad;\n }\n}\n\n/**\n * Main widget initialization function\n */\nasync function CountriesWidgetLoad(\n options: WidgetOptions = {} as WidgetOptions\n): Promise<boolean> {\n // Initialize namespace\n if (!window[NS_KEY]) {\n window[NS_KEY] = {\n initialized: false,\n initPromise: null,\n version: 0,\n eventHandlers: new WeakMap<SelectElement, EventHandlers>(),\n };\n }\n\n const NS = window[NS_KEY];\n \n // Ensure eventHandlers exists (for backwards compatibility)\n if (!NS.eventHandlers) {\n NS.eventHandlers = new WeakMap<SelectElement, EventHandlers>();\n }\n\n // Handle reload option - reset state to force re-initialization\n const shouldReload = (options as any).reload === true;\n if (shouldReload) {\n NS.initialized = false;\n NS.initPromise = null;\n \n // Clear consumed preselected flags to allow preselected values to be reapplied on reload: true\n // This ensures full reload behavior where preselected values are reapplied\n if (typeof document !== 'undefined') {\n const subdivisionSelects = document.querySelectorAll('.subdivision-selection');\n subdivisionSelects.forEach((select) => {\n if ((select as HTMLElement).dataset._widgetPreselectedConsumed) {\n delete (select as HTMLElement).dataset._widgetPreselectedConsumed;\n }\n });\n }\n }\n\n // Share the same promise across concurrent calls\n NS.initPromise = (async () => {\n // Wait for DOM if needed\n if (document.readyState === 'loading') {\n await new Promise<void>((resolve) => {\n document.addEventListener('DOMContentLoaded', () => resolve(), {\n once: true,\n });\n });\n }\n\n // Get configuration from options or script URL\n const config = getConfigFromOptionsOrScript(options);\n\n // Fix mis-classed elements early (DOM cleanup that should always happen)\n fixMisClassedElements();\n\n // Check for conflicting parameters\n if (config.followRelated && config.followUpward) {\n showParamConflictError();\n return false;\n }\n\n // Initialize widget state\n // Use global eventHandlers from namespace so we can clean up old handlers on re-initialization\n const state: WidgetState = {\n countriesMap: new WeakMap(),\n subdivisionsMap: new WeakMap(),\n subdivisionsLanguageMap: new WeakMap(),\n isInitializing: new Set(),\n eventHandlers: NS.eventHandlers, // Use global WeakMap that persists across calls\n };\n\n // Use empty string if publicKey is missing (will show error when API calls fail)\n const apiKey = config.publicKey || '';\n\n // Setup subdivisions first (they depend on countries)\n await setupSubdivisionSelection(apiKey, config.backendUrl, state, {\n followRelated: config.followRelated || false,\n followUpward: config.followUpward || false,\n showSubdivisionType: config.showSubdivisionType !== false,\n allowParentSelection: config.allowParentSelection || false,\n preferOfficialSubdivisions: config.preferOfficialSubdivisions || false,\n subdivisionRomanizationPreference: config.subdivisionRomanizationPreference,\n preferLocalVariant: config.preferLocalVariant || false,\n subdivisionNameFilter: config.subdivisionNameFilter,\n });\n\n const subdivisionConfig = {\n followRelated: config.followRelated || false,\n followUpward: config.followUpward || false,\n showSubdivisionType: config.showSubdivisionType !== false,\n allowParentSelection: config.allowParentSelection || false,\n preferOfficialSubdivisions: config.preferOfficialSubdivisions || false,\n subdivisionRomanizationPreference: config.subdivisionRomanizationPreference,\n preferLocalVariant: config.preferLocalVariant || false,\n forcedLanguage: config.forcedLanguage,\n defaultLanguage: config.defaultLanguage,\n subdivisionNameFilter: config.subdivisionNameFilter,\n };\n\n // Setup countries\n await setupCountrySelection(\n apiKey,\n config.backendUrl,\n state,\n {\n defaultLanguage: config.defaultLanguage,\n forcedLanguage: config.forcedLanguage,\n isoCountryNames: config.isoCountryNames || false,\n followRelated: config.followRelated || false,\n followUpward: config.followUpward || false,\n countryNameFilter: config.countryNameFilter,\n },\n subdivisionConfig\n );\n\n // After countries are set up, update subdivisions for any preselected countries\n const countrySelects = Array.from(\n document.querySelectorAll<SelectElement>('.country-selection')\n );\n for (const select of countrySelects) {\n if (\n select.value &&\n select.value !== (select.dataset.defaultValue || '')\n ) {\n await updateSubdivisions(select, apiKey, config.backendUrl, state, subdivisionConfig);\n }\n }\n\n NS.initialized = true;\n return true;\n })();\n\n return NS.initPromise;\n}\n\n/**\n * Get configuration from options or script URL parameters\n */\nfunction getConfigFromOptionsOrScript(\n options: WidgetOptions\n): WidgetConfig & { backendUrl: string } {\n // Check for global config first (for bundled widgets that need config before auto-init)\n const globalConfig = typeof window !== 'undefined' && (window as any).CountriesDBConfig\n ? (window as any).CountriesDBConfig\n : null;\n \n // Try to get config from script URL (for backward compatibility with widget.blade.php)\n let scriptUrl: URL | null = null;\n try {\n let loaderScript: HTMLScriptElement | null = null;\n \n // First try document.currentScript (works during script execution)\n // But only if it matches the widget pattern (not a bundled file)\n if (document.currentScript && document.currentScript instanceof HTMLScriptElement) {\n const src = document.currentScript.src;\n if (src && (src.includes('@countriesdb/widget') || src.includes('widget/dist/index.js'))) {\n loaderScript = document.currentScript;\n }\n }\n \n // If currentScript didn't match, search for widget script\n if (!loaderScript) {\n const scripts = Array.from(document.getElementsByTagName('script'));\n loaderScript = scripts.find((s) => \n s.src && (\n s.src.includes('@countriesdb/widget') ||\n s.src.includes('widget/dist/index.js')\n )\n ) as HTMLScriptElement || null;\n }\n \n if (loaderScript && loaderScript.src) {\n scriptUrl = new URL(loaderScript.src);\n }\n } catch {\n // Ignore errors\n }\n\n const config: WidgetConfig & { backendUrl: string } = {\n // Priority: options > globalConfig > scriptUrl params > defaults\n publicKey: options.publicKey ?? globalConfig?.publicKey ?? scriptUrl?.searchParams.get('public_key') ?? '',\n backendUrl: options.backendUrl ?? globalConfig?.backendUrl ?? scriptUrl?.searchParams.get('backend_url') ?? getDefaultBackendUrl(),\n defaultLanguage: options.defaultLanguage ?? globalConfig?.defaultLanguage ?? scriptUrl?.searchParams.get('default_language') ?? undefined,\n forcedLanguage: options.forcedLanguage ?? globalConfig?.forcedLanguage ?? scriptUrl?.searchParams.get('forced_language') ?? undefined,\n showSubdivisionType: options.showSubdivisionType !== undefined\n ? options.showSubdivisionType\n : globalConfig?.showSubdivisionType !== undefined\n ? globalConfig.showSubdivisionType\n : parseBoolean(scriptUrl?.searchParams.get('show_subdivision_type') ?? '1'),\n followRelated: options.followRelated !== undefined\n ? options.followRelated\n : globalConfig?.followRelated !== undefined\n ? globalConfig.followRelated\n : parseBoolean(scriptUrl?.searchParams.get('follow_related') ?? 'false'),\n followUpward: options.followUpward !== undefined\n ? options.followUpward\n : globalConfig?.followUpward !== undefined\n ? globalConfig.followUpward\n : parseBoolean(scriptUrl?.searchParams.get('follow_upward') ?? 'false'),\n allowParentSelection: options.allowParentSelection !== undefined\n ? options.allowParentSelection\n : globalConfig?.allowParentSelection !== undefined\n ? globalConfig.allowParentSelection\n : parseBoolean(scriptUrl?.searchParams.get('allow_parent_selection') ?? 'false'),\n isoCountryNames: options.isoCountryNames !== undefined\n ? options.isoCountryNames\n : globalConfig?.isoCountryNames !== undefined\n ? globalConfig.isoCountryNames\n : parseBoolean(scriptUrl?.searchParams.get('iso_country_names') ?? 'false'),\n subdivisionRomanizationPreference:\n options.subdivisionRomanizationPreference ||\n globalConfig?.subdivisionRomanizationPreference ||\n scriptUrl?.searchParams.get('subdivision_romanization_preference') ||\n undefined,\n preferLocalVariant: options.preferLocalVariant !== undefined\n ? options.preferLocalVariant\n : globalConfig?.preferLocalVariant !== undefined\n ? globalConfig.preferLocalVariant\n : parseBoolean(scriptUrl?.searchParams.get('prefer_local_variant') ?? 'false'),\n preferOfficialSubdivisions: options.preferOfficialSubdivisions !== undefined\n ? options.preferOfficialSubdivisions\n : globalConfig?.preferOfficialSubdivisions !== undefined\n ? globalConfig.preferOfficialSubdivisions\n : parseBoolean(scriptUrl?.searchParams.get('prefer_official') ?? 'false'),\n countryNameFilter: options.countryNameFilter ?? globalConfig?.countryNameFilter,\n subdivisionNameFilter: options.subdivisionNameFilter ?? globalConfig?.subdivisionNameFilter,\n autoInit: options.autoInit !== undefined\n ? options.autoInit\n : globalConfig?.autoInit !== undefined\n ? globalConfig.autoInit\n : parseBoolean(scriptUrl?.searchParams.get('auto_init') ?? 'true'),\n };\n\n // Resolve filter functions from global scope if specified by name\n if (scriptUrl) {\n const countryNameFilterName = scriptUrl.searchParams.get('countryNameFilter');\n if (countryNameFilterName && typeof window !== 'undefined') {\n const filter = (window as any)[countryNameFilterName];\n if (typeof filter === 'function') {\n config.countryNameFilter = filter;\n }\n }\n\n const subdivisionNameFilterName = scriptUrl.searchParams.get('subdivisionNameFilter');\n if (subdivisionNameFilterName && typeof window !== 'undefined') {\n const filter = (window as any)[subdivisionNameFilterName];\n if (typeof filter === 'function') {\n config.subdivisionNameFilter = filter;\n }\n }\n }\n\n return config;\n}\n\n/**\n * Get default backend URL\n */\nfunction getDefaultBackendUrl(): string {\n // Always default to API domain\n // Users should explicitly set backendUrl if they need a custom one\n return 'https://api.countriesdb.com';\n}\n\n/**\n * Fix mis-classed elements (e.g., country-selection with subdivision-selection class)\n * This should happen early, before API calls, as it's just DOM cleanup\n */\nfunction fixMisClassedElements(): void {\n const countrySelects = Array.from(\n document.querySelectorAll<HTMLSelectElement>('.country-selection')\n );\n \n for (const select of countrySelects) {\n // Avoid conflict if mis-classed\n if (select.classList.contains('subdivision-selection')) {\n select.classList.remove('subdivision-selection');\n select.classList.add('subdivision-selection-removed');\n }\n }\n}\n\n/**\n * Parse boolean from string value\n */\nfunction parseBoolean(value: string | null | undefined): boolean {\n if (value === null || value === undefined) {\n return false;\n }\n const lowered = String(value).trim().toLowerCase();\n return !(lowered === '0' || lowered === 'false');\n}\n\n/**\n * Show error when both follow_related and follow_upward are enabled\n */\nfunction showParamConflictError(): void {\n const errorMessage = 'Error: Cannot enable both follow_related and follow_upward';\n const countrySelects = Array.from(\n document.querySelectorAll<SelectElement>('.country-selection')\n );\n for (const select of countrySelects) {\n select.innerHTML = `<option value=\"${select.dataset.defaultValue ?? ''}\" disabled>${errorMessage}</option>`;\n }\n const subdivisionSelects = Array.from(\n document.querySelectorAll<SelectElement>('.subdivision-selection')\n );\n for (const select of subdivisionSelects) {\n select.innerHTML = `<option value=\"${select.dataset.defaultValue ?? ''}\" disabled>${errorMessage}</option>`;\n }\n}\n\n// Expose public loader\nif (typeof window !== 'undefined') {\n window.CountriesWidgetLoad = CountriesWidgetLoad;\n\n // Auto-init if script URL has auto_init=true (or not set, default is true)\n // Use a function that waits for DOM to be ready and finds the script tag reliably\n (function checkAutoInit() {\n // Wait for DOM to be ready\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', checkAutoInit, { once: true });\n return;\n }\n\n // Find the script tag that loaded this widget\n let loaderScript: HTMLScriptElement | null = null;\n \n // First try document.currentScript (works during script execution)\n // But only if it matches the widget pattern (not a bundled file)\n if (document.currentScript && document.currentScript instanceof HTMLScriptElement) {\n const src = document.currentScript.src;\n if (src && (src.includes('@countriesdb/widget') || src.includes('widget/dist/index.js'))) {\n loaderScript = document.currentScript;\n }\n }\n \n // If currentScript didn't match, search for widget script\n if (!loaderScript) {\n const scripts = Array.from(document.getElementsByTagName('script'));\n loaderScript = scripts.find((s) => \n s.src && (\n s.src.includes('@countriesdb/widget') ||\n s.src.includes('widget/dist/index.js')\n )\n ) as HTMLScriptElement || null;\n }\n \n // Default to auto-init = true (only disable if explicitly set to false)\n let shouldAutoInit = true;\n \n const globalConfig = typeof window !== 'undefined'\n ? (window as any).CountriesDBConfig || null\n : null;\n \n if (globalConfig && typeof globalConfig.autoInit !== 'undefined') {\n shouldAutoInit = !!globalConfig.autoInit;\n } else if (loaderScript && loaderScript.src) {\n try {\n const scriptUrl = new URL(loaderScript.src);\n const autoInit = scriptUrl.searchParams.get('auto_init');\n // Only disable if explicitly set to false/0\n shouldAutoInit = autoInit === null || autoInit === 'true' || autoInit === '1';\n } catch {\n // If URL parsing fails, default to true (auto-init enabled)\n shouldAutoInit = true;\n }\n }\n \n // Auto-init by default (unless explicitly disabled)\n if (shouldAutoInit) {\n // Use setTimeout to ensure script tag is fully processed\n setTimeout(() => {\n CountriesWidgetLoad().catch(console.error);\n }, 0);\n }\n })();\n}\n\n// Export for ES modules\nexport default CountriesWidgetLoad;\n\n"],"names":["CountriesDBClient","fetchCountries","options","apiKey","backendUrl","shouldUseGeoIP","isoCountryNames","languageHeaders","base","params","push","url","length","join","this","fetchFromApi","fetchSubdivisions","countryCode","preferOfficial","subdivisionRomanizationPreference","preferLocalVariant","data","language","encodeURIComponent","response","fetch","headers","ok","errorMessage","status","errorData","json","error","Error","get","console","getLanguageHeaders","forcedLanguage","defaultLanguage","navigator","flattenSubdivisionOptions","nodes","level","prefixes","labelKey","allowParentSelection","subdivisionNameFilter","html","nodesWithDisplayNames","map","node","displayName","name","code","split","filteredName","_displayName","filter","locale","undefined","sort","a","b","localeCompare","sensitivity","ignorePunctuation","prefix","repeat","cssClass","hasChildren","children","label","initializeSelect","select","fallbackLabel","isSubdivision","hasAttribute","innerHTML","dataset","defaultValue","dataLabel","dataDefaultValue","disabled","populateCountrySelect","countries","countryNameFilter","filteredCountries","country","iso_alpha_2","c","applyCountryNameFilter","sortCountries","multiple","defaultOption","querySelector","outerHTML","forEach","option","document","createElement","value","textContent","appendChild","buildSubdivisionOptionsHTML","subdivisions","showSubdivisionType","tree","roots","item","id","parent_id","buildSubdivisionTree","dataAttributes","lvl","key","parseNestingPrefixes","defaultLabel","applyPreselectedValue","tempOnce","_widgetTempPreselect","permanent","getAttribute","preselected","chosen","String","trim","values","v","Array","from","selected","includes","_widgetPreselectedConsumed","handleApiError","replace","message","formattedMessage","startsWith","dispatchUpdateEvent","detail","selectedValues","selectedOptions","opt","evt","CustomEvent","bubbles","classList","contains","dispatchEvent","dispatchReadyEvent","type","phase","isWidgetInitiatedEvent","event","isWidgetInitiated","async","triggerFollowLogic","state","followRelated","followUpward","updateSubdivisionSelectFn","updateSubdivisionsFn","linkedCountrySelect","allSubs","subdivisionsMap","selectedCode","picked","find","s","related_country_code","targetCountry","targetSubdivision","related_subdivision_code","relatedSubsSelect","reason","is_subdivision_of","parentCode","parent_country_code","parentSub","subdivision_code","handleFollowRelatedFromSubdivision","handleFollowUpwardFromSubdivision","handleFollowUpwardFromCountry","countriesMap","linkedSubdivisionSelects","querySelectorAll","updateSubdivisionSelect","config","preselectedValue","isReload","has","isInitializing","add","effectiveCountryCode","valueSetByWidget","preferOfficialSubdivisions","subdivisionsResult","subdivisionsLanguage","set","subdivisionsLanguageMap","isMultiple","currentValue","hasUserSelection","userSelectionRestored","some","hasPreselectedValue","preselectedConsumed","preselectedSubdivision","subdivision","subdivisionToSelect","preselectedOption","directChildren","sub","firstChild","firstChildOption","grandChildren","sortedGrandChildren","countrySelect","updateSubdivisions","delete","getCurrentSubdivisionConfig","globalConfig","window","CountriesDBConfig","scriptUrl","loaderScript","getElementsByTagName","src","URL","parseBoolean","lowered","toLowerCase","searchParams","selectedCountry","NS_KEY","CountriesWidgetLoad","initialized","initPromise","version","eventHandlers","WeakMap","NS","reload","readyState","Promise","resolve","addEventListener","once","currentScript","HTMLScriptElement","publicKey","autoInit","countryNameFilterName","subdivisionNameFilterName","getConfigFromOptionsOrScript","countrySelects","remove","fixMisClassedElements","subdivisionSelects","showParamConflictError","Set","countryName","oldHandlers","update","removeEventListener","handlers","setupSubdivisionSelection","subdivisionConfig","seenNames","removeAttribute","loadedInitialSubdivisions","countriesResult","countriesLanguage","preselectedCountry","oldCountryHandlers","countryChange","countryChangeHandler","currentSubdivisionConfig","currentConfig","currentFollowUpward","countryHandlers","setupCountrySelection","checkAutoInit","shouldAutoInit","setTimeout","catch"],"mappings":"+OAGO,MAAMA,EAIT,2BAAaC,CAAeC,GACxB,MAAMC,OAAEA,EAAMC,WAAEA,EAAUC,eAAEA,GAAiB,EAAIC,gBAAEA,GAAkB,EAAKC,gBAAEA,EAAkB,CAAA,GAAQL,EAChGM,EAAO,GAAGJ,kBACVK,EAAS,GACVJ,GACDI,EAAOC,KAAK,cAEZJ,GACAG,EAAOC,KAAK,2BAEhB,MAAMC,EAAMF,EAAOG,OAAS,GAAGJ,KAAQC,EAAOI,KAAK,OAASL,EAC5D,OAAOM,KAAKC,aAAaJ,EAAKR,EAAQI,EAC1C,CAIA,8BAAaS,CAAkBd,GAC3B,MAAMC,OAAEA,EAAMC,WAAEA,EAAUa,YAAEA,EAAWZ,eAAEA,GAAiB,EAAIa,eAAEA,GAAiB,EAAKC,kCAAEA,EAAiCC,mBAAEA,GAAqB,EAAKb,gBAAEA,EAAkB,CAAA,GAAQL,EACjL,IAAKe,EACD,MAAO,CAAEI,KAAM,GAAIC,SAAU,MAEjC,MAAMd,EAAO,GAAGJ,mBAA4Ba,iBACtCR,EAAS,GACVJ,GAC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B,EAErB,MAAM9D,EAAiC,oBAAXC,QACvBA,OAAeC,mBAChB,KAEJ,GAAIF,QAAiD,IAA1BA,EAAa8B,SACtCgC,IAAmB9D,EAAa8B,cAC3B,GAAI1B,GAAgBA,EAAaE,IACtC,IACE,MACMwB,EADY,IAAIvB,IAAIH,EAAaE,KACZK,aAAatM,IAAI,aAE5CyP,EAA8B,OAAbhC,GAAkC,SAAbA,GAAoC,MAAbA,CAC/D,CAAE,MAEAgC,GAAiB,CACnB,CAIEA,GAEFC,WAAW,KACTjD,IAAsBkD,MAAM1P,QAAQH,QACnC,EAEN,CA1DD"}
1
+ {"version":3,"file":"index.js","sources":["../../widget-core/dist/esm/api-client.js","../../widget-core/dist/esm/subdivision-tree.js","../src/dom-manipulation.ts","../../widget-core/dist/esm/filters.js","../src/event-system.ts","../src/follow-logic.ts","../src/initialization.ts","../src/index.ts"],"sourcesContent":["/**\n * API client for CountriesDB API\n */\nexport class CountriesDBClient {\n /**\n * Fetch countries from the API\n */\n static async fetchCountries(options) {\n const { apiKey, backendUrl, shouldUseGeoIP = true, isoCountryNames = false, languageHeaders = {}, } = options;\n const base = `${backendUrl}/api/countries`;\n const params = [];\n if (!shouldUseGeoIP) {\n params.push('no_geoip=1');\n }\n if (isoCountryNames) {\n params.push('country_name_source=iso');\n }\n const url = params.length ? `${base}?${params.join('&')}` : base;\n return this.fetchFromApi(url, apiKey, languageHeaders);\n }\n /**\n * Fetch subdivisions for a specific country\n */\n static async fetchSubdivisions(options) {\n const { apiKey, backendUrl, countryCode, shouldUseGeoIP = true, preferOfficial = false, subdivisionRomanizationPreference, preferLocalVariant = false, languageHeaders = {}, } = options;\n if (!countryCode) {\n return { data: [], language: null };\n }\n const base = `${backendUrl}/api/countries/${countryCode}/subdivisions`;\n const params = [];\n if (!shouldUseGeoIP) {\n params.push('no_geoip=1');\n }\n if (subdivisionRomanizationPreference) {\n params.push(`subdivision_romanization_preference=${encodeURIComponent(subdivisionRomanizationPreference)}`);\n }\n if (preferLocalVariant) {\n params.push('prefer_local_variant=1');\n }\n if (preferOfficial) {\n params.push('prefer_official=1');\n }\n const url = params.length ? `${base}?${params.join('&')}` : base;\n return this.fetchFromApi(url, apiKey, languageHeaders);\n }\n /**\n * Generic API fetch method\n */\n static async fetchFromApi(url, apiKey, languageHeaders) {\n try {\n const response = await fetch(url, {\n headers: {\n ...languageHeaders,\n 'X-API-KEY': apiKey,\n 'Content-Type': 'application/json',\n },\n });\n if (!response.ok) {\n let errorMessage = `HTTP Error: ${response.status}`;\n try {\n const errorData = await response.json();\n // Check for error message in various formats (ApplicationException uses 'detail', others may use 'error' or 'message')\n if (errorData.detail) {\n errorMessage = errorData.detail;\n }\n else if (errorData.message) {\n errorMessage = errorData.message;\n }\n else if (errorData.error) {\n errorMessage = errorData.error;\n }\n }\n catch {\n // Ignore JSON parse errors\n }\n throw new Error(errorMessage);\n }\n const data = (await response.json());\n const language = response.headers.get('X-Selected-Language') || null;\n return { data, language };\n }\n catch (error) {\n console.error(`Failed to fetch data from ${url}:`, error);\n throw error;\n }\n }\n /**\n * Get language headers from browser and config\n */\n static getLanguageHeaders(forcedLanguage, defaultLanguage) {\n const headers = {};\n if (forcedLanguage) {\n headers['X-Forced-Language'] = forcedLanguage;\n }\n if (defaultLanguage) {\n headers['X-Default-Language'] = defaultLanguage;\n }\n // Use browser's language preference\n if (typeof navigator !== 'undefined' && navigator.language) {\n headers['Accept-Language'] = navigator.language;\n }\n else {\n headers['Accept-Language'] = 'en';\n }\n return headers;\n }\n}\n","/**\n * Utilities for building and working with subdivision trees\n */\n/**\n * Build a tree structure from a flat list of subdivisions\n */\nexport function buildSubdivisionTree(subdivisions) {\n const map = {};\n const roots = [];\n // Create map of all subdivisions\n subdivisions.forEach((item) => {\n map[item.id] = {\n ...item,\n children: [],\n };\n });\n // Build tree structure\n subdivisions.forEach((item) => {\n const node = map[item.id];\n if (item.parent_id && map[item.parent_id]) {\n map[item.parent_id].children.push(node);\n }\n else {\n roots.push(node);\n }\n });\n return roots;\n}\n/**\n * Flatten subdivision tree into HTML options\n */\nexport function flattenSubdivisionOptions(nodes, level, prefixes, labelKey, language, allowParentSelection, subdivisionNameFilter) {\n let html = '';\n // Apply name filter and get display names\n const nodesWithDisplayNames = nodes\n .map((node) => {\n let displayName = node[labelKey] || node.name;\n const countryCode = node.code ? node.code.split('-')[0] : null;\n // Apply subdivisionNameFilter if provided\n if (subdivisionNameFilter && typeof subdivisionNameFilter === 'function') {\n const filteredName = subdivisionNameFilter(node.code, displayName, language, countryCode, node);\n if (filteredName === false) {\n return null; // Mark for filtering - remove this item\n }\n if (filteredName !== null && filteredName !== undefined) {\n displayName = filteredName;\n }\n }\n return { ...node, _displayName: displayName };\n })\n .filter((node) => node !== null);\n // Sort: use Unicode-aware sorting if subdivisionNameFilter was used\n const locale = subdivisionNameFilter && typeof subdivisionNameFilter === 'function' && language\n ? language\n : undefined;\n nodesWithDisplayNames.sort((a, b) => {\n if (locale) {\n return a._displayName.localeCompare(b._displayName, locale, {\n sensitivity: 'accent', // Case-insensitive, accent-sensitive\n ignorePunctuation: false,\n });\n }\n return a._displayName.localeCompare(b._displayName); // Default behavior\n });\n const prefix = level > 0 ? (prefixes[level] ?? '&nbsp;'.repeat(level * 2)) : '';\n const cssClass = `subdivision-level-${level}`;\n for (const node of nodesWithDisplayNames) {\n const hasChildren = node.children && node.children.length > 0;\n const displayName = node._displayName;\n const label = `${prefix}${displayName}`;\n if (hasChildren) {\n if (allowParentSelection) {\n html += `<option value=\"${node.code}\" class=\"${cssClass}\">${label}</option>`;\n }\n else {\n html += `<option disabled value=\"${node.code}\" class=\"${cssClass}\">${label}</option>`;\n }\n html += flattenSubdivisionOptions(node.children, level + 1, prefixes, labelKey, language, allowParentSelection, subdivisionNameFilter);\n }\n else {\n html += `<option value=\"${node.code}\" class=\"${cssClass}\">${label}</option>`;\n }\n }\n return html;\n}\n/**\n * Parse nesting prefixes from data attributes\n */\nexport function parseNestingPrefixes(dataAttributes) {\n const prefixes = {};\n for (let lvl = 1; lvl <= 10; lvl++) {\n const key = `nested${lvl}Prefix`;\n const value = dataAttributes[key];\n if (value !== undefined) {\n prefixes[lvl] = value;\n }\n else {\n break;\n }\n }\n return prefixes;\n}\n","/**\n * DOM manipulation utilities\n */\n\nimport type { SelectElement } from './types';\nimport type { Country, Subdivision } from '@countriesdb/widget-core';\nimport {\n applyCountryNameFilter,\n sortCountries,\n buildSubdivisionTree,\n flattenSubdivisionOptions,\n parseNestingPrefixes,\n} from '@countriesdb/widget-core';\n\n/**\n * Initialize a select element with default option\n */\nexport function initializeSelect(\n select: SelectElement,\n fallbackLabel: string = 'Not Applicable',\n isSubdivision: boolean = false\n): void {\n const isMultiple = select.hasAttribute('multiple');\n\n // For multi-select, don't add default option or use data-label/data-default-value\n if (isMultiple) {\n select.innerHTML = '';\n // Remove data-label and data-default-value for multi-select (they're ignored)\n if (select.dataset.label !== undefined) {\n delete select.dataset.label;\n }\n if (select.dataset.defaultValue !== undefined) {\n delete select.dataset.defaultValue;\n }\n } else {\n const dataLabel = select.dataset.label;\n const dataDefaultValue = select.dataset.defaultValue;\n\n const label = dataLabel || fallbackLabel;\n const defaultValue = dataDefaultValue ?? '';\n select.innerHTML = `<option value=\"${defaultValue}\">${label}</option>`;\n\n if (dataLabel !== undefined) {\n select.dataset.label = dataLabel;\n }\n if (dataDefaultValue !== undefined) {\n select.dataset.defaultValue = dataDefaultValue;\n }\n }\n\n if (isSubdivision) {\n select.disabled = true;\n }\n}\n\n/**\n * Populate a select element with countries\n */\nexport function populateCountrySelect(\n select: SelectElement,\n countries: Country[],\n language: string,\n countryNameFilter?: (code: string, name: string, lang: string, item: Country) => string | false | null | undefined\n): void {\n // Apply filter and get display names\n let filteredCountries = applyCountryNameFilter(countries, countryNameFilter, language);\n \n // Sort if filter was applied\n if (countryNameFilter) {\n filteredCountries = sortCountries(filteredCountries, language);\n }\n\n // Check for multi-select using both attribute and property\n const isMultiple = select.hasAttribute('multiple') || select.multiple;\n \n if (isMultiple) {\n // For multi-select, don't add default option (like old widget)\n select.innerHTML = '';\n } else {\n // Clear existing options (except default)\n const defaultOption = select.querySelector('option[value=\"\"]') || \n (select.dataset.defaultValue ? select.querySelector(`option[value=\"${select.dataset.defaultValue}\"]`) : null);\n const defaultValue = select.dataset.defaultValue ?? '';\n \n // Keep default option if it exists\n select.innerHTML = defaultOption ? defaultOption.outerHTML : `<option value=\"${defaultValue}\">${select.dataset.label || '&mdash;'}</option>`;\n }\n\n // Add country options\n filteredCountries.forEach((country) => {\n const option = document.createElement('option');\n option.value = country.iso_alpha_2;\n option.textContent = country._displayName;\n select.appendChild(option);\n });\n}\n\n/**\n * Populate a select element with subdivisions\n */\nexport function buildSubdivisionOptionsHTML(\n subdivisions: Subdivision[],\n select: SelectElement,\n language: string,\n showSubdivisionType: boolean,\n allowParentSelection: boolean,\n subdivisionNameFilter?: (\n code: string,\n originalName: string,\n language: string,\n countryCode: string | null,\n item: Subdivision\n ) => string | false | null | undefined\n): string {\n const tree = buildSubdivisionTree(subdivisions);\n \n // Parse nesting prefixes from data attributes\n const dataAttributes: Record<string, string | undefined> = {};\n for (let lvl = 1; lvl <= 10; lvl++) {\n const key = `nested${lvl}Prefix`;\n const value = select.dataset[key];\n if (value !== undefined) {\n dataAttributes[`nested${lvl}Prefix`] = value;\n } else {\n break;\n }\n }\n const prefixes = parseNestingPrefixes(dataAttributes);\n \n const isMultiple = select.hasAttribute('multiple');\n const labelKey = showSubdivisionType ? 'full_name' : 'name';\n\n let html = '';\n // For multi-select, don't add default option\n if (!isMultiple) {\n const defaultLabel = select.dataset.label || '&mdash;';\n const defaultValue = select.dataset.defaultValue ?? '';\n html = `<option value=\"${defaultValue}\">${defaultLabel}</option>`;\n }\n\n html += flattenSubdivisionOptions(\n tree,\n 0,\n prefixes,\n labelKey,\n language,\n allowParentSelection,\n subdivisionNameFilter\n );\n \n return html;\n}\n\n/**\n * Apply preselected value to a select element\n * Like old widget, reads the value from the select element itself to get current state\n */\nexport function applyPreselectedValue(\n select: SelectElement,\n apiKey?: string\n): void {\n // Read from select element like old widget (line 740)\n const tempOnce = select.dataset._widgetTempPreselect;\n const permanent = select.getAttribute('data-preselected') || select.dataset.preselected;\n const hasTemp = tempOnce !== undefined && tempOnce !== null && String(tempOnce).trim() !== '';\n const chosen = hasTemp ? tempOnce : permanent;\n \n if (!chosen || (typeof chosen === 'string' && chosen.trim() === '')) {\n return;\n }\n\n const value = String(chosen);\n const isMultiple = select.hasAttribute('multiple');\n\n if (isMultiple) {\n // For multi-select, parse comma-separated values\n const values = value\n .split(',')\n .map((v) => v.trim())\n .filter((v) => v !== '');\n // Select all matching options\n Array.from(select.options).forEach((option) => {\n option.selected = values.includes(option.value);\n });\n } else {\n // Single select: set single value\n select.value = value;\n }\n \n // Consume temp preselect so it's only applied once (like old widget)\n // Note: We keep data-preselected attribute to support reload: true\n if (select.dataset._widgetTempPreselect !== undefined) {\n delete select.dataset._widgetTempPreselect;\n }\n \n // Mark permanent preselect as consumed after first application\n // This prevents it from being reapplied on user-initiated country changes\n // But reload: true will clear this flag to allow reapplication\n if (permanent !== undefined && permanent !== null && String(permanent).trim() !== '') {\n select.dataset._widgetPreselectedConsumed = '1';\n }\n}\n\n/**\n * Handle API error by showing error message in select\n */\nexport function handleApiError(\n select: SelectElement,\n errorMessage: string | Error,\n replace: boolean = false\n): void {\n const message = errorMessage instanceof Error ? errorMessage.message : errorMessage;\n const defaultValue = select.dataset.defaultValue ?? '';\n // Add \"Error: \" prefix to match old widget behavior and test expectations\n const formattedMessage = message.startsWith('Error: ') ? message : `Error: ${message}`;\n if (replace) {\n select.innerHTML = `<option value=\"${defaultValue}\" disabled>${formattedMessage}</option>`;\n } else {\n select.innerHTML += `<option value=\"${defaultValue}\" disabled>${formattedMessage}</option>`;\n }\n}\n\n/**\n * Parse boolean from string value\n */\nexport function parseBoolean(value: string | null | undefined): boolean {\n if (value === null || value === undefined) {\n return false;\n }\n const lowered = String(value).trim().toLowerCase();\n return !(lowered === '0' || lowered === 'false');\n}\n\n","/**\n * Name filtering utilities\n */\n/**\n * Apply country name filter to a list of countries\n */\nexport function applyCountryNameFilter(countries, filter, language) {\n if (!filter || typeof filter !== 'function') {\n return countries.map((c) => ({ ...c, _displayName: c.name }));\n }\n return countries\n .map((country) => {\n const filteredName = filter(country.iso_alpha_2, country.name, language, country);\n if (filteredName === false) {\n return null; // Skip this item\n }\n const displayName = filteredName !== null && filteredName !== undefined\n ? filteredName\n : country.name;\n return { ...country, _displayName: displayName };\n })\n .filter((c) => c !== null);\n}\n/**\n * Sort countries with Unicode-aware sorting\n */\nexport function sortCountries(countries, language) {\n const locale = language || undefined;\n return [...countries].sort((a, b) => {\n if (locale) {\n return a._displayName.localeCompare(b._displayName, locale, {\n sensitivity: 'accent', // Case-insensitive, accent-sensitive\n ignorePunctuation: false,\n });\n }\n return a._displayName.localeCompare(b._displayName);\n });\n}\n/**\n * Apply subdivision name filter to a list of subdivisions\n */\nexport function applySubdivisionNameFilter(subdivisions, filter, language, countryCode) {\n if (!filter || typeof filter !== 'function') {\n return subdivisions.map((s) => ({\n ...s,\n _displayName: s.full_name || s.name,\n }));\n }\n return subdivisions\n .map((subdivision) => {\n const originalName = subdivision.full_name || subdivision.name;\n const filteredName = filter(subdivision.code, originalName, language, countryCode, subdivision);\n if (filteredName === false) {\n return null; // Skip this item\n }\n const displayName = filteredName !== null && filteredName !== undefined\n ? filteredName\n : originalName;\n return { ...subdivision, _displayName: displayName };\n })\n .filter((s) => s !== null);\n}\n","/**\n * Event system for widget updates\n */\n\nimport type {\n ReadyEventDetail,\n SelectElement,\n UpdateEventDetail,\n} from './types';\n\n/**\n * Dispatch a custom update event for widget changes\n */\nexport function dispatchUpdateEvent(\n select: SelectElement,\n detail: Partial<UpdateEventDetail> = {}\n): void {\n let selectedValues: string[] = [];\n \n if (select.multiple) {\n // For multi-select, selectedOptions is a HTMLCollection, convert to array\n selectedValues = Array.from(select.selectedOptions || [])\n .map((opt) => opt.value)\n .filter((v) => v !== '');\n } else {\n // For single-select, use value\n selectedValues = select.value ? [select.value] : [];\n }\n\n const evt = new CustomEvent<UpdateEventDetail>('countriesWidget:update', {\n bubbles: true,\n detail: {\n value: select.value || '',\n selectedValues,\n name: select.dataset.name || null,\n country: select.dataset.country || null,\n isSubdivision: select.classList.contains('subdivision-selection'),\n ...detail,\n },\n });\n \n select.dispatchEvent(evt);\n}\n\n/**\n * Dispatch a custom ready event once a select has been populated.\n */\nexport function dispatchReadyEvent(\n select: SelectElement,\n detail: Partial<ReadyEventDetail> = {}\n): void {\n const selectedValues = select.multiple\n ? Array.from(select.selectedOptions || [])\n .map((opt) => opt.value)\n .filter((v) => v !== '')\n : select.value\n ? [select.value]\n : [];\n\n const evt = new CustomEvent<ReadyEventDetail>('countriesWidget:ready', {\n bubbles: true,\n detail: {\n value: select.value || '',\n selectedValues,\n name: select.dataset.name || null,\n country: select.dataset.country || null,\n isSubdivision: select.classList.contains('subdivision-selection'),\n type: select.classList.contains('subdivision-selection')\n ? 'subdivision'\n : 'country',\n phase: 'initial',\n ...detail,\n },\n });\n\n select.dispatchEvent(evt);\n}\n\n/**\n * Check if an event was initiated by the widget (not user)\n */\nexport function isWidgetInitiatedEvent(event: Event): boolean {\n return (event as any).isWidgetInitiated === true;\n}\n\n/**\n * Mark an event as widget-initiated\n */\nexport function markEventAsWidgetInitiated(event: Event): void {\n (event as any).isWidgetInitiated = true;\n}\n\n","/**\n * Follow logic for related and upward navigation\n */\n\nimport type { SelectElement, WidgetState } from './types';\nimport type { Subdivision } from '@countriesdb/widget-core';\nimport { dispatchUpdateEvent } from './event-system';\nimport { CountriesDBClient } from '@countriesdb/widget-core';\nimport { updateSubdivisionSelect } from './initialization';\n\n/**\n * Trigger follow logic when a subdivision is selected\n */\nexport async function triggerFollowLogic(\n select: SelectElement,\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n followRelated: boolean,\n followUpward: boolean,\n updateSubdivisionSelectFn: (\n select: SelectElement,\n apiKey: string,\n countryCode: string\n ) => Promise<void>,\n updateSubdivisionsFn?: (\n countrySelect: SelectElement,\n apiKey: string\n ) => Promise<void>\n): Promise<void> {\n if (!followRelated && !followUpward) {\n return;\n }\n\n const linkedCountrySelect = document.querySelector<SelectElement>(\n `.country-selection[data-name=\"${select.dataset.country}\"]`\n );\n \n // Only work if country is single-select (never when country is multi)\n if (!linkedCountrySelect || linkedCountrySelect.multiple) {\n return;\n }\n\n const allSubs = state.subdivisionsMap.get(select);\n if (!allSubs) {\n return;\n }\n\n // For follow_upward, only work if subdivision is single-select\n if (followUpward && select.multiple) {\n return;\n }\n\n const selectedCode = select.value;\n if (!selectedCode) {\n return;\n }\n\n const picked = allSubs.find((s) => s.code === selectedCode);\n if (!picked) {\n return;\n }\n\n // follow_related\n if (followRelated && picked.related_country_code) {\n const targetCountry = picked.related_country_code;\n const targetSubdivision = picked.related_subdivision_code;\n\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n \n if (relatedSubsSelect && targetSubdivision) {\n relatedSubsSelect.dataset._widgetTempPreselect = targetSubdivision; // one-time preselect\n }\n\n if (linkedCountrySelect.value !== targetCountry) {\n // Directly set value like old widget did\n linkedCountrySelect.value = targetCountry;\n dispatchUpdateEvent(linkedCountrySelect, { type: 'country', reason: 'regular' });\n // Update all subdivision selects for the new country (like old widget)\n if (updateSubdivisionsFn) {\n await updateSubdivisionsFn(linkedCountrySelect, apiKey);\n } else if (relatedSubsSelect) {\n // Fallback: update just the one subdivision select\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, targetCountry);\n }\n } else {\n if (relatedSubsSelect && targetSubdivision) {\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, targetCountry);\n }\n }\n }\n\n // follow_upward\n if (followUpward && picked.is_subdivision_of) {\n const parentCode = picked.is_subdivision_of.parent_country_code;\n const parentSub = picked.is_subdivision_of.subdivision_code;\n\n if (parentSub) {\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n // Only preselect if subdivision is single-select (follow_upward doesn't work with multi)\n if (relatedSubsSelect && !relatedSubsSelect.multiple) {\n relatedSubsSelect.dataset._widgetTempPreselect = parentSub; // one-time preselect\n }\n }\n\n if (linkedCountrySelect.value !== parentCode) {\n // Directly set value like old widget did\n linkedCountrySelect.value = parentCode;\n dispatchUpdateEvent(linkedCountrySelect, { type: 'country', reason: 'regular' });\n // Update all subdivision selects for the new country (like old widget)\n if (updateSubdivisionsFn) {\n await updateSubdivisionsFn(linkedCountrySelect, apiKey);\n } else {\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n if (relatedSubsSelect) {\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, parentCode);\n }\n }\n } else if (parentSub) {\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n if (relatedSubsSelect && !relatedSubsSelect.multiple) {\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, parentCode);\n }\n }\n }\n}\n\n/**\n * Handle follow_related from subdivision change event\n */\nexport async function handleFollowRelatedFromSubdivision(\n select: SelectElement,\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n followRelated: boolean,\n updateSubdivisionSelectFn: (\n select: SelectElement,\n apiKey: string,\n countryCode: string\n ) => Promise<void>\n): Promise<void> {\n if (!followRelated) {\n return;\n }\n\n const linkedCountrySelect = document.querySelector<SelectElement>(\n `.country-selection[data-name=\"${select.dataset.country}\"]`\n );\n \n // Only work if country is single-select (never when country is multi)\n if (!linkedCountrySelect || linkedCountrySelect.multiple) {\n return;\n }\n\n const allSubs = state.subdivisionsMap.get(select);\n if (!allSubs) {\n return;\n }\n\n // Get selected code (for multi-select, use first selected value)\n const selectedCode = select.multiple\n ? (select.selectedOptions[0]?.value || null)\n : select.value;\n \n if (!selectedCode) {\n return;\n }\n\n const picked = allSubs.find((s) => s.code === selectedCode);\n if (!picked || !picked.related_country_code) {\n return;\n }\n\n const targetCountry = picked.related_country_code;\n const targetSubdivision = picked.related_subdivision_code;\n\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n \n if (relatedSubsSelect && targetSubdivision) {\n relatedSubsSelect.dataset.preselected = targetSubdivision;\n }\n\n if (linkedCountrySelect.value !== targetCountry) {\n // Directly set value like old widget did\n linkedCountrySelect.value = targetCountry;\n dispatchUpdateEvent(linkedCountrySelect, { type: 'country', reason: 'regular' });\n // Update all subdivision selects for the new country (like old widget)\n // Note: updateSubdivisionsFn is not available in handleFollowRelatedFromSubdivision,\n // so we update the subdivision select manually\n if (relatedSubsSelect) {\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, targetCountry);\n }\n } else {\n if (relatedSubsSelect && targetSubdivision) {\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, targetCountry);\n }\n }\n}\n\n/**\n * Handle follow_upward from subdivision change event\n */\nexport async function handleFollowUpwardFromSubdivision(\n select: SelectElement,\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n followUpward: boolean,\n updateSubdivisionSelectFn: (\n select: SelectElement,\n apiKey: string,\n countryCode: string\n ) => Promise<void>\n): Promise<void> {\n if (!followUpward) {\n return;\n }\n \n // Disable for multi-select subdivisions\n if (select.multiple) {\n return;\n }\n\n const linkedCountrySelect = document.querySelector<SelectElement>(\n `.country-selection[data-name=\"${select.dataset.country}\"]`\n );\n \n // Only work if country is single-select (never when country is multi)\n if (!linkedCountrySelect || linkedCountrySelect.multiple) {\n return;\n }\n\n const allSubs = state.subdivisionsMap.get(select);\n if (!allSubs) {\n return;\n }\n\n const selectedCode = select.value;\n if (!selectedCode) {\n return;\n }\n\n const picked = allSubs.find((s) => s.code === selectedCode);\n if (!picked || !picked.is_subdivision_of) {\n return;\n }\n\n const parentCode = picked.is_subdivision_of.parent_country_code;\n const parentSub = picked.is_subdivision_of.subdivision_code;\n\n if (parentSub) {\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n if (relatedSubsSelect) {\n relatedSubsSelect.dataset.preselected = parentSub;\n }\n }\n\n if (linkedCountrySelect.value !== parentCode) {\n // Directly set value like old widget did\n linkedCountrySelect.value = parentCode;\n dispatchUpdateEvent(linkedCountrySelect, { type: 'country', reason: 'follow' });\n // Update all subdivision selects for the new country (like old widget)\n // Note: updateSubdivisionsFn is not available in handleFollowUpwardFromSubdivision,\n // so we update the subdivision select manually\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n if (relatedSubsSelect) {\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, parentCode);\n }\n } else if (parentSub) {\n const relatedSubsSelect = document.querySelector<SelectElement>(\n `.subdivision-selection[data-country=\"${linkedCountrySelect.dataset.name}\"]`\n );\n if (relatedSubsSelect) {\n await updateSubdivisionSelectFn(relatedSubsSelect, apiKey, parentCode);\n }\n }\n}\n\n/**\n * Handle follow_upward from country change event\n */\nexport async function handleFollowUpwardFromCountry(\n select: SelectElement,\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n followUpward: boolean,\n updateSubdivisionSelectFn: (\n select: SelectElement,\n apiKey: string,\n countryCode: string\n ) => Promise<void>\n): Promise<void> {\n // Only works when country is single-select (never for multi-select)\n if (!followUpward || select.multiple) {\n return;\n }\n\n const countries = state.countriesMap.get(select);\n if (!countries) {\n return;\n }\n\n const chosen = select.value;\n if (!chosen) {\n return;\n }\n\n const picked = countries.find((c) => c.iso_alpha_2 === chosen);\n if (!picked || !picked.is_subdivision_of) {\n return;\n }\n\n const parentCode = picked.is_subdivision_of.parent_country_code;\n const parentSub = picked.is_subdivision_of.subdivision_code;\n\n if (select.value !== parentCode) {\n if (parentSub) {\n const linkedSubdivisionSelects = Array.from(\n document.querySelectorAll<SelectElement>(\n `.subdivision-selection[data-country=\"${select.dataset.name}\"]`\n )\n );\n for (const s of linkedSubdivisionSelects) {\n // Only preselect if subdivision is single-select (follow_upward doesn't work with multi)\n if (!s.multiple) {\n s.dataset.preselected = parentSub;\n }\n }\n }\n // Directly set value like old widget did\n select.value = parentCode;\n dispatchUpdateEvent(select, { type: 'country', reason: 'regular' });\n // Update all subdivision selects for the new country (like old widget)\n // Note: updateSubdivisionsFn is not available in handleFollowUpwardFromCountry,\n // so we update all subdivision selects manually\n const linkedSubdivisionSelects = Array.from(\n document.querySelectorAll<SelectElement>(\n `.subdivision-selection[data-country=\"${select.dataset.name}\"]`\n )\n );\n for (const s of linkedSubdivisionSelects) {\n await updateSubdivisionSelectFn(s, apiKey, parentCode);\n }\n } else if (parentSub) {\n const linkedSubdivisionSelects = Array.from(\n document.querySelectorAll<SelectElement>(\n `.subdivision-selection[data-country=\"${select.dataset.name}\"]`\n )\n );\n for (const s of linkedSubdivisionSelects) {\n // Only update if subdivision is single-select\n if (!s.multiple) {\n await updateSubdivisionSelectFn(s, apiKey, parentCode);\n }\n }\n }\n}\n\n","/**\n * Widget initialization logic\n */\n\nimport type { SelectElement, WidgetState, EventHandlers } from './types';\nimport type { Country, Subdivision } from '@countriesdb/widget-core';\nimport { CountriesDBClient } from '@countriesdb/widget-core';\nimport {\n initializeSelect,\n populateCountrySelect,\n buildSubdivisionOptionsHTML,\n applyPreselectedValue,\n handleApiError,\n parseBoolean,\n} from './dom-manipulation';\nimport {\n dispatchReadyEvent,\n dispatchUpdateEvent,\n isWidgetInitiatedEvent,\n} from './event-system';\nimport {\n triggerFollowLogic,\n handleFollowRelatedFromSubdivision,\n handleFollowUpwardFromSubdivision,\n handleFollowUpwardFromCountry,\n} from './follow-logic';\n\n/**\n * Setup subdivision selection elements\n */\nexport async function setupSubdivisionSelection(\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n config: {\n followRelated: boolean;\n followUpward: boolean;\n showSubdivisionType: boolean;\n allowParentSelection: boolean;\n preferOfficialSubdivisions: boolean;\n subdivisionRomanizationPreference?: string;\n preferLocalVariant: boolean;\n subdivisionNameFilter?: (\n code: string,\n originalName: string,\n language: string,\n countryCode: string | null,\n item: Subdivision\n ) => string | false | null | undefined;\n }\n): Promise<void> {\n const subdivisionSelects = Array.from(\n document.querySelectorAll<SelectElement>('.subdivision-selection')\n );\n\n for (const select of subdivisionSelects) {\n // Initialize with a default option\n initializeSelect(select, '&mdash;', true);\n\n // Linked country select (if any)\n const countryName = select.dataset.country;\n const linkedCountrySelect = countryName\n ? document.querySelector<SelectElement>(\n `.country-selection[data-name=\"${countryName}\"]`\n )\n : null;\n\n // Check if linked country select is multi-select (not allowed)\n if (linkedCountrySelect && linkedCountrySelect.hasAttribute('multiple')) {\n const defaultValue = select.dataset.defaultValue ?? '';\n select.innerHTML = `<option value=\"${defaultValue}\" disabled>Error: Cannot link to multi-select country. Use data-country-code instead.</option>`;\n continue;\n }\n\n // No direct link → maybe data-country-code\n if (!countryName || !linkedCountrySelect) {\n if (\n select.hasAttribute('data-country-code') &&\n select.dataset.countryCode\n ) {\n await updateSubdivisionSelect(\n select,\n apiKey,\n backendUrl,\n state,\n config,\n select.dataset.countryCode\n );\n } else {\n const defaultValue = select.dataset.defaultValue ?? '';\n select.innerHTML += `<option value=\"${defaultValue}\" disabled>Error: No country select present</option>`;\n }\n }\n\n // Remove old event handlers if they exist (for re-initialization)\n const oldHandlers = state.eventHandlers.get(select);\n if (oldHandlers) {\n if (oldHandlers.update) {\n select.removeEventListener('change', oldHandlers.update);\n }\n if (oldHandlers.followRelated) {\n select.removeEventListener('change', oldHandlers.followRelated);\n }\n if (oldHandlers.followUpward) {\n select.removeEventListener('change', oldHandlers.followUpward);\n }\n }\n\n // Create new event handlers\n const handlers: EventHandlers = {};\n\n // Always dispatch an update event for user-initiated subdivision changes\n handlers.update = (event: Event) => {\n if (isWidgetInitiatedEvent(event)) {\n return;\n }\n dispatchUpdateEvent(select, { type: 'subdivision', reason: 'regular' });\n };\n select.addEventListener('change', handlers.update);\n\n // --- follow_related (forward direction) ---\n handlers.followRelated = async (event: Event) => {\n if (isWidgetInitiatedEvent(event)) {\n return;\n }\n await handleFollowRelatedFromSubdivision(\n select,\n apiKey,\n backendUrl,\n state,\n config.followRelated,\n (s, key, code) =>\n updateSubdivisionSelect(s, key, backendUrl, state, config, code)\n );\n };\n select.addEventListener('change', handlers.followRelated);\n\n // --- follow_upward (reverse direction) ---\n handlers.followUpward = async (event: Event) => {\n if (isWidgetInitiatedEvent(event)) {\n return;\n }\n await handleFollowUpwardFromSubdivision(\n select,\n apiKey,\n backendUrl,\n state,\n config.followUpward,\n (s, key, code) =>\n updateSubdivisionSelect(s, key, backendUrl, state, config, code)\n );\n };\n select.addEventListener('change', handlers.followUpward);\n\n // Store handlers for future cleanup\n state.eventHandlers.set(select, handlers);\n }\n}\n\n/**\n * Update subdivision select with data for a specific country\n */\nexport async function updateSubdivisionSelect(\n select: SelectElement,\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n config: {\n followRelated: boolean;\n followUpward: boolean;\n showSubdivisionType: boolean;\n allowParentSelection: boolean;\n preferOfficialSubdivisions: boolean;\n subdivisionRomanizationPreference?: string;\n preferLocalVariant: boolean;\n forcedLanguage?: string;\n defaultLanguage?: string;\n subdivisionNameFilter?: (\n code: string,\n originalName: string,\n language: string,\n countryCode: string | null,\n item: Subdivision\n ) => string | false | null | undefined;\n },\n countryCode: string\n): Promise<void> {\n const preselectedValue =\n select.getAttribute('data-preselected') || select.dataset.preselected;\n\n // Check if this is a reload (select was already populated before)\n const isReload = state.subdivisionsMap.has(select);\n\n initializeSelect(select, '&mdash;', true);\n\n // Mark as initializing to prevent change events\n state.isInitializing.add(select);\n\n let effectiveCountryCode = countryCode;\n if (!effectiveCountryCode) {\n effectiveCountryCode = select.dataset.countryCode || '';\n }\n\n if (effectiveCountryCode) {\n let valueSetByWidget = false; // Track if a value was set by widget\n try {\n // Use GeoIP only if data-preselected attribute is not set at all\n const shouldUseGeoIP =\n preselectedValue === undefined || preselectedValue === null;\n\n // Check if this subdivision select prefers official subdivisions\n // Use data attribute if present, otherwise use config\n const preferOfficial = select.hasAttribute('data-prefer-official') \n ? true \n : config.preferOfficialSubdivisions;\n\n const languageHeaders = CountriesDBClient.getLanguageHeaders(\n config.forcedLanguage,\n config.defaultLanguage\n );\n\n const subdivisionsResult = await CountriesDBClient.fetchSubdivisions({\n apiKey,\n backendUrl,\n countryCode: effectiveCountryCode,\n shouldUseGeoIP,\n preferOfficial,\n subdivisionRomanizationPreference: config.subdivisionRomanizationPreference,\n preferLocalVariant: config.preferLocalVariant,\n languageHeaders,\n });\n\n const subdivisions = subdivisionsResult.data;\n const subdivisionsLanguage = subdivisionsResult.language || 'en';\n\n // Store in memory\n state.subdivisionsMap.set(select, subdivisions);\n state.subdivisionsLanguageMap.set(select, subdivisionsLanguage);\n\n if (subdivisions.length > 0) {\n // Populate <option>\n select.disabled = false;\n\n // Preserve data attributes before setting innerHTML (only for non-multi-select)\n const isMultiple = select.hasAttribute('multiple');\n const dataLabel = !isMultiple ? select.dataset.label : undefined;\n const dataDefaultValue = !isMultiple\n ? select.dataset.defaultValue\n : undefined;\n\n // Preserve user's current selection before clearing innerHTML\n // This prevents preselected values from overwriting user selections\n const currentValue = select.value;\n const defaultValue = select.dataset.defaultValue || '';\n const hasUserSelection = currentValue && currentValue !== defaultValue && currentValue.trim() !== '';\n\n select.innerHTML = buildSubdivisionOptionsHTML(\n subdivisions,\n select,\n subdivisionsLanguage,\n config.showSubdivisionType,\n config.allowParentSelection,\n config.subdivisionNameFilter\n );\n\n // Restore data attributes after setting innerHTML\n if (!isMultiple) {\n if (dataLabel !== undefined) {\n select.dataset.label = dataLabel;\n }\n if (dataDefaultValue !== undefined) {\n select.dataset.defaultValue = dataDefaultValue;\n }\n }\n\n // Restore user's selection if it exists in the new options (user selection takes priority)\n let userSelectionRestored = false;\n if (hasUserSelection && !isMultiple) {\n const optionExists = Array.from(select.options).some(opt => opt.value === currentValue);\n if (optionExists) {\n select.value = currentValue;\n userSelectionRestored = true;\n // Don't dispatch event here - user already selected it, no need to notify again\n }\n }\n\n // Manual preselection only if user hasn't selected anything\n if (!userSelectionRestored) {\n // Check if preselected value exists (applyPreselectedValue will read it from select element)\n const hasPreselectedValue = \n (select.getAttribute('data-preselected') || select.dataset.preselected || select.dataset._widgetTempPreselect) !== undefined;\n const preselectedConsumed = select.dataset._widgetPreselectedConsumed === '1';\n \n // Only apply preselected if:\n // 1. It exists AND\n // 2. Either it hasn't been consumed yet, OR this is the initial load (not a reload)\n // This prevents reapplying preselected values on user-initiated country changes\n // But allows them on initial load and on reload: true (which clears the consumed flag)\n if (hasPreselectedValue && (!preselectedConsumed || !isReload)) {\n applyPreselectedValue(select, apiKey);\n dispatchUpdateEvent(select, {\n type: 'subdivision',\n reason: 'preselected',\n });\n valueSetByWidget = true;\n await triggerFollowLogic(\n select,\n apiKey,\n backendUrl,\n state,\n config.followRelated,\n config.followUpward,\n (s, key, code) =>\n updateSubdivisionSelect(s, key, backendUrl, state, config, code),\n (countrySelect, key) =>\n updateSubdivisions(countrySelect, key, backendUrl, state, config)\n );\n } else {\n // Try GeoIP preselect (only if user hasn't selected anything)\n if (shouldUseGeoIP) {\n const preselectedSubdivision = subdivisions.find(\n (subdivision) => subdivision.preselected\n );\n if (preselectedSubdivision) {\n const isMultiple = select.hasAttribute('multiple');\n let subdivisionToSelect = preselectedSubdivision;\n \n // If preselected is disabled and allowParentSelection is false, find first enabled child\n if (!config.allowParentSelection && !isMultiple) {\n const preselectedOption = Array.from(select.options).find(\n (opt) => opt.value === preselectedSubdivision.code\n );\n \n if (preselectedOption?.disabled) {\n // Find direct children by parent_id\n const directChildren = subdivisions.filter(\n (sub) => sub.parent_id === preselectedSubdivision.id\n );\n \n if (directChildren.length > 0) {\n // Sort by name and get first child\n const sorted = directChildren.sort((a, b) => {\n return (a.name || '').localeCompare(b.name || '', subdivisionsLanguage, { sensitivity: 'accent' });\n });\n \n const firstChild = sorted[0];\n \n // Check if first child is also disabled (has its own children)\n const firstChildOption = Array.from(select.options).find(\n (opt) => opt.value === firstChild.code\n );\n \n if (firstChildOption?.disabled) {\n // First child is disabled, find its first child (grandchild)\n const grandChildren = subdivisions.filter(\n (sub) => sub.parent_id === firstChild.id\n );\n if (grandChildren.length > 0) {\n const sortedGrandChildren = grandChildren.sort((a, b) => {\n return (a.name || '').localeCompare(b.name || '', subdivisionsLanguage, { sensitivity: 'accent' });\n });\n subdivisionToSelect = sortedGrandChildren[0];\n } else {\n subdivisionToSelect = firstChild;\n }\n } else {\n subdivisionToSelect = firstChild;\n }\n }\n }\n }\n \n if (isMultiple) {\n // For multi-select, find and select the option\n const option = Array.from(select.options).find(\n (opt) => opt.value === subdivisionToSelect.code\n );\n if (option) {\n option.selected = true;\n }\n } else {\n // Single select: set value directly\n select.value = subdivisionToSelect.code;\n }\n dispatchUpdateEvent(select, {\n type: 'subdivision',\n reason: 'geoip',\n });\n valueSetByWidget = true;\n await triggerFollowLogic(\n select,\n apiKey,\n backendUrl,\n state,\n config.followRelated,\n config.followUpward,\n (s, key, code) =>\n updateSubdivisionSelect(s, key, backendUrl, state, config, code),\n (countrySelect, key) =>\n updateSubdivisions(countrySelect, key, backendUrl, state, config)\n );\n }\n }\n }\n }\n } else {\n select.disabled = true;\n }\n } catch (error) {\n console.error('Failed to fetch subdivisions:', error);\n handleApiError(select, error as Error);\n } finally {\n // Mark initialization as complete\n state.isInitializing.delete(select);\n dispatchReadyEvent(select, {\n type: 'subdivision',\n phase: isReload ? 'reload' : 'initial',\n });\n // Only fire 'reload' if this is a reload, not initial load\n if (isReload && !valueSetByWidget) {\n dispatchUpdateEvent(select, {\n type: 'subdivision',\n reason: 'reload',\n });\n }\n }\n } else if (\n !select.dataset.country ||\n !document.querySelector(\n `.country-selection[data-name=\"${select.dataset.country}\"]`\n )\n ) {\n const defaultValue = select.dataset.defaultValue ?? '';\n select.innerHTML += `<option value=\"${defaultValue}\" disabled>Error: No country select present</option>`;\n }\n}\n\n/**\n * Get current subdivision config from window.CountriesDBConfig and script URL\n * This ensures we always use the latest config values, even after widget reload\n */\nfunction getCurrentSubdivisionConfig(apiKey: string, backendUrl: string): {\n followRelated: boolean;\n followUpward: boolean;\n showSubdivisionType: boolean;\n allowParentSelection: boolean;\n preferOfficialSubdivisions: boolean;\n subdivisionRomanizationPreference?: string;\n preferLocalVariant: boolean;\n forcedLanguage?: string;\n defaultLanguage?: string;\n subdivisionNameFilter?: (\n code: string,\n originalName: string,\n language: string,\n countryCode: string | null,\n item: Subdivision\n ) => string | false | null | undefined;\n} {\n const globalConfig = typeof window !== 'undefined' && (window as any).CountriesDBConfig\n ? (window as any).CountriesDBConfig\n : null;\n\n // Also check script URL parameters (for backward compatibility and reload scenarios)\n let scriptUrl: URL | null = null;\n try {\n const scripts = Array.from(document.getElementsByTagName('script'));\n const loaderScript = scripts.find((s) => \n s.src && (\n s.src.includes('@countriesdb/widget') ||\n s.src.includes('widget/dist/index.js')\n )\n ) as HTMLScriptElement || null;\n \n if (loaderScript && loaderScript.src) {\n scriptUrl = new URL(loaderScript.src);\n }\n } catch {\n // Ignore errors\n }\n\n // Import parseBoolean from dom-manipulation\n const parseBoolean = (value: string | null | undefined): boolean => {\n if (value === null || value === undefined) {\n return false;\n }\n const lowered = String(value).trim().toLowerCase();\n return !(lowered === '0' || lowered === 'false');\n };\n\n return {\n followRelated: globalConfig?.followRelated !== undefined\n ? globalConfig.followRelated\n : parseBoolean(scriptUrl?.searchParams.get('follow_related') ?? 'false'),\n followUpward: globalConfig?.followUpward !== undefined\n ? globalConfig.followUpward\n : parseBoolean(scriptUrl?.searchParams.get('follow_upward') ?? 'false'),\n showSubdivisionType: globalConfig?.showSubdivisionType !== undefined\n ? globalConfig.showSubdivisionType\n : parseBoolean(scriptUrl?.searchParams.get('show_subdivision_type') ?? '1'),\n allowParentSelection: globalConfig?.allowParentSelection !== undefined\n ? globalConfig.allowParentSelection\n : parseBoolean(scriptUrl?.searchParams.get('allow_parent_selection') ?? 'false'),\n preferOfficialSubdivisions: globalConfig?.preferOfficialSubdivisions !== undefined\n ? globalConfig.preferOfficialSubdivisions\n : parseBoolean(scriptUrl?.searchParams.get('prefer_official') ?? 'false'),\n subdivisionRomanizationPreference: globalConfig?.subdivisionRomanizationPreference ||\n scriptUrl?.searchParams.get('subdivision_romanization_preference') ||\n undefined,\n preferLocalVariant: globalConfig?.preferLocalVariant !== undefined\n ? globalConfig.preferLocalVariant\n : parseBoolean(scriptUrl?.searchParams.get('prefer_local_variant') ?? 'false'),\n forcedLanguage: globalConfig?.forcedLanguage ||\n scriptUrl?.searchParams.get('forced_language') ||\n undefined,\n defaultLanguage: globalConfig?.defaultLanguage ||\n scriptUrl?.searchParams.get('default_language') ||\n undefined,\n subdivisionNameFilter: globalConfig?.subdivisionNameFilter,\n };\n}\n\n/**\n * Update subdivisions for all linked subdivision selects when country changes\n */\nexport async function updateSubdivisions(\n countrySelect: SelectElement,\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n config: {\n followRelated: boolean;\n followUpward: boolean;\n showSubdivisionType: boolean;\n allowParentSelection: boolean;\n preferOfficialSubdivisions: boolean;\n subdivisionRomanizationPreference?: string;\n preferLocalVariant: boolean;\n forcedLanguage?: string;\n defaultLanguage?: string;\n subdivisionNameFilter?: (\n code: string,\n originalName: string,\n language: string,\n countryCode: string | null,\n item: Subdivision\n ) => string | false | null | undefined;\n }\n): Promise<void> {\n // Don't update subdivisions for multi-select countries (not supported)\n if (countrySelect.hasAttribute('multiple')) {\n return;\n }\n\n const selectedCountry = countrySelect.value;\n const linkedSubdivisionSelects = Array.from(\n document.querySelectorAll<SelectElement>(\n `.subdivision-selection[data-country=\"${countrySelect.dataset.name}\"]`\n )\n );\n\n for (const select of linkedSubdivisionSelects) {\n await updateSubdivisionSelect(\n select,\n apiKey,\n backendUrl,\n state,\n config,\n selectedCountry\n );\n }\n}\n\n/**\n * Setup country selection elements\n */\nexport async function setupCountrySelection(\n apiKey: string,\n backendUrl: string,\n state: WidgetState,\n config: {\n defaultLanguage?: string;\n forcedLanguage?: string;\n isoCountryNames: boolean;\n followRelated: boolean;\n followUpward: boolean;\n countryNameFilter?: (\n code: string,\n name: string,\n language: string,\n item: Country\n ) => string | false | null | undefined;\n },\n subdivisionConfig: {\n followRelated: boolean;\n followUpward: boolean;\n showSubdivisionType: boolean;\n allowParentSelection: boolean;\n preferOfficialSubdivisions: boolean;\n subdivisionRomanizationPreference?: string;\n preferLocalVariant: boolean;\n subdivisionNameFilter?: (\n code: string,\n originalName: string,\n language: string,\n countryCode: string | null,\n item: Subdivision\n ) => string | false | null | undefined;\n }\n): Promise<void> {\n const countrySelects = Array.from(\n document.querySelectorAll<SelectElement>('.country-selection')\n );\n const seenNames: Record<string, boolean> = {}; // track data-name to detect duplicates\n\n for (const select of countrySelects) {\n const name = select.dataset.name;\n\n // Duplicates\n if (name && seenNames[name]) {\n select.removeAttribute('data-name');\n initializeSelect(select, '&mdash;');\n const defaultValue = select.dataset.defaultValue ?? '';\n select.innerHTML += `<option value=\"${defaultValue}\" disabled>Error: Duplicate field</option>`;\n continue;\n }\n if (name) {\n seenNames[name] = true;\n }\n\n // Note: Class renaming is now handled earlier in fixMisClassedElements()\n // This check is kept as a safety net but should not be needed\n\n // Initialize\n initializeSelect(select, '&mdash;');\n\n // Mark as initializing to prevent change events\n state.isInitializing.add(select);\n\n let valueSetByWidget = false; // Track if value was set by widget\n let loadedInitialSubdivisions = false; // Track if subdivisions were loaded\n\n try {\n const preselectedValue =\n select.getAttribute('data-preselected') || select.dataset.preselected;\n // Use GeoIP only if data-preselected attribute is not set at all\n const shouldUseGeoIP =\n preselectedValue === undefined || preselectedValue === null;\n\n const languageHeaders = CountriesDBClient.getLanguageHeaders(\n config.forcedLanguage,\n config.defaultLanguage\n );\n\n // Fetch & populate countries\n const countriesResult = await CountriesDBClient.fetchCountries({\n apiKey,\n backendUrl,\n shouldUseGeoIP,\n isoCountryNames: config.isoCountryNames,\n languageHeaders,\n });\n\n const countries = countriesResult.data;\n const countriesLanguage = countriesResult.language || 'en';\n\n state.countriesMap.set(select, countries);\n populateCountrySelect(\n select,\n countries,\n countriesLanguage,\n config.countryNameFilter\n );\n\n // Apply preselected (manual)\n // Check if preselected value exists (applyPreselectedValue will read it from select element)\n const hasPreselectedValue = \n (select.getAttribute('data-preselected') || select.dataset.preselected || select.dataset._widgetTempPreselect) !== undefined;\n if (hasPreselectedValue) {\n applyPreselectedValue(select, apiKey);\n dispatchUpdateEvent(select, { type: 'country', reason: 'preselected' });\n valueSetByWidget = true;\n // Load subdivisions after applying preselected value\n if (\n select.value &&\n select.value !== (select.dataset.defaultValue || '')\n ) {\n // This will be handled by the updateSubdivisions call below\n // We need to pass the config for subdivisions\n }\n }\n\n // GeoIP auto-select\n if (shouldUseGeoIP) {\n const preselectedCountry = countries.find(\n (country) => country.preselected\n );\n if (preselectedCountry) {\n select.value = preselectedCountry.iso_alpha_2;\n dispatchUpdateEvent(select, { type: 'country', reason: 'geoip' });\n valueSetByWidget = true;\n }\n }\n\n // If already chosen, load subdivisions\n if (\n !loadedInitialSubdivisions &&\n select.value &&\n select.value !== (select.dataset.defaultValue || '')\n ) {\n // Subdivisions will be loaded by event handler\n loadedInitialSubdivisions = true;\n }\n\n // Remove old event handlers if they exist (for re-initialization)\n const oldCountryHandlers = state.eventHandlers.get(select);\n if (oldCountryHandlers?.countryChange) {\n select.removeEventListener('change', oldCountryHandlers.countryChange);\n }\n\n // Create new country change handler\n const countryChangeHandler = async (event: Event) => {\n if (isWidgetInitiatedEvent(event)) {\n return;\n }\n\n // Dispatch update event for user-initiated country change\n dispatchUpdateEvent(select, { type: 'country', reason: 'regular' });\n\n // Get current config dynamically to ensure we use the latest values\n const currentSubdivisionConfig = getCurrentSubdivisionConfig(apiKey, backendUrl);\n const currentConfig = typeof window !== 'undefined' && (window as any).CountriesDBConfig\n ? (window as any).CountriesDBConfig\n : config;\n\n // Update subdivisions with current config\n await updateSubdivisions(select, apiKey, backendUrl, state, currentSubdivisionConfig);\n\n const chosen = select.value;\n if (!chosen) {\n return;\n }\n\n const stored = state.countriesMap.get(select) || [];\n const picked = stored.find((c) => c.iso_alpha_2 === chosen);\n if (!picked) {\n return;\n }\n\n // followUpward from country perspective\n // Only works when country is single-select (never for multi-select)\n const currentFollowUpward = currentConfig?.followUpward || false;\n if (currentFollowUpward && !select.multiple && picked.is_subdivision_of) {\n await handleFollowUpwardFromCountry(\n select,\n apiKey,\n backendUrl,\n state,\n currentFollowUpward,\n (s, key, code) =>\n updateSubdivisionSelect(s, key, backendUrl, state, currentSubdivisionConfig, code)\n );\n }\n };\n\n // Store and attach the handler\n const countryHandlers = state.eventHandlers.get(select) || {};\n countryHandlers.countryChange = countryChangeHandler;\n state.eventHandlers.set(select, countryHandlers);\n select.addEventListener('change', countryChangeHandler);\n } catch (error) {\n console.error('Failed to fetch countries:', error);\n handleApiError(select, error as Error);\n // Handle subdivision errors\n if (select.dataset.name) {\n const linkedSubdivisionSelects = Array.from(\n document.querySelectorAll<SelectElement>(\n `.subdivision-selection[data-country=\"${select.dataset.name}\"]`\n )\n );\n for (const s of linkedSubdivisionSelects) {\n initializeSelect(s, '&mdash;');\n handleApiError(s, error as Error);\n }\n }\n } finally {\n // Mark initialization as complete\n state.isInitializing.delete(select);\n dispatchReadyEvent(select, {\n type: 'country',\n phase: 'initial',\n });\n // If no preselected and no geoip selection happened, emit a regular update\n if (!valueSetByWidget) {\n dispatchUpdateEvent(select, { type: 'country', reason: 'regular' });\n }\n }\n }\n}\n\n","/**\n * @countriesdb/widget\n * \n * Plain JavaScript widget for CountriesDB.\n * Provides DOM manipulation and auto-initialization for country/subdivision selects.\n */\n\nimport type { WidgetOptions } from './types';\nimport type { WidgetConfig } from '@countriesdb/widget-core';\nimport { setupCountrySelection, setupSubdivisionSelection, updateSubdivisions } from './initialization';\nimport type { SelectElement, WidgetState, EventHandlers } from './types';\n\n// Global namespace to prevent double initialization\nconst NS_KEY = '__CountriesWidgetNS__';\n\ninterface WidgetNamespace {\n initialized: boolean;\n initPromise: Promise<boolean> | null;\n version: number;\n eventHandlers: WeakMap<SelectElement, EventHandlers>;\n}\n\ndeclare global {\n interface Window {\n [NS_KEY]: WidgetNamespace;\n CountriesWidgetLoad: typeof CountriesWidgetLoad;\n }\n}\n\n/**\n * Main widget initialization function\n */\nasync function CountriesWidgetLoad(\n options: WidgetOptions = {} as WidgetOptions\n): Promise<boolean> {\n // Initialize namespace\n if (!window[NS_KEY]) {\n window[NS_KEY] = {\n initialized: false,\n initPromise: null,\n version: 0,\n eventHandlers: new WeakMap<SelectElement, EventHandlers>(),\n };\n }\n\n const NS = window[NS_KEY];\n \n // Ensure eventHandlers exists (for backwards compatibility)\n if (!NS.eventHandlers) {\n NS.eventHandlers = new WeakMap<SelectElement, EventHandlers>();\n }\n\n // Handle reload option - reset state to force re-initialization\n const shouldReload = (options as any).reload === true;\n if (shouldReload) {\n NS.initialized = false;\n NS.initPromise = null;\n \n // Clear consumed preselected flags to allow preselected values to be reapplied on reload: true\n // This ensures full reload behavior where preselected values are reapplied\n if (typeof document !== 'undefined') {\n const subdivisionSelects = document.querySelectorAll('.subdivision-selection');\n subdivisionSelects.forEach((select) => {\n if ((select as HTMLElement).dataset._widgetPreselectedConsumed) {\n delete (select as HTMLElement).dataset._widgetPreselectedConsumed;\n }\n });\n }\n }\n\n // Share the same promise across concurrent calls\n NS.initPromise = (async () => {\n // Wait for DOM if needed\n if (document.readyState === 'loading') {\n await new Promise<void>((resolve) => {\n document.addEventListener('DOMContentLoaded', () => resolve(), {\n once: true,\n });\n });\n }\n\n // Get configuration from options or script URL\n const config = getConfigFromOptionsOrScript(options);\n\n // Fix mis-classed elements early (DOM cleanup that should always happen)\n fixMisClassedElements();\n\n // Check for conflicting parameters\n if (config.followRelated && config.followUpward) {\n showParamConflictError();\n return false;\n }\n\n // Initialize widget state\n // Use global eventHandlers from namespace so we can clean up old handlers on re-initialization\n const state: WidgetState = {\n countriesMap: new WeakMap(),\n subdivisionsMap: new WeakMap(),\n subdivisionsLanguageMap: new WeakMap(),\n isInitializing: new Set(),\n eventHandlers: NS.eventHandlers, // Use global WeakMap that persists across calls\n };\n\n // Use empty string if publicKey is missing (will show error when API calls fail)\n const apiKey = config.publicKey || '';\n\n // Setup subdivisions first (they depend on countries)\n await setupSubdivisionSelection(apiKey, config.backendUrl, state, {\n followRelated: config.followRelated || false,\n followUpward: config.followUpward || false,\n showSubdivisionType: config.showSubdivisionType !== false,\n allowParentSelection: config.allowParentSelection || false,\n preferOfficialSubdivisions: config.preferOfficialSubdivisions || false,\n subdivisionRomanizationPreference: config.subdivisionRomanizationPreference,\n preferLocalVariant: config.preferLocalVariant || false,\n subdivisionNameFilter: config.subdivisionNameFilter,\n });\n\n const subdivisionConfig = {\n followRelated: config.followRelated || false,\n followUpward: config.followUpward || false,\n showSubdivisionType: config.showSubdivisionType !== false,\n allowParentSelection: config.allowParentSelection || false,\n preferOfficialSubdivisions: config.preferOfficialSubdivisions || false,\n subdivisionRomanizationPreference: config.subdivisionRomanizationPreference,\n preferLocalVariant: config.preferLocalVariant || false,\n forcedLanguage: config.forcedLanguage,\n defaultLanguage: config.defaultLanguage,\n subdivisionNameFilter: config.subdivisionNameFilter,\n };\n\n // Setup countries\n await setupCountrySelection(\n apiKey,\n config.backendUrl,\n state,\n {\n defaultLanguage: config.defaultLanguage,\n forcedLanguage: config.forcedLanguage,\n isoCountryNames: config.isoCountryNames || false,\n followRelated: config.followRelated || false,\n followUpward: config.followUpward || false,\n countryNameFilter: config.countryNameFilter,\n },\n subdivisionConfig\n );\n\n // After countries are set up, update subdivisions for any preselected countries\n const countrySelects = Array.from(\n document.querySelectorAll<SelectElement>('.country-selection')\n );\n for (const select of countrySelects) {\n if (\n select.value &&\n select.value !== (select.dataset.defaultValue || '')\n ) {\n await updateSubdivisions(select, apiKey, config.backendUrl, state, subdivisionConfig);\n }\n }\n\n NS.initialized = true;\n return true;\n })();\n\n return NS.initPromise;\n}\n\n/**\n * Get configuration from options or script URL parameters\n */\nfunction getConfigFromOptionsOrScript(\n options: WidgetOptions\n): WidgetConfig & { backendUrl: string } {\n // Check for global config first (for bundled widgets that need config before auto-init)\n const globalConfig = typeof window !== 'undefined' && (window as any).CountriesDBConfig\n ? (window as any).CountriesDBConfig\n : null;\n \n // Try to get config from script URL (for backward compatibility with widget.blade.php)\n let scriptUrl: URL | null = null;\n try {\n let loaderScript: HTMLScriptElement | null = null;\n \n // First try document.currentScript (works during script execution)\n // But only if it matches the widget pattern (not a bundled file)\n if (document.currentScript && document.currentScript instanceof HTMLScriptElement) {\n const src = document.currentScript.src;\n if (src && (src.includes('@countriesdb/widget') || src.includes('widget/dist/index.js'))) {\n loaderScript = document.currentScript;\n }\n }\n \n // If currentScript didn't match, search for widget script\n if (!loaderScript) {\n const scripts = Array.from(document.getElementsByTagName('script'));\n loaderScript = scripts.find((s) => \n s.src && (\n s.src.includes('@countriesdb/widget') ||\n s.src.includes('widget/dist/index.js')\n )\n ) as HTMLScriptElement || null;\n }\n \n if (loaderScript && loaderScript.src) {\n scriptUrl = new URL(loaderScript.src);\n }\n } catch {\n // Ignore errors\n }\n\n const config: WidgetConfig & { backendUrl: string } = {\n // Priority: options > globalConfig > scriptUrl params > defaults\n publicKey: options.publicKey ?? globalConfig?.publicKey ?? scriptUrl?.searchParams.get('public_key') ?? '',\n backendUrl: options.backendUrl ?? globalConfig?.backendUrl ?? scriptUrl?.searchParams.get('backend_url') ?? getDefaultBackendUrl(),\n defaultLanguage: options.defaultLanguage ?? globalConfig?.defaultLanguage ?? scriptUrl?.searchParams.get('default_language') ?? undefined,\n forcedLanguage: options.forcedLanguage ?? globalConfig?.forcedLanguage ?? scriptUrl?.searchParams.get('forced_language') ?? undefined,\n showSubdivisionType: options.showSubdivisionType !== undefined\n ? options.showSubdivisionType\n : globalConfig?.showSubdivisionType !== undefined\n ? globalConfig.showSubdivisionType\n : parseBoolean(scriptUrl?.searchParams.get('show_subdivision_type') ?? '1'),\n followRelated: options.followRelated !== undefined\n ? options.followRelated\n : globalConfig?.followRelated !== undefined\n ? globalConfig.followRelated\n : parseBoolean(scriptUrl?.searchParams.get('follow_related') ?? 'false'),\n followUpward: options.followUpward !== undefined\n ? options.followUpward\n : globalConfig?.followUpward !== undefined\n ? globalConfig.followUpward\n : parseBoolean(scriptUrl?.searchParams.get('follow_upward') ?? 'false'),\n allowParentSelection: options.allowParentSelection !== undefined\n ? options.allowParentSelection\n : globalConfig?.allowParentSelection !== undefined\n ? globalConfig.allowParentSelection\n : parseBoolean(scriptUrl?.searchParams.get('allow_parent_selection') ?? 'false'),\n isoCountryNames: options.isoCountryNames !== undefined\n ? options.isoCountryNames\n : globalConfig?.isoCountryNames !== undefined\n ? globalConfig.isoCountryNames\n : parseBoolean(scriptUrl?.searchParams.get('iso_country_names') ?? 'false'),\n subdivisionRomanizationPreference:\n options.subdivisionRomanizationPreference ||\n globalConfig?.subdivisionRomanizationPreference ||\n scriptUrl?.searchParams.get('subdivision_romanization_preference') ||\n undefined,\n preferLocalVariant: options.preferLocalVariant !== undefined\n ? options.preferLocalVariant\n : globalConfig?.preferLocalVariant !== undefined\n ? globalConfig.preferLocalVariant\n : parseBoolean(scriptUrl?.searchParams.get('prefer_local_variant') ?? 'false'),\n preferOfficialSubdivisions: options.preferOfficialSubdivisions !== undefined\n ? options.preferOfficialSubdivisions\n : globalConfig?.preferOfficialSubdivisions !== undefined\n ? globalConfig.preferOfficialSubdivisions\n : parseBoolean(scriptUrl?.searchParams.get('prefer_official') ?? 'false'),\n countryNameFilter: options.countryNameFilter ?? globalConfig?.countryNameFilter,\n subdivisionNameFilter: options.subdivisionNameFilter ?? globalConfig?.subdivisionNameFilter,\n autoInit: options.autoInit !== undefined\n ? options.autoInit\n : globalConfig?.autoInit !== undefined\n ? globalConfig.autoInit\n : parseBoolean(scriptUrl?.searchParams.get('auto_init') ?? 'true'),\n };\n\n // Resolve filter functions from global scope if specified by name\n if (scriptUrl) {\n const countryNameFilterName = scriptUrl.searchParams.get('countryNameFilter');\n if (countryNameFilterName && typeof window !== 'undefined') {\n const filter = (window as any)[countryNameFilterName];\n if (typeof filter === 'function') {\n config.countryNameFilter = filter;\n }\n }\n\n const subdivisionNameFilterName = scriptUrl.searchParams.get('subdivisionNameFilter');\n if (subdivisionNameFilterName && typeof window !== 'undefined') {\n const filter = (window as any)[subdivisionNameFilterName];\n if (typeof filter === 'function') {\n config.subdivisionNameFilter = filter;\n }\n }\n }\n\n return config;\n}\n\n/**\n * Get default backend URL\n */\nfunction getDefaultBackendUrl(): string {\n // Always default to API domain\n // Users should explicitly set backendUrl if they need a custom one\n return 'https://api.countriesdb.com';\n}\n\n/**\n * Fix mis-classed elements (e.g., country-selection with subdivision-selection class)\n * This should happen early, before API calls, as it's just DOM cleanup\n */\nfunction fixMisClassedElements(): void {\n const countrySelects = Array.from(\n document.querySelectorAll<HTMLSelectElement>('.country-selection')\n );\n \n for (const select of countrySelects) {\n // Avoid conflict if mis-classed\n if (select.classList.contains('subdivision-selection')) {\n select.classList.remove('subdivision-selection');\n select.classList.add('subdivision-selection-removed');\n }\n }\n}\n\n/**\n * Parse boolean from string value\n */\nfunction parseBoolean(value: string | null | undefined): boolean {\n if (value === null || value === undefined) {\n return false;\n }\n const lowered = String(value).trim().toLowerCase();\n return !(lowered === '0' || lowered === 'false');\n}\n\n/**\n * Show error when both follow_related and follow_upward are enabled\n */\nfunction showParamConflictError(): void {\n const errorMessage = 'Error: Cannot enable both follow_related and follow_upward';\n const countrySelects = Array.from(\n document.querySelectorAll<SelectElement>('.country-selection')\n );\n for (const select of countrySelects) {\n select.innerHTML = `<option value=\"${select.dataset.defaultValue ?? ''}\" disabled>${errorMessage}</option>`;\n }\n const subdivisionSelects = Array.from(\n document.querySelectorAll<SelectElement>('.subdivision-selection')\n );\n for (const select of subdivisionSelects) {\n select.innerHTML = `<option value=\"${select.dataset.defaultValue ?? ''}\" disabled>${errorMessage}</option>`;\n }\n}\n\n// Expose public loader\nif (typeof window !== 'undefined') {\n window.CountriesWidgetLoad = CountriesWidgetLoad;\n\n // Auto-init if script URL has auto_init=true (or not set, default is true)\n // Use a function that waits for DOM to be ready and finds the script tag reliably\n (function checkAutoInit() {\n // Wait for DOM to be ready\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', checkAutoInit, { once: true });\n return;\n }\n\n // Find the script tag that loaded this widget\n let loaderScript: HTMLScriptElement | null = null;\n \n // First try document.currentScript (works during script execution)\n // But only if it matches the widget pattern (not a bundled file)\n if (document.currentScript && document.currentScript instanceof HTMLScriptElement) {\n const src = document.currentScript.src;\n if (src && (src.includes('@countriesdb/widget') || src.includes('widget/dist/index.js'))) {\n loaderScript = document.currentScript;\n }\n }\n \n // If currentScript didn't match, search for widget script\n if (!loaderScript) {\n const scripts = Array.from(document.getElementsByTagName('script'));\n loaderScript = scripts.find((s) => \n s.src && (\n s.src.includes('@countriesdb/widget') ||\n s.src.includes('widget/dist/index.js')\n )\n ) as HTMLScriptElement || null;\n }\n \n // Default to auto-init = true (only disable if explicitly set to false)\n let shouldAutoInit = true;\n \n const globalConfig = typeof window !== 'undefined'\n ? (window as any).CountriesDBConfig || null\n : null;\n \n if (globalConfig && typeof globalConfig.autoInit !== 'undefined') {\n shouldAutoInit = !!globalConfig.autoInit;\n } else if (loaderScript && loaderScript.src) {\n try {\n const scriptUrl = new URL(loaderScript.src);\n const autoInit = scriptUrl.searchParams.get('auto_init');\n // Only disable if explicitly set to false/0\n shouldAutoInit = autoInit === null || autoInit === 'true' || autoInit === '1';\n } catch {\n // If URL parsing fails, default to true (auto-init enabled)\n shouldAutoInit = true;\n }\n }\n \n // Auto-init by default (unless explicitly disabled)\n if (shouldAutoInit) {\n // Use setTimeout to ensure script tag is fully processed\n setTimeout(() => {\n CountriesWidgetLoad().catch(console.error);\n }, 0);\n }\n })();\n}\n\n// Export for ES modules\nexport default CountriesWidgetLoad;\n\n"],"names":["CountriesDBClient","fetchCountries","options","apiKey","backendUrl","shouldUseGeoIP","isoCountryNames","languageHeaders","base","params","push","url","length","join","this","fetchFromApi","fetchSubdivisions","countryCode","preferOfficial","subdivisionRomanizationPreference","preferLocalVariant","data","language","encodeURIComponent","response","fetch","headers","ok","errorMessage","status","errorData","json","detail","message","error","Error","get","console","getLanguageHeaders","forcedLanguage","defaultLanguage","navigator","flattenSubdivisionOptions","nodes","level","prefixes","labelKey","allowParentSelection","subdivisionNameFilter","html","nodesWithDisplayNames","map","node","displayName","name","code","split","filteredName","_displayName","filter","locale","undefined","sort","a","b","localeCompare","sensitivity","ignorePunctuation","prefix","repeat","cssClass","hasChildren","children","label","initializeSelect","select","fallbackLabel","isSubdivision","hasAttribute","innerHTML","dataset","defaultValue","dataLabel","dataDefaultValue","disabled","populateCountrySelect","countries","countryNameFilter","filteredCountries","country","iso_alpha_2","c","applyCountryNameFilter","sortCountries","multiple","defaultOption","querySelector","outerHTML","forEach","option","document","createElement","value","textContent","appendChild","buildSubdivisionOptionsHTML","subdivisions","showSubdivisionType","tree","roots","item","id","parent_id","buildSubdivisionTree","dataAttributes","lvl","key","parseNestingPrefixes","defaultLabel","applyPreselectedValue","tempOnce","_widgetTempPreselect","permanent","getAttribute","preselected","chosen","String","trim","values","v","Array","from","selected","includes","_widgetPreselectedConsumed","handleApiError","replace","formattedMessage","startsWith","dispatchUpdateEvent","selectedValues","selectedOptions","opt","evt","CustomEvent","bubbles","classList","contains","dispatchEvent","dispatchReadyEvent","type","phase","isWidgetInitiatedEvent","event","isWidgetInitiated","async","triggerFollowLogic","state","followRelated","followUpward","updateSubdivisionSelectFn","updateSubdivisionsFn","linkedCountrySelect","allSubs","subdivisionsMap","selectedCode","picked","find","s","related_country_code","targetCountry","targetSubdivision","related_subdivision_code","relatedSubsSelect","reason","is_subdivision_of","parentCode","parent_country_code","parentSub","subdivision_code","handleFollowRelatedFromSubdivision","handleFollowUpwardFromSubdivision","handleFollowUpwardFromCountry","countriesMap","linkedSubdivisionSelects","querySelectorAll","updateSubdivisionSelect","config","preselectedValue","isReload","has","isInitializing","add","effectiveCountryCode","valueSetByWidget","preferOfficialSubdivisions","subdivisionsResult","subdivisionsLanguage","set","subdivisionsLanguageMap","isMultiple","currentValue","hasUserSelection","userSelectionRestored","some","hasPreselectedValue","preselectedConsumed","preselectedSubdivision","subdivision","subdivisionToSelect","preselectedOption","directChildren","sub","firstChild","firstChildOption","grandChildren","sortedGrandChildren","countrySelect","updateSubdivisions","delete","getCurrentSubdivisionConfig","globalConfig","window","CountriesDBConfig","scriptUrl","loaderScript","getElementsByTagName","src","URL","parseBoolean","lowered","toLowerCase","searchParams","selectedCountry","NS_KEY","CountriesWidgetLoad","initialized","initPromise","version","eventHandlers","WeakMap","NS","reload","readyState","Promise","resolve","addEventListener","once","currentScript","HTMLScriptElement","publicKey","autoInit","countryNameFilterName","subdivisionNameFilterName","getConfigFromOptionsOrScript","countrySelects","remove","fixMisClassedElements","subdivisionSelects","showParamConflictError","Set","countryName","oldHandlers","update","removeEventListener","handlers","setupSubdivisionSelection","subdivisionConfig","seenNames","removeAttribute","loadedInitialSubdivisions","countriesResult","countriesLanguage","preselectedCountry","oldCountryHandlers","countryChange","countryChangeHandler","currentSubdivisionConfig","currentConfig","currentFollowUpward","countryHandlers","setupCountrySelection","checkAutoInit","shouldAutoInit","setTimeout","catch"],"mappings":"+OAGO,MAAMA,EAIT,2BAAaC,CAAeC,GACxB,MAAMC,OAAEA,EAAMC,WAAEA,EAAUC,eAAEA,GAAiB,EAAIC,gBAAEA,GAAkB,EAAKC,gBAAEA,EAAkB,CAAA,GAAQL,EAChGM,EAAO,GAAGJ,kBACVK,EAAS,GACVJ,GACDI,EAAOC,KAAK,cAEZJ,GACAG,EAAOC,KAAK,2BAEhB,MAAMC,EAAMF,EAAOG,OAAS,GAAGJ,KAAQC,EAAOI,KAAK,OAASL,EAC5D,OAAOM,KAAKC,aAAaJ,EAAKR,EAAQI,EAC1C,CAIA,8BAAaS,CAAkBd,GAC3B,MAAMC,OAAE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J,SAASoJ,yBAAyBC,kBAAmB,CACjF,MAAMtB,EAAM/H,SAASoJ,cAAcrB,IAC/BA,IAAQA,EAAI9F,SAAS,wBAA0B8F,EAAI9F,SAAS,2BAC9D4F,EAAe7H,SAASoJ,cAE5B,CAGA,IAAKvB,EAAc,CAEjBA,EADgB/F,MAAMC,KAAK/B,SAAS8H,qBAAqB,WAClC3D,KAAMC,GAC3BA,EAAE2D,MACA3D,EAAE2D,IAAI9F,SAAS,wBACfmC,EAAE2D,IAAI9F,SAAS,2BAEO,IAC5B,CAGA,IAAIsJ,GAAiB,EAErB,MAAM9D,EAAiC,oBAAXC,QACvBA,OAAeC,mBAChB,KAEJ,GAAIF,QAAiD,IAA1BA,EAAa8B,SACtCgC,IAAmB9D,EAAa8B,cAC3B,GAAI1B,GAAgBA,EAAaE,IACtC,IACE,MACMwB,EADY,IAAIvB,IAAIH,EAAaE,KACZK,aAAapM,IAAI,aAE5CuP,EAA8B,OAAbhC,GAAkC,SAAbA,GAAoC,MAAbA,CAC/D,CAAE,MAEAgC,GAAiB,CACnB,CAIEA,GAEFC,WAAW,KACTjD,IAAsBkD,MAAMxP,QAAQH,QACnC,EAEN,CA1DD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@countriesdb/widget",
3
- "version": "0.1.36",
3
+ "version": "1.0.1",
4
4
  "description": "Country and state/province select widget with ISO 3166-1 and ISO 3166-2 codes. Auto-populates dropdowns with up-to-date country and subdivision data in multiple languages. Easy integration for forms, location selection, and address validation.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.esm.js",
@@ -46,7 +46,7 @@
46
46
  "license": "PROPRIETARY",
47
47
  "homepage": "https://countriesdb.com",
48
48
  "dependencies": {
49
- "@countriesdb/widget-core": "*"
49
+ "@countriesdb/widget-core": "^1.0.1"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@rollup/plugin-alias": "^6.0.0",