@shipstatic/ship 0.1.20 → 0.1.21
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 +30 -6
- package/dist/browser.js +7 -7
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +26 -25
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -4
- package/dist/index.d.ts +13 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var he=Object.create;var $=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var ge=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var Pe=(i,e)=>{for(var t in e)$(i,t,{get:e[t],enumerable:!0})},O=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of de(e))!we.call(i,n)&&n!==t&&$(i,n,{get:()=>e[n],enumerable:!(o=ye(e,n))||o.enumerable});return i},J=(i,e,t)=>(O(i,e,"default"),t&&O(t,e,"default")),w=(i,e,t)=>(t=i!=null?he(ge(i)):{},O(e||!i||!i.__esModule?$(t,"default",{value:i,enumerable:!0}):t,i)),Se=i=>O($({},"__esModule",{value:!0}),i);var Be={};Pe(Be,{Ship:()=>z,ShipError:()=>M.ShipError,ShipErrorType:()=>M.ShipErrorType,__setTestEnvironment:()=>W,default:()=>Ne,processFilesForBrowser:()=>L,processFilesForNode:()=>B});module.exports=Se(Be);var _=null;function W(i){_=i}function De(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function f(){return _||De()}var v=require("zod");var D={};J(D,require("@shipstatic/types"));var T="https://api.shipstatic.com";var K="ship",Fe=v.z.object({apiUrl:v.z.string().url().optional(),apiKey:v.z.string().optional()}).strict();function V(i){try{return Fe.parse(i)}catch(e){if(e instanceof v.z.ZodError){let t=e.issues[0],o=t.path.length>0?` at ${t.path.join(".")}`:"";throw D.ShipError.config(`Configuration validation failed${o}: ${t.message}`)}throw D.ShipError.config("Configuration validation failed")}}async function Ae(i){try{if(f()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),o=e(K,{searchPlaces:[`.${K}rc`,"package.json",`${t.homedir()}/.${K}rc`],stopDir:t.homedir()}),n;if(i?n=o.load(i):n=o.search(),n&&n.config)return V(n.config)}catch(e){if(e instanceof D.ShipError)throw e}return{}}async function Y(i){if(f()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY},t=await Ae(i),o={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey};return V(o)}function j(i={},e={}){let t={apiUrl:i.apiUrl||e.apiUrl||T,apiKey:i.apiKey||e.apiKey};return t.apiKey!==void 0?{apiUrl:t.apiUrl,apiKey:t.apiKey}:{apiUrl:t.apiUrl}}function X(i={},e){return{onProgress:e.onProgress,onProgressStats:e.onProgressStats,maxConcurrency:e.maxConcurrentDeploys,timeout:e.timeout,apiKey:e.apiKey,apiUrl:e.apiUrl,...i}}var I=w(require("mime-types"),1),h=require("@shipstatic/types");var k="/deployments",Z="/ping",C="/aliases",be="/config",ve="/account",Ce="/spa-check";function xe(i){return typeof i=="string"?I.lookup(i)||"application/octet-stream":I.lookup(i.name)||i.type||"application/octet-stream"}async function Ee(i){let e=[];for await(let t of i)e.push(t);return e}var x=class{constructor(e){this.apiUrl=e.apiUrl||T,this.apiKey=e.apiKey??""}#n(e={}){let t={...e};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}async#i(e,t={},o){let n=this.#n(t.headers),s={...t,headers:n,credentials:f()==="browser"?"include":"same-origin"};try{return await fetch(e,s)}catch(a){throw this.#t(a,o),a}}async#e(e,t={},o){try{let n=await this.#i(e,t,o);return n.ok||await this.#o(n,o),n.headers.get("Content-Length")==="0"||n.status===204?void 0:await n.json()}catch(n){throw n instanceof h.ShipError||this.#t(n,o),n}}async ping(){return(await this.#e(`${this.apiUrl}${Z}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.#e(`${this.apiUrl}${Z}`,{method:"GET"},"Ping")}async getConfig(){return await this.#e(`${this.apiUrl}${be}`,{method:"GET"},"Config")}async deploy(e,t={}){this.#s(e);let{apiUrl:o=this.apiUrl,signal:n}=t,{requestBody:s,requestHeaders:a}=await this.#r(e),p={method:"POST",body:s,headers:a,signal:n||null};return await this.#e(`${o}${k}`,p,"Deploy")}#s(e){if(!e.length)throw h.ShipError.business("No files to deploy.");for(let t of e)if(!t.md5)throw h.ShipError.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async#r(e){let t,o={};if(f()==="browser")t=this.#a(e);else if(f()==="node"){let{body:n,headers:s}=await this.#l(e);t=n,o=s}else throw h.ShipError.business("Unknown or unsupported execution environment");return{requestBody:t,requestHeaders:o}}#a(e){let t=new FormData,o=[];for(let n=0;n<e.length;n++){let s=e[n],a;if(s.content instanceof File||s.content instanceof Blob)a=s.content;else throw h.ShipError.file(`Unsupported file.content type for browser FormData: ${s.path}`,s.path);let p=xe(a instanceof File?a:s.path),y=new File([a],s.path,{type:p});t.append("files[]",y),o.push(s.md5)}return t.append("checksums",JSON.stringify(o)),t}async#l(e){let{FormData:t,File:o}=await import("formdata-node"),{FormDataEncoder:n}=await import("form-data-encoder"),s=await import("path"),a=new t,p=[];for(let P=0;P<e.length;P++){let m=e[P],R=I.lookup(m.path)||"application/octet-stream",g;if(Buffer.isBuffer(m.content))g=new o([m.content],m.path,{type:R});else if(typeof Blob<"u"&&m.content instanceof Blob)g=new o([m.content],m.path,{type:R});else throw h.ShipError.file(`Unsupported file.content type for Node.js FormData: ${m.path}`,m.path);let ue=m.path.startsWith("/")?m.path:"/"+m.path;a.append("files[]",g,ue),p.push(m.md5)}a.append("checksums",JSON.stringify(p));let y=new n(a),l=await Ee(y.encode()),r=Buffer.concat(l.map(P=>Buffer.from(P))),c={"Content-Type":y.contentType,"Content-Length":Buffer.byteLength(r).toString()};return{body:r,headers:c}}async#o(e,t){let o={};try{let n=e.headers.get("content-type");n&&n.includes("application/json")?o=await e.json():o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}if(o.error||o.code||o.message){let n=o.message||o.error||`${t} failed due to API error`;throw e.status===401?h.ShipError.authentication(n):h.ShipError.api(n,e.status,o.code,o)}throw e.status===401?h.ShipError.authentication(`Authentication failed for ${t}`):h.ShipError.api(`${t} failed due to API error`,e.status,void 0,o)}#t(e,t){throw e.name==="AbortError"?h.ShipError.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?h.ShipError.network(`${t} failed due to network error: ${e.message}`,e):e instanceof h.ShipError?e:h.ShipError.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async listDeployments(){return await this.#e(`${this.apiUrl}${k}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.#e(`${this.apiUrl}${k}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.#e(`${this.apiUrl}${k}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t){try{let o=await this.#i(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({deployment:t})},"Set Alias");return o.ok||await this.#o(o,"Set Alias"),{...await o.json(),isCreate:o.status===201}}catch(o){this.#t(o,"Set Alias")}}async getAlias(e){return await this.#e(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${C}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.#e(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async checkAlias(e){return await this.#e(`${this.apiUrl}${C}/${encodeURIComponent(e)}/dns-check`,{method:"POST"},"Check Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${ve}`,{method:"GET"},"Get Account")}async createApiKey(){return await this.#e(`${this.apiUrl}/key`,{method:"POST"},"Create API Key")}async checkSPA(e){return(await this.#e(`${this.apiUrl}${Ce}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:e})},"SPA Check")).isSPA}};var fe=require("@shipstatic/types");var Q=require("@shipstatic/types"),H=null;function ee(i){H=i}function E(){if(H===null)throw Q.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return H}var u=require("@shipstatic/types");var F=require("@shipstatic/types");async function Re(i){let e=(await import("spark-md5")).default;return new Promise((t,o)=>{let s=Math.ceil(i.size/2097152),a=0,p=new e.ArrayBuffer,y=new FileReader,l=()=>{let r=a*2097152,c=Math.min(r+2097152,i.size);y.readAsArrayBuffer(i.slice(r,c))};y.onload=r=>{let c=r.target?.result;if(!c){o(F.ShipError.business("Failed to read file chunk"));return}p.append(c),a++,a<s?l():t({md5:p.end()})},y.onerror=()=>{o(F.ShipError.business("Failed to calculate MD5: FileReader error"))},l()})}async function Oe(i){let e=await import("crypto");if(Buffer.isBuffer(i)){let o=e.createHash("md5");return o.update(i),{md5:o.digest("hex")}}let t=await import("fs");return new Promise((o,n)=>{let s=e.createHash("md5"),a=t.createReadStream(i);a.on("error",p=>n(F.ShipError.business(`Failed to read file for MD5: ${p.message}`))),a.on("data",p=>s.update(p)),a.on("end",()=>o({md5:s.digest("hex")}))})}async function A(i){let e=f();if(e==="browser"){if(!(i instanceof Blob))throw F.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Re(i)}if(e==="node"){if(!(Buffer.isBuffer(i)||typeof i=="string"))throw F.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Oe(i)}throw F.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var te=require("junk"),$e=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"];function U(i){return!i||i.length===0?[]:i.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let o=t[t.length-1];if((0,te.isJunk)(o))return!1;let n=t.slice(0,-1);for(let s of n)if($e.some(a=>s.toLowerCase()===a.toLowerCase()))return!1;return!0})}var b=require("@shipstatic/types");function N(i){if(!i||i.length===0)return"";let e=i.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(s=>s.split("/").filter(Boolean)),o=[],n=Math.min(...t.map(s=>s.length));for(let s=0;s<n;s++){let a=t[0][s];if(t.every(p=>p[s]===a))o.push(a);else break}return o.join("/")}function G(i){return i.replace(/\\/g,"/").replace(/^\/+/,"")}var S=w(require("fs"),1),d=w(require("path"),1);function oe(i){let e=[];try{let t=S.readdirSync(i);for(let o of t){let n=d.join(i,o),s=S.statSync(n);if(s.isDirectory()){let a=oe(n);e.push(...a)}else s.isFile()&&e.push(n)}}catch(t){console.error(`Error reading directory ${i}:`,t)}return e}async function ie(i,e={}){let t=d.resolve(i),n=(()=>{let r=S.statSync(t);return r.isFile()?[t]:r.isDirectory()?oe(t):[]})().filter(r=>{let c=d.basename(r);return U([c]).length>0}),s=S.statSync(t),a;if(e.pathDetect===!1)a=s.isDirectory()?t:d.dirname(t);else{let r=n.map(c=>d.dirname(c));a=N(r)}let p=[],y=0;for(let r of n)try{let c=S.statSync(r);if(c.size===0){console.warn(`Skipping empty file: ${r}`);continue}let P=E();if(c.size>P.maxFileSize)throw b.ShipError.business(`File ${r} is too large. Maximum allowed size is ${P.maxFileSize/(1024*1024)}MB.`);if(y+=c.size,y>P.maxTotalSize)throw b.ShipError.business(`Total deploy size is too large. Maximum allowed is ${P.maxTotalSize/(1024*1024)}MB.`);let m=S.readFileSync(r),{md5:R}=await A(m),g=d.relative(a,r).replace(/\\/g,"/");(g.includes("\0")||g.includes("/../")||g.startsWith("../")||g.endsWith("/.."))&&(g=d.basename(r)),g||(g=d.basename(r)),p.push({path:g,content:m,size:m.length,md5:R})}catch(c){if(c instanceof b.ShipError&&c.isClientError&&c.isClientError())throw c;console.error(`Could not process file ${r}:`,c)}let l=E();if(p.length>l.maxFilesCount)throw b.ShipError.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return p}async function B(i,e={}){if(f()!=="node")throw b.ShipError.business("processFilesForNode can only be called in a Node.js environment.");if(i.length>1){let t=[];for(let o of i){let n=await ie(o,e);t.push(...n)}return t}return await ie(i[0],e)}var q=require("@shipstatic/types");async function L(i,e={}){if(f()!=="browser")throw q.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let t=Array.isArray(i)?i:Array.from(i),o="";if(e.pathDetect!==!1){let l=t.map(r=>r.webkitRelativePath||r.name).filter(r=>r).map(r=>r.includes("/")?r.substring(0,r.lastIndexOf("/")):"");o=N(l)}let n=[];for(let l of t){let r=l.webkitRelativePath||l.name;if(o&&e.pathDetect!==!1){r=G(r);let c=o.endsWith("/")?o:`${o}/`;r.startsWith(c)?r=r.substring(c.length):r===o&&(r="")}if(r=G(r),r.includes("..")||r.includes("\0"))throw q.ShipError.business(`Security error: Unsafe file path "${r}" for file: ${l.name}`);r||(r=l.name),n.push({file:l,relativePath:r})}let s=n.map(l=>l.relativePath),a=U(s),p=new Set(a),y=[];for(let l of n){if(!p.has(l.relativePath)||l.file.size===0)continue;let{md5:r}=await A(l.file);y.push({content:l.file,path:l.relativePath,size:l.file.size,md5:r})}return y}function ne(i,e={}){let t=E();if(!e.skipEmptyCheck&&i.length===0)throw u.ShipError.business("No files to deploy.");if(i.length>t.maxFilesCount)throw u.ShipError.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let o=0;for(let n of i){if(n.size>t.maxFileSize)throw u.ShipError.business(`File ${n.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(o+=n.size,o>t.maxTotalSize)throw u.ShipError.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function se(i,e){if(e==="node"){if(!Array.isArray(i))throw u.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(i.length===0)throw u.ShipError.business("No files to deploy.");if(!i.every(t=>typeof t=="string"))throw u.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&i instanceof HTMLInputElement&&!i.files)throw u.ShipError.business("No files selected in HTMLInputElement")}function re(i){return ne(i,{skipEmptyCheck:!0}),i.forEach(e=>{e.path&&(e.path=e.path.replace(/\\/g,"/"))}),i}async function Te(i,e={}){se(i,"node");let t=await B(i,e);return re(t)}async function ke(i,e={}){se(i,"browser");let t;if(i instanceof HTMLInputElement)t=Array.from(i.files);else if(typeof i=="object"&&i!==null&&typeof i.length=="number"&&typeof i.item=="function")t=Array.from(i);else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string")throw u.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=i}else throw u.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(n=>n.size===0?(console.warn(`Skipping empty file: ${n.name}`),!1):!0),ne(t);let o=await L(t,e);return re(o)}async function ae(i,e={},t){let o=f();if(o!=="node"&&o!=="browser")throw u.ShipError.business("Unsupported execution environment.");let n;return o==="node"?n=await Te(i,e):n=await ke(i,e),t&&(n=await Ue(n,t,e)),n}async function Ie(){let i={rewrites:[{source:"/(.*)",destination:"/index.html"}]},e=Buffer.from(JSON.stringify(i,null,2),"utf-8"),{md5:t}=await A(e);return{path:u.DEPLOYMENT_CONFIG_FILENAME,content:e,size:e.length,md5:t}}async function Ue(i,e,t){if(t.spaDetect===!1||i.some(o=>o.path===u.DEPLOYMENT_CONFIG_FILENAME))return i;try{let o=i.map(s=>s.path);if(await e.checkSPA(o)){let s=await Ie();return console.log(`SPA detected - generated ${u.DEPLOYMENT_CONFIG_FILENAME}`),[...i,s]}}catch{console.warn("SPA detection failed, continuing without auto-config")}return i}function le(i,e,t){return{create:async(o,n={})=>{t&&await t();let s=e?X(n,e):n,a=await ae(o,s,i());return await i().deploy(a,s)},list:async()=>(t&&await t(),i().listDeployments()),remove:async o=>{t&&await t(),await i().removeDeployment(o)},get:async o=>(t&&await t(),i().getDeployment(o))}}function ce(i,e){return{set:async(t,o)=>(e&&await e(),i().setAlias(t,o)),get:async t=>(e&&await e(),i().getAlias(t)),list:async()=>(e&&await e(),i().listAliases()),remove:async t=>{e&&await e(),await i().removeAlias(t)},check:async t=>(e&&await e(),i().checkAlias(t))}}function pe(i,e){return{get:async()=>(e&&await e(),i().getAccount())}}function me(i,e){return{create:async()=>(e&&await e(),i().createApiKey())}}var M=require("@shipstatic/types"),z=class{constructor(e={}){this.initPromise=null;if(this.clientOptions=e,this.environment=f(),this.environment!=="node"&&this.environment!=="browser")throw fe.ShipError.business("Unsupported execution environment.");let t=j(e,{});this.http=new x({...e,...t});let o=this.getInitCallback(),n=()=>this.http;this._deployments=le(n,this.clientOptions,o),this._aliases=ce(n,o),this._account=pe(n,o),this._keys=me(n,o)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.initializeConfig()),this.initPromise}getInitCallback(){return()=>this.ensureInitialized()}async initializeConfig(){try{let e=await Y(this.clientOptions.configFile),t=j(this.clientOptions,e);this.http=new x({...this.clientOptions,...t});let o=await this.http.getConfig();ee(o)}catch(e){throw this.initPromise=null,e}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get aliases(){return this._aliases}get account(){return this._account}get keys(){return this._keys}},Ne=z;0&&(module.exports={Ship,ShipError,ShipErrorType,__setTestEnvironment,processFilesForBrowser,processFilesForNode});
|
|
1
|
+
"use strict";var he=Object.create;var k=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var ge=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var Pe=(i,e)=>{for(var t in e)k(i,t,{get:e[t],enumerable:!0})},T=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of de(e))!we.call(i,n)&&n!==t&&k(i,n,{get:()=>e[n],enumerable:!(o=ye(e,n))||o.enumerable});return i},J=(i,e,t)=>(T(i,e,"default"),t&&T(t,e,"default")),w=(i,e,t)=>(t=i!=null?he(ge(i)):{},T(e||!i||!i.__esModule?k(t,"default",{value:i,enumerable:!0}):t,i)),Se=i=>T(k({},"__esModule",{value:!0}),i);var Be={};Pe(Be,{Ship:()=>z,ShipError:()=>_.ShipError,ShipErrorType:()=>_.ShipErrorType,__setTestEnvironment:()=>W,default:()=>Ue,processFilesForBrowser:()=>L,processFilesForNode:()=>B});module.exports=Se(Be);var M=null;function W(i){M=i}function De(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function f(){return M||De()}var A=require("zod");var D={};J(D,require("@shipstatic/types"));var O="https://api.shipstatic.com";var K="ship",Fe=A.z.object({apiUrl:A.z.string().url().optional(),apiKey:A.z.string().optional(),deployToken:A.z.string().optional()}).strict();function V(i){try{return Fe.parse(i)}catch(e){if(e instanceof A.z.ZodError){let t=e.issues[0],o=t.path.length>0?` at ${t.path.join(".")}`:"";throw D.ShipError.config(`Configuration validation failed${o}: ${t.message}`)}throw D.ShipError.config("Configuration validation failed")}}async function Ae(i){try{if(f()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),o=e(K,{searchPlaces:[`.${K}rc`,"package.json",`${t.homedir()}/.${K}rc`],stopDir:t.homedir()}),n;if(i?n=o.load(i):n=o.search(),n&&n.config)return V(n.config)}catch(e){if(e instanceof D.ShipError)throw e}return{}}async function Y(i){if(f()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await Ae(i),o={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return V(o)}function j(i={},e={}){let t={apiUrl:i.apiUrl||e.apiUrl||O,apiKey:i.apiKey||e.apiKey,deployToken:i.deployToken||e.deployToken},o={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(o.apiKey=t.apiKey),t.deployToken!==void 0&&(o.deployToken=t.deployToken),o}function X(i={},e){return{onProgress:e.onProgress,onProgressStats:e.onProgressStats,maxConcurrency:e.maxConcurrentDeploys,timeout:e.timeout,apiKey:e.apiKey,deployToken:e.deployToken,apiUrl:e.apiUrl,...i}}var I=w(require("mime-types"),1),y=require("@shipstatic/types");var $="/deployments",Z="/ping",C="/aliases",be="/config",ve="/account",Ce="/spa-check";function Ee(i){return typeof i=="string"?I.lookup(i)||"application/octet-stream":I.lookup(i.name)||i.type||"application/octet-stream"}async function xe(i){let e=[];for await(let t of i)e.push(t);return e}var E=class{constructor(e){this.apiUrl=e.apiUrl||O,this.apiKey=e.apiKey??"",this.deployToken=e.deployToken??""}#n(e={}){let t={...e};return this.deployToken?t.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}async#i(e,t={},o){let n=this.#n(t.headers),s={...t,headers:n,credentials:f()==="browser"?"include":"same-origin"};try{return await fetch(e,s)}catch(a){throw this.#t(a,o),a}}async#e(e,t={},o){try{let n=await this.#i(e,t,o);return n.ok||await this.#o(n,o),n.headers.get("Content-Length")==="0"||n.status===204?void 0:await n.json()}catch(n){throw n instanceof y.ShipError||this.#t(n,o),n}}async ping(){return(await this.#e(`${this.apiUrl}${Z}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.#e(`${this.apiUrl}${Z}`,{method:"GET"},"Ping")}async getConfig(){return await this.#e(`${this.apiUrl}${be}`,{method:"GET"},"Config")}async deploy(e,t={}){this.#s(e);let{apiUrl:o=this.apiUrl,signal:n,apiKey:s,deployToken:a}=t,{requestBody:c,requestHeaders:u}=await this.#r(e),l={};a?l={Authorization:`Bearer ${a}`}:s&&(l={Authorization:`Bearer ${s}`});let r={method:"POST",body:c,headers:{...u,...l},signal:n||null};return await this.#e(`${o}${$}`,r,"Deploy")}#s(e){if(!e.length)throw y.ShipError.business("No files to deploy.");for(let t of e)if(!t.md5)throw y.ShipError.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async#r(e){let t,o={};if(f()==="browser")t=this.#a(e);else if(f()==="node"){let{body:n,headers:s}=await this.#l(e);t=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),o=s}else throw y.ShipError.business("Unknown or unsupported execution environment");return{requestBody:t,requestHeaders:o}}#a(e){let t=new FormData,o=[];for(let n=0;n<e.length;n++){let s=e[n],a;if(s.content instanceof File||s.content instanceof Blob)a=s.content;else throw y.ShipError.file(`Unsupported file.content type for browser FormData: ${s.path}`,s.path);let c=Ee(a instanceof File?a:s.path),u=new File([a],s.path,{type:c});t.append("files[]",u),o.push(s.md5)}return t.append("checksums",JSON.stringify(o)),t}async#l(e){let{FormData:t,File:o}=await import("formdata-node"),{FormDataEncoder:n}=await import("form-data-encoder"),s=await import("path"),a=new t,c=[];for(let P=0;P<e.length;P++){let m=e[P],R=I.lookup(m.path)||"application/octet-stream",g;if(Buffer.isBuffer(m.content))g=new o([m.content],m.path,{type:R});else if(typeof Blob<"u"&&m.content instanceof Blob)g=new o([m.content],m.path,{type:R});else throw y.ShipError.file(`Unsupported file.content type for Node.js FormData: ${m.path}`,m.path);let ue=m.path.startsWith("/")?m.path:"/"+m.path;a.append("files[]",g,ue),c.push(m.md5)}a.append("checksums",JSON.stringify(c));let u=new n(a),l=await xe(u.encode()),r=Buffer.concat(l.map(P=>Buffer.from(P))),p={"Content-Type":u.contentType,"Content-Length":Buffer.byteLength(r).toString()};return{body:r,headers:p}}async#o(e,t){let o={};try{let n=e.headers.get("content-type");n&&n.includes("application/json")?o=await e.json():o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}if(o.error||o.code||o.message){let n=o.message||o.error||`${t} failed due to API error`;throw e.status===401?y.ShipError.authentication(n):y.ShipError.api(n,e.status,o.code,o)}throw e.status===401?y.ShipError.authentication(`Authentication failed for ${t}`):y.ShipError.api(`${t} failed due to API error`,e.status,void 0,o)}#t(e,t){throw e.name==="AbortError"?y.ShipError.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?y.ShipError.network(`${t} failed due to network error: ${e.message}`,e):e instanceof y.ShipError?e:y.ShipError.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async listDeployments(){return await this.#e(`${this.apiUrl}${$}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.#e(`${this.apiUrl}${$}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.#e(`${this.apiUrl}${$}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t){try{let o=await this.#i(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({deployment:t})},"Set Alias");return o.ok||await this.#o(o,"Set Alias"),{...await o.json(),isCreate:o.status===201}}catch(o){this.#t(o,"Set Alias")}}async getAlias(e){return await this.#e(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${C}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.#e(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async checkAlias(e){return await this.#e(`${this.apiUrl}${C}/${encodeURIComponent(e)}/dns-check`,{method:"POST"},"Check Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${ve}`,{method:"GET"},"Get Account")}async createApiKey(){return await this.#e(`${this.apiUrl}/key`,{method:"POST"},"Create API Key")}async checkSPA(e){return(await this.#e(`${this.apiUrl}${Ce}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:e})},"SPA Check")).isSPA}};var fe=require("@shipstatic/types");var Q=require("@shipstatic/types"),H=null;function ee(i){H=i}function x(){if(H===null)throw Q.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return H}var h=require("@shipstatic/types");var F=require("@shipstatic/types");async function Re(i){let e=(await import("spark-md5")).default;return new Promise((t,o)=>{let s=Math.ceil(i.size/2097152),a=0,c=new e.ArrayBuffer,u=new FileReader,l=()=>{let r=a*2097152,p=Math.min(r+2097152,i.size);u.readAsArrayBuffer(i.slice(r,p))};u.onload=r=>{let p=r.target?.result;if(!p){o(F.ShipError.business("Failed to read file chunk"));return}c.append(p),a++,a<s?l():t({md5:c.end()})},u.onerror=()=>{o(F.ShipError.business("Failed to calculate MD5: FileReader error"))},l()})}async function Te(i){let e=await import("crypto");if(Buffer.isBuffer(i)){let o=e.createHash("md5");return o.update(i),{md5:o.digest("hex")}}let t=await import("fs");return new Promise((o,n)=>{let s=e.createHash("md5"),a=t.createReadStream(i);a.on("error",c=>n(F.ShipError.business(`Failed to read file for MD5: ${c.message}`))),a.on("data",c=>s.update(c)),a.on("end",()=>o({md5:s.digest("hex")}))})}async function b(i){let e=f();if(e==="browser"){if(!(i instanceof Blob))throw F.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Re(i)}if(e==="node"){if(!(Buffer.isBuffer(i)||typeof i=="string"))throw F.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Te(i)}throw F.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var te=require("junk"),ke=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"];function N(i){return!i||i.length===0?[]:i.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let o=t[t.length-1];if((0,te.isJunk)(o))return!1;let n=t.slice(0,-1);for(let s of n)if(ke.some(a=>s.toLowerCase()===a.toLowerCase()))return!1;return!0})}var v=require("@shipstatic/types");function U(i){if(!i||i.length===0)return"";let e=i.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(s=>s.split("/").filter(Boolean)),o=[],n=Math.min(...t.map(s=>s.length));for(let s=0;s<n;s++){let a=t[0][s];if(t.every(c=>c[s]===a))o.push(a);else break}return o.join("/")}function G(i){return i.replace(/\\/g,"/").replace(/^\/+/,"")}var S=w(require("fs"),1),d=w(require("path"),1);function oe(i){let e=[];try{let t=S.readdirSync(i);for(let o of t){let n=d.join(i,o),s=S.statSync(n);if(s.isDirectory()){let a=oe(n);e.push(...a)}else s.isFile()&&e.push(n)}}catch(t){console.error(`Error reading directory ${i}:`,t)}return e}async function ie(i,e={}){let t=d.resolve(i),n=(()=>{let r=S.statSync(t);return r.isFile()?[t]:r.isDirectory()?oe(t):[]})().filter(r=>{let p=d.basename(r);return N([p]).length>0}),s=S.statSync(t),a;if(e.pathDetect===!1)a=s.isDirectory()?t:d.dirname(t);else{let r=n.map(p=>d.dirname(p));a=U(r)}let c=[],u=0;for(let r of n)try{let p=S.statSync(r);if(p.size===0){console.warn(`Skipping empty file: ${r}`);continue}let P=x();if(p.size>P.maxFileSize)throw v.ShipError.business(`File ${r} is too large. Maximum allowed size is ${P.maxFileSize/(1024*1024)}MB.`);if(u+=p.size,u>P.maxTotalSize)throw v.ShipError.business(`Total deploy size is too large. Maximum allowed is ${P.maxTotalSize/(1024*1024)}MB.`);let m=S.readFileSync(r),{md5:R}=await b(m),g=d.relative(a,r).replace(/\\/g,"/");(g.includes("\0")||g.includes("/../")||g.startsWith("../")||g.endsWith("/.."))&&(g=d.basename(r)),g||(g=d.basename(r)),c.push({path:g,content:m,size:m.length,md5:R})}catch(p){if(p instanceof v.ShipError&&p.isClientError&&p.isClientError())throw p;console.error(`Could not process file ${r}:`,p)}let l=x();if(c.length>l.maxFilesCount)throw v.ShipError.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return c}async function B(i,e={}){if(f()!=="node")throw v.ShipError.business("processFilesForNode can only be called in a Node.js environment.");if(i.length>1){let t=[];for(let o of i){let n=await ie(o,e);t.push(...n)}return t}return await ie(i[0],e)}var q=require("@shipstatic/types");async function L(i,e={}){if(f()!=="browser")throw q.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let t=Array.isArray(i)?i:Array.from(i),o="";if(e.pathDetect!==!1){let l=t.map(r=>r.webkitRelativePath||r.name).filter(r=>r).map(r=>r.includes("/")?r.substring(0,r.lastIndexOf("/")):"");o=U(l)}let n=[];for(let l of t){let r=l.webkitRelativePath||l.name;if(o&&e.pathDetect!==!1){r=G(r);let p=o.endsWith("/")?o:`${o}/`;r.startsWith(p)?r=r.substring(p.length):r===o&&(r="")}if(r=G(r),r.includes("..")||r.includes("\0"))throw q.ShipError.business(`Security error: Unsafe file path "${r}" for file: ${l.name}`);r||(r=l.name),n.push({file:l,relativePath:r})}let s=n.map(l=>l.relativePath),a=N(s),c=new Set(a),u=[];for(let l of n){if(!c.has(l.relativePath)||l.file.size===0)continue;let{md5:r}=await b(l.file);u.push({content:l.file,path:l.relativePath,size:l.file.size,md5:r})}return u}function ne(i,e={}){let t=x();if(!e.skipEmptyCheck&&i.length===0)throw h.ShipError.business("No files to deploy.");if(i.length>t.maxFilesCount)throw h.ShipError.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let o=0;for(let n of i){if(n.size>t.maxFileSize)throw h.ShipError.business(`File ${n.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(o+=n.size,o>t.maxTotalSize)throw h.ShipError.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function se(i,e){if(e==="node"){if(!Array.isArray(i))throw h.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(i.length===0)throw h.ShipError.business("No files to deploy.");if(!i.every(t=>typeof t=="string"))throw h.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&i instanceof HTMLInputElement&&!i.files)throw h.ShipError.business("No files selected in HTMLInputElement")}function re(i){return ne(i,{skipEmptyCheck:!0}),i.forEach(e=>{e.path&&(e.path=e.path.replace(/\\/g,"/"))}),i}async function Oe(i,e={}){se(i,"node");let t=await B(i,e);return re(t)}async function $e(i,e={}){se(i,"browser");let t;if(i instanceof HTMLInputElement)t=Array.from(i.files);else if(typeof i=="object"&&i!==null&&typeof i.length=="number"&&typeof i.item=="function")t=Array.from(i);else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string")throw h.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=i}else throw h.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(n=>n.size===0?(console.warn(`Skipping empty file: ${n.name}`),!1):!0),ne(t);let o=await L(t,e);return re(o)}async function ae(i,e={},t){let o=f();if(o!=="node"&&o!=="browser")throw h.ShipError.business("Unsupported execution environment.");let n;return o==="node"?n=await Oe(i,e):n=await $e(i,e),t&&(n=await Ne(n,t,e)),n}async function Ie(){let i={rewrites:[{source:"/(.*)",destination:"/index.html"}]},e=Buffer.from(JSON.stringify(i,null,2),"utf-8"),{md5:t}=await b(e);return{path:h.DEPLOYMENT_CONFIG_FILENAME,content:e,size:e.length,md5:t}}async function Ne(i,e,t){if(t.spaDetect===!1||i.some(o=>o.path===h.DEPLOYMENT_CONFIG_FILENAME))return i;try{let o=i.map(s=>s.path);if(await e.checkSPA(o)){let s=await Ie();return console.log(`SPA detected - generated ${h.DEPLOYMENT_CONFIG_FILENAME}`),[...i,s]}}catch{console.warn("SPA detection failed, continuing without auto-config")}return i}function le(i,e,t){return{create:async(o,n={})=>{t&&await t();let s=e?X(n,e):n,a=await ae(o,s,i());return await i().deploy(a,s)},list:async()=>(t&&await t(),i().listDeployments()),remove:async o=>{t&&await t(),await i().removeDeployment(o)},get:async o=>(t&&await t(),i().getDeployment(o))}}function pe(i,e){return{set:async(t,o)=>(e&&await e(),i().setAlias(t,o)),get:async t=>(e&&await e(),i().getAlias(t)),list:async()=>(e&&await e(),i().listAliases()),remove:async t=>{e&&await e(),await i().removeAlias(t)},check:async t=>(e&&await e(),i().checkAlias(t))}}function ce(i,e){return{get:async()=>(e&&await e(),i().getAccount())}}function me(i,e){return{create:async()=>(e&&await e(),i().createApiKey())}}var _=require("@shipstatic/types"),z=class{constructor(e={}){this.initPromise=null;if(this.clientOptions=e,this.environment=f(),this.environment!=="node"&&this.environment!=="browser")throw fe.ShipError.business("Unsupported execution environment.");let t=j(e,{});this.http=new E({...e,...t});let o=this.getInitCallback(),n=()=>this.http;this._deployments=le(n,this.clientOptions,o),this._aliases=pe(n,o),this._account=ce(n,o),this._keys=me(n,o)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.initializeConfig()),this.initPromise}getInitCallback(){return()=>this.ensureInitialized()}async initializeConfig(){try{let e=await Y(this.clientOptions.configFile),t=j(this.clientOptions,e);this.http=new E({...this.clientOptions,...t});let o=await this.http.getConfig();ee(o)}catch(e){throw this.initPromise=null,e}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get aliases(){return this._aliases}get account(){return this._account}get keys(){return this._keys}},Ue=z;0&&(module.exports={Ship,ShipError,ShipErrorType,__setTestEnvironment,processFilesForBrowser,processFilesForNode});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|