@shipstatic/ship 3.0.0 → 3.2.0-beta.1

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
@@ -734,12 +734,45 @@ interface Caps {
734
734
  * A downgraded account therefore reads honestly as "3 of 0".
735
735
  */
736
736
  readonly customDomains: number;
737
+ /**
738
+ * People with a seat in the account: the owner and every member, each a
739
+ * membership row; a pending invitation holds no seat. As `usage` it is the
740
+ * current member count, as `caps` the plan's ceiling. Optional by the
741
+ * additive-evolution law: responses older than 3.1 carry no seats, and a
742
+ * consumer reads one seat and one owner where the field is absent.
743
+ */
744
+ readonly seats?: number;
737
745
  }
746
+ /**
747
+ * A person's standing in an account. `owner` founded it and alone manages
748
+ * billing, credentials, people and deletion; `member` uses its resources
749
+ * exactly as the owner does. These are Better Auth's own organization roles,
750
+ * and the only two the platform makes reachable.
751
+ */
752
+ type AccountRole = 'owner' | 'member';
753
+ /**
754
+ * Whether the credential's standing currently admits it to the account's
755
+ * resources. The owner is always `active`; a member is `active` while the
756
+ * account fits its seat cap and `paused` while it holds more people than
757
+ * the plan allows, until the owner upgrades or removes people. The state
758
+ * is derived on every request and never stored, and a paused member still
759
+ * reads the account, switches accounts and leaves; every other request is
760
+ * refused (403, `details.account: 'paused'`). A key or a deploy token is
761
+ * account automation, not a person, and is always `active`.
762
+ */
763
+ type AccountAccess = 'active' | 'paused';
738
764
  /**
739
765
  * Core account object - used in both API responses and SDK
740
766
  * All fields are readonly to prevent accidental mutations
741
767
  */
