@novence/sdk 0.4.0 → 0.6.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/README.md CHANGED
@@ -40,6 +40,11 @@ console.log(url); // https://{suffix}.novence.ai
40
40
 
41
41
  One HTML document (report, dashboard, artifact): `client.publishHtml({ html, title })` then poll `deployments.latest`. CLI: `npx novence deploy report.html`.
42
42
 
43
+ > **Behaviour change in 0.6.0:** `files.uploadDir` now makes the project's files match
44
+ > the directory. Files it no longer has are removed (`/data/*.json` is kept), and
45
+ > `.well-known/` is uploaded. Pass `{ prune: false }` for the old add-only behaviour.
46
+ > It returns `{ uploaded, removed, kept }`.
47
+
43
48
  ### Bootstrap + verify (email path)
44
49
 
45
50
  When you need a key from email OTP instead of the CLI:
@@ -80,6 +85,9 @@ if (deployment.status === "live") {
80
85
  `deployment.status` is a union — `pending | queued | checking | promoting | live | failed`
81
86
  — so the compiler catches typos in status comparisons.
82
87
 
88
+ A deploy takes about 20 seconds with a check runner warm and 1–2 minutes from cold. Every
89
+ deploy ends in `live` or `failed`: at the latest after 15 minutes without a runner or 10 in checks.
90
+
83
91
  ### Checks
84
92
 
85
93
  `deployment.checksResults` carries the quality gate. When `skipped` is true
@@ -94,6 +102,13 @@ if (checks?.skipped) {
94
102
  }
95
103
  ```
96
104
 
105
+ Checks score the files in this deployment before anything goes live, so a rejected
106
+ deploy leaves the live site as it was. `checks.measurementError` is set when the page
107
+ could not be scored; that deploy fails.
108
+
109
+ `deployments.rollback(projectId)` restores the version live immediately before the
110
+ current one, so rolling back twice is an undo. Pass `{ deploymentId }` to go further back.
111
+
97
112
  Every method returns a typed response. `Project`, `Deployment`, `ChecksResults`,
98
113
  `Form`, `Quotas`, `Analytics`, `StagingFile` and the rest are exported for your own
99
114
  signatures:
@@ -119,17 +134,54 @@ call at a different control plane — useful when running the API locally.
119
134
  | Namespace | Methods |
120
135
  | --- | --- |
121
136
  | `client.projects` | `create` · `list` · `get` · `update` · `usage` · `analytics` · `brief` · `putBrief` · `events` |
122
- | `client.files` | `uploadDir` · `uploadBuffer` · `getUploadUrl` · `getUploadUrlsBatch` · `confirm` · `confirmBatch` |
123
- | `client.deployments` | `create` · `latest` |
137
+ | `client.files` | `uploadDir` · `uploadBuffer` · `list` · `delete` · `getUploadUrl` · `getUploadUrlsBatch` · `confirm` · `confirmBatch` |
138
+ | `client.deployments` | `create` · `latest` · `rollback` |
139
+ | `client.git` | `connect` · `get` · `disconnect` |
124
140
  | `client.domains` | `configure` · `status` |
125
141
  | `client.forms` | `create` · `list` · `get` · `update` · `delete` · `listSubmissions` · `deleteSubmission` |
126
- | `client.billing` | `quotas` · `checkout` · `portal` · `mppUpgrade` |
142
+ | `client.billing` | `quotas` · `spendLimit` · `setSpendLimit` · `checkout` · `portal` · `mppUpgrade` |
127
143
  | `client.account` | `get` · `consoleKit` · `createSession` · `revokeSession` |
128
144
  | `client.apiKeys` | `revoke` |
129
145
 
146
+ ### Rate limits
147
+
148
+ The API allows about 100 requests per 10 seconds per IP. When a call gets HTTP 429 with
149
+ a short `Retry-After` (30 seconds or less), the SDK waits and sends it again, up to 5
150
+ times, so a large `uploadDir` finishes instead of failing partway. Longer limits (hourly
151
+ caps) are thrown at once as a `NovenceError` with `status: 429`. Tune or disable with
152
+ the exported `rateLimitRetry` (`rateLimitRetry.maxRetries = 0`).
153
+
154
+ ### Deploy from a GitHub repo (optional)
155
+
156
+ ```ts
157
+ const { connection } = await client.git.connect(project.id, { repository: "owner/name", branch: "main" });
158
+ // Write connection.workflow to .github/workflows/novence.yml, add your build step, commit and push.
159
+ ```
160
+
161
+ Pushes to that branch then deploy. The workflow signs in with GitHub OIDC, so no API key
162
+ is stored in the repository; Novence does not clone or build it. Inside such a job,
163
+ `exchangeGithubOidc()` returns a 30-minute key that can only upload to and deploy that
164
+ project. Each `Deployment` carries a `source` (commit, ref, repository for git deploys).
165
+ A deploy requested while another is running comes back with `queuedRedeploy: true` and
166
+ starts by itself afterwards: keep polling `deployments.latest` for a new id.
167
+
130
168
  Standalone helpers for the pre-auth flow: `createDemoAccount`, `claimAccount`,
131
169
  `bootstrapAccount`, `verifyEmail`, `resendVerification`, `reissueApiKey`.
132
170
 
171
+ ## Spend limit
172
+
173
+ Cap monthly overage on Pro/Scale. At the cap, anything that would add overage pauses —
174
+ including live sites once bandwidth is past the included pool — until you raise it or the
175
+ UTC month resets. A request blocked by the cap throws `NovenceError` with `status` 402 and
176
+ `wall` `"spend_limit"`.
177
+
178
+ ```ts
179
+ await client.billing.setSpendLimit(50); // $50/month; 0 = never pay overage
180
+ const s = await client.billing.spendLimit();
181
+ // { limitUsd: 50, overageUsd: 12.4, usedPct: 24, reached: false, paused: [], … }
182
+ await client.billing.setSpendLimit(null); // remove the cap
183
+ ```
184
+
133
185
  ## Identity checks
134
186
 
135
187
  Prefer `isNovenceClient()` over `instanceof Novence`:
@@ -1,5 +1,23 @@
1
1
  /** Public control plane. */
2
2
  export declare const DEFAULT_BASE_URL = "https://api.novence.ai";
3
+ /**
4
+ * How the SDK handles HTTP 429. The API allows about 100 requests per 10 seconds per IP,
5
+ * and a large directory upload from a shared CI runner can exceed that. A 429 means the
6
+ * request was not processed, so it is safe to send again.
7
+ *
8
+ * Mutable on purpose: set `rateLimitRetry.maxRetries = 0` to turn retries off.
9
+ */
10
+ export declare const rateLimitRetry: {
11
+ /** Extra attempts after the first 429. */
12
+ maxRetries: number;
13
+ /**
14
+ * Longest `Retry-After` worth waiting for, in seconds. Hourly limits (too many
15
+ * sign-ups, too many data writes) answer with a longer wait and are returned to the
16
+ * caller at once instead.
17
+ */
18
+ maxWaitSeconds: number;
19
+ sleep: (ms: number) => Promise<void>;
20
+ };
3
21
  /** True for a Novence client from any copy of this module. */
4
22
  export declare function isNovenceClient(value: unknown): value is Novence;
5
23
  /**
@@ -8,7 +26,14 @@ export declare function isNovenceClient(value: unknown): value is Novence;
8
26
  */
9
27
  export declare class NovenceError extends Error {
10
28
  readonly status: number;
11
- constructor(message: string, status: number);
29
+ /**
30
+ * On a 402, which wall was hit: `verify` (email OTP), `upgrade` (Checkout/MPP), or
31
+ * `spend_limit` (the account's own overage cap — raise it with billing.setSpendLimit).
32
+ */
33
+ readonly wall?: string;
34
+ /** Machine-readable reason when the API sends one, e.g. `repo_not_connected`. */
35
+ readonly code?: string;
36
+ constructor(message: string, status: number, wall?: string, code?: string);
12
37
  }
13
38
  export interface NovenceOptions {
14
39
  apiKey: string;
@@ -74,11 +99,70 @@ export interface ChecksResults {
74
99
  reason?: string;
75
100
  /** Non-blocking findings, e.g. low Lighthouse performance while `enforcePerformance` is off. */
76
101
  warnings?: string[];
102
+ /** The deployment these results were measured from. */
103
+ deploymentId?: string;
104
+ /** Why the page could not be scored. The deploy fails and `lighthouse` is null. */
105
+ measurementError?: string;
77
106
  [key: string]: unknown;
78
107
  }
108
+ /** Where a deployment came from. `verified` means the git fields were read from a GitHub OIDC token. */
109
+ export interface DeploySource {
110
+ kind: "api" | "cli" | "mcp" | "sdk" | "github-actions";
111
+ repository?: string;
112
+ ref?: string;
113
+ sha?: string;
114
+ /** First line of the commit message. */
115
+ message?: string;
116
+ actor?: string;
117
+ runUrl?: string;
118
+ verified?: boolean;
119
+ }
120
+ /** A project's link to a GitHub repository for push-to-deploy. */
121
+ export interface GitConnection {
122
+ provider: "github";
123
+ /** Lower-cased `owner/name`. */
124
+ repository: string;
125
+ /** The only branch that deploys. */
126
+ branch: string;
127
+ /** True once a workflow run from the repository has authenticated. */
128
+ verified: boolean;
129
+ connectedAt: string;
130
+ /** Audience the workflow must request its OIDC token for. */
131
+ audience: string;
132
+ /** Contents for `.github/workflows/novence.yml`. */
133
+ workflow: string;
134
+ }
135
+ /** Result of trading a GitHub Actions OIDC token for a short-lived deploy key. */
136
+ export interface GithubOidcExchange {
137
+ /** Deploy-only key for `projectId`. Expires at `expiresAt` (about 30 minutes). */
138
+ apiKey: string;
139
+ expiresAt: string;
140
+ projectId: string;
141
+ project: {
142
+ id: string;
143
+ name: string;
144
+ suffix: string;
145
+ url: string;
146
+ };
147
+ source: DeploySource;
148
+ }
149
+ export interface UploadDirResult {
150
+ /** Site paths uploaded from the directory. */
151
+ uploaded: string[];
152
+ /** Site paths deleted because the directory no longer has them. Empty with `prune: false`. */
153
+ removed: string[];
154
+ /** Site paths left alone although the directory lacks them (`/data/*.json`). */
155
+ kept: string[];
156
+ }
79
157
  export interface Deployment {
80
158
  id: string;
81
159
  status: DeploymentStatus;
160
+ source?: DeploySource | null;
161
+ /**
162
+ * True while a newer deploy is waiting for this one to settle. Keep polling
163
+ * `deployments.latest`: a deployment with a different id follows.
164
+ */
165
+ queuedRedeploy?: boolean;
82
166
  phase?: DeploymentPhase;
83
167
  /** 1-based place in the check-runner queue while `status` is `queued`; null otherwise. */
84
168
  queuePosition?: number | null;
@@ -181,6 +265,27 @@ export interface Quotas {
181
265
  /** Extra collaborators per project (owner excluded). Free/unverified is 0. */
182
266
  teamSeats: number;
183
267
  }
268
+ /** Monthly overage cap (Pro/Scale). Matches SpendLimitStatus in openapi.yaml. */
269
+ export interface SpendLimitStatus {
270
+ /** Cap in USD. null = no cap. */
271
+ limitUsd: number | null;
272
+ /** Month-to-date overage at list rates (excludes the base plan price). */
273
+ overageUsd: number;
274
+ remainingUsd: number | null;
275
+ /** overage / limit as a whole percent, capped at 100. null when the limit is null or 0. */
276
+ usedPct: number | null;
277
+ /** Only verified Pro/Scale accounts incur overage. A limit on Free is kept for later. */
278
+ applies: boolean;
279
+ reached: boolean;
280
+ /** What is paused right now. `bandwidth_gb` means live sites are paused. */
281
+ paused: Array<"bandwidth_gb" | "check_minutes" | "form_submissions" | "custom_domains">;
282
+ pausedLabels: string[];
283
+ sitesPaused: boolean;
284
+ period: {
285
+ start: string;
286
+ resetsAt: string;
287
+ };
288
+ }
184
289
  export interface ProjectUsage {
185
290
  /** Prefer storage_bytes over storage_gb for exact accounting. */
186
291
  storage_bytes: number;
@@ -258,6 +363,7 @@ export interface AccountSnapshot {
258
363
  emailVerified?: boolean;
259
364
  quotas?: Quotas;
260
365
  usage?: Record<string, number>;
366
+ spendLimit?: SpendLimitStatus;
261
367
  projects?: Array<Record<string, unknown>>;
262
368
  subscription?: {
263
369
  id: string;
@@ -390,14 +496,33 @@ export declare class Novence {
390
496
  uploadBuffer: (projectId: string, path: string, contentType: string | undefined, body: ArrayBuffer | Uint8Array) => Promise<{
391
497
  file: StagingFile;
392
498
  }>;
393
- /** Node-only: upload every allowed file under `dir` with root-relative site paths. */
394
- uploadDir: (projectId: string, dir: string) => Promise<{
395
- uploaded: string[];
499
+ list: (projectId: string) => Promise<{
500
+ files: StagingFile[];
501
+ }>;
502
+ /** Remove one file from staging. It leaves the live site on the next deploy. */
503
+ delete: (projectId: string, path: string) => Promise<{
504
+ deleted: boolean;
396
505
  }>;
506
+ /**
507
+ * Node-only: make the project's files match `dir`. Uploads every allowed file with a
508
+ * root-relative site path, then removes files the directory no longer has, so a file
509
+ * deleted locally stops being served after the next deploy. `/data/*.json` is never
510
+ * removed (the live-data API writes it). Pass `{ prune: false }` to only add.
511
+ * Dot-files and dot-directories are skipped, except `.well-known/`.
512
+ */
513
+ uploadDir: (projectId: string, dir: string, opts?: {
514
+ prune?: boolean;
515
+ }) => Promise<UploadDirResult>;
397
516
  };
398
517
  deployments: {
518
+ /**
519
+ * Start a deploy. `source` records where it came from (shown by `deployments.latest`).
520
+ * Called while another deploy is in progress, it returns that deploy; if files changed
521
+ * since, `queuedRedeploy` is true and a follow-up starts once the first settles.
522
+ */
399
523
  create: (projectId: string, opts?: {
400
524
  force?: boolean;
525
+ source?: Partial<DeploySource>;
401
526
  }) => Promise<{
402
527
  deployment: Deployment;
403
528
  }>;
@@ -420,6 +545,29 @@ export declare class Novence {
420
545
  projectId?: string;
421
546
  force?: boolean;
422
547
  }): Promise<PublishHtmlResult>;
548
+ /** Optional push-to-deploy from a GitHub repository. Novence does not clone or build it. */
549
+ git: {
550
+ /** The project's repository connection, or null. */
551
+ get: (projectId: string) => Promise<{
552
+ connection: GitConnection | null;
553
+ }>;
554
+ /**
555
+ * Link the project to a repository (`owner/name` or a github.com URL). Only pushes to
556
+ * `branch` (default `main`) deploy. Write the returned `workflow` to
557
+ * `.github/workflows/novence.yml`; it authenticates with GitHub OIDC, so no API key
558
+ * is stored in the repository. Needs a verified email.
559
+ */
560
+ connect: (projectId: string, input: {
561
+ repository: string;
562
+ branch?: string;
563
+ }) => Promise<{
564
+ connection: GitConnection;
565
+ }>;
566
+ disconnect: (projectId: string) => Promise<{
567
+ disconnected: boolean;
568
+ repository: string | null;
569
+ }>;
570
+ };
423
571
  domains: {
424
572
  configure: (projectId: string, hostname: string, input?: {
425
573
  primary?: "www" | "apex";
@@ -487,7 +635,17 @@ export declare class Novence {
487
635
  quotas: Quotas;
488
636
  usage: Record<string, number>;
489
637
  bandwidthMetering?: string;
638
+ spendLimit?: SpendLimitStatus;
490
639
  }>;
640
+ /** Monthly overage cap, month-to-date overage, and what is paused. */
641
+ spendLimit: () => Promise<SpendLimitStatus>;
642
+ /**
643
+ * Set or change the monthly overage cap in USD (up to 2 decimals), or pass `null` to
644
+ * remove it. At the cap, anything that would add overage pauses — including live sites
645
+ * once bandwidth is past the included pool — until it is raised or the UTC month resets.
646
+ * `0` means never pay overage.
647
+ */
648
+ setSpendLimit: (limitUsd: number | null) => Promise<SpendLimitStatus>;
491
649
  checkout: (input: {
492
650
  successUrl?: string;
493
651
  cancelUrl?: string;
@@ -562,6 +720,17 @@ export declare class Novence {
562
720
  }>;
563
721
  };
564
722
  }
723
+ /**
724
+ * Inside a GitHub Actions job with `permissions: id-token: write`, trade the job's OIDC
725
+ * token for a short-lived, deploy-only key on the project its repository is connected to
726
+ * (`git.connect`). No stored secret. Throws a NovenceError whose `code` says why not:
727
+ * `repo_not_connected`, `branch_not_allowed`, `project_required`, `event_not_allowed`.
728
+ */
729
+ export declare function exchangeGithubOidc(opts?: {
730
+ baseUrl?: string;
731
+ projectId?: string;
732
+ env?: Record<string, string | undefined>;
733
+ }): Promise<GithubOidcExchange>;
565
734
  export interface SignupAttributionInput {
566
735
  method?: "web" | "mcp" | "cli" | "sdk" | "api";
567
736
  client?: string;
package/dist/cjs/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Novence = exports.CONSOLE_INJECT_MARKER = exports.NovenceError = exports.DEFAULT_BASE_URL = void 0;
3
+ exports.Novence = exports.CONSOLE_INJECT_MARKER = exports.NovenceError = exports.rateLimitRetry = exports.DEFAULT_BASE_URL = void 0;
4
4
  exports.isNovenceClient = isNovenceClient;
5
+ exports.exchangeGithubOidc = exchangeGithubOidc;
5
6
  exports.bootstrapAccount = bootstrapAccount;
6
7
  exports.createDemoAccount = createDemoAccount;
7
8
  exports.claimAccount = claimAccount;
@@ -23,6 +24,46 @@ function resolveBaseUrl(explicit) {
23
24
  const raw = explicit ?? process.env.NOVENCE_BASE_URL ?? exports.DEFAULT_BASE_URL;
24
25
  return raw.replace(/\/$/, "");
25
26
  }
27
+ /**
28
+ * How the SDK handles HTTP 429. The API allows about 100 requests per 10 seconds per IP,
29
+ * and a large directory upload from a shared CI runner can exceed that. A 429 means the
30
+ * request was not processed, so it is safe to send again.
31
+ *
32
+ * Mutable on purpose: set `rateLimitRetry.maxRetries = 0` to turn retries off.
33
+ */
34
+ exports.rateLimitRetry = {
35
+ /** Extra attempts after the first 429. */
36
+ maxRetries: 5,
37
+ /**
38
+ * Longest `Retry-After` worth waiting for, in seconds. Hourly limits (too many
39
+ * sign-ups, too many data writes) answer with a longer wait and are returned to the
40
+ * caller at once instead.
41
+ */
42
+ maxWaitSeconds: 30,
43
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
44
+ };
45
+ /** Seconds to wait before retrying a 429, or null when the caller should get the error. */
46
+ function retryDelaySeconds(res, attempt) {
47
+ if (res.status !== 429 || attempt >= exports.rateLimitRetry.maxRetries)
48
+ return null;
49
+ const header = Number(res.headers.get("retry-after"));
50
+ // No usable header: back off 1, 2, 4, 8… seconds.
51
+ const seconds = Number.isFinite(header) && header > 0 ? header : 2 ** attempt;
52
+ return seconds <= exports.rateLimitRetry.maxWaitSeconds ? seconds : null;
53
+ }
54
+ /** `fetch` that waits out short rate limits. `init` must be replayable (string body). */
55
+ async function fetchWithRateLimitRetry(url, init) {
56
+ for (let attempt = 0;; attempt += 1) {
57
+ const res = await fetch(url, init);
58
+ const wait = retryDelaySeconds(res, attempt);
59
+ if (wait === null)
60
+ return res;
61
+ // Free the connection before sleeping; the body of a 429 says nothing we need.
62
+ await res.body?.cancel().catch(() => undefined);
63
+ // A little jitter so parallel jobs behind one IP do not all come back together.
64
+ await exports.rateLimitRetry.sleep(Math.round(wait * 1000 + Math.random() * 250));
65
+ }
66
+ }
26
67
  /**
27
68
  * Brand for cross-copy identity checks.
28
69
  *
@@ -45,10 +86,21 @@ function isNovenceClient(value) {
45
86
  */
46
87
  class NovenceError extends Error {
47
88
  status;
48
- constructor(message, status) {
89
+ /**
90
+ * On a 402, which wall was hit: `verify` (email OTP), `upgrade` (Checkout/MPP), or
91
+ * `spend_limit` (the account's own overage cap — raise it with billing.setSpendLimit).
92
+ */
93
+ wall;
94
+ /** Machine-readable reason when the API sends one, e.g. `repo_not_connected`. */
95
+ code;
96
+ constructor(message, status, wall, code) {
49
97
  super(message);
50
98
  this.name = "NovenceError";
51
99
  this.status = status;
100
+ if (wall)
101
+ this.wall = wall;
102
+ if (code)
103
+ this.code = code;
52
104
  }
53
105
  }
54
106
  exports.NovenceError = NovenceError;
@@ -92,7 +144,7 @@ class Novence {
92
144
  });
93
145
  }
94
146
  async request(method, path, body) {
95
- const res = await fetch(`${this.baseUrl}${path}`, {
147
+ const res = await fetchWithRateLimitRetry(`${this.baseUrl}${path}`, {
96
148
  method,
97
149
  headers: {
98
150
  Authorization: `Bearer ${this.apiKey}`,
@@ -102,7 +154,8 @@ class Novence {
102
154
  });
103
155
  const data = (await res.json());
104
156
  if (!res.ok) {
105
- throw new NovenceError(data.error ?? `HTTP ${res.status}`, res.status);
157
+ const err = data;
158
+ throw new NovenceError(err.error ?? `HTTP ${res.status}`, res.status, typeof err.wall === "string" ? err.wall : undefined, typeof err.code === "string" ? err.code : undefined);
106
159
  }
107
160
  return data;
108
161
  }
@@ -164,12 +217,21 @@ class Novence {
164
217
  throw new NovenceError(`Upload failed for ${path}`, put.status);
165
218
  return this.files.confirm(projectId, path, type);
166
219
  },
167
- /** Node-only: upload every allowed file under `dir` with root-relative site paths. */
168
- uploadDir: async (projectId, dir) => {
220
+ list: (projectId) => this.request("GET", `/v1/projects/${projectId}/files`),
221
+ /** Remove one file from staging. It leaves the live site on the next deploy. */
222
+ delete: (projectId, path) => this.request("DELETE", `/v1/projects/${projectId}/files/${encodeSitePath(path)}`),
223
+ /**
224
+ * Node-only: make the project's files match `dir`. Uploads every allowed file with a
225
+ * root-relative site path, then removes files the directory no longer has, so a file
226
+ * deleted locally stops being served after the next deploy. `/data/*.json` is never
227
+ * removed (the live-data API writes it). Pass `{ prune: false }` to only add.
228
+ * Dot-files and dot-directories are skipped, except `.well-known/`.
229
+ */
230
+ uploadDir: async (projectId, dir, opts = {}) => {
169
231
  function walk(current) {
170
232
  const out = [];
171
233
  for (const name of (0, node_fs_1.readdirSync)(current)) {
172
- if (name.startsWith("."))
234
+ if (name.startsWith(".") && name !== ".well-known")
173
235
  continue;
174
236
  const full = (0, node_path_1.join)(current, name);
175
237
  if ((0, node_fs_1.statSync)(full).isDirectory())
@@ -191,10 +253,32 @@ class Novence {
191
253
  await this.files.uploadBuffer(projectId, rel, contentType, body);
192
254
  uploaded.push(rel);
193
255
  }
194
- return { uploaded };
256
+ const removed = [];
257
+ const kept = [];
258
+ // Never prune from an empty walk: a wrong directory must not wipe the site.
259
+ if (opts.prune !== false && uploaded.length > 0) {
260
+ const present = new Set(uploaded);
261
+ const { files } = await this.files.list(projectId);
262
+ for (const file of files) {
263
+ if (present.has(file.path))
264
+ continue;
265
+ if (isPruneProtectedPath(file.path)) {
266
+ kept.push(file.path);
267
+ continue;
268
+ }
269
+ await this.files.delete(projectId, file.path);
270
+ removed.push(file.path);
271
+ }
272
+ }
273
+ return { uploaded, removed, kept };
195
274
  },
196
275
  };
197
276
  deployments = {
277
+ /**
278
+ * Start a deploy. `source` records where it came from (shown by `deployments.latest`).
279
+ * Called while another deploy is in progress, it returns that deploy; if files changed
280
+ * since, `queuedRedeploy` is true and a follow-up starts once the first settles.
281
+ */
198
282
  create: (projectId, opts) => this.request("POST", `/v1/projects/${projectId}/deployments`, opts ?? {}),
199
283
  latest: (projectId) => this.request("GET", `/v1/projects/${projectId}/deployments/latest`),
200
284
  rollback: (projectId, opts) => this.request("POST", `/v1/projects/${projectId}/rollback`, opts ?? {}),
@@ -213,6 +297,19 @@ class Novence {
213
297
  force: input.force,
214
298
  });
215
299
  }
300
+ /** Optional push-to-deploy from a GitHub repository. Novence does not clone or build it. */
301
+ git = {
302
+ /** The project's repository connection, or null. */
303
+ get: (projectId) => this.request("GET", `/v1/projects/${projectId}/git`),
304
+ /**
305
+ * Link the project to a repository (`owner/name` or a github.com URL). Only pushes to
306
+ * `branch` (default `main`) deploy. Write the returned `workflow` to
307
+ * `.github/workflows/novence.yml`; it authenticates with GitHub OIDC, so no API key
308
+ * is stored in the repository. Needs a verified email.
309
+ */
310
+ connect: (projectId, input) => this.request("PUT", `/v1/projects/${projectId}/git`, input),
311
+ disconnect: (projectId) => this.request("DELETE", `/v1/projects/${projectId}/git`),
312
+ };
216
313
  domains = {
217
314
  configure: (projectId, hostname, input) => this.request("POST", `/v1/projects/${projectId}/domains`, {
218
315
  hostname,
@@ -243,6 +340,15 @@ class Novence {
243
340
  };
244
341
  billing = {
245
342
  quotas: () => this.request("GET", "/v1/billing/quotas"),
343
+ /** Monthly overage cap, month-to-date overage, and what is paused. */
344
+ spendLimit: () => this.request("GET", "/v1/billing/spend-limit"),
345
+ /**
346
+ * Set or change the monthly overage cap in USD (up to 2 decimals), or pass `null` to
347
+ * remove it. At the cap, anything that would add overage pauses — including live sites
348
+ * once bandwidth is past the included pool — until it is raised or the UTC month resets.
349
+ * `0` means never pay overage.
350
+ */
351
+ setSpendLimit: (limitUsd) => this.request("PUT", "/v1/billing/spend-limit", { limitUsd }),
246
352
  checkout: (input) => this.request("POST", "/v1/billing/checkout", input),
247
353
  portal: (input = {}) => this.request("POST", "/v1/billing/portal", input),
248
354
  /**
@@ -305,6 +411,50 @@ class Novence {
305
411
  };
306
412
  }
307
413
  exports.Novence = Novence;
414
+ /** Percent-encode a site path for a `/files/*` URL, keeping the slashes. */
415
+ function encodeSitePath(path) {
416
+ return path.replace(/^\/+/, "").split("/").map(encodeURIComponent).join("/");
417
+ }
418
+ /** Paths `uploadDir` never prunes: `/data/*.json` belongs to the live-data API. */
419
+ function isPruneProtectedPath(path) {
420
+ return /^\/data\/[^/]+\.json$/i.test(path);
421
+ }
422
+ /**
423
+ * Inside a GitHub Actions job with `permissions: id-token: write`, trade the job's OIDC
424
+ * token for a short-lived, deploy-only key on the project its repository is connected to
425
+ * (`git.connect`). No stored secret. Throws a NovenceError whose `code` says why not:
426
+ * `repo_not_connected`, `branch_not_allowed`, `project_required`, `event_not_allowed`.
427
+ */
428
+ async function exchangeGithubOidc(opts = {}) {
429
+ const env = opts.env ?? process.env;
430
+ const requestUrl = env.ACTIONS_ID_TOKEN_REQUEST_URL;
431
+ const requestToken = env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
432
+ if (!requestUrl || !requestToken) {
433
+ throw new NovenceError("No GitHub OIDC token available. Add `permissions: id-token: write` to the workflow job.", 400, undefined, "oidc_unavailable");
434
+ }
435
+ const base = resolveBaseUrl(opts.baseUrl);
436
+ // The API only accepts tokens minted for it; the audience is its own origin.
437
+ const audience = new URL(base).origin;
438
+ const tokenUrl = new URL(requestUrl);
439
+ tokenUrl.searchParams.set("audience", audience);
440
+ const tokenRes = await fetch(tokenUrl, {
441
+ headers: { Authorization: `Bearer ${requestToken}`, Accept: "application/json" },
442
+ });
443
+ const tokenBody = (await tokenRes.json().catch(() => ({})));
444
+ if (!tokenRes.ok || !tokenBody.value) {
445
+ throw new NovenceError(`GitHub did not issue an OIDC token (HTTP ${tokenRes.status}).`, tokenRes.status || 500, undefined, "oidc_unavailable");
446
+ }
447
+ const res = await fetchWithRateLimitRetry(`${base}/v1/auth/github-oidc`, {
448
+ method: "POST",
449
+ headers: { "Content-Type": "application/json" },
450
+ body: JSON.stringify({ token: tokenBody.value, projectId: opts.projectId }),
451
+ });
452
+ const data = (await readErrorBody(res));
453
+ if (!res.ok) {
454
+ throw new NovenceError(data.error ?? `HTTP ${res.status}`, res.status, undefined, data.code);
455
+ }
456
+ return data;
457
+ }
308
458
  function withMethod(attribution, method) {
309
459
  return { ...attribution, method: attribution?.method ?? method };
310
460
  }
@@ -1,5 +1,23 @@
1
1
  /** Public control plane. */
2
2
  export declare const DEFAULT_BASE_URL = "https://api.novence.ai";
3
+ /**
4
+ * How the SDK handles HTTP 429. The API allows about 100 requests per 10 seconds per IP,
5
+ * and a large directory upload from a shared CI runner can exceed that. A 429 means the
6
+ * request was not processed, so it is safe to send again.
7
+ *
8
+ * Mutable on purpose: set `rateLimitRetry.maxRetries = 0` to turn retries off.
9
+ */
10
+ export declare const rateLimitRetry: {
11
+ /** Extra attempts after the first 429. */
12
+ maxRetries: number;
13
+ /**
14
+ * Longest `Retry-After` worth waiting for, in seconds. Hourly limits (too many
15
+ * sign-ups, too many data writes) answer with a longer wait and are returned to the
16
+ * caller at once instead.
17
+ */
18
+ maxWaitSeconds: number;
19
+ sleep: (ms: number) => Promise<void>;
20
+ };
3
21
  /** True for a Novence client from any copy of this module. */
4
22
  export declare function isNovenceClient(value: unknown): value is Novence;
5
23
  /**
@@ -8,7 +26,14 @@ export declare function isNovenceClient(value: unknown): value is Novence;
8
26
  */
9
27
  export declare class NovenceError extends Error {
10
28
  readonly status: number;
11
- constructor(message: string, status: number);
29
+ /**
30
+ * On a 402, which wall was hit: `verify` (email OTP), `upgrade` (Checkout/MPP), or
31
+ * `spend_limit` (the account's own overage cap — raise it with billing.setSpendLimit).
32
+ */
33
+ readonly wall?: string;
34
+ /** Machine-readable reason when the API sends one, e.g. `repo_not_connected`. */
35
+ readonly code?: string;
36
+ constructor(message: string, status: number, wall?: string, code?: string);
12
37
  }
13
38
  export interface NovenceOptions {
14
39
  apiKey: string;
@@ -74,11 +99,70 @@ export interface ChecksResults {
74
99
  reason?: string;
75
100
  /** Non-blocking findings, e.g. low Lighthouse performance while `enforcePerformance` is off. */
76
101
  warnings?: string[];
102
+ /** The deployment these results were measured from. */
103
+ deploymentId?: string;
104
+ /** Why the page could not be scored. The deploy fails and `lighthouse` is null. */
105
+ measurementError?: string;
77
106
  [key: string]: unknown;
78
107
  }
108
+ /** Where a deployment came from. `verified` means the git fields were read from a GitHub OIDC token. */
109
+ export interface DeploySource {
110
+ kind: "api" | "cli" | "mcp" | "sdk" | "github-actions";
111
+ repository?: string;
112
+ ref?: string;
113
+ sha?: string;
114
+ /** First line of the commit message. */
115
+ message?: string;
116
+ actor?: string;
117
+ runUrl?: string;
118
+ verified?: boolean;
119
+ }
120
+ /** A project's link to a GitHub repository for push-to-deploy. */
121
+ export interface GitConnection {
122
+ provider: "github";
123
+ /** Lower-cased `owner/name`. */
124
+ repository: string;
125
+ /** The only branch that deploys. */
126
+ branch: string;
127
+ /** True once a workflow run from the repository has authenticated. */
128
+ verified: boolean;
129
+ connectedAt: string;
130
+ /** Audience the workflow must request its OIDC token for. */
131
+ audience: string;
132
+ /** Contents for `.github/workflows/novence.yml`. */
133
+ workflow: string;
134
+ }
135
+ /** Result of trading a GitHub Actions OIDC token for a short-lived deploy key. */
136
+ export interface GithubOidcExchange {
137
+ /** Deploy-only key for `projectId`. Expires at `expiresAt` (about 30 minutes). */
138
+ apiKey: string;
139
+ expiresAt: string;
140
+ projectId: string;
141
+ project: {
142
+ id: string;
143
+ name: string;
144
+ suffix: string;
145
+ url: string;
146
+ };
147
+ source: DeploySource;
148
+ }
149
+ export interface UploadDirResult {
150
+ /** Site paths uploaded from the directory. */
151
+ uploaded: string[];
152
+ /** Site paths deleted because the directory no longer has them. Empty with `prune: false`. */
153
+ removed: string[];
154
+ /** Site paths left alone although the directory lacks them (`/data/*.json`). */
155
+ kept: string[];
156
+ }
79
157
  export interface Deployment {
80
158
  id: string;
81
159
  status: DeploymentStatus;
160
+ source?: DeploySource | null;
161
+ /**
162
+ * True while a newer deploy is waiting for this one to settle. Keep polling
163
+ * `deployments.latest`: a deployment with a different id follows.
164
+ */
165
+ queuedRedeploy?: boolean;
82
166
  phase?: DeploymentPhase;
83
167
  /** 1-based place in the check-runner queue while `status` is `queued`; null otherwise. */
84
168
  queuePosition?: number | null;
@@ -181,6 +265,27 @@ export interface Quotas {
181
265
  /** Extra collaborators per project (owner excluded). Free/unverified is 0. */
182
266
  teamSeats: number;
183
267
  }
268
+ /** Monthly overage cap (Pro/Scale). Matches SpendLimitStatus in openapi.yaml. */
269
+ export interface SpendLimitStatus {
270
+ /** Cap in USD. null = no cap. */
271
+ limitUsd: number | null;
272
+ /** Month-to-date overage at list rates (excludes the base plan price). */
273
+ overageUsd: number;
274
+ remainingUsd: number | null;
275
+ /** overage / limit as a whole percent, capped at 100. null when the limit is null or 0. */
276
+ usedPct: number | null;
277
+ /** Only verified Pro/Scale accounts incur overage. A limit on Free is kept for later. */
278
+ applies: boolean;
279
+ reached: boolean;
280
+ /** What is paused right now. `bandwidth_gb` means live sites are paused. */
281
+ paused: Array<"bandwidth_gb" | "check_minutes" | "form_submissions" | "custom_domains">;
282
+ pausedLabels: string[];
283
+ sitesPaused: boolean;
284
+ period: {
285
+ start: string;
286
+ resetsAt: string;
287
+ };
288
+ }
184
289
  export interface ProjectUsage {
185
290
  /** Prefer storage_bytes over storage_gb for exact accounting. */
186
291
  storage_bytes: number;
@@ -258,6 +363,7 @@ export interface AccountSnapshot {
258
363
  emailVerified?: boolean;
259
364
  quotas?: Quotas;
260
365
  usage?: Record<string, number>;
366
+ spendLimit?: SpendLimitStatus;
261
367
  projects?: Array<Record<string, unknown>>;
262
368
  subscription?: {
263
369
  id: string;
@@ -390,14 +496,33 @@ export declare class Novence {
390
496
  uploadBuffer: (projectId: string, path: string, contentType: string | undefined, body: ArrayBuffer | Uint8Array) => Promise<{
391
497
  file: StagingFile;
392
498
  }>;
393
- /** Node-only: upload every allowed file under `dir` with root-relative site paths. */
394
- uploadDir: (projectId: string, dir: string) => Promise<{
395
- uploaded: string[];
499
+ list: (projectId: string) => Promise<{
500
+ files: StagingFile[];
501
+ }>;
502
+ /** Remove one file from staging. It leaves the live site on the next deploy. */
503
+ delete: (projectId: string, path: string) => Promise<{
504
+ deleted: boolean;
396
505
  }>;
506
+ /**
507
+ * Node-only: make the project's files match `dir`. Uploads every allowed file with a
508
+ * root-relative site path, then removes files the directory no longer has, so a file
509
+ * deleted locally stops being served after the next deploy. `/data/*.json` is never
510
+ * removed (the live-data API writes it). Pass `{ prune: false }` to only add.
511
+ * Dot-files and dot-directories are skipped, except `.well-known/`.
512
+ */
513
+ uploadDir: (projectId: string, dir: string, opts?: {
514
+ prune?: boolean;
515
+ }) => Promise<UploadDirResult>;
397
516
  };
398
517
  deployments: {
518
+ /**
519
+ * Start a deploy. `source` records where it came from (shown by `deployments.latest`).
520
+ * Called while another deploy is in progress, it returns that deploy; if files changed
521
+ * since, `queuedRedeploy` is true and a follow-up starts once the first settles.
522
+ */
399
523
  create: (projectId: string, opts?: {
400
524
  force?: boolean;
525
+ source?: Partial<DeploySource>;
401
526
  }) => Promise<{
402
527
  deployment: Deployment;
403
528
  }>;
@@ -420,6 +545,29 @@ export declare class Novence {
420
545
  projectId?: string;
421
546
  force?: boolean;
422
547
  }): Promise<PublishHtmlResult>;
548
+ /** Optional push-to-deploy from a GitHub repository. Novence does not clone or build it. */
549
+ git: {
550
+ /** The project's repository connection, or null. */
551
+ get: (projectId: string) => Promise<{
552
+ connection: GitConnection | null;
553
+ }>;
554
+ /**
555
+ * Link the project to a repository (`owner/name` or a github.com URL). Only pushes to
556
+ * `branch` (default `main`) deploy. Write the returned `workflow` to
557
+ * `.github/workflows/novence.yml`; it authenticates with GitHub OIDC, so no API key
558
+ * is stored in the repository. Needs a verified email.
559
+ */
560
+ connect: (projectId: string, input: {
561
+ repository: string;
562
+ branch?: string;
563
+ }) => Promise<{
564
+ connection: GitConnection;
565
+ }>;
566
+ disconnect: (projectId: string) => Promise<{
567
+ disconnected: boolean;
568
+ repository: string | null;
569
+ }>;
570
+ };
423
571
  domains: {
424
572
  configure: (projectId: string, hostname: string, input?: {
425
573
  primary?: "www" | "apex";
@@ -487,7 +635,17 @@ export declare class Novence {
487
635
  quotas: Quotas;
488
636
  usage: Record<string, number>;
489
637
  bandwidthMetering?: string;
638
+ spendLimit?: SpendLimitStatus;
490
639
  }>;
640
+ /** Monthly overage cap, month-to-date overage, and what is paused. */
641
+ spendLimit: () => Promise<SpendLimitStatus>;
642
+ /**
643
+ * Set or change the monthly overage cap in USD (up to 2 decimals), or pass `null` to
644
+ * remove it. At the cap, anything that would add overage pauses — including live sites
645
+ * once bandwidth is past the included pool — until it is raised or the UTC month resets.
646
+ * `0` means never pay overage.
647
+ */
648
+ setSpendLimit: (limitUsd: number | null) => Promise<SpendLimitStatus>;
491
649
  checkout: (input: {
492
650
  successUrl?: string;
493
651
  cancelUrl?: string;
@@ -562,6 +720,17 @@ export declare class Novence {
562
720
  }>;
563
721
  };
564
722
  }
723
+ /**
724
+ * Inside a GitHub Actions job with `permissions: id-token: write`, trade the job's OIDC
725
+ * token for a short-lived, deploy-only key on the project its repository is connected to
726
+ * (`git.connect`). No stored secret. Throws a NovenceError whose `code` says why not:
727
+ * `repo_not_connected`, `branch_not_allowed`, `project_required`, `event_not_allowed`.
728
+ */
729
+ export declare function exchangeGithubOidc(opts?: {
730
+ baseUrl?: string;
731
+ projectId?: string;
732
+ env?: Record<string, string | undefined>;
733
+ }): Promise<GithubOidcExchange>;
565
734
  export interface SignupAttributionInput {
566
735
  method?: "web" | "mcp" | "cli" | "sdk" | "api";
567
736
  client?: string;
package/dist/esm/index.js CHANGED
@@ -11,6 +11,46 @@ function resolveBaseUrl(explicit) {
11
11
  const raw = explicit ?? process.env.NOVENCE_BASE_URL ?? DEFAULT_BASE_URL;
12
12
  return raw.replace(/\/$/, "");
13
13
  }
14
+ /**
15
+ * How the SDK handles HTTP 429. The API allows about 100 requests per 10 seconds per IP,
16
+ * and a large directory upload from a shared CI runner can exceed that. A 429 means the
17
+ * request was not processed, so it is safe to send again.
18
+ *
19
+ * Mutable on purpose: set `rateLimitRetry.maxRetries = 0` to turn retries off.
20
+ */
21
+ export const rateLimitRetry = {
22
+ /** Extra attempts after the first 429. */
23
+ maxRetries: 5,
24
+ /**
25
+ * Longest `Retry-After` worth waiting for, in seconds. Hourly limits (too many
26
+ * sign-ups, too many data writes) answer with a longer wait and are returned to the
27
+ * caller at once instead.
28
+ */
29
+ maxWaitSeconds: 30,
30
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
31
+ };
32
+ /** Seconds to wait before retrying a 429, or null when the caller should get the error. */
33
+ function retryDelaySeconds(res, attempt) {
34
+ if (res.status !== 429 || attempt >= rateLimitRetry.maxRetries)
35
+ return null;
36
+ const header = Number(res.headers.get("retry-after"));
37
+ // No usable header: back off 1, 2, 4, 8… seconds.
38
+ const seconds = Number.isFinite(header) && header > 0 ? header : 2 ** attempt;
39
+ return seconds <= rateLimitRetry.maxWaitSeconds ? seconds : null;
40
+ }
41
+ /** `fetch` that waits out short rate limits. `init` must be replayable (string body). */
42
+ async function fetchWithRateLimitRetry(url, init) {
43
+ for (let attempt = 0;; attempt += 1) {
44
+ const res = await fetch(url, init);
45
+ const wait = retryDelaySeconds(res, attempt);
46
+ if (wait === null)
47
+ return res;
48
+ // Free the connection before sleeping; the body of a 429 says nothing we need.
49
+ await res.body?.cancel().catch(() => undefined);
50
+ // A little jitter so parallel jobs behind one IP do not all come back together.
51
+ await rateLimitRetry.sleep(Math.round(wait * 1000 + Math.random() * 250));
52
+ }
53
+ }
14
54
  /**
15
55
  * Brand for cross-copy identity checks.
16
56
  *
@@ -33,10 +73,21 @@ export function isNovenceClient(value) {
33
73
  */
34
74
  export class NovenceError extends Error {
35
75
  status;
36
- constructor(message, status) {
76
+ /**
77
+ * On a 402, which wall was hit: `verify` (email OTP), `upgrade` (Checkout/MPP), or
78
+ * `spend_limit` (the account's own overage cap — raise it with billing.setSpendLimit).
79
+ */
80
+ wall;
81
+ /** Machine-readable reason when the API sends one, e.g. `repo_not_connected`. */
82
+ code;
83
+ constructor(message, status, wall, code) {
37
84
  super(message);
38
85
  this.name = "NovenceError";
39
86
  this.status = status;
87
+ if (wall)
88
+ this.wall = wall;
89
+ if (code)
90
+ this.code = code;
40
91
  }
41
92
  }
42
93
  /** Marker in `ConsoleKit.htmlTemplate` to replace with the snapshot + token globals. */
@@ -79,7 +130,7 @@ export class Novence {
79
130
  });
80
131
  }
81
132
  async request(method, path, body) {
82
- const res = await fetch(`${this.baseUrl}${path}`, {
133
+ const res = await fetchWithRateLimitRetry(`${this.baseUrl}${path}`, {
83
134
  method,
84
135
  headers: {
85
136
  Authorization: `Bearer ${this.apiKey}`,
@@ -89,7 +140,8 @@ export class Novence {
89
140
  });
90
141
  const data = (await res.json());
91
142
  if (!res.ok) {
92
- throw new NovenceError(data.error ?? `HTTP ${res.status}`, res.status);
143
+ const err = data;
144
+ throw new NovenceError(err.error ?? `HTTP ${res.status}`, res.status, typeof err.wall === "string" ? err.wall : undefined, typeof err.code === "string" ? err.code : undefined);
93
145
  }
94
146
  return data;
95
147
  }
@@ -151,12 +203,21 @@ export class Novence {
151
203
  throw new NovenceError(`Upload failed for ${path}`, put.status);
152
204
  return this.files.confirm(projectId, path, type);
153
205
  },
154
- /** Node-only: upload every allowed file under `dir` with root-relative site paths. */
155
- uploadDir: async (projectId, dir) => {
206
+ list: (projectId) => this.request("GET", `/v1/projects/${projectId}/files`),
207
+ /** Remove one file from staging. It leaves the live site on the next deploy. */
208
+ delete: (projectId, path) => this.request("DELETE", `/v1/projects/${projectId}/files/${encodeSitePath(path)}`),
209
+ /**
210
+ * Node-only: make the project's files match `dir`. Uploads every allowed file with a
211
+ * root-relative site path, then removes files the directory no longer has, so a file
212
+ * deleted locally stops being served after the next deploy. `/data/*.json` is never
213
+ * removed (the live-data API writes it). Pass `{ prune: false }` to only add.
214
+ * Dot-files and dot-directories are skipped, except `.well-known/`.
215
+ */
216
+ uploadDir: async (projectId, dir, opts = {}) => {
156
217
  function walk(current) {
157
218
  const out = [];
158
219
  for (const name of readdirSync(current)) {
159
- if (name.startsWith("."))
220
+ if (name.startsWith(".") && name !== ".well-known")
160
221
  continue;
161
222
  const full = join(current, name);
162
223
  if (statSync(full).isDirectory())
@@ -178,10 +239,32 @@ export class Novence {
178
239
  await this.files.uploadBuffer(projectId, rel, contentType, body);
179
240
  uploaded.push(rel);
180
241
  }
181
- return { uploaded };
242
+ const removed = [];
243
+ const kept = [];
244
+ // Never prune from an empty walk: a wrong directory must not wipe the site.
245
+ if (opts.prune !== false && uploaded.length > 0) {
246
+ const present = new Set(uploaded);
247
+ const { files } = await this.files.list(projectId);
248
+ for (const file of files) {
249
+ if (present.has(file.path))
250
+ continue;
251
+ if (isPruneProtectedPath(file.path)) {
252
+ kept.push(file.path);
253
+ continue;
254
+ }
255
+ await this.files.delete(projectId, file.path);
256
+ removed.push(file.path);
257
+ }
258
+ }
259
+ return { uploaded, removed, kept };
182
260
  },
183
261
  };
184
262
  deployments = {
263
+ /**
264
+ * Start a deploy. `source` records where it came from (shown by `deployments.latest`).
265
+ * Called while another deploy is in progress, it returns that deploy; if files changed
266
+ * since, `queuedRedeploy` is true and a follow-up starts once the first settles.
267
+ */
185
268
  create: (projectId, opts) => this.request("POST", `/v1/projects/${projectId}/deployments`, opts ?? {}),
186
269
  latest: (projectId) => this.request("GET", `/v1/projects/${projectId}/deployments/latest`),
187
270
  rollback: (projectId, opts) => this.request("POST", `/v1/projects/${projectId}/rollback`, opts ?? {}),
@@ -200,6 +283,19 @@ export class Novence {
200
283
  force: input.force,
201
284
  });
202
285
  }
286
+ /** Optional push-to-deploy from a GitHub repository. Novence does not clone or build it. */
287
+ git = {
288
+ /** The project's repository connection, or null. */
289
+ get: (projectId) => this.request("GET", `/v1/projects/${projectId}/git`),
290
+ /**
291
+ * Link the project to a repository (`owner/name` or a github.com URL). Only pushes to
292
+ * `branch` (default `main`) deploy. Write the returned `workflow` to
293
+ * `.github/workflows/novence.yml`; it authenticates with GitHub OIDC, so no API key
294
+ * is stored in the repository. Needs a verified email.
295
+ */
296
+ connect: (projectId, input) => this.request("PUT", `/v1/projects/${projectId}/git`, input),
297
+ disconnect: (projectId) => this.request("DELETE", `/v1/projects/${projectId}/git`),
298
+ };
203
299
  domains = {
204
300
  configure: (projectId, hostname, input) => this.request("POST", `/v1/projects/${projectId}/domains`, {
205
301
  hostname,
@@ -230,6 +326,15 @@ export class Novence {
230
326
  };
231
327
  billing = {
232
328
  quotas: () => this.request("GET", "/v1/billing/quotas"),
329
+ /** Monthly overage cap, month-to-date overage, and what is paused. */
330
+ spendLimit: () => this.request("GET", "/v1/billing/spend-limit"),
331
+ /**
332
+ * Set or change the monthly overage cap in USD (up to 2 decimals), or pass `null` to
333
+ * remove it. At the cap, anything that would add overage pauses — including live sites
334
+ * once bandwidth is past the included pool — until it is raised or the UTC month resets.
335
+ * `0` means never pay overage.
336
+ */
337
+ setSpendLimit: (limitUsd) => this.request("PUT", "/v1/billing/spend-limit", { limitUsd }),
233
338
  checkout: (input) => this.request("POST", "/v1/billing/checkout", input),
234
339
  portal: (input = {}) => this.request("POST", "/v1/billing/portal", input),
235
340
  /**
@@ -291,6 +396,50 @@ export class Novence {
291
396
  revoke: (id, opts = {}) => this.request("DELETE", `/v1/api-keys/${id}${opts.force ? "?force=true" : ""}`),
292
397
  };
293
398
  }
399
+ /** Percent-encode a site path for a `/files/*` URL, keeping the slashes. */
400
+ function encodeSitePath(path) {
401
+ return path.replace(/^\/+/, "").split("/").map(encodeURIComponent).join("/");
402
+ }
403
+ /** Paths `uploadDir` never prunes: `/data/*.json` belongs to the live-data API. */
404
+ function isPruneProtectedPath(path) {
405
+ return /^\/data\/[^/]+\.json$/i.test(path);
406
+ }
407
+ /**
408
+ * Inside a GitHub Actions job with `permissions: id-token: write`, trade the job's OIDC
409
+ * token for a short-lived, deploy-only key on the project its repository is connected to
410
+ * (`git.connect`). No stored secret. Throws a NovenceError whose `code` says why not:
411
+ * `repo_not_connected`, `branch_not_allowed`, `project_required`, `event_not_allowed`.
412
+ */
413
+ export async function exchangeGithubOidc(opts = {}) {
414
+ const env = opts.env ?? process.env;
415
+ const requestUrl = env.ACTIONS_ID_TOKEN_REQUEST_URL;
416
+ const requestToken = env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
417
+ if (!requestUrl || !requestToken) {
418
+ throw new NovenceError("No GitHub OIDC token available. Add `permissions: id-token: write` to the workflow job.", 400, undefined, "oidc_unavailable");
419
+ }
420
+ const base = resolveBaseUrl(opts.baseUrl);
421
+ // The API only accepts tokens minted for it; the audience is its own origin.
422
+ const audience = new URL(base).origin;
423
+ const tokenUrl = new URL(requestUrl);
424
+ tokenUrl.searchParams.set("audience", audience);
425
+ const tokenRes = await fetch(tokenUrl, {
426
+ headers: { Authorization: `Bearer ${requestToken}`, Accept: "application/json" },
427
+ });
428
+ const tokenBody = (await tokenRes.json().catch(() => ({})));
429
+ if (!tokenRes.ok || !tokenBody.value) {
430
+ throw new NovenceError(`GitHub did not issue an OIDC token (HTTP ${tokenRes.status}).`, tokenRes.status || 500, undefined, "oidc_unavailable");
431
+ }
432
+ const res = await fetchWithRateLimitRetry(`${base}/v1/auth/github-oidc`, {
433
+ method: "POST",
434
+ headers: { "Content-Type": "application/json" },
435
+ body: JSON.stringify({ token: tokenBody.value, projectId: opts.projectId }),
436
+ });
437
+ const data = (await readErrorBody(res));
438
+ if (!res.ok) {
439
+ throw new NovenceError(data.error ?? `HTTP ${res.status}`, res.status, undefined, data.code);
440
+ }
441
+ return data;
442
+ }
294
443
  function withMethod(attribution, method) {
295
444
  return { ...attribution, method: attribution?.method ?? method };
296
445
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@novence/sdk",
3
- "version": "0.4.0",
3
+ "version": "0.6.1",
4
4
  "description": "Official TypeScript SDK for Novence — static site hosting for AI agents. Create projects, upload files, run quality checks, deploy to the edge.",
5
5
  "license": "MIT",
6
6
  "type": "module",