const e=require("plugin-error"),t=require("through2"),n=require("find-cache-dir"),o=require("vinyl"),s=require("fontkit"),r=require("path"),a=require("fs"),c=require("node-fetch"),i=require("object-hash"),l=require("url");var f="undefined"!=typeof document?document.currentScript:null;function u(e){return e&&"object"==typeof e&&"default"in e?e.default:e}const p=u(e),g=u(t),m=u(n),h=u(o),d=u(r),y=u(a),j=u(c),w=u(i),F="gulp-local-fonts",S=m({name:F}),x={cache:!0,google:{},nodeFetchOptions:{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"}},createdJsFiles:!0},$={url:"https://fonts.googleapis.com/css",display:"swap",text:"abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789,.!?&%$#@;:/|\\'\"`^{}[]()<>+=*~",subset:!1,effect:!1},N={100:["Thin","Hairline"],200:["Extra Light","Ultra Light"],300:["Light"],400:["Regular",""],500:["Medium"],600:["Semi Bold","Demi Bold"],700:["Bold"],800:["Extra Bold","Ultra Bold"],900:["Black","Heavy"]};function b(e){const t=v;return"file:"===new c.Request(e,t).url.substring(0,5)?new Promise(((t,n)=>{const o=d.normalize(e.substring(8));y.existsSync(o)||n(`File not found: ${o}`);const s=y.createReadStream(o);s.on("open",(function(){t(new c.Response(s,{status:200,statusText:"OK",headers:{"Content-Length":y.statSync(o).size.toString()}}))}))})):j(e,t)}let v,R;function C(e,t,n){return n.indexOf(e)===t}function q(){return R}function U(e,t,n,o,s){const r=e.matchAll(/@font-face\s*{[^}]+}/g);return Array.from(r,(e=>e[0])).map((e=>(t.forEach((function(t){const r=n[t],a=o[t],c=s[t],i=new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");i.test(e)&&(e=function(e,t,n){if(!/local\(/.test(e)){const o=/font-weight:\s*(\d+);/.exec(e),s=parseInt(o&&o[1]||"0",10);if(N[s]){const n=/font-style:\s*italic;/.test(e)?"Italic":"",o=[],r=function(e,t){for(const n of N[t]){const t=new RegExp(n,"i");if(n&&t.test(e))return n;const o=n.replace(/ +/g,"-");if(new RegExp(o,"i").test(e))return o}return""}(t,s);if(r){B(t.replace(r,"").replace(/^\s+|\s+$/g,""),n,r,o)}else for(const e of N[s])B(t,n,e,o);e=e.replace(/src:\s+url/g,`src: ${o.join(", ")}, url`)}else{const t=n.includes(" ")?"'":"";e=e.replace(/src:\s+url/g,`src: local(${t}${n}${t}), url`)}}return e}(e=e.replace(i,r),a,c))})),e))).join("\r\n")+"\r\n"}function E(e){const t=e.matchAll(/url\((?['"]?)(?[^)"']+?)(\??#[^)"']+)?\k\)/g);return Array.from(t,(e=>e.groups.uri)).filter(C)}async function k(e){const t=[],n={},o={},a={};return await Promise.all(e.filter(C).map((async e=>{const{fontFile:c,fontFilePath:i,fontFamilyName:l,fontFullName:f}=await async function(e){let t,n,o,a;const c=/^https?:\/\//.test(e),i=await b(c?e:"file:///"+e);i.ok||q().emit("error",new p(F,`Failed to load font from ${e}. Status text: ${i.statusText}.`));const l=Buffer.from(await i.arrayBuffer());try{const c=s.create(l);t=`.${c.type.toLowerCase()}`;const i=r.basename(e,t);n=c.postscriptName||i,o=c.familyName||i,a=c.fullName||i}catch(s){t=r.extname(e);const c=r.basename(e,t);n=c,o=c,a=c}let f;f=c?n.replace(/[\s_-]+/g,"-").replace(/[^a-zA-Z0-9-]/g,""):r.basename(e,t);const u=`${f}${t}`;return{fontFile:new h({path:u,contents:l}),fontFilePath:u,fontFamilyName:o,fontFullName:a}}(e);t.push(c),a[e]=i,n[e]=l,o[e]=f}))),{fontFiles:t,fontFamilyNames:n,fontFullNames:o,fontPaths:a}}async function L(e,t,n,o){return o?o({js:e,fileName:t,css:n}):e}function A(e,t,n=""){const o=`${e} ${n} ${t}`.replace(/ +/g," ").trim(),s=o.includes(" ")?"'":"";return`local(${s}${o}${s})`}function B(e,t,n,o){const s=A(e,t,n);if(o.push(s),s.includes(" ")&&o.push(s.replace(/ +/g,"-").replace(/["']/g,"")),e.includes(" ")){const s=A(e.replace(/ +/g,""),t,n);o.push(s),s.includes(" ")&&o.push(s.replace(/ +/g,"-").replace(/["']/g,""))}if(n.includes(" ")){const s=A(e,t,n.replace(/ +/g,""));o.push(s),s.includes(" ")&&o.push(s.replace(/ +/g,"-").replace(/["']/g,""))}if(e.includes(" ")&&n.includes(" ")){const s=A(e.replace(/ +/g,""),t,n.replace(/ +/g,""));o.push(s),s.includes(" ")&&o.push(s.replace(/ +/g,"-").replace(/["']/g,""))}if(t){const s=A(e,n.replace(/ +/g,"")+t);if(o.push(s),s.includes(" ")&&o.push(s.replace(/ +/g,"-").replace(/["']/g,"")),e.includes(" ")){const s=A(e.replace(/ +/g,""),n.replace(/ +/g,"")+t);o.push(s),s.includes(" ")&&o.push(s.replace(/ +/g,"-").replace(/["']/g,""))}}}async function I(e,t){const n=function(e,t){const n=[],o=[];return e.forEach((e=>{const t=e.split(":");t[0]=encodeURIComponent(t[0]).replace(/%20/g,"+"),2===t.length?(t[1]=t[1].split(",").map((e=>encodeURIComponent(e))).join(","),n.push(t.join(":"))):n.push(t[0])})),o.push("family="+n.join("|")),t.display&&o.push("display="+encodeURIComponent(t.display)),t.subset&&o.push("subset="+encodeURIComponent(t.subset)),t.effect&&o.push("effect="+encodeURIComponent(t.effect)),t.text&&o.push("text="+encodeURIComponent(t.text)),`${encodeURI(t.url)}?${o.join("&")}`}(e,Object.assign($,t.google)),o=await async function(e){const t=await b(e);return t.ok||q().emit("error",new p(F,`Unexpected response "${t.statusText}" for ${e}`)),t.text()}(n),s=E(o),{fontFiles:r,fontPaths:a,fontFamilyNames:c,fontFullNames:i}=await k(s),l=U(o,s,a,c,i);return{googleFiles:r,googleCss:l?`/*${n}*/\r\n${l}`:""}}async function T(e,t){const n=await async function(e,t){return e.map((e=>{const n=r.resolve(t,e);if(!a.existsSync(n))return q().emit("error",new p(F,"Local font css not found!")),"";let o=a.readFileSync(n,"utf-8");const s=o.matchAll(/url\((?['"]?)(?[^)"':]+?)(\??#[^)"']+)?\k\)/g);return Array.from(s,(e=>e.groups.uri)).forEach((e=>{const t=r.resolve(r.dirname(n),e).replace(/\\/g,"/");o=o.replace(e,t)})),o})).join("\r\n")}(e,t),o=E(n),{fontFiles:s,fontPaths:c,fontFamilyNames:i,fontFullNames:l}=await k(o);return{localFiles:s,localCss:U(n,o,c,i,l)}}if(void 0===O)var O=r.dirname(l.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:f&&f.src||new URL("index.cjs",document.baseURI).href));async function P(e,t,n){let o="";const s=[];var c;if(c=t.nodeFetchOptions,v=c,void 0!==e.google)if(e.google instanceof Array){if(e.google.length>0){const{googleFiles:n,googleCss:r}=await I(e.google,t);n.forEach((e=>{s.push(e)})),o+=r}}else q().emit("warning",new p(F,"Google option must be an array."));if(void 0!==e.local)if(e.local instanceof Array){if(e.local.length>0){const{localFiles:t,localCss:r}=await T(e.local,n);t.forEach((e=>{s.push(e)})),o+=r}}else q().emit("warning",new p(F,"Local option must be an array."));if(o){const e=await async function(e,t){return t?t({css:e}):e}(o,t.cssTransform),n=new h({path:"fonts.css",contents:Buffer.from(e)});if(s.push(n),t.createdJsFiles){const e=o.match(/(?<={)([^}]+)(?=})/gm);if(e&&e.length){const n={};e.forEach((function(e){const t=["",400,"normal"],o=["","",{}];e.trim().split(";").map((function(e){const[t,...n]=e.split(":");return[t,n.join(":")].map((e=>e.trim()))})).filter((e=>!!e[0])).forEach((function([e,n]){if(e&&n){const r=(s=n,isNaN(parseFloat(s))||isNaN(s-0)?n.replace(/^['"]+|['"]+$/g,""):parseFloat(n));"font-family"===e?(o[0]=r,t[0]=r.toString().toLowerCase().replace(/\s+/g,"-")):"src"===e?o[1]=r.toString().replace(/,\s*url/g,", url"):("font-weight"===e?t[1]=parseInt(r.toString()):"font-style"===e&&(t[2]=r),o[2][function(e){return e[0].toLowerCase()+e.slice(1).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g,((e,t)=>t.toUpperCase()))}(e.replace(/^font-/,""))]=r)}var s})),n[t.join("-")]=o}));const c=["fonts.js","fonts-all.js","fonts-classes.js","fonts-get-format-from-font-data.js","fonts-get-key-from-font-face.js","fonts-get-src-from-font-data.js","fonts-load.js","fonts-preloader-main.js","fonts-preloader-worker.js"];for(const e of c){let c=a.readFileSync(r.join(O,"js",e)).toString();"fonts.js"===e?c=c.replace("{}",JSON.stringify(n)):"fonts-all.js"===e&&(c=c.replace("// const fontsData","const fontsData = "+JSON.stringify(n)+";"),c=c.replace("// fonts-load.js",a.readFileSync(r.join(O,"js","fonts-load.js")).toString().replace("import fontsData from './fonts.js';","")),c=c.replace("// fonts-get-key-from-font-face.js",a.readFileSync(r.join(O,"js","fonts-get-key-from-font-face.js")).toString().replace("export default ","")),c=c.replace("// fonts-classes.js",a.readFileSync(r.join(O,"js","fonts-classes.js")).toString().replace("import fontsData from './fonts.js';","").replace("import fontsGetKeyFromFontFace from './fonts-get-key-from-font-face.js';","")));const i=new h({path:e,contents:Buffer.from(await L(c,e,o,t.jsTransform))});s.push(i)}}}}return s}function z(e){return a.existsSync(r.resolve(S,e))}async function D(e,t,n){const o=w(e);if(z(o))return function(e){const t=[];if(z(e)){const n=r.resolve(S,e);a.readdirSync(n).forEach((e=>{t.push(new h({path:e,contents:Buffer.from(a.readFileSync(r.resolve(n,e)))}))}))}return t}(o);a.existsSync(S)&&a.rmSync(S,{recursive:!0,force:!0});const s=await P(e,t,n);return s.forEach((e=>function(e,t){const n=r.resolve(S,e);a.existsSync(n)||a.mkdirSync(n,{recursive:!0}),a.writeFileSync(r.resolve(n,t.basename),t.contents)}(o,e))),s}module.exports=function(e={}){const t=Object.assign(x,e);return g({objectMode:!0},(async function(e,n,o){if(R=this,e.isNull()||".json"!==e.extname)this.push(e);else if(e.isStream())q().emit("error",new p(F,"Streams not supported!"));else if(e.isBuffer()){const n=function(e){return JSON.parse(e)}(e.contents.toString());(t.cache?await D(n,t,e.base):await P(n,t,e.base)).forEach((e=>this.push(e)))}return o(null,null)}))};