742
768
  interface Account {
769
+ /**
770
+ * The account this response describes, by id. A person may belong to
771
+ * several accounts and a browser session selects one, so a client names
772
+ * the one it means on every request (`X-Account`) and this is where it
773
+ * learns the name. Optional by the additive-evolution law.
774
+ */
775
+ readonly account?: string;
743
776
  /** User email address */
744
777
  readonly email: string;
745
778
  /** User display name, null if not set */
@@ -747,12 +780,10 @@ interface Account {
747
780
  /** User profile picture URL, null if not set */
748
781
  readonly picture: string | null;
749
782
  /**
750
- * The tier the account stands at. A sponsored account is Pro that nobody
751
- * bills, so it reports `pro` here with {@link billed} false; the grant
752
- * itself is the operator's fact, seen on the operator's surfaces and never
753
- * here. A console therefore treats a sponsored account exactly as a Pro one
754
- * everywhere, and the one difference it can see is the one that is real:
755
- * there is no Subscription.
783
+ * The plan the account is on, by its own name. A granted plan names
784
+ * itself: a sponsored account reports `sponsored` and a scale one `scale`,
785
+ * each with {@link billed} false. So a billed plan's name is a promise:
786
+ * `pro` or `team` here always means a Subscription bills the account.
756
787
  */
757
788
  readonly plan: AccountPlanType;
758
789
  /**
@@ -769,6 +800,22 @@ interface Account {
769
800
  * individually.
770
801
  */
771
802
  readonly caps: Caps;
803
+ /**
804
+ * The credential's standing in this account. Optional by the
805
+ * additive-evolution law: a response that predates seats names no role,
806
+ * and a consumer reads `owner`, because every account then had exactly one
807
+ * person. A key or a deploy token carries the owner's authority and reports
808
+ * `owner` too.
809
+ */
810
+ readonly role?: AccountRole;
811
+ /**
812
+ * Whether that standing admits the credential today: see
813
+ * {@link AccountAccess}. The API derives it from the same row that yields
814
+ * {@link role}, so a console reads it here rather than re-deriving it from
815
+ * the seat numbers. Optional by the additive-evolution law: a response
816
+ * that predates seats is always `active`.
817
+ */
818
+ readonly access?: AccountAccess;
772
819
  /** Unix timestamp (seconds) when account was created */
773
820
  readonly created: number;
774
821
  /** Unix timestamp (seconds) when account was activated (first deployment), null if not yet activated */
@@ -803,10 +850,12 @@ interface Account {
803
850
  readonly billed: boolean;
804
851
  /**
805
852
  * The next plan up the ladder this account could move to, or `null` when
806
- * there is none: the top billed tier, a plan sold by conversation, and any
807
- * plan not on the menu answer `null`. One server-side fact so that no surface derives "can this account
808
- * upgrade, and to what" from the menu — a grandfathered row has no menu
809
- * price to compare, and a conversation plan must never be sent to Checkout.
853
+ * there is none: the top billed tier and a plan sold by conversation answer
854
+ * `null`, and a plan below the ladder (free, sponsored) is offered its
855
+ * first sold row. One server-side fact so that no surface derives "can this
856
+ * account upgrade, and to what" from the menu — a grandfathered row has no
857
+ * menu price to compare, and a conversation plan must never be sent to
858
+ * Checkout.
810
859
  */
811
860
  readonly upgrade: AccountPlanType | null;
812
861
  /**
@@ -833,6 +882,27 @@ interface Account {
833
882
  * mirrored, what it would merely display is not.
834
883
  */
835
884
  readonly cancelAt: number | null;
885
+ /**
886
+ * Where this account may MOVE, as the change door would accept it: every
887
+ * sold plan whose door is open, with the billing intervals that are legal
888
+ * from where the account stands. It excludes the plan and cadence the
889
+ * account already holds and the one move the door refuses, a dearer tier
890
+ * at a shorter interval (an immediate move would mint a proration credit,
891
+ * a deferred one would make a customer asking for more wait a year). The
892
+ * rule's owner is the platform's plan table; a console feeds these
893
+ * intervals into its own move model instead of restating it. Additive:
894
+ * absent on responses that predate it, and a client then derives as it did.
895
+ */
896
+ readonly destinations?: PlanDestination[];
897
+ }
898
+ /**
899
+ * One row of `Account.destinations`: a plan the account may move to, and the
900
+ * intervals it may move to it with. `intervals` is never empty; a plan with
901
+ * no legal cadence is simply absent from the list.
902
+ */
903
+ interface PlanDestination {
904
+ readonly plan: AccountPlanType;
905
+ readonly intervals: BillingInterval[];
836
906
  }
837
907
  /**
838
908
  * Account as returned by `GET /account` — the entity plus how the request
@@ -1564,6 +1634,19 @@ declare const CALLER: {
1564
1634
  /** Allowed characters: alphanumeric, dot, underscore, hyphen. */
1565
1635
  readonly PATTERN: RegExp;
1566
1636
  };
1637
+ /**
1638
+ * The account a session request MEANS.
1639
+ *
1640
+ * A browser session selects one account for every tab at once, so a tab that
1641
+ * switched leaves its siblings acting for an account they no longer show. A
1642
+ * session caller may name the account it means in this header; the API
1643
+ * answers 409 `details.account: 'select'` when it differs from the account the
1644
+ * session resolves to, and the client re-selects. A precondition check the
1645
+ * client volunteers, never authority: a request without it resolves exactly as
1646
+ * before, and machine credentials never send it. One owner for the name, since
1647
+ * the API's CORS allowlist and every browser transport spell it.
1648
+ */
1649
+ declare const ACCOUNT_HEADER = "X-Account";
1567
1650
  /**
1568
1651
  * Token populations distinguishable by shape. The platform carries every
1569
1652
  * client token in one wire slot (`Authorization: Bearer <value>`) and
@@ -2281,6 +2364,13 @@ interface BillingPortalSession {
2281
2364
  */
2282
2365
  interface BillingSyncResponse {
2283
2366
  readonly plan: AccountPlanType;
2367
+ /**
2368
+ * Does Stripe bill that plan? The same fact as {@link Account.billed}, for
2369
+ * the plan named beside it. A purchase lands on a billed plan, so this is
2370
+ * what tells a Checkout arrival that the payment has landed: a plan that is
2371
+ * paid but granted (sponsored) is where the buyer stood before paying.
2372
+ */
2373
+ readonly billed: boolean;
2284
2374
  }
2285
2375
  /**
2286
2376
  * All activity event types logged in the system.
@@ -2292,11 +2382,11 @@ interface BillingSyncResponse {
2292
2382
  * keeps no IP address. Activity from deploys made without an account ages
2293
2383
  * out sooner, and deleting an account removes its rows outright, at any age.
2294
2384
  */
2295
- type ActivityEvent = 'account.create' | 'account.delete' | 'account.key.generate' | 'account.plan.transition' | 'deployment.create' | 'deployment.update' | 'deployment.delete' | 'deployment.claim' | 'deployment.flagged' | 'deployment.open' | 'domain.create' | 'domain.update' | 'domain.delete' | 'domain.verify' | 'domain.setup.open' | 'token.create' | 'token.consume' | 'token.delete' | 'checkout.open' | 'admin.account.plan.update' | 'admin.account.suspended.update' | 'admin.account.ref.update' | 'admin.account.labels.update' | 'admin.deployment.delete' | 'admin.deployment.review' | 'admin.domain.delete' | 'admin.impersonate';
2385
+ type ActivityEvent = 'account.create' | 'account.delete' | 'account.key.generate' | 'account.plan.transition' | 'deployment.create' | 'deployment.update' | 'deployment.delete' | 'deployment.claim' | 'deployment.flagged' | 'deployment.open' | 'domain.create' | 'domain.update' | 'domain.delete' | 'domain.verify' | 'domain.setup.open' | 'token.create' | 'token.consume' | 'token.delete' | 'member.join' | 'member.leave' | 'checkout.open' | 'admin.account.plan.update' | 'admin.account.suspended.update' | 'admin.account.ref.update' | 'admin.account.labels.update' | 'admin.deployment.delete' | 'admin.deployment.review' | 'admin.domain.delete' | 'admin.impersonate';
2296
2386
  /**
2297
2387
  * Activity events visible to users in the dashboard
2298
2388
  */
2299
- type UserVisibleActivityEvent = 'account.create' | 'account.delete' | 'account.key.generate' | 'account.plan.transition' | 'deployment.create' | 'deployment.update' | 'deployment.delete' | 'deployment.claim' | 'domain.create' | 'domain.update' | 'domain.delete' | 'domain.verify' | 'token.create' | 'token.consume' | 'token.delete';
2389
+ type UserVisibleActivityEvent = 'account.create' | 'account.delete' | 'account.key.generate' | 'account.plan.transition' | 'deployment.create' | 'deployment.update' | 'deployment.delete' | 'deployment.claim' | 'domain.create' | 'domain.update' | 'domain.delete' | 'domain.verify' | 'token.create' | 'token.consume' | 'token.delete' | 'member.join' | 'member.leave';
2300
2390
  /**
2301
2391
  * Activity record returned from the API
2302
2392
  */
@@ -2342,6 +2432,10 @@ interface ActivityMeta {
2342
2432
  * origin stays answerable afterwards.
2343
2433
  */
2344
2434
  via?: DeploymentViaType;
2435
+ /** The person the event is about, by user id: who joined, who left, who was removed. */
2436
+ subject?: string;
2437
+ /** On `member.leave` only, and only when somebody else acted: the remover's user id. A leave names nobody here. */
2438
+ by?: string;
2345
2439
  /** Whether this was an update (vs create) */
2346
2440
  isUpdate?: boolean;
2347
2441
  /** Whether domain was already verified */
@@ -3511,6 +3605,6 @@ declare class Ship extends Ship$1 {
3511
3605
  }
3512
3606
 
3513
3607
  declare namespace Ship {
3514
- export { API_KEY, API_PATHS, AUTH_BASE_PATH, Account, AccountDeleteResponse, AccountGetResponse, AccountKeyResponse, AccountPlan, AccountPlanType, AccountResource, Activity, ActivityEvent, ActivityListResponse, ActivityMeta, ApiDeployOptions, ApiHttp, ApiHttpOptions, AuthMethod, AuthMethodType, BUILD_SETTINGS, BillingInterval, BillingPortalSession, BillingSyncResponse, BuildFailureDetails, CALLER, Caps, DEFAULT_API, DEPLOYMENT_CONFIG_FILENAME, DEPLOY_FIELDS, DEPLOY_FILE_GRAMMAR, DEPLOY_TOKEN, DeployBodyContext, DeployFile, DeployFileEncoding, DeployFileSpec, DeployInput, DeployTransport, Deployment, DeploymentCreateResponse, DeploymentDeleteResponse, DeploymentListResponse, DeploymentOptions, DeploymentResource, DeploymentResourceContext, DeploymentSetOptions, DeploymentStatus, DeploymentStatusType, DeploymentUploadOptions, DeploymentVia, DeploymentViaType, DnsLookup, DnsProvider, DnsRecord, DnsRecordType, Domain, DomainDeleteResponse, DomainDnsResponse, DomainListResponse, DomainRecordsResponse, DomainResource, DomainSetOptions, DomainSetResult, DomainShareResponse, DomainStatus, DomainStatusType, DomainValidateResponse, DomainVerification, DomainVerificationType, DomainVerifyResponse, ErrorResponse, ErrorType, ExecutionEnvironment, FileValidationStatus as FILE_VALIDATION_STATUS, Fetch, FileValidationResult, FileValidationStatus, FileValidationStatusType, IDEMPOTENCY_KEY_CONSTRAINTS, JUNK_DIRECTORIES, LABEL_CONSTRAINTS, LABEL_PATTERN, LabelsResponse, ListOptions, ListResponse, MD5Result, MY_API_KEY_URL, OAUTH_TOKEN, OAuthScope, OAuthScopeType, PASSWORD_CONSTRAINTS, PUBLIC_DEPLOYMENT_TTL_SECONDS, PingResponse, Plan, PlanChangeRequest, PlanChangeResponse, PlansResponse, PlatformLimits, RequestResult, ResourceContext, SHIP_ENV, SHIP_VIA_ENV, SIGN_IN_RETURN_PARAM, SPACheckDebug, SPACheckRequest, SPACheckResponse, SPA_CHECK_CONSTRAINTS, SPA_DEFAULT_CONFIG, ScheduledChange, SetupInstructionsResponse, ShipClientOptions, ShipError, ShipEvents, ShipRequestInit, StaticFile, TTL_CONSTRAINTS, Token, TokenCreateOptions, TokenCreateResponse, TokenDeleteResponse, TokenKind, TokenKindType, TokenListResponse, TokenProvider, TokenResource, Transport, UNBUILT_PROJECT_MARKERS, UNSAFE_FILENAME_CHARS, UploadedFile, UserVisibleActivityEvent, ValidatableFile, ValidationIssue, WEB_FILE_ACCEPT, __setTestEnvironment, allValidFilesReady, assertShipJsonSyntax, calculateMD5, classifyToken, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, deserializeLabels, extractSubdomain, filterJunk, formatDuration, formatFileSize, formatTimeRemaining, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isCustomDomain, isDeployment, isPlatformDomain, isShipError, normalizeVia, optimizeDeployPaths, pluralize, processFilesForNode, readBearerValue, serializeLabels, validateApiKey, validateApiUrl, validateBuildCommand, validateCaller, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validateIdempotencyKey, validateOAuthToken, validateOutputDir, validatePassword, validateToken, validateTtl };
3608
+ export { ACCOUNT_HEADER, API_KEY, API_PATHS, AUTH_BASE_PATH, Account, AccountAccess, AccountDeleteResponse, AccountGetResponse, AccountKeyResponse, AccountPlan, AccountPlanType, AccountResource, AccountRole, Activity, ActivityEvent, ActivityListResponse, ActivityMeta, ApiDeployOptions, ApiHttp, ApiHttpOptions, AuthMethod, AuthMethodType, BUILD_SETTINGS, BillingInterval, BillingPortalSession, BillingSyncResponse, BuildFailureDetails, CALLER, Caps, DEFAULT_API, DEPLOYMENT_CONFIG_FILENAME, DEPLOY_FIELDS, DEPLOY_FILE_GRAMMAR, DEPLOY_TOKEN, DeployBodyContext, DeployFile, DeployFileEncoding, DeployFileSpec, DeployInput, DeployTransport, Deployment, DeploymentCreateResponse, DeploymentDeleteResponse, DeploymentListResponse, DeploymentOptions, DeploymentResource, DeploymentResourceContext, DeploymentSetOptions, DeploymentStatus, DeploymentStatusType, DeploymentUploadOptions, DeploymentVia, DeploymentViaType, DnsLookup, DnsProvider, DnsRecord, DnsRecordType, Domain, DomainDeleteResponse, DomainDnsResponse, DomainListResponse, DomainRecordsResponse, DomainResource, DomainSetOptions, DomainSetResult, DomainShareResponse, DomainStatus, DomainStatusType, DomainValidateResponse, DomainVerification, DomainVerificationType, DomainVerifyResponse, ErrorResponse, ErrorType, ExecutionEnvironment, FileValidationStatus as FILE_VALIDATION_STATUS, Fetch, FileValidationResult, FileValidationStatus, FileValidationStatusType, IDEMPOTENCY_KEY_CONSTRAINTS, JUNK_DIRECTORIES, LABEL_CONSTRAINTS, LABEL_PATTERN, LabelsResponse, ListOptions, ListResponse, MD5Result, MY_API_KEY_URL, OAUTH_TOKEN, OAuthScope, OAuthScopeType, PASSWORD_CONSTRAINTS, PUBLIC_DEPLOYMENT_TTL_SECONDS, PingResponse, Plan, PlanChangeRequest, PlanChangeResponse, PlanDestination, PlansResponse, PlatformLimits, RequestResult, ResourceContext, SHIP_ENV, SHIP_VIA_ENV, SIGN_IN_RETURN_PARAM, SPACheckDebug, SPACheckRequest, SPACheckResponse, SPA_CHECK_CONSTRAINTS, SPA_DEFAULT_CONFIG, ScheduledChange, SetupInstructionsResponse, ShipClientOptions, ShipError, ShipEvents, ShipRequestInit, StaticFile, TTL_CONSTRAINTS, Token, TokenCreateOptions, TokenCreateResponse, TokenDeleteResponse, TokenKind, TokenKindType, TokenListResponse, TokenProvider, TokenResource, Transport, UNBUILT_PROJECT_MARKERS, UNSAFE_FILENAME_CHARS, UploadedFile, UserVisibleActivityEvent, ValidatableFile, ValidationIssue, WEB_FILE_ACCEPT, __setTestEnvironment, allValidFilesReady, assertShipJsonSyntax, calculateMD5, classifyToken, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, deserializeLabels, extractSubdomain, filterJunk, formatDuration, formatFileSize, formatTimeRemaining, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isCustomDomain, isDeployment, isPlatformDomain, isShipError, normalizeVia, optimizeDeployPaths, pluralize, processFilesForNode, readBearerValue, serializeLabels, validateApiKey, validateApiUrl, validateBuildCommand, validateCaller, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validateIdempotencyKey, validateOAuthToken, validateOutputDir, validatePassword, validateToken, validateTtl };
3515
3609
  }
3516
3610
  export = Ship;
package/dist/index.d.ts CHANGED
@@ -734,12 +734,45 @@ interface Caps {
734
734
  * A downgraded account therefore reads honestly as "3 of 0".
735
735
  */
736
736
  readonly customDomains: number;
737
+ /**
738
+ * People with a seat in the account: the owner and every member, each a
739
+ * membership row; a pending invitation holds no seat. As `usage` it is the
740
+ * current member count, as `caps` the plan's ceiling. Optional by the
741
+ * additive-evolution law: responses older than 3.1 carry no seats, and a
742
+ * consumer reads one seat and one owner where the field is absent.
743
+ */
744
+ readonly seats?: number;
737
745
  }
746
+ /**
747
+ * A person's standing in an account. `owner` founded it and alone manages
748
+ * billing, credentials, people and deletion; `member` uses its resources
749
+ * exactly as the owner does. These are Better Auth's own organization roles,
750
+ * and the only two the platform makes reachable.
751
+ */
752
+ type AccountRole = 'owner' | 'member';
753
+ /**
754
+ * Whether the credential's standing currently admits it to the account's
755
+ * resources. The owner is always `active`; a member is `active` while the
756
+ * account fits its seat cap and `paused` while it holds more people than
757
+ * the plan allows, until the owner upgrades or removes people. The state
758
+ * is derived on every request and never stored, and a paused member still
759
+ * reads the account, switches accounts and leaves; every other request is
760
+ * refused (403, `details.account: 'paused'`). A key or a deploy token is
761
+ * account automation, not a person, and is always `active`.
762
+ */
763
+ type AccountAccess = 'active' | 'paused';
738
764
  /**
739
765
  * Core account object - used in both API responses and SDK
740
766
  * All fields are readonly to prevent accidental mutations
741
767
  */
742
768
  interface Account {
769
+ /**
770
+ * The account this response describes, by id. A person may belong to
771
+ * several accounts and a browser session selects one, so a client names
772
+ * the one it means on every request (`X-Account`) and this is where it
773
+ * learns the name. Optional by the additive-evolution law.
774
+ */
775
+ readonly account?: string;
743
776
  /** User email address */
744
777
  readonly email: string;
745
778
  /** User display name, null if not set */
@@ -747,12 +780,10 @@ interface Account {
747
780
  /** User profile picture URL, null if not set */
748
781
  readonly picture: string | null;
749
782
  /**
750
- * The tier the account stands at. A sponsored account is Pro that nobody
751
- * bills, so it reports `pro` here with {@link billed} false; the grant
752
- * itself is the operator's fact, seen on the operator's surfaces and never
753
- * here. A console therefore treats a sponsored account exactly as a Pro one
754
- * everywhere, and the one difference it can see is the one that is real:
755
- * there is no Subscription.
783
+ * The plan the account is on, by its own name. A granted plan names
784
+ * itself: a sponsored account reports `sponsored` and a scale one `scale`,
785
+ * each with {@link billed} false. So a billed plan's name is a promise:
786
+ * `pro` or `team` here always means a Subscription bills the account.
756
787
  */
757
788
  readonly plan: AccountPlanType;
758
789
  /**
@@ -769,6 +800,22 @@ interface Account {
769
800
  * individually.
770
801
  */
771
802
  readonly caps: Caps;
803
+ /**
804
+ * The credential's standing in this account. Optional by the
805
+ * additive-evolution law: a response that predates seats names no role,
806
+ * and a consumer reads `owner`, because every account then had exactly one
807
+ * person. A key or a deploy token carries the owner's authority and reports
808
+ * `owner` too.
809
+ */
810
+ readonly role?: AccountRole;
811
+ /**
812
+ * Whether that standing admits the credential today: see
813
+ * {@link AccountAccess}. The API derives it from the same row that yields
814
+ * {@link role}, so a console reads it here rather than re-deriving it from
815
+ * the seat numbers. Optional by the additive-evolution law: a response
816
+ * that predates seats is always `active`.
817
+ */
818
+ readonly access?: AccountAccess;
772
819
  /** Unix timestamp (seconds) when account was created */
773
820
  readonly created: number;
774
821
  /** Unix timestamp (seconds) when account was activated (first deployment), null if not yet activated */
@@ -803,10 +850,12 @@ interface Account {
803
850
  readonly billed: boolean;
804
851
  /**
805
852
  * The next plan up the ladder this account could move to, or `null` when
806
- * there is none: the top billed tier, a plan sold by conversation, and any
807
- * plan not on the menu answer `null`. One server-side fact so that no surface derives "can this account
808
- * upgrade, and to what" from the menu — a grandfathered row has no menu
809
- * price to compare, and a conversation plan must never be sent to Checkout.
853
+ * there is none: the top billed tier and a plan sold by conversation answer
854
+ * `null`, and a plan below the ladder (free, sponsored) is offered its
855
+ * first sold row. One server-side fact so that no surface derives "can this
856
+ * account upgrade, and to what" from the menu — a grandfathered row has no
857
+ * menu price to compare, and a conversation plan must never be sent to
858
+ * Checkout.
810
859
  */
811
860
  readonly upgrade: AccountPlanType | null;
812
861
  /**
@@ -833,6 +882,27 @@ interface Account {
833
882
  * mirrored, what it would merely display is not.
834
883
  */
835
884
  readonly cancelAt: number | null;
885
+ /**
886
+ * Where this account may MOVE, as the change door would accept it: every
887
+ * sold plan whose door is open, with the billing intervals that are legal
888
+ * from where the account stands. It excludes the plan and cadence the
889
+ * account already holds and the one move the door refuses, a dearer tier
890
+ * at a shorter interval (an immediate move would mint a proration credit,
891
+ * a deferred one would make a customer asking for more wait a year). The
892
+ * rule's owner is the platform's plan table; a console feeds these
893
+ * intervals into its own move model instead of restating it. Additive:
894
+ * absent on responses that predate it, and a client then derives as it did.
895
+ */
896
+ readonly destinations?: PlanDestination[];
897
+ }
898
+ /**
899
+ * One row of `Account.destinations`: a plan the account may move to, and the
900
+ * intervals it may move to it with. `intervals` is never empty; a plan with
901
+ * no legal cadence is simply absent from the list.
902
+ */
903
+ interface PlanDestination {
904
+ readonly plan: AccountPlanType;
905
+ readonly intervals: BillingInterval[];
836
906
  }
837
907
  /**
838
908
  * Account as returned by `GET /account` — the entity plus how the request
@@ -1564,6 +1634,19 @@ declare const CALLER: {
1564
1634
  /** Allowed characters: alphanumeric, dot, underscore, hyphen. */
1565
1635
  readonly PATTERN: RegExp;
1566
1636
  };
1637
+ /**
1638
+ * The account a session request MEANS.
1639
+ *
1640
+ * A browser session selects one account for every tab at once, so a tab that
1641
+ * switched leaves its siblings acting for an account they no longer show. A
1642
+ * session caller may name the account it means in this header; the API
1643
+ * answers 409 `details.account: 'select'` when it differs from the account the
1644
+ * session resolves to, and the client re-selects. A precondition check the
1645
+ * client volunteers, never authority: a request without it resolves exactly as
1646
+ * before, and machine credentials never send it. One owner for the name, since
1647
+ * the API's CORS allowlist and every browser transport spell it.
1648
+ */
1649
+ declare const ACCOUNT_HEADER = "X-Account";
1567
1650
  /**
1568
1651
  * Token populations distinguishable by shape. The platform carries every
1569
1652
  * client token in one wire slot (`Authorization: Bearer <value>`) and
@@ -2281,6 +2364,13 @@ interface BillingPortalSession {
2281
2364
  */
2282
2365
  interface BillingSyncResponse {
2283
2366
  readonly plan: AccountPlanType;
2367
+ /**
2368
+ * Does Stripe bill that plan? The same fact as {@link Account.billed}, for
2369
+ * the plan named beside it. A purchase lands on a billed plan, so this is
2370
+ * what tells a Checkout arrival that the payment has landed: a plan that is
2371
+ * paid but granted (sponsored) is where the buyer stood before paying.
2372
+ */
2373
+ readonly billed: boolean;
2284
2374
  }
2285
2375
  /**
2286
2376
  * All activity event types logged in the system.
@@ -2292,11 +2382,11 @@ interface BillingSyncResponse {
2292
2382
  * keeps no IP address. Activity from deploys made without an account ages
2293
2383
  * out sooner, and deleting an account removes its rows outright, at any age.
2294
2384
  */
2295
- type ActivityEvent = 'account.create' | 'account.delete' | 'account.key.generate' | 'account.plan.transition' | 'deployment.create' | 'deployment.update' | 'deployment.delete' | 'deployment.claim' | 'deployment.flagged' | 'deployment.open' | 'domain.create' | 'domain.update' | 'domain.delete' | 'domain.verify' | 'domain.setup.open' | 'token.create' | 'token.consume' | 'token.delete' | 'checkout.open' | 'admin.account.plan.update' | 'admin.account.suspended.update' | 'admin.account.ref.update' | 'admin.account.labels.update' | 'admin.deployment.delete' | 'admin.deployment.review' | 'admin.domain.delete' | 'admin.impersonate';
2385
+ type ActivityEvent = 'account.create' | 'account.delete' | 'account.key.generate' | 'account.plan.transition' | 'deployment.create' | 'deployment.update' | 'deployment.delete' | 'deployment.claim' | 'deployment.flagged' | 'deployment.open' | 'domain.create' | 'domain.update' | 'domain.delete' | 'domain.verify' | 'domain.setup.open' | 'token.create' | 'token.consume' | 'token.delete' | 'member.join' | 'member.leave' | 'checkout.open' | 'admin.account.plan.update' | 'admin.account.suspended.update' | 'admin.account.ref.update' | 'admin.account.labels.update' | 'admin.deployment.delete' | 'admin.deployment.review' | 'admin.domain.delete' | 'admin.impersonate';
2296
2386
  /**
2297
2387
  * Activity events visible to users in the dashboard
2298
2388
  */
2299
- type UserVisibleActivityEvent = 'account.create' | 'account.delete' | 'account.key.generate' | 'account.plan.transition' | 'deployment.create' | 'deployment.update' | 'deployment.delete' | 'deployment.claim' | 'domain.create' | 'domain.update' | 'domain.delete' | 'domain.verify' | 'token.create' | 'token.consume' | 'token.delete';
2389
+ type UserVisibleActivityEvent = 'account.create' | 'account.delete' | 'account.key.generate' | 'account.plan.transition' | 'deployment.create' | 'deployment.update' | 'deployment.delete' | 'deployment.claim' | 'domain.create' | 'domain.update' | 'domain.delete' | 'domain.verify' | 'token.create' | 'token.consume' | 'token.delete' | 'member.join' | 'member.leave';
2300
2390
  /**
2301
2391
  * Activity record returned from the API
2302
2392
  */
@@ -2342,6 +2432,10 @@ interface ActivityMeta {
2342
2432
  * origin stays answerable afterwards.
2343
2433
  */
2344
2434
  via?: DeploymentViaType;
2435
+ /** The person the event is about, by user id: who joined, who left, who was removed. */
2436
+ subject?: string;
2437
+ /** On `member.leave` only, and only when somebody else acted: the remover's user id. A leave names nobody here. */
2438
+ by?: string;
2345
2439
  /** Whether this was an update (vs create) */
2346
2440
  isUpdate?: boolean;
2347
2441
  /** Whether domain was already verified */
@@ -3510,4 +3604,4 @@ declare class Ship extends Ship$1 {
3510
3604
  protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
3511
3605
  }
3512
3606
 
3513
- export { API_KEY, API_PATHS, AUTH_BASE_PATH, type Account, type AccountDeleteResponse, type AccountGetResponse, type AccountKeyResponse, AccountPlan, type AccountPlanType, type AccountResource, type Activity, type ActivityEvent, type ActivityListResponse, type ActivityMeta, type ApiDeployOptions, ApiHttp, type ApiHttpOptions, AuthMethod, type AuthMethodType, BUILD_SETTINGS, type BillingInterval, type BillingPortalSession, type BillingSyncResponse, type BuildFailureDetails, CALLER, type Caps, DEFAULT_API, DEPLOYMENT_CONFIG_FILENAME, DEPLOY_FIELDS, DEPLOY_FILE_GRAMMAR, DEPLOY_TOKEN, type DeployBodyContext, type DeployFile, type DeployFileEncoding, type DeployFileSpec, type DeployInput, type DeployTransport, type Deployment, type DeploymentCreateResponse, type DeploymentDeleteResponse, type DeploymentListResponse, type DeploymentOptions, type DeploymentResource, type DeploymentResourceContext, type DeploymentSetOptions, DeploymentStatus, type DeploymentStatusType, type DeploymentUploadOptions, DeploymentVia, type DeploymentViaType, type DnsLookup, type DnsProvider, type DnsRecord, type DnsRecordType, type Domain, type DomainDeleteResponse, type DomainDnsResponse, type DomainListResponse, type DomainRecordsResponse, type DomainResource, type DomainSetOptions, type DomainSetResult, type DomainShareResponse, DomainStatus, type DomainStatusType, type DomainValidateResponse, DomainVerification, type DomainVerificationType, type DomainVerifyResponse, type ErrorResponse, ErrorType, type ExecutionEnvironment, FileValidationStatus as FILE_VALIDATION_STATUS, type Fetch, type FileValidationResult, FileValidationStatus, type FileValidationStatusType, IDEMPOTENCY_KEY_CONSTRAINTS, JUNK_DIRECTORIES, LABEL_CONSTRAINTS, LABEL_PATTERN, type LabelsResponse, type ListOptions, type ListResponse, type MD5Result, MY_API_KEY_URL, OAUTH_TOKEN, OAuthScope, type OAuthScopeType, PASSWORD_CONSTRAINTS, PUBLIC_DEPLOYMENT_TTL_SECONDS, type PingResponse, type Plan, type PlanChangeRequest, type PlanChangeResponse, type PlansResponse, type PlatformLimits, type RequestResult, type ResourceContext, SHIP_ENV, SHIP_VIA_ENV, SIGN_IN_RETURN_PARAM, type SPACheckDebug, type SPACheckRequest, type SPACheckResponse, SPA_CHECK_CONSTRAINTS, SPA_DEFAULT_CONFIG, type ScheduledChange, type SetupInstructionsResponse, Ship, type ShipClientOptions, ShipError, type ShipEvents, type ShipRequestInit, type StaticFile, TTL_CONSTRAINTS, type Token, type TokenCreateOptions, type TokenCreateResponse, type TokenDeleteResponse, TokenKind, type TokenKindType, type TokenListResponse, type TokenProvider, type TokenResource, type Transport, UNBUILT_PROJECT_MARKERS, UNSAFE_FILENAME_CHARS, type UploadedFile, type UserVisibleActivityEvent, type ValidatableFile, type ValidationIssue, WEB_FILE_ACCEPT, __setTestEnvironment, allValidFilesReady, assertShipJsonSyntax, calculateMD5, classifyToken, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, deserializeLabels, extractSubdomain, filterJunk, formatDuration, formatFileSize, formatTimeRemaining, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isCustomDomain, isDeployment, isPlatformDomain, isShipError, normalizeVia, optimizeDeployPaths, pluralize, processFilesForNode, readBearerValue, serializeLabels, validateApiKey, validateApiUrl, validateBuildCommand, validateCaller, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validateIdempotencyKey, validateOAuthToken, validateOutputDir, validatePassword, validateToken, validateTtl };
3607
+ export { ACCOUNT_HEADER, API_KEY, API_PATHS, AUTH_BASE_PATH, type Account, type AccountAccess, type AccountDeleteResponse, type AccountGetResponse, type AccountKeyResponse, AccountPlan, type AccountPlanType, type AccountResource, type AccountRole, type Activity, type ActivityEvent, type ActivityListResponse, type ActivityMeta, type ApiDeployOptions, ApiHttp, type ApiHttpOptions, AuthMethod, type AuthMethodType, BUILD_SETTINGS, type BillingInterval, type BillingPortalSession, type BillingSyncResponse, type BuildFailureDetails, CALLER, type Caps, DEFAULT_API, DEPLOYMENT_CONFIG_FILENAME, DEPLOY_FIELDS, DEPLOY_FILE_GRAMMAR, DEPLOY_TOKEN, type DeployBodyContext, type DeployFile, type DeployFileEncoding, type DeployFileSpec, type DeployInput, type DeployTransport, type Deployment, type DeploymentCreateResponse, type DeploymentDeleteResponse, type DeploymentListResponse, type DeploymentOptions, type DeploymentResource, type DeploymentResourceContext, type DeploymentSetOptions, DeploymentStatus, type DeploymentStatusType, type DeploymentUploadOptions, DeploymentVia, type DeploymentViaType, type DnsLookup, type DnsProvider, type DnsRecord, type DnsRecordType, type Domain, type DomainDeleteResponse, type DomainDnsResponse, type DomainListResponse, type DomainRecordsResponse, type DomainResource, type DomainSetOptions, type DomainSetResult, type DomainShareResponse, DomainStatus, type DomainStatusType, type DomainValidateResponse, DomainVerification, type DomainVerificationType, type DomainVerifyResponse, type ErrorResponse, ErrorType, type ExecutionEnvironment, FileValidationStatus as FILE_VALIDATION_STATUS, type Fetch, type FileValidationResult, FileValidationStatus, type FileValidationStatusType, IDEMPOTENCY_KEY_CONSTRAINTS, JUNK_DIRECTORIES, LABEL_CONSTRAINTS, LABEL_PATTERN, type LabelsResponse, type ListOptions, type ListResponse, type MD5Result, MY_API_KEY_URL, OAUTH_TOKEN, OAuthScope, type OAuthScopeType, PASSWORD_CONSTRAINTS, PUBLIC_DEPLOYMENT_TTL_SECONDS, type PingResponse, type Plan, type PlanChangeRequest, type PlanChangeResponse, type PlanDestination, type PlansResponse, type PlatformLimits, type RequestResult, type ResourceContext, SHIP_ENV, SHIP_VIA_ENV, SIGN_IN_RETURN_PARAM, type SPACheckDebug, type SPACheckRequest, type SPACheckResponse, SPA_CHECK_CONSTRAINTS, SPA_DEFAULT_CONFIG, type ScheduledChange, type SetupInstructionsResponse, Ship, type ShipClientOptions, ShipError, type ShipEvents, type ShipRequestInit, type StaticFile, TTL_CONSTRAINTS, type Token, type TokenCreateOptions, type TokenCreateResponse, type TokenDeleteResponse, TokenKind, type TokenKindType, type TokenListResponse, type TokenProvider, type TokenResource, type Transport, UNBUILT_PROJECT_MARKERS, UNSAFE_FILENAME_CHARS, type UploadedFile, type UserVisibleActivityEvent, type ValidatableFile, type ValidationIssue, WEB_FILE_ACCEPT, __setTestEnvironment, allValidFilesReady, assertShipJsonSyntax, calculateMD5, classifyToken, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, deserializeLabels, extractSubdomain, filterJunk, formatDuration, formatFileSize, formatTimeRemaining, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isCustomDomain, isDeployment, isPlatformDomain, isShipError, normalizeVia, optimizeDeployPaths, pluralize, processFilesForNode, readBearerValue, serializeLabels, validateApiKey, validateApiUrl, validateBuildCommand, validateCaller, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validateIdempotencyKey, validateOAuthToken, validateOutputDir, validatePassword, validateToken, validateTtl };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Qe=Object.defineProperty;var A=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ze=(e,t)=>{for(var n in t)Qe(e,n,{get:t[n],enumerable:!0})};function Vt(e){if(!e||typeof e!="string")return;let t=e.trim().toLowerCase();return Object.values(et).includes(t)?t:void 0}function ye(e){if(e==null)return;if(typeof e!="string")throw s.validation("Idempotency key must be a string.");let t=e.trim();if(!t)throw s.validation("Idempotency key must not be empty.");if(t.length>N.MAX_LENGTH)throw s.validation(`Idempotency key must be at most ${N.MAX_LENGTH} characters.`);return t}function it(e){let t=e.code;return t==="ERR_INVALID_URL"?!1:typeof t=="string"?!0:e instanceof TypeError?!/\burl\b/i.test(e.message):!1}function F(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function ot(e){let t=e.replace(/\\/g,"/").split("/").pop()??"",n=t.lastIndexOf(".");return n<=0||n===t.length-1?null:t.slice(n+1).toLowerCase()}function Ee(e,t){let n=ot(e);return n===null?!1:Array.isArray(t)?t.includes(n):t.has(n)}function ge(e){return at.test(e)}function M(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>Q.has(n))}function lt(e){return e.startsWith(Te.PREFIX)?R.API_KEY:e.startsWith(Ae.PREFIX)?R.DEPLOY_TOKEN:e.startsWith(De.PREFIX)?R.OAUTH:R.OPAQUE}function Wt(e){return e.slice(0,W.length).toLowerCase()!==W?null:e.slice(W.length)||null}function Re(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(r){throw s.config(`invalid JSON format in config: ${r.message}`,{filePath:D})}if(n===null||typeof n!="object"||Array.isArray(n))throw s.config(`${D} must contain a JSON object`,{filePath:D})}function Z(e,t,n){if(!e.startsWith(t.PREFIX))throw s.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw s.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let r=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(r))throw s.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function pt(e){Z(e,Te,"API key")}function ct(e){Z(e,Ae,"Deploy token")}function ut(e){Z(e,De,"OAuth access token")}function ee(e){switch(lt(e)){case R.API_KEY:pt(e);return;case R.DEPLOY_TOKEN:ct(e);return;case R.OAUTH:ut(e);return;case R.OPAQUE:if(!e)throw s.validation("Token must be a non-empty string")}}function Ie(e){if(!e||e.length>P.MAX_LENGTH||!P.PATTERN.test(e))throw s.validation(`Caller must be 1-${P.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function Qt(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw s.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw s.validation("API URL must not contain a path");if(t.search||t.hash)throw s.validation("API URL must not contain query parameters or fragments")}catch(t){throw F(t)?t:s.validation("API URL must be a valid URL")}}function Zt(e){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(e)}function te(e){if(e!=null){if(typeof e!="number"||!Number.isFinite(e))throw s.validation("TTL must be a number of seconds");if(!Number.isInteger(e))throw s.validation("TTL must be a whole number of seconds");if(e<v.MIN_SECONDS||e>v.MAX_SECONDS)throw s.validation(`TTL must be between ${v.MIN_SECONDS} and ${v.MAX_SECONDS} seconds`);return e}}function dt(e){let t=Math.round(e/60);if(!(t>=1))return"less than a minute";if(t<120)return J(t,"minute");let n=Math.round(e/3600);return n<48?J(n,"hour"):J(Math.round(e/86400),"day")}function rn(e,t=Date.now()/1e3){let n=e-t;return n>0?dt(n):null}function J(e,t){return`${e} ${t}${e===1?"":"s"}`}function _(e,t=1){if(e===0)return"0 Bytes";let n=1024,r=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(n));return`${Number.parseFloat((e/n**i).toFixed(t))} ${r[i]}`}function Ne(e,t){return e.endsWith(`.${t}`)}function on(e,t){return!Ne(e,t)}function sn(e,t){return Ne(e,t)?e.slice(0,-(t.length+1)):null}function an(e){return`https://${e}`}function ln(e){return`https://${e}`}function pn(e){return!e||e.length===0?null:JSON.stringify(e)}function cn(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Pe(e){if(e==null||e==="")return;if(typeof e!="string")throw s.validation("Build command must be a string");let t=e.trim();if(t.length===0||t.length>b.COMMAND_MAX_LENGTH)throw s.validation(`Build command must be between 1 and ${b.COMMAND_MAX_LENGTH} characters`);if(/[\x00-\x1f\x7f]/.test(t))throw s.validation("Build command must be a single line");return t}function be(e){if(e==null||e==="")return;if(typeof e!="string")throw s.validation("Output folder must be a string");let t=e.trim().replace(/\/+$/,"");if(t.length===0||t.length>b.OUTPUT_DIR_MAX_LENGTH)throw s.validation(`Output folder must be between 1 and ${b.OUTPUT_DIR_MAX_LENGTH} characters`);if(!b.OUTPUT_DIR_PATTERN.test(t)||t.split("/").some(n=>n===".."||n==="."))throw s.validation("Output folder must be a relative path inside the project, like dist or dist/site");return t}function re(e){if(e==null)return;if(typeof e!="string")throw s.validation("Password must be a string");let t=e.trim();if(t.length<C.MIN_LENGTH||t.length>C.MAX_LENGTH)throw s.validation(`Password must be between ${C.MIN_LENGTH} and ${C.MAX_LENGTH} characters`);return t}var Gt,et,Bt,zt,N,Kt,m,E,qt,d,tt,Y,nt,rt,s,st,Xt,at,Q,Yt,jt,j,Te,Ae,De,P,R,W,Jt,D,Se,U,v,ne,O,en,tn,nn,h,I,Le,b,C,f=A(()=>{"use strict";Gt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},et={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc",CLD:"cld",CRS:"crs",GMN:"gmn",API:"api"},Bt={LIVE:"live",UNLINKED:"unlinked",UNVERIFIED:"unverified",PAUSED:"paused"},zt={PENDING:"pending",PARTIAL:"partial",VERIFIED:"verified"},N={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};Kt={FREE:"free",PRO:"pro",TEAM:"team",SCALE:"scale",SPONSORED:"sponsored"},m={DEPLOYMENTS:"/deployments",DEPLOYMENT:e=>`/deployments/${e}`,DEPLOYMENT_CONFIG:e=>`/deployments/${e}/config`,DOMAINS:"/domains",DOMAIN:e=>`/domains/${e}`,DOMAIN_VERIFY:e=>`/domains/${e}/verify`,DOMAIN_DNS:e=>`/domains/${e}/dns`,DOMAIN_RECORDS:e=>`/domains/${e}/records`,DOMAIN_SHARE:e=>`/domains/${e}/share`,DOMAIN_PROPAGATION:e=>`/domains/${e}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:e=>`/tokens/${e}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PLANS:"/plans",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},E={FILES:"files[]",CHECKSUMS:"checksums",LABELS:"labels",VIA:"via",PASSWORD:"password",TTL:"ttl",BUILD:"build",PRERENDER:"prerender",SPA:"spa",BUILD_COMMAND:"buildCommand",OUTPUT_DIR:"outputDir",CAPTCHA:"captcha"},qt={PATH:"path",CONTENT:"content",ENCODING:"encoding",DEFAULT_ENCODING:"utf-8",ENCODINGS:["utf-8","base64"]},d={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",Build:"build_failed",Network:"network_error",Timeout:"timeout_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},tt=new Set([d.Network,d.Timeout,d.Cancelled,d.File,d.Config]),Y={client:new Set([d.Build,d.Business,d.Cancelled,d.Config,d.File,d.Forbidden,d.NotFound,d.RateLimit,d.Validation]),network:new Set([d.Network,d.Timeout]),auth:new Set([d.Authentication])},nt=new Set(Object.values(d).filter(e=>!tt.has(e))),rt=200;s=class e extends Error{type;status;details;constructor(t,n,r,i){super(n),this.type=t,this.status=r,this.details=i,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===d.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:n}}static async fromHttpResponse(t,n){let r,i,o;try{if(t.headers.get("content-type")?.includes("application/json")){let u=await t.json();if(u&&typeof u=="object"){let p=u;typeof p.message=="string"?r=p.message:typeof p.error=="string"&&(r=p.error),i=p.details,typeof p.error=="string"&&nt.has(p.error)&&(o=p.error)}}else{let u=(await t.text()).trim();u&&!u.startsWith("<")&&u.length<=rt&&(r=u)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let a=l.trim(),u=/^\d+$/.test(a)?Number(a):Math.ceil((Date.parse(a)-Date.now())/1e3);if(Number.isFinite(u)&&u>=0){let p=i&&typeof i=="object"?i:{};p.retryAfter===void 0&&(i={...p,retryAfter:u})}}r=r||`${n||"Request"} failed with status ${t.status}`;let c=o??(t.status===401?d.Authentication:t.status===403?d.Forbidden:t.status===429?d.RateLimit:d.Api);return new e(c,r,t.status,i)}static fromFetchError(t,n){if(F(t))return t;let r=n||"Request",i=t?.name;return i==="AbortError"?e.cancelled(`${r} was cancelled`):i==="TimeoutError"?e.timeout(`${r} timed out`,{cause:t}):t instanceof Error?it(t)?e.network(`${r} failed: ${t.message}`,{cause:t}):new e(d.Api,`${r} failed: ${t.message}`):new e(d.Api,`${r} failed: Unknown error`)}static validation(t,n){return new e(d.Validation,t,400,n)}static notFound(t,n){let r=n?`${t} ${n} not found`:`${t} not found`;return new e(d.NotFound,r,404)}static forbidden(t,n){return new e(d.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(d.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(d.Authentication,t,401,n)}static business(t,n=400,r){return new e(d.Business,t,n,r)}static network(t,n){return new e(d.Network,t,void 0,n)}static timeout(t,n){return new e(d.Timeout,t,void 0,n)}static cancelled(t,n){return new e(d.Cancelled,t,void 0,n)}static file(t,n){return new e(d.File,t,void 0,n)}static config(t,n){return new e(d.Config,t,void 0,n)}static api(t,n=500,r){return new e(d.Api,t,n,r)}static maintenance(t,n){return new e(d.Maintenance,t,503,n)}static build(t,n){return new e(d.Build,t,422,n)}isClientError(){return Y.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return Y.network.has(this.type)}isAuthError(){return Y.auth.has(this.type)}isType(t){return this.type===t}};st=["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"],Xt=st.map(e=>`.${e}`).join(","),at=/[\x00-\x1f\x7f#?%\\<>"]/;Q=new Set(["node_modules","package.json"]);Yt="/auth",jt="signing-in",j={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",SYSTEM:"system"},Te={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},Ae={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},De={PREFIX:"oauth-",HEX_LENGTH:32,TOTAL_LENGTH:38},P={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},R={API_KEY:j.API_KEY,DEPLOY_TOKEN:j.TOKEN,OAUTH:j.OAUTH,OPAQUE:"opaque"};W="bearer ";Jt={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},D="ship.json",Se={rewrites:[{source:"/(.*)",destination:"/index.html"}]},U={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};v={MIN_SECONDS:1,MAX_SECONDS:365*24*60*60};ne="https://api.shipstatic.com",O={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},en="SHIP_VIA",tn="https://my.shipstatic.com/api-key",nn=4320*60;h={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};I={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},Le=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;b={COMMAND_MAX_LENGTH:200,OUTPUT_DIR_MAX_LENGTH:100,OUTPUT_DIR_PATTERN:/^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/};C={MIN_LENGTH:6,MAX_LENGTH:128}});async function Dt(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,r=2097152;for(let i=0;i<e.size;i+=r){let o=Math.min(i+r,e.size);n.append(await e.slice(i,o).arrayBuffer())}return{md5:n.end()}}async function St(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function Rt(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((r,i)=>{let o=t("md5"),l=n(e);l.on("error",c=>i(s.file(`Failed to read file for MD5: ${c.message}`,{filePath:e}))),l.on("data",c=>o.update(c)),l.on("end",()=>r({md5:o.digest("hex")}))})}async function $(e){if(e instanceof Blob)return Dt(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return St(e);if(typeof e=="string")return Rt(e);throw s.business("Invalid input for MD5 calculation")}var G=A(()=>{"use strict";f()});function Fn(e){oe=e}function Pt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function L(){return oe||Pt()}var oe,w=A(()=>{"use strict";oe=null});function Ge(e){if(!e||e.length===0)return"";let t=e.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(o=>o.split("/").filter(Boolean)),r=[],i=Math.min(...n.map(o=>o.length));for(let o=0;o<i;o++){let l=n[0][o];if(n.every(c=>c[o]===l))r.push(l);else break}return r.join("/")}function V(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var se=A(()=>{"use strict"});function Be(e,t={}){if(t.flatten===!1)return e.map(r=>({path:V(r),name:ae(r)}));let n=_t(e);return e.map(r=>{let i=V(r);if(n){let o=n.endsWith("/")?n:`${n}/`;i.startsWith(o)&&(i=i.substring(o.length))}return i||(i=ae(r)),{path:i,name:ae(r)}})}function _t(e){if(!e.length)return"";let n=e.map(o=>V(o)).map(o=>o.split("/")),r=[],i=Math.min(...n.map(o=>o.length));for(let o=0;o<i-1;o++){let l=n[0][o];if(n.every(c=>c[o]===l))r.push(l);else break}return r.join("/")}function ae(e){return e.split(/[/\\]/).pop()||e}var le=A(()=>{"use strict";se()});function K(e,t){return xt.find(n=>n.broken(e,t))}var xt,ce=A(()=>{"use strict";f();ue();xt=[{name:"name",broken:({path:e})=>!pe(e).valid,sentence:({path:e})=>pe(e).reason??"Invalid file name"},{name:"extension",broken:({path:e},t)=>Ee(e,t.blockedExtensions??[]),sentence:({path:e})=>`File extension not allowed: "${e}"`},{name:"fileSize",broken:({size:e},t)=>e>t.maxFileSize,sentence:({path:e},t)=>`File "${e}" too large. Maximum ${_(t.maxFileSize)} allowed`},{name:"totalSize",broken:({totalSize:e},t)=>e>t.maxTotalSize,sentence:({totalSize:e},t)=>`Total upload size too large. ${_(e)} exceeds maximum of ${_(t.maxTotalSize)}`}]});function pe(e){if(ge(e))return{valid:!1,reason:"File name contains unsafe characters"};if(e.startsWith(" ")||e.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(e.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=e.split("/").pop()||e;return t.test(n)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function er(e,t){let n=[],r=[],i=[];if(e.length===0){let a={file:"(no files)",message:"At least one file must be provided"};return n.push(a),{files:[],validFiles:[],errors:n,warnings:[],canDeploy:!1}}for(let a of e)if(M(a.name))return n.push({file:a.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:e.map(u=>({...u,status:h.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:n,warnings:[],canDeploy:!1};if(e.length>t.maxFilesCount){let a={file:`(${e.length} files)`,message:`File count (${e.length}) exceeds limit of ${t.maxFilesCount}`};return n.push(a),{files:e.map(u=>({...u,status:h.VALIDATION_FAILED,statusMessage:a.message})),validFiles:[],errors:n,warnings:[],canDeploy:!1}}let o=0;for(let a of e){let u=h.READY,p="Ready for upload";if(a.status===h.PROCESSING_ERROR)u=h.VALIDATION_FAILED,p=a.statusMessage||"File failed during processing",n.push({file:a.name,message:p});else if(a.size===0){u=h.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",r.push({file:a.name,message:p}),i.push({...a,status:u,statusMessage:p});continue}else if(a.size<0)u=h.VALIDATION_FAILED,p="File size must be positive",n.push({file:a.name,message:p});else if(!a.name||a.name.trim().length===0)u=h.VALIDATION_FAILED,p="File name cannot be empty",n.push({file:a.name||"(empty)",message:p});else if(a.name.includes("\0"))u=h.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",n.push({file:a.name,message:p});else{let y={path:a.name,size:a.size,totalSize:o+a.size},S=K(y,t);S?(u=h.VALIDATION_FAILED,p=S.sentence(y,t),n.push({file:S.name==="totalSize"?`(${e.length} files)`:a.name,message:p})):o=y.totalSize}i.push({...a,status:u,statusMessage:p})}n.length>0&&(i=i.map(a=>a.status===h.EXCLUDED?a:{...a,status:h.VALIDATION_FAILED,statusMessage:a.status===h.VALIDATION_FAILED?a.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=n.length===0?i.filter(a=>a.status===h.READY):[],c=n.length===0;return{files:i,validFiles:l,errors:n,warnings:r,canDeploy:c}}function wt(e){return e.filter(t=>t.status===h.READY)}function tr(e){return wt(e).length>0}var ue=A(()=>{"use strict";f();ce();f()});import{isJunk as vt}from"junk";function ze(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(r=>r&&M(r)))throw s.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(n=>{if(!n)return!1;let r=n.replace(/\\/g,"/").split("/").filter(Boolean);if(r.length===0)return!0;let i=r[r.length-1];if(vt(i))return!1;for(let l of r)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let o=r.slice(0,-1);for(let l of o)if(Ct.some(c=>l.toLowerCase()===c.toLowerCase()))return!1;return!0})}var Ct,de=A(()=>{"use strict";f();Ct=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ve(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw s.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function Ke(e,t){let n=K(e,t);if(n)throw s.business(n.sentence(e,t))}var me=A(()=>{"use strict";f();ce()});async function qe(e,t={},n){let r=!!(t.build||t.prerender),i=Be(e.map(p=>p.path),{flatten:t.pathDetect!==!1}).map(p=>p.path),o=new Set(ze(i,{allowUnbuilt:r})),l=e.map((p,y)=>({source:p,deployPath:i[y]})).filter(({deployPath:p})=>o.has(p));if(l.length===0)return[];let c=r?null:Ft(n),a=[],u=0;for(let{source:p,deployPath:y}of l){if(c&&Ve(y,p.origin),p.size===0)continue;c&&(u+=p.size,Ke({path:y,size:p.size,totalSize:u},c));let S=await p.read(),{md5:q}=await $(S);a.push({path:y,content:S,size:p.size,md5:q})}if(c&&a.length>c.maxFilesCount)throw s.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return a}function Ft(e){if(!e)throw s.config("Platform limits not provided. Deploy-mode validation requires the limits argument \u2014 pass `ship.getLimits()` result.");return e}var Xe=A(()=>{"use strict";f();le();de();G();me()});var We={};Ze(We,{processFilesForNode:()=>je});import*as T from"fs";import*as g from"path";function Ye(e,t=new Set){let n=[],r=T.realpathSync(e);if(t.has(r))return n;t.add(r);for(let i of T.readdirSync(e)){let o=g.join(e,i),l=T.statSync(o);l.isDirectory()?n.push(...Ye(o,t)):l.isFile()&&n.push({absPath:o,size:l.size})}return n}async function Mt(e){try{return T.readFileSync(e)}catch(t){let n=t instanceof Error?t.message:String(t);throw s.file(`Failed to read file "${e}": ${n}`,{filePath:e})}}function Ut(e){for(let t of e){let n=g.resolve(t);try{if(T.statSync(n).isDirectory()){let r=T.readdirSync(n).find(i=>Q.has(i));if(r)throw s.business(`"${r}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(r){if(F(r))throw r}}}async function je(e,t={},n){if(L()!=="node")throw s.business("processFilesForNode can only be called in Node.js environment.");Ut(e);let r=e.flatMap(c=>{let a=g.resolve(c);try{let u=T.statSync(a);return u.isDirectory()?Ye(a):[{absPath:a,size:u.size}]}catch{throw s.file(`Path does not exist: ${c}`,{filePath:c})}}),i=new Map(r.map(c=>[c.absPath,c.size])),o=Ge(e.map(c=>g.resolve(c)).map(c=>{try{return T.statSync(c).isDirectory()?c:g.dirname(c)}catch{return g.dirname(c)}})),l=[...i].map(([c,a])=>({path:kt(c,o),origin:c,size:a,read:()=>Mt(c)}));return qe(l,t,n)}function kt(e,t){if(t&&t.length>0){let n=g.relative(t,e);if(n&&typeof n=="string"&&!n.startsWith(".."))return n.replace(/\\/g,"/")}return g.basename(e)}var fe=A(()=>{"use strict";f();Xe();w();se()});f();f();f();var k=class{constructor(){this.handlers=new Map}on(t,n){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(n)}off(t,n){let r=this.handlers.get(t);r&&(r.delete(n),r.size===0&&this.handlers.delete(t))}emit(t,...n){let r=this.handlers.get(t);if(!r)return;let i=Array.from(r);for(let o of i)try{o(...n)}catch(l){r.delete(o),t!=="error"&&setTimeout(()=>{let c=l instanceof Error?l:new Error(String(l));this.emit("error",c,String(t))},0)}}};var mt=3e4,ft=2,ht=300,yt=2e3,Et=new Set([500,502,503,504]);function gt(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let i=()=>{clearTimeout(l),t?.removeEventListener("abort",o)},o=()=>{i(),r(t?.reason)},l=setTimeout(()=>{i(),n()},e);t?.addEventListener("abort",o)})}var Oe=3e5,Tt=3e5,At=Oe+Tt,H=class extends k{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||ne,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??mt,this.maxRetries=Math.max(0,n.maxRetries??ft),this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.deploy={endpoint:n.deployEndpoint||m.DEPLOYMENTS,timeout:n.timeout??Oe,buildTimeout:n.timeout??At}}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,r,i,o=this.timeout){for(let l=0;;l++)try{return await this.attemptOnce(n,r,i,o)}catch(c){let a=s.fromFetchError(c,i);if(l>=this.maxRetries||!this.isRetryable(a,r))throw this.emit("error",a,n),a;this.emit("retry",a,n,l+1);let u=Math.min(yt,ht*2**l);try{await gt(Math.random()*u,r.signal)}catch(p){let y=s.fromFetchError(p,i);throw this.emit("error",y,n),y}}}isRetryable(n,r){if(r.signal?.aborted||n.isType(d.Maintenance)||n.isType(d.Cancelled)||!(n.isNetworkError()||n.status!==void 0&&Et.has(n.status)))return!1;let o=(r.method??"GET").toUpperCase();return o==="GET"||o==="HEAD"?!0:o==="PUT"||o==="DELETE"?!1:this.hasIdempotencyKey(r.headers)}hasIdempotencyKey(n){if(!n)return!1;let r=N.HEADER.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===r)}async attemptOnce(n,r,i,o=this.timeout){let l=()=>{};try{let c=await this.mergeHeaders(r.headers),a=this.createTimeoutSignal(r.signal,o);l=a.cleanup;let u={...r,headers:c,credentials:this.session&&!c.Authorization?"include":void 0,signal:a.signal};this.emit("request",n,u);let p=await this.fetch(n,u);if(l(),!p.ok)throw await s.fromHttpResponse(p,i);return this.emit("response",this.safeClone(p),n),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(c){throw l(),s.fromFetchError(c,i)}}async request(n,r,i,o){let{data:l}=await this.executeRequest(`${this.apiUrl}${n}`,r,i,o);return l}async requestWithStatus(n,r,i){return this.executeRequest(`${this.apiUrl}${n}`,r,i)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{[P.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n,r=this.timeout){let i=new AbortController,o=setTimeout(()=>i.abort(new DOMException(`Timed out after ${r}ms`,"TimeoutError")),r),l=n?()=>i.abort(n.reason):void 0;return n&&l&&(n.addEventListener("abort",l),n.aborted&&i.abort(n.reason)),{signal:i.signal,cleanup:()=>{clearTimeout(o),n&&l&&n.removeEventListener("abort",l)}}}safeClone(n){try{return n.clone()}catch{return n}}async parseResponse(n){if(!(n.headers.get("Content-Length")==="0"||n.status===204))return n.json()}};f();f();async function _e(e,t={}){let{labels:n,via:r,password:i,ttl:o,flags:l,captcha:c}=t,a=new FormData,u=[];for(let p of e){if(typeof p.content=="string"||p.content===null||p.content===void 0)throw s.file(`Unsupported file.content type: ${p.path}`,{filePath:p.path});if(!p.md5)throw s.file(`File missing md5 checksum: ${p.path}`,{filePath:p.path});a.append(E.FILES,new File([p.content],p.path,{type:"application/octet-stream"})),u.push(p.md5)}return a.append(E.CHECKSUMS,JSON.stringify(u)),n&&n.length>0&&a.append(E.LABELS,JSON.stringify(n)),r&&a.append(E.VIA,r),i&&a.append(E.PASSWORD,i),o!==void 0&&a.append(E.TTL,String(o)),l?.build&&a.append(E.BUILD,"true"),l?.prerender&&a.append(E.PRERENDER,"true"),l?.spa&&a.append(E.SPA,"true"),l?.buildCommand&&a.append(E.BUILD_COMMAND,l.buildCommand),l?.outputDir&&a.append(E.OUTPUT_DIR,l.outputDir),c&&a.append(E.CAPTCHA,c),a}f();G();async function It(){let e=JSON.stringify(Se,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await $(t);return{path:D,content:t,size:e.length,md5:n}}async function Nt(e,t){let n=e.find(l=>l.path===U.INDEX_FILE||l.path===`/${U.INDEX_FILE}`);if(!n||n.size>U.MAX_INDEX_BYTES)return!1;let r;if(typeof Buffer<"u"&&Buffer.isBuffer(n.content))r=n.content.toString("utf-8");else if(typeof Blob<"u"&&n.content instanceof Blob)r=await n.content.text();else if(typeof File<"u"&&n.content instanceof File)r=await n.content.text();else return!1;let i={files:e.map(l=>l.path),index:r};return(await t.request(m.SPA_CHECK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA check")).isSPA}async function xe(e,t,n){if(n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(r=>r.path===D))return e;try{if(await Nt(e,t)){let i=await It();return[...e,i]}}catch{}return e}f();f();function x(e){if(e==null)return;if(e.length===0)return e;if(e.length>I.MAX_COUNT)throw s.validation(`Maximum ${I.MAX_COUNT} labels allowed`);let t=e.map((r,i)=>{if(typeof r!="string")throw s.validation(`Label at index ${i} must be a string`);let o=r.trim().toLowerCase();if(o.length<I.MIN_LENGTH)throw s.validation(`Labels must be at least ${I.MIN_LENGTH} characters long`);if(o.length>I.MAX_LENGTH)throw s.validation(`Labels must be no more than ${I.MAX_LENGTH} characters long`);if(!Le.test(o))throw s.validation(`Labels must start and end with alphanumeric characters, with optional separators (${I.SEPARATORS}) between segments`);return o}),n=[...new Set(t)];if(n.length!==t.length)throw s.validation("Duplicate labels are not allowed");return n}async function we(e){let t=e.find(i=>i.path===D||i.path===`/${D}`);if(!t)return;let n=t.content,r=typeof n.text=="function"?await n.text():t.content.toString("utf8");Re(r)}var B={"Content-Type":"application/json"},Lt="sdk";function ie(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor!==void 0&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}function ve(e){let{getApi:t,processInput:n}=e;return{upload:async(r,i={})=>{if(!n)throw s.config("processInput function is not provided.");let o=t(),l=await n(r,i),c=await xe(l,o,i);if(!c.length)throw s.business("No files to deploy");for(let X of c)if(!X.md5)throw s.file(`MD5 checksum missing for file: ${X.path}`,{filePath:X.path});re(i.password);let a=te(i.ttl),u=ye(i.idempotencyKey),p=x(i.labels);await we(c);let y=Pe(i.buildCommand),S=be(i.outputDir),q=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa,buildCommand:y,outputDir:S}:void 0,Je=await _e(c,{labels:p,via:i.via??Lt,password:i.password,ttl:a,flags:q,captcha:i.captcha});return o.request(o.deploy.endpoint,{method:"POST",body:Je,...u?{headers:{[N.HEADER]:u}}:{},signal:i.signal||null},"Deploy",i.build||i.prerender?o.deploy.buildTimeout:o.deploy.timeout)},list:async r=>t().request(`${m.DEPLOYMENTS}${ie(r)}`,{method:"GET"},"List deployments"),get:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"GET"},"Get deployment"),set:async(r,i)=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"PATCH",headers:B,body:JSON.stringify({labels:x(i.labels)})},"Update deployment labels"),delete:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"DELETE"},"Delete deployment")}}function Ce(e){let{getApi:t}=e;return{set:async(n,r={})=>{let i=x(r.labels),o={};r.deployment&&(o.deployment=r.deployment),i!==void 0&&(o.labels=i);let{data:l,status:c}=await t().requestWithStatus(m.DOMAIN(encodeURIComponent(n)),{method:"PUT",headers:B,body:JSON.stringify(o)},"Set domain");return{...l,isCreate:c===201}},list:async n=>t().request(`${m.DOMAINS}${ie(n)}`,{method:"GET"},"List domains"),get:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"GET"},"Get domain"),delete:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"DELETE"},"Delete domain"),verify:async n=>t().request(m.DOMAIN_VERIFY(encodeURIComponent(n)),{method:"POST"},"Verify domain"),validate:async n=>t().request(m.DOMAINS_VALIDATE,{method:"POST",headers:B,body:JSON.stringify({domain:n})},"Validate domain"),dns:async n=>t().request(m.DOMAIN_DNS(encodeURIComponent(n)),{method:"GET"},"Get domain DNS"),records:async n=>t().request(m.DOMAIN_RECORDS(encodeURIComponent(n)),{method:"GET"},"Get domain records"),share:async n=>t().request(m.DOMAIN_SHARE(encodeURIComponent(n)),{method:"GET"},"Get domain share")}}function Fe(e){let{getApi:t}=e;return{get:async()=>t().request(m.ACCOUNT,{method:"GET"},"Get account")}}function Me(e){let{getApi:t}=e;return{create:async(n={})=>{let r=te(n.ttl),i=x(n.labels),o={};return r!==void 0&&(o.ttl=r),i!==void 0&&(o.labels=i),t().request(m.TOKENS,{method:"POST",headers:B,body:JSON.stringify(o)},"Create token")},list:async n=>t().request(`${m.TOKENS}${ie(n)}`,{method:"GET"},"List tokens"),get:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"GET"},"Get token"),delete:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"DELETE"},"Delete token")}}var z=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&&Ie(t.caller),t.token&&t.session)throw s.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(ee(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new H({...t,getAuthHeaders:()=>this.getAuthHeaders()});let n={getApi:()=>this.http};this.deployments=ve({...n,processInput:async(r,i)=>(await this.ensureInitialized(),this.processInput(r,i))}),this.domains=Ce(n),this.account=Fe(n),this.tokens=Me(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.request(m.LIMITS,{method:"GET"},"Get limits")}catch(t){throw this.initPromise=null,t}}async ping(){return this.http.request(m.PING,{method:"GET"},"Ping")}async deploy(t,n){return this.deployments.upload(t,n)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,n){this.http.on(t,n)}off(t,n){this.http.off(t,n)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw s.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw s.business("Invalid token provided. Token must be a non-empty string.");ee(t),this.credential=t;return}if(typeof t!="function")throw s.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 s.authentication("Token provider returned no token.");if(typeof t!="string")throw s.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};w();f();import{z as He}from"zod";import{z as Ue}from"zod";var ke={apiUrl:Ue.string().url().optional(),token:Ue.string().min(1).optional()};w();var bt=He.object(ke).strict(),Ot={apiUrl:O.API_URL,token:O.TOKEN};function $e(){if(L()!=="node")return{};let e={apiUrl:process.env[O.API_URL]||void 0,token:process.env[O.TOKEN]||void 0};try{return bt.parse(e)}catch(t){if(t instanceof He.ZodError){let n=t.issues[0],r=n.path[0],i=(r&&Ot[r])??"SHIP environment configuration";throw s.config(`Invalid ${i}: ${n.message}`)}throw s.config("Invalid environment configuration")}}f();f();le();w();ue();de();G();me();function cr(e,t,n,r=!0){let i=e===1?t:n;return r?`${e} ${i}`:i}fe();var he=class extends z{constructor(t={}){if(L()!=="node")throw s.business("Node.js Ship class can only be used in Node.js environment.");let n=$e();super({...t,apiUrl:t.apiUrl||n.apiUrl,token:t.token||(t.session?void 0:n.token)})}async deploy(t,n){return super.deploy(t,n)}async processInput(t,n){let r=typeof t=="string"?[t]:t;if(!Array.isArray(r)||!r.every(o=>typeof o=="string"))throw s.business("Invalid input type for Node.js environment. Expected string or string[].");if(r.length===0)throw s.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(fe(),We));return i(r,n,this.platformLimits??void 0)}},Ht=he;export{Te as API_KEY,m as API_PATHS,Yt as AUTH_BASE_PATH,Kt as AccountPlan,H as ApiHttp,j as AuthMethod,b as BUILD_SETTINGS,P as CALLER,ne as DEFAULT_API,D as DEPLOYMENT_CONFIG_FILENAME,E as DEPLOY_FIELDS,qt as DEPLOY_FILE_GRAMMAR,Ae as DEPLOY_TOKEN,Gt as DeploymentStatus,et as DeploymentVia,Bt as DomainStatus,zt as DomainVerification,d as ErrorType,h as FILE_VALIDATION_STATUS,h as FileValidationStatus,N as IDEMPOTENCY_KEY_CONSTRAINTS,Ct as JUNK_DIRECTORIES,I as LABEL_CONSTRAINTS,Le as LABEL_PATTERN,tn as MY_API_KEY_URL,De as OAUTH_TOKEN,Jt as OAuthScope,C as PASSWORD_CONSTRAINTS,nn as PUBLIC_DEPLOYMENT_TTL_SECONDS,O as SHIP_ENV,en as SHIP_VIA_ENV,jt as SIGN_IN_RETURN_PARAM,U as SPA_CHECK_CONSTRAINTS,Se as SPA_DEFAULT_CONFIG,he as Ship,s as ShipError,v as TTL_CONSTRAINTS,R as TokenKind,Q as UNBUILT_PROJECT_MARKERS,at as UNSAFE_FILENAME_CHARS,Xt as WEB_FILE_ACCEPT,Fn as __setTestEnvironment,tr as allValidFilesReady,Re as assertShipJsonSyntax,$ as calculateMD5,lt as classifyToken,Fe as createAccountResource,ve as createDeploymentResource,Ce as createDomainResource,Me as createTokenResource,Ht as default,cn as deserializeLabels,sn as extractSubdomain,ze as filterJunk,dt as formatDuration,_ as formatFileSize,rn as formatTimeRemaining,an as generateDeploymentUrl,ln as generateDomainUrl,L as getENV,wt as getValidFiles,M as hasUnbuiltMarker,ge as hasUnsafeChars,Ee as isBlockedExtension,on as isCustomDomain,Zt as isDeployment,Ne as isPlatformDomain,F as isShipError,Vt as normalizeVia,Be as optimizeDeployPaths,cr as pluralize,je as processFilesForNode,Wt as readBearerValue,pn as serializeLabels,pt as validateApiKey,Qt as validateApiUrl,Pe as validateBuildCommand,Ie as validateCaller,Ke as validateDeployFile,Ve as validateDeployPath,ct as validateDeployToken,pe as validateFileName,er as validateFiles,ye as validateIdempotencyKey,ut as validateOAuthToken,be as validateOutputDir,re as validatePassword,ee as validateToken,te as validateTtl};
1
+ var Qe=Object.defineProperty;var A=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ze=(e,t)=>{for(var n in t)Qe(e,n,{get:t[n],enumerable:!0})};function Vt(e){if(!e||typeof e!="string")return;let t=e.trim().toLowerCase();return Object.values(et).includes(t)?t:void 0}function ye(e){if(e==null)return;if(typeof e!="string")throw s.validation("Idempotency key must be a string.");let t=e.trim();if(!t)throw s.validation("Idempotency key must not be empty.");if(t.length>N.MAX_LENGTH)throw s.validation(`Idempotency key must be at most ${N.MAX_LENGTH} characters.`);return t}function it(e){let t=e.code;return t==="ERR_INVALID_URL"?!1:typeof t=="string"?!0:e instanceof TypeError?!/\burl\b/i.test(e.message):!1}function F(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function ot(e){let t=e.replace(/\\/g,"/").split("/").pop()??"",n=t.lastIndexOf(".");return n<=0||n===t.length-1?null:t.slice(n+1).toLowerCase()}function Ee(e,t){let n=ot(e);return n===null?!1:Array.isArray(t)?t.includes(n):t.has(n)}function ge(e){return at.test(e)}function M(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>Q.has(n))}function lt(e){return e.startsWith(Te.PREFIX)?R.API_KEY:e.startsWith(Ae.PREFIX)?R.DEPLOY_TOKEN:e.startsWith(De.PREFIX)?R.OAUTH:R.OPAQUE}function Jt(e){return e.slice(0,W.length).toLowerCase()!==W?null:e.slice(W.length)||null}function Re(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(r){throw s.config(`invalid JSON format in config: ${r.message}`,{filePath:D})}if(n===null||typeof n!="object"||Array.isArray(n))throw s.config(`${D} must contain a JSON object`,{filePath:D})}function Z(e,t,n){if(!e.startsWith(t.PREFIX))throw s.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw s.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let r=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(r))throw s.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function pt(e){Z(e,Te,"API key")}function ct(e){Z(e,Ae,"Deploy token")}function ut(e){Z(e,De,"OAuth access token")}function ee(e){switch(lt(e)){case R.API_KEY:pt(e);return;case R.DEPLOY_TOKEN:ct(e);return;case R.OAUTH:ut(e);return;case R.OPAQUE:if(!e)throw s.validation("Token must be a non-empty string")}}function Ie(e){if(!e||e.length>P.MAX_LENGTH||!P.PATTERN.test(e))throw s.validation(`Caller must be 1-${P.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function Zt(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw s.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw s.validation("API URL must not contain a path");if(t.search||t.hash)throw s.validation("API URL must not contain query parameters or fragments")}catch(t){throw F(t)?t:s.validation("API URL must be a valid URL")}}function en(e){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(e)}function te(e){if(e!=null){if(typeof e!="number"||!Number.isFinite(e))throw s.validation("TTL must be a number of seconds");if(!Number.isInteger(e))throw s.validation("TTL must be a whole number of seconds");if(e<C.MIN_SECONDS||e>C.MAX_SECONDS)throw s.validation(`TTL must be between ${C.MIN_SECONDS} and ${C.MAX_SECONDS} seconds`);return e}}function dt(e){let t=Math.round(e/60);if(!(t>=1))return"less than a minute";if(t<120)return J(t,"minute");let n=Math.round(e/3600);return n<48?J(n,"hour"):J(Math.round(e/86400),"day")}function on(e,t=Date.now()/1e3){let n=e-t;return n>0?dt(n):null}function J(e,t){return`${e} ${t}${e===1?"":"s"}`}function _(e,t=1){if(e===0)return"0 Bytes";let n=1024,r=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(n));return`${Number.parseFloat((e/n**i).toFixed(t))} ${r[i]}`}function Ne(e,t){return e.endsWith(`.${t}`)}function sn(e,t){return!Ne(e,t)}function an(e,t){return Ne(e,t)?e.slice(0,-(t.length+1)):null}function ln(e){return`https://${e}`}function pn(e){return`https://${e}`}function cn(e){return!e||e.length===0?null:JSON.stringify(e)}function un(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Pe(e){if(e==null||e==="")return;if(typeof e!="string")throw s.validation("Build command must be a string");let t=e.trim();if(t.length===0||t.length>b.COMMAND_MAX_LENGTH)throw s.validation(`Build command must be between 1 and ${b.COMMAND_MAX_LENGTH} characters`);if(/[\x00-\x1f\x7f]/.test(t))throw s.validation("Build command must be a single line");return t}function be(e){if(e==null||e==="")return;if(typeof e!="string")throw s.validation("Output folder must be a string");let t=e.trim().replace(/\/+$/,"");if(t.length===0||t.length>b.OUTPUT_DIR_MAX_LENGTH)throw s.validation(`Output folder must be between 1 and ${b.OUTPUT_DIR_MAX_LENGTH} characters`);if(!b.OUTPUT_DIR_PATTERN.test(t)||t.split("/").some(n=>n===".."||n==="."))throw s.validation("Output folder must be a relative path inside the project, like dist or dist/site");return t}function re(e){if(e==null)return;if(typeof e!="string")throw s.validation("Password must be a string");let t=e.trim();if(t.length<v.MIN_LENGTH||t.length>v.MAX_LENGTH)throw s.validation(`Password must be between ${v.MIN_LENGTH} and ${v.MAX_LENGTH} characters`);return t}var Gt,et,Bt,zt,N,Kt,m,E,qt,d,tt,Y,nt,rt,s,st,Xt,at,Q,Yt,jt,j,Te,Ae,De,P,Wt,R,W,Qt,D,Se,U,C,ne,O,tn,nn,rn,h,I,Le,b,v,f=A(()=>{"use strict";Gt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},et={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc",CLD:"cld",CRS:"crs",GMN:"gmn",API:"api"},Bt={LIVE:"live",UNLINKED:"unlinked",UNVERIFIED:"unverified",PAUSED:"paused"},zt={PENDING:"pending",PARTIAL:"partial",VERIFIED:"verified"},N={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};Kt={FREE:"free",PRO:"pro",TEAM:"team",SCALE:"scale",SPONSORED:"sponsored"},m={DEPLOYMENTS:"/deployments",DEPLOYMENT:e=>`/deployments/${e}`,DEPLOYMENT_CONFIG:e=>`/deployments/${e}/config`,DOMAINS:"/domains",DOMAIN:e=>`/domains/${e}`,DOMAIN_VERIFY:e=>`/domains/${e}/verify`,DOMAIN_DNS:e=>`/domains/${e}/dns`,DOMAIN_RECORDS:e=>`/domains/${e}/records`,DOMAIN_SHARE:e=>`/domains/${e}/share`,DOMAIN_PROPAGATION:e=>`/domains/${e}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:e=>`/tokens/${e}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PLANS:"/plans",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},E={FILES:"files[]",CHECKSUMS:"checksums",LABELS:"labels",VIA:"via",PASSWORD:"password",TTL:"ttl",BUILD:"build",PRERENDER:"prerender",SPA:"spa",BUILD_COMMAND:"buildCommand",OUTPUT_DIR:"outputDir",CAPTCHA:"captcha"},qt={PATH:"path",CONTENT:"content",ENCODING:"encoding",DEFAULT_ENCODING:"utf-8",ENCODINGS:["utf-8","base64"]},d={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",Build:"build_failed",Network:"network_error",Timeout:"timeout_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},tt=new Set([d.Network,d.Timeout,d.Cancelled,d.File,d.Config]),Y={client:new Set([d.Build,d.Business,d.Cancelled,d.Config,d.File,d.Forbidden,d.NotFound,d.RateLimit,d.Validation]),network:new Set([d.Network,d.Timeout]),auth:new Set([d.Authentication])},nt=new Set(Object.values(d).filter(e=>!tt.has(e))),rt=200;s=class e extends Error{type;status;details;constructor(t,n,r,i){super(n),this.type=t,this.status=r,this.details=i,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===d.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:n}}static async fromHttpResponse(t,n){let r,i,o;try{if(t.headers.get("content-type")?.includes("application/json")){let u=await t.json();if(u&&typeof u=="object"){let p=u;typeof p.message=="string"?r=p.message:typeof p.error=="string"&&(r=p.error),i=p.details,typeof p.error=="string"&&nt.has(p.error)&&(o=p.error)}}else{let u=(await t.text()).trim();u&&!u.startsWith("<")&&u.length<=rt&&(r=u)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let a=l.trim(),u=/^\d+$/.test(a)?Number(a):Math.ceil((Date.parse(a)-Date.now())/1e3);if(Number.isFinite(u)&&u>=0){let p=i&&typeof i=="object"?i:{};p.retryAfter===void 0&&(i={...p,retryAfter:u})}}r=r||`${n||"Request"} failed with status ${t.status}`;let c=o??(t.status===401?d.Authentication:t.status===403?d.Forbidden:t.status===429?d.RateLimit:d.Api);return new e(c,r,t.status,i)}static fromFetchError(t,n){if(F(t))return t;let r=n||"Request",i=t?.name;return i==="AbortError"?e.cancelled(`${r} was cancelled`):i==="TimeoutError"?e.timeout(`${r} timed out`,{cause:t}):t instanceof Error?it(t)?e.network(`${r} failed: ${t.message}`,{cause:t}):new e(d.Api,`${r} failed: ${t.message}`):new e(d.Api,`${r} failed: Unknown error`)}static validation(t,n){return new e(d.Validation,t,400,n)}static notFound(t,n){let r=n?`${t} ${n} not found`:`${t} not found`;return new e(d.NotFound,r,404)}static forbidden(t,n){return new e(d.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(d.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(d.Authentication,t,401,n)}static business(t,n=400,r){return new e(d.Business,t,n,r)}static network(t,n){return new e(d.Network,t,void 0,n)}static timeout(t,n){return new e(d.Timeout,t,void 0,n)}static cancelled(t,n){return new e(d.Cancelled,t,void 0,n)}static file(t,n){return new e(d.File,t,void 0,n)}static config(t,n){return new e(d.Config,t,void 0,n)}static api(t,n=500,r){return new e(d.Api,t,n,r)}static maintenance(t,n){return new e(d.Maintenance,t,503,n)}static build(t,n){return new e(d.Build,t,422,n)}isClientError(){return Y.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return Y.network.has(this.type)}isAuthError(){return Y.auth.has(this.type)}isType(t){return this.type===t}};st=["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"],Xt=st.map(e=>`.${e}`).join(","),at=/[\x00-\x1f\x7f#?%\\<>"]/;Q=new Set(["node_modules","package.json"]);Yt="/auth",jt="signing-in",j={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",SYSTEM:"system"},Te={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},Ae={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},De={PREFIX:"oauth-",HEX_LENGTH:32,TOTAL_LENGTH:38},P={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},Wt="X-Account",R={API_KEY:j.API_KEY,DEPLOY_TOKEN:j.TOKEN,OAUTH:j.OAUTH,OPAQUE:"opaque"};W="bearer ";Qt={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},D="ship.json",Se={rewrites:[{source:"/(.*)",destination:"/index.html"}]},U={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};C={MIN_SECONDS:1,MAX_SECONDS:365*24*60*60};ne="https://api.shipstatic.com",O={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},tn="SHIP_VIA",nn="https://my.shipstatic.com/api-key",rn=4320*60;h={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};I={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},Le=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;b={COMMAND_MAX_LENGTH:200,OUTPUT_DIR_MAX_LENGTH:100,OUTPUT_DIR_PATTERN:/^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/};v={MIN_LENGTH:6,MAX_LENGTH:128}});async function Dt(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,r=2097152;for(let i=0;i<e.size;i+=r){let o=Math.min(i+r,e.size);n.append(await e.slice(i,o).arrayBuffer())}return{md5:n.end()}}async function St(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function Rt(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((r,i)=>{let o=t("md5"),l=n(e);l.on("error",c=>i(s.file(`Failed to read file for MD5: ${c.message}`,{filePath:e}))),l.on("data",c=>o.update(c)),l.on("end",()=>r({md5:o.digest("hex")}))})}async function $(e){if(e instanceof Blob)return Dt(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return St(e);if(typeof e=="string")return Rt(e);throw s.business("Invalid input for MD5 calculation")}var G=A(()=>{"use strict";f()});function Mn(e){oe=e}function Pt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function L(){return oe||Pt()}var oe,w=A(()=>{"use strict";oe=null});function Ge(e){if(!e||e.length===0)return"";let t=e.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(o=>o.split("/").filter(Boolean)),r=[],i=Math.min(...n.map(o=>o.length));for(let o=0;o<i;o++){let l=n[0][o];if(n.every(c=>c[o]===l))r.push(l);else break}return r.join("/")}function V(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var se=A(()=>{"use strict"});function Be(e,t={}){if(t.flatten===!1)return e.map(r=>({path:V(r),name:ae(r)}));let n=_t(e);return e.map(r=>{let i=V(r);if(n){let o=n.endsWith("/")?n:`${n}/`;i.startsWith(o)&&(i=i.substring(o.length))}return i||(i=ae(r)),{path:i,name:ae(r)}})}function _t(e){if(!e.length)return"";let n=e.map(o=>V(o)).map(o=>o.split("/")),r=[],i=Math.min(...n.map(o=>o.length));for(let o=0;o<i-1;o++){let l=n[0][o];if(n.every(c=>c[o]===l))r.push(l);else break}return r.join("/")}function ae(e){return e.split(/[/\\]/).pop()||e}var le=A(()=>{"use strict";se()});function K(e,t){return xt.find(n=>n.broken(e,t))}var xt,ce=A(()=>{"use strict";f();ue();xt=[{name:"name",broken:({path:e})=>!pe(e).valid,sentence:({path:e})=>pe(e).reason??"Invalid file name"},{name:"extension",broken:({path:e},t)=>Ee(e,t.blockedExtensions??[]),sentence:({path:e})=>`File extension not allowed: "${e}"`},{name:"fileSize",broken:({size:e},t)=>e>t.maxFileSize,sentence:({path:e},t)=>`File "${e}" too large. Maximum ${_(t.maxFileSize)} allowed`},{name:"totalSize",broken:({totalSize:e},t)=>e>t.maxTotalSize,sentence:({totalSize:e},t)=>`Total upload size too large. ${_(e)} exceeds maximum of ${_(t.maxTotalSize)}`}]});function pe(e){if(ge(e))return{valid:!1,reason:"File name contains unsafe characters"};if(e.startsWith(" ")||e.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(e.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=e.split("/").pop()||e;return t.test(n)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function tr(e,t){let n=[],r=[],i=[];if(e.length===0){let a={file:"(no files)",message:"At least one file must be provided"};return n.push(a),{files:[],validFiles:[],errors:n,warnings:[],canDeploy:!1}}for(let a of e)if(M(a.name))return n.push({file:a.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:e.map(u=>({...u,status:h.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:n,warnings:[],canDeploy:!1};if(e.length>t.maxFilesCount){let a={file:`(${e.length} files)`,message:`File count (${e.length}) exceeds limit of ${t.maxFilesCount}`};return n.push(a),{files:e.map(u=>({...u,status:h.VALIDATION_FAILED,statusMessage:a.message})),validFiles:[],errors:n,warnings:[],canDeploy:!1}}let o=0;for(let a of e){let u=h.READY,p="Ready for upload";if(a.status===h.PROCESSING_ERROR)u=h.VALIDATION_FAILED,p=a.statusMessage||"File failed during processing",n.push({file:a.name,message:p});else if(a.size===0){u=h.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",r.push({file:a.name,message:p}),i.push({...a,status:u,statusMessage:p});continue}else if(a.size<0)u=h.VALIDATION_FAILED,p="File size must be positive",n.push({file:a.name,message:p});else if(!a.name||a.name.trim().length===0)u=h.VALIDATION_FAILED,p="File name cannot be empty",n.push({file:a.name||"(empty)",message:p});else if(a.name.includes("\0"))u=h.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",n.push({file:a.name,message:p});else{let y={path:a.name,size:a.size,totalSize:o+a.size},S=K(y,t);S?(u=h.VALIDATION_FAILED,p=S.sentence(y,t),n.push({file:S.name==="totalSize"?`(${e.length} files)`:a.name,message:p})):o=y.totalSize}i.push({...a,status:u,statusMessage:p})}n.length>0&&(i=i.map(a=>a.status===h.EXCLUDED?a:{...a,status:h.VALIDATION_FAILED,statusMessage:a.status===h.VALIDATION_FAILED?a.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=n.length===0?i.filter(a=>a.status===h.READY):[],c=n.length===0;return{files:i,validFiles:l,errors:n,warnings:r,canDeploy:c}}function wt(e){return e.filter(t=>t.status===h.READY)}function nr(e){return wt(e).length>0}var ue=A(()=>{"use strict";f();ce();f()});import{isJunk as Ct}from"junk";function ze(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(r=>r&&M(r)))throw s.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(n=>{if(!n)return!1;let r=n.replace(/\\/g,"/").split("/").filter(Boolean);if(r.length===0)return!0;let i=r[r.length-1];if(Ct(i))return!1;for(let l of r)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let o=r.slice(0,-1);for(let l of o)if(vt.some(c=>l.toLowerCase()===c.toLowerCase()))return!1;return!0})}var vt,de=A(()=>{"use strict";f();vt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ve(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw s.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function Ke(e,t){let n=K(e,t);if(n)throw s.business(n.sentence(e,t))}var me=A(()=>{"use strict";f();ce()});async function qe(e,t={},n){let r=!!(t.build||t.prerender),i=Be(e.map(p=>p.path),{flatten:t.pathDetect!==!1}).map(p=>p.path),o=new Set(ze(i,{allowUnbuilt:r})),l=e.map((p,y)=>({source:p,deployPath:i[y]})).filter(({deployPath:p})=>o.has(p));if(l.length===0)return[];let c=r?null:Ft(n),a=[],u=0;for(let{source:p,deployPath:y}of l){if(c&&Ve(y,p.origin),p.size===0)continue;c&&(u+=p.size,Ke({path:y,size:p.size,totalSize:u},c));let S=await p.read(),{md5:q}=await $(S);a.push({path:y,content:S,size:p.size,md5:q})}if(c&&a.length>c.maxFilesCount)throw s.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return a}function Ft(e){if(!e)throw s.config("Platform limits not provided. Deploy-mode validation requires the limits argument \u2014 pass `ship.getLimits()` result.");return e}var Xe=A(()=>{"use strict";f();le();de();G();me()});var We={};Ze(We,{processFilesForNode:()=>je});import*as T from"fs";import*as g from"path";function Ye(e,t=new Set){let n=[],r=T.realpathSync(e);if(t.has(r))return n;t.add(r);for(let i of T.readdirSync(e)){let o=g.join(e,i),l=T.statSync(o);l.isDirectory()?n.push(...Ye(o,t)):l.isFile()&&n.push({absPath:o,size:l.size})}return n}async function Mt(e){try{return T.readFileSync(e)}catch(t){let n=t instanceof Error?t.message:String(t);throw s.file(`Failed to read file "${e}": ${n}`,{filePath:e})}}function Ut(e){for(let t of e){let n=g.resolve(t);try{if(T.statSync(n).isDirectory()){let r=T.readdirSync(n).find(i=>Q.has(i));if(r)throw s.business(`"${r}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(r){if(F(r))throw r}}}async function je(e,t={},n){if(L()!=="node")throw s.business("processFilesForNode can only be called in Node.js environment.");Ut(e);let r=e.flatMap(c=>{let a=g.resolve(c);try{let u=T.statSync(a);return u.isDirectory()?Ye(a):[{absPath:a,size:u.size}]}catch{throw s.file(`Path does not exist: ${c}`,{filePath:c})}}),i=new Map(r.map(c=>[c.absPath,c.size])),o=Ge(e.map(c=>g.resolve(c)).map(c=>{try{return T.statSync(c).isDirectory()?c:g.dirname(c)}catch{return g.dirname(c)}})),l=[...i].map(([c,a])=>({path:kt(c,o),origin:c,size:a,read:()=>Mt(c)}));return qe(l,t,n)}function kt(e,t){if(t&&t.length>0){let n=g.relative(t,e);if(n&&typeof n=="string"&&!n.startsWith(".."))return n.replace(/\\/g,"/")}return g.basename(e)}var fe=A(()=>{"use strict";f();Xe();w();se()});f();f();f();var k=class{constructor(){this.handlers=new Map}on(t,n){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(n)}off(t,n){let r=this.handlers.get(t);r&&(r.delete(n),r.size===0&&this.handlers.delete(t))}emit(t,...n){let r=this.handlers.get(t);if(!r)return;let i=Array.from(r);for(let o of i)try{o(...n)}catch(l){r.delete(o),t!=="error"&&setTimeout(()=>{let c=l instanceof Error?l:new Error(String(l));this.emit("error",c,String(t))},0)}}};var mt=3e4,ft=2,ht=300,yt=2e3,Et=new Set([500,502,503,504]);function gt(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let i=()=>{clearTimeout(l),t?.removeEventListener("abort",o)},o=()=>{i(),r(t?.reason)},l=setTimeout(()=>{i(),n()},e);t?.addEventListener("abort",o)})}var Oe=3e5,Tt=3e5,At=Oe+Tt,H=class extends k{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||ne,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??mt,this.maxRetries=Math.max(0,n.maxRetries??ft),this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.deploy={endpoint:n.deployEndpoint||m.DEPLOYMENTS,timeout:n.timeout??Oe,buildTimeout:n.timeout??At}}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,r,i,o=this.timeout){for(let l=0;;l++)try{return await this.attemptOnce(n,r,i,o)}catch(c){let a=s.fromFetchError(c,i);if(l>=this.maxRetries||!this.isRetryable(a,r))throw this.emit("error",a,n),a;this.emit("retry",a,n,l+1);let u=Math.min(yt,ht*2**l);try{await gt(Math.random()*u,r.signal)}catch(p){let y=s.fromFetchError(p,i);throw this.emit("error",y,n),y}}}isRetryable(n,r){if(r.signal?.aborted||n.isType(d.Maintenance)||n.isType(d.Cancelled)||!(n.isNetworkError()||n.status!==void 0&&Et.has(n.status)))return!1;let o=(r.method??"GET").toUpperCase();return o==="GET"||o==="HEAD"?!0:o==="PUT"||o==="DELETE"?!1:this.hasIdempotencyKey(r.headers)}hasIdempotencyKey(n){if(!n)return!1;let r=N.HEADER.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===r)}async attemptOnce(n,r,i,o=this.timeout){let l=()=>{};try{let c=await this.mergeHeaders(r.headers),a=this.createTimeoutSignal(r.signal,o);l=a.cleanup;let u={...r,headers:c,credentials:this.session&&!c.Authorization?"include":void 0,signal:a.signal};this.emit("request",n,u);let p=await this.fetch(n,u);if(l(),!p.ok)throw await s.fromHttpResponse(p,i);return this.emit("response",this.safeClone(p),n),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(c){throw l(),s.fromFetchError(c,i)}}async request(n,r,i,o){let{data:l}=await this.executeRequest(`${this.apiUrl}${n}`,r,i,o);return l}async requestWithStatus(n,r,i){return this.executeRequest(`${this.apiUrl}${n}`,r,i)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{[P.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n,r=this.timeout){let i=new AbortController,o=setTimeout(()=>i.abort(new DOMException(`Timed out after ${r}ms`,"TimeoutError")),r),l=n?()=>i.abort(n.reason):void 0;return n&&l&&(n.addEventListener("abort",l),n.aborted&&i.abort(n.reason)),{signal:i.signal,cleanup:()=>{clearTimeout(o),n&&l&&n.removeEventListener("abort",l)}}}safeClone(n){try{return n.clone()}catch{return n}}async parseResponse(n){if(!(n.headers.get("Content-Length")==="0"||n.status===204))return n.json()}};f();f();async function _e(e,t={}){let{labels:n,via:r,password:i,ttl:o,flags:l,captcha:c}=t,a=new FormData,u=[];for(let p of e){if(typeof p.content=="string"||p.content===null||p.content===void 0)throw s.file(`Unsupported file.content type: ${p.path}`,{filePath:p.path});if(!p.md5)throw s.file(`File missing md5 checksum: ${p.path}`,{filePath:p.path});a.append(E.FILES,new File([p.content],p.path,{type:"application/octet-stream"})),u.push(p.md5)}return a.append(E.CHECKSUMS,JSON.stringify(u)),n&&n.length>0&&a.append(E.LABELS,JSON.stringify(n)),r&&a.append(E.VIA,r),i&&a.append(E.PASSWORD,i),o!==void 0&&a.append(E.TTL,String(o)),l?.build&&a.append(E.BUILD,"true"),l?.prerender&&a.append(E.PRERENDER,"true"),l?.spa&&a.append(E.SPA,"true"),l?.buildCommand&&a.append(E.BUILD_COMMAND,l.buildCommand),l?.outputDir&&a.append(E.OUTPUT_DIR,l.outputDir),c&&a.append(E.CAPTCHA,c),a}f();G();async function It(){let e=JSON.stringify(Se,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await $(t);return{path:D,content:t,size:e.length,md5:n}}async function Nt(e,t){let n=e.find(l=>l.path===U.INDEX_FILE||l.path===`/${U.INDEX_FILE}`);if(!n||n.size>U.MAX_INDEX_BYTES)return!1;let r;if(typeof Buffer<"u"&&Buffer.isBuffer(n.content))r=n.content.toString("utf-8");else if(typeof Blob<"u"&&n.content instanceof Blob)r=await n.content.text();else if(typeof File<"u"&&n.content instanceof File)r=await n.content.text();else return!1;let i={files:e.map(l=>l.path),index:r};return(await t.request(m.SPA_CHECK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA check")).isSPA}async function xe(e,t,n){if(n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(r=>r.path===D))return e;try{if(await Nt(e,t)){let i=await It();return[...e,i]}}catch{}return e}f();f();function x(e){if(e==null)return;if(e.length===0)return e;if(e.length>I.MAX_COUNT)throw s.validation(`Maximum ${I.MAX_COUNT} labels allowed`);let t=e.map((r,i)=>{if(typeof r!="string")throw s.validation(`Label at index ${i} must be a string`);let o=r.trim().toLowerCase();if(o.length<I.MIN_LENGTH)throw s.validation(`Labels must be at least ${I.MIN_LENGTH} characters long`);if(o.length>I.MAX_LENGTH)throw s.validation(`Labels must be no more than ${I.MAX_LENGTH} characters long`);if(!Le.test(o))throw s.validation(`Labels must start and end with alphanumeric characters, with optional separators (${I.SEPARATORS}) between segments`);return o}),n=[...new Set(t)];if(n.length!==t.length)throw s.validation("Duplicate labels are not allowed");return n}async function we(e){let t=e.find(i=>i.path===D||i.path===`/${D}`);if(!t)return;let n=t.content,r=typeof n.text=="function"?await n.text():t.content.toString("utf8");Re(r)}var B={"Content-Type":"application/json"},Lt="sdk";function ie(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor!==void 0&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}function Ce(e){let{getApi:t,processInput:n}=e;return{upload:async(r,i={})=>{if(!n)throw s.config("processInput function is not provided.");let o=t(),l=await n(r,i),c=await xe(l,o,i);if(!c.length)throw s.business("No files to deploy");for(let X of c)if(!X.md5)throw s.file(`MD5 checksum missing for file: ${X.path}`,{filePath:X.path});re(i.password);let a=te(i.ttl),u=ye(i.idempotencyKey),p=x(i.labels);await we(c);let y=Pe(i.buildCommand),S=be(i.outputDir),q=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa,buildCommand:y,outputDir:S}:void 0,Je=await _e(c,{labels:p,via:i.via??Lt,password:i.password,ttl:a,flags:q,captcha:i.captcha});return o.request(o.deploy.endpoint,{method:"POST",body:Je,...u?{headers:{[N.HEADER]:u}}:{},signal:i.signal||null},"Deploy",i.build||i.prerender?o.deploy.buildTimeout:o.deploy.timeout)},list:async r=>t().request(`${m.DEPLOYMENTS}${ie(r)}`,{method:"GET"},"List deployments"),get:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"GET"},"Get deployment"),set:async(r,i)=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"PATCH",headers:B,body:JSON.stringify({labels:x(i.labels)})},"Update deployment labels"),delete:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"DELETE"},"Delete deployment")}}function ve(e){let{getApi:t}=e;return{set:async(n,r={})=>{let i=x(r.labels),o={};r.deployment&&(o.deployment=r.deployment),i!==void 0&&(o.labels=i);let{data:l,status:c}=await t().requestWithStatus(m.DOMAIN(encodeURIComponent(n)),{method:"PUT",headers:B,body:JSON.stringify(o)},"Set domain");return{...l,isCreate:c===201}},list:async n=>t().request(`${m.DOMAINS}${ie(n)}`,{method:"GET"},"List domains"),get:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"GET"},"Get domain"),delete:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"DELETE"},"Delete domain"),verify:async n=>t().request(m.DOMAIN_VERIFY(encodeURIComponent(n)),{method:"POST"},"Verify domain"),validate:async n=>t().request(m.DOMAINS_VALIDATE,{method:"POST",headers:B,body:JSON.stringify({domain:n})},"Validate domain"),dns:async n=>t().request(m.DOMAIN_DNS(encodeURIComponent(n)),{method:"GET"},"Get domain DNS"),records:async n=>t().request(m.DOMAIN_RECORDS(encodeURIComponent(n)),{method:"GET"},"Get domain records"),share:async n=>t().request(m.DOMAIN_SHARE(encodeURIComponent(n)),{method:"GET"},"Get domain share")}}function Fe(e){let{getApi:t}=e;return{get:async()=>t().request(m.ACCOUNT,{method:"GET"},"Get account")}}function Me(e){let{getApi:t}=e;return{create:async(n={})=>{let r=te(n.ttl),i=x(n.labels),o={};return r!==void 0&&(o.ttl=r),i!==void 0&&(o.labels=i),t().request(m.TOKENS,{method:"POST",headers:B,body:JSON.stringify(o)},"Create token")},list:async n=>t().request(`${m.TOKENS}${ie(n)}`,{method:"GET"},"List tokens"),get:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"GET"},"Get token"),delete:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"DELETE"},"Delete token")}}var z=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&&Ie(t.caller),t.token&&t.session)throw s.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(ee(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new H({...t,getAuthHeaders:()=>this.getAuthHeaders()});let n={getApi:()=>this.http};this.deployments=Ce({...n,processInput:async(r,i)=>(await this.ensureInitialized(),this.processInput(r,i))}),this.domains=ve(n),this.account=Fe(n),this.tokens=Me(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.request(m.LIMITS,{method:"GET"},"Get limits")}catch(t){throw this.initPromise=null,t}}async ping(){return this.http.request(m.PING,{method:"GET"},"Ping")}async deploy(t,n){return this.deployments.upload(t,n)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,n){this.http.on(t,n)}off(t,n){this.http.off(t,n)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw s.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw s.business("Invalid token provided. Token must be a non-empty string.");ee(t),this.credential=t;return}if(typeof t!="function")throw s.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 s.authentication("Token provider returned no token.");if(typeof t!="string")throw s.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};w();f();import{z as He}from"zod";import{z as Ue}from"zod";var ke={apiUrl:Ue.string().url().optional(),token:Ue.string().min(1).optional()};w();var bt=He.object(ke).strict(),Ot={apiUrl:O.API_URL,token:O.TOKEN};function $e(){if(L()!=="node")return{};let e={apiUrl:process.env[O.API_URL]||void 0,token:process.env[O.TOKEN]||void 0};try{return bt.parse(e)}catch(t){if(t instanceof He.ZodError){let n=t.issues[0],r=n.path[0],i=(r&&Ot[r])??"SHIP environment configuration";throw s.config(`Invalid ${i}: ${n.message}`)}throw s.config("Invalid environment configuration")}}f();f();le();w();ue();de();G();me();function ur(e,t,n,r=!0){let i=e===1?t:n;return r?`${e} ${i}`:i}fe();var he=class extends z{constructor(t={}){if(L()!=="node")throw s.business("Node.js Ship class can only be used in Node.js environment.");let n=$e();super({...t,apiUrl:t.apiUrl||n.apiUrl,token:t.token||(t.session?void 0:n.token)})}async deploy(t,n){return super.deploy(t,n)}async processInput(t,n){let r=typeof t=="string"?[t]:t;if(!Array.isArray(r)||!r.every(o=>typeof o=="string"))throw s.business("Invalid input type for Node.js environment. Expected string or string[].");if(r.length===0)throw s.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(fe(),We));return i(r,n,this.platformLimits??void 0)}},Ht=he;export{Wt as ACCOUNT_HEADER,Te as API_KEY,m as API_PATHS,Yt as AUTH_BASE_PATH,Kt as AccountPlan,H as ApiHttp,j as AuthMethod,b as BUILD_SETTINGS,P as CALLER,ne as DEFAULT_API,D as DEPLOYMENT_CONFIG_FILENAME,E as DEPLOY_FIELDS,qt as DEPLOY_FILE_GRAMMAR,Ae as DEPLOY_TOKEN,Gt as DeploymentStatus,et as DeploymentVia,Bt as DomainStatus,zt as DomainVerification,d as ErrorType,h as FILE_VALIDATION_STATUS,h as FileValidationStatus,N as IDEMPOTENCY_KEY_CONSTRAINTS,vt as JUNK_DIRECTORIES,I as LABEL_CONSTRAINTS,Le as LABEL_PATTERN,nn as MY_API_KEY_URL,De as OAUTH_TOKEN,Qt as OAuthScope,v as PASSWORD_CONSTRAINTS,rn as PUBLIC_DEPLOYMENT_TTL_SECONDS,O as SHIP_ENV,tn as SHIP_VIA_ENV,jt as SIGN_IN_RETURN_PARAM,U as SPA_CHECK_CONSTRAINTS,Se as SPA_DEFAULT_CONFIG,he as Ship,s as ShipError,C as TTL_CONSTRAINTS,R as TokenKind,Q as UNBUILT_PROJECT_MARKERS,at as UNSAFE_FILENAME_CHARS,Xt as WEB_FILE_ACCEPT,Mn as __setTestEnvironment,nr as allValidFilesReady,Re as assertShipJsonSyntax,$ as calculateMD5,lt as classifyToken,Fe as createAccountResource,Ce as createDeploymentResource,ve as createDomainResource,Me as createTokenResource,Ht as default,un as deserializeLabels,an as extractSubdomain,ze as filterJunk,dt as formatDuration,_ as formatFileSize,on as formatTimeRemaining,ln as generateDeploymentUrl,pn as generateDomainUrl,L as getENV,wt as getValidFiles,M as hasUnbuiltMarker,ge as hasUnsafeChars,Ee as isBlockedExtension,sn as isCustomDomain,en as isDeployment,Ne as isPlatformDomain,F as isShipError,Vt as normalizeVia,Be as optimizeDeployPaths,ur as pluralize,je as processFilesForNode,Jt as readBearerValue,cn as serializeLabels,pt as validateApiKey,Zt as validateApiUrl,Pe as validateBuildCommand,Ie as validateCaller,Ke as validateDeployFile,Ve as validateDeployPath,ct as validateDeployToken,pe as validateFileName,tr as validateFiles,ye as validateIdempotencyKey,ut as validateOAuthToken,be as validateOutputDir,re as validatePassword,ee as validateToken,te as validateTtl};
2
2
  //# sourceMappingURL=index.js.map