@shipstatic/ship 0.1.18 → 0.1.20

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/index.d.cts CHANGED
@@ -30,8 +30,10 @@ interface DeploymentOptions {
30
30
  timeout?: number;
31
31
  /** The API key to use for this specific deploy. Overrides client's default. */
32
32
  apiKey?: string;
33
- /** Whether to preserve directory structure. By default, common parent directories are flattened. */
34
- preserveDirs?: boolean;
33
+ /** Whether to auto-detect and optimize file paths by flattening common directories. Defaults to true. */
34
+ pathDetect?: boolean;
35
+ /** Whether to auto-detect SPAs and generate ship.json configuration. Defaults to true. */
36
+ spaDetect?: boolean;
35
37
  /** Callback for overall deploy progress (0-100). */
36
38
  onProgress?: (progress: number) => void;
37
39
  /** Callback for detailed progress statistics. */
@@ -41,7 +43,7 @@ interface DeploymentOptions {
41
43
  * Options for configuring an deploy operation via `apiClient.deployFiles`.
42
44
  * Derived from DeploymentOptions but excludes client-side only options.
43
45
  */
44
- type ApiDeployOptions = Omit<DeploymentOptions, 'preserveDirs'>;
46
+ type ApiDeployOptions = Omit<DeploymentOptions, 'pathDetect'>;
45
47
  /**
46
48
  * Detailed statistics about the progress of an deploy operation.
47
49
  */
@@ -133,6 +135,9 @@ interface AliasResource {
133
135
  get: (aliasName: string) => Promise<Alias>;
134
136
  list: () => Promise<AliasListResponse>;
135
137
  remove: (aliasName: string) => Promise<void>;
138
+ check: (aliasName: string) => Promise<{
139
+ message: string;
140
+ }>;
136
141
  }
137
142
  interface AccountResource {
138
143
  get: () => Promise<Account>;
@@ -156,10 +161,10 @@ declare function processFilesForNode(paths: string[], options?: DeploymentOption
156
161
 
157
162
  /**
158
163
  * Processes browser files (FileList or File[]) into an array of StaticFile objects ready for deploy.
159
- * Calculates MD5, filters junk files, and determines relative paths (stripping basePath if provided).
164
+ * Calculates MD5, filters junk files, and applies automatic path optimization.
160
165
  *
161
166
  * @param browserFiles - FileList or File[] to process for deploy.
162
- * @param options - Optional processing options (basePath for path stripping, preserveDirs).
167
+ * @param options - Processing options including pathDetect for automatic path optimization.
163
168
  * @returns Promise resolving to an array of StaticFile objects.
164
169
  * @throws {ShipClientError} If called outside a browser or with invalid input.
165
170
  */
package/dist/index.d.ts CHANGED
@@ -30,8 +30,10 @@ interface DeploymentOptions {
30
30
  timeout?: number;
31
31
  /** The API key to use for this specific deploy. Overrides client's default. */
32
32
  apiKey?: string;
33
- /** Whether to preserve directory structure. By default, common parent directories are flattened. */
34
- preserveDirs?: boolean;
33
+ /** Whether to auto-detect and optimize file paths by flattening common directories. Defaults to true. */
34
+ pathDetect?: boolean;
35
+ /** Whether to auto-detect SPAs and generate ship.json configuration. Defaults to true. */
36
+ spaDetect?: boolean;
35
37
  /** Callback for overall deploy progress (0-100). */
36
38
  onProgress?: (progress: number) => void;
37
39
  /** Callback for detailed progress statistics. */
@@ -41,7 +43,7 @@ interface DeploymentOptions {
41
43
  * Options for configuring an deploy operation via `apiClient.deployFiles`.
42
44
  * Derived from DeploymentOptions but excludes client-side only options.
43
45
  */
44
- type ApiDeployOptions = Omit<DeploymentOptions, 'preserveDirs'>;
46
+ type ApiDeployOptions = Omit<DeploymentOptions, 'pathDetect'>;
45
47
  /**
46
48
  * Detailed statistics about the progress of an deploy operation.
47
49
  */
@@ -133,6 +135,9 @@ interface AliasResource {
133
135
  get: (aliasName: string) => Promise<Alias>;
134
136
  list: () => Promise<AliasListResponse>;
135
137
  remove: (aliasName: string) => Promise<void>;
138
+ check: (aliasName: string) => Promise<{
139
+ message: string;
140
+ }>;
136
141
  }
137
142
  interface AccountResource {
138
143
  get: () => Promise<Account>;
@@ -156,10 +161,10 @@ declare function processFilesForNode(paths: string[], options?: DeploymentOption
156
161
 
157
162
  /**
158
163
  * Processes browser files (FileList or File[]) into an array of StaticFile objects ready for deploy.
159
- * Calculates MD5, filters junk files, and determines relative paths (stripping basePath if provided).
164
+ * Calculates MD5, filters junk files, and applies automatic path optimization.
160
165
  *
161
166
  * @param browserFiles - FileList or File[] to process for deploy.
162
- * @param options - Optional processing options (basePath for path stripping, preserveDirs).
167
+ * @param options - Processing options including pathDetect for automatic path optimization.
163
168
  * @returns Promise resolving to an array of StaticFile objects.
164
169
  * @throws {ShipClientError} If called outside a browser or with invalid input.
165
170
  */
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var ae=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var pe=Object.getOwnPropertyNames;var ce=Object.prototype.hasOwnProperty;var _=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of pe(e))!ce.call(i,r)&&r!==t&&ae(i,r,{get:()=>e[r],enumerable:!(o=le(e,r))||o.enumerable});return i},j=(i,e,t)=>(_(i,e,"default"),t&&_(t,e,"default"));var U=null;function me(i){U=i}function fe(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function f(){return U||fe()}import{z as x}from"zod";var D={};j(D,Ee);import*as Ee from"@shipstatic/types";var C="https://api.shipstatic.com";var k="ship",ue=x.object({apiUrl:x.string().url().optional(),apiKey:x.string().optional()}).strict();function H(i){try{return ue.parse(i)}catch(e){if(e instanceof x.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 he(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()}),r;if(i?r=o.load(i):r=o.search(),r&&r.config)return H(r.config)}catch(e){if(e instanceof D.ShipError)throw e}return{}}async function G(i){if(f()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY},t=await he(i),o={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey};return H(o)}function B(i={},e={}){let t={apiUrl:i.apiUrl||e.apiUrl||C,apiKey:i.apiKey||e.apiKey};return t.apiKey!==void 0?{apiUrl:t.apiUrl,apiKey:t.apiKey}:{apiUrl:t.apiUrl}}function q(i={},e){return{onProgress:e.onProgress,onProgressStats:e.onProgressStats,maxConcurrency:e.maxConcurrentDeploys,timeout:e.timeout,apiKey:e.apiKey,apiUrl:e.apiUrl,...i}}import*as O from"mime-types";import{ShipError as h}from"@shipstatic/types";var R="/deployments",J="/ping",E="/aliases",ye="/config",de="/account";function ge(i){return typeof i=="string"?O.lookup(i)||"application/octet-stream":O.lookup(i.name)||i.type||"application/octet-stream"}async function we(i){let e=[];for await(let t of i)e.push(t);return e}var F=class{constructor(e){this.apiUrl=e.apiUrl||C,this.apiKey=e.apiKey??""}#r(e={}){let t={...e};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}async#i(e,t={},o){let r=this.#r(t.headers),s={...t,headers:r,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 r=await this.#i(e,t,o);return r.ok||await this.#o(r,o),r.headers.get("Content-Length")==="0"||r.status===204?void 0:await r.json()}catch(r){throw r instanceof h||this.#t(r,o),r}}async ping(){return(await this.#e(`${this.apiUrl}${J}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.#e(`${this.apiUrl}${J}`,{method:"GET"},"Ping")}async getConfig(){return await this.#e(`${this.apiUrl}${ye}`,{method:"GET"},"Config")}async deploy(e,t={}){this.#n(e);let{apiUrl:o=this.apiUrl,signal:r}=t,{requestBody:s,requestHeaders:a}=await this.#s(e),c={method:"POST",body:s,headers:a,signal:r||null};return await this.#e(`${o}${R}`,c,"Deploy")}#n(e){if(!e.length)throw h.business("No files to deploy.");for(let t of e)if(!t.md5)throw h.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async#s(e){let t,o={};if(f()==="browser")t=this.#a(e);else if(f()==="node"){let{body:r,headers:s}=await this.#l(e);t=r,o=s}else throw h.business("Unknown or unsupported execution environment");return{requestBody:t,requestHeaders:o}}#a(e){let t=new FormData,o=[];for(let r=0;r<e.length;r++){let s=e[r],a;if(s.content instanceof File||s.content instanceof Blob)a=s.content;else throw h.file(`Unsupported file.content type for browser FormData: ${s.path}`,s.path);let c=ge(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:r}=await import("form-data-encoder"),s=await import("path"),a=new t,c=[];for(let w=0;w<e.length;w++){let m=e[w],A=O.lookup(m.path)||"application/octet-stream",d;if(Buffer.isBuffer(m.content))d=new o([m.content],m.path,{type:A});else if(typeof Blob<"u"&&m.content instanceof Blob)d=new o([m.content],m.path,{type:A});else throw h.file(`Unsupported file.content type for Node.js FormData: ${m.path}`,m.path);let se=m.path.startsWith("/")?m.path:"/"+m.path;a.append("files[]",d,se),c.push(m.md5)}a.append("checksums",JSON.stringify(c));let u=new r(a),l=await we(u.encode()),n=Buffer.concat(l.map(w=>Buffer.from(w))),p={"Content-Type":u.contentType,"Content-Length":Buffer.byteLength(n).toString()};return{body:n,headers:p}}async#o(e,t){let o={};try{let r=e.headers.get("content-type");r&&r.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 r=o.message||o.error||`${t} failed due to API error`;throw e.status===401?h.authentication(r):h.api(r,e.status,o.code,o)}throw e.status===401?h.authentication(`Authentication failed for ${t}`):h.api(`${t} failed due to API error`,e.status,void 0,o)}#t(e,t){throw e.name==="AbortError"?h.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?h.network(`${t} failed due to network error: ${e.message}`,e):e instanceof h?e:h.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async listDeployments(){return await this.#e(`${this.apiUrl}${R}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.#e(`${this.apiUrl}${R}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.#e(`${this.apiUrl}${R}/${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 getAccount(){return await this.#e(`${this.apiUrl}${de}`,{method:"GET"},"Get Account")}async createApiKey(){return await this.#e(`${this.apiUrl}/key`,{method:"POST"},"Create API Key")}};import{ShipError as Ce}from"@shipstatic/types";import{ShipError as Pe}from"@shipstatic/types";var N=null;function W(i){N=i}function S(){if(N===null)throw Pe.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return N}import{ShipError as g}from"@shipstatic/types";import{ShipError as v}from"@shipstatic/types";async function De(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 n=a*2097152,p=Math.min(n+2097152,i.size);u.readAsArrayBuffer(i.slice(n,p))};u.onload=n=>{let p=n.target?.result;if(!p){o(v.business("Failed to read file chunk"));return}c.append(p),a++,a<s?l():t({md5:c.end()})},u.onerror=()=>{o(v.business("Failed to calculate MD5: FileReader error"))},l()})}async function ve(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,r)=>{let s=e.createHash("md5"),a=t.createReadStream(i);a.on("error",c=>r(v.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 $(i){let e=f();if(e==="browser"){if(!(i instanceof Blob))throw v.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return De(i)}if(e==="node"){if(!(Buffer.isBuffer(i)||typeof i=="string"))throw v.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return ve(i)}throw v.business("Unknown or unsupported execution environment for MD5 calculation.")}import{isJunk as Fe}from"junk";var Se=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"];function T(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(Fe(o))return!1;let r=t.slice(0,-1);for(let s of r)if(Se.some(a=>s.toLowerCase()===a.toLowerCase()))return!1;return!0})}import{ShipError as b}from"@shipstatic/types";function I(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=[],r=Math.min(...t.map(s=>s.length));for(let s=0;s<r;s++){let a=t[0][s];if(t.every(c=>c[s]===a))o.push(a);else break}return o.join("/")}function L(i){return i.replace(/\\/g,"/").replace(/^\/+/,"")}import*as P from"fs";import*as y from"path";function Y(i){let e=[];try{let t=P.readdirSync(i);for(let o of t){let r=y.join(i,o),s=P.statSync(r);if(s.isDirectory()){let a=Y(r);e.push(...a)}else s.isFile()&&e.push(r)}}catch(t){console.error(`Error reading directory ${i}:`,t)}return e}async function V(i,e={}){let t=y.resolve(i),r=(()=>{let n=P.statSync(t);return n.isFile()?[t]:n.isDirectory()?Y(t):[]})().filter(n=>{let p=y.basename(n);return T([p]).length>0}),s=P.statSync(t),a;if(e.preserveDirs)a=s.isDirectory()?t:y.dirname(t);else{let n=r.map(p=>y.dirname(p));a=I(n)}let c=[],u=0;for(let n of r)try{let p=P.statSync(n);if(p.size===0){console.warn(`Skipping empty file: ${n}`);continue}let w=S();if(p.size>w.maxFileSize)throw b.business(`File ${n} is too large. Maximum allowed size is ${w.maxFileSize/(1024*1024)}MB.`);if(u+=p.size,u>w.maxTotalSize)throw b.business(`Total deploy size is too large. Maximum allowed is ${w.maxTotalSize/(1024*1024)}MB.`);let m=P.readFileSync(n),{md5:A}=await $(m),d=y.relative(a,n).replace(/\\/g,"/");(d.includes("\0")||d.includes("/../")||d.startsWith("../")||d.endsWith("/.."))&&(d=y.basename(n)),d||(d=y.basename(n)),c.push({path:d,content:m,size:m.length,md5:A})}catch(p){if(p instanceof b&&p.isClientError&&p.isClientError())throw p;console.error(`Could not process file ${n}:`,p)}let l=S();if(c.length>l.maxFilesCount)throw b.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return c}async function z(i,e={}){if(f()!=="node")throw b.business("processFilesForNode can only be called in a Node.js environment.");if(i.length>1){let t=[];for(let o of i){let r=await V(o,e);t.push(...r)}return t}return await V(i[0],e)}import{ShipError as X}from"@shipstatic/types";async function M(i,e={}){if(f()!=="browser")throw X.business("processFilesForBrowser can only be called in a browser environment.");let t=Array.isArray(i)?i:Array.from(i),o="";if(!e.preserveDirs){let l=t.map(n=>n.webkitRelativePath||n.name).filter(n=>n).map(n=>n.includes("/")?n.substring(0,n.lastIndexOf("/")):"");o=I(l)}let r=[];for(let l of t){let n=l.webkitRelativePath||l.name;if(o&&!e.preserveDirs){n=L(n);let p=o.endsWith("/")?o:`${o}/`;n.startsWith(p)?n=n.substring(p.length):n===o&&(n="")}if(n=L(n),n.includes("..")||n.includes("\0"))throw X.business(`Security error: Unsafe file path "${n}" for file: ${l.name}`);n||(n=l.name),r.push({file:l,relativePath:n})}let s=r.map(l=>l.relativePath),a=T(s),c=new Set(a),u=[];for(let l of r){if(!c.has(l.relativePath)||l.file.size===0)continue;let{md5:n}=await $(l.file);u.push({content:l.file,path:l.relativePath,size:l.file.size,md5:n})}return u}function Z(i,e={}){let t=S();if(!e.skipEmptyCheck&&i.length===0)throw g.business("No files to deploy.");if(i.length>t.maxFilesCount)throw g.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let o=0;for(let r of i){if(r.size>t.maxFileSize)throw g.business(`File ${r.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(o+=r.size,o>t.maxTotalSize)throw g.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Q(i,e){if(e==="node"){if(!Array.isArray(i))throw g.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(i.length===0)throw g.business("No files to deploy.");if(!i.every(t=>typeof t=="string"))throw g.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&i instanceof HTMLInputElement&&!i.files)throw g.business("No files selected in HTMLInputElement")}function ee(i){return Z(i,{skipEmptyCheck:!0}),i.forEach(e=>{e.path&&(e.path=e.path.replace(/\\/g,"/"))}),i}async function be(i,e={}){Q(i,"node");let t=await z(i,e);return ee(t)}async function Ae(i,e={}){Q(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 g.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=i}else throw g.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(r=>r.size===0?(console.warn(`Skipping empty file: ${r.name}`),!1):!0),Z(t);let o=await M(t,e);return ee(o)}async function te(i,e={}){let t=f();if(t!=="node"&&t!=="browser")throw g.business("Unsupported execution environment.");return t==="node"?be(i,e):Ae(i,e)}function ie(i,e,t){return{create:async(o,r={})=>{t&&await t();let s=e?q(r,e):r,a=await te(o,s);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 oe(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)}}}function re(i,e){return{get:async()=>(e&&await e(),i().getAccount())}}function ne(i,e){return{create:async()=>(e&&await e(),i().createApiKey())}}import{ShipError as xt,ShipErrorType as Rt}from"@shipstatic/types";var K=class{constructor(e={}){this.initPromise=null;if(this.clientOptions=e,this.environment=f(),this.environment!=="node"&&this.environment!=="browser")throw Ce.business("Unsupported execution environment.");let t=B(e,{});this.http=new F({...e,...t});let o=this.getInitCallback(),r=()=>this.http;this._deployments=ie(r,this.clientOptions,o),this._aliases=oe(r,o),this._account=re(r,o),this._keys=ne(r,o)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.initializeConfig()),this.initPromise}getInitCallback(){return()=>this.ensureInitialized()}async initializeConfig(){try{let e=await G(this.clientOptions.configFile),t=B(this.clientOptions,e);this.http=new F({...this.clientOptions,...t});let o=await this.http.getConfig();W(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}},bt=K;export{K as Ship,xt as ShipError,Rt as ShipErrorType,me as __setTestEnvironment,bt as default,M as processFilesForBrowser,z as processFilesForNode};
1
+ var le=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var pe=Object.getOwnPropertyNames;var me=Object.prototype.hasOwnProperty;var j=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of pe(e))!me.call(i,n)&&n!==t&&le(i,n,{get:()=>e[n],enumerable:!(o=ce(e,n))||o.enumerable});return i},H=(i,e,t)=>(j(i,e,"default"),t&&j(t,e,"default"));var I=null;function fe(i){I=i}function ue(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function f(){return I||ue()}import{z as R}from"zod";var S={};H(S,ke);import*as ke from"@shipstatic/types";var E="https://api.shipstatic.com";var U="ship",he=R.object({apiUrl:R.string().url().optional(),apiKey:R.string().optional()}).strict();function G(i){try{return he.parse(i)}catch(e){if(e instanceof R.ZodError){let t=e.issues[0],o=t.path.length>0?` at ${t.path.join(".")}`:"";throw S.ShipError.config(`Configuration validation failed${o}: ${t.message}`)}throw S.ShipError.config("Configuration validation failed")}}async function ye(i){try{if(f()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),o=e(U,{searchPlaces:[`.${U}rc`,"package.json",`${t.homedir()}/.${U}rc`],stopDir:t.homedir()}),n;if(i?n=o.load(i):n=o.search(),n&&n.config)return G(n.config)}catch(e){if(e instanceof S.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},t=await ye(i),o={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey};return G(o)}function N(i={},e={}){let t={apiUrl:i.apiUrl||e.apiUrl||E,apiKey:i.apiKey||e.apiKey};return t.apiKey!==void 0?{apiUrl:t.apiUrl,apiKey:t.apiKey}:{apiUrl:t.apiUrl}}function J(i={},e){return{onProgress:e.onProgress,onProgressStats:e.onProgressStats,maxConcurrency:e.maxConcurrentDeploys,timeout:e.timeout,apiKey:e.apiKey,apiUrl:e.apiUrl,...i}}import*as $ from"mime-types";import{ShipError as h}from"@shipstatic/types";var O="/deployments",W="/ping",A="/aliases",de="/config",ge="/account",we="/spa-check";function Pe(i){return typeof i=="string"?$.lookup(i)||"application/octet-stream":$.lookup(i.name)||i.type||"application/octet-stream"}async function Se(i){let e=[];for await(let t of i)e.push(t);return e}var b=class{constructor(e){this.apiUrl=e.apiUrl||E,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||this.#t(n,o),n}}async ping(){return(await this.#e(`${this.apiUrl}${W}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.#e(`${this.apiUrl}${W}`,{method:"GET"},"Ping")}async getConfig(){return await this.#e(`${this.apiUrl}${de}`,{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}${O}`,p,"Deploy")}#s(e){if(!e.length)throw h.business("No files to deploy.");for(let t of e)if(!t.md5)throw h.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.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.file(`Unsupported file.content type for browser FormData: ${s.path}`,s.path);let p=Pe(a instanceof File?a:s.path),u=new File([a],s.path,{type:p});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,p=[];for(let w=0;w<e.length;w++){let m=e[w],x=$.lookup(m.path)||"application/octet-stream",d;if(Buffer.isBuffer(m.content))d=new o([m.content],m.path,{type:x});else if(typeof Blob<"u"&&m.content instanceof Blob)d=new o([m.content],m.path,{type:x});else throw h.file(`Unsupported file.content type for Node.js FormData: ${m.path}`,m.path);let ae=m.path.startsWith("/")?m.path:"/"+m.path;a.append("files[]",d,ae),p.push(m.md5)}a.append("checksums",JSON.stringify(p));let u=new n(a),l=await Se(u.encode()),r=Buffer.concat(l.map(w=>Buffer.from(w))),c={"Content-Type":u.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.authentication(n):h.api(n,e.status,o.code,o)}throw e.status===401?h.authentication(`Authentication failed for ${t}`):h.api(`${t} failed due to API error`,e.status,void 0,o)}#t(e,t){throw e.name==="AbortError"?h.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?h.network(`${t} failed due to network error: ${e.message}`,e):e instanceof h?e:h.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async listDeployments(){return await this.#e(`${this.apiUrl}${O}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.#e(`${this.apiUrl}${O}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.#e(`${this.apiUrl}${O}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t){try{let o=await this.#i(`${this.apiUrl}${A}/${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}${A}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${A}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.#e(`${this.apiUrl}${A}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async checkAlias(e){return await this.#e(`${this.apiUrl}${A}/${encodeURIComponent(e)}/dns-check`,{method:"POST"},"Check Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${ge}`,{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}${we}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:e})},"SPA Check")).isSPA}};import{ShipError as Oe}from"@shipstatic/types";import{ShipError as De}from"@shipstatic/types";var B=null;function V(i){B=i}function v(){if(B===null)throw De.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return B}import{ShipError as g,DEPLOYMENT_CONFIG_FILENAME as _}from"@shipstatic/types";import{ShipError as D}from"@shipstatic/types";async function Fe(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,u=new FileReader,l=()=>{let r=a*2097152,c=Math.min(r+2097152,i.size);u.readAsArrayBuffer(i.slice(r,c))};u.onload=r=>{let c=r.target?.result;if(!c){o(D.business("Failed to read file chunk"));return}p.append(c),a++,a<s?l():t({md5:p.end()})},u.onerror=()=>{o(D.business("Failed to calculate MD5: FileReader error"))},l()})}async function Ae(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(D.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 F(i){let e=f();if(e==="browser"){if(!(i instanceof Blob))throw D.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Fe(i)}if(e==="node"){if(!(Buffer.isBuffer(i)||typeof i=="string"))throw D.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Ae(i)}throw D.business("Unknown or unsupported execution environment for MD5 calculation.")}import{isJunk as be}from"junk";var ve=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"];function T(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(be(o))return!1;let n=t.slice(0,-1);for(let s of n)if(ve.some(a=>s.toLowerCase()===a.toLowerCase()))return!1;return!0})}import{ShipError as C}from"@shipstatic/types";function k(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 L(i){return i.replace(/\\/g,"/").replace(/^\/+/,"")}import*as P from"fs";import*as y from"path";function X(i){let e=[];try{let t=P.readdirSync(i);for(let o of t){let n=y.join(i,o),s=P.statSync(n);if(s.isDirectory()){let a=X(n);e.push(...a)}else s.isFile()&&e.push(n)}}catch(t){console.error(`Error reading directory ${i}:`,t)}return e}async function Y(i,e={}){let t=y.resolve(i),n=(()=>{let r=P.statSync(t);return r.isFile()?[t]:r.isDirectory()?X(t):[]})().filter(r=>{let c=y.basename(r);return T([c]).length>0}),s=P.statSync(t),a;if(e.pathDetect===!1)a=s.isDirectory()?t:y.dirname(t);else{let r=n.map(c=>y.dirname(c));a=k(r)}let p=[],u=0;for(let r of n)try{let c=P.statSync(r);if(c.size===0){console.warn(`Skipping empty file: ${r}`);continue}let w=v();if(c.size>w.maxFileSize)throw C.business(`File ${r} is too large. Maximum allowed size is ${w.maxFileSize/(1024*1024)}MB.`);if(u+=c.size,u>w.maxTotalSize)throw C.business(`Total deploy size is too large. Maximum allowed is ${w.maxTotalSize/(1024*1024)}MB.`);let m=P.readFileSync(r),{md5:x}=await F(m),d=y.relative(a,r).replace(/\\/g,"/");(d.includes("\0")||d.includes("/../")||d.startsWith("../")||d.endsWith("/.."))&&(d=y.basename(r)),d||(d=y.basename(r)),p.push({path:d,content:m,size:m.length,md5:x})}catch(c){if(c instanceof C&&c.isClientError&&c.isClientError())throw c;console.error(`Could not process file ${r}:`,c)}let l=v();if(p.length>l.maxFilesCount)throw C.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return p}async function z(i,e={}){if(f()!=="node")throw C.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 Y(o,e);t.push(...n)}return t}return await Y(i[0],e)}import{ShipError as Z}from"@shipstatic/types";async function M(i,e={}){if(f()!=="browser")throw Z.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=k(l)}let n=[];for(let l of t){let r=l.webkitRelativePath||l.name;if(o&&e.pathDetect!==!1){r=L(r);let c=o.endsWith("/")?o:`${o}/`;r.startsWith(c)?r=r.substring(c.length):r===o&&(r="")}if(r=L(r),r.includes("..")||r.includes("\0"))throw Z.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=T(s),p=new Set(a),u=[];for(let l of n){if(!p.has(l.relativePath)||l.file.size===0)continue;let{md5:r}=await F(l.file);u.push({content:l.file,path:l.relativePath,size:l.file.size,md5:r})}return u}function Q(i,e={}){let t=v();if(!e.skipEmptyCheck&&i.length===0)throw g.business("No files to deploy.");if(i.length>t.maxFilesCount)throw g.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 g.business(`File ${n.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(o+=n.size,o>t.maxTotalSize)throw g.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function ee(i,e){if(e==="node"){if(!Array.isArray(i))throw g.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(i.length===0)throw g.business("No files to deploy.");if(!i.every(t=>typeof t=="string"))throw g.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&i instanceof HTMLInputElement&&!i.files)throw g.business("No files selected in HTMLInputElement")}function te(i){return Q(i,{skipEmptyCheck:!0}),i.forEach(e=>{e.path&&(e.path=e.path.replace(/\\/g,"/"))}),i}async function Ce(i,e={}){ee(i,"node");let t=await z(i,e);return te(t)}async function xe(i,e={}){ee(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 g.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=i}else throw g.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),Q(t);let o=await M(t,e);return te(o)}async function ie(i,e={},t){let o=f();if(o!=="node"&&o!=="browser")throw g.business("Unsupported execution environment.");let n;return o==="node"?n=await Ce(i,e):n=await xe(i,e),t&&(n=await Re(n,t,e)),n}async function Ee(){let i={rewrites:[{source:"/(.*)",destination:"/index.html"}]},e=Buffer.from(JSON.stringify(i,null,2),"utf-8"),{md5:t}=await F(e);return{path:_,content:e,size:e.length,md5:t}}async function Re(i,e,t){if(t.spaDetect===!1||i.some(o=>o.path===_))return i;try{let o=i.map(s=>s.path);if(await e.checkSPA(o)){let s=await Ee();return console.log(`SPA detected - generated ${_}`),[...i,s]}}catch{console.warn("SPA detection failed, continuing without auto-config")}return i}function oe(i,e,t){return{create:async(o,n={})=>{t&&await t();let s=e?J(n,e):n,a=await ie(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 ne(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 se(i,e){return{get:async()=>(e&&await e(),i().getAccount())}}function re(i,e){return{create:async()=>(e&&await e(),i().createApiKey())}}import{ShipError as Tt,ShipErrorType as kt}from"@shipstatic/types";var K=class{constructor(e={}){this.initPromise=null;if(this.clientOptions=e,this.environment=f(),this.environment!=="node"&&this.environment!=="browser")throw Oe.business("Unsupported execution environment.");let t=N(e,{});this.http=new b({...e,...t});let o=this.getInitCallback(),n=()=>this.http;this._deployments=oe(n,this.clientOptions,o),this._aliases=ne(n,o),this._account=se(n,o),this._keys=re(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=N(this.clientOptions,e);this.http=new b({...this.clientOptions,...t});let o=await this.http.getConfig();V(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}},Rt=K;export{K as Ship,Tt as ShipError,kt as ShipErrorType,fe as __setTestEnvironment,Rt as default,M as processFilesForBrowser,z as processFilesForNode};
2
2
  //# sourceMappingURL=index.js.map