@netlify/spark-ui 1.29.0 → 1.31.0-alpha.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.
Files changed (54) hide show
  1. package/README.md +4 -3
  2. package/dist/chunks/browser.Ca2rTNTu.js +769 -0
  3. package/dist/components/articleCopyActions.d.ts +9 -0
  4. package/dist/components/articleCopyActions.test.d.ts +1 -0
  5. package/dist/components/index.d.ts +2 -2
  6. package/dist/components/preact/DropZone/DropZone.d.ts +84 -15
  7. package/dist/components/preact/DropZone/DropZone.js +117 -85
  8. package/dist/components/preact/DropZone/drop-core/authedDropClient.d.ts +80 -0
  9. package/dist/components/preact/DropZone/drop-core/authedDropClient.js +99 -0
  10. package/dist/components/preact/DropZone/drop-core/buildClient.d.ts +98 -0
  11. package/dist/components/preact/DropZone/drop-core/buildClient.js +92 -0
  12. package/dist/components/preact/DropZone/drop-core/client.d.ts +4 -0
  13. package/dist/components/preact/DropZone/drop-core/client.js +2 -1
  14. package/dist/components/preact/DropZone/drop-core/deploy.d.ts +31 -0
  15. package/dist/components/preact/DropZone/drop-core/deploy.js +36 -18
  16. package/dist/components/preact/DropZone/drop-core/detectBuild.d.ts +26 -0
  17. package/dist/components/preact/DropZone/drop-core/detectBuild.js +80 -53
  18. package/dist/components/preact/DropZone/drop-core/errors.d.ts +38 -0
  19. package/dist/components/preact/DropZone/drop-core/errors.js +50 -5
  20. package/dist/components/preact/DropZone/drop-core/fileTypes.d.ts +17 -0
  21. package/dist/components/preact/DropZone/drop-core/fileTypes.js +11 -0
  22. package/dist/components/preact/DropZone/drop-core/index.d.ts +4 -0
  23. package/dist/components/preact/DropZone/drop-core/index.js +32 -15
  24. package/dist/components/preact/DropZone/drop-core/readFiles.js +1 -1
  25. package/dist/components/preact/DropZone/drop-core/types.d.ts +6 -1
  26. package/dist/components/preact/DropZone/drop-core/zip.d.ts +46 -0
  27. package/dist/components/preact/DropZone/drop-core/zip.js +43 -0
  28. package/dist/components/preact/DropZone/index.d.ts +3 -2
  29. package/dist/components/preact/DropZone/index.js +27 -9
  30. package/dist/components/preact/DropZone/useDropDeploy.d.ts +36 -5
  31. package/dist/components/preact/DropZone/useDropDeploy.js +140 -65
  32. package/dist/components/preact/index.d.ts +2 -1
  33. package/dist/components/preact/index.js +17 -12
  34. package/package.json +5 -2
  35. package/packages/components/ArticleCopyActions.astro +122 -0
  36. package/packages/components/articleCopyActions.test.ts +143 -0
  37. package/packages/components/articleCopyActions.ts +41 -0
  38. package/packages/components/index.ts +15 -0
  39. package/packages/components/preact/DropZone/DropZone.tsx +145 -24
  40. package/packages/components/preact/DropZone/drop-core/authedDropClient.ts +194 -0
  41. package/packages/components/preact/DropZone/drop-core/buildClient.ts +190 -0
  42. package/packages/components/preact/DropZone/drop-core/client.ts +1 -1
  43. package/packages/components/preact/DropZone/drop-core/deploy.ts +65 -0
  44. package/packages/components/preact/DropZone/drop-core/detectBuild.ts +125 -41
  45. package/packages/components/preact/DropZone/drop-core/errors.ts +84 -1
  46. package/packages/components/preact/DropZone/drop-core/fileTypes.ts +34 -0
  47. package/packages/components/preact/DropZone/drop-core/index.ts +4 -0
  48. package/packages/components/preact/DropZone/drop-core/readFiles.ts +1 -1
  49. package/packages/components/preact/DropZone/drop-core/types.ts +12 -1
  50. package/packages/components/preact/DropZone/drop-core/zip.ts +118 -0
  51. package/packages/components/preact/DropZone/index.tsx +24 -0
  52. package/packages/components/preact/DropZone/useDropDeploy.ts +219 -34
  53. package/packages/components/preact/index.ts +2 -1
  54. package/dist/chunks/browser.D58rdxmc.js +0 -444
