@sheetxl/io
Version:
IO - Import/Export Libraries for SheetXL.
7 lines (6 loc) • 13.5 kB
JavaScript
;/**
* @license @sheetxl/io - IO - Import/Export Libraries for SheetXL. - v0.7.27
*
* (C) 2025-present SheetXL Inc. & Michael T. Ford
* License: The license can be found at https://www.sheetxl.com/license.
*/Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("@sheetxl/utils"),b=require("@sheetxl/sdk"),F=[{key:"SheetXL",description:"SheetXL",mimeType:".sxl",exts:["sxl","json"],isDefault:!0,handler:async(d,e)=>(await Promise.resolve().then(()=>require("./C_3Pu4GnjZ7HRs9q.cjs"))).readBufferSXL(d,e)},{key:"CSV",description:"Comma Delimited",mimeType:"text/csv",exts:["csv"],handler:async(d,e)=>(await Promise.resolve().then(()=>require("./CXIyTQtdwMU5vBRb.cjs"))).readBufferCSV(d,e)},{key:"Excel",description:"Excel Workbook",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",exts:["xlsx","xls","xlsm"],handler:async(d,e)=>(await Promise.resolve().then(()=>require("./BE2lwMALdql-mWPe.cjs")).then(n=>n.Handler)).readBufferXLSX(d,e)}],W=[{key:"SheetXL",mimeType:"application/vnd.sheetxl.sheet",description:"SheetXL",exts:["sxl","json"],isDefault:!0,async handler(d,e){return e?.format==="json"&&(e={compress:!1,...e}),(await Promise.resolve().then(()=>require("./C_3Pu4GnjZ7HRs9q.cjs"))).writeBufferSXL(d,e)}},{key:"CSV",mimeType:"text/csv",description:"Comma Delimited",exts:["csv"],handler:async(d,e)=>(await Promise.resolve().then(()=>require("./CXIyTQtdwMU5vBRb.cjs"))).writeBufferCSV(d,e)},{key:"Excel",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",description:"Excel Workbook",exts:["xlsx"],tags:["SheetJS Pro"],handler:async(d,e)=>(await Promise.resolve().then(()=>require("./BE2lwMALdql-mWPe.cjs")).then(n=>n.Handler)).writeBufferXLSX(d,e)}],T=async(d,e)=>{let n;typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer?(n=new ArrayBuffer(e.byteLength),new Uint8Array(n).set(new Uint8Array(e))):n=e,(function(t,r){const o=URL.createObjectURL(t),a=document.createElement("a");a.style.display="none",a.href=o,a.download=r,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(o)})(new Blob([n],{type:"application/octet-stream"}),d)};class L{constructor(e=F,n=W){this._readFormats=[],this._writeFormats=[],this._readFormats=Object.freeze([...e]),this._writeFormats=Object.freeze([...n])}async getReadFormats(e){return e?this._filterFormats(e,this._readFormats):[...this._readFormats]}async getWriteFormats(e){return this._writeFormats?e?this._filterFormats(e,this._writeFormats):[...this._writeFormats]:[]}async writeArrayBuffer(e,n){const t=(await this.getWriteFormats({search:n?.format??"slx"}))[0];return this._writeArrayBuffer(e,t,n)}async read(e){if(!e)throw new Error("'options' must be provided for read.");let n=e.source;if(!n)throw new Error("'options.source' must be provided for read.");let t,r=e.name,o=e.format;!o&&r&&(t=b.TextUtils.getFileNameExtension(r)),typeof n=="function"&&(n=n()),n&&typeof n=="object"&&typeof n.then=="function"&&(n=await Promise.resolve(n));const a=this._detectImportSourceType(n);if(!a)throw new Error("Unable to detect source type from provided input.");const s=this,i=async(l,u,c)=>{if(!l&&!u)throw new Error("Either format or file extension must be provided to determine read type.");const h=(await s.getReadFormats({search:l,ext:u}))[0];if(!h)throw new Error(`No read format available for '${e.format??u}' input.`);delete(e={...e,...e?.typedCreateWorkbookOptions?.[h.key]}).typedCreateWorkbookOptions;const m=r??c??`read-${a}`;e.createWorkbookOptions={...e.createWorkbookOptions||{},name:m},e.readonly!==void 0&&(e.createWorkbookOptions={readonly:e.readonly,...e.createWorkbookOptions},delete e.readonly);const w=e?.progress?.onStart;return w&&await Promise.resolve(w({format:h,name:m})),h},f=async(l,u,c)=>{const h=await Promise.resolve(l),m=await this._readArrayBuffer(h,u,c);return c?.progress?.onComplete?.(),m};switch(a){case"file":{const l=n,u=l?.name;let c="";u&&(c=`${b.TextUtils.getBaseName(u)}`);const h=await i(o,b.TextUtils.getFileNameExtension(u),c);return f(l.arrayBuffer(),h,e)}case"blob":{const l=await i(o,t);return f(n.arrayBuffer(),l,e)}case"base64":{const l=await i(o,t);let u;if(n&&typeof n=="object"&&"base64"in n)u=n.base64;else if(typeof n=="string"&&n.startsWith("data:")){const[,c]=n.split(",");u=c}else u=n;return f(_.BufferUtils.base64ToArrayBuffer(u),l,e)}case"fetch":{let l,u,c=null;if(typeof n=="string")c=n;else{if(!n||typeof n!="object"||!("input"in n))throw new Error("Invalid fetch source provided.");{const p=n;c=p.input,l=p.init,u=p.timeout}}const h=u||3e4,m=new AbortController,w=setTimeout(()=>m.abort(),h),y=typeof c=="string"?c:c.toString(),g=t||b.TextUtils.getFileNameExtension(y),v=await i(o,g,b.TextUtils.getBaseName(y,!0));try{const p=await fetch(c,{...l,signal:m.signal});if(clearTimeout(w),!p.ok)throw new Error(`Failed to fetch: ${p.status} ${p.statusText}`);const E=await p.arrayBuffer();if(!E)throw new Error(`Unable to fetched content: ${y}`);return f(E,v,e)}catch(p){throw clearTimeout(w),p.name==="AbortError"?new Error(`Fetch timeout after ${h}ms: ${y}`):p}}case"buffer":return f(n,await i(o,t),e);case"stream":{const l=await i(o,t),u=n.getReader(),c=[];let h=0;try{for(;;){const{done:g,value:v}=await u.read();if(g)break;c.push(v),h+=v.length}}finally{u.releaseLock()}const m=new ArrayBuffer(h),w=new Uint8Array(m);let y=0;for(const g of c)w.set(g,y),y+=g.length;return f(m,l,e)}default:throw new Error(`Unsupported source type: ${a}`)}}async writeFile(e,n,t){if(!e)throw new Error("File name must be provided.");if(!n)throw new Error("Workbook must be provided.");if(!n.isIWorkbook)throw new Error("Invalid workbook model provided. Must be an instance of IWorkbook.");const r=b.TextUtils.getFileNameExtension(e).toLowerCase();r&&(e=e.slice(0,e.length-r.length-1));const o=(await this.getWriteFormats({search:t?.format,ext:r}))[0];if(!o)throw new Error(`Unable to determine write type for '${e}'.`);const a=e+"."+(r||o.exts[0]);let s=null;try{s=await this._writeArrayBuffer(n,o,t)}catch(i){throw typeof i=="string"?new Error(i):i}try{await T(a,s)}catch(i){throw new Error("Unable to write file.",{cause:i})}return t?.progress?.onComplete?.(),!0}async registerReadFormat(e){this._registerFormatType(e,this._readFormats)}async registerWriteFormat(e){this._registerFormatType(e,this._writeFormats)}async _registerFormatType(e,n){if(!e)throw new Error("format must be provided.")}_detectImportSourceType(e){return e&&typeof e=="object"&&"base64"in e?"base64":e&&typeof e=="object"&&"input"in e?"fetch":typeof e=="string"?e.startsWith("data:")?"base64":(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")||e.startsWith("./")||e.startsWith("../"),"fetch"):typeof File<"u"&&e instanceof File?"file":typeof Blob<"u"&&e instanceof Blob?"blob":e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"buffer":typeof ReadableStream<"u"&&e instanceof ReadableStream?"stream":null}_filterFormats(e,n,t){if(!e||Object.keys(e).length===0){if(!t)return[...n];e={ext:t}}const r=e.search?.toLocaleLowerCase();return n.filter(o=>{if(r){const s=o.key.toLocaleLowerCase().includes(r),i=!!o.exts&&o.exts.some(c=>c.toLocaleLowerCase().includes(r)),f=!!o.mimeType&&o.mimeType.toLocaleLowerCase().includes(r),l=!!o.tags&&o.tags.some(c=>c.toLocaleLowerCase().includes(r)),u=!!o.description&&o.description.toLocaleLowerCase().includes(r);if(!(s||i||f||l||u))return!1}const a=e.ext||t;if(a){const s=a.toLocaleLowerCase();if(!o.exts.some(i=>i.toLocaleLowerCase()===s))return!1}if(e.mimeType&&o.mimeType!==e.mimeType||e.key&&o.key.toLocaleLowerCase()!==e.key.toLocaleLowerCase()||e.isDefault!==void 0&&o.isDefault!==e.isDefault)return!1;if(e.tags){const s=o.tags||[];if(!(typeof e.tags=="string"?[e.tags]:e.tags).every(i=>s.includes(i)))return!1}return!0})}async _writeArrayBuffer(e,n,t){if(!n)throw new Error(`Invalid write type for '${n}'.`);try{const r=n.handler;if(!r)throw new Error(`Unable to resolve handler for type: ${n.description??n}.`);return r(e,t)}catch(r){throw new Error(`Unable to load handler for '${n}.'`,{cause:r})}}async _readArrayBuffer(e,n,t=null){if(!e)throw new Error("ArrayBuffer must be specified.");if(!n)throw new Error("format must be specified.");const r=n.handler;if(!r)throw new Error(`Unable to resolve handler for format type: ${n?.description??n}.`);let o;try{o=await r(e,t)}catch(a){throw new Error("Unable to read",{cause:a})}return o}}const B=new L;var x,k,S=(function(){if(k)return x;function d(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}function e(t,r){for(var o,a="",s=0,i=-1,f=0,l=0;l<=t.length;++l){if(l<t.length)o=t.charCodeAt(l);else{if(o===47)break;o=47}if(o===47){if(!(i===l-1||f===1))if(i!==l-1&&f===2){if(a.length<2||s!==2||a.charCodeAt(a.length-1)!==46||a.charCodeAt(a.length-2)!==46){if(a.length>2){var u=a.lastIndexOf("/");if(u!==a.length-1){u===-1?(a="",s=0):s=(a=a.slice(0,u)).length-1-a.lastIndexOf("/"),i=l,f=0;continue}}else if(a.length===2||a.length===1){a="",s=0,i=l,f=0;continue}}r&&(a.length>0?a+="/..":a="..",s=2)}else a.length>0?a+="/"+t.slice(i+1,l):a=t.slice(i+1,l),s=l-i-1;i=l,f=0}else o===46&&f!==-1?++f:f=-1}return a}k=1;var n={resolve:function(){for(var t,r="",o=!1,a=arguments.length-1;a>=-1&&!o;a--){var s;a>=0?s=arguments[a]:(t===void 0&&(t=process.cwd()),s=t),d(s),s.length!==0&&(r=s+"/"+r,o=s.charCodeAt(0)===47)}return r=e(r,!o),o?r.length>0?"/"+r:"/":r.length>0?r:"."},normalize:function(t){if(d(t),t.length===0)return".";var r=t.charCodeAt(0)===47,o=t.charCodeAt(t.length-1)===47;return(t=e(t,!r)).length!==0||r||(t="."),t.length>0&&o&&(t+="/"),r?"/"+t:t},isAbsolute:function(t){return d(t),t.length>0&&t.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var t,r=0;r<arguments.length;++r){var o=arguments[r];d(o),o.length>0&&(t===void 0?t=o:t+="/"+o)}return t===void 0?".":n.normalize(t)},relative:function(t,r){if(d(t),d(r),t===r||(t=n.resolve(t))===(r=n.resolve(r)))return"";for(var o=1;o<t.length&&t.charCodeAt(o)===47;++o);for(var a=t.length,s=a-o,i=1;i<r.length&&r.charCodeAt(i)===47;++i);for(var f=r.length-i,l=s<f?s:f,u=-1,c=0;c<=l;++c){if(c===l){if(f>l){if(r.charCodeAt(i+c)===47)return r.slice(i+c+1);if(c===0)return r.slice(i+c)}else s>l&&(t.charCodeAt(o+c)===47?u=c:c===0&&(u=0));break}var h=t.charCodeAt(o+c);if(h!==r.charCodeAt(i+c))break;h===47&&(u=c)}var m="";for(c=o+u+1;c<=a;++c)c!==a&&t.charCodeAt(c)!==47||(m.length===0?m+="..":m+="/..");return m.length>0?m+r.slice(i+u):(i+=u,r.charCodeAt(i)===47&&++i,r.slice(i))},_makeLong:function(t){return t},dirname:function(t){if(d(t),t.length===0)return".";for(var r=t.charCodeAt(0),o=r===47,a=-1,s=!0,i=t.length-1;i>=1;--i)if((r=t.charCodeAt(i))===47){if(!s){a=i;break}}else s=!1;return a===-1?o?"/":".":o&&a===1?"//":t.slice(0,a)},basename:function(t,r){if(r!==void 0&&typeof r!="string")throw new TypeError('"ext" argument must be a string');d(t);var o,a=0,s=-1,i=!0;if(r!==void 0&&r.length>0&&r.length<=t.length){if(r.length===t.length&&r===t)return"";var f=r.length-1,l=-1;for(o=t.length-1;o>=0;--o){var u=t.charCodeAt(o);if(u===47){if(!i){a=o+1;break}}else l===-1&&(i=!1,l=o+1),f>=0&&(u===r.charCodeAt(f)?--f===-1&&(s=o):(f=-1,s=l))}return a===s?s=l:s===-1&&(s=t.length),t.slice(a,s)}for(o=t.length-1;o>=0;--o)if(t.charCodeAt(o)===47){if(!i){a=o+1;break}}else s===-1&&(i=!1,s=o+1);return s===-1?"":t.slice(a,s)},extname:function(t){d(t);for(var r=-1,o=0,a=-1,s=!0,i=0,f=t.length-1;f>=0;--f){var l=t.charCodeAt(f);if(l!==47)a===-1&&(s=!1,a=f+1),l===46?r===-1?r=f:i!==1&&(i=1):r!==-1&&(i=-1);else if(!s){o=f+1;break}}return r===-1||a===-1||i===0||i===1&&r===a-1&&r===o+1?"":t.slice(r,a)},format:function(t){if(t===null||typeof t!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof t);return(function(r,o){var a=o.dir||o.root,s=o.base||(o.name||"")+(o.ext||"");return a?a===o.root?a+s:a+r+s:s})("/",t)},parse:function(t){d(t);var r={root:"",dir:"",base:"",ext:"",name:""};if(t.length===0)return r;var o,a=t.charCodeAt(0),s=a===47;s?(r.root="/",o=1):o=0;for(var i=-1,f=0,l=-1,u=!0,c=t.length-1,h=0;c>=o;--c)if((a=t.charCodeAt(c))!==47)l===-1&&(u=!1,l=c+1),a===46?i===-1?i=c:h!==1&&(h=1):i!==-1&&(h=-1);else if(!u){f=c+1;break}return i===-1||l===-1||h===0||h===1&&i===l-1&&i===f+1?l!==-1&&(r.base=r.name=f===0&&s?t.slice(1,l):t.slice(f,l)):(f===0&&s?(r.name=t.slice(1,i),r.base=t.slice(1,l)):(r.name=t.slice(f,i),r.base=t.slice(f,l)),r.ext=t.slice(i,l)),f>0?r.dir=t.slice(0,f-1):s&&(r.dir="/"),r},sep:"/",delimiter:":",win32:null,posix:null};return n.posix=n,x=n})();const A=/^(con|prn|aux|nul|com\d|lpt\d)$/i,C=/[<>:"/\\|?*\u0000-\u001F]/g,U=Object.freeze(Object.defineProperty({__proto__:null,MAX_WORKBOOK_NAME_SIZE:96,WINDOW_FILENAME_CHAR_RESERVED_REGEX:C,WINDOW_FILENAME_RESERVED_REGEX:A,isValidWindowsFilename:d=>!(!d||d.length>255)&&!C.test(d)&&!A.test(d)&&d!=="."&&d!=="..",relativePath:(d,e)=>{try{return new URL(e),e}catch{}if(e.startsWith("/")||/^[a-zA-Z]:/.test(e))return e;if(typeof window>"u"||window.document===void 0){if(typeof require<"u"&&typeof process<"u")return S.Path.resolve(d,e);throw new Error("Unsupported environment")}try{let n=d.startsWith("http")?d:`file:///${d.replace(/\\/g,"/")}`;return n.endsWith("/")||(n+="/"),new URL(e,n).href}catch{const n=document.createElement("a");let t=d;return t.endsWith("/")||(t+="/"),n.href=new URL(e,t).href,n.href}}},Symbol.toStringTag,{value:"Module"}));exports.DefaultWorkbookIO=L,exports.IOUtils=U,exports.WorkbookIO=B;