@shipstatic/ship 0.1.24 → 0.1.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +11 -11
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var ge=Object.create;var O=Object.defineProperty;var we=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty;var Fe=(i,e)=>{for(var t in e)O(i,t,{get:e[t],enumerable:!0})},T=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Pe(e))!De.call(i,n)&&n!==t&&O(i,n,{get:()=>e[n],enumerable:!(o=we(e,n))||o.enumerable});return i},Y=(i,e,t)=>(T(i,e,"default"),t&&T(t,e,"default")),w=(i,e,t)=>(t=i!=null?ge(Se(i)):{},T(e||!i||!i.__esModule?O(t,"default",{value:i,enumerable:!0}):t,i)),Ae=i=>T(O({},"__esModule",{value:!0}),i);var Me={};Fe(Me,{Ship:()=>M,ShipError:()=>K.ShipError,ShipErrorType:()=>K.ShipErrorType,__setTestEnvironment:()=>X,default:()=>_e,processFilesForBrowser:()=>_,processFilesForNode:()=>L});module.exports=Ae(Me);var H=null;function X(i){H=i}function be(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function f(){return H||be()}var C=require("zod");var F={};Y(F,require("@shipstatic/types"));var $="https://api.shipstatic.com";var q="ship",ve=C.z.object({apiUrl:C.z.string().url().optional(),apiKey:C.z.string().optional(),deployToken:C.z.string().optional()}).strict();function Z(i){try{return ve.parse(i)}catch(e){if(e instanceof C.z.ZodError){let t=e.issues[0],o=t.path.length>0?` at ${t.path.join(".")}`:"";throw F.ShipError.config(`Configuration validation failed${o}: ${t.message}`)}throw F.ShipError.config("Configuration validation failed")}}async function Ce(i){try{if(f()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),o=e(q,{searchPlaces:[`.${q}rc`,"package.json",`${t.homedir()}/.${q}rc`],stopDir:t.homedir()}),n;if(i?n=o.load(i):n=o.search(),n&&n.config)return Z(n.config)}catch(e){if(e instanceof F.ShipError)throw e}return{}}async function Q(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 Ce(i),o={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Z(o)}function G(i={},e={}){let t={apiUrl:i.apiUrl||e.apiUrl||$,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 ee(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 B=w(require("mime-types"),1),y=require("@shipstatic/types");var I="/deployments",te="/ping",E="/aliases",xe="/config",Ee="/account",Re="/spa-check";function ke(i){return typeof i=="string"?B.lookup(i)||"application/octet-stream":B.lookup(i.name)||i.type||"application/octet-stream"}async function Te(i){let e=[];for await(let t of i)e.push(t);return e}var R=class{constructor(e){this.apiUrl=e.apiUrl||$,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(r){throw this.#t(r,o),r}}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}${te}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.#e(`${this.apiUrl}${te}`,{method:"GET"},"Ping")}async getConfig(){return await this.#e(`${this.apiUrl}${xe}`,{method:"GET"},"Config")}async deploy(e,t={}){this.#s(e);let{apiUrl:o=this.apiUrl,signal:n,apiKey:s,deployToken:r}=t,{requestBody:c,requestHeaders:m}=await this.#r(e),h={};r?h={Authorization:`Bearer ${r}`}:s&&(h={Authorization:`Bearer ${s}`});let a={method:"POST",body:c,headers:{...m,...h},signal:n||null};return await this.#e(`${o}${I}`,a,"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],r;if(s.content instanceof File||s.content instanceof Blob)r=s.content;else throw y.ShipError.file(`Unsupported file.content type for browser FormData: ${s.path}`,s.path);let c=ke(r instanceof File?r:s.path),m=new File([r],s.path,{type:c});t.append("files[]",m),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"),r=new t,c=[];for(let l=0;l<e.length;l++){let p=e[l],S=B.lookup(p.path)||"application/octet-stream",g;if(Buffer.isBuffer(p.content))g=new o([p.content],p.path,{type:S});else if(typeof Blob<"u"&&p.content instanceof Blob)g=new o([p.content],p.path,{type:S});else throw y.ShipError.file(`Unsupported file.content type for Node.js FormData: ${p.path}`,p.path);let v=p.path.startsWith("/")?p.path:"/"+p.path;r.append("files[]",g,v),c.push(p.md5)}r.append("checksums",JSON.stringify(c));let m=new n(r),h=await Te(m.encode()),a=Buffer.concat(h.map(l=>Buffer.from(l))),d={"Content-Type":m.contentType,"Content-Length":Buffer.byteLength(a).toString()};return{body:a,headers:d}}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}${I}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.#e(`${this.apiUrl}${I}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.#e(`${this.apiUrl}${I}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t){try{let o=await this.#i(`${this.apiUrl}${E}/${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}${E}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${E}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.#e(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async checkAlias(e){return await this.#e(`${this.apiUrl}${E}/${encodeURIComponent(e)}/dns-check`,{method:"POST"},"Check Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${Ee}`,{method:"GET"},"Get Account")}async createApiKey(){return await this.#e(`${this.apiUrl}/key`,{method:"POST"},"Create API Key")}async checkSPA(e){let t=e.find(m=>m.path==="index.html"||m.path==="/index.html");if(!t)return!1;let o=100*1024;if(t.size>o)return!1;let n;if(Buffer.isBuffer(t.content))n=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)n=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)n=await t.content.text();else return!1;let r={files:e.map(m=>m.path),index:n};return(await this.#e(`${this.apiUrl}${Re}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"SPA Check")).isSPA}};var ye=require("@shipstatic/types");var ie=require("@shipstatic/types"),J=null;function oe(i){J=i}function k(){if(J===null)throw ie.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return J}var u=require("@shipstatic/types");var A=require("@shipstatic/types");async function Oe(i){let e=(await import("spark-md5")).default;return new Promise((t,o)=>{let s=Math.ceil(i.size/2097152),r=0,c=new e.ArrayBuffer,m=new FileReader,h=()=>{let a=r*2097152,d=Math.min(a+2097152,i.size);m.readAsArrayBuffer(i.slice(a,d))};m.onload=a=>{let d=a.target?.result;if(!d){o(A.ShipError.business("Failed to read file chunk"));return}c.append(d),r++,r<s?h():t({md5:c.end()})},m.onerror=()=>{o(A.ShipError.business("Failed to calculate MD5: FileReader error"))},h()})}async function $e(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"),r=t.createReadStream(i);r.on("error",c=>n(A.ShipError.business(`Failed to read file for MD5: ${c.message}`))),r.on("data",c=>s.update(c)),r.on("end",()=>o({md5:s.digest("hex")}))})}async function x(i){let e=f();if(e==="browser"){if(!(i instanceof Blob))throw A.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Oe(i)}if(e==="node"){if(!(Buffer.isBuffer(i)||typeof i=="string"))throw A.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return $e(i)}throw A.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var ne=require("junk"),Ie=["__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,ne.isJunk)(o))return!1;let n=t.slice(0,-1);for(let s of n)if(Ie.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var b=require("@shipstatic/types");function U(i){return i.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}function z(i,e={}){if(e.flatten===!1)return i.map(o=>({path:U(o),name:V(o)}));let t=Be(i);return i.map(o=>{let n=U(o);if(t){let s=t.endsWith("/")?t:`${t}/`;n.startsWith(s)&&(n=n.substring(s.length))}return n||(n=V(o)),{path:n,name:V(o)}})}function Be(i){if(!i.length)return"";let t=i.map(s=>U(s)).map(s=>s.split("/")),o=[],n=Math.min(...t.map(s=>s.length));for(let s=0;s<n-1;s++){let r=t[0][s];if(t.every(c=>c[s]===r))o.push(r);else break}return o.join("/")}function V(i){return i.split(/[/\\]/).pop()||i}var D=w(require("fs"),1),P=w(require("path"),1);function re(i){let e=[];try{let t=D.readdirSync(i);for(let o of t){let n=P.join(i,o),s=D.statSync(n);if(s.isDirectory()){let r=re(n);e.push(...r)}else s.isFile()&&e.push(n)}}catch(t){console.error(`Error reading directory ${i}:`,t)}return e}async function se(i,e={}){let t=P.resolve(i),n=(()=>{let l=D.statSync(t);return l.isFile()?[t]:l.isDirectory()?re(t):[]})().filter(l=>{let p=P.basename(l);return N([p]).length>0}),r=D.statSync(t).isDirectory()?t:P.dirname(t),c=n.map(l=>P.relative(r,l).replace(/\\/g,"/")||P.basename(l)),m=z(c,{flatten:e.pathDetect!==!1}),h=[],a=0;for(let l=0;l<n.length;l++){let p=n[l],S=m[l].path;try{let g=D.statSync(p);if(g.size===0){console.warn(`Skipping empty file: ${p}`);continue}let v=k();if(g.size>v.maxFileSize)throw b.ShipError.business(`File ${p} is too large. Maximum allowed size is ${v.maxFileSize/(1024*1024)}MB.`);if(a+=g.size,a>v.maxTotalSize)throw b.ShipError.business(`Total deploy size is too large. Maximum allowed is ${v.maxTotalSize/(1024*1024)}MB.`);let j=D.readFileSync(p),{md5:de}=await x(j);if(S.includes("\0")||S.includes("/../")||S.startsWith("../")||S.endsWith("/.."))throw b.ShipError.business(`Security error: Unsafe file path "${S}" for file: ${p}`);h.push({path:S,content:j,size:j.length,md5:de})}catch(g){if(g instanceof b.ShipError&&g.isClientError&&g.isClientError())throw g;console.error(`Could not process file ${p}:`,g)}}let d=k();if(h.length>d.maxFilesCount)throw b.ShipError.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return h}async function L(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 se(o,e);t.push(...n)}return t}return await se(i[0],e)}var W=require("@shipstatic/types");async function _(i,e={}){if(f()!=="browser")throw W.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let t=Array.isArray(i)?i:Array.from(i),o=t.map(a=>a.webkitRelativePath||a.name),n=z(o,{flatten:e.pathDetect!==!1}),s=[];for(let a=0;a<t.length;a++){let d=t[a],l=n[a].path;if(l.includes("..")||l.includes("\0"))throw W.ShipError.business(`Security error: Unsafe file path "${l}" for file: ${d.name}`);s.push({file:d,relativePath:l})}let r=s.map(a=>a.relativePath),c=N(r),m=new Set(c),h=[];for(let a of s){if(!m.has(a.relativePath)||a.file.size===0)continue;let{md5:d}=await x(a.file);h.push({content:a.file,path:a.relativePath,size:a.file.size,md5:d})}return h}function ae(i,e={}){let t=k();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 le(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 pe(i){return ae(i,{skipEmptyCheck:!0}),i.forEach(e=>{e.path&&(e.path=e.path.replace(/\\/g,"/"))}),i}async function Ne(i,e={}){le(i,"node");let t=await L(i,e);return pe(t)}async function Ue(i,e={}){le(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),ae(t);let o=await _(t,e);return pe(o)}async function ce(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 Ne(i,e):n=await Ue(i,e),t&&(n=await Le(n,t,e)),n}async function ze(){let i={rewrites:[{source:"/(.*)",destination:"/index.html"}]},e=Buffer.from(JSON.stringify(i,null,2),"utf-8"),{md5:t}=await x(e);return{path:u.DEPLOYMENT_CONFIG_FILENAME,content:e,size:e.length,md5:t}}async function Le(i,e,t){if(t.spaDetect===!1||i.some(o=>o.path===u.DEPLOYMENT_CONFIG_FILENAME))return i;try{if(await e.checkSPA(i)){let n=await ze();return console.log(`SPA detected - generated ${u.DEPLOYMENT_CONFIG_FILENAME}`),[...i,n]}}catch{console.warn("SPA detection failed, continuing without auto-config")}return i}function me(i,e,t){return{create:async(o,n={})=>{t&&await t();let s=e?ee(n,e):n,r=await ce(o,s,i());return await i().deploy(r,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 fe(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 ue(i,e){return{get:async()=>(e&&await e(),i().getAccount())}}function he(i,e){return{create:async()=>(e&&await e(),i().createApiKey())}}var K=require("@shipstatic/types"),M=class{constructor(e={}){this.initPromise=null;if(this.clientOptions=e,this.environment=f(),this.environment!=="node"&&this.environment!=="browser")throw ye.ShipError.business("Unsupported execution environment.");let t=G(e,{});this.http=new R({...e,...t});let o=this.getInitCallback(),n=()=>this.http;this._deployments=me(n,this.clientOptions,o),this._aliases=fe(n,o),this._account=ue(n,o),this._keys=he(n,o)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.initializeConfig()),this.initPromise}getInitCallback(){return()=>this.ensureInitialized()}async initializeConfig(){try{let e=await Q(this.clientOptions.configFile),t=G(this.clientOptions,e);this.http=new R({...this.clientOptions,...t});let o=await this.http.getConfig();oe(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}},_e=M;0&&(module.exports={Ship,ShipError,ShipErrorType,__setTestEnvironment,processFilesForBrowser,processFilesForNode});
|
|
1
|
+
"use strict";var ge=Object.create;var O=Object.defineProperty;var we=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty;var Fe=(i,e)=>{for(var t in e)O(i,t,{get:e[t],enumerable:!0})},T=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Pe(e))!De.call(i,n)&&n!==t&&O(i,n,{get:()=>e[n],enumerable:!(o=we(e,n))||o.enumerable});return i},Y=(i,e,t)=>(T(i,e,"default"),t&&T(t,e,"default")),w=(i,e,t)=>(t=i!=null?ge(Se(i)):{},T(e||!i||!i.__esModule?O(t,"default",{value:i,enumerable:!0}):t,i)),Ae=i=>T(O({},"__esModule",{value:!0}),i);var Me={};Fe(Me,{Ship:()=>M,ShipError:()=>K.ShipError,ShipErrorType:()=>K.ShipErrorType,__setTestEnvironment:()=>X,default:()=>_e,processFilesForBrowser:()=>_,processFilesForNode:()=>L});module.exports=Ae(Me);var H=null;function X(i){H=i}function be(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function f(){return H||be()}var C=require("zod");var F={};Y(F,require("@shipstatic/types"));var $="https://api.shipstatic.com";var q="ship",ve=C.z.object({apiUrl:C.z.string().url().optional(),apiKey:C.z.string().optional(),deployToken:C.z.string().optional()}).strict();function Z(i){try{return ve.parse(i)}catch(e){if(e instanceof C.z.ZodError){let t=e.issues[0],o=t.path.length>0?` at ${t.path.join(".")}`:"";throw F.ShipError.config(`Configuration validation failed${o}: ${t.message}`)}throw F.ShipError.config("Configuration validation failed")}}async function Ce(i){try{if(f()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),o=e(q,{searchPlaces:[`.${q}rc`,"package.json",`${t.homedir()}/.${q}rc`],stopDir:t.homedir()}),n;if(i?n=o.load(i):n=o.search(),n&&n.config)return Z(n.config)}catch(e){if(e instanceof F.ShipError)throw e}return{}}async function Q(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 Ce(i),o={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Z(o)}function G(i={},e={}){let t={apiUrl:i.apiUrl||e.apiUrl||$,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 ee(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 B=w(require("mime-types"),1),y=require("@shipstatic/types");var I="/deployments",te="/ping",E="/aliases",xe="/config",Ee="/account",Re="/spa-check";function ke(i){return typeof i=="string"?B.lookup(i)||"application/octet-stream":B.lookup(i.name)||i.type||"application/octet-stream"}async function Te(i){let e=[];for await(let t of i)e.push(t);return e}var R=class{constructor(e){this.apiUrl=e.apiUrl||$,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(r){throw this.#t(r,o),r}}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}${te}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.#e(`${this.apiUrl}${te}`,{method:"GET"},"Ping")}async getConfig(){return await this.#e(`${this.apiUrl}${xe}`,{method:"GET"},"Config")}async deploy(e,t={}){this.#s(e);let{apiUrl:o=this.apiUrl,signal:n,apiKey:s,deployToken:r}=t,{requestBody:c,requestHeaders:m}=await this.#r(e),h={};r?h={Authorization:`Bearer ${r}`}:s&&(h={Authorization:`Bearer ${s}`});let a={method:"POST",body:c,headers:{...m,...h},signal:n||null};return await this.#e(`${o}${I}`,a,"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],r;if(s.content instanceof File||s.content instanceof Blob)r=s.content;else throw y.ShipError.file(`Unsupported file.content type for browser FormData: ${s.path}`,s.path);let c=ke(r instanceof File?r:s.path),m=new File([r],s.path,{type:c});t.append("files[]",m),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"),r=new t,c=[];for(let l=0;l<e.length;l++){let p=e[l],S=B.lookup(p.path)||"application/octet-stream",g;if(Buffer.isBuffer(p.content))g=new o([p.content],p.path,{type:S});else if(typeof Blob<"u"&&p.content instanceof Blob)g=new o([p.content],p.path,{type:S});else throw y.ShipError.file(`Unsupported file.content type for Node.js FormData: ${p.path}`,p.path);let v=p.path.startsWith("/")?p.path:"/"+p.path;r.append("files[]",g,v),c.push(p.md5)}r.append("checksums",JSON.stringify(c));let m=new n(r),h=await Te(m.encode()),a=Buffer.concat(h.map(l=>Buffer.from(l))),d={"Content-Type":m.contentType,"Content-Length":Buffer.byteLength(a).toString()};return{body:a,headers:d}}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}${I}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.#e(`${this.apiUrl}${I}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.#e(`${this.apiUrl}${I}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t){try{let o=await this.#i(`${this.apiUrl}${E}/${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}${E}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${E}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.#e(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async checkAlias(e){return await this.#e(`${this.apiUrl}${E}/${encodeURIComponent(e)}/dns-check`,{method:"POST"},"Check Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${Ee}`,{method:"GET"},"Get Account")}async createApiKey(){return await this.#e(`${this.apiUrl}/key`,{method:"POST"},"Create API Key")}async checkSPA(e){let t=e.find(m=>m.path==="index.html"||m.path==="/index.html");if(!t)return!1;let o=100*1024;if(t.size>o)return!1;let n;if(Buffer.isBuffer(t.content))n=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)n=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)n=await t.content.text();else return!1;let r={files:e.map(m=>m.path),index:n};return(await this.#e(`${this.apiUrl}${Re}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"SPA Check")).isSPA}};var ye=require("@shipstatic/types");var ie=require("@shipstatic/types"),J=null;function oe(i){J=i}function k(){if(J===null)throw ie.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return J}var u=require("@shipstatic/types");var A=require("@shipstatic/types");async function Oe(i){let e=(await import("spark-md5")).default;return new Promise((t,o)=>{let s=Math.ceil(i.size/2097152),r=0,c=new e.ArrayBuffer,m=new FileReader,h=()=>{let a=r*2097152,d=Math.min(a+2097152,i.size);m.readAsArrayBuffer(i.slice(a,d))};m.onload=a=>{let d=a.target?.result;if(!d){o(A.ShipError.business("Failed to read file chunk"));return}c.append(d),r++,r<s?h():t({md5:c.end()})},m.onerror=()=>{o(A.ShipError.business("Failed to calculate MD5: FileReader error"))},h()})}async function $e(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"),r=t.createReadStream(i);r.on("error",c=>n(A.ShipError.business(`Failed to read file for MD5: ${c.message}`))),r.on("data",c=>s.update(c)),r.on("end",()=>o({md5:s.digest("hex")}))})}async function x(i){let e=f();if(e==="browser"){if(!(i instanceof Blob))throw A.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Oe(i)}if(e==="node"){if(!(Buffer.isBuffer(i)||typeof i=="string"))throw A.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return $e(i)}throw A.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var ne=require("junk"),Ie=["__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,ne.isJunk)(o))return!1;let n=t.slice(0,-1);for(let s of n)if(Ie.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var b=require("@shipstatic/types");function U(i){return i.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}function z(i,e={}){if(e.flatten===!1)return i.map(o=>({path:U(o),name:V(o)}));let t=Be(i);return i.map(o=>{let n=U(o);if(t){let s=t.endsWith("/")?t:`${t}/`;n.startsWith(s)&&(n=n.substring(s.length))}return n||(n=V(o)),{path:n,name:V(o)}})}function Be(i){if(!i.length)return"";let t=i.map(s=>U(s)).map(s=>s.split("/")),o=[],n=Math.min(...t.map(s=>s.length));for(let s=0;s<n-1;s++){let r=t[0][s];if(t.every(c=>c[s]===r))o.push(r);else break}return o.join("/")}function V(i){return i.split(/[/\\]/).pop()||i}var D=w(require("fs"),1),P=w(require("path"),1);function re(i){let e=[];try{let t=D.readdirSync(i);for(let o of t){let n=P.join(i,o),s=D.statSync(n);if(s.isDirectory()){let r=re(n);e.push(...r)}else s.isFile()&&e.push(n)}}catch(t){console.error(`Error reading directory ${i}:`,t)}return e}async function se(i,e={}){let t=P.resolve(i),n=(()=>{let l=D.statSync(t);return l.isFile()?[t]:l.isDirectory()?re(t):[]})().filter(l=>{let p=P.basename(l);return N([p]).length>0}),r=D.statSync(t).isDirectory()?t:P.dirname(t),c=n.map(l=>P.relative(r,l).replace(/\\/g,"/")||P.basename(l)),m=z(c,{flatten:e.pathDetect!==!1}),h=[],a=0;for(let l=0;l<n.length;l++){let p=n[l],S=m[l].path;try{let g=D.statSync(p);if(g.size===0){console.warn(`Skipping empty file: ${p}`);continue}let v=k();if(g.size>v.maxFileSize)throw b.ShipError.business(`File ${p} is too large. Maximum allowed size is ${v.maxFileSize/(1024*1024)}MB.`);if(a+=g.size,a>v.maxTotalSize)throw b.ShipError.business(`Total deploy size is too large. Maximum allowed is ${v.maxTotalSize/(1024*1024)}MB.`);let j=D.readFileSync(p),{md5:de}=await x(j);if(S.includes("\0")||S.includes("/../")||S.startsWith("../")||S.endsWith("/.."))throw b.ShipError.business(`Security error: Unsafe file path "${S}" for file: ${p}`);h.push({path:S,content:j,size:j.length,md5:de})}catch(g){if(g instanceof b.ShipError&&g.isClientError&&g.isClientError())throw g;console.error(`Could not process file ${p}:`,g)}}let d=k();if(h.length>d.maxFilesCount)throw b.ShipError.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return h}async function L(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 se(o,e);t.push(...n)}return t}return await se(i[0],e)}var W=require("@shipstatic/types");async function _(i,e={}){if(f()!=="browser")throw W.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let t=Array.isArray(i)?i:Array.from(i),o=t.map(a=>a.webkitRelativePath||a.name),n=z(o,{flatten:e.pathDetect!==!1}),s=[];for(let a=0;a<t.length;a++){let d=t[a],l=n[a].path;if(l.includes("..")||l.includes("\0"))throw W.ShipError.business(`Security error: Unsafe file path "${l}" for file: ${d.name}`);s.push({file:d,relativePath:l})}let r=s.map(a=>a.relativePath),c=N(r),m=new Set(c),h=[];for(let a of s){if(!m.has(a.relativePath)||a.file.size===0)continue;let{md5:d}=await x(a.file);h.push({content:a.file,path:a.relativePath,size:a.file.size,md5:d})}return h}function ae(i,e={}){let t=k();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 le(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 pe(i){return ae(i,{skipEmptyCheck:!0}),i.forEach(e=>{e.path&&(e.path=e.path.replace(/\\/g,"/"))}),i}async function Ne(i,e={}){le(i,"node");let t=await L(i,e);return pe(t)}async function Ue(i,e={}){le(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),ae(t);let o=await _(t,e);return pe(o)}async function ce(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 Ne(i,e):n=await Ue(i,e),t&&(n=await Le(n,t,e)),n}async function ze(){let i={rewrites:[{source:"/(.*)",destination:"/index.html"}]},e=Buffer.from(JSON.stringify(i,null,2),"utf-8"),{md5:t}=await x(e);return{path:u.DEPLOYMENT_CONFIG_FILENAME,content:e,size:e.length,md5:t}}async function Le(i,e,t){if(t.spaDetect===!1||i.some(o=>o.path===u.DEPLOYMENT_CONFIG_FILENAME))return i;try{if(await e.checkSPA(i)){let n=await ze();return console.log(`SPA detected - generated ${u.DEPLOYMENT_CONFIG_FILENAME}`),[...i,n]}}catch{console.warn("SPA detection failed, continuing without auto-config")}return i}function me(i,e,t){return{create:async(o,n={})=>{t&&await t();let s=e?ee(n,e):n,r=i(),c=await ce(o,s,r);return await r.deploy(c,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 fe(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 ue(i,e){return{get:async()=>(e&&await e(),i().getAccount())}}function he(i,e){return{create:async()=>(e&&await e(),i().createApiKey())}}var K=require("@shipstatic/types"),M=class{constructor(e={}){this.initPromise=null;if(this.clientOptions=e,this.environment=f(),this.environment!=="node"&&this.environment!=="browser")throw ye.ShipError.business("Unsupported execution environment.");let t=G(e,{});this.http=new R({...e,...t});let o=this.getInitCallback(),n=()=>this.http;this._deployments=me(n,this.clientOptions,o),this._aliases=fe(n,o),this._account=ue(n,o),this._keys=he(n,o)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.initializeConfig()),this.initPromise}getInitCallback(){return()=>this.ensureInitialized()}async initializeConfig(){try{let e=await Q(this.clientOptions.configFile),t=G(this.clientOptions,e);this.http=new R({...this.clientOptions,...t});let o=await this.http.getConfig();oe(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}},_e=M;0&&(module.exports={Ship,ShipError,ShipErrorType,__setTestEnvironment,processFilesForBrowser,processFilesForNode});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|