@shipstatic/ship 2.2.0-beta.6 → 2.2.0-beta.7
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 +10 -4
- package/THIRD-PARTY-LICENSES.md +1 -1
- package/dist/browser.d.ts +79 -13
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +20 -20
- 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 +79 -13
- package/dist/index.d.ts +79 -13
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/package.json +2 -2
package/dist/index.d.cts
CHANGED
|
@@ -725,6 +725,23 @@ declare const ErrorType: {
|
|
|
725
725
|
readonly Maintenance: "maintenance";
|
|
726
726
|
/** Network/connection error. Client-side only — set by HTTP clients on fetch failure; never produced server-side. */
|
|
727
727
|
readonly Network: "network_error";
|
|
728
|
+
/**
|
|
729
|
+
* A deadline expired before the exchange completed. Client-side only — set
|
|
730
|
+
* by HTTP clients when a timeout signal fires; never produced server-side.
|
|
731
|
+
*
|
|
732
|
+
* A member of the NETWORK category rather than a sibling of it:
|
|
733
|
+
* `isNetworkError()` answers "nothing was exchanged", which is true of a
|
|
734
|
+
* deadline exactly as it is of a refused connection, so every consumer that
|
|
735
|
+
* retries, declines to report, or declines to relay a wire message on that
|
|
736
|
+
* category is already right about a timeout. The distinct TYPE exists for
|
|
737
|
+
* the one decision the category cannot make — what to SAY. "Check your
|
|
738
|
+
* internet connection" is the wrong sentence for a five-minute deploy
|
|
739
|
+
* ceiling, and a surface can only tell the two apart by type.
|
|
740
|
+
*
|
|
741
|
+
* The same relationship every comparable SDK ships:
|
|
742
|
+
* `APIConnectionTimeoutError extends APIConnectionError`.
|
|
743
|
+
*/
|
|
744
|
+
readonly Timeout: "timeout_error";
|
|
728
745
|
/** Operation was cancelled. Client-side only — set on `AbortSignal` abort; never produced server-side. */
|
|
729
746
|
readonly Cancelled: "operation_cancelled";
|
|
730
747
|
/** File operation error. Client-side only — set by SDK during local file processing; never produced server-side. */
|
|
@@ -769,7 +786,7 @@ declare class ShipError extends Error {
|
|
|
769
786
|
* on the client). Falls back to status-derived (401 → Authentication,
|
|
770
787
|
* 403 → Forbidden, 429 → RateLimit, else → Api) for non-API responses
|
|
771
788
|
* (CDN errors, intermediaries) or malformed bodies. Client-only types
|
|
772
|
-
* (`Network`, `Cancelled`, `File`, `Config`) are filtered out of the
|
|
789
|
+
* (`Network`, `Timeout`, `Cancelled`, `File`, `Config`) are filtered out of the
|
|
773
790
|
* trusted set — a misbehaving server claiming one of those is ignored.
|
|
774
791
|
*
|
|
775
792
|
* `operationName` (e.g. `"Get account"`) is used to compose the fallback
|
|
@@ -789,8 +806,9 @@ declare class ShipError extends Error {
|
|
|
789
806
|
* Routing:
|
|
790
807
|
* - Already a `ShipError` → returned as-is (caller's intent preserved)
|
|
791
808
|
* - `AbortError` → `ShipError.cancelled(...)` — someone stopped it on purpose
|
|
792
|
-
* - `TimeoutError` → `ShipError.
|
|
793
|
-
*
|
|
809
|
+
* - `TimeoutError` → `ShipError.timeout(...)` — a deadline expired; the
|
|
810
|
+
* message names the timeout, and the type is in the network CATEGORY
|
|
811
|
+
* because nothing was exchanged
|
|
794
812
|
* - A transport failure → `ShipError.network(...)` — see `isTransportFailure`
|
|
795
813
|
* for what each runtime offers as evidence
|
|
796
814
|
* - Any other `Error` → `ShipError(Api, ...)` (no HTTP status — fetch never reached the server)
|
|
@@ -837,6 +855,14 @@ declare class ShipError extends Error {
|
|
|
837
855
|
static authentication(message?: string, details?: unknown): ShipError;
|
|
838
856
|
static business(message: string, status?: number, details?: unknown): ShipError;
|
|
839
857
|
static network(message: string, details?: unknown): ShipError;
|
|
858
|
+
/**
|
|
859
|
+
* A deadline expired before the exchange completed.
|
|
860
|
+
*
|
|
861
|
+
* Statusless like its four client-only siblings: no exchange completed, so
|
|
862
|
+
* there is no HTTP status to report. `isNetworkError()` is true — see
|
|
863
|
+
* `ErrorType.Timeout` for why the category is shared and the type is not.
|
|
864
|
+
*/
|
|
865
|
+
static timeout(message: string, details?: unknown): ShipError;
|
|
840
866
|
static cancelled(message: string, details?: unknown): ShipError;
|
|
841
867
|
static file(message: string, details?: unknown): ShipError;
|
|
842
868
|
static config(message: string, details?: unknown): ShipError;
|
|
@@ -1964,17 +1990,45 @@ interface ShipClientOptions {
|
|
|
1964
1990
|
deployEndpoint?: string | undefined;
|
|
1965
1991
|
}
|
|
1966
1992
|
/**
|
|
1967
|
-
* Event map for Ship SDK events
|
|
1968
|
-
*
|
|
1993
|
+
* Event map for Ship SDK events.
|
|
1994
|
+
*
|
|
1995
|
+
* **Every failure is visible, and the event NAME says whether it ended the
|
|
1996
|
+
* call.** One call emits `retry* (error | response)` — so the stream is
|
|
1997
|
+
* unambiguous at every prefix, and a consumer never has to wait to find out
|
|
1998
|
+
* what it is watching.
|
|
1999
|
+
*
|
|
2000
|
+
* `request` counts what went out; `retry` counts what failed and will be
|
|
2001
|
+
* tried again; `error` and `response` are the two terminal answers, exactly
|
|
2002
|
+
* one of which arrives.
|
|
1969
2003
|
*/
|
|
1970
2004
|
interface ShipEvents {
|
|
1971
|
-
/** Emitted before each API request */
|
|
2005
|
+
/** Emitted before each API request — once per ATTEMPT, so it counts what actually went out. */
|
|
1972
2006
|
request: [url: string, init: RequestInit];
|
|
1973
|
-
/** Emitted after successful API response */
|
|
2007
|
+
/** Emitted after successful API response — once, on the attempt that worked. */
|
|
1974
2008
|
response: [response: Response, url: string];
|
|
1975
2009
|
/**
|
|
1976
|
-
* Emitted when
|
|
1977
|
-
* the
|
|
2010
|
+
* Emitted when an attempt failed and the client is going to try again.
|
|
2011
|
+
* Carries the same normalized `ShipError` the terminal `error` would, plus
|
|
2012
|
+
* `attempt` — the number of the attempt that just failed, counting from 1,
|
|
2013
|
+
* which matches the arithmetic the docs use ("two retries by default, so
|
|
2014
|
+
* three attempts"). Under that numbering the value reads both ways at once:
|
|
2015
|
+
* attempt N failing IS retry N, so `retry 1 of ${maxRetries}` needs no
|
|
2016
|
+
* adjustment.
|
|
2017
|
+
*
|
|
2018
|
+
* This event exists so `error` can keep meaning what it always meant. When
|
|
2019
|
+
* retries landed, `error` fired per attempt — honest about what happened,
|
|
2020
|
+
* but it silently redefined the event: a consumer seeing `error, error,
|
|
2021
|
+
* response` could not tell "failed, retrying" from "failed, terminally" at
|
|
2022
|
+
* any prefix, and counting `error`s no longer counted failed calls. Two
|
|
2023
|
+
* names, two meanings, and nothing lost: every failure is still announced.
|
|
2024
|
+
*
|
|
2025
|
+
* A failure the loop will NOT retry is terminal and emits `error` directly,
|
|
2026
|
+
* never this. So is an abort that lands mid-backoff.
|
|
2027
|
+
*/
|
|
2028
|
+
retry: [error: Error, url: string, attempt: number];
|
|
2029
|
+
/**
|
|
2030
|
+
* Emitted when the CALL failed — terminally, exactly once. TWO populations
|
|
2031
|
+
* arrive here, which is why the type is `Error` and not `ShipError`:
|
|
1978
2032
|
*
|
|
1979
2033
|
* - a failed request — always a `ShipError` (`executeRequest` normalizes
|
|
1980
2034
|
* every failure through `ShipError.fromFetchError` before emitting), so
|
|
@@ -2052,9 +2106,16 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
2052
2106
|
* for headers, the timeout signal, the events and error normalization — so
|
|
2053
2107
|
* an attempt is a whole request and nothing has to be undone between two.
|
|
2054
2108
|
*
|
|
2055
|
-
* **
|
|
2056
|
-
*
|
|
2057
|
-
*
|
|
2109
|
+
* **Every failure is visible, and the event NAME says whether it ended the
|
|
2110
|
+
* call.** One call emits `retry* (error | response)`: `request` fires per
|
|
2111
|
+
* attempt, so a consumer counting requests sees what actually went out; a
|
|
2112
|
+
* failure that will be tried again is a `retry`; `error` and `response` are
|
|
2113
|
+
* the two terminal answers, exactly one of which arrives.
|
|
2114
|
+
*
|
|
2115
|
+
* The failure events are emitted HERE rather than in `attemptOnce`, and
|
|
2116
|
+
* that placement is the whole mechanism: terminality is a property of the
|
|
2117
|
+
* loop — of `isRetryable` and the attempt budget — so it is knowable only
|
|
2118
|
+
* at the one point that owns both. An attempt cannot name its own failure.
|
|
2058
2119
|
*
|
|
2059
2120
|
* **The caller's `timeout` governs an ATTEMPT, not the wall clock.** Each
|
|
2060
2121
|
* attempt is an honest request and deserves the ceiling the caller named;
|
|
@@ -2073,7 +2134,12 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
2073
2134
|
/** Did this request carry the header that makes a repeat safe? */
|
|
2074
2135
|
private hasIdempotencyKey;
|
|
2075
2136
|
/**
|
|
2076
|
-
* One attempt: headers, timeout signal, events, and
|
|
2137
|
+
* One attempt: headers, timeout signal, the `request`/`response` events, and
|
|
2138
|
+
* error normalization.
|
|
2139
|
+
*
|
|
2140
|
+
* It does NOT emit a failure event. An attempt cannot know whether its own
|
|
2141
|
+
* failure ended the call — that is `executeRequest`'s question — so it
|
|
2142
|
+
* normalizes and throws, and the loop names what happened.
|
|
2077
2143
|
*/
|
|
2078
2144
|
private attemptOnce;
|
|
2079
2145
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -725,6 +725,23 @@ declare const ErrorType: {
|
|
|
725
725
|
readonly Maintenance: "maintenance";
|
|
726
726
|
/** Network/connection error. Client-side only — set by HTTP clients on fetch failure; never produced server-side. */
|
|
727
727
|
readonly Network: "network_error";
|
|
728
|
+
/**
|
|
729
|
+
* A deadline expired before the exchange completed. Client-side only — set
|
|
730
|
+
* by HTTP clients when a timeout signal fires; never produced server-side.
|
|
731
|
+
*
|
|
732
|
+
* A member of the NETWORK category rather than a sibling of it:
|
|
733
|
+
* `isNetworkError()` answers "nothing was exchanged", which is true of a
|
|
734
|
+
* deadline exactly as it is of a refused connection, so every consumer that
|
|
735
|
+
* retries, declines to report, or declines to relay a wire message on that
|
|
736
|
+
* category is already right about a timeout. The distinct TYPE exists for
|
|
737
|
+
* the one decision the category cannot make — what to SAY. "Check your
|
|
738
|
+
* internet connection" is the wrong sentence for a five-minute deploy
|
|
739
|
+
* ceiling, and a surface can only tell the two apart by type.
|
|
740
|
+
*
|
|
741
|
+
* The same relationship every comparable SDK ships:
|
|
742
|
+
* `APIConnectionTimeoutError extends APIConnectionError`.
|
|
743
|
+
*/
|
|
744
|
+
readonly Timeout: "timeout_error";
|
|
728
745
|
/** Operation was cancelled. Client-side only — set on `AbortSignal` abort; never produced server-side. */
|
|
729
746
|
readonly Cancelled: "operation_cancelled";
|
|
730
747
|
/** File operation error. Client-side only — set by SDK during local file processing; never produced server-side. */
|
|
@@ -769,7 +786,7 @@ declare class ShipError extends Error {
|
|
|
769
786
|
* on the client). Falls back to status-derived (401 → Authentication,
|
|
770
787
|
* 403 → Forbidden, 429 → RateLimit, else → Api) for non-API responses
|
|
771
788
|
* (CDN errors, intermediaries) or malformed bodies. Client-only types
|
|
772
|
-
* (`Network`, `Cancelled`, `File`, `Config`) are filtered out of the
|
|
789
|
+
* (`Network`, `Timeout`, `Cancelled`, `File`, `Config`) are filtered out of the
|
|
773
790
|
* trusted set — a misbehaving server claiming one of those is ignored.
|
|
774
791
|
*
|
|
775
792
|
* `operationName` (e.g. `"Get account"`) is used to compose the fallback
|
|
@@ -789,8 +806,9 @@ declare class ShipError extends Error {
|
|
|
789
806
|
* Routing:
|
|
790
807
|
* - Already a `ShipError` → returned as-is (caller's intent preserved)
|
|
791
808
|
* - `AbortError` → `ShipError.cancelled(...)` — someone stopped it on purpose
|
|
792
|
-
* - `TimeoutError` → `ShipError.
|
|
793
|
-
*
|
|
809
|
+
* - `TimeoutError` → `ShipError.timeout(...)` — a deadline expired; the
|
|
810
|
+
* message names the timeout, and the type is in the network CATEGORY
|
|
811
|
+
* because nothing was exchanged
|
|
794
812
|
* - A transport failure → `ShipError.network(...)` — see `isTransportFailure`
|
|
795
813
|
* for what each runtime offers as evidence
|
|
796
814
|
* - Any other `Error` → `ShipError(Api, ...)` (no HTTP status — fetch never reached the server)
|
|
@@ -837,6 +855,14 @@ declare class ShipError extends Error {
|
|
|
837
855
|
static authentication(message?: string, details?: unknown): ShipError;
|
|
838
856
|
static business(message: string, status?: number, details?: unknown): ShipError;
|
|
839
857
|
static network(message: string, details?: unknown): ShipError;
|
|
858
|
+
/**
|
|
859
|
+
* A deadline expired before the exchange completed.
|
|
860
|
+
*
|
|
861
|
+
* Statusless like its four client-only siblings: no exchange completed, so
|
|
862
|
+
* there is no HTTP status to report. `isNetworkError()` is true — see
|
|
863
|
+
* `ErrorType.Timeout` for why the category is shared and the type is not.
|
|
864
|
+
*/
|
|
865
|
+
static timeout(message: string, details?: unknown): ShipError;
|
|
840
866
|
static cancelled(message: string, details?: unknown): ShipError;
|
|
841
867
|
static file(message: string, details?: unknown): ShipError;
|
|
842
868
|
static config(message: string, details?: unknown): ShipError;
|
|
@@ -1964,17 +1990,45 @@ interface ShipClientOptions {
|
|
|
1964
1990
|
deployEndpoint?: string | undefined;
|
|
1965
1991
|
}
|
|
1966
1992
|
/**
|
|
1967
|
-
* Event map for Ship SDK events
|
|
1968
|
-
*
|
|
1993
|
+
* Event map for Ship SDK events.
|
|
1994
|
+
*
|
|
1995
|
+
* **Every failure is visible, and the event NAME says whether it ended the
|
|
1996
|
+
* call.** One call emits `retry* (error | response)` — so the stream is
|
|
1997
|
+
* unambiguous at every prefix, and a consumer never has to wait to find out
|
|
1998
|
+
* what it is watching.
|
|
1999
|
+
*
|
|
2000
|
+
* `request` counts what went out; `retry` counts what failed and will be
|
|
2001
|
+
* tried again; `error` and `response` are the two terminal answers, exactly
|
|
2002
|
+
* one of which arrives.
|
|
1969
2003
|
*/
|
|
1970
2004
|
interface ShipEvents {
|
|
1971
|
-
/** Emitted before each API request */
|
|
2005
|
+
/** Emitted before each API request — once per ATTEMPT, so it counts what actually went out. */
|
|
1972
2006
|
request: [url: string, init: RequestInit];
|
|
1973
|
-
/** Emitted after successful API response */
|
|
2007
|
+
/** Emitted after successful API response — once, on the attempt that worked. */
|
|
1974
2008
|
response: [response: Response, url: string];
|
|
1975
2009
|
/**
|
|
1976
|
-
* Emitted when
|
|
1977
|
-
* the
|
|
2010
|
+
* Emitted when an attempt failed and the client is going to try again.
|
|
2011
|
+
* Carries the same normalized `ShipError` the terminal `error` would, plus
|
|
2012
|
+
* `attempt` — the number of the attempt that just failed, counting from 1,
|
|
2013
|
+
* which matches the arithmetic the docs use ("two retries by default, so
|
|
2014
|
+
* three attempts"). Under that numbering the value reads both ways at once:
|
|
2015
|
+
* attempt N failing IS retry N, so `retry 1 of ${maxRetries}` needs no
|
|
2016
|
+
* adjustment.
|
|
2017
|
+
*
|
|
2018
|
+
* This event exists so `error` can keep meaning what it always meant. When
|
|
2019
|
+
* retries landed, `error` fired per attempt — honest about what happened,
|
|
2020
|
+
* but it silently redefined the event: a consumer seeing `error, error,
|
|
2021
|
+
* response` could not tell "failed, retrying" from "failed, terminally" at
|
|
2022
|
+
* any prefix, and counting `error`s no longer counted failed calls. Two
|
|
2023
|
+
* names, two meanings, and nothing lost: every failure is still announced.
|
|
2024
|
+
*
|
|
2025
|
+
* A failure the loop will NOT retry is terminal and emits `error` directly,
|
|
2026
|
+
* never this. So is an abort that lands mid-backoff.
|
|
2027
|
+
*/
|
|
2028
|
+
retry: [error: Error, url: string, attempt: number];
|
|
2029
|
+
/**
|
|
2030
|
+
* Emitted when the CALL failed — terminally, exactly once. TWO populations
|
|
2031
|
+
* arrive here, which is why the type is `Error` and not `ShipError`:
|
|
1978
2032
|
*
|
|
1979
2033
|
* - a failed request — always a `ShipError` (`executeRequest` normalizes
|
|
1980
2034
|
* every failure through `ShipError.fromFetchError` before emitting), so
|
|
@@ -2052,9 +2106,16 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
2052
2106
|
* for headers, the timeout signal, the events and error normalization — so
|
|
2053
2107
|
* an attempt is a whole request and nothing has to be undone between two.
|
|
2054
2108
|
*
|
|
2055
|
-
* **
|
|
2056
|
-
*
|
|
2057
|
-
*
|
|
2109
|
+
* **Every failure is visible, and the event NAME says whether it ended the
|
|
2110
|
+
* call.** One call emits `retry* (error | response)`: `request` fires per
|
|
2111
|
+
* attempt, so a consumer counting requests sees what actually went out; a
|
|
2112
|
+
* failure that will be tried again is a `retry`; `error` and `response` are
|
|
2113
|
+
* the two terminal answers, exactly one of which arrives.
|
|
2114
|
+
*
|
|
2115
|
+
* The failure events are emitted HERE rather than in `attemptOnce`, and
|
|
2116
|
+
* that placement is the whole mechanism: terminality is a property of the
|
|
2117
|
+
* loop — of `isRetryable` and the attempt budget — so it is knowable only
|
|
2118
|
+
* at the one point that owns both. An attempt cannot name its own failure.
|
|
2058
2119
|
*
|
|
2059
2120
|
* **The caller's `timeout` governs an ATTEMPT, not the wall clock.** Each
|
|
2060
2121
|
* attempt is an honest request and deserves the ceiling the caller named;
|
|
@@ -2073,7 +2134,12 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
2073
2134
|
/** Did this request carry the header that makes a repeat safe? */
|
|
2074
2135
|
private hasIdempotencyKey;
|
|
2075
2136
|
/**
|
|
2076
|
-
* One attempt: headers, timeout signal, events, and
|
|
2137
|
+
* One attempt: headers, timeout signal, the `request`/`response` events, and
|
|
2138
|
+
* error normalization.
|
|
2139
|
+
*
|
|
2140
|
+
* It does NOT emit a failure event. An attempt cannot know whether its own
|
|
2141
|
+
* failure ended the call — that is `executeRequest`'s question — so it
|
|
2142
|
+
* normalizes and throws, and the loop names what happened.
|
|
2077
2143
|
*/
|
|
2078
2144
|
private attemptOnce;
|
|
2079
2145
|
/**
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var je=Object.defineProperty;var R=(n,t)=>()=>(n&&(t=n(n=0)),t);var Ye=(n,t)=>{for(var e in t)je(n,e,{get:t[e],enumerable:!0})};function xt(n){if(!n||typeof n!="string")return;let t=n.trim().toLowerCase();return Object.values(qe).includes(t)?t:void 0}function fe(n){if(n==null)return;if(typeof n!="string")throw a.validation("Idempotency key must be a string.");let t=n.trim();if(!t)throw a.validation("Idempotency key must not be empty.");if(t.length>_.MAX_LENGTH)throw a.validation(`Idempotency key must be at most ${_.MAX_LENGTH} characters.`);return t}function Qe(n){let t=n.code;return t==="ERR_INVALID_URL"?!1:typeof t=="string"?!0:n instanceof TypeError?!/\burl\b/i.test(n.message):!1}function F(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function Ze(n){let t=n.replace(/\\/g,"/").split("/").pop()??"",e=t.lastIndexOf(".");return e<=0||e===t.length-1?null:t.slice(e+1).toLowerCase()}function he(n,t){let e=Ze(n);return e===null?!1:Array.isArray(t)?t.includes(e):t.has(e)}function ye(n){return tt.test(n)}function B(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>J.has(e))}function nt(n){return n.startsWith(ge.PREFIX)?x.API_KEY:n.startsWith(Ee.PREFIX)?x.DEPLOY_TOKEN:x.OPAQUE}function Te(n){let t=n.charCodeAt(0)===65279?n.slice(1):n,e;try{e=JSON.parse(t)}catch(r){throw a.config(`invalid JSON format in config: ${r.message}`,{filePath:L})}if(e===null||typeof e!="object"||Array.isArray(e))throw a.config(`${L} must contain a JSON object`,{filePath:L})}function Ae(n,t,e){if(!n.startsWith(t.PREFIX))throw a.validation(`${e} must start with "${t.PREFIX}"`);if(n.length!==t.TOTAL_LENGTH)throw a.validation(`${e} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let r=n.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(r))throw a.validation(`${e} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function rt(n){Ae(n,ge,"API key")}function it(n){Ae(n,Ee,"Deploy token")}function Q(n){switch(nt(n)){case x.API_KEY:rt(n);return;case x.DEPLOY_TOKEN:it(n);return;case x.OPAQUE:if(!n)throw a.validation("Token must be a non-empty string")}}function Se(n){if(!n||n.length>C.MAX_LENGTH||!C.PATTERN.test(n))throw a.validation(`Caller must be 1-${C.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function Ft(n){try{let t=new URL(n);if(!["http:","https:"].includes(t.protocol))throw a.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw a.validation("API URL must not contain a path");if(t.search||t.hash)throw a.validation("API URL must not contain query parameters or fragments")}catch(t){throw F(t)?t:a.validation("API URL must be a valid URL")}}function kt(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function Re(n,t){return n.endsWith(`.${t}`)}function Mt(n,t){return!Re(n,t)}function Bt(n,t){return Re(n,t)?n.slice(0,-(t.length+1)):null}function Ht(n){return`https://${n}`}function Gt(n){return`https://${n}`}function zt(n){return!n||n.length===0?null:JSON.stringify(n)}function Kt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}function ee(n){if(n==null)return;if(typeof n!="string")throw a.validation("Password must be a string");let t=n.trim();if(t.length<M.MIN_LENGTH||t.length>M.MAX_LENGTH)throw a.validation(`Password must be between ${M.MIN_LENGTH} and ${M.MAX_LENGTH} characters`);return t}var bt,qe,Nt,_,vt,f,I,m,Xe,W,We,Je,a,et,Ot,tt,J,Ct,me,ge,Ee,C,x,_t,L,De,H,Z,k,Ut,$t,g,b,Ie,M,y=R(()=>{"use strict";bt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},qe={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc"},Nt={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},_={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};vt={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},f={DEPLOYMENTS:"/deployments",DEPLOYMENT:n=>`/deployments/${n}`,DEPLOYMENT_CONFIG:n=>`/deployments/${n}/config`,DOMAINS:"/domains",DOMAIN:n=>`/domains/${n}`,DOMAIN_VERIFY:n=>`/domains/${n}/verify`,DOMAIN_DNS:n=>`/domains/${n}/dns`,DOMAIN_RECORDS:n=>`/domains/${n}/records`,DOMAIN_SHARE:n=>`/domains/${n}/share`,DOMAIN_PROPAGATION:n=>`/domains/${n}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:n=>`/tokens/${n}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},I={FILES:"files[]",CHECKSUMS:"checksums",LABELS:"labels",VIA:"via",PASSWORD:"password",BUILD:"build",PRERENDER:"prerender",SPA:"spa",CAPTCHA:"captcha"},m={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Maintenance:"maintenance",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},Xe=new Set([m.Network,m.Cancelled,m.File,m.Config]),W={client:new Set([m.Business,m.Cancelled,m.Config,m.File,m.Forbidden,m.NotFound,m.RateLimit,m.Validation]),network:new Set([m.Network]),auth:new Set([m.Authentication])},We=new Set(Object.values(m).filter(n=>!Xe.has(n))),Je=200;a=class n extends Error{type;status;details;constructor(t,e,r,i){super(e),this.type=t,this.status=r,this.details=i,this.name="ShipError"}toResponse(){let t=this.details,e=this.type===m.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static async fromHttpResponse(t,e){let r,i,s;try{if(t.headers.get("content-type")?.includes("application/json")){let u=await t.json();if(u&&typeof u=="object"){let c=u;typeof c.message=="string"?r=c.message:typeof c.error=="string"&&(r=c.error),i=c.details,typeof c.error=="string"&&We.has(c.error)&&(s=c.error)}}else{let u=(await t.text()).trim();u&&!u.startsWith("<")&&u.length<=Je&&(r=u)}}catch{}let o=t.headers.get("retry-after");if(o!==null){let l=o.trim(),u=/^\d+$/.test(l)?Number(l):Math.ceil((Date.parse(l)-Date.now())/1e3);if(Number.isFinite(u)&&u>=0){let c=i&&typeof i=="object"?i:{};c.retryAfter===void 0&&(i={...c,retryAfter:u})}}r=r||`${e||"Request"} failed with status ${t.status}`;let p=s??(t.status===401?m.Authentication:t.status===403?m.Forbidden:t.status===429?m.RateLimit:m.Api);return new n(p,r,t.status,i)}static fromFetchError(t,e){if(F(t))return t;let r=e||"Request",i=t?.name;return i==="AbortError"?n.cancelled(`${r} was cancelled`):i==="TimeoutError"?n.network(`${r} timed out`,{cause:t}):t instanceof Error?Qe(t)?n.network(`${r} failed: ${t.message}`,{cause:t}):new n(m.Api,`${r} failed: ${t.message}`):new n(m.Api,`${r} failed: Unknown error`)}static validation(t,e){return new n(m.Validation,t,400,e)}static notFound(t,e){let r=e?`${t} ${e} not found`:`${t} not found`;return new n(m.NotFound,r,404)}static forbidden(t,e){return new n(m.Forbidden,t,403,e)}static rateLimit(t="Too many requests",e){return new n(m.RateLimit,t,429,e)}static authentication(t="Authentication required",e){return new n(m.Authentication,t,401,e)}static business(t,e=400,r){return new n(m.Business,t,e,r)}static network(t,e){return new n(m.Network,t,void 0,e)}static cancelled(t,e){return new n(m.Cancelled,t,void 0,e)}static file(t,e){return new n(m.File,t,void 0,e)}static config(t,e){return new n(m.Config,t,void 0,e)}static api(t,e=500,r){return new n(m.Api,t,e,r)}static maintenance(t,e){return new n(m.Maintenance,t,503,e)}isClientError(){return W.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return W.network.has(this.type)}isAuthError(){return W.auth.has(this.type)}isType(t){return this.type===t}};et=["html","htm","xhtml","xml","txt","md","markdown","pdf","csv","json","jsonc","webmanifest","map","toml","yaml","yml","rss","atom","css","scss","sass","less","js","mjs","cjs","jsx","ts","tsx","wasm","vue","svelte","png","jpg","jpeg","gif","webp","avif","svg","ico","bmp","tif","tiff","heic","heif","woff","woff2","ttf","otf","eot","mp3","wav","ogg","oga","opus","m4a","aac","flac","weba","mp4","webm","ogv","mov","m4v","avi","glb","gltf","usdz","vtt","srt","zip"],Ot=et.map(n=>`.${n}`).join(","),tt=/[\x00-\x1f\x7f#?%\\<>"]/;J=new Set(["node_modules","package.json"]);Ct="/auth",me={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},ge={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},Ee={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},C={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},x={API_KEY:me.API_KEY,DEPLOY_TOKEN:me.TOKEN,OPAQUE:"opaque"};_t={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},L="ship.json",De={rewrites:[{source:"/(.*)",destination:"/index.html"}]},H={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};Z="https://api.shipstatic.com",k={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},Ut="https://my.shipstatic.com/api-key",$t=4320*60,g={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};b={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},Ie=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;M={MIN_LENGTH:6,MAX_LENGTH:128}});async function ft(n){let t=(await import("spark-md5")).default,e=new t.ArrayBuffer,r=2097152;for(let i=0;i<n.size;i+=r){let s=Math.min(i+r,n.size);e.append(await n.slice(i,s).arrayBuffer())}return{md5:e.end()}}async function ht(n){let{createHash:t}=await import("crypto"),e=t("md5");return e.update(n),{md5:e.digest("hex")}}async function yt(n){let{createHash:t}=await import("crypto"),{createReadStream:e}=await import("fs");return new Promise((r,i)=>{let s=t("md5"),o=e(n);o.on("error",p=>i(a.file(`Failed to read file for MD5: ${p.message}`,{filePath:n}))),o.on("data",p=>s.update(p)),o.on("end",()=>r({md5:s.digest("hex")}))})}async function K(n){if(n instanceof Blob)return ft(n);if(typeof Buffer<"u"&&Buffer.isBuffer(n))return ht(n);if(typeof n=="string")return yt(n);throw a.business("Invalid input for MD5 calculation")}var V=R(()=>{"use strict";y()});function mn(n){ne=n}function Et(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function v(){return ne||Et()}var ne,$=R(()=>{"use strict";ne=null});function Ue(n){if(!n||n.length===0)return"";let t=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let e=t.map(s=>s.split("/").filter(Boolean)),r=[],i=Math.min(...e.map(s=>s.length));for(let s=0;s<i;s++){let o=e[0][s];if(e.every(p=>p[s]===o))r.push(o);else break}return r.join("/")}function Y(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var re=R(()=>{"use strict"});function $e(n,t={}){if(t.flatten===!1)return n.map(r=>({path:Y(r),name:ie(r)}));let e=At(n);return n.map(r=>{let i=Y(r);if(e){let s=e.endsWith("/")?e:`${e}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=ie(r)),{path:i,name:ie(r)}})}function At(n){if(!n.length)return"";let e=n.map(s=>Y(s)).map(s=>s.split("/")),r=[],i=Math.min(...e.map(s=>s.length));for(let s=0;s<i-1;s++){let o=e[0][s];if(e.every(p=>p[s]===o))r.push(o);else break}return r.join("/")}function ie(n){return n.split(/[/\\]/).pop()||n}var se=R(()=>{"use strict";re()});function X(n,t){return St.find(e=>e.broken(n,t))}var St,ae=R(()=>{"use strict";y();le();St=[{name:"name",broken:({path:n})=>!oe(n).valid,sentence:({path:n})=>oe(n).reason??"Invalid file name"},{name:"extension",broken:({path:n},t)=>he(n,t.blockedExtensions??[]),sentence:({path:n})=>`File extension not allowed: "${n}"`},{name:"fileSize",broken:({size:n},t)=>n>t.maxFileSize,sentence:({path:n},t)=>`File "${n}" too large. Maximum ${q(t.maxFileSize)} allowed`},{name:"totalSize",broken:({totalSize:n},t)=>n>t.maxTotalSize,sentence:({totalSize:n},t)=>`Total upload size too large. ${q(n)} exceeds maximum of ${q(t.maxTotalSize)}`}]});function q(n,t=1){if(n===0)return"0 Bytes";let e=1024,r=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(n)/Math.log(e));return`${parseFloat((n/e**i).toFixed(t))} ${r[i]}`}function oe(n){if(ye(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,e=n.split("/").pop()||n;return t.test(e)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function _n(n,t){let e=[],r=[],i=[];if(n.length===0){let l={file:"(no files)",message:"At least one file must be provided"};return e.push(l),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let l of n)if(B(l.name))return e.push({file:l.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(u=>({...u,status:g.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let l={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(l),{files:n.map(u=>({...u,status:g.VALIDATION_FAILED,statusMessage:l.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let l of n){let u=g.READY,c="Ready for upload";if(l.status===g.PROCESSING_ERROR)u=g.VALIDATION_FAILED,c=l.statusMessage||"File failed during processing",e.push({file:l.name,message:c});else if(l.size===0){u=g.EXCLUDED,c="File is empty (0 bytes) and cannot be deployed due to storage limitations",r.push({file:l.name,message:c}),i.push({...l,status:u,statusMessage:c});continue}else if(l.size<0)u=g.VALIDATION_FAILED,c="File size must be positive",e.push({file:l.name,message:c});else if(!l.name||l.name.trim().length===0)u=g.VALIDATION_FAILED,c="File name cannot be empty",e.push({file:l.name||"(empty)",message:c});else if(l.name.includes("\0"))u=g.VALIDATION_FAILED,c="File name contains invalid characters (null byte)",e.push({file:l.name,message:c});else{let E={path:l.name,size:l.size,totalSize:s+l.size},P=X(E,t);P?(u=g.VALIDATION_FAILED,c=P.sentence(E,t),e.push({file:P.name==="totalSize"?`(${n.length} files)`:l.name,message:c})):s=E.totalSize}i.push({...l,status:u,statusMessage:c})}e.length>0&&(i=i.map(l=>l.status===g.EXCLUDED?l:{...l,status:g.VALIDATION_FAILED,statusMessage:l.status===g.VALIDATION_FAILED?l.statusMessage:"Deployment failed due to validation errors in bundle"}));let o=e.length===0?i.filter(l=>l.status===g.READY):[],p=e.length===0;return{files:i,validFiles:o,errors:e,warnings:r,canDeploy:p}}function Rt(n){return n.filter(t=>t.status===g.READY)}function Fn(n){return Rt(n).length>0}var le=R(()=>{"use strict";y();ae()});import{isJunk as It}from"junk";function Me(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(r=>r&&B(r)))throw a.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return n.filter(e=>{if(!e)return!1;let r=e.replace(/\\/g,"/").split("/").filter(Boolean);if(r.length===0)return!0;let i=r[r.length-1];if(It(i))return!1;for(let o of r)if(o!==".well-known"&&(o.startsWith(".")||o.length>255))return!1;let s=r.slice(0,-1);for(let o of s)if(Pt.some(p=>o.toLowerCase()===p.toLowerCase()))return!1;return!0})}var Pt,ce=R(()=>{"use strict";y();Pt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Be(n,t){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw a.business(`Security error: Unsafe file path "${n}" for file: ${t}`)}function He(n,t){let e=X(n,t);if(e)throw a.business(e.sentence(n,t))}var pe=R(()=>{"use strict";y();ae()});var Ke={};Ye(Ke,{processFilesForNode:()=>ze});import*as D from"fs";import*as T from"path";function Ge(n,t=new Set){let e=[],r=D.realpathSync(n);if(t.has(r))return e;t.add(r);let i=D.readdirSync(n);for(let s of i){let o=T.join(n,s),p=D.statSync(o);if(p.isDirectory()){let l=Ge(o,t);e.push(...l)}else p.isFile()&&e.push(o)}return e}async function ze(n,t={},e){if(v()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let d of n){let h=T.resolve(d);try{if(D.statSync(h).isDirectory()){let A=D.readdirSync(h).find(S=>J.has(S));if(A)throw a.business(`"${A}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(A){if(F(A))throw A}}let r=n.flatMap(d=>{let h=T.resolve(d);try{return D.statSync(h).isDirectory()?Ge(h):[h]}catch{throw a.file(`Path does not exist: ${d}`,{filePath:d})}}),i=[...new Set(r)],s=n.map(d=>T.resolve(d)),o=Ue(s.map(d=>{try{return D.statSync(d).isDirectory()?d:T.dirname(d)}catch{return T.dirname(d)}})),p=i.map(d=>{if(o&&o.length>0){let h=T.relative(o,d);if(h&&typeof h=="string"&&!h.startsWith(".."))return h.replace(/\\/g,"/")}return T.basename(d)}),u=$e(p,{flatten:t.pathDetect!==!1}).map(d=>d.path),c=new Set(Me(u));if(c.size===0)return[];let E=[],P=[];for(let d=0;d<i.length;d++)c.has(u[d])&&(E.push(i[d]),P.push(u[d]));let N=[],w=0;if(!e)throw a.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let d=0;d<E.length;d++){let h=E[d],A=P[d];try{Be(A,h);let S=D.statSync(h);if(S.size===0)continue;w+=S.size,He({path:A,size:S.size,totalSize:w},e);let O=D.readFileSync(h),{md5:Ve}=await K(O);N.push({path:A,content:O,size:O.length,md5:Ve})}catch(S){if(F(S))throw S;let O=S instanceof Error?S.message:String(S);throw a.file(`Failed to read file "${h}": ${O}`,{filePath:h})}}if(N.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return N}var ue=R(()=>{"use strict";y();se();$();ce();V();re();pe()});y();y();y();var G=class{constructor(){this.handlers=new Map}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(e)}off(t,e){let r=this.handlers.get(t);r&&(r.delete(e),r.size===0&&this.handlers.delete(t))}emit(t,...e){let r=this.handlers.get(t);if(!r)return;let i=Array.from(r);for(let s of i)try{s(...e)}catch(o){r.delete(s),t!=="error"&&setTimeout(()=>{let p=o instanceof Error?o:new Error(String(o));this.emit("error",p,String(t))},0)}}};y();y();function U(n){if(n==null)return;if(n.length===0)return n;if(n.length>b.MAX_COUNT)throw a.validation(`Maximum ${b.MAX_COUNT} labels allowed`);let t=n.map((r,i)=>{if(typeof r!="string")throw a.validation(`Label at index ${i} must be a string`);let s=r.trim().toLowerCase();if(s.length<b.MIN_LENGTH)throw a.validation(`Labels must be at least ${b.MIN_LENGTH} characters long`);if(s.length>b.MAX_LENGTH)throw a.validation(`Labels must be no more than ${b.MAX_LENGTH} characters long`);if(!Ie.test(s))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${b.SEPARATORS}) between segments`);return s}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}async function Pe(n){let t=n.find(i=>i.path===L||i.path===`/${L}`);if(!t)return;let e=t.content,r=typeof e.text=="function"?await e.text():t.content.toString("utf8");Te(r)}var st=3e4,ot=2,at=300,lt=2e3,ct=new Set([500,502,503,504]);function pt(n,t){return new Promise((e,r)=>{if(t?.aborted){r(t.reason);return}let i=()=>{clearTimeout(o),t?.removeEventListener("abort",s)},s=()=>{i(),r(t?.reason)},o=setTimeout(()=>{i(),e()},n);t?.addEventListener("abort",s)})}var Le=3e5,ut=3e5,dt=Le+ut,mt="sdk";function te(n){let t=new URLSearchParams;n?.limit!==void 0&&t.set("limit",String(n.limit)),n?.cursor!==void 0&&t.set("cursor",n.cursor);let e=t.toString();return e?`?${e}`:""}var z=class extends G{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||Z,this.getAuthHeadersCallback=e.getAuthHeaders,this.session=e.session??!1,this.caller=e.caller,this.timeout=e.timeout??st,this.maxRetries=Math.max(0,e.maxRetries??ot),this.deployTimeout=e.timeout??Le,this.deployBuildTimeout=e.timeout??dt,this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||f.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}async executeRequest(e,r,i,s=this.timeout){for(let o=0;;o++)try{return await this.attemptOnce(e,r,i,s)}catch(p){let l=a.fromFetchError(p,i);if(o>=this.maxRetries||!this.isRetryable(l,r))throw l;let u=Math.min(lt,at*2**o);try{await pt(Math.random()*u,r.signal)}catch(c){let E=a.fromFetchError(c,i);throw this.emit("error",E,e),E}}}isRetryable(e,r){if(r.signal?.aborted||e.isType(m.Maintenance)||e.isType(m.Cancelled)||!(e.isNetworkError()||e.status!==void 0&&ct.has(e.status)))return!1;let s=(r.method??"GET").toUpperCase();return s==="GET"||s==="HEAD"?!0:s==="PUT"||s==="DELETE"?!1:this.hasIdempotencyKey(r.headers)}hasIdempotencyKey(e){if(!e)return!1;let r=_.HEADER.toLowerCase(),i=!1,s=o=>{o.toLowerCase()===r&&(i=!0)};if(e instanceof Headers)e.forEach((o,p)=>{s(p)});else if(Array.isArray(e))for(let[o]of e)s(o);else for(let o of Object.keys(e))s(o);return i}async attemptOnce(e,r,i,s=this.timeout){let o=()=>{};try{let p=await this.mergeHeaders(r.headers),l=this.createTimeoutSignal(r.signal,s);o=l.cleanup;let u={...r,headers:p,credentials:this.session&&!p.Authorization?"include":void 0,signal:l.signal};this.emit("request",e,u);let c=await this.fetch(e,u);if(o(),!c.ok)throw await a.fromHttpResponse(c,i);return this.emit("response",this.safeClone(c),e),{data:await this.parseResponse(this.safeClone(c)),status:c.status}}catch(p){o();let l=a.fromFetchError(p,i);throw this.emit("error",l,e),l}}async request(e,r,i,s){let{data:o}=await this.executeRequest(e,r,i,s);return o}async requestWithStatus(e,r,i){return this.executeRequest(e,r,i)}async mergeHeaders(e={}){return{...this.globalHeaders,...this.caller?{[C.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e,r=this.timeout){let i=new AbortController,s=setTimeout(()=>i.abort(new DOMException(`Timed out after ${r}ms`,"TimeoutError")),r),o=e?()=>i.abort(e.reason):void 0;return e&&o&&(e.addEventListener("abort",o),e.aborted&&i.abort(e.reason)),{signal:i.signal,cleanup:()=>{clearTimeout(s),e&&o&&e.removeEventListener("abort",o)}}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async deploy(e,r={}){if(!e.length)throw a.business("No files to deploy");for(let u of e)if(!u.md5)throw a.file(`MD5 checksum missing for file: ${u.path}`,{filePath:u.path});ee(r.password);let i=fe(r.idempotencyKey),s=U(r.labels);await Pe(e);let o=r.build||r.prerender||r.spa?{build:r.build,prerender:r.prerender,spa:r.spa}:void 0,{body:p,headers:l}=await this.createDeployBody(e,{labels:s,via:r.via??mt,password:r.password,flags:o,captcha:r.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:p,headers:i?{...l,[_.HEADER]:i}:l,signal:r.signal||null},"Deploy",r.build||r.prerender?this.deployBuildTimeout:this.deployTimeout)}async listDeployments(e){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}${te(e)}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENT(encodeURIComponent(e))}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,r){let i=U(r);return this.request(`${this.apiUrl}${f.DEPLOYMENT(encodeURIComponent(e))}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:i})},"Update deployment labels")}async deleteDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENT(encodeURIComponent(e))}`,{method:"DELETE"},"Delete deployment")}async setDomain(e,r,i){let s=U(i),o={};r&&(o.deployment=r),s!==void 0&&(o.labels=s);let{data:p,status:l}=await this.requestWithStatus(`${this.apiUrl}${f.DOMAIN(encodeURIComponent(e))}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Set domain");return{...p,isCreate:l===201}}async listDomains(e){return this.request(`${this.apiUrl}${f.DOMAINS}${te(e)}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${f.DOMAIN(encodeURIComponent(e))}`,{method:"GET"},"Get domain")}async deleteDomain(e){return this.request(`${this.apiUrl}${f.DOMAIN(encodeURIComponent(e))}`,{method:"DELETE"},"Delete domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${f.DOMAIN_VERIFY(encodeURIComponent(e))}`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${f.DOMAIN_DNS(encodeURIComponent(e))}`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${f.DOMAIN_RECORDS(encodeURIComponent(e))}`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${f.DOMAIN_SHARE(encodeURIComponent(e))}`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS_VALIDATE}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,r){let i=U(r),s={};return e!==void 0&&(s.ttl=e),i!==void 0&&(s.labels=i),this.request(`${this.apiUrl}${f.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(e){return this.request(`${this.apiUrl}${f.TOKENS}${te(e)}`,{method:"GET"},"List tokens")}async deleteToken(e){return this.request(`${this.apiUrl}${f.TOKEN(encodeURIComponent(e))}`,{method:"DELETE"},"Delete token")}async getToken(e){return this.request(`${this.apiUrl}${f.TOKEN(encodeURIComponent(e))}`,{method:"GET"},"Get token")}async getAccount(){return this.request(`${this.apiUrl}${f.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${f.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return this.request(`${this.apiUrl}${f.PING}`,{method:"GET"},"Ping")}async checkSPA(e,r={}){let i=e.find(l=>l.path===H.INDEX_FILE||l.path===`/${H.INDEX_FILE}`);if(!i||i.size>H.MAX_INDEX_BYTES)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(i.content))s=i.content.toString("utf-8");else if(typeof Blob<"u"&&i.content instanceof Blob)s=await i.content.text();else if(typeof File<"u"&&i.content instanceof File)s=await i.content.text();else return!1;let o={files:e.map(l=>l.path),index:s};return(await this.request(`${this.apiUrl}${f.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"SPA check")).isSPA}};y();y();V();async function gt(){let n=JSON.stringify(De,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await K(t);return{path:L,content:t,size:n.length,md5:e}}async function we(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(r=>r.path===L))return n;try{if(await t.checkSPA(n,e)){let i=await gt();return[...n,i]}}catch{}return n}function be(n){let{getApi:t,ensureInit:e,processInput:r}=n;return{upload:async(i,s={})=>{if(await e(),!r)throw a.config("processInput function is not provided.");let o=t(),p=await r(i,s);return p=await we(p,o,s),o.deploy(p,s)},list:async i=>(await e(),t().listDeployments(i)),get:async i=>(await e(),t().getDeployment(i)),set:async(i,s)=>(await e(),t().updateDeploymentLabels(i,s.labels)),delete:async i=>(await e(),t().deleteDeployment(i))}}function Ne(n){let{getApi:t,ensureInit:e}=n;return{set:async(r,i={})=>(await e(),t().setDomain(r,i.deployment,i.labels)),list:async r=>(await e(),t().listDomains(r)),get:async r=>(await e(),t().getDomain(r)),delete:async r=>(await e(),t().deleteDomain(r)),verify:async r=>(await e(),t().verifyDomain(r)),validate:async r=>(await e(),t().validateDomain(r)),dns:async r=>(await e(),t().getDomainDns(r)),records:async r=>(await e(),t().getDomainRecords(r)),share:async r=>(await e(),t().getDomainShare(r))}}function xe(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function ve(n){let{getApi:t,ensureInit:e}=n;return{create:async(r={})=>(await e(),t().createToken(r.ttl,r.labels)),list:async r=>(await e(),t().listTokens(r)),get:async r=>(await e(),t().getToken(r)),delete:async r=>(await e(),t().deleteToken(r))}}var j=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&Se(t.caller),t.token&&t.session)throw a.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(Q(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new z({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=be({...e,processInput:(r,i)=>this.processInput(r,i)}),this.domains=Ne(e),this.account=xe(e),this.tokens=ve(e)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,e){return this.deployments.upload(t,e)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw a.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw a.business("Invalid token provided. Token must be a non-empty string.");Q(t),this.credential=t;return}if(typeof t!="function")throw a.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw a.authentication("Token provider returned no token.");if(typeof t!="string")throw a.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};$();y();import{z as _e}from"zod";import{z as Oe}from"zod";var Ce={apiUrl:Oe.string().url().optional(),token:Oe.string().min(1).optional()};$();var Dt=_e.object(Ce).strict(),Tt={apiUrl:k.API_URL,token:k.TOKEN};function Fe(){if(v()!=="node")return{};let n={apiUrl:process.env[k.API_URL]||void 0,token:process.env[k.TOKEN]||void 0};try{return Dt.parse(n)}catch(t){if(t instanceof _e.ZodError){let e=t.issues[0],r=e.path[0],i=(r&&Tt[r])??"SHIP environment configuration";throw a.config(`Invalid ${i}: ${e.message}`)}throw a.config("Invalid environment configuration")}}y();async function ke(n,t={}){let{FormData:e,File:r}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),{labels:s,via:o,password:p,flags:l,captcha:u}=t,c=new e,E=[];for(let d of n){if(!Buffer.isBuffer(d.content)&&!(typeof Blob<"u"&&d.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${d.path}`,{filePath:d.path});if(!d.md5)throw a.file(`File missing md5 checksum: ${d.path}`,{filePath:d.path});let h=new r([d.content],d.path,{type:"application/octet-stream"});c.append(I.FILES,h),E.push(d.md5)}c.append(I.CHECKSUMS,JSON.stringify(E)),s&&s.length>0&&c.append(I.LABELS,JSON.stringify(s)),o&&c.append(I.VIA,o),p&&c.append(I.PASSWORD,p),l?.build&&c.append(I.BUILD,"true"),l?.prerender&&c.append(I.PRERENDER,"true"),l?.spa&&c.append(I.SPA,"true"),u&&c.append(I.CAPTCHA,u);let P=new i(c),N=[];for await(let d of P.encode())N.push(Buffer.from(d));let w=Buffer.concat(N);return{body:w.buffer.slice(w.byteOffset,w.byteOffset+w.byteLength),headers:{"Content-Type":P.contentType,"Content-Length":Buffer.byteLength(w).toString()}}}y();y();se();$();le();ce();V();pe();function zn(n,t,e,r=!0){let i=n===1?t:e;return r?`${n} ${i}`:i}ue();var de=class extends j{constructor(t={}){if(v()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=Fe();super({...t,apiUrl:t.apiUrl||e.apiUrl,token:t.token||(t.session?void 0:e.token)})}async deploy(t,e){return super.deploy(t,e)}async processInput(t,e){let r=typeof t=="string"?[t]:t;if(!Array.isArray(r)||!r.every(s=>typeof s=="string"))throw a.business("Invalid input type for Node.js environment. Expected string or string[].");if(r.length===0)throw a.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(ue(),Ke));return i(r,e,this.platformLimits??void 0)}getDeployBodyCreator(){return ke}},Lt=de;export{ge as API_KEY,f as API_PATHS,Ct as AUTH_BASE_PATH,vt as AccountPlan,z as ApiHttp,me as AuthMethod,C as CALLER,Z as DEFAULT_API,L as DEPLOYMENT_CONFIG_FILENAME,I as DEPLOY_FIELDS,Ee as DEPLOY_TOKEN,bt as DeploymentStatus,qe as DeploymentVia,Nt as DomainStatus,m as ErrorType,g as FILE_VALIDATION_STATUS,g as FileValidationStatus,_ as IDEMPOTENCY_KEY_CONSTRAINTS,Pt as JUNK_DIRECTORIES,b as LABEL_CONSTRAINTS,Ie as LABEL_PATTERN,Ut as MY_API_KEY_URL,_t as OAuthScope,M as PASSWORD_CONSTRAINTS,$t as PUBLIC_DEPLOYMENT_TTL_SECONDS,k as SHIP_ENV,H as SPA_CHECK_CONSTRAINTS,De as SPA_DEFAULT_CONFIG,de as Ship,a as ShipError,x as TokenKind,J as UNBUILT_PROJECT_MARKERS,tt as UNSAFE_FILENAME_CHARS,Ot as WEB_FILE_ACCEPT,mn as __setTestEnvironment,Fn as allValidFilesReady,Te as assertShipJsonSyntax,K as calculateMD5,nt as classifyToken,xe as createAccountResource,be as createDeploymentResource,Ne as createDomainResource,ve as createTokenResource,Lt as default,Kt as deserializeLabels,Bt as extractSubdomain,Me as filterJunk,q as formatFileSize,Ht as generateDeploymentUrl,Gt as generateDomainUrl,v as getENV,Rt as getValidFiles,B as hasUnbuiltMarker,ye as hasUnsafeChars,he as isBlockedExtension,Mt as isCustomDomain,kt as isDeployment,Re as isPlatformDomain,F as isShipError,xt as normalizeVia,$e as optimizeDeployPaths,zn as pluralize,ze as processFilesForNode,zt as serializeLabels,rt as validateApiKey,Ft as validateApiUrl,Se as validateCaller,He as validateDeployFile,Be as validateDeployPath,it as validateDeployToken,oe as validateFileName,_n as validateFiles,fe as validateIdempotencyKey,ee as validatePassword,Q as validateToken};
|
|
1
|
+
var je=Object.defineProperty;var R=(n,t)=>()=>(n&&(t=n(n=0)),t);var Ye=(n,t)=>{for(var e in t)je(n,e,{get:t[e],enumerable:!0})};function xt(n){if(!n||typeof n!="string")return;let t=n.trim().toLowerCase();return Object.values(qe).includes(t)?t:void 0}function fe(n){if(n==null)return;if(typeof n!="string")throw a.validation("Idempotency key must be a string.");let t=n.trim();if(!t)throw a.validation("Idempotency key must not be empty.");if(t.length>_.MAX_LENGTH)throw a.validation(`Idempotency key must be at most ${_.MAX_LENGTH} characters.`);return t}function Qe(n){let t=n.code;return t==="ERR_INVALID_URL"?!1:typeof t=="string"?!0:n instanceof TypeError?!/\burl\b/i.test(n.message):!1}function F(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function Ze(n){let t=n.replace(/\\/g,"/").split("/").pop()??"",e=t.lastIndexOf(".");return e<=0||e===t.length-1?null:t.slice(e+1).toLowerCase()}function he(n,t){let e=Ze(n);return e===null?!1:Array.isArray(t)?t.includes(e):t.has(e)}function ye(n){return tt.test(n)}function B(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>J.has(e))}function nt(n){return n.startsWith(ge.PREFIX)?x.API_KEY:n.startsWith(Ee.PREFIX)?x.DEPLOY_TOKEN:x.OPAQUE}function Te(n){let t=n.charCodeAt(0)===65279?n.slice(1):n,e;try{e=JSON.parse(t)}catch(r){throw a.config(`invalid JSON format in config: ${r.message}`,{filePath:L})}if(e===null||typeof e!="object"||Array.isArray(e))throw a.config(`${L} must contain a JSON object`,{filePath:L})}function Ae(n,t,e){if(!n.startsWith(t.PREFIX))throw a.validation(`${e} must start with "${t.PREFIX}"`);if(n.length!==t.TOTAL_LENGTH)throw a.validation(`${e} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let r=n.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(r))throw a.validation(`${e} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function rt(n){Ae(n,ge,"API key")}function it(n){Ae(n,Ee,"Deploy token")}function Q(n){switch(nt(n)){case x.API_KEY:rt(n);return;case x.DEPLOY_TOKEN:it(n);return;case x.OPAQUE:if(!n)throw a.validation("Token must be a non-empty string")}}function Se(n){if(!n||n.length>C.MAX_LENGTH||!C.PATTERN.test(n))throw a.validation(`Caller must be 1-${C.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function Ft(n){try{let t=new URL(n);if(!["http:","https:"].includes(t.protocol))throw a.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw a.validation("API URL must not contain a path");if(t.search||t.hash)throw a.validation("API URL must not contain query parameters or fragments")}catch(t){throw F(t)?t:a.validation("API URL must be a valid URL")}}function kt(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function Re(n,t){return n.endsWith(`.${t}`)}function Mt(n,t){return!Re(n,t)}function Bt(n,t){return Re(n,t)?n.slice(0,-(t.length+1)):null}function Ht(n){return`https://${n}`}function Gt(n){return`https://${n}`}function zt(n){return!n||n.length===0?null:JSON.stringify(n)}function Kt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}function ee(n){if(n==null)return;if(typeof n!="string")throw a.validation("Password must be a string");let t=n.trim();if(t.length<M.MIN_LENGTH||t.length>M.MAX_LENGTH)throw a.validation(`Password must be between ${M.MIN_LENGTH} and ${M.MAX_LENGTH} characters`);return t}var bt,qe,Nt,_,vt,f,I,m,Xe,W,We,Je,a,et,Ot,tt,J,Ct,me,ge,Ee,C,x,_t,L,De,H,Z,k,Ut,$t,g,b,Ie,M,y=R(()=>{"use strict";bt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},qe={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc"},Nt={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},_={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};vt={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},f={DEPLOYMENTS:"/deployments",DEPLOYMENT:n=>`/deployments/${n}`,DEPLOYMENT_CONFIG:n=>`/deployments/${n}/config`,DOMAINS:"/domains",DOMAIN:n=>`/domains/${n}`,DOMAIN_VERIFY:n=>`/domains/${n}/verify`,DOMAIN_DNS:n=>`/domains/${n}/dns`,DOMAIN_RECORDS:n=>`/domains/${n}/records`,DOMAIN_SHARE:n=>`/domains/${n}/share`,DOMAIN_PROPAGATION:n=>`/domains/${n}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:n=>`/tokens/${n}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},I={FILES:"files[]",CHECKSUMS:"checksums",LABELS:"labels",VIA:"via",PASSWORD:"password",BUILD:"build",PRERENDER:"prerender",SPA:"spa",CAPTCHA:"captcha"},m={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Maintenance:"maintenance",Network:"network_error",Timeout:"timeout_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},Xe=new Set([m.Network,m.Timeout,m.Cancelled,m.File,m.Config]),W={client:new Set([m.Business,m.Cancelled,m.Config,m.File,m.Forbidden,m.NotFound,m.RateLimit,m.Validation]),network:new Set([m.Network,m.Timeout]),auth:new Set([m.Authentication])},We=new Set(Object.values(m).filter(n=>!Xe.has(n))),Je=200;a=class n extends Error{type;status;details;constructor(t,e,r,i){super(e),this.type=t,this.status=r,this.details=i,this.name="ShipError"}toResponse(){let t=this.details,e=this.type===m.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static async fromHttpResponse(t,e){let r,i,s;try{if(t.headers.get("content-type")?.includes("application/json")){let u=await t.json();if(u&&typeof u=="object"){let c=u;typeof c.message=="string"?r=c.message:typeof c.error=="string"&&(r=c.error),i=c.details,typeof c.error=="string"&&We.has(c.error)&&(s=c.error)}}else{let u=(await t.text()).trim();u&&!u.startsWith("<")&&u.length<=Je&&(r=u)}}catch{}let o=t.headers.get("retry-after");if(o!==null){let l=o.trim(),u=/^\d+$/.test(l)?Number(l):Math.ceil((Date.parse(l)-Date.now())/1e3);if(Number.isFinite(u)&&u>=0){let c=i&&typeof i=="object"?i:{};c.retryAfter===void 0&&(i={...c,retryAfter:u})}}r=r||`${e||"Request"} failed with status ${t.status}`;let p=s??(t.status===401?m.Authentication:t.status===403?m.Forbidden:t.status===429?m.RateLimit:m.Api);return new n(p,r,t.status,i)}static fromFetchError(t,e){if(F(t))return t;let r=e||"Request",i=t?.name;return i==="AbortError"?n.cancelled(`${r} was cancelled`):i==="TimeoutError"?n.timeout(`${r} timed out`,{cause:t}):t instanceof Error?Qe(t)?n.network(`${r} failed: ${t.message}`,{cause:t}):new n(m.Api,`${r} failed: ${t.message}`):new n(m.Api,`${r} failed: Unknown error`)}static validation(t,e){return new n(m.Validation,t,400,e)}static notFound(t,e){let r=e?`${t} ${e} not found`:`${t} not found`;return new n(m.NotFound,r,404)}static forbidden(t,e){return new n(m.Forbidden,t,403,e)}static rateLimit(t="Too many requests",e){return new n(m.RateLimit,t,429,e)}static authentication(t="Authentication required",e){return new n(m.Authentication,t,401,e)}static business(t,e=400,r){return new n(m.Business,t,e,r)}static network(t,e){return new n(m.Network,t,void 0,e)}static timeout(t,e){return new n(m.Timeout,t,void 0,e)}static cancelled(t,e){return new n(m.Cancelled,t,void 0,e)}static file(t,e){return new n(m.File,t,void 0,e)}static config(t,e){return new n(m.Config,t,void 0,e)}static api(t,e=500,r){return new n(m.Api,t,e,r)}static maintenance(t,e){return new n(m.Maintenance,t,503,e)}isClientError(){return W.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return W.network.has(this.type)}isAuthError(){return W.auth.has(this.type)}isType(t){return this.type===t}};et=["html","htm","xhtml","xml","txt","md","markdown","pdf","csv","json","jsonc","webmanifest","map","toml","yaml","yml","rss","atom","css","scss","sass","less","js","mjs","cjs","jsx","ts","tsx","wasm","vue","svelte","png","jpg","jpeg","gif","webp","avif","svg","ico","bmp","tif","tiff","heic","heif","woff","woff2","ttf","otf","eot","mp3","wav","ogg","oga","opus","m4a","aac","flac","weba","mp4","webm","ogv","mov","m4v","avi","glb","gltf","usdz","vtt","srt","zip"],Ot=et.map(n=>`.${n}`).join(","),tt=/[\x00-\x1f\x7f#?%\\<>"]/;J=new Set(["node_modules","package.json"]);Ct="/auth",me={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},ge={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},Ee={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},C={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},x={API_KEY:me.API_KEY,DEPLOY_TOKEN:me.TOKEN,OPAQUE:"opaque"};_t={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},L="ship.json",De={rewrites:[{source:"/(.*)",destination:"/index.html"}]},H={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};Z="https://api.shipstatic.com",k={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},Ut="https://my.shipstatic.com/api-key",$t=4320*60,g={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};b={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},Ie=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;M={MIN_LENGTH:6,MAX_LENGTH:128}});async function ft(n){let t=(await import("spark-md5")).default,e=new t.ArrayBuffer,r=2097152;for(let i=0;i<n.size;i+=r){let s=Math.min(i+r,n.size);e.append(await n.slice(i,s).arrayBuffer())}return{md5:e.end()}}async function ht(n){let{createHash:t}=await import("crypto"),e=t("md5");return e.update(n),{md5:e.digest("hex")}}async function yt(n){let{createHash:t}=await import("crypto"),{createReadStream:e}=await import("fs");return new Promise((r,i)=>{let s=t("md5"),o=e(n);o.on("error",p=>i(a.file(`Failed to read file for MD5: ${p.message}`,{filePath:n}))),o.on("data",p=>s.update(p)),o.on("end",()=>r({md5:s.digest("hex")}))})}async function K(n){if(n instanceof Blob)return ft(n);if(typeof Buffer<"u"&&Buffer.isBuffer(n))return ht(n);if(typeof n=="string")return yt(n);throw a.business("Invalid input for MD5 calculation")}var V=R(()=>{"use strict";y()});function mn(n){ne=n}function Et(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function v(){return ne||Et()}var ne,$=R(()=>{"use strict";ne=null});function Ue(n){if(!n||n.length===0)return"";let t=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let e=t.map(s=>s.split("/").filter(Boolean)),r=[],i=Math.min(...e.map(s=>s.length));for(let s=0;s<i;s++){let o=e[0][s];if(e.every(p=>p[s]===o))r.push(o);else break}return r.join("/")}function Y(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var re=R(()=>{"use strict"});function $e(n,t={}){if(t.flatten===!1)return n.map(r=>({path:Y(r),name:ie(r)}));let e=At(n);return n.map(r=>{let i=Y(r);if(e){let s=e.endsWith("/")?e:`${e}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=ie(r)),{path:i,name:ie(r)}})}function At(n){if(!n.length)return"";let e=n.map(s=>Y(s)).map(s=>s.split("/")),r=[],i=Math.min(...e.map(s=>s.length));for(let s=0;s<i-1;s++){let o=e[0][s];if(e.every(p=>p[s]===o))r.push(o);else break}return r.join("/")}function ie(n){return n.split(/[/\\]/).pop()||n}var se=R(()=>{"use strict";re()});function X(n,t){return St.find(e=>e.broken(n,t))}var St,ae=R(()=>{"use strict";y();le();St=[{name:"name",broken:({path:n})=>!oe(n).valid,sentence:({path:n})=>oe(n).reason??"Invalid file name"},{name:"extension",broken:({path:n},t)=>he(n,t.blockedExtensions??[]),sentence:({path:n})=>`File extension not allowed: "${n}"`},{name:"fileSize",broken:({size:n},t)=>n>t.maxFileSize,sentence:({path:n},t)=>`File "${n}" too large. Maximum ${q(t.maxFileSize)} allowed`},{name:"totalSize",broken:({totalSize:n},t)=>n>t.maxTotalSize,sentence:({totalSize:n},t)=>`Total upload size too large. ${q(n)} exceeds maximum of ${q(t.maxTotalSize)}`}]});function q(n,t=1){if(n===0)return"0 Bytes";let e=1024,r=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(n)/Math.log(e));return`${parseFloat((n/e**i).toFixed(t))} ${r[i]}`}function oe(n){if(ye(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,e=n.split("/").pop()||n;return t.test(e)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function _n(n,t){let e=[],r=[],i=[];if(n.length===0){let l={file:"(no files)",message:"At least one file must be provided"};return e.push(l),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let l of n)if(B(l.name))return e.push({file:l.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(u=>({...u,status:g.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let l={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(l),{files:n.map(u=>({...u,status:g.VALIDATION_FAILED,statusMessage:l.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let l of n){let u=g.READY,c="Ready for upload";if(l.status===g.PROCESSING_ERROR)u=g.VALIDATION_FAILED,c=l.statusMessage||"File failed during processing",e.push({file:l.name,message:c});else if(l.size===0){u=g.EXCLUDED,c="File is empty (0 bytes) and cannot be deployed due to storage limitations",r.push({file:l.name,message:c}),i.push({...l,status:u,statusMessage:c});continue}else if(l.size<0)u=g.VALIDATION_FAILED,c="File size must be positive",e.push({file:l.name,message:c});else if(!l.name||l.name.trim().length===0)u=g.VALIDATION_FAILED,c="File name cannot be empty",e.push({file:l.name||"(empty)",message:c});else if(l.name.includes("\0"))u=g.VALIDATION_FAILED,c="File name contains invalid characters (null byte)",e.push({file:l.name,message:c});else{let E={path:l.name,size:l.size,totalSize:s+l.size},P=X(E,t);P?(u=g.VALIDATION_FAILED,c=P.sentence(E,t),e.push({file:P.name==="totalSize"?`(${n.length} files)`:l.name,message:c})):s=E.totalSize}i.push({...l,status:u,statusMessage:c})}e.length>0&&(i=i.map(l=>l.status===g.EXCLUDED?l:{...l,status:g.VALIDATION_FAILED,statusMessage:l.status===g.VALIDATION_FAILED?l.statusMessage:"Deployment failed due to validation errors in bundle"}));let o=e.length===0?i.filter(l=>l.status===g.READY):[],p=e.length===0;return{files:i,validFiles:o,errors:e,warnings:r,canDeploy:p}}function Rt(n){return n.filter(t=>t.status===g.READY)}function Fn(n){return Rt(n).length>0}var le=R(()=>{"use strict";y();ae()});import{isJunk as It}from"junk";function Me(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(r=>r&&B(r)))throw a.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return n.filter(e=>{if(!e)return!1;let r=e.replace(/\\/g,"/").split("/").filter(Boolean);if(r.length===0)return!0;let i=r[r.length-1];if(It(i))return!1;for(let o of r)if(o!==".well-known"&&(o.startsWith(".")||o.length>255))return!1;let s=r.slice(0,-1);for(let o of s)if(Pt.some(p=>o.toLowerCase()===p.toLowerCase()))return!1;return!0})}var Pt,ce=R(()=>{"use strict";y();Pt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Be(n,t){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw a.business(`Security error: Unsafe file path "${n}" for file: ${t}`)}function He(n,t){let e=X(n,t);if(e)throw a.business(e.sentence(n,t))}var pe=R(()=>{"use strict";y();ae()});var Ke={};Ye(Ke,{processFilesForNode:()=>ze});import*as D from"fs";import*as T from"path";function Ge(n,t=new Set){let e=[],r=D.realpathSync(n);if(t.has(r))return e;t.add(r);let i=D.readdirSync(n);for(let s of i){let o=T.join(n,s),p=D.statSync(o);if(p.isDirectory()){let l=Ge(o,t);e.push(...l)}else p.isFile()&&e.push(o)}return e}async function ze(n,t={},e){if(v()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let d of n){let h=T.resolve(d);try{if(D.statSync(h).isDirectory()){let A=D.readdirSync(h).find(S=>J.has(S));if(A)throw a.business(`"${A}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(A){if(F(A))throw A}}let r=n.flatMap(d=>{let h=T.resolve(d);try{return D.statSync(h).isDirectory()?Ge(h):[h]}catch{throw a.file(`Path does not exist: ${d}`,{filePath:d})}}),i=[...new Set(r)],s=n.map(d=>T.resolve(d)),o=Ue(s.map(d=>{try{return D.statSync(d).isDirectory()?d:T.dirname(d)}catch{return T.dirname(d)}})),p=i.map(d=>{if(o&&o.length>0){let h=T.relative(o,d);if(h&&typeof h=="string"&&!h.startsWith(".."))return h.replace(/\\/g,"/")}return T.basename(d)}),u=$e(p,{flatten:t.pathDetect!==!1}).map(d=>d.path),c=new Set(Me(u));if(c.size===0)return[];let E=[],P=[];for(let d=0;d<i.length;d++)c.has(u[d])&&(E.push(i[d]),P.push(u[d]));let N=[],w=0;if(!e)throw a.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let d=0;d<E.length;d++){let h=E[d],A=P[d];try{Be(A,h);let S=D.statSync(h);if(S.size===0)continue;w+=S.size,He({path:A,size:S.size,totalSize:w},e);let O=D.readFileSync(h),{md5:Ve}=await K(O);N.push({path:A,content:O,size:O.length,md5:Ve})}catch(S){if(F(S))throw S;let O=S instanceof Error?S.message:String(S);throw a.file(`Failed to read file "${h}": ${O}`,{filePath:h})}}if(N.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return N}var ue=R(()=>{"use strict";y();se();$();ce();V();re();pe()});y();y();y();var G=class{constructor(){this.handlers=new Map}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(e)}off(t,e){let r=this.handlers.get(t);r&&(r.delete(e),r.size===0&&this.handlers.delete(t))}emit(t,...e){let r=this.handlers.get(t);if(!r)return;let i=Array.from(r);for(let s of i)try{s(...e)}catch(o){r.delete(s),t!=="error"&&setTimeout(()=>{let p=o instanceof Error?o:new Error(String(o));this.emit("error",p,String(t))},0)}}};y();y();function U(n){if(n==null)return;if(n.length===0)return n;if(n.length>b.MAX_COUNT)throw a.validation(`Maximum ${b.MAX_COUNT} labels allowed`);let t=n.map((r,i)=>{if(typeof r!="string")throw a.validation(`Label at index ${i} must be a string`);let s=r.trim().toLowerCase();if(s.length<b.MIN_LENGTH)throw a.validation(`Labels must be at least ${b.MIN_LENGTH} characters long`);if(s.length>b.MAX_LENGTH)throw a.validation(`Labels must be no more than ${b.MAX_LENGTH} characters long`);if(!Ie.test(s))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${b.SEPARATORS}) between segments`);return s}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}async function Pe(n){let t=n.find(i=>i.path===L||i.path===`/${L}`);if(!t)return;let e=t.content,r=typeof e.text=="function"?await e.text():t.content.toString("utf8");Te(r)}var st=3e4,ot=2,at=300,lt=2e3,ct=new Set([500,502,503,504]);function pt(n,t){return new Promise((e,r)=>{if(t?.aborted){r(t.reason);return}let i=()=>{clearTimeout(o),t?.removeEventListener("abort",s)},s=()=>{i(),r(t?.reason)},o=setTimeout(()=>{i(),e()},n);t?.addEventListener("abort",s)})}var Le=3e5,ut=3e5,dt=Le+ut,mt="sdk";function te(n){let t=new URLSearchParams;n?.limit!==void 0&&t.set("limit",String(n.limit)),n?.cursor!==void 0&&t.set("cursor",n.cursor);let e=t.toString();return e?`?${e}`:""}var z=class extends G{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||Z,this.getAuthHeadersCallback=e.getAuthHeaders,this.session=e.session??!1,this.caller=e.caller,this.timeout=e.timeout??st,this.maxRetries=Math.max(0,e.maxRetries??ot),this.deployTimeout=e.timeout??Le,this.deployBuildTimeout=e.timeout??dt,this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||f.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}async executeRequest(e,r,i,s=this.timeout){for(let o=0;;o++)try{return await this.attemptOnce(e,r,i,s)}catch(p){let l=a.fromFetchError(p,i);if(o>=this.maxRetries||!this.isRetryable(l,r))throw this.emit("error",l,e),l;this.emit("retry",l,e,o+1);let u=Math.min(lt,at*2**o);try{await pt(Math.random()*u,r.signal)}catch(c){let E=a.fromFetchError(c,i);throw this.emit("error",E,e),E}}}isRetryable(e,r){if(r.signal?.aborted||e.isType(m.Maintenance)||e.isType(m.Cancelled)||!(e.isNetworkError()||e.status!==void 0&&ct.has(e.status)))return!1;let s=(r.method??"GET").toUpperCase();return s==="GET"||s==="HEAD"?!0:s==="PUT"||s==="DELETE"?!1:this.hasIdempotencyKey(r.headers)}hasIdempotencyKey(e){if(!e)return!1;let r=_.HEADER.toLowerCase(),i=!1,s=o=>{o.toLowerCase()===r&&(i=!0)};if(e instanceof Headers)e.forEach((o,p)=>{s(p)});else if(Array.isArray(e))for(let[o]of e)s(o);else for(let o of Object.keys(e))s(o);return i}async attemptOnce(e,r,i,s=this.timeout){let o=()=>{};try{let p=await this.mergeHeaders(r.headers),l=this.createTimeoutSignal(r.signal,s);o=l.cleanup;let u={...r,headers:p,credentials:this.session&&!p.Authorization?"include":void 0,signal:l.signal};this.emit("request",e,u);let c=await this.fetch(e,u);if(o(),!c.ok)throw await a.fromHttpResponse(c,i);return this.emit("response",this.safeClone(c),e),{data:await this.parseResponse(this.safeClone(c)),status:c.status}}catch(p){throw o(),a.fromFetchError(p,i)}}async request(e,r,i,s){let{data:o}=await this.executeRequest(e,r,i,s);return o}async requestWithStatus(e,r,i){return this.executeRequest(e,r,i)}async mergeHeaders(e={}){return{...this.globalHeaders,...this.caller?{[C.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e,r=this.timeout){let i=new AbortController,s=setTimeout(()=>i.abort(new DOMException(`Timed out after ${r}ms`,"TimeoutError")),r),o=e?()=>i.abort(e.reason):void 0;return e&&o&&(e.addEventListener("abort",o),e.aborted&&i.abort(e.reason)),{signal:i.signal,cleanup:()=>{clearTimeout(s),e&&o&&e.removeEventListener("abort",o)}}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async deploy(e,r={}){if(!e.length)throw a.business("No files to deploy");for(let u of e)if(!u.md5)throw a.file(`MD5 checksum missing for file: ${u.path}`,{filePath:u.path});ee(r.password);let i=fe(r.idempotencyKey),s=U(r.labels);await Pe(e);let o=r.build||r.prerender||r.spa?{build:r.build,prerender:r.prerender,spa:r.spa}:void 0,{body:p,headers:l}=await this.createDeployBody(e,{labels:s,via:r.via??mt,password:r.password,flags:o,captcha:r.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:p,headers:i?{...l,[_.HEADER]:i}:l,signal:r.signal||null},"Deploy",r.build||r.prerender?this.deployBuildTimeout:this.deployTimeout)}async listDeployments(e){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}${te(e)}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENT(encodeURIComponent(e))}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,r){let i=U(r);return this.request(`${this.apiUrl}${f.DEPLOYMENT(encodeURIComponent(e))}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:i})},"Update deployment labels")}async deleteDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENT(encodeURIComponent(e))}`,{method:"DELETE"},"Delete deployment")}async setDomain(e,r,i){let s=U(i),o={};r&&(o.deployment=r),s!==void 0&&(o.labels=s);let{data:p,status:l}=await this.requestWithStatus(`${this.apiUrl}${f.DOMAIN(encodeURIComponent(e))}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Set domain");return{...p,isCreate:l===201}}async listDomains(e){return this.request(`${this.apiUrl}${f.DOMAINS}${te(e)}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${f.DOMAIN(encodeURIComponent(e))}`,{method:"GET"},"Get domain")}async deleteDomain(e){return this.request(`${this.apiUrl}${f.DOMAIN(encodeURIComponent(e))}`,{method:"DELETE"},"Delete domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${f.DOMAIN_VERIFY(encodeURIComponent(e))}`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${f.DOMAIN_DNS(encodeURIComponent(e))}`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${f.DOMAIN_RECORDS(encodeURIComponent(e))}`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${f.DOMAIN_SHARE(encodeURIComponent(e))}`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS_VALIDATE}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,r){let i=U(r),s={};return e!==void 0&&(s.ttl=e),i!==void 0&&(s.labels=i),this.request(`${this.apiUrl}${f.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(e){return this.request(`${this.apiUrl}${f.TOKENS}${te(e)}`,{method:"GET"},"List tokens")}async deleteToken(e){return this.request(`${this.apiUrl}${f.TOKEN(encodeURIComponent(e))}`,{method:"DELETE"},"Delete token")}async getToken(e){return this.request(`${this.apiUrl}${f.TOKEN(encodeURIComponent(e))}`,{method:"GET"},"Get token")}async getAccount(){return this.request(`${this.apiUrl}${f.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${f.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return this.request(`${this.apiUrl}${f.PING}`,{method:"GET"},"Ping")}async checkSPA(e,r={}){let i=e.find(l=>l.path===H.INDEX_FILE||l.path===`/${H.INDEX_FILE}`);if(!i||i.size>H.MAX_INDEX_BYTES)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(i.content))s=i.content.toString("utf-8");else if(typeof Blob<"u"&&i.content instanceof Blob)s=await i.content.text();else if(typeof File<"u"&&i.content instanceof File)s=await i.content.text();else return!1;let o={files:e.map(l=>l.path),index:s};return(await this.request(`${this.apiUrl}${f.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"SPA check")).isSPA}};y();y();V();async function gt(){let n=JSON.stringify(De,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await K(t);return{path:L,content:t,size:n.length,md5:e}}async function we(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(r=>r.path===L))return n;try{if(await t.checkSPA(n,e)){let i=await gt();return[...n,i]}}catch{}return n}function be(n){let{getApi:t,ensureInit:e,processInput:r}=n;return{upload:async(i,s={})=>{if(await e(),!r)throw a.config("processInput function is not provided.");let o=t(),p=await r(i,s);return p=await we(p,o,s),o.deploy(p,s)},list:async i=>(await e(),t().listDeployments(i)),get:async i=>(await e(),t().getDeployment(i)),set:async(i,s)=>(await e(),t().updateDeploymentLabels(i,s.labels)),delete:async i=>(await e(),t().deleteDeployment(i))}}function Ne(n){let{getApi:t,ensureInit:e}=n;return{set:async(r,i={})=>(await e(),t().setDomain(r,i.deployment,i.labels)),list:async r=>(await e(),t().listDomains(r)),get:async r=>(await e(),t().getDomain(r)),delete:async r=>(await e(),t().deleteDomain(r)),verify:async r=>(await e(),t().verifyDomain(r)),validate:async r=>(await e(),t().validateDomain(r)),dns:async r=>(await e(),t().getDomainDns(r)),records:async r=>(await e(),t().getDomainRecords(r)),share:async r=>(await e(),t().getDomainShare(r))}}function xe(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function ve(n){let{getApi:t,ensureInit:e}=n;return{create:async(r={})=>(await e(),t().createToken(r.ttl,r.labels)),list:async r=>(await e(),t().listTokens(r)),get:async r=>(await e(),t().getToken(r)),delete:async r=>(await e(),t().deleteToken(r))}}var j=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&Se(t.caller),t.token&&t.session)throw a.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(Q(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new z({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=be({...e,processInput:(r,i)=>this.processInput(r,i)}),this.domains=Ne(e),this.account=xe(e),this.tokens=ve(e)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,e){return this.deployments.upload(t,e)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw a.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw a.business("Invalid token provided. Token must be a non-empty string.");Q(t),this.credential=t;return}if(typeof t!="function")throw a.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw a.authentication("Token provider returned no token.");if(typeof t!="string")throw a.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};$();y();import{z as _e}from"zod";import{z as Oe}from"zod";var Ce={apiUrl:Oe.string().url().optional(),token:Oe.string().min(1).optional()};$();var Dt=_e.object(Ce).strict(),Tt={apiUrl:k.API_URL,token:k.TOKEN};function Fe(){if(v()!=="node")return{};let n={apiUrl:process.env[k.API_URL]||void 0,token:process.env[k.TOKEN]||void 0};try{return Dt.parse(n)}catch(t){if(t instanceof _e.ZodError){let e=t.issues[0],r=e.path[0],i=(r&&Tt[r])??"SHIP environment configuration";throw a.config(`Invalid ${i}: ${e.message}`)}throw a.config("Invalid environment configuration")}}y();async function ke(n,t={}){let{FormData:e,File:r}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),{labels:s,via:o,password:p,flags:l,captcha:u}=t,c=new e,E=[];for(let d of n){if(!Buffer.isBuffer(d.content)&&!(typeof Blob<"u"&&d.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${d.path}`,{filePath:d.path});if(!d.md5)throw a.file(`File missing md5 checksum: ${d.path}`,{filePath:d.path});let h=new r([d.content],d.path,{type:"application/octet-stream"});c.append(I.FILES,h),E.push(d.md5)}c.append(I.CHECKSUMS,JSON.stringify(E)),s&&s.length>0&&c.append(I.LABELS,JSON.stringify(s)),o&&c.append(I.VIA,o),p&&c.append(I.PASSWORD,p),l?.build&&c.append(I.BUILD,"true"),l?.prerender&&c.append(I.PRERENDER,"true"),l?.spa&&c.append(I.SPA,"true"),u&&c.append(I.CAPTCHA,u);let P=new i(c),N=[];for await(let d of P.encode())N.push(Buffer.from(d));let w=Buffer.concat(N);return{body:w.buffer.slice(w.byteOffset,w.byteOffset+w.byteLength),headers:{"Content-Type":P.contentType,"Content-Length":Buffer.byteLength(w).toString()}}}y();y();se();$();le();ce();V();pe();function zn(n,t,e,r=!0){let i=n===1?t:e;return r?`${n} ${i}`:i}ue();var de=class extends j{constructor(t={}){if(v()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=Fe();super({...t,apiUrl:t.apiUrl||e.apiUrl,token:t.token||(t.session?void 0:e.token)})}async deploy(t,e){return super.deploy(t,e)}async processInput(t,e){let r=typeof t=="string"?[t]:t;if(!Array.isArray(r)||!r.every(s=>typeof s=="string"))throw a.business("Invalid input type for Node.js environment. Expected string or string[].");if(r.length===0)throw a.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(ue(),Ke));return i(r,e,this.platformLimits??void 0)}getDeployBodyCreator(){return ke}},Lt=de;export{ge as API_KEY,f as API_PATHS,Ct as AUTH_BASE_PATH,vt as AccountPlan,z as ApiHttp,me as AuthMethod,C as CALLER,Z as DEFAULT_API,L as DEPLOYMENT_CONFIG_FILENAME,I as DEPLOY_FIELDS,Ee as DEPLOY_TOKEN,bt as DeploymentStatus,qe as DeploymentVia,Nt as DomainStatus,m as ErrorType,g as FILE_VALIDATION_STATUS,g as FileValidationStatus,_ as IDEMPOTENCY_KEY_CONSTRAINTS,Pt as JUNK_DIRECTORIES,b as LABEL_CONSTRAINTS,Ie as LABEL_PATTERN,Ut as MY_API_KEY_URL,_t as OAuthScope,M as PASSWORD_CONSTRAINTS,$t as PUBLIC_DEPLOYMENT_TTL_SECONDS,k as SHIP_ENV,H as SPA_CHECK_CONSTRAINTS,De as SPA_DEFAULT_CONFIG,de as Ship,a as ShipError,x as TokenKind,J as UNBUILT_PROJECT_MARKERS,tt as UNSAFE_FILENAME_CHARS,Ot as WEB_FILE_ACCEPT,mn as __setTestEnvironment,Fn as allValidFilesReady,Te as assertShipJsonSyntax,K as calculateMD5,nt as classifyToken,xe as createAccountResource,be as createDeploymentResource,Ne as createDomainResource,ve as createTokenResource,Lt as default,Kt as deserializeLabels,Bt as extractSubdomain,Me as filterJunk,q as formatFileSize,Ht as generateDeploymentUrl,Gt as generateDomainUrl,v as getENV,Rt as getValidFiles,B as hasUnbuiltMarker,ye as hasUnsafeChars,he as isBlockedExtension,Mt as isCustomDomain,kt as isDeployment,Re as isPlatformDomain,F as isShipError,xt as normalizeVia,$e as optimizeDeployPaths,zn as pluralize,ze as processFilesForNode,zt as serializeLabels,rt as validateApiKey,Ft as validateApiUrl,Se as validateCaller,He as validateDeployFile,Be as validateDeployPath,it as validateDeployToken,oe as validateFileName,_n as validateFiles,fe as validateIdempotencyKey,ee as validatePassword,Q as validateToken};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|