@@ -0,0 +1,194 @@
1
+ import { apiError, type DropClient } from './client';
2
+ import type { BuildSite } from './buildClient';
3
+ import type { Digest, DropResponse } from './types';
4
+ import { NotAuthenticatedError, SiteCreateError } from './errors';
5
+
6
+ export interface AuthenticatedDropClientConfig {
7
+ /**
8
+ * Base for JSON API calls, routed through the consumer's access-control
9
+ * rewrite so the session cookie authenticates them. On netlify.com that
10
+ * rewrite is `/access-control/*` → the app's access-control function, which
11
+ * makes `/access-control/bb-api/api/v1` the API root (the default here).
12
+ */
13
+ proxyBase?: string;
14
+ /**
15
+ * Direct API base for the per-file uploads. The proxy above runs in a Lambda
16
+ * with a ~6MB request body limit, so file PUTs go straight to
17
+ * `api.netlify.com` (whose `/api/*` CORS policy allows any origin).
18
+ */
19
+ apiBase?: string;
20
+ /**
21
+ * Mint a short-lived bearer token for those direct uploads. On netlify.com
22
+ * this is `GET /access-control/generate-access-control-token`, whose
23
+ * `accessControlToken` the API decrypts back into the user's access token.
24
+ * Resolving `null` means "no session" and surfaces as `NotAuthenticatedError`.
25
+ */
26
+ getUploadToken: () => Promise<string | null>;
27
+ /** Create the site in this account. Omit to use the user's default account. */
28
+ accountSlug?: string;
29
+ /** How often to re-read the deploy while waiting. Default 1s. */
30
+ pollIntervalMs?: number;
31
+ /** How long to wait before giving up on the deploy. Default 10 minutes. */
32
+ timeoutMs?: number;
33
+ }
34
+
35
+ // Same defaults as AuthenticatedBuildClient — the ~15 lines shared with it
36
+ // (constants + site create) are deliberately duplicated rather than extracted,
37
+ // to avoid churn on the in-review build-client branch. Worth unifying once both
38
+ // have landed.
39
+ const PROXY_BASE = '/access-control/bb-api/api/v1';
40
+ const API_BASE = 'https://api.netlify.com/api/v1';
41
+ const POLL_INTERVAL_MS = 1000;
42
+ const TIMEOUT_MS = 10 * 60 * 1000;
43
+
44
+ /** Deploy states that end the wait — `ready` succeeds, the rest are failures. */
45
+ const TERMINAL_STATES = new Set(['ready', 'error', 'rejected']);
46
+
47
+ interface DeployState {
48
+ state?: string;
49
+ error_message?: string;
50
+ }
51
+
52
+ /** Response body of `POST /sites/{id}/deploys` — the slice the drop flow needs. */
53
+ interface SiteDeployResponse {
54
+ /** deploy id (BSON) */
55
+ id: string;
56
+ /** SHAs the backend does NOT yet have — only these get uploaded */
57
+ required?: string[];
58
+ }
59
+
60
+ /**
61
+ * Authenticated drop client for logged-in visitors. Unlike `AnonymousDropClient`
62
+ * — which creates an account-less site the visitor must later claim — this
63
+ * deploys straight into the visitor's account via the sites/deploys API,
64
+ * mirroring what app.netlify.com does for a logged-in drag-and-drop deploy.
65
+ * There is no claim step, so the caller should hand off to the site's dashboard
66
+ * page rather than the claim page.
67
+ *
68
+ * Requests split across two hosts by necessity: JSON calls go through the
69
+ * consumer's access-control proxy (cookie session, no token handling in the
70
+ * browser), while the per-file PUTs go direct to `api.netlify.com` with the
71
+ * short-lived bearer from `getUploadToken()` because the proxy can't carry
72
+ * large bodies.
73
+ *
74
+ * Error-mapping invariant: only pre-mutation failures — a null upload token, or
75
+ * a 401/403 creating the site — throw `NotAuthenticatedError`, which is the
76
+ * signal the drop flow may safely retry anonymously. Once the site exists, an
77
+ * auth failure throws a plain status-carrying error instead: falling back at
78
+ * that point would strand an empty site in the account *and* deploy a duplicate
79
+ * anonymously.
80
+ */
81
+ export class AuthenticatedDropClient implements DropClient {
82
+ private proxyBase: string;
83
+ private apiBase: string;
84
+ private getUploadToken: () => Promise<string | null>;
85
+ private accountSlug?: string;
86
+ private pollIntervalMs: number;
87
+ private timeoutMs: number;
88
+
89
+ constructor({
90
+ proxyBase = PROXY_BASE,
91
+ apiBase = API_BASE,
92
+ getUploadToken,
93
+ accountSlug,
94
+ pollIntervalMs = POLL_INTERVAL_MS,
95
+ timeoutMs = TIMEOUT_MS,
96
+ }: AuthenticatedDropClientConfig) {
97
+ this.proxyBase = proxyBase;
98
+ this.apiBase = apiBase;
99
+ this.getUploadToken = getUploadToken;
100
+ this.accountSlug = accountSlug;
101
+ this.pollIntervalMs = pollIntervalMs;
102
+ this.timeoutMs = timeoutMs;
103
+ }
104
+
105
+ /**
106
+ * The token here is the upload bearer, not a drop token — it authorizes the
107
+ * direct-API file PUTs, while the proxied JSON calls ignore it and ride the
108
+ * session cookie. Minted once per deploy, before anything is created, so a
109
+ * missing session fails the whole attempt cleanly.
110
+ */
111
+ async getToken(): Promise<string> {
112
+ const token = await this.getUploadToken();
113
+ if (!token) throw new NotAuthenticatedError();
114
+ return token;
115
+ }
116
+
117
+ /**
118
+ * Two proxied calls: create the site in the visitor's account, then the
119
+ * deploy on it. Mapped into the anonymous `DropResponse` shape so
120
+ * `deployFiles` runs unchanged over either client.
121
+ */
122
+ async createDeploy(files: Digest, _token: string): Promise<DropResponse> {
123
+ const path = this.accountSlug ? `/${this.accountSlug}/sites` : '/sites';
124
+ const siteRes = await fetch(`${this.proxyBase}${path}`, {
125
+ method: 'POST',
126
+ credentials: 'include',
127
+ headers: { 'Content-Type': 'application/json' },
128
+ body: JSON.stringify({ created_via: 'drop' }),
129
+ });
130
+ // A logged-out visitor 401s here, before anything is created — the one
131
+ // point an anonymous fallback is still safe (see the class doc).
132
+ if (siteRes.status === 401 || siteRes.status === 403) throw new NotAuthenticatedError();
133
+ if (!siteRes.ok) throw new SiteCreateError(siteRes.status);
134
+ const site: BuildSite = await siteRes.json();
135
+
136
+ const deployRes = await fetch(`${this.proxyBase}/sites/${site.id}/deploys`, {
137
+ method: 'POST',
138
+ credentials: 'include',
139
+ headers: { 'Content-Type': 'application/json' },
140
+ body: JSON.stringify({ files, deploy_source: 'drop' }),
141
+ });
142
+ if (!deployRes.ok) throw apiError('deploy create', deployRes.status);
143
+ const deploy: SiteDeployResponse = await deployRes.json();
144
+
145
+ return {
146
+ id: site.id,
147
+ deploy_id: deploy.id,
148
+ subdomain: site.name,
149
+ required: deploy.required ?? [],
150
+ };
151
+ }
152
+
153
+ async uploadFile(
154
+ deployId: string,
155
+ path: string,
156
+ content: ArrayBuffer,
157
+ token: string
158
+ ): Promise<void> {
159
+ // Direct to api.netlify.com with the upload bearer — see the class doc.
160
+ // PUT (not POST) so paths with "&" etc. work.
161
+ const res = await fetch(`${this.apiBase}/deploys/${deployId}/files${path}`, {
162
+ method: 'PUT',
163
+ headers: { 'Content-Type': 'application/octet-stream', Authorization: `Bearer ${token}` },
164
+ body: content,
165
+ });
166
+ if (!res.ok) throw apiError(`upload ${path}`, res.status);
167
+ }
168
+
169
+ /**
170
+ * Poll the deploy through the proxy until it settles — the session cookie
171
+ * outlives the short-lived upload bearer, so a slow deploy can't expire its
172
+ * own poll. Resolve on `ready`, throw on `error`/`rejected`, throw on timeout.
173
+ */
174
+ async waitUntilReady(deploy: DropResponse, _token: string): Promise<void> {
175
+ const deadline = this.timeoutMs / this.pollIntervalMs;
176
+ for (let i = 0; i < deadline; i++) {
177
+ const res = await fetch(`${this.proxyBase}/deploys/${deploy.deploy_id}`, {
178
+ credentials: 'include',
179
+ });
180
+ if (res.ok) {
181
+ const state: DeployState = await res.json();
182
+ if (state.state && TERMINAL_STATES.has(state.state)) {
183
+ if (state.state === 'ready') return;
184
+ throw new Error(
185
+ state.error_message ? `deploy failed: ${state.error_message}` : 'deploy failed'
186
+ );
187
+ }
188
+ }
189
+ await new Promise(r => setTimeout(r, this.pollIntervalMs));
190
+ }
191
+ // Same message the anonymous client uses, so humanizeDropError maps it.
192
+ throw new Error('Deploy did not become ready in time');
193
+ }
194
+ }
@@ -0,0 +1,190 @@
1
+ import {
2
+ BuildCreateError,
3
+ BuildFailedError,
4
+ BuildTimeoutError,
5
+ NotAuthenticatedError,
6
+ SiteCreateError,
7
+ } from './errors';
8
+
9
+ /** The subset of a Netlify Site the drop flow needs to redirect and report. */
10
+ export interface BuildSite {
11
+ /** site id (UUID) */
12
+ id: string;
13
+ /** the *.netlify.app subdomain, also the app's URL segment */
14
+ name: string;
15
+ /** https://<name>.netlify.app */
16
+ ssl_url?: string;
17
+ url?: string;
18
+ }
19
+
20
+ /** The subset of a Netlify Build returned by `POST /sites/{id}/builds`. */
21
+ export interface BuildResponse {
22
+ /** build id */
23
+ id: string;
24
+ /** the deploy the build produces — present as soon as the build is enqueued */
25
+ deploy_id?: string;
26
+ }
27
+
28
+ export interface BuildClient {
29
+ createSite(): Promise<BuildSite>;
30
+ createBuildFromZip(siteId: string, zip: File): Promise<BuildResponse>;
31
+ waitUntilBuildReady(build: BuildResponse): Promise<void>;
32
+ }
33
+
34
+ export interface AuthenticatedBuildClientConfig {
35
+ /**
36
+ * Base for JSON API calls, routed through the consumer's access-control
37
+ * rewrite so the session cookie authenticates them. On netlify.com that
38
+ * rewrite is `/access-control/*` → the app's access-control function, which
39
+ * makes `/access-control/bb-api/api/v1` the API root (the default here).
40
+ */
41
+ proxyBase?: string;
42
+ /**
43
+ * Direct API base for the zip upload. The proxy above runs in a Lambda with a
44
+ * ~6MB request body limit, so the multipart POST has to go straight to
45
+ * `api.netlify.com` (whose `/api/*` CORS policy allows any origin).
46
+ */
47
+ apiBase?: string;
48
+ /**
49
+ * Mint a short-lived bearer token for that direct upload. On netlify.com this
50
+ * is `GET /access-control/generate-access-control-token`, whose
51
+ * `accessControlToken` the API decrypts back into the user's access token.
52
+ * Resolving `null` means "no session" and surfaces as `NotAuthenticatedError`.
53
+ */
54
+ getUploadToken: () => Promise<string | null>;
55
+ /** Create the site in this account. Omit to use the user's default account. */
56
+ accountSlug?: string;
57
+ /** Title recorded against the build. */
58
+ title?: string;
59
+ /** How often to re-read the deploy while waiting. Default 1s. */
60
+ pollIntervalMs?: number;
61
+ /** How long to wait before giving up on the build. Default 10 minutes. */
62
+ timeoutMs?: number;
63
+ }
64
+
65
+ const PROXY_BASE = '/access-control/bb-api/api/v1';
66
+ const API_BASE = 'https://api.netlify.com/api/v1';
67
+ const POLL_INTERVAL_MS = 1000;
68
+ const TIMEOUT_MS = 10 * 60 * 1000;
69
+
70
+ /** Deploy states that end the wait — `ready` succeeds, the rest are failures. */
71
+ const TERMINAL_STATES = new Set(['ready', 'error', 'rejected']);
72
+
73
+ interface DeployState {
74
+ state?: string;
75
+ error_message?: string;
76
+ }
77
+
78
+ /**
79
+ * Authenticated drop client for projects that need a build. Unlike
80
+ * `AnonymousDropClient` — which creates an account-less static site and can only
81
+ * upload pre-built files — this creates a real site in the user's account and
82
+ * hands buildbot a source archive to build, mirroring what app.netlify.com does
83
+ * for a drag-and-drop build.
84
+ *
85
+ * Requests split across two hosts by necessity: JSON calls go through the
86
+ * consumer's access-control proxy (cookie session, no token handling in the
87
+ * browser), while the zip upload goes direct to `api.netlify.com` with a
88
+ * short-lived bearer token because the proxy can't carry a body that large.
89
+ */
90
+ export class AuthenticatedBuildClient implements BuildClient {
91
+ private proxyBase: string;
92
+ private apiBase: string;
93
+ private getUploadToken: () => Promise<string | null>;
94
+ private accountSlug?: string;
95
+ private title: string;
96
+ private pollIntervalMs: number;
97
+ private timeoutMs: number;
98
+
99
+ constructor({
100
+ proxyBase = PROXY_BASE,
101
+ apiBase = API_BASE,
102
+ getUploadToken,
103
+ accountSlug,
104
+ title = 'Build from drop deployment',
105
+ pollIntervalMs = POLL_INTERVAL_MS,
106
+ timeoutMs = TIMEOUT_MS,
107
+ }: AuthenticatedBuildClientConfig) {
108
+ this.proxyBase = proxyBase;
109
+ this.apiBase = apiBase;
110
+ this.getUploadToken = getUploadToken;
111
+ this.accountSlug = accountSlug;
112
+ this.title = title;
113
+ this.pollIntervalMs = pollIntervalMs;
114
+ this.timeoutMs = timeoutMs;
115
+ }
116
+
117
+ /**
118
+ * Create the site the build deploys into. Goes through the proxy with
119
+ * `credentials: 'include'` so the app session authorizes it; without an
120
+ * account slug the API picks the user's default account.
121
+ */
122
+ async createSite(): Promise<BuildSite> {
123
+ const path = this.accountSlug ? `/${this.accountSlug}/sites` : '/sites';
124
+ const res = await fetch(`${this.proxyBase}${path}`, {
125
+ method: 'POST',
126
+ credentials: 'include',
127
+ headers: { 'Content-Type': 'application/json' },
128
+ body: JSON.stringify({ created_via: 'drop' }),
129
+ });
130
+ // A logged-out visitor gets a 401 here rather than at the token step, since
131
+ // this is the first call that needs the session.
132
+ if (res.status === 401 || res.status === 403) throw new NotAuthenticatedError();
133
+ if (!res.ok) throw new SiteCreateError(res.status);
134
+ return res.json();
135
+ }
136
+
137
+ /**
138
+ * Upload the source archive and enqueue a build. Direct to `api.netlify.com`
139
+ * (see the note on `apiBase`), authorized by a freshly minted bearer token.
140
+ * `Content-Type` is left unset on purpose so the browser adds the multipart
141
+ * boundary itself.
142
+ */
143
+ async createBuildFromZip(siteId: string, zip: File): Promise<BuildResponse> {
144
+ const token = await this.getUploadToken();
145
+ if (!token) throw new NotAuthenticatedError();
146
+
147
+ const body = new FormData();
148
+ body.append('zip', zip);
149
+ body.append('title', this.title);
150
+
151
+ const res = await fetch(`${this.apiBase}/sites/${siteId}/builds`, {
152
+ method: 'POST',
153
+ headers: { Authorization: `Bearer ${token}` },
154
+ body,
155
+ });
156
+ if (res.status === 401 || res.status === 403) throw new NotAuthenticatedError();
157
+ if (!res.ok) throw new BuildCreateError(res.status);
158
+ return res.json();
159
+ }
160
+
161
+ /**
162
+ * Poll the build's deploy through the proxy until it settles, mirroring
163
+ * `AnonymousDropClient.waitUntilReady` — resolve on `ready`, throw on
164
+ * `error`/`rejected`, throw on timeout. A build that hasn't been given a
165
+ * deploy id yet has nothing pollable, so it resolves immediately and the
166
+ * caller falls back to the site page.
167
+ *
168
+ * Optional in the drop flow: a build takes minutes, so the default hand-off
169
+ * redirects to the app's deploy page (live logs) instead of waiting here.
170
+ */
171
+ async waitUntilBuildReady(build: BuildResponse): Promise<void> {
172
+ if (!build.deploy_id) return;
173
+
174
+ const deadline = this.timeoutMs / this.pollIntervalMs;
175
+ for (let i = 0; i < deadline; i++) {
176
+ const res = await fetch(`${this.proxyBase}/deploys/${build.deploy_id}`, {
177
+ credentials: 'include',
178
+ });
179
+ if (res.ok) {
180
+ const deploy: DeployState = await res.json();
181
+ if (deploy.state && TERMINAL_STATES.has(deploy.state)) {
182
+ if (deploy.state === 'ready') return;
183
+ throw new BuildFailedError(deploy.error_message);
184
+ }
185
+ }
186
+ await new Promise(r => setTimeout(r, this.pollIntervalMs));
187
+ }
188
+ throw new BuildTimeoutError();
189
+ }
190
+ }
@@ -1,7 +1,7 @@
1
1
  import type { DropResponse, Digest } from './types';
2
2
 
3
3
  /** A normal Error with the response's HTTP status attached, so callers can branch on it directly. */
4
- function apiError(action: string, status: number): Error & { status: number } {
4
+ export function apiError(action: string, status: number): Error & { status: number } {
5
5
  return Object.assign(new Error(`${action} failed: ${status}`), { status });
6
6
  }
7
7
 
@@ -1,6 +1,9 @@
1
1
  import { getDigest } from './digest';
2
+ import type { BuildClient, BuildResponse, BuildSite } from './buildClient';
2
3
  import type { DropClient } from './client';
4
+ import type { InferredBuildSettings } from './detectBuild';
3
5
  import type { DeployProgress, DeployResult, ProcessedFile } from './types';
6
+ import { zipFiles } from './zip';
4
7
 
5
8
  const MAX_CONCURRENT_UPLOADS = 5;
6
9
 
@@ -55,3 +58,65 @@ export async function deployFiles(
55
58
  onProgress?.({ phase: 'ready' });
56
59
  return { deploy, token, url: `https://${deploy.subdomain}.netlify.app` };
57
60
  }
61
+
62
+ export interface BuildDeployResult {
63
+ /** The site created for this build. */
64
+ site: BuildSite;
65
+ /** The enqueued build; `deploy_id` is what the app's deploy page keys off. */
66
+ build: BuildResponse;
67
+ /** Settings synthesised into the uploaded `netlify.toml`, or null if none were. */
68
+ buildSettings: InferredBuildSettings | null;
69
+ /** The site's live URL — only serves content once the build finishes. */
70
+ url: string;
71
+ }
72
+
73
+ export interface BuildDeployOptions extends DeployOptions {
74
+ /**
75
+ * Poll until the build finishes instead of returning as soon as it's enqueued.
76
+ * Off by default: a build takes minutes, so the useful hand-off is usually the
77
+ * app's deploy page with its live logs, not a spinner. Turn it on when the
78
+ * caller needs to know the outcome — only then can a `BuildFailedError` reach
79
+ * it with the build's own error message.
80
+ */
81
+ waitForBuild?: boolean;
82
+ }
83
+
84
+ /**
85
+ * The build counterpart to `deployFiles`: zip the drop, create a site in the
86
+ * user's account, and hand the archive to buildbot. Requires an authenticated
87
+ * client — builds have no anonymous equivalent.
88
+ *
89
+ * Site creation deliberately happens *after* zipping, so a zip that fails
90
+ * doesn't leave an empty site behind in the user's account.
91
+ */
92
+ export async function deployBuild(
93
+ client: BuildClient,
94
+ files: ProcessedFile[],
95
+ opts: BuildDeployOptions = {}
96
+ ): Promise<BuildDeployResult> {
97
+ if (!files.length) throw new Error('No files to deploy');
98
+ const { onProgress, waitForBuild = false } = opts;
99
+
100
+ onProgress?.({ phase: 'zipping' });
101
+ const { file: zip, buildSettings } = await zipFiles(files);
102
+
103
+ onProgress?.({ phase: 'creating' });
104
+ const site = await client.createSite();
105
+
106
+ // No byte-level progress to report: this is one multipart request, and
107
+ // `fetch` exposes no upload progress. The phase still flips so the UI can say
108
+ // "uploading" rather than sitting on "creating" for the length of the upload.
109
+ onProgress?.({ phase: 'uploading' });
110
+ const build = await client.createBuildFromZip(site.id, zip);
111
+
112
+ onProgress?.({ phase: 'building' });
113
+ if (waitForBuild) await client.waitUntilBuildReady(build);
114
+
115
+ onProgress?.({ phase: 'ready' });
116
+ return {
117
+ site,
118
+ build,
119
+ buildSettings,
120
+ url: site.ssl_url || site.url || `https://${site.name}.netlify.app`,
121
+ };
122
+ }
@@ -18,28 +18,35 @@ export interface BuildDetection {
18
18
  * Dependencies whose presence implies a build even without an explicit `build`
19
19
  * script (e.g. a framework wired through its own CLI). Not exhaustive — the
20
20
  * `build` script check below catches the common case; this is the backstop.
21
+ *
22
+ * The value is the framework's default publish directory, or `null` where that
23
+ * directory isn't a fixed string we can state with confidence — Nuxt, SvelteKit,
24
+ * Remix and Angular all resolve it from an adapter or project name. `null` means
25
+ * "a build is required, but don't guess a publish directory": see
26
+ * `inferBuildSettings`, which only synthesises a `netlify.toml` when it knows
27
+ * both halves of the answer.
21
28
  */
22
- const FRAMEWORK_DEPENDENCIES = new Set([
23
- 'astro',
24
- 'next',
25
- 'nuxt',
26
- 'gatsby',
27
- 'vite',
28
- 'react-scripts',
29
- 'parcel',
30
- 'expo',
31
- 'gridsome',
32
- 'vuepress',
33
- 'hexo',
34
- '@remix-run/dev',
35
- '@sveltejs/kit',
36
- '@angular/cli',
37
- '@vue/cli-service',
38
- '@11ty/eleventy',
39
- '@docusaurus/core',
40
- '@builder.io/qwik',
41
- '@analogjs/platform',
42
- '@solidjs/start',
29
+ const FRAMEWORK_DEPENDENCIES = new Map<string, string | null>([
30
+ ['astro', 'dist'],
31
+ ['next', '.next'],
32
+ ['nuxt', null],
33
+ ['gatsby', 'public'],
34
+ ['vite', 'dist'],
35
+ ['react-scripts', 'build'],
36
+ ['parcel', 'dist'],
37
+ ['expo', 'dist'],
38
+ ['gridsome', 'dist'],
39
+ ['vuepress', null],
40
+ ['hexo', 'public'],
41
+ ['@remix-run/dev', null],
42
+ ['@sveltejs/kit', null],
43
+ ['@angular/cli', null],
44
+ ['@vue/cli-service', 'dist'],
45
+ ['@11ty/eleventy', '_site'],
46
+ ['@docusaurus/core', 'build'],
47
+ ['@builder.io/qwik', 'dist'],
48
+ ['@analogjs/platform', null],
49
+ ['@solidjs/start', null],
43
50
  ]);
44
51
 
45
52
  /**
@@ -71,16 +78,21 @@ function hasBuildScript(pkg: Record<string, unknown>): boolean {
71
78
  return typeof build === 'string' && build.trim().length > 0;
72
79
  }
73
80
 
74
- /** True if any dependency (prod or dev) is a known build-requiring framework. */
75
- function hasFrameworkDependency(pkg: Record<string, unknown>): boolean {
81
+ /** The first known build-requiring framework among the deps (prod or dev), if any. */
82
+ function findFrameworkDependency(pkg: Record<string, unknown>): string | null {
76
83
  for (const key of ['dependencies', 'devDependencies'] as const) {
77
84
  const deps = pkg[key];
78
85
  if (!deps || typeof deps !== 'object') continue;
79
86
  for (const name of Object.keys(deps)) {
80
- if (FRAMEWORK_DEPENDENCIES.has(name)) return true;
87
+ if (FRAMEWORK_DEPENDENCIES.has(name)) return name;
81
88
  }
82
89
  }
83
- return false;
90
+ return null;
91
+ }
92
+
93
+ /** True if any dependency (prod or dev) is a known build-requiring framework. */
94
+ function hasFrameworkDependency(pkg: Record<string, unknown>): boolean {
95
+ return findFrameworkDependency(pkg) !== null;
84
96
  }
85
97
 
86
98
  /**
@@ -102,23 +114,13 @@ export function detectBuild(files: ProcessedFile[]): BuildDetection {
102
114
  return { buildRequired: true, reason: 'netlify-toml-build' };
103
115
  }
104
116
 
105
- const pkg = rootFile(files, '/package.json');
106
- if (pkg) {
107
- let parsed: Record<string, unknown> | null = null;
108
- try {
109
- parsed = JSON.parse(text(pkg)) as Record<string, unknown>;
110
- } catch {
111
- // A malformed package.json isn't a reliable build signal on its own —
112
- // fall through and let the other heuristics decide.
113
- parsed = null;
117
+ const parsed = readPackageJson(files);
118
+ if (parsed) {
119
+ if (hasBuildScript(parsed)) {
120
+ return { buildRequired: true, reason: 'package-json-build-script' };
114
121
  }
115
- if (parsed) {
116
- if (hasBuildScript(parsed)) {
117
- return { buildRequired: true, reason: 'package-json-build-script' };
118
- }
119
- if (hasFrameworkDependency(parsed)) {
120
- return { buildRequired: true, reason: 'framework-dependency' };
121
- }
122
+ if (hasFrameworkDependency(parsed)) {
123
+ return { buildRequired: true, reason: 'framework-dependency' };
122
124
  }
123
125
  }
124
126
 
@@ -128,3 +130,85 @@ export function detectBuild(files: ProcessedFile[]): BuildDetection {
128
130
 
129
131
  return { buildRequired: false, reason: null };
130
132
  }
133
+
134
+ /** Parse the root `package.json`, or null when it's absent or malformed. */
135
+ function readPackageJson(files: ProcessedFile[]): Record<string, unknown> | null {
136
+ const pkg = rootFile(files, '/package.json');
137
+ if (!pkg) return null;
138
+ try {
139
+ return JSON.parse(text(pkg)) as Record<string, unknown>;
140
+ } catch {
141
+ // A malformed package.json isn't a reliable build signal on its own —
142
+ // callers fall through and let the other heuristics decide.
143
+ return null;
144
+ }
145
+ }
146
+
147
+ // --- build settings for the synthesised netlify.toml ------------------------
148
+
149
+ /** Build settings confident enough to write into a `netlify.toml` for buildbot. */
150
+ export interface InferredBuildSettings {
151
+ /** Build command, e.g. `"npm run build"`. */
152
+ command: string;
153
+ /** Publish directory relative to the deploy root, no leading slash, e.g. `"dist"`. */
154
+ publish: string;
155
+ /** The dependency the settings were inferred from, e.g. `"astro"`. */
156
+ framework: string;
157
+ }
158
+
159
+ /** Lockfile at the deploy root → the package manager that wrote it. */
160
+ const LOCKFILE_PACKAGE_MANAGERS: ReadonlyArray<readonly [string, string]> = [
161
+ ['/pnpm-lock.yaml', 'pnpm'],
162
+ ['/yarn.lock', 'yarn'],
163
+ ['/bun.lockb', 'bun'],
164
+ ['/bun.lock', 'bun'],
165
+ ['/package-lock.json', 'npm'],
166
+ ];
167
+
168
+ /**
169
+ * A bare `[build]` table header at the start of a line. Stricter than
170
+ * `NETLIFY_TOML_BUILD_SECTION` on purpose: a config with only
171
+ * `[build.environment]` carries no command or publish directory, so it still
172
+ * needs a `[build]` table synthesised. (TOML permits defining a super-table
173
+ * after its sub-tables, so appending one is valid.)
174
+ */
175
+ const NETLIFY_TOML_BUILD_TABLE = /^\s*\[build\]/m;
176
+
177
+ function detectPackageManager(files: ProcessedFile[]): string {
178
+ for (const [path, manager] of LOCKFILE_PACKAGE_MANAGERS) {
179
+ if (rootFile(files, path)) return manager;
180
+ }
181
+ return 'npm';
182
+ }
183
+
184
+ /**
185
+ * Infer the build command and publish directory for a build-required drop, so
186
+ * `zipFiles` can write them into a `netlify.toml` that buildbot reads.
187
+ *
188
+ * Deliberately conservative: it returns settings **only** when both halves are
189
+ * known — a `build` script (which gives the command) and a recognised framework
190
+ * with a fixed default publish directory (which gives the output). Anything else
191
+ * returns `null`, leaving the zip without a synthesised `[build]` table so
192
+ * buildbot's own framework detection resolves the settings instead. That matters
193
+ * because a `[build]` table with a command but no `publish` makes buildbot
194
+ * publish the deploy root — shipping the project's *source* rather than its
195
+ * built output, which is worse than not guessing at all.
196
+ *
197
+ * Returns `null` too when the drop already declares a `[build]` table: the
198
+ * author's own config always wins.
199
+ */
200
+ export function inferBuildSettings(files: ProcessedFile[]): InferredBuildSettings | null {
201
+ const toml = rootFile(files, '/netlify.toml');
202
+ if (toml && NETLIFY_TOML_BUILD_TABLE.test(text(toml))) return null;
203
+
204
+ const pkg = readPackageJson(files);
205
+ if (!pkg || !hasBuildScript(pkg)) return null;
206
+
207
+ const framework = findFrameworkDependency(pkg);
208
+ if (!framework) return null;
209
+
210
+ const publish = FRAMEWORK_DEPENDENCIES.get(framework);
211
+ if (!publish) return null;
212
+
213
+ return { command: `${detectPackageManager(files)} run build`, publish, framework };
214
+ }