scribase CLI + TypeScript SDK (public edge repo)
Extracted from the private caelum0x/scribase monorepo's packages/scribase-js with a fresh, single-commit history (no core history leaks). The npx scribase CLI and the typed /v1 API client, unchanged except: prepublishOnly simplified (the monorepo-only tarball gitleaks gate dropped), repository/homepage/bugs fields added, and one test that cross-checked embedded template strings against the monorepo's templates/ directory removed (nothing it tested changed; that directory isn't shipped here).
This commit is contained in:
commit
92f7df83c4
32
CHANGELOG.md
Normal file
32
CHANGELOG.md
Normal file
@ -0,0 +1,32 @@
|
||||
# Changelog
|
||||
|
||||
## 0.3.0 (2026-11-11, not yet published)
|
||||
|
||||
- `npx scribase connect [tool...]` writes the Scribase MCP server into every
|
||||
AI coding tool this machine has (Claude Code via `claude mcp add`, Cursor,
|
||||
VS Code, Codex, Windsurf, Zed) in one idempotent command. `--dry-run` shows
|
||||
what would change; `--tool <id>` (repeatable) configures exactly those
|
||||
tools regardless of detection. Never writes a token or secret — every
|
||||
client's own MCP OAuth flow runs on first use instead.
|
||||
|
||||
## 0.2.0 (2026-11-11)
|
||||
|
||||
- `npx scribase init` is temporary-first: with no sign-in it creates a 72-hour
|
||||
temporary project and prints a claim link; `--account`, `--watch` and
|
||||
`scribase doctor` are new.
|
||||
- `npx scribase init` prints the project URL and, for a temporary project, the
|
||||
claim link as soon as the backend is live, before the Vercel push and the
|
||||
client-library install.
|
||||
- `scribase add <capability>` (analytics, deploy, flags, uptime, ai, billing,
|
||||
consent, …) wires one capability into the project and prints proof JSON of
|
||||
the first real event.
|
||||
- `scribase ota deploy|rollback|status` for over-the-air updates, and
|
||||
`scribase migrate` runs the real plan/lint/apply route.
|
||||
- `init` detects SvelteKit and scaffolds its `$env/static/public` client; the
|
||||
generated plain-Node client auto-loads `.env`.
|
||||
- The default region id is `eu-frankfurt` (it names the city, not a hosting
|
||||
provider). Projects created with the earlier `oci-eu-frankfurt-1` label keep
|
||||
working unchanged.
|
||||
- `prepublishOnly` runs `scripts/check-npm-tarball.mjs --gitleaks`: the publish
|
||||
stops if the tarball holds an env file, a key file, a file outside the allow
|
||||
list, or a secret-looking string.
|
||||
202
LICENSE
Normal file
202
LICENSE
Normal file
@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
246
README.md
Normal file
246
README.md
Normal file
@ -0,0 +1,246 @@
|
||||
# scribase
|
||||
|
||||
Supabase gives you a database and sign-in. Scribase is the whole backend for
|
||||
your app: Postgres, Auth, Storage, Realtime, Functions and migrations behind
|
||||
one flat price per project, with copy-on-write branching and an agent-native
|
||||
CLI/SDK/MCP surface built in from day one.
|
||||
|
||||
This repo is the `npx scribase` CLI and the typed, fetch-based TypeScript
|
||||
client for the [Scribase](https://scribase.com) management `/v1` API, both
|
||||
shipped as the single `scribase` npm package. It talks to the same public
|
||||
`https://api.scribase.com` endpoint the dashboard and console use — nothing
|
||||
in this repo runs a database or a control plane itself.
|
||||
|
||||
- **Zero runtime dependencies.** A thin, typed wrapper over `fetch`.
|
||||
- **Contract-first core.** `src/types.gen.ts` is emitted from
|
||||
`api/openapi.yaml` (orgs, memberships, projects, environments, operations,
|
||||
audit, imports, migrations, exports). Newer surfaces (backups, restores,
|
||||
usage, database, queues, functions, account, …) are typed by hand in
|
||||
`src/resources/*.ts` against the exact bodies `crates/control-api` renders;
|
||||
each type's doc comment names the server function it mirrors.
|
||||
- **Async-operation aware.** Every mutation returns an `Operation` to poll, and
|
||||
the client gives you `wait(...)` helpers so "accepted" becomes "done".
|
||||
- **Idempotency + retries built in.** Mutating calls attach an
|
||||
`Idempotency-Key` automatically; 429/503/network failures back off and retry.
|
||||
|
||||
Requires Node >= 22.13 (built-in `fetch`, `crypto.randomUUID`) or any runtime
|
||||
with the Fetch and Web Crypto globals.
|
||||
|
||||
## `npx scribase init`
|
||||
|
||||
The package also ships a `scribase` binary, made for coding agents (Claude
|
||||
Code, Codex, Cursor, Windsurf) and people alike:
|
||||
|
||||
```bash
|
||||
npx scribase init --json # not signed in: a 72-hour temporary project with a claim link
|
||||
# signed in (SCRIBASE_ACCESS_TOKEN or `scribase login`): your account
|
||||
npx scribase init --account # not signed in, but use an account (approve in the browser)
|
||||
npx scribase init --watch # also wait for the app's first request
|
||||
npx scribase sql "create table notes (id bigint generated always as identity primary key, body text)"
|
||||
# run SQL on this folder's project, in one transaction
|
||||
npx scribase doctor # check env vars, keys and the connection; one fix per problem
|
||||
```
|
||||
|
||||
A new project's database is empty, so init's first next step creates a small
|
||||
`notes` table with `npx scribase sql` (row level security on, read-only for
|
||||
the public key) and the second queries it with `supabase.from('notes')`.
|
||||
`sql` holds back statements that remove data until you add `--confirm`.
|
||||
|
||||
Init prints "Live in N s" with the measured time. The claim link carries
|
||||
`?ref=<install id>`, a random id stored in `~/.config/scribase/install-id`
|
||||
(`SCRIBASE_NO_REF=1` sends none). Claiming (sign up + card check) keeps the
|
||||
same URL and keys.
|
||||
|
||||
It detects Next.js, Expo, Vite or plain Node, creates (or reuses) a project,
|
||||
writes the env file with that framework's variable names
|
||||
(`NEXT_PUBLIC_SUPABASE_URL`, `EXPO_PUBLIC_SUPABASE_URL`, `VITE_SUPABASE_URL`,
|
||||
`SUPABASE_URL`, and the anon key; the service-role key only where it cannot
|
||||
reach a client bundle), installs `@supabase/supabase-js`, writes a small
|
||||
client module and prints one JSON object (`ok`, `api_url`, `env_vars`,
|
||||
`client_file`, `claim_url`, `next_steps`, or `ok: false` with an error `code`
|
||||
and a `next` step). Run it again and it reuses the same project.
|
||||
|
||||
When the folder is linked to Vercel (`.vercel/project.json` or
|
||||
`VERCEL_PROJECT_ID`), init also sets the URL and keys on that Vercel project for
|
||||
development, preview and production, using `VERCEL_TOKEN` or the signed-in
|
||||
`vercel` CLI, and reports `vercel: { status, targets }` (`updated`,
|
||||
`not_linked`, `no_credentials`, `failed`). It never fails init; `--no-vercel`
|
||||
turns it off.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
npm install scribase
|
||||
# or
|
||||
pnpm add scribase
|
||||
```
|
||||
|
||||
Working on this repository directly? Clone it and build from source instead:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/caelum0x/scribase-cli.git
|
||||
cd scribase-cli
|
||||
npm install
|
||||
npm run build
|
||||
npx ./dist/cli/index.js --help # or: npm link, then `scribase --help`
|
||||
npm install file:../path/to/scribase-cli # in your app, instead of the npm registry
|
||||
```
|
||||
|
||||
|
||||
## Quick start
|
||||
|
||||
```ts
|
||||
import { ScribaseClient } from 'scribase';
|
||||
|
||||
const scribase = new ScribaseClient({
|
||||
baseUrl: 'https://api.scribase.com', // your installation's management endpoint
|
||||
token: process.env.SCRIBASE_ACCESS_TOKEN ?? '',
|
||||
});
|
||||
|
||||
// Bootstrap an org (idempotent; caller becomes owner), then a project.
|
||||
await scribase.organizations.put('acme', { display_name: 'Acme, Inc.' });
|
||||
await scribase.projects.put('acme', 'store', { region: 'us-east', postgres_major: 17 });
|
||||
|
||||
// Provision production. Mutations are asynchronous.
|
||||
const { operation } = await scribase.environments.create({
|
||||
organization_id: 'acme',
|
||||
project_id: 'store',
|
||||
environment_id: 'production',
|
||||
kind: 'production',
|
||||
data_mode: 'snapshot',
|
||||
region: 'us-east',
|
||||
postgres_major: 17,
|
||||
});
|
||||
await scribase.operations.wait(operation.id, 'acme', {
|
||||
onUpdate: (op) => console.info(`provision: ${op.state}`),
|
||||
});
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
Every method maps to one real route in `crates/control-api/src/http.rs`.
|
||||
|
||||
| Accessor | Methods → endpoints |
|
||||
|---|---|
|
||||
| `client.organizations` | `put`/`get` `/v1/organizations/{id}`, `update` (`PATCH`, rename), `list` `/v1/organizations`, `putMembership`/`listMemberships` `…/memberships`, `scheduleDeletion` (`DELETE`), `get`/`putNotificationSettings`, `listApiKeys`/`createApiKey`/`revokeApiKey` `…/api-keys`, `listPolicies`, `listMcpTools` |
|
||||
| `client.projects` | `put`/`get` `…/projects/{id}`, `list` `…/projects`, `listDomains` `…/domains` |
|
||||
| `client.environments` | `list`/`create` `/v1/environments`, `get`/`delete` `…/{env}`, `suspend`/`resume`/`renew`, `connection` (server-side only), `logs` |
|
||||
| `client.previews` | built on environments: `create`/`list`/`get`/`delete`/`renew` — TTL-swept, `sanitized` by default |
|
||||
| `client.backups` | `list`/`create` `…/environments/{env}/backups`, `get` `…/projects/{p}/backups/{id}?environment=`, `verify` `…/environments/{env}/backups/{id}/verify`, `restore` `…/backups/{id}/restore` |
|
||||
| `client.restores` | `start` — restore-shaped form of `backups.restore`; `list`/`get` `…/environments/{env}/restores[/{id}]`, `waitForCompletion` |
|
||||
| `client.export` | `create` `…/environments/{env}/exports`, `createForProject` `…/projects/{p}/export`, `list` `…/projects/{p}/exports`, `getManifest` `…/exports/{id}`, `downloadUrl`/`download` (signed `…/exports/{id}/download`) |
|
||||
| `client.migrations` | `run` `…/migrations` — plan → lint → apply |
|
||||
| `client.imports` | `create`/`dryRun` `/v1/imports`, `history`/`report` `…/imports` |
|
||||
| `client.usage` | `get` `…/environments/{env}/usage`, `capsNearingLimit`, `billing` `…/organizations/{org}/billing` |
|
||||
| `client.database` | `tables` `…/database/tables`, `query` `…/database/query` (read-only) |
|
||||
| `client.queues` | `list`, `peek`, `create`/`send`/`read`/`archive`/`delete`/`purge` |
|
||||
| `client.functions` | `list`, `deploy`, `invoke` |
|
||||
| `client.auth` | `listUsers`, `listProviders`, `listPolicies` |
|
||||
| `client.storage` / `client.realtime` / `client.metrics` / `client.insights` | read surfaces for the console |
|
||||
| `client.branches` | `list`/`register`/`diff`/`merge`/`linkPullRequest` |
|
||||
| `client.account` | `get`/`update` (`PATCH`) `/v1/account`, `security`, `revokeSession`/`removeFactor`, `enrollFactor`/`verifyFactor` (TOTP), `challenge` (MFA step-up), `listTokens`/`createToken`/`revokeToken` |
|
||||
| `client.operations` | `get` `/v1/operations/{id}`, `wait` |
|
||||
| `client.audit` | `list`, `paginate` over `…/audit-events` |
|
||||
|
||||
## The two money surfaces
|
||||
|
||||
**Verified restore.** Backups become restorable only once the backup worker has
|
||||
verified them (`status: 'available'`); the control plane refuses anything else.
|
||||
A restore always lands in a *different* environment, and the finished record
|
||||
carries its own evidence: relation count, RLS relation count, and the SHA-256
|
||||
of the evidence document.
|
||||
|
||||
```ts
|
||||
import { isRestorable, restoreEvidence } from 'scribase';
|
||||
|
||||
const production = { organizationId: 'acme', projectId: 'store', environmentId: 'production' };
|
||||
const [latest] = (await scribase.backups.list(production)).filter(isRestorable);
|
||||
if (latest) {
|
||||
// Restore into a scratch preview, never over production, to prove the backup.
|
||||
const { restore } = await scribase.backups.restore(production, latest.backup_id, 'restore-check');
|
||||
console.info(restore.id, restore.status); // 'pending' until the restore worker finishes
|
||||
const proof = restoreEvidence(restore); // non-null once status === 'restored'
|
||||
}
|
||||
```
|
||||
|
||||
**Runnable export.** No lock-in: assemble a complete, runnable stack with a
|
||||
signed manifest. The call is synchronous and returns the manifest directly.
|
||||
|
||||
```ts
|
||||
const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'production' };
|
||||
const { manifest, bundleRef } = await scribase.export.create(ref, { format: 'compose' });
|
||||
// `manifest.artifacts[]` carries per-file sha256; `manifest.signature` signs the
|
||||
// manifest; `bundleRef` is where the control plane wrote the bundle.
|
||||
```
|
||||
|
||||
## Migrate an existing project
|
||||
|
||||
The dry-run is the sales tool: it prints exactly what will move and what won't,
|
||||
before anything is written. Acceptance is binding — existing users log in
|
||||
afterward *without resetting passwords*.
|
||||
|
||||
```ts
|
||||
const source = {
|
||||
source: 'supabase' as const,
|
||||
sourceProjectRef: 'abcdefgh',
|
||||
sourceConnectionString: process.env.SOURCE_DB_URL ?? '',
|
||||
sourceServiceKey: process.env.SOURCE_SERVICE_KEY ?? '', // sent once, never logged
|
||||
destination: { organizationId: 'acme', projectId: 'store', environmentId: 'production' },
|
||||
};
|
||||
const plan = await scribase.imports.dryRun(source); // nothing is written
|
||||
const report = await scribase.imports.run(source); // starts it in the background, follows progress, returns the verified report
|
||||
// or: const job = await scribase.imports.createFrom(source); then scribase.imports.progress(job.import_id)
|
||||
```
|
||||
|
||||
## Apply migrations safely
|
||||
|
||||
`plan → lint → apply`. A blocking lint finding (`missing_rls`, `public_grant`,
|
||||
`permissive_policy`, `no_with_check`, `security_definer`) refuses the migration
|
||||
before a single statement runs.
|
||||
|
||||
```ts
|
||||
const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'production' };
|
||||
const result = await scribase.migrations.run(ref, {
|
||||
migrations: [{ version: '20260921120000', name: 'add_notes', up: 'create table ...' }],
|
||||
apply: true,
|
||||
});
|
||||
// result.plan, result.lintFindings, result.applied
|
||||
```
|
||||
|
||||
## Pagination
|
||||
|
||||
```ts
|
||||
for await (const event of scribase.audit.paginate('acme', { limit: 200 })) {
|
||||
console.info(event.sequence, event.action);
|
||||
}
|
||||
```
|
||||
|
||||
## Errors
|
||||
|
||||
Every failure is a typed subclass of `ScribaseError`. API errors carry the
|
||||
parsed RFC 9457 `problem+json` body:
|
||||
|
||||
```ts
|
||||
import { ConflictError, QuotaExceededError } from 'scribase';
|
||||
|
||||
try {
|
||||
await scribase.environments.create(spec);
|
||||
} catch (error) {
|
||||
if (error instanceof QuotaExceededError) {
|
||||
// buy a capacity pack; retry after error.retryAfterSeconds
|
||||
} else if (error instanceof ConflictError) {
|
||||
console.error(error.problem.code, error.requestId);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Regenerating types
|
||||
|
||||
`src/types.gen.ts` is generated; never edit it by hand. `scripts/generate.ts`
|
||||
reads the `api/openapi.yaml` contract from Scribase's main (private) repo, so
|
||||
regenerating it is a Scribase-team-only step — it is not needed to build,
|
||||
test or use this package, since `types.gen.ts` already ships checked in.
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0.
|
||||
65
package.json
Normal file
65
package.json
Normal file
@ -0,0 +1,65 @@
|
||||
{
|
||||
"name": "scribase",
|
||||
"version": "0.3.0",
|
||||
"description": "The npx scribase CLI and a typed, fetch-based TypeScript client for the Scribase /v1 API: an agent-first, flat-priced application cloud that works with the Supabase client libraries.",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"engines": {
|
||||
"node": ">=22.13"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"bin": {
|
||||
"scribase": "./dist/cli/index.js"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./importers": {
|
||||
"types": "./dist/importers/index.d.ts",
|
||||
"import": "./dist/importers/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md",
|
||||
"CHANGELOG.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/caelum0x/scribase-cli.git"
|
||||
},
|
||||
"homepage": "https://scribase.com",
|
||||
"bugs": {
|
||||
"url": "https://github.com/caelum0x/scribase-cli/issues"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"generate": "tsx scripts/generate.ts",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "node --import tsx/esm --test tests/client.test.ts tests/resources.test.ts tests/importers.test.ts tests/cli.test.ts tests/login.test.ts tests/vercel.test.ts tests/front-door.test.ts tests/sql.test.ts tests/migrate.test.ts tests/add.test.ts tests/ota.test.ts tests/connect.test.ts",
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"keywords": [
|
||||
"scribase",
|
||||
"supabase",
|
||||
"supabase-alternative",
|
||||
"postgres",
|
||||
"backend",
|
||||
"control-plane",
|
||||
"sdk",
|
||||
"agent-native"
|
||||
],
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.0",
|
||||
"tsx": "^4.19.0",
|
||||
"typescript": "^5.7.0",
|
||||
"yaml": "^2.6.0"
|
||||
}
|
||||
}
|
||||
339
pnpm-lock.yaml
generated
Normal file
339
pnpm-lock.yaml
generated
Normal file
@ -0,0 +1,339 @@
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
settings:
|
||||
autoInstallPeers: true
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^22.10.0
|
||||
version: 22.20.4
|
||||
tsx:
|
||||
specifier: ^4.19.0
|
||||
version: 4.23.15
|
||||
typescript:
|
||||
specifier: ^5.7.0
|
||||
version: 5.9.3
|
||||
yaml:
|
||||
specifier: ^2.6.0
|
||||
version: 2.9.1
|
||||
|
||||
packages:
|
||||
|
||||
'@esbuild/aix-ppc64@0.28.2':
|
||||
resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ppc64]
|
||||
os: [aix]
|
||||
|
||||
'@esbuild/android-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [android]
|
||||
|
||||
'@esbuild/android-arm@0.28.2':
|
||||
resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm]
|
||||
os: [android]
|
||||
|
||||
'@esbuild/android-x64@0.28.2':
|
||||
resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [android]
|
||||
|
||||
'@esbuild/darwin-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@esbuild/darwin-x64@0.28.2':
|
||||
resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@esbuild/freebsd-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [freebsd]
|
||||
|
||||
'@esbuild/freebsd-x64@0.28.2':
|
||||
resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [freebsd]
|
||||
|
||||
'@esbuild/linux-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-arm@0.28.2':
|
||||
resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-ia32@0.28.2':
|
||||
resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ia32]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-loong64@0.28.2':
|
||||
resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [loong64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-mips64el@0.28.2':
|
||||
resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [mips64el]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-ppc64@0.28.2':
|
||||
resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-riscv64@0.28.2':
|
||||
resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-s390x@0.28.2':
|
||||
resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/linux-x64@0.28.2':
|
||||
resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@esbuild/netbsd-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [netbsd]
|
||||
|
||||
'@esbuild/netbsd-x64@0.28.2':
|
||||
resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [netbsd]
|
||||
|
||||
'@esbuild/openbsd-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [openbsd]
|
||||
|
||||
'@esbuild/openbsd-x64@0.28.2':
|
||||
resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [openbsd]
|
||||
|
||||
'@esbuild/openharmony-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [openharmony]
|
||||
|
||||
'@esbuild/sunos-x64@0.28.2':
|
||||
resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [sunos]
|
||||
|
||||
'@esbuild/win32-arm64@0.28.2':
|
||||
resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@esbuild/win32-ia32@0.28.2':
|
||||
resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
|
||||
'@esbuild/win32-x64@0.28.2':
|
||||
resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==}
|
||||
engines: {node: '>=18'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@types/node@22.20.4':
|
||||
resolution: {integrity: sha512-zJRE40jpHtKqE/C4fgHrAKQLJuSpzEnP9ff9Y7YtoR3Wd2pwqzlekDeEuUQXjRd+QCYnVnNwuJYmhdk9XV8gvA==}
|
||||
|
||||
esbuild@0.28.2:
|
||||
resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==}
|
||||
engines: {node: '>=18'}
|
||||
hasBin: true
|
||||
|
||||
fsevents@2.3.3:
|
||||
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
|
||||
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
|
||||
os: [darwin]
|
||||
|
||||
tsx@4.23.15:
|
||||
resolution: {integrity: sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==}
|
||||
engines: {node: '>=18.0.0'}
|
||||
hasBin: true
|
||||
|
||||
typescript@5.9.3:
|
||||
resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
|
||||
engines: {node: '>=14.17'}
|
||||
hasBin: true
|
||||
|
||||
undici-types@6.21.0:
|
||||
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
|
||||
|
||||
yaml@2.9.1:
|
||||
resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==}
|
||||
engines: {node: '>= 14.6'}
|
||||
hasBin: true
|
||||
|
||||
snapshots:
|
||||
|
||||
'@esbuild/aix-ppc64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/android-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/android-arm@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/android-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/darwin-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/darwin-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/freebsd-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/freebsd-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-arm@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-ia32@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-loong64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-mips64el@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-ppc64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-riscv64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-s390x@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/linux-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/netbsd-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/netbsd-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/openbsd-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/openbsd-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/openharmony-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/sunos-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/win32-arm64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/win32-ia32@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@esbuild/win32-x64@0.28.2':
|
||||
optional: true
|
||||
|
||||
'@types/node@22.20.4':
|
||||
dependencies:
|
||||
undici-types: 6.21.0
|
||||
|
||||
esbuild@0.28.2:
|
||||
optionalDependencies:
|
||||
'@esbuild/aix-ppc64': 0.28.2
|
||||
'@esbuild/android-arm': 0.28.2
|
||||
'@esbuild/android-arm64': 0.28.2
|
||||
'@esbuild/android-x64': 0.28.2
|
||||
'@esbuild/darwin-arm64': 0.28.2
|
||||
'@esbuild/darwin-x64': 0.28.2
|
||||
'@esbuild/freebsd-arm64': 0.28.2
|
||||
'@esbuild/freebsd-x64': 0.28.2
|
||||
'@esbuild/linux-arm': 0.28.2
|
||||
'@esbuild/linux-arm64': 0.28.2
|
||||
'@esbuild/linux-ia32': 0.28.2
|
||||
'@esbuild/linux-loong64': 0.28.2
|
||||
'@esbuild/linux-mips64el': 0.28.2
|
||||
'@esbuild/linux-ppc64': 0.28.2
|
||||
'@esbuild/linux-riscv64': 0.28.2
|
||||
'@esbuild/linux-s390x': 0.28.2
|
||||
'@esbuild/linux-x64': 0.28.2
|
||||
'@esbuild/netbsd-arm64': 0.28.2
|
||||
'@esbuild/netbsd-x64': 0.28.2
|
||||
'@esbuild/openbsd-arm64': 0.28.2
|
||||
'@esbuild/openbsd-x64': 0.28.2
|
||||
'@esbuild/openharmony-arm64': 0.28.2
|
||||
'@esbuild/sunos-x64': 0.28.2
|
||||
'@esbuild/win32-arm64': 0.28.2
|
||||
'@esbuild/win32-ia32': 0.28.2
|
||||
'@esbuild/win32-x64': 0.28.2
|
||||
|
||||
fsevents@2.3.3:
|
||||
optional: true
|
||||
|
||||
tsx@4.23.15:
|
||||
dependencies:
|
||||
esbuild: 0.28.2
|
||||
optionalDependencies:
|
||||
fsevents: 2.3.3
|
||||
|
||||
typescript@5.9.3: {}
|
||||
|
||||
undici-types@6.21.0: {}
|
||||
|
||||
yaml@2.9.1: {}
|
||||
176
scripts/generate.ts
Normal file
176
scripts/generate.ts
Normal file
@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Generate `src/types.gen.ts` from `api/openapi.yaml`.
|
||||
*
|
||||
* A focused, dependency-light OpenAPI 3.1 → TypeScript emitter tailored to the
|
||||
* Scribase management contract: it handles `$ref`, string/integer enums,
|
||||
* objects with required/optional properties, arrays, scalars, and inline
|
||||
* response bodies. It is intentionally not a general-purpose codegen — the
|
||||
* contract is small and stable, and a readable emitter beats a giant dependency.
|
||||
*
|
||||
* Usage: `pnpm generate` (or `tsx scripts/generate.ts [openapi.yaml] [out.ts]`).
|
||||
*/
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { parse } from 'yaml';
|
||||
|
||||
interface SchemaNode {
|
||||
$ref?: string;
|
||||
type?: string;
|
||||
enum?: Array<string | number>;
|
||||
properties?: Record<string, SchemaNode>;
|
||||
required?: string[];
|
||||
items?: SchemaNode;
|
||||
format?: string;
|
||||
description?: string;
|
||||
oneOf?: SchemaNode[];
|
||||
anyOf?: SchemaNode[];
|
||||
}
|
||||
|
||||
interface OpenApiDoc {
|
||||
components?: { schemas?: Record<string, SchemaNode> };
|
||||
paths?: Record<string, Record<string, OperationNode>>;
|
||||
}
|
||||
|
||||
interface OperationNode {
|
||||
operationId?: string;
|
||||
responses?: Record<string, { content?: Record<string, { schema?: SchemaNode }> }>;
|
||||
}
|
||||
|
||||
const HTTP_METHODS = ['get', 'put', 'post', 'delete', 'patch'] as const;
|
||||
|
||||
function refName(ref: string): string {
|
||||
const parts = ref.split('/');
|
||||
const last = parts[parts.length - 1];
|
||||
if (last === undefined || last.length === 0) {
|
||||
throw new Error(`unresolvable $ref: ${ref}`);
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
function pascalCase(input: string): string {
|
||||
return input.replace(/(^|[_-])([a-z])/g, (_, __, ch: string) => ch.toUpperCase());
|
||||
}
|
||||
|
||||
/** Render a schema node as a TypeScript type expression. */
|
||||
function typeExpr(schema: SchemaNode, indent: string): string {
|
||||
if (schema.$ref) {
|
||||
return refName(schema.$ref);
|
||||
}
|
||||
// `oneOf`/`anyOf` become a TS union. The contract uses this for nullable
|
||||
// references (e.g. `ImportVerification | null`), so it must not collapse to
|
||||
// `unknown` — a caller needs to see that the value can be null.
|
||||
const variants = schema.oneOf ?? schema.anyOf;
|
||||
if (variants && variants.length > 0) {
|
||||
const members = variants.map((variant) => typeExpr(variant, indent));
|
||||
return [...new Set(members)].join(' | ');
|
||||
}
|
||||
if (schema.enum && schema.enum.length > 0) {
|
||||
return schema.enum
|
||||
.map((value) => (typeof value === 'string' ? JSON.stringify(value) : String(value)))
|
||||
.join(' | ');
|
||||
}
|
||||
switch (schema.type) {
|
||||
case 'null':
|
||||
return 'null';
|
||||
case 'string':
|
||||
return 'string';
|
||||
case 'integer':
|
||||
case 'number':
|
||||
return 'number';
|
||||
case 'boolean':
|
||||
return 'boolean';
|
||||
case 'array':
|
||||
return `${typeExpr(schema.items ?? { type: 'string' }, indent)}[]`;
|
||||
case 'object':
|
||||
return objectExpr(schema, indent);
|
||||
default:
|
||||
return 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
/** Render an object schema as an inline `{ ... }` type or interface body. */
|
||||
function objectExpr(schema: SchemaNode, indent: string): string {
|
||||
const props = schema.properties ?? {};
|
||||
const required = new Set(schema.required ?? []);
|
||||
const inner = `${indent} `;
|
||||
const lines = Object.entries(props).map(([name, prop]) => {
|
||||
const optional = required.has(name) ? '' : '?';
|
||||
const doc = prop.description ? `${inner}/** ${prop.description} */\n` : '';
|
||||
return `${doc}${inner}${name}${optional}: ${typeExpr(prop, inner)};`;
|
||||
});
|
||||
return `{\n${lines.join('\n')}\n${indent}}`;
|
||||
}
|
||||
|
||||
/** Emit a top-level named declaration for one component schema. */
|
||||
function emitSchema(name: string, schema: SchemaNode): string {
|
||||
const doc = schema.description ? `/** ${schema.description} */\n` : '';
|
||||
if (schema.enum && schema.enum.length > 0 && schema.type !== 'object') {
|
||||
return `${doc}export type ${name} = ${typeExpr(schema, '')};\n`;
|
||||
}
|
||||
if (schema.type === 'object') {
|
||||
return `${doc}export interface ${name} ${objectExpr(schema, '')}\n`;
|
||||
}
|
||||
return `${doc}export type ${name} = ${typeExpr(schema, '')};\n`;
|
||||
}
|
||||
|
||||
/** Collect inline (non-$ref) object response bodies, named after their op. */
|
||||
function emitInlineResponses(paths: OpenApiDoc['paths']): string[] {
|
||||
if (!paths) {
|
||||
return [];
|
||||
}
|
||||
const out: string[] = [];
|
||||
for (const item of Object.values(paths)) {
|
||||
for (const method of HTTP_METHODS) {
|
||||
const op = item[method];
|
||||
if (!op?.operationId || !op.responses) {
|
||||
continue;
|
||||
}
|
||||
for (const [status, response] of Object.entries(op.responses)) {
|
||||
const schema = response.content?.['application/json']?.schema;
|
||||
if (!schema || schema.$ref || schema.type !== 'object' || !schema.properties) {
|
||||
continue;
|
||||
}
|
||||
if (status[0] !== '2') {
|
||||
continue;
|
||||
}
|
||||
const name = `${pascalCase(op.operationId)}Response`;
|
||||
out.push(
|
||||
`/** Inline ${status} body of \`${op.operationId}\`. */\n` +
|
||||
`export interface ${name} ${objectExpr(schema, '')}\n`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function main(): void {
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const inputPath = process.argv[2] ?? resolve(here, '..', '..', '..', 'api', 'openapi.yaml');
|
||||
const outputPath = process.argv[3] ?? resolve(here, '..', 'src', 'types.gen.ts');
|
||||
|
||||
const doc = parse(readFileSync(inputPath, 'utf8')) as OpenApiDoc;
|
||||
const schemas = doc.components?.schemas ?? {};
|
||||
|
||||
const header =
|
||||
'/**\n' +
|
||||
' * DO NOT EDIT BY HAND.\n' +
|
||||
' *\n' +
|
||||
` * Generated from \`api/openapi.yaml\` by \`scripts/generate.ts\`.\n` +
|
||||
' * Run `pnpm generate` to refresh after the contract changes.\n' +
|
||||
' */\n';
|
||||
|
||||
const parts: string[] = [header];
|
||||
for (const [name, schema] of Object.entries(schemas)) {
|
||||
parts.push(emitSchema(name, schema));
|
||||
}
|
||||
parts.push(...emitInlineResponses(doc.paths));
|
||||
|
||||
writeFileSync(outputPath, `${parts.join('\n')}`, 'utf8');
|
||||
process.stdout.write(
|
||||
`Wrote ${Object.keys(schemas).length} schemas to ${outputPath}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
main();
|
||||
433
src/cli/add.ts
Normal file
433
src/cli/add.ts
Normal file
@ -0,0 +1,433 @@
|
||||
/**
|
||||
* `npx scribase add <slot>`: turns a capability on for the project this folder
|
||||
* is connected to and prints its proof (SP-D1).
|
||||
*
|
||||
* npx scribase add email send a proof email to your own address
|
||||
* npx scribase add email --own use your own mail server (entered in the
|
||||
* browser, never here)
|
||||
* npx scribase add --list what can be added, Live or Arriving
|
||||
*
|
||||
* The control plane does the work (`POST .../capabilities/{slot}`) and answers
|
||||
* with `{slot, live, proof:{kind,id,at}}`. When a slot needs a credential, the
|
||||
* answer is a console link instead: the person enters it there, and this
|
||||
* command waits for the proof. No secret is read from or written to the
|
||||
* terminal, the chat, or the env file: only public values are written, and a
|
||||
* value that looks like a secret is refused by name.
|
||||
*/
|
||||
|
||||
import { spawn } from 'node:child_process';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
import { readCredentials } from './credentials.js';
|
||||
import { mergeEnv, publicEnvOnly, readEnvValue } from './envfile.js';
|
||||
import { InitError, STATE_FILE } from './init.js';
|
||||
import { railyardAddHandler } from './capabilities/railyard/index.js';
|
||||
|
||||
const DEFAULT_API_URL = 'https://api.scribase.com';
|
||||
const ENV_FILES = ['.env.local', '.env'] as const;
|
||||
const DEFAULT_WAIT_SECONDS = 600;
|
||||
const POLL_MS = 3_000;
|
||||
|
||||
export interface AddOptions {
|
||||
slot: string | null;
|
||||
list: boolean;
|
||||
own: boolean;
|
||||
resend: boolean;
|
||||
json: boolean;
|
||||
wait: boolean;
|
||||
browser: boolean;
|
||||
waitSeconds: number;
|
||||
}
|
||||
|
||||
export interface AddIo {
|
||||
cwd: string;
|
||||
env: Record<string, string | undefined>;
|
||||
fetch: typeof fetch;
|
||||
readFile: (path: string) => string | null;
|
||||
writeFile: (path: string, contents: string) => void;
|
||||
credentials: () => { apiUrl?: string; token?: string };
|
||||
sleep: (ms: number) => Promise<void>;
|
||||
now: () => number;
|
||||
log: (line: string) => void;
|
||||
openBrowser: (url: string) => void;
|
||||
}
|
||||
|
||||
export interface Proof {
|
||||
kind: string;
|
||||
id: string;
|
||||
at: number;
|
||||
detail?: string | null;
|
||||
}
|
||||
|
||||
export interface CapabilityState {
|
||||
slot: string;
|
||||
title: string;
|
||||
status: 'live' | 'arriving';
|
||||
state: string;
|
||||
live: boolean;
|
||||
provider: string | null;
|
||||
proof: Proof | null;
|
||||
proof_label?: string;
|
||||
connect_url: string | null;
|
||||
next: string | null;
|
||||
env?: Record<string, string>;
|
||||
sent?: boolean;
|
||||
}
|
||||
|
||||
export interface RegistryEntry {
|
||||
slot: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
status: 'live' | 'arriving';
|
||||
}
|
||||
|
||||
export type AddResult =
|
||||
| {
|
||||
ok: true;
|
||||
slot: string;
|
||||
status: 'live' | 'needs_connect';
|
||||
live: boolean;
|
||||
provider: string | null;
|
||||
proof: Proof | null;
|
||||
sent: boolean;
|
||||
connect_url?: string;
|
||||
env_written: string[];
|
||||
env_refused: string[];
|
||||
next: string | null;
|
||||
}
|
||||
| { ok: true; status: 'list'; capabilities: RegistryEntry[] };
|
||||
|
||||
interface ProjectState {
|
||||
organization_id: string;
|
||||
project_id: string;
|
||||
environment_id: string;
|
||||
api_url?: string;
|
||||
}
|
||||
|
||||
const SLOT = /^[a-z][a-z0-9-]{1,31}$/;
|
||||
|
||||
/** Parses `add` arguments. */
|
||||
export function parseAddArgs(argv: string[]): AddOptions {
|
||||
const options: AddOptions = {
|
||||
slot: null,
|
||||
list: false,
|
||||
own: false,
|
||||
resend: false,
|
||||
json: false,
|
||||
wait: true,
|
||||
browser: true,
|
||||
waitSeconds: DEFAULT_WAIT_SECONDS,
|
||||
};
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index] ?? '';
|
||||
if (arg === '--list') options.list = true;
|
||||
else if (arg === '--own') options.own = true;
|
||||
else if (arg === '--resend') options.resend = true;
|
||||
else if (arg === '--json') options.json = true;
|
||||
else if (arg === '--no-wait') options.wait = false;
|
||||
else if (arg === '--no-browser') options.browser = false;
|
||||
else if (arg === '--wait' || arg.startsWith('--wait=')) {
|
||||
const raw = arg.startsWith('--wait=') ? arg.slice('--wait='.length) : argv[++index];
|
||||
const seconds = Number(raw);
|
||||
if (!Number.isInteger(seconds) || seconds < 1 || seconds > 3_600) {
|
||||
throw new InitError('invalid_argument', '--wait takes whole seconds from 1 to 3600');
|
||||
}
|
||||
options.waitSeconds = seconds;
|
||||
} else if (arg.startsWith('--')) {
|
||||
throw new InitError('invalid_argument', `unknown option ${arg}`, 'run `npx scribase add --help`');
|
||||
} else if (options.slot === null) {
|
||||
if (!SLOT.test(arg)) {
|
||||
throw new InitError('invalid_argument', `"${arg}" is not a capability name`, 'run `npx scribase add --list`');
|
||||
}
|
||||
options.slot = arg;
|
||||
} else {
|
||||
throw new InitError('invalid_argument', `unexpected argument ${arg}`);
|
||||
}
|
||||
}
|
||||
if (!options.list && options.slot === null) {
|
||||
throw new InitError('invalid_argument', 'no capability given', 'run `npx scribase add email`, or `--list` to see them all');
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function join(root: string, relative: string): string {
|
||||
return `${root.replace(/\/+$/, '')}/${relative}`;
|
||||
}
|
||||
|
||||
function readProject(io: AddIo): ProjectState {
|
||||
const text = io.readFile(join(io.cwd, STATE_FILE));
|
||||
let state: Partial<ProjectState> | null = null;
|
||||
try {
|
||||
state = text ? (JSON.parse(text) as Partial<ProjectState>) : null;
|
||||
} catch {
|
||||
state = null;
|
||||
}
|
||||
if (!state?.organization_id || !state.project_id || !state.environment_id) {
|
||||
throw new InitError('not_initialized', 'this folder is not connected to a Scribase project', 'run `npx scribase init` here first');
|
||||
}
|
||||
return state as ProjectState;
|
||||
}
|
||||
|
||||
function findToken(io: AddIo): string | undefined {
|
||||
const fromEnv = io.env.SCRIBASE_ACCESS_TOKEN?.trim();
|
||||
if (fromEnv) return fromEnv;
|
||||
for (const file of ENV_FILES) {
|
||||
const contents = io.readFile(join(io.cwd, file));
|
||||
const value = contents ? readEnvValue(contents, 'SCRIBASE_ACCESS_TOKEN')?.trim() : undefined;
|
||||
if (value) return value;
|
||||
}
|
||||
return io.credentials().token;
|
||||
}
|
||||
|
||||
function apiUrlFor(io: AddIo, project?: ProjectState): string {
|
||||
return (io.env.SCRIBASE_API_URL ?? project?.api_url ?? io.credentials().apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
async function call(io: AddIo, url: string, init: { method: 'GET' | 'POST'; token?: string; body?: unknown }): Promise<unknown> {
|
||||
const headers: Record<string, string> = { accept: 'application/json', 'user-agent': 'scribase-add' };
|
||||
if (init.token) headers.authorization = `Bearer ${init.token}`;
|
||||
if (init.body !== undefined) headers['content-type'] = 'application/json';
|
||||
let response: Response;
|
||||
try {
|
||||
response = await io.fetch(url, {
|
||||
method: init.method,
|
||||
headers,
|
||||
...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new InitError('network_error', `could not reach the control plane: ${(error as Error).message}`, 'check your connection or SCRIBASE_API_URL');
|
||||
}
|
||||
const text = await response.text();
|
||||
let body: unknown = null;
|
||||
try {
|
||||
body = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
body = { detail: text.slice(0, 200) };
|
||||
}
|
||||
if (response.status !== 200) {
|
||||
const value = (body ?? {}) as { code?: unknown; detail?: unknown };
|
||||
const code = typeof value.code === 'string' ? value.code : 'request_failed';
|
||||
const detail = typeof value.detail === 'string' ? value.detail : 'the request failed';
|
||||
const next =
|
||||
response.status === 401 || response.status === 403
|
||||
? 'run `npx scribase login` (adding a capability needs an owner or admin)'
|
||||
: code === 'unknown_capability' || code === 'capability_arriving'
|
||||
? 'run `npx scribase add --list`'
|
||||
: undefined;
|
||||
throw new InitError(code, `${detail} (HTTP ${response.status})`, next);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
function asState(body: unknown): CapabilityState {
|
||||
const value = (body ?? {}) as Partial<CapabilityState>;
|
||||
if (typeof value.slot !== 'string' || typeof value.state !== 'string') {
|
||||
throw new InitError('invalid_response', 'the control plane answered with an unexpected shape');
|
||||
}
|
||||
return value as CapabilityState;
|
||||
}
|
||||
|
||||
function capabilityPath(project: ProjectState, slot: string): string {
|
||||
return (
|
||||
`/v1/organizations/${encodeURIComponent(project.organization_id)}` +
|
||||
`/projects/${encodeURIComponent(project.project_id)}` +
|
||||
`/environments/${encodeURIComponent(project.environment_id)}` +
|
||||
`/capabilities/${encodeURIComponent(slot)}`
|
||||
);
|
||||
}
|
||||
|
||||
/** Which env file public values go to: the first one init wrote, else `.env`. */
|
||||
function envFileFor(io: AddIo): string {
|
||||
for (const file of ENV_FILES) {
|
||||
if (io.readFile(join(io.cwd, file)) !== null) return file;
|
||||
}
|
||||
return '.env';
|
||||
}
|
||||
|
||||
function writePublicEnv(io: AddIo, values: Record<string, string> | undefined): { written: string[]; refused: string[] } {
|
||||
const { safe, refused } = publicEnvOnly(values ?? {});
|
||||
const written = Object.keys(safe);
|
||||
if (written.length > 0) {
|
||||
const file = join(io.cwd, envFileFor(io));
|
||||
io.writeFile(file, mergeEnv(io.readFile(file) ?? '', safe));
|
||||
}
|
||||
return { written, refused };
|
||||
}
|
||||
|
||||
/** Runs `add` and returns its result. Never returns or logs a secret. */
|
||||
export async function runAdd(options: AddOptions, io: AddIo): Promise<AddResult> {
|
||||
if (options.list) {
|
||||
let connected: ProjectState | undefined;
|
||||
try {
|
||||
connected = readProject(io);
|
||||
} catch {
|
||||
connected = undefined;
|
||||
}
|
||||
const body = (await call(io, `${apiUrlFor(io, connected)}/v1/capabilities`, { method: 'GET' })) as { capabilities?: RegistryEntry[] };
|
||||
const capabilities = (body.capabilities ?? []).map(({ slot, title, summary, status }) => ({ slot, title, summary, status }));
|
||||
return { ok: true, status: 'list', capabilities };
|
||||
}
|
||||
const slot = options.slot ?? '';
|
||||
// Wave P carve-out (PY lane): a Railyard slot with its own local handler.
|
||||
const local = railyardAddHandler(slot);
|
||||
if (local) return local(options, io);
|
||||
const project = readProject(io);
|
||||
const token = findToken(io);
|
||||
if (!token) {
|
||||
throw new InitError('not_signed_in', 'no Scribase token for this folder', 'run `npx scribase login`, or `npx scribase init` here');
|
||||
}
|
||||
const url = `${apiUrlFor(io, project)}${capabilityPath(project, slot)}`;
|
||||
const startedAt = Math.floor(io.now() / 1000);
|
||||
const body: Record<string, unknown> = {};
|
||||
if (options.own) body.provider = 'own';
|
||||
if (options.resend) body.resend = true;
|
||||
let state = asState(await call(io, url, { method: 'POST', token, body }));
|
||||
let sent = state.sent === true;
|
||||
|
||||
if (state.state === 'needs_connect' && state.connect_url) {
|
||||
io.log(`Open this link to finish in the browser (nothing to type here): ${state.connect_url}`);
|
||||
if (options.browser) io.openBrowser(state.connect_url);
|
||||
if (!options.wait) {
|
||||
return {
|
||||
ok: true,
|
||||
slot,
|
||||
status: 'needs_connect',
|
||||
live: false,
|
||||
provider: null,
|
||||
proof: state.proof,
|
||||
sent: false,
|
||||
connect_url: state.connect_url,
|
||||
env_written: [],
|
||||
env_refused: [],
|
||||
next: `finish on the connect page, then run \`npx scribase add ${slot}\` again`,
|
||||
};
|
||||
}
|
||||
const deadline = io.now() + options.waitSeconds * 1_000;
|
||||
io.log('Waiting for the proof...');
|
||||
for (;;) {
|
||||
await io.sleep(POLL_MS);
|
||||
state = asState(await call(io, url, { method: 'GET', token }));
|
||||
if (state.state === 'live' && state.proof && state.proof.at >= startedAt) {
|
||||
sent = true;
|
||||
break;
|
||||
}
|
||||
if (io.now() >= deadline) {
|
||||
throw new InitError(
|
||||
'connect_timeout',
|
||||
`no proof arrived within ${options.waitSeconds} s`,
|
||||
`finish on ${state.connect_url ?? 'the connect page'}, then run \`npx scribase add ${slot}\` again`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
const env = writePublicEnv(io, state.env);
|
||||
return {
|
||||
ok: true,
|
||||
slot,
|
||||
status: state.state === 'live' ? 'live' : 'needs_connect',
|
||||
live: state.live,
|
||||
provider: state.provider,
|
||||
proof: state.proof,
|
||||
sent,
|
||||
...(state.connect_url ? { connect_url: state.connect_url } : {}),
|
||||
env_written: env.written,
|
||||
env_refused: env.refused,
|
||||
next: state.next,
|
||||
};
|
||||
}
|
||||
|
||||
/** The human-readable output of {@link runAdd}. */
|
||||
export function formatAdd(result: AddResult): string {
|
||||
if (result.status === 'list') {
|
||||
const lines = ['Capabilities:'];
|
||||
for (const entry of result.capabilities) {
|
||||
lines.push(` ${entry.slot.padEnd(12)} ${entry.status === 'live' ? 'Live ' : 'Arriving'} ${entry.summary}`);
|
||||
}
|
||||
lines.push('', 'Add one with `npx scribase add <name>`.', '');
|
||||
return lines.join('\n');
|
||||
}
|
||||
const lines: string[] = [];
|
||||
if (result.status === 'live') {
|
||||
lines.push(`${result.slot} is live${result.provider ? ` (${result.provider === 'own' ? 'your mail server' : 'Scribase'})` : ''}.`);
|
||||
} else {
|
||||
lines.push(`${result.slot} is not on yet.`);
|
||||
}
|
||||
if (result.proof) {
|
||||
const when = new Date(result.proof.at * 1000).toISOString();
|
||||
const detail = result.proof.detail ? ` to ${result.proof.detail}` : '';
|
||||
lines.push(` proof ${result.proof.kind} #${result.proof.id}${detail} at ${when}${result.sent ? ' (just now)' : ''}`);
|
||||
}
|
||||
if (result.env_written.length > 0) lines.push(` env wrote ${result.env_written.join(', ')}`);
|
||||
if (result.env_refused.length > 0) lines.push(` env refused (secret): ${result.env_refused.join(', ')}`);
|
||||
if (result.connect_url && result.status !== 'live') lines.push(` connect ${result.connect_url}`);
|
||||
if (result.next) lines.push(` next ${result.next}`);
|
||||
lines.push('');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export const ADD_HELP = `Usage: npx scribase add <capability> [--own] [--resend] [--json] [--no-wait] [--no-browser] [--wait <seconds>]
|
||||
npx scribase add --list [--json]
|
||||
|
||||
Turns a capability on for the project this folder is connected to, and prints
|
||||
its proof (for email: a real email sent to your own address, with its log id).
|
||||
A capability that needs a provider credential (--own for your own mail
|
||||
server) prints a console link: enter the credential there, never here. This
|
||||
command waits for the proof (up to 10 minutes; --wait to change). Only public
|
||||
values are written to the env file; secrets are never printed or written.
|
||||
`;
|
||||
|
||||
/** Entry point for the `add` command; returns the exit code. */
|
||||
export async function addMain(argv: string[], io: AddIo, write: (text: string) => void): Promise<number> {
|
||||
if (argv.includes('--help') || argv.includes('-h')) {
|
||||
write(ADD_HELP);
|
||||
return 0;
|
||||
}
|
||||
const json = argv.includes('--json');
|
||||
try {
|
||||
const result = await runAdd(parseAddArgs(argv), io);
|
||||
write(json ? `${JSON.stringify(result)}\n` : formatAdd(result));
|
||||
return result.status === 'needs_connect' ? 3 : 0;
|
||||
} catch (error) {
|
||||
const failure =
|
||||
error instanceof InitError
|
||||
? { code: error.code, message: error.message, next: error.next ?? null }
|
||||
: { code: 'unexpected_error', message: (error as Error).message, next: null };
|
||||
write(json ? `${JSON.stringify({ ok: false, error: failure })}\n` : `scribase add: ${failure.message}\n${failure.next ? ` next: ${failure.next}\n` : ''}`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
function openBrowser(url: string): void {
|
||||
const [command, args] =
|
||||
process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
|
||||
try {
|
||||
spawn(command as string, args as string[], { stdio: 'ignore', detached: true }).unref();
|
||||
} catch {
|
||||
// The link is printed anyway.
|
||||
}
|
||||
}
|
||||
|
||||
/** The real-process IO for `add`. In --json mode stdout carries one JSON document; notes go to stderr. */
|
||||
export function nodeAddIo(json: boolean): AddIo {
|
||||
return {
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
fetch: globalThis.fetch.bind(globalThis),
|
||||
readFile: (path) => (existsSync(path) ? readFileSync(path, 'utf8') : null),
|
||||
writeFile: (path, contents) => {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, contents, { mode: 0o600 });
|
||||
},
|
||||
credentials: () => readCredentials(process.env),
|
||||
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
||||
now: () => Date.now(),
|
||||
log: (line) => (json ? process.stderr.write(`${line}\n`) : process.stdout.write(`${line}\n`)),
|
||||
openBrowser,
|
||||
};
|
||||
}
|
||||
|
||||
/** `npx scribase add ...` as the CLI runs it (the one line \`index.ts\` needs). */
|
||||
export function addCommand(argv: string[]): Promise<number> {
|
||||
return addMain(argv, nodeAddIo(argv.includes('--json')), (text) => process.stdout.write(text));
|
||||
}
|
||||
13
src/cli/aliases.ts
Normal file
13
src/cli/aliases.ts
Normal file
@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Command aliases of the `scribase` npm binary (Wave P PS2.0, hand-off P-Y4).
|
||||
*
|
||||
* `npx scribase deploy [...]` is `npx scribase add deploy [...]`: the Railyard
|
||||
* deploy slot, which links on first use and then deploys this folder.
|
||||
*/
|
||||
|
||||
/** The argv the CLI runs for `argv`, with an alias expanded. */
|
||||
export function expandAlias(argv: readonly string[]): string[] {
|
||||
const [command, ...rest] = argv;
|
||||
if (command === 'deploy') return ['add', 'deploy', ...rest];
|
||||
return [...argv];
|
||||
}
|
||||
373
src/cli/capabilities/ota.ts
Normal file
373
src/cli/capabilities/ota.ts
Normal file
@ -0,0 +1,373 @@
|
||||
/**
|
||||
* `npx scribase ota <deploy|rollback|status>`: over-the-air updates for the
|
||||
* app in this folder (PS3.1), on the project `npx scribase init` connected.
|
||||
*
|
||||
* npx scribase ota deploy -p ios [-c production] [-m "message"] [-r 25]
|
||||
* npx scribase ota rollback -p android [-c production]
|
||||
* npx scribase ota status
|
||||
*
|
||||
* `deploy` sets OTA up on the environment when it is not yet (the schema, the
|
||||
* private bucket and the update-check function), writes `hot-updater.config.ts`
|
||||
* when the folder has none, then runs the unmodified `hot-updater deploy` CLI
|
||||
* (MIT) with the environment's URL and secret key in the child process only:
|
||||
* the key is never printed, logged or written to a file. The update URL the
|
||||
* app reads (`EXPO_PUBLIC_HOT_UPDATER_URL`) is written to the env file, a
|
||||
* public value. After the upload it reads the release back as proof.
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
import { readCredentials } from '../credentials.js';
|
||||
|
||||
import { mergeEnv, publicEnvOnly, readEnvValue } from '../envfile.js';
|
||||
import { InitError, STATE_FILE } from '../init.js';
|
||||
|
||||
const DEFAULT_API_URL = 'https://api.scribase.com';
|
||||
const ENV_FILES = ['.env.local', '.env'] as const;
|
||||
export const CONFIG_FILE = 'hot-updater.config.ts';
|
||||
export const BUCKET = 'ota-bundles';
|
||||
/** The hot-updater CLI, pinned to the protocol the update-check function speaks. */
|
||||
export const HOT_UPDATER_CLI = ['npx', '--yes', 'hot-updater@0.36.16'] as const;
|
||||
|
||||
export type Platform = 'ios' | 'android';
|
||||
|
||||
export interface OtaOptions {
|
||||
action: 'deploy' | 'rollback' | 'status';
|
||||
platform: Platform | null;
|
||||
channel: string;
|
||||
/** Extra `hot-updater deploy` flags, passed through as written. */
|
||||
passthrough: string[];
|
||||
json: boolean;
|
||||
}
|
||||
|
||||
export interface OtaIo {
|
||||
cwd: string;
|
||||
env: Record<string, string | undefined>;
|
||||
fetch: typeof fetch;
|
||||
readFile: (path: string) => string | null;
|
||||
writeFile: (path: string, contents: string) => void;
|
||||
credentials: () => { apiUrl?: string; token?: string };
|
||||
log: (line: string) => void;
|
||||
/** Runs a command; resolves with its exit code. `env` holds extra variables. */
|
||||
run: (command: string, args: string[], env: Record<string, string>) => Promise<number>;
|
||||
}
|
||||
|
||||
export interface Release {
|
||||
id: string;
|
||||
platform: Platform;
|
||||
channel: string;
|
||||
target_app_version: string | null;
|
||||
fingerprint_hash: string | null;
|
||||
enabled: boolean;
|
||||
force_update: boolean;
|
||||
rollout_percent: number;
|
||||
message: string | null;
|
||||
created_at_epoch_seconds: number;
|
||||
}
|
||||
|
||||
export interface OtaStatus {
|
||||
enabled: boolean;
|
||||
conflict: boolean;
|
||||
update_url: string | null;
|
||||
bucket: string;
|
||||
releases: number;
|
||||
latest: Release[];
|
||||
}
|
||||
|
||||
export type OtaResult =
|
||||
| { ok: true; action: 'status'; status: OtaStatus }
|
||||
| { ok: true; action: 'rollback'; turned_off: string; now_serving: string | null; platform: Platform; channel: string }
|
||||
| { ok: true; action: 'deploy'; release: Release | null; set_up: boolean; config_written: boolean; env_written: string[] };
|
||||
|
||||
const CHANNEL = /^[A-Za-z0-9._-]{1,64}$/;
|
||||
|
||||
/** Parses `ota` arguments. */
|
||||
export function parseOtaArgs(argv: string[]): OtaOptions {
|
||||
const [action, ...rest] = argv;
|
||||
if (action !== 'deploy' && action !== 'rollback' && action !== 'status') {
|
||||
throw new InitError('invalid_argument', 'say what to do: deploy, rollback or status', 'run `npx scribase ota deploy -p ios`');
|
||||
}
|
||||
let platform: Platform | null = null;
|
||||
let channel = 'production';
|
||||
let json = false;
|
||||
const passthrough: string[] = [];
|
||||
for (let index = 0; index < rest.length; index += 1) {
|
||||
const arg = rest[index] ?? '';
|
||||
const value = () => {
|
||||
const next = rest[index + 1];
|
||||
if (next === undefined || next.startsWith('-')) throw new InitError('invalid_argument', `${arg} needs a value`);
|
||||
index += 1;
|
||||
return next;
|
||||
};
|
||||
if (arg === '-p' || arg === '--platform') {
|
||||
const chosen = value();
|
||||
if (chosen !== 'ios' && chosen !== 'android') throw new InitError('invalid_argument', 'platform must be ios or android');
|
||||
platform = chosen;
|
||||
} else if (arg === '-c' || arg === '--channel') {
|
||||
channel = value();
|
||||
if (!CHANNEL.test(channel)) throw new InitError('invalid_argument', 'channel must be letters, digits, ".", "_" or "-"');
|
||||
} else if (arg === '--json') {
|
||||
json = true;
|
||||
} else if (action === 'deploy' && ['-m', '--message', '-r', '--rollout', '-t', '--target-app-version'].includes(arg)) {
|
||||
passthrough.push(arg, value());
|
||||
} else if (action === 'deploy' && ['-f', '--force-update', '-d', '--disabled'].includes(arg)) {
|
||||
passthrough.push(arg);
|
||||
} else {
|
||||
throw new InitError('invalid_argument', `unknown option ${arg}`, 'run `npx scribase ota --help`');
|
||||
}
|
||||
}
|
||||
if (action !== 'status' && !platform) {
|
||||
throw new InitError('invalid_argument', `ota ${action} needs a platform`, `run \`npx scribase ota ${action} -p ios\` (or android)`);
|
||||
}
|
||||
return { action, platform, channel, passthrough, json };
|
||||
}
|
||||
|
||||
/** The config the hot-updater CLI reads, for an Expo app on Scribase. */
|
||||
export const CONFIG_TEMPLATE = `import { expo } from '@hot-updater/expo';
|
||||
import { supabaseDatabase, supabaseStorage } from '@hot-updater/supabase';
|
||||
import { defineConfig } from 'hot-updater';
|
||||
|
||||
// Over-the-air updates stored in your Scribase project. \`npx scribase ota deploy\`
|
||||
// sets HOT_UPDATER_SUPABASE_URL and the secret key for the upload only; never
|
||||
// put the secret key in this file or in your app.
|
||||
const supabaseUrl = process.env.HOT_UPDATER_SUPABASE_URL!;
|
||||
const supabaseServiceRoleKey = process.env.HOT_UPDATER_SUPABASE_SERVICE_ROLE_KEY!;
|
||||
|
||||
export default defineConfig({
|
||||
build: expo(),
|
||||
storage: supabaseStorage({ supabaseUrl, supabaseServiceRoleKey, bucketName: '${BUCKET}' }),
|
||||
database: supabaseDatabase({ supabaseUrl, supabaseServiceRoleKey }),
|
||||
updateStrategy: 'appVersion',
|
||||
});
|
||||
`;
|
||||
|
||||
interface ProjectState {
|
||||
organization_id: string;
|
||||
project_id: string;
|
||||
environment_id: string;
|
||||
api_url?: string;
|
||||
}
|
||||
|
||||
const joinPath = (root: string, relative: string) => `${root.replace(/\/+$/, '')}/${relative}`;
|
||||
|
||||
function readProject(io: OtaIo): ProjectState {
|
||||
const text = io.readFile(joinPath(io.cwd, STATE_FILE));
|
||||
let state: Partial<ProjectState> | null = null;
|
||||
try {
|
||||
state = text ? (JSON.parse(text) as Partial<ProjectState>) : null;
|
||||
} catch {
|
||||
state = null;
|
||||
}
|
||||
if (!state?.organization_id || !state.project_id || !state.environment_id) {
|
||||
throw new InitError('not_initialized', 'this folder is not connected to a Scribase project', 'run `npx scribase init` here first');
|
||||
}
|
||||
return state as ProjectState;
|
||||
}
|
||||
|
||||
function findToken(io: OtaIo): string | undefined {
|
||||
const fromEnv = io.env.SCRIBASE_ACCESS_TOKEN?.trim();
|
||||
if (fromEnv) return fromEnv;
|
||||
for (const file of ENV_FILES) {
|
||||
const contents = io.readFile(joinPath(io.cwd, file));
|
||||
const value = contents ? readEnvValue(contents, 'SCRIBASE_ACCESS_TOKEN')?.trim() : undefined;
|
||||
if (value) return value;
|
||||
}
|
||||
return io.credentials().token;
|
||||
}
|
||||
|
||||
type Call = (method: 'GET' | 'POST', suffix: string, body?: unknown) => Promise<unknown>;
|
||||
|
||||
function client(io: OtaIo, project: ProjectState): { call: Call; environmentPath: string } {
|
||||
const token = findToken(io);
|
||||
if (!token) throw new InitError('not_signed_in', 'no Scribase token for this folder', 'run `npx scribase login`');
|
||||
const apiUrl = (io.env.SCRIBASE_API_URL ?? project.api_url ?? io.credentials().apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, '');
|
||||
const environmentPath =
|
||||
`/v1/organizations/${encodeURIComponent(project.organization_id)}` +
|
||||
`/projects/${encodeURIComponent(project.project_id)}` +
|
||||
`/environments/${encodeURIComponent(project.environment_id)}`;
|
||||
const call: Call = async (method, suffix, body) => {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await io.fetch(`${apiUrl}${environmentPath}${suffix}`, {
|
||||
method,
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
authorization: `Bearer ${token}`,
|
||||
'user-agent': 'scribase-ota',
|
||||
...(body === undefined ? {} : { 'content-type': 'application/json' }),
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new InitError('network_error', `could not reach ${apiUrl}: ${(error as Error).message}`);
|
||||
}
|
||||
const text = await response.text();
|
||||
let parsed: unknown = null;
|
||||
try {
|
||||
parsed = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
parsed = null;
|
||||
}
|
||||
if (!response.ok) {
|
||||
const value = (parsed ?? {}) as { code?: unknown; detail?: unknown };
|
||||
throw new InitError(
|
||||
typeof value.code === 'string' ? value.code : 'request_failed',
|
||||
`${typeof value.detail === 'string' ? value.detail : 'the request failed'} (HTTP ${response.status})`,
|
||||
response.status === 401 || response.status === 403 ? 'run `npx scribase login`' : undefined,
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
return { call, environmentPath };
|
||||
}
|
||||
|
||||
function envFile(io: OtaIo): string {
|
||||
for (const file of ENV_FILES) {
|
||||
if (io.readFile(joinPath(io.cwd, file)) !== null) return joinPath(io.cwd, file);
|
||||
}
|
||||
return joinPath(io.cwd, '.env');
|
||||
}
|
||||
|
||||
async function deploy(options: OtaOptions, io: OtaIo, call: Call): Promise<OtaResult> {
|
||||
let status = (await call('GET', '/ota')) as OtaStatus;
|
||||
let setUp = false;
|
||||
if (status.conflict) {
|
||||
throw new InitError('ota_table_conflict', 'this database has its own public.bundles table; OTA updates need that name', 'rename your table, then run this again');
|
||||
}
|
||||
if (!status.enabled) {
|
||||
io.log('Setting up over-the-air updates in this environment...');
|
||||
status = (await call('POST', '/ota')) as OtaStatus;
|
||||
setUp = true;
|
||||
}
|
||||
const keys = (await call('GET', '/api-keys')) as { api_url?: string; secret_key?: string | null; service_role_key?: string | null };
|
||||
const secret = keys.secret_key ?? keys.service_role_key;
|
||||
if (!keys.api_url || !secret) {
|
||||
throw new InitError('forbidden', 'your role cannot read this environment\'s secret key, which the upload needs', 'ask an owner, admin or developer to run the deploy');
|
||||
}
|
||||
const configPath = joinPath(io.cwd, CONFIG_FILE);
|
||||
const configWritten = io.readFile(configPath) === null;
|
||||
if (configWritten) io.writeFile(configPath, CONFIG_TEMPLATE);
|
||||
const envWritten: string[] = [];
|
||||
if (status.update_url) {
|
||||
const { safe } = publicEnvOnly({ EXPO_PUBLIC_HOT_UPDATER_URL: status.update_url });
|
||||
const file = envFile(io);
|
||||
const current = io.readFile(file) ?? '';
|
||||
if (readEnvValue(current, 'EXPO_PUBLIC_HOT_UPDATER_URL') !== status.update_url) {
|
||||
io.writeFile(file, mergeEnv(current, safe));
|
||||
envWritten.push(...Object.keys(safe));
|
||||
}
|
||||
}
|
||||
const [command, ...prefix] = HOT_UPDATER_CLI;
|
||||
const args = [...prefix, 'deploy', '-p', options.platform as Platform, '-c', options.channel, ...options.passthrough];
|
||||
const code = await io.run(command, args, {
|
||||
HOT_UPDATER_SUPABASE_URL: keys.api_url.replace(/\/+$/, ''),
|
||||
HOT_UPDATER_SUPABASE_SERVICE_ROLE_KEY: secret,
|
||||
HOT_UPDATER_SUPABASE_BUCKET_NAME: BUCKET,
|
||||
});
|
||||
if (code !== 0) {
|
||||
throw new InitError('deploy_failed', `hot-updater deploy exited with code ${code}`, 'read its output above; nothing was published if it failed before the upload');
|
||||
}
|
||||
const after = (await call('GET', '/ota')) as OtaStatus;
|
||||
const release = after.latest.find((entry) => entry.platform === options.platform && entry.channel === options.channel) ?? null;
|
||||
return { ok: true, action: 'deploy', release, set_up: setUp, config_written: configWritten, env_written: envWritten };
|
||||
}
|
||||
|
||||
/** Runs one `ota` action against this folder's project. */
|
||||
export async function runOta(options: OtaOptions, io: OtaIo): Promise<OtaResult> {
|
||||
const { call } = client(io, readProject(io));
|
||||
if (options.action === 'status') return { ok: true, action: 'status', status: (await call('GET', '/ota')) as OtaStatus };
|
||||
if (options.action === 'rollback') {
|
||||
const answer = (await call('POST', '/ota/rollback', { platform: options.platform, channel: options.channel })) as {
|
||||
turned_off: string;
|
||||
now_serving: string | null;
|
||||
};
|
||||
return { ok: true, action: 'rollback', turned_off: answer.turned_off, now_serving: answer.now_serving, platform: options.platform as Platform, channel: options.channel };
|
||||
}
|
||||
return deploy(options, io, call);
|
||||
}
|
||||
|
||||
const describe = (release: Release) =>
|
||||
`${release.platform} ${release.channel}: ${release.id} (${release.enabled ? `on for ${release.rollout_percent}% of devices` : 'off'}${
|
||||
release.target_app_version ? `, app ${release.target_app_version}` : ''
|
||||
})`;
|
||||
|
||||
/** Human output. */
|
||||
export function formatOta(result: OtaResult): string {
|
||||
if (result.action === 'status') {
|
||||
const status = result.status;
|
||||
if (!status.enabled) {
|
||||
return status.conflict
|
||||
? 'OTA updates are not set up: this database has its own public.bundles table.\n'
|
||||
: 'OTA updates are not set up yet. Run `npx scribase ota deploy -p ios` to set them up and publish.\n';
|
||||
}
|
||||
const lines = [`OTA updates are on. Update URL: ${status.update_url ?? 'unknown'}`, `${status.releases} release(s).`];
|
||||
for (const release of status.latest) lines.push(` ${describe(release)}`);
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
if (result.action === 'rollback') {
|
||||
const target = result.now_serving ? `release ${result.now_serving}` : "the bundle built into the app";
|
||||
return `Turned off ${result.turned_off}. ${result.platform} devices on ${result.channel} go back to ${target} on their next launch.\n`;
|
||||
}
|
||||
const lines: string[] = [];
|
||||
if (result.set_up) lines.push('Set up over-the-air updates in this environment.');
|
||||
if (result.config_written) lines.push(`Wrote ${CONFIG_FILE}.`);
|
||||
if (result.env_written.length) lines.push(`Wrote ${result.env_written.join(', ')} to your env file.`);
|
||||
lines.push(result.release ? `Published. ${describe(result.release)}` : 'Published; the release will show in `npx scribase ota status`.');
|
||||
lines.push('Installed builds take it on their next launch.');
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
|
||||
export const OTA_HELP = `Usage: npx scribase ota <deploy|rollback|status> [options]
|
||||
|
||||
deploy -p <ios|android> set OTA up if needed, then publish this app's JavaScript
|
||||
-c <channel> channel (default production)
|
||||
-m <message> release message
|
||||
-r <percent> share of devices that get it (default 100)
|
||||
-t <range> app versions it targets, e.g. 1.x.x
|
||||
-f force the update
|
||||
rollback -p <ios|android> turn off the newest release; devices go back to the one before
|
||||
status what is published
|
||||
`;
|
||||
|
||||
/** The default IO: real fetch, files and child processes. */
|
||||
export function nodeOtaIo(json: boolean): OtaIo {
|
||||
const cwd = process.cwd();
|
||||
return {
|
||||
cwd,
|
||||
env: process.env,
|
||||
fetch: globalThis.fetch.bind(globalThis),
|
||||
readFile: (path) => (existsSync(path) ? readFileSync(path, 'utf8') : null),
|
||||
writeFile: (path, contents) => {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, contents, { mode: 0o600 });
|
||||
},
|
||||
credentials: () => readCredentials(process.env),
|
||||
log: (line) => (json ? process.stderr.write(`${line}\n`) : process.stdout.write(`${line}\n`)),
|
||||
run: (command, args, env) =>
|
||||
new Promise((resolve) => {
|
||||
const child = spawn(command, args, { cwd, env: { ...process.env, ...env }, stdio: ['inherit', json ? 'ignore' : 'inherit', 'inherit'] });
|
||||
child.on('error', () => resolve(127));
|
||||
child.on('close', (code) => resolve(code ?? 1));
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** `ota` entry: parses, runs, prints. Returns the exit code. */
|
||||
export async function otaMain(argv: string[], io: OtaIo, write: (text: string) => void): Promise<number> {
|
||||
if (argv.length === 0 || argv.includes('--help') || argv.includes('-h')) {
|
||||
write(OTA_HELP);
|
||||
return argv.length === 0 ? 1 : 0;
|
||||
}
|
||||
let options: OtaOptions;
|
||||
try {
|
||||
options = parseOtaArgs(argv);
|
||||
const result = await runOta(options, io);
|
||||
write(options.json ? `${JSON.stringify(result)}\n` : formatOta(result));
|
||||
return 0;
|
||||
} catch (error) {
|
||||
const failure = error instanceof InitError ? error : new InitError('unexpected', (error as Error).message);
|
||||
write(`scribase ota: ${failure.message}${failure.next ? `\n next: ${failure.next}` : ''}\n`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
43
src/cli/capabilities/railyard/ai.ts
Normal file
43
src/cli/capabilities/railyard/ai.ts
Normal file
@ -0,0 +1,43 @@
|
||||
/**
|
||||
* `npx scribase add ai` (Wave P PY1.4): the project's gateway key goes
|
||||
* straight to the environment's secrets (`AI_GATEWAY_KEY`, read by functions
|
||||
* at run time); only the public `AI_GATEWAY_URL` reaches the env file. The
|
||||
* customer connects their own AI provider on a one-time page opened in the
|
||||
* browser (nothing typed here), and this command waits for it. Their provider
|
||||
* bills them directly.
|
||||
*/
|
||||
import type { AddIo, AddOptions, AddResult } from '../../add.js';
|
||||
import { InitError } from '../../init.js';
|
||||
import type { SlotAnswer, SlotContext } from './index.js';
|
||||
|
||||
const POLL_MS = 3_000;
|
||||
|
||||
type ReadSlot = (io: AddIo, ctx: SlotContext) => Promise<SlotAnswer>;
|
||||
|
||||
function toSeconds(at: string | number): number {
|
||||
return typeof at === 'number' ? at : Math.floor(Date.parse(at) / 1000);
|
||||
}
|
||||
|
||||
export async function aiConnect(result: AddResult, io: AddIo, options: AddOptions, ctx: SlotContext, readSlot: ReadSlot): Promise<AddResult> {
|
||||
if (result.status === 'list') return result;
|
||||
if (ctx.answer.state === 'live' && ctx.answer.proof) return result;
|
||||
const link = ctx.answer.connect_url;
|
||||
if (!link || !/^https?:\/\//.test(link)) throw new InitError('invalid_response', 'the control plane did not return a connect link');
|
||||
io.log(`Connect your AI provider in the browser (nothing to type here): ${link}`);
|
||||
if (options.browser) io.openBrowser(link);
|
||||
if (!options.wait) {
|
||||
return { ...result, status: 'needs_connect', live: false, connect_url: link, next: 'connect a provider on the page, then run `npx scribase add ai` again' };
|
||||
}
|
||||
io.log('Waiting for the connection...');
|
||||
const deadline = io.now() + options.waitSeconds * 1_000;
|
||||
for (;;) {
|
||||
await io.sleep(POLL_MS);
|
||||
const state = await readSlot(io, ctx);
|
||||
if (state.state === 'live' && state.proof) {
|
||||
return { ...result, live: true, proof: { kind: state.proof.kind, id: state.proof.id, at: toSeconds(state.proof.at) }, sent: true, next: null };
|
||||
}
|
||||
if (io.now() >= deadline) {
|
||||
throw new InitError('connect_timeout', `no provider was connected within ${options.waitSeconds} s`, 'open the link again from `npx scribase add ai`');
|
||||
}
|
||||
}
|
||||
}
|
||||
99
src/cli/capabilities/railyard/analytics.ts
Normal file
99
src/cli/capabilities/railyard/analytics.ts
Normal file
@ -0,0 +1,99 @@
|
||||
/**
|
||||
* `npx scribase add analytics` (Wave P PY1.3): the control plane creates this
|
||||
* project environment's analytics site and answers with its public values,
|
||||
* which go to the env file (the site key ships in the page, like an anon
|
||||
* key). Then, results first: this machine sends one proof event to the
|
||||
* collector, and the command waits (up to 60 s) until the Analytics tab
|
||||
* shows it. The proof is that first event.
|
||||
*
|
||||
* Wave Q QY1.2: the answer also carries the product analytics host and the
|
||||
* project's public key (`*_ANALYTICS_HOST`, `*_ANALYTICS_KEY`). The command
|
||||
* then sends the check event to product analytics too, in its capture
|
||||
* protocol, so an app that only uses the SDK sees its first product event in
|
||||
* the Analytics tab; whichever arrives first is the proof.
|
||||
*/
|
||||
import type { AddIo, AddOptions, AddResult } from '../../add.js';
|
||||
import { InitError } from '../../init.js';
|
||||
import type { SlotAnswer, SlotContext } from './index.js';
|
||||
|
||||
export const PROOF_EVENT = 'scribase_proof';
|
||||
export const WAIT_MS = 60_000;
|
||||
const POLL_MS = 3_000;
|
||||
|
||||
type ReadSlot = (io: AddIo, ctx: SlotContext) => Promise<SlotAnswer>;
|
||||
|
||||
function toSeconds(at: string | number): number {
|
||||
return typeof at === 'number' ? at : Math.floor(Date.parse(at) / 1000);
|
||||
}
|
||||
|
||||
/** The page tag to put in the app's HTML head. */
|
||||
export function pageTag(scriptUrl: string, siteKey: string): string {
|
||||
return `<script defer src="${scriptUrl}" data-site="${siteKey}"></script>`;
|
||||
}
|
||||
|
||||
/** The check event in the product analytics capture protocol (QY1.2). */
|
||||
export function productCheckEvent(key: string, at: number): Record<string, unknown> {
|
||||
return {
|
||||
api_key: key,
|
||||
event: PROOF_EVENT,
|
||||
distinct_id: 'scribase-cli',
|
||||
timestamp: new Date(at).toISOString(),
|
||||
properties: { $lib: 'scribase-cli', $current_url: 'https://scribase.local/scribase/add-analytics', $pathname: '/scribase/add-analytics', $process_person_profile: false },
|
||||
};
|
||||
}
|
||||
|
||||
async function post(io: AddIo, url: string, init: RequestInit, what: string): Promise<void> {
|
||||
let sent: Response;
|
||||
try {
|
||||
sent = await io.fetch(url, init);
|
||||
} catch (error) {
|
||||
throw new InitError('network_error', `could not reach ${what}: ${(error as Error).message}`);
|
||||
}
|
||||
if (sent.status >= 400) throw new InitError('proof_refused', `${what} refused the check event (HTTP ${sent.status})`);
|
||||
}
|
||||
|
||||
/** Sends one proof event the way the page tag does (and the way the SDK does), then waits for it to show. */
|
||||
export async function analyticsProof(result: AddResult, io: AddIo, options: AddOptions, ctx: SlotContext, readSlot: ReadSlot): Promise<AddResult> {
|
||||
if (result.status !== 'live') return result;
|
||||
if (ctx.answer.state === 'live' && ctx.answer.proof) return result;
|
||||
const env = ctx.answer.env ?? {};
|
||||
const site = env.NEXT_PUBLIC_ANALYTICS_SITE ?? env.VITE_ANALYTICS_SITE ?? env.EXPO_PUBLIC_ANALYTICS_SITE;
|
||||
const collector = env.ANALYTICS_COLLECTOR_URL;
|
||||
const host = env.NEXT_PUBLIC_ANALYTICS_HOST ?? env.VITE_ANALYTICS_HOST ?? env.EXPO_PUBLIC_ANALYTICS_HOST;
|
||||
const key = env.NEXT_PUBLIC_ANALYTICS_KEY ?? env.VITE_ANALYTICS_KEY ?? env.EXPO_PUBLIC_ANALYTICS_KEY ?? site;
|
||||
if (!site || (!collector && !host)) {
|
||||
throw new InitError('invalid_response', 'the control plane did not return the analytics site');
|
||||
}
|
||||
if (env.ANALYTICS_SCRIPT_URL) io.log(`Page tag for your app's <head>: ${pageTag(env.ANALYTICS_SCRIPT_URL, site)}`);
|
||||
if (host) io.log(`Product analytics: send events to ${host} with the key in ${env.NEXT_PUBLIC_ANALYTICS_KEY ? 'NEXT_PUBLIC_ANALYTICS_KEY' : env.VITE_ANALYTICS_KEY ? 'VITE_ANALYTICS_KEY' : 'EXPO_PUBLIC_ANALYTICS_KEY'}.`);
|
||||
const started = Math.floor(io.now() / 1000);
|
||||
if (collector) {
|
||||
const payload = { type: 'event', payload: { website: site, url: '/scribase/add-analytics', hostname: 'scribase.local', name: PROOF_EVENT, title: 'Analytics check', language: 'en', screen: '0x0' } };
|
||||
await post(
|
||||
io,
|
||||
`${collector.replace(/\/+$/, '')}/api/send`,
|
||||
{ method: 'POST', headers: { 'content-type': 'text/plain', 'user-agent': 'Scribase CLI (analytics check)' }, body: JSON.stringify(payload) },
|
||||
'the collector',
|
||||
);
|
||||
}
|
||||
if (host && key) {
|
||||
await post(
|
||||
io,
|
||||
`${host.replace(/\/+$/, '')}/capture/`,
|
||||
{ method: 'POST', headers: { 'content-type': 'application/json', 'user-agent': 'Scribase CLI (analytics check)' }, body: JSON.stringify(productCheckEvent(key, io.now())) },
|
||||
'product analytics',
|
||||
);
|
||||
}
|
||||
io.log('Sent one check event; waiting for it to arrive...');
|
||||
const deadline = io.now() + (options.wait ? WAIT_MS : 0);
|
||||
for (;;) {
|
||||
const state = await readSlot(io, ctx);
|
||||
if (state.state === 'live' && state.proof && toSeconds(state.proof.at) >= started - 5) {
|
||||
return { ...result, live: true, proof: { kind: state.proof.kind, id: state.proof.id, at: toSeconds(state.proof.at) }, sent: true, next: null };
|
||||
}
|
||||
if (io.now() >= deadline) {
|
||||
return { ...result, next: 'The check event is on its way; it shows in the Analytics tab shortly.' };
|
||||
}
|
||||
await io.sleep(POLL_MS);
|
||||
}
|
||||
}
|
||||
49
src/cli/capabilities/railyard/billing.ts
Normal file
49
src/cli/capabilities/railyard/billing.ts
Normal file
@ -0,0 +1,49 @@
|
||||
/**
|
||||
* `npx scribase add billing` (Wave P PY2.3): opens the one-time connect page
|
||||
* in the browser, where the customer connects their own payment account (no
|
||||
* key is typed here), and waits for the connection. Buyers then pay the
|
||||
* customer's account directly; each purchase becomes a row in
|
||||
* billing.entitlements of this environment. The proof is the first test
|
||||
* purchase, made from the Billing tab.
|
||||
*/
|
||||
import type { AddIo, AddOptions, AddResult } from '../../add.js';
|
||||
import { InitError } from '../../init.js';
|
||||
import type { SlotAnswer, SlotContext } from './index.js';
|
||||
|
||||
const POLL_MS = 3_000;
|
||||
|
||||
type ReadSlot = (io: AddIo, ctx: SlotContext) => Promise<SlotAnswer>;
|
||||
|
||||
function toSeconds(at: string | number): number {
|
||||
return typeof at === 'number' ? at : Math.floor(Date.parse(at) / 1000);
|
||||
}
|
||||
|
||||
export async function billingConnect(result: AddResult, io: AddIo, options: AddOptions, ctx: SlotContext, readSlot: ReadSlot): Promise<AddResult> {
|
||||
if (result.status !== 'live') return result;
|
||||
if (ctx.answer.state === 'live' && ctx.answer.proof) return result;
|
||||
if (ctx.answer.state === 'no_proof_yet') {
|
||||
return { ...result, next: 'Connected. Add a product and make one test purchase in Environment > Add-ons > Billing.' };
|
||||
}
|
||||
const link = ctx.answer.connect_url;
|
||||
if (!link || !/^https?:\/\//.test(link)) throw new InitError('invalid_response', 'the control plane did not return a connect link');
|
||||
io.log(`Connect your payment account in the browser (nothing to type here): ${link}`);
|
||||
if (options.browser) io.openBrowser(link);
|
||||
if (!options.wait) {
|
||||
return { ...result, status: 'needs_connect', live: false, connect_url: link, next: 'connect your account on the page, then run `npx scribase add billing` again' };
|
||||
}
|
||||
io.log('Waiting for the connection...');
|
||||
const deadline = io.now() + options.waitSeconds * 1_000;
|
||||
for (;;) {
|
||||
await io.sleep(POLL_MS);
|
||||
const state = await readSlot(io, ctx);
|
||||
if (state.state === 'live' && state.proof) {
|
||||
return { ...result, live: true, proof: { kind: state.proof.kind, id: state.proof.id, at: toSeconds(state.proof.at) }, sent: true, next: null };
|
||||
}
|
||||
if (state.state === 'no_proof_yet') {
|
||||
return { ...result, next: 'Connected. Add a product and make one test purchase in Environment > Add-ons > Billing.' };
|
||||
}
|
||||
if (io.now() >= deadline) {
|
||||
throw new InitError('connect_timeout', `no account was connected within ${options.waitSeconds} s`, 'open the link again from `npx scribase add billing`');
|
||||
}
|
||||
}
|
||||
}
|
||||
34
src/cli/capabilities/railyard/consent-files.ts
Normal file
34
src/cli/capabilities/railyard/consent-files.ts
Normal file
@ -0,0 +1,34 @@
|
||||
/**
|
||||
* The consent templates `npx scribase add consent` copies into an app (Wave
|
||||
* P PY2.5). Generated from `templates/consent/**`; railyard.test.mjs checks
|
||||
* they stay byte-identical. Do not edit here: edit the template and copy.
|
||||
*/
|
||||
|
||||
export interface TemplateFile {
|
||||
/** Where it goes in the app folder. */
|
||||
path: string;
|
||||
/** The repository template it comes from. */
|
||||
template: string;
|
||||
/** Only for Next.js apps. */
|
||||
next?: boolean;
|
||||
contents: string;
|
||||
}
|
||||
|
||||
export const CONSENT_FILES: readonly TemplateFile[] = Object.freeze([
|
||||
{
|
||||
path: "consent/consent-core.js",
|
||||
template: "templates/consent/web/consent-core.js",
|
||||
contents: "// Consent for your app (Scribase, the consent slot; Wave P PY2.5). No\n// dependencies. Categories follow the common consent-manager names\n// (necessary, measurement, marketing, functionality, experience), so another\n// banner can replace this one later without changing your checks.\n//\n// const consent = createConsent({ supabaseUrl, anonKey, policyVersion: '1' });\n// consent.allowed('measurement') // false until the person agrees\n// await consent.decide({ measurement: true, marketing: false });\n//\n// Every decision is stored on this device and added, with its time and the\n// policy version, to the insert-only consent_records table of your project.\n\nexport const CATEGORIES = ['necessary', 'measurement', 'marketing', 'functionality', 'experience'];\nconst STORE_KEY = 'scribase-consent';\n\nfunction randomId() {\n const bytes = new Uint8Array(16);\n globalThis.crypto.getRandomValues(bytes);\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nexport function createConsent({ supabaseUrl, anonKey, policyVersion = '1', storage = globalThis.localStorage, fetchImpl = globalThis.fetch?.bind(globalThis), source = 'web' } = {}) {\n if (!supabaseUrl || !anonKey) throw new Error('createConsent needs supabaseUrl and anonKey');\n const read = () => {\n try {\n const saved = JSON.parse(storage?.getItem(STORE_KEY) ?? 'null');\n return saved && saved.version === policyVersion ? saved : null;\n } catch {\n return null;\n }\n };\n let state = read();\n const listeners = new Set();\n const subject = () => {\n let id = null;\n try {\n id = storage?.getItem(`${STORE_KEY}:subject`) ?? null;\n if (!id) {\n id = randomId();\n storage?.setItem(`${STORE_KEY}:subject`, id);\n }\n } catch {\n id = id ?? randomId();\n }\n return id;\n };\n return {\n /** Whether the person decided under the current policy version. */\n decided: () => state !== null,\n /** `necessary` is always allowed; everything else only after a yes. */\n allowed: (category) => category === 'necessary' || state?.choices?.[category] === true,\n current: () => (state ? { ...state.choices } : null),\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n /** Saves the choice here and records it in your project. Resolves true when recorded. */\n async decide(choices) {\n const clean = Object.fromEntries(CATEGORIES.map((c) => [c, c === 'necessary' ? true : choices?.[c] === true]));\n state = { version: policyVersion, choices: clean, at: new Date().toISOString() };\n try {\n storage?.setItem(STORE_KEY, JSON.stringify(state));\n } catch {\n // Private mode: the choice holds for this page.\n }\n for (const l of listeners) l({ ...clean });\n if (!fetchImpl) return false;\n try {\n const res = await fetchImpl(`${supabaseUrl.replace(/\\/+$/, '')}/rest/v1/consent_records`, {\n method: 'POST',\n headers: { apikey: anonKey, authorization: `Bearer ${anonKey}`, 'content-type': 'application/json', prefer: 'return=minimal' },\n body: JSON.stringify({ subject_id: subject(), choices: clean, policy_version: policyVersion, source }),\n });\n return res.ok;\n } catch {\n return false;\n }\n },\n };\n}\n\n/**\n * Loads the analytics page tag only once measurement is allowed. Before that\n * (and after a no) no analytics request leaves the browser: the script is\n * never added to the page.\n */\nexport function loadAnalyticsWhenAllowed(consent, { scriptUrl, site, doc = globalThis.document }) {\n let loaded = false;\n const load = () => {\n if (loaded || !consent.allowed('measurement') || !doc) return;\n loaded = true;\n const s = doc.createElement('script');\n s.defer = true;\n s.src = scriptUrl;\n s.setAttribute('data-site', site);\n doc.head.appendChild(s);\n };\n load();\n const stop = consent.subscribe(load);\n return () => stop();\n}\n",
|
||||
},
|
||||
{
|
||||
path: "consent/banner.js",
|
||||
template: "templates/consent/web/banner.js",
|
||||
contents: "// A plain consent banner for any web page (Scribase, the consent slot).\n// Include after consent-core.js; it shows once, until the person decides.\n//\n// <script type=\"module\">\n// import { createConsent, loadAnalyticsWhenAllowed } from './consent/consent-core.js';\n// import { showBanner } from './consent/banner.js';\n// const consent = createConsent({ supabaseUrl: '...', anonKey: '...', policyVersion: '1' });\n// loadAnalyticsWhenAllowed(consent, { scriptUrl: '...', site: 'ry_site_...' });\n// showBanner(consent, { privacyUrl: '/privacy' });\n// </script>\n\nexport function showBanner(consent, { privacyUrl = '/privacy', doc = globalThis.document, text = {} } = {}) {\n if (!doc || consent.decided()) return null;\n const t = {\n body: 'We use cookies and similar tools to measure how the app is used. Choose what you allow.',\n accept: 'Allow all',\n reject: 'Only necessary',\n privacy: 'Privacy',\n ...text,\n };\n const box = doc.createElement('div');\n box.setAttribute('role', 'dialog');\n box.setAttribute('aria-label', 'Consent');\n box.style.cssText = 'position:fixed;left:16px;right:16px;bottom:16px;max-width:560px;margin:0 auto;padding:16px;border-radius:12px;background:#fff;color:#1b1f24;box-shadow:0 8px 30px rgba(0,0,0,.15);font:14px/1.5 system-ui,sans-serif;z-index:2147483000';\n const p = doc.createElement('p');\n p.textContent = `${t.body} `;\n const link = doc.createElement('a');\n link.href = privacyUrl;\n link.textContent = t.privacy;\n p.appendChild(link);\n const row = doc.createElement('div');\n row.style.cssText = 'display:flex;gap:8px;justify-content:flex-end;margin-top:8px';\n const button = (label, primary, choices) => {\n const b = doc.createElement('button');\n b.type = 'button';\n b.textContent = label;\n b.style.cssText = `padding:8px 14px;border-radius:8px;border:1px solid #1b1f24;cursor:pointer;${primary ? 'background:#1b1f24;color:#fff' : 'background:#fff;color:#1b1f24'}`;\n b.addEventListener('click', () => {\n box.remove();\n void consent.decide(choices);\n });\n return b;\n };\n row.appendChild(button(t.reject, false, {}));\n row.appendChild(button(t.accept, true, { measurement: true, marketing: true, functionality: true, experience: true }));\n box.appendChild(p);\n box.appendChild(row);\n doc.body.appendChild(box);\n return box;\n}\n",
|
||||
},
|
||||
{
|
||||
path: "components/ConsentBanner.tsx",
|
||||
template: "templates/consent/next/ConsentBanner.tsx",
|
||||
next: true,
|
||||
contents: "'use client';\n\n// A consent banner for Next.js apps (Scribase, the consent slot). The page\n// tag for analytics loads only after measurement is allowed.\n//\n// <ConsentBanner analyticsScript={process.env.NEXT_PUBLIC_ANALYTICS_SCRIPT_URL} analyticsSite={process.env.NEXT_PUBLIC_ANALYTICS_SITE} />\n\nimport { useEffect, useMemo, useState } from 'react';\n// @ts-expect-error: plain ESM module shipped next to this file\nimport { createConsent, loadAnalyticsWhenAllowed } from '../consent/consent-core.js';\n\nexport function ConsentBanner({ analyticsScript, analyticsSite, privacyUrl = '/privacy' }: { analyticsScript?: string; analyticsSite?: string; privacyUrl?: string }) {\n const consent = useMemo(\n () =>\n createConsent({\n supabaseUrl: process.env.NEXT_PUBLIC_SUPABASE_URL,\n anonKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,\n policyVersion: process.env.NEXT_PUBLIC_CONSENT_POLICY_VERSION ?? '1',\n }),\n [],\n );\n const [open, setOpen] = useState(false);\n useEffect(() => {\n setOpen(!consent.decided());\n if (analyticsScript && analyticsSite) return loadAnalyticsWhenAllowed(consent, { scriptUrl: analyticsScript, site: analyticsSite });\n return undefined;\n }, [consent, analyticsScript, analyticsSite]);\n if (!open) return null;\n const decide = (choices: Record<string, boolean>) => {\n setOpen(false);\n void consent.decide(choices);\n };\n return (\n <div role=\"dialog\" aria-label=\"Consent\" style={{ position: 'fixed', left: 16, right: 16, bottom: 16, maxWidth: 560, margin: '0 auto', padding: 16, borderRadius: 12, background: '#fff', color: '#1b1f24', boxShadow: '0 8px 30px rgba(0,0,0,.15)', zIndex: 2147483000 }}>\n <p style={{ margin: 0 }}>\n We use cookies and similar tools to measure how the app is used. Choose what you allow. <a href={privacyUrl}>Privacy</a>\n </p>\n <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 8 }}>\n <button type=\"button\" onClick={() => decide({})}>\n Only necessary\n </button>\n <button type=\"button\" onClick={() => decide({ measurement: true, marketing: true, functionality: true, experience: true })}>\n Allow all\n </button>\n </div>\n </div>\n );\n}\n",
|
||||
},
|
||||
]);
|
||||
44
src/cli/capabilities/railyard/consent.ts
Normal file
44
src/cli/capabilities/railyard/consent.ts
Normal file
@ -0,0 +1,44 @@
|
||||
/**
|
||||
* `npx scribase add consent` (Wave P PY2.5, SP-F3): the control plane creates
|
||||
* the insert-only consent_records table in this environment's database; this
|
||||
* machine copies the consent files into the app (the core, a plain banner,
|
||||
* and the Next.js banner when the app uses Next.js). Existing files are never
|
||||
* overwritten. The analytics tag then loads only after a yes. The proof is
|
||||
* the first consent record from a visitor.
|
||||
*/
|
||||
import type { AddIo, AddOptions, AddResult } from '../../add.js';
|
||||
import { CONSENT_FILES } from './consent-files.js';
|
||||
import type { SlotContext } from './index.js';
|
||||
|
||||
function isNext(io: AddIo): boolean {
|
||||
const pkg = io.readFile(`${io.cwd.replace(/\/+$/, '')}/package.json`);
|
||||
if (!pkg) return false;
|
||||
try {
|
||||
const parsed = JSON.parse(pkg) as { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };
|
||||
return Boolean(parsed.dependencies?.next ?? parsed.devDependencies?.next);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function consentFiles(result: AddResult, io: AddIo, options: AddOptions, ctx: SlotContext): Promise<AddResult> {
|
||||
void options;
|
||||
void ctx;
|
||||
if (result.status !== 'live') return result;
|
||||
const next = isNext(io);
|
||||
const root = io.cwd.replace(/\/+$/, '');
|
||||
const written: string[] = [];
|
||||
for (const file of CONSENT_FILES) {
|
||||
if (file.next && !next) continue;
|
||||
const target = `${root}/${file.path}`;
|
||||
if (io.readFile(target) !== null) {
|
||||
io.log(`Kept your ${file.path} (already there).`);
|
||||
continue;
|
||||
}
|
||||
io.writeFile(target, file.contents);
|
||||
written.push(file.path);
|
||||
}
|
||||
if (written.length) io.log(`Added ${written.join(', ')}.`);
|
||||
io.log(next ? 'Render <ConsentBanner /> in your root layout; analytics loads only after a yes.' : "Call showBanner() from consent/banner.js on your pages; analytics loads only after a yes.");
|
||||
return { ...result, next: result.next ?? 'The first consent record from a visitor shows in the Consent tab.' };
|
||||
}
|
||||
75
src/cli/capabilities/railyard/deploy.ts
Normal file
75
src/cli/capabilities/railyard/deploy.ts
Normal file
@ -0,0 +1,75 @@
|
||||
/**
|
||||
* `npx scribase add deploy` (Wave P PY1.2): links this machine to the
|
||||
* organization's deploy account with a one-time claim (never printed), then
|
||||
* deploys the folder to the person's own Cloudflare account and answers with
|
||||
* the live URL as the proof. The project's URL and anon key come from the env
|
||||
* file `scribase init` wrote; nothing is pasted.
|
||||
*
|
||||
* The deploy runs the pinned deploy CLI (see `DEPLOY_CLI`); its lines are
|
||||
* passed through, and the URL line becomes the proof.
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
|
||||
import type { AddIo, AddOptions, AddResult } from '../../add.js';
|
||||
import { InitError } from '../../init.js';
|
||||
|
||||
export const DEPLOY_CLI = ['npx', '--yes', 'railyard@0.1.0', 'deploy'] as const;
|
||||
|
||||
/** Runs the deploy in `cwd`; resolves with its exit code and every line it printed. */
|
||||
export type RunDeploy = (io: AddIo) => Promise<{ code: number; lines: string[] }>;
|
||||
|
||||
const defaultRun: RunDeploy = (io) =>
|
||||
new Promise((resolve) => {
|
||||
const [command, ...args] = io.env.SCRIBASE_RAILYARD_CLI ? [io.env.SCRIBASE_RAILYARD_CLI, 'deploy'] : DEPLOY_CLI;
|
||||
const child = spawn(command as string, args, { cwd: io.cwd, env: io.env as NodeJS.ProcessEnv, stdio: ['inherit', 'pipe', 'pipe'] });
|
||||
const lines: string[] = [];
|
||||
const take = (chunk: Buffer): void => {
|
||||
for (const line of String(chunk).split(/\r?\n/)) if (line.trim()) lines.push(line);
|
||||
};
|
||||
child.stdout.on('data', take);
|
||||
child.stderr.on('data', take);
|
||||
child.on('error', () => resolve({ code: 127, lines }));
|
||||
child.on('close', (code) => resolve({ code: code ?? 1, lines }));
|
||||
});
|
||||
|
||||
let run: RunDeploy = defaultRun;
|
||||
|
||||
/** Test seam: replaces the deploy runner; returns the previous one. */
|
||||
export function setRunDeploy(next: RunDeploy): RunDeploy {
|
||||
const previous = run;
|
||||
run = next;
|
||||
return previous;
|
||||
}
|
||||
|
||||
/** The live URL a deploy printed (`Live: https://<name>.<account>.workers.dev`). */
|
||||
export function liveUrl(lines: readonly string[]): string | null {
|
||||
for (const line of lines) {
|
||||
const match = /^Live: (https:\/\/[a-z0-9.-]+\.workers\.dev)\b/i.exec(line.trim());
|
||||
if (match?.[1]) return match[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Lines worth showing: the deploy's own progress, minus anything naming the vendor tool. */
|
||||
export function shownLines(lines: readonly string[]): string[] {
|
||||
return lines.filter((line) => !/railyard/i.test(line));
|
||||
}
|
||||
|
||||
/** Link (done by the slot answer's claim), then deploy and prove with the live URL. */
|
||||
export async function deployAfterLink(linked: AddResult, io: AddIo, options: AddOptions): Promise<AddResult> {
|
||||
void options;
|
||||
if (linked.status !== 'live') return linked;
|
||||
const { code, lines } = await run(io);
|
||||
for (const line of shownLines(lines)) io.log(line);
|
||||
const url = liveUrl(lines);
|
||||
if (code !== 0 || !url) {
|
||||
throw new InitError('deploy_failed', 'the deploy did not finish; the lines above say why', 'fix it, then run the same command again');
|
||||
}
|
||||
return {
|
||||
...linked,
|
||||
live: true,
|
||||
proof: { kind: 'deploy', id: url, at: Math.floor(io.now() / 1000) },
|
||||
sent: true,
|
||||
next: null,
|
||||
};
|
||||
}
|
||||
57
src/cli/capabilities/railyard/flags.ts
Normal file
57
src/cli/capabilities/railyard/flags.ts
Normal file
@ -0,0 +1,57 @@
|
||||
/**
|
||||
* `npx scribase add flags` (Wave P PY2.1): the control plane creates this
|
||||
* project environment's flags on first use and answers with its public
|
||||
* values for the env file (the flags key ships in the app, like an anon key).
|
||||
* Then, results first: this machine reads the flags once the way the app's
|
||||
* SDK does, and the command waits until that first read shows as the slot's
|
||||
* proof. Flip flags in Environment > Add-ons > Flags; the app sees a flip on
|
||||
* its next read, with no new build.
|
||||
*/
|
||||
import type { AddIo, AddOptions, AddResult } from '../../add.js';
|
||||
import { InitError } from '../../init.js';
|
||||
import type { SlotAnswer, SlotContext } from './index.js';
|
||||
|
||||
export const WAIT_MS = 60_000;
|
||||
const POLL_MS = 3_000;
|
||||
|
||||
type ReadSlot = (io: AddIo, ctx: SlotContext) => Promise<SlotAnswer>;
|
||||
|
||||
function toSeconds(at: string | number): number {
|
||||
return typeof at === 'number' ? at : Math.floor(Date.parse(at) / 1000);
|
||||
}
|
||||
|
||||
/** How the app reads its flags (plain fetch; the SDK polls the same URL). */
|
||||
export function readSnippet(envName: string): string {
|
||||
return `const { flags } = await (await fetch(\`\${process.env.FLAGS_URL}?key=\${process.env.${envName}}\`)).json();`;
|
||||
}
|
||||
|
||||
export async function flagsFirstRead(result: AddResult, io: AddIo, options: AddOptions, ctx: SlotContext, readSlot: ReadSlot): Promise<AddResult> {
|
||||
if (result.status !== 'live') return result;
|
||||
if (ctx.answer.state === 'live' && ctx.answer.proof) return result;
|
||||
const env = ctx.answer.env ?? {};
|
||||
const key = env.NEXT_PUBLIC_FLAGS_KEY ?? env.EXPO_PUBLIC_FLAGS_KEY ?? env.VITE_FLAGS_KEY;
|
||||
const url = env.FLAGS_URL;
|
||||
if (!key || !/^ry_flags_/.test(key) || !url || !/^https?:\/\//.test(url)) {
|
||||
throw new InitError('invalid_response', 'the control plane did not return the flags key');
|
||||
}
|
||||
io.log(`Read flags in your app: ${readSnippet('NEXT_PUBLIC_FLAGS_KEY')}`);
|
||||
let read: Response;
|
||||
try {
|
||||
read = await io.fetch(`${url.replace(/\/+$/, '')}?key=${encodeURIComponent(key)}`, { method: 'GET', headers: { accept: 'application/json', 'user-agent': 'Scribase CLI (flags check)' } });
|
||||
} catch (error) {
|
||||
throw new InitError('network_error', `could not read the flags: ${(error as Error).message}`);
|
||||
}
|
||||
if (read.status !== 200) throw new InitError('proof_refused', `the flags read answered HTTP ${read.status}`);
|
||||
io.log('Read the flags once, the way the app does; waiting for it to show...');
|
||||
const deadline = io.now() + (options.wait ? WAIT_MS : 0);
|
||||
for (;;) {
|
||||
const state = await readSlot(io, ctx);
|
||||
if (state.state === 'live' && state.proof) {
|
||||
return { ...result, live: true, proof: { kind: state.proof.kind, id: state.proof.id, at: toSeconds(state.proof.at) }, sent: true, next: null };
|
||||
}
|
||||
if (io.now() >= deadline) {
|
||||
return { ...result, next: 'The first read is recorded; it shows in the Flags tab shortly.' };
|
||||
}
|
||||
await io.sleep(POLL_MS);
|
||||
}
|
||||
}
|
||||
275
src/cli/capabilities/railyard/index.ts
Normal file
275
src/cli/capabilities/railyard/index.ts
Normal file
@ -0,0 +1,275 @@
|
||||
/**
|
||||
* `npx scribase add <slot>` handlers for the Railyard slots: deploy,
|
||||
* analytics, flags, uptime, ai, billing, consent (Wave P carve-out, dispatch
|
||||
* section 3.1; PY1.0 slot dispatcher).
|
||||
*
|
||||
* Owned by the PY lane. PS1.0 created this skeleton and its dispatch line in
|
||||
* `src/cli/add.ts`; nobody in the PS lane edits this folder.
|
||||
*
|
||||
* Each slot calls the control plane's Railyard route
|
||||
* (`POST .../environments/{env}/railyard/{slot}`), which answers in the
|
||||
* capability-state shape `{slot, state, live, proof:{kind,id,at}, next, env}`.
|
||||
* A slot whose package has not landed answers `arriving`, and this command says
|
||||
* so and changes nothing. When a slot needs this machine linked to Railyard
|
||||
* (deploy), the answer carries a one-time claim: it is piped on stdin to
|
||||
* `railyard link-scribase`, which saves the token to Railyard's own credentials
|
||||
* file (mode 600). The claim and the token are never printed, logged, or
|
||||
* written to the project's env file.
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
|
||||
import type { AddIo, AddOptions, AddResult, Proof } from '../../add.js';
|
||||
import { publicEnvOnly, mergeEnv, readEnvValue } from '../../envfile.js';
|
||||
import { InitError, STATE_FILE } from '../../init.js';
|
||||
import { deployAfterLink } from './deploy.js';
|
||||
import { analyticsProof } from './analytics.js';
|
||||
import { aiConnect } from './ai.js';
|
||||
import { flagsFirstRead } from './flags.js';
|
||||
import { uptimeBody, uptimeFirstResult } from './uptime.js';
|
||||
import { billingConnect } from './billing.js';
|
||||
import { consentFiles } from './consent.js';
|
||||
|
||||
export type RailyardAddHandler = (options: AddOptions, io: AddIo) => Promise<AddResult>;
|
||||
|
||||
/** The Railyard slots this CLI dispatches (errors stays Scribase's own slot). */
|
||||
export const RAILYARD_SLOTS = Object.freeze(['deploy', 'analytics', 'ai', 'flags', 'uptime', 'billing', 'consent'] as const);
|
||||
|
||||
const DEFAULT_API_URL = 'https://api.scribase.com';
|
||||
const ENV_FILES = ['.env.local', '.env'] as const;
|
||||
/** The Railyard CLI that saves the linked token (pinned; the claim goes on stdin). */
|
||||
export const RAILYARD_CLI = ['npx', '--yes', 'railyard@0.1.0', 'link-scribase'] as const;
|
||||
|
||||
interface ProjectState {
|
||||
organization_id: string;
|
||||
project_id: string;
|
||||
environment_id: string;
|
||||
api_url?: string;
|
||||
}
|
||||
|
||||
/** The answer of the Railyard route (capability-state shape plus an optional claim). */
|
||||
export interface SlotAnswer {
|
||||
slot: string;
|
||||
state: string;
|
||||
live: boolean;
|
||||
proof: Proof | { kind: string; id: string; at: string } | null;
|
||||
next: string | null;
|
||||
env?: Record<string, string>;
|
||||
/** A one-time link to a page where a credential is entered (never in the terminal). */
|
||||
connect_url?: string | null;
|
||||
claim?: { claim: string; console: string } | null;
|
||||
}
|
||||
|
||||
/** Pipes a one-time claim to the Railyard CLI. Resolves with its exit code. */
|
||||
export type LinkRailyard = (input: string, io: AddIo) => Promise<number>;
|
||||
|
||||
const defaultLink: LinkRailyard = (input, io) =>
|
||||
new Promise((resolve) => {
|
||||
const [command, ...args] = RAILYARD_CLI;
|
||||
const child = spawn(command, args, { cwd: io.cwd, env: io.env as NodeJS.ProcessEnv, stdio: ['pipe', 'ignore', 'inherit'] });
|
||||
child.on('error', () => resolve(127));
|
||||
child.on('close', (code) => resolve(code ?? 1));
|
||||
child.stdin.end(input);
|
||||
});
|
||||
|
||||
let link: LinkRailyard = defaultLink;
|
||||
|
||||
/** Test seam: replaces the Railyard CLI runner; returns the previous one. */
|
||||
export function setLinkRailyard(next: LinkRailyard): LinkRailyard {
|
||||
const previous = link;
|
||||
link = next;
|
||||
return previous;
|
||||
}
|
||||
|
||||
function joinPath(root: string, relative: string): string {
|
||||
return `${root.replace(/\/+$/, '')}/${relative}`;
|
||||
}
|
||||
|
||||
function readProject(io: AddIo): ProjectState {
|
||||
const text = io.readFile(joinPath(io.cwd, STATE_FILE));
|
||||
let state: Partial<ProjectState> | null = null;
|
||||
try {
|
||||
state = text ? (JSON.parse(text) as Partial<ProjectState>) : null;
|
||||
} catch {
|
||||
state = null;
|
||||
}
|
||||
if (!state?.organization_id || !state.project_id || !state.environment_id) {
|
||||
throw new InitError('not_initialized', 'this folder is not connected to a Scribase project', 'run `npx scribase init` here first');
|
||||
}
|
||||
return state as ProjectState;
|
||||
}
|
||||
|
||||
function findToken(io: AddIo): string | undefined {
|
||||
const fromEnv = io.env.SCRIBASE_ACCESS_TOKEN?.trim();
|
||||
if (fromEnv) return fromEnv;
|
||||
for (const file of ENV_FILES) {
|
||||
const contents = io.readFile(joinPath(io.cwd, file));
|
||||
const value = contents ? readEnvValue(contents, 'SCRIBASE_ACCESS_TOKEN')?.trim() : undefined;
|
||||
if (value) return value;
|
||||
}
|
||||
return io.credentials().token;
|
||||
}
|
||||
|
||||
/** The control-plane path of one Railyard slot for this folder's environment. */
|
||||
export function slotPath(project: ProjectState, slot: string): string {
|
||||
return (
|
||||
`/v1/organizations/${encodeURIComponent(project.organization_id)}` +
|
||||
`/projects/${encodeURIComponent(project.project_id)}` +
|
||||
`/environments/${encodeURIComponent(project.environment_id)}` +
|
||||
`/railyard/${encodeURIComponent(slot)}`
|
||||
);
|
||||
}
|
||||
|
||||
function asAnswer(body: unknown): SlotAnswer {
|
||||
const value = (body ?? {}) as Partial<SlotAnswer>;
|
||||
if (typeof value.slot !== 'string' || typeof value.state !== 'string' || typeof value.live !== 'boolean') {
|
||||
throw new InitError('invalid_response', 'the control plane answered with an unexpected shape');
|
||||
}
|
||||
return value as SlotAnswer;
|
||||
}
|
||||
|
||||
async function post(io: AddIo, url: string, token: string, payload: Record<string, string> = {}): Promise<SlotAnswer> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await io.fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { accept: 'application/json', 'content-type': 'application/json', authorization: `Bearer ${token}`, 'user-agent': 'scribase-add' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new InitError('network_error', `could not reach the control plane: ${(error as Error).message}`, 'check your connection or SCRIBASE_API_URL');
|
||||
}
|
||||
const text = await response.text();
|
||||
let body: unknown = null;
|
||||
try {
|
||||
body = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
body = { detail: text.slice(0, 200) };
|
||||
}
|
||||
if (response.status !== 200) {
|
||||
const value = (body ?? {}) as { code?: unknown; detail?: unknown };
|
||||
const code = typeof value.code === 'string' ? value.code : 'request_failed';
|
||||
const detail = typeof value.detail === 'string' ? value.detail : 'the request failed';
|
||||
const next =
|
||||
response.status === 402
|
||||
? 'turn on the Portfolio add-on under Billing, Add-ons in the console'
|
||||
: response.status === 401 || response.status === 403
|
||||
? 'run `npx scribase login` (adding a slot needs an owner or admin)'
|
||||
: undefined;
|
||||
throw new InitError(code, `${detail} (HTTP ${response.status})`, next);
|
||||
}
|
||||
return asAnswer(body);
|
||||
}
|
||||
|
||||
function envFileFor(io: AddIo): string {
|
||||
for (const file of ENV_FILES) {
|
||||
if (io.readFile(joinPath(io.cwd, file)) !== null) return file;
|
||||
}
|
||||
return '.env';
|
||||
}
|
||||
|
||||
function toProof(proof: SlotAnswer['proof']): Proof | null {
|
||||
if (!proof) return null;
|
||||
const at = typeof proof.at === 'number' ? proof.at : Math.floor(Date.parse(String(proof.at)) / 1000);
|
||||
return { kind: proof.kind, id: proof.id, at: Number.isFinite(at) ? at : 0 };
|
||||
}
|
||||
|
||||
/** What a slot's follow-up step on this machine may use (never printed). */
|
||||
export interface SlotContext {
|
||||
/** The slot's control-plane URL. */
|
||||
url: string;
|
||||
token: string;
|
||||
answer: SlotAnswer;
|
||||
}
|
||||
|
||||
/** Follow-up steps: deploy runs the deploy, analytics sends a proof event and waits for it. */
|
||||
export type AfterStep = (result: AddResult, io: AddIo, options: AddOptions, ctx: SlotContext) => Promise<AddResult>;
|
||||
|
||||
/** One Railyard slot, end to end. Never returns or logs a secret. */
|
||||
export async function addRailyardSlot(slot: string, options: AddOptions, io: AddIo): Promise<AddResult> {
|
||||
return (await addWithContext(slot, options, io)).result;
|
||||
}
|
||||
|
||||
async function addWithContext(slot: string, options: AddOptions, io: AddIo): Promise<{ result: AddResult; ctx: SlotContext }> {
|
||||
void options;
|
||||
const project = readProject(io);
|
||||
const token = findToken(io);
|
||||
if (!token) {
|
||||
throw new InitError('not_signed_in', 'no Scribase token for this folder', 'run `npx scribase login`, or `npx scribase init` here');
|
||||
}
|
||||
const base = (io.env.SCRIBASE_API_URL ?? project.api_url ?? io.credentials().apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, '');
|
||||
const url = `${base}${slotPath(project, slot)}`;
|
||||
const answer = await post(io, url, token, BODY[slot]?.(io) ?? {});
|
||||
if (answer.state === 'arriving') {
|
||||
throw new InitError('capability_arriving', answer.next ?? `${slot} is arriving and cannot be turned on yet. Nothing was changed.`, 'run `npx scribase add --list`');
|
||||
}
|
||||
if (answer.claim) {
|
||||
// The secure channel: stdin of the Railyard CLI only.
|
||||
const code = await link(JSON.stringify({ claim: answer.claim.claim, console: answer.claim.console }), io);
|
||||
if (code !== 0) {
|
||||
throw new InitError('link_failed', 'this machine could not be linked to Railyard; nothing was printed', `run \`npx scribase add ${slot}\` again`);
|
||||
}
|
||||
io.log('This machine is linked to your organization for deploys (saved for your user only).');
|
||||
}
|
||||
const { safe, refused } = publicEnvOnly(answer.env ?? {});
|
||||
const written = Object.keys(safe);
|
||||
if (written.length > 0) {
|
||||
const file = joinPath(io.cwd, envFileFor(io));
|
||||
io.writeFile(file, mergeEnv(io.readFile(file) ?? '', safe));
|
||||
}
|
||||
const result: AddResult = {
|
||||
ok: true,
|
||||
slot,
|
||||
status: 'live',
|
||||
live: answer.live,
|
||||
provider: 'railyard',
|
||||
proof: toProof(answer.proof),
|
||||
sent: answer.proof !== null,
|
||||
env_written: written,
|
||||
env_refused: refused,
|
||||
next: answer.next,
|
||||
};
|
||||
return { result, ctx: { url, token, answer } };
|
||||
}
|
||||
|
||||
/** Reads a slot's state again (the follow-up steps poll it). */
|
||||
export async function readSlot(io: AddIo, ctx: SlotContext): Promise<SlotAnswer> {
|
||||
const response = await io.fetch(ctx.url, { method: 'GET', headers: { accept: 'application/json', authorization: `Bearer ${ctx.token}`, 'user-agent': 'scribase-add' } });
|
||||
if (response.status !== 200) throw new InitError('request_failed', `the control plane answered HTTP ${response.status}`);
|
||||
return asAnswer(JSON.parse(await response.text()));
|
||||
}
|
||||
|
||||
export { toProof };
|
||||
|
||||
/** Slots whose add request carries a body (uptime: the app's address when known). */
|
||||
const BODY: Readonly<Record<string, (io: AddIo) => Record<string, string>>> = Object.freeze({
|
||||
uptime: uptimeBody,
|
||||
});
|
||||
|
||||
/** Slots that do more on this machine once the control plane answers (deploy runs the deploy). */
|
||||
const AFTER: Readonly<Record<string, AfterStep>> = Object.freeze({
|
||||
deploy: (result, io, options) => deployAfterLink(result, io, options),
|
||||
analytics: (result, io, options, ctx) => analyticsProof(result, io, options, ctx, readSlot),
|
||||
ai: (result, io, options, ctx) => aiConnect(result, io, options, ctx, readSlot),
|
||||
flags: (result, io, options, ctx) => flagsFirstRead(result, io, options, ctx, readSlot),
|
||||
uptime: (result, io, options, ctx) => uptimeFirstResult(result, io, options, ctx, readSlot),
|
||||
billing: (result, io, options, ctx) => billingConnect(result, io, options, ctx, readSlot),
|
||||
consent: (result, io, options, ctx) => consentFiles(result, io, options, ctx),
|
||||
});
|
||||
|
||||
const HANDLERS: Readonly<Record<string, RailyardAddHandler>> = Object.freeze(
|
||||
Object.fromEntries(
|
||||
RAILYARD_SLOTS.map((slot) => [
|
||||
slot,
|
||||
async (options: AddOptions, io: AddIo) => {
|
||||
const { result, ctx } = await addWithContext(slot, options, io);
|
||||
const after = AFTER[slot];
|
||||
return after ? after(result, io, options, ctx) : result;
|
||||
},
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
/** The local handler for `slot`, or `null` when the generic path serves it. */
|
||||
export function railyardAddHandler(slot: string): RailyardAddHandler | null {
|
||||
return Object.hasOwn(HANDLERS, slot) ? (HANDLERS[slot] ?? null) : null;
|
||||
}
|
||||
354
src/cli/capabilities/railyard/railyard.test.mjs
Normal file
354
src/cli/capabilities/railyard/railyard.test.mjs
Normal file
@ -0,0 +1,354 @@
|
||||
// PY1.0: `npx scribase add <railyard slot>` dispatch. Run:
|
||||
// node --import tsx/esm --test src/cli/capabilities/railyard/railyard.test.mjs
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readdirSync, readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { RAILYARD_SLOTS, railyardAddHandler, setLinkRailyard, slotPath } from './index.ts';
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||
const project = { organization_id: 'org_a', project_id: 'shop', environment_id: 'prod' };
|
||||
const CLAIM = 'claim_0123456789abcdefghijklmnop';
|
||||
|
||||
function io(answer, status = 200) {
|
||||
const files = new Map([['/app/.scribase/project.json', JSON.stringify(project)], ['/app/.env.local', 'NEXT_PUBLIC_SUPABASE_URL=https://x\n']]);
|
||||
const logs = [];
|
||||
const calls = [];
|
||||
return {
|
||||
logs,
|
||||
calls,
|
||||
files,
|
||||
io: {
|
||||
cwd: '/app',
|
||||
env: { SCRIBASE_API_URL: 'https://api.test', SCRIBASE_ACCESS_TOKEN: 'scb_pat_test' },
|
||||
fetch: async (url, init) => {
|
||||
calls.push({ url, init });
|
||||
return new Response(JSON.stringify(answer), { status });
|
||||
},
|
||||
readFile: (p) => files.get(p) ?? null,
|
||||
writeFile: (p, c) => files.set(p, c),
|
||||
credentials: () => ({}),
|
||||
sleep: async () => {},
|
||||
now: () => 0,
|
||||
log: (l) => logs.push(l),
|
||||
openBrowser: () => {},
|
||||
},
|
||||
};
|
||||
}
|
||||
const opts = { slot: 'deploy', list: false, own: false, resend: false, json: false, wait: true, browser: false, waitSeconds: 1 };
|
||||
|
||||
test('every Railyard slot has a handler; errors and unknown slots stay on the generic path', () => {
|
||||
for (const slot of RAILYARD_SLOTS) assert.equal(typeof railyardAddHandler(slot), 'function', slot);
|
||||
assert.equal(railyardAddHandler('errors'), null);
|
||||
assert.equal(railyardAddHandler('email'), null);
|
||||
assert.equal(slotPath(project, 'deploy'), '/v1/organizations/org_a/projects/shop/environments/prod/railyard/deploy');
|
||||
});
|
||||
|
||||
test('an arriving slot says so and changes nothing', async () => {
|
||||
const t = io({ slot: 'analytics', state: 'arriving', live: false, proof: null, next: 'Analytics is arriving (PY1.3).', env: {} });
|
||||
await assert.rejects(railyardAddHandler('analytics')(opts, t.io), (e) => e.code === 'capability_arriving' && /PY1\.3/.test(e.message));
|
||||
assert.equal(t.calls[0].url, 'https://api.test/v1/organizations/org_a/projects/shop/environments/prod/railyard/analytics');
|
||||
assert.equal(t.calls[0].init.headers.authorization, 'Bearer scb_pat_test');
|
||||
assert.equal(t.files.get('/app/.env.local'), 'NEXT_PUBLIC_SUPABASE_URL=https://x\n');
|
||||
});
|
||||
|
||||
test('a live slot returns its proof; a claim goes only to the Railyard CLI stdin and is never logged or written', async () => {
|
||||
const piped = [];
|
||||
const previous = setLinkRailyard(async (input) => {
|
||||
piped.push(input);
|
||||
return 0;
|
||||
});
|
||||
try {
|
||||
const t = io({
|
||||
slot: 'flags',
|
||||
state: 'live',
|
||||
live: true,
|
||||
proof: { kind: 'flag_flip', id: 'd1', at: '2026-09-29T12:00:00.000Z' },
|
||||
next: null,
|
||||
env: { PUBLIC_X: '1', RAILYARD_TOKEN_SECRET: 'nope' },
|
||||
claim: { claim: CLAIM, console: 'https://railyard.example' },
|
||||
});
|
||||
const r = await railyardAddHandler('flags')(opts, t.io);
|
||||
assert.equal(r.live, true);
|
||||
assert.deepEqual(r.proof, { kind: 'flag_flip', id: 'd1', at: 1790683200 });
|
||||
assert.deepEqual(r.env_written, ['PUBLIC_X']);
|
||||
assert.deepEqual(r.env_refused, ['RAILYARD_TOKEN_SECRET']);
|
||||
assert.deepEqual(JSON.parse(piped[0]), { claim: CLAIM, console: 'https://railyard.example' });
|
||||
const everything = [...t.logs, ...t.files.values(), JSON.stringify(r)].join('\n');
|
||||
assert.ok(!everything.includes(CLAIM), 'the claim is never printed, logged or written');
|
||||
} finally {
|
||||
setLinkRailyard(previous);
|
||||
}
|
||||
});
|
||||
|
||||
test('a missing add-on is a plain 402 with the next step', async () => {
|
||||
const t = io({ code: 'addon_required', detail: 'Deploy comes with the Portfolio add-on, which is off for this organization.' }, 402);
|
||||
await assert.rejects(railyardAddHandler('deploy')(opts, t.io), (e) => e.code === 'addon_required' && /Billing, Add-ons/.test(e.next));
|
||||
});
|
||||
|
||||
test('no file in this folder prints to the console directly (grep test)', () => {
|
||||
for (const f of readdirSync(HERE).filter((f) => f.endsWith('.ts'))) {
|
||||
assert.doesNotMatch(readFileSync(join(HERE, f), 'utf8'), /console\.(log|info|warn|error|debug)|process\.(stdout|stderr)/, f);
|
||||
}
|
||||
});
|
||||
|
||||
test('deploy (PY1.2): link with the claim, then deploy, and the live URL is the proof; vendor lines are not shown', async () => {
|
||||
const { setRunDeploy, liveUrl, shownLines } = await import('./deploy.ts');
|
||||
const piped = [];
|
||||
const prevLink = setLinkRailyard(async (input) => {
|
||||
piped.push(input);
|
||||
return 0;
|
||||
});
|
||||
const prevRun = setRunDeploy(async () => ({
|
||||
code: 0,
|
||||
lines: ['Deploying vite app shop (branch main) as shop', 'Using the Scribase project settings: VITE_SUPABASE_ANON_KEY, VITE_SUPABASE_URL', 'Run railyard login first.', 'Live: https://shop.founder.workers.dev'],
|
||||
}));
|
||||
try {
|
||||
const t = io({ slot: 'deploy', state: 'no_proof_yet', live: true, proof: null, next: 'Deploy from the project folder.', env: {}, claim: { claim: CLAIM, console: 'https://r.example' } });
|
||||
t.io.now = () => 1790683200000;
|
||||
const r = await railyardAddHandler('deploy')(opts, t.io);
|
||||
assert.equal(piped.length, 1);
|
||||
assert.deepEqual(r.proof, { kind: 'deploy', id: 'https://shop.founder.workers.dev', at: 1790683200 });
|
||||
assert.ok(!t.logs.some((l) => /railyard/i.test(l)), 'vendor lines are not shown');
|
||||
assert.ok(t.logs.includes('Live: https://shop.founder.workers.dev'));
|
||||
assert.ok(![...t.logs, JSON.stringify(r)].join('\n').includes(CLAIM));
|
||||
} finally {
|
||||
setLinkRailyard(prevLink);
|
||||
setRunDeploy(prevRun);
|
||||
}
|
||||
assert.equal(liveUrl(['nope']), null);
|
||||
assert.deepEqual(shownLines(['Railyard x', 'ok']), ['ok']);
|
||||
});
|
||||
|
||||
test('a failed deploy is an error with the next step, not a proof', async () => {
|
||||
const { setRunDeploy } = await import('./deploy.ts');
|
||||
const prevLink = setLinkRailyard(async () => 0);
|
||||
const prevRun = setRunDeploy(async () => ({ code: 1, lines: ['X [ERROR] build failed'] }));
|
||||
try {
|
||||
const t = io({ slot: 'deploy', state: 'no_proof_yet', live: true, proof: null, next: null, env: {}, claim: { claim: CLAIM, console: 'https://r.example' } });
|
||||
await assert.rejects(railyardAddHandler('deploy')(opts, t.io), (e) => e.code === 'deploy_failed');
|
||||
} finally {
|
||||
setLinkRailyard(prevLink);
|
||||
setRunDeploy(prevRun);
|
||||
}
|
||||
});
|
||||
|
||||
test('analytics (PY1.3): public site values go to the env file, one check event is sent, and the first event is the proof', async () => {
|
||||
const answers = [
|
||||
{ slot: 'analytics', state: 'no_proof_yet', live: true, proof: null, next: 'Waiting.', env: { NEXT_PUBLIC_ANALYTICS_SITE: 'ry_site_abcdefgh12', ANALYTICS_SCRIPT_URL: 'https://i.example/s.js', ANALYTICS_COLLECTOR_URL: 'https://i.example' } },
|
||||
];
|
||||
const t = io(answers[0]);
|
||||
const sends = [];
|
||||
let polls = 0;
|
||||
let clock = 1790683200000;
|
||||
t.io.now = () => clock;
|
||||
t.io.sleep = async (ms) => void (clock += ms);
|
||||
t.io.fetch = async (url, init) => {
|
||||
if (url === 'https://i.example/api/send') {
|
||||
sends.push({ body: JSON.parse(init.body), ua: init.headers['user-agent'] });
|
||||
return new Response('', { status: 202 });
|
||||
}
|
||||
if (init.method === 'GET') {
|
||||
polls += 1;
|
||||
const live = polls >= 2;
|
||||
return new Response(JSON.stringify({ slot: 'analytics', state: live ? 'live' : 'no_proof_yet', live: true, proof: live ? { kind: 'first_event', id: 'app1', at: '2026-09-29T12:00:06.000Z' } : null, next: null }), { status: 200 });
|
||||
}
|
||||
return new Response(JSON.stringify(answers[0]), { status: 200 });
|
||||
};
|
||||
const r = await railyardAddHandler('analytics')(opts, t.io);
|
||||
assert.deepEqual(r.env_written.sort(), ['ANALYTICS_COLLECTOR_URL', 'ANALYTICS_SCRIPT_URL', 'NEXT_PUBLIC_ANALYTICS_SITE']);
|
||||
assert.equal(sends.length, 1);
|
||||
assert.equal(sends[0].body.payload.website, 'ry_site_abcdefgh12');
|
||||
assert.doesNotMatch(sends[0].ua, /bot|curl|node/i);
|
||||
assert.deepEqual(r.proof, { kind: 'first_event', id: 'app1', at: 1790683206 });
|
||||
assert.ok(t.logs.some((l) => l.includes('data-site="ry_site_abcdefgh12"')));
|
||||
assert.ok(clock - 1790683200000 <= 60_000, 'within 60 s');
|
||||
});
|
||||
|
||||
test('analytics (QY1.2): host and project key reach the env file; the check event also goes to product analytics; the first product event is the proof', async () => {
|
||||
const env = {
|
||||
NEXT_PUBLIC_ANALYTICS_SITE: 'ry_site_abcdefgh12',
|
||||
ANALYTICS_SCRIPT_URL: 'https://i.example/s.js',
|
||||
ANALYTICS_COLLECTOR_URL: 'https://i.example',
|
||||
NEXT_PUBLIC_ANALYTICS_HOST: 'https://pa.example',
|
||||
NEXT_PUBLIC_ANALYTICS_KEY: 'ry_site_abcdefgh12',
|
||||
};
|
||||
const answer = { slot: 'analytics', state: 'no_proof_yet', live: true, proof: null, next: 'Waiting.', env };
|
||||
const t = io(answer);
|
||||
const sends = [];
|
||||
let polls = 0;
|
||||
let clock = 1790683200000;
|
||||
t.io.now = () => clock;
|
||||
t.io.sleep = async (ms) => void (clock += ms);
|
||||
t.io.fetch = async (url, init) => {
|
||||
if (url === 'https://i.example/api/send' || url === 'https://pa.example/capture/') {
|
||||
sends.push({ url, body: JSON.parse(init.body), headers: init.headers });
|
||||
return new Response('{"status":1}', { status: url.includes('pa.example') ? 200 : 202 });
|
||||
}
|
||||
if (init.method === 'GET') {
|
||||
polls += 1;
|
||||
const live = polls >= 2;
|
||||
return new Response(JSON.stringify({ slot: 'analytics', state: live ? 'live' : 'no_proof_yet', live: true, proof: live ? { kind: 'first_product_event', id: 'app1', at: '2026-09-29T12:00:04.000Z' } : null, next: null }), { status: 200 });
|
||||
}
|
||||
return new Response(JSON.stringify(answer), { status: 200 });
|
||||
};
|
||||
const r = await railyardAddHandler('analytics')(opts, t.io);
|
||||
assert.deepEqual(r.env_written.sort(), Object.keys(env).sort());
|
||||
assert.deepEqual(sends.map((s) => s.url), ['https://i.example/api/send', 'https://pa.example/capture/'], 'the page-tag path is kept; product analytics gets the same check');
|
||||
const product = sends[1].body;
|
||||
assert.equal(product.api_key, 'ry_site_abcdefgh12');
|
||||
assert.equal(product.event, 'scribase_proof');
|
||||
assert.equal(product.properties.$process_person_profile, false);
|
||||
assert.doesNotMatch(sends[1].headers['user-agent'], /bot|curl|node/i);
|
||||
assert.deepEqual(r.proof, { kind: 'first_product_event', id: 'app1', at: 1790683204 });
|
||||
assert.ok(t.logs.some((l) => l.includes('https://pa.example') && l.includes('NEXT_PUBLIC_ANALYTICS_KEY')));
|
||||
assert.ok(!t.logs.join('\n').includes('ry_pak_'), 'no server key is ever printed');
|
||||
// An SDK-only stack (no collector) still sends its check to product analytics.
|
||||
const onlyPa = { ...answer, env: { NEXT_PUBLIC_ANALYTICS_SITE: 'ry_site_abcdefgh12', NEXT_PUBLIC_ANALYTICS_HOST: 'https://pa.example', NEXT_PUBLIC_ANALYTICS_KEY: 'ry_site_abcdefgh12' } };
|
||||
const t2 = io(onlyPa);
|
||||
const urls = [];
|
||||
t2.io.fetch = async (url, init) => {
|
||||
if (init.method === 'GET') return new Response(JSON.stringify({ slot: 'analytics', state: 'live', live: true, proof: { kind: 'first_product_event', id: 'app1', at: '2026-09-29T12:00:04.000Z' }, next: null }), { status: 200 });
|
||||
urls.push(url);
|
||||
return new Response(JSON.stringify(url.includes('/capture/') ? { status: 1 } : onlyPa), { status: 200 });
|
||||
};
|
||||
t2.io.now = () => 1790683200000;
|
||||
await railyardAddHandler('analytics')(opts, t2.io);
|
||||
assert.ok(urls.includes('https://pa.example/capture/'));
|
||||
assert.ok(!urls.some((u) => u.endsWith('/api/send')));
|
||||
});
|
||||
|
||||
test('ai (PY1.4): only the public gateway URL reaches the env file; the connect page opens in the browser; connected provider is the proof', async () => {
|
||||
const answer = { slot: 'ai', state: 'needs_connect', live: false, proof: null, next: 'Open the connect link.', env: { AI_GATEWAY_URL: 'https://r.example/api/v1/ai' }, connect_url: 'https://r.example/connect/ai?t=ry_ct_0123456789abcdefghijkl' };
|
||||
const t = io(answer);
|
||||
const opened = [];
|
||||
let polls = 0;
|
||||
let clock = 1790683200000;
|
||||
t.io.now = () => clock;
|
||||
t.io.sleep = async (ms) => void (clock += ms);
|
||||
t.io.openBrowser = (u) => opened.push(u);
|
||||
t.io.fetch = async (url, init) => {
|
||||
if (init.method === 'GET') {
|
||||
polls += 1;
|
||||
const live = polls >= 2;
|
||||
return new Response(JSON.stringify({ slot: 'ai', state: live ? 'live' : 'needs_connect', live, proof: live ? { kind: 'gateway_key', id: 'anthropic', at: '2026-09-29T12:00:09.000Z' } : null, next: null }), { status: 200 });
|
||||
}
|
||||
return new Response(JSON.stringify(answer), { status: 200 });
|
||||
};
|
||||
const r = await railyardAddHandler('ai')({ ...opts, browser: true, waitSeconds: 60 }, t.io);
|
||||
assert.deepEqual(r.env_written, ['AI_GATEWAY_URL']);
|
||||
assert.deepEqual(opened, [answer.connect_url]);
|
||||
assert.deepEqual(r.proof, { kind: 'gateway_key', id: 'anthropic', at: 1790683209 });
|
||||
const envFile = t.files.get('/app/.env.local');
|
||||
assert.ok(!/ry_ai_|AI_GATEWAY_KEY/.test(envFile), 'the key never reaches the env file');
|
||||
});
|
||||
|
||||
test('flags (PY2.1): public flags values go to the env file, one read the way the app reads, and the first read is the proof', async () => {
|
||||
const KEY = 'ry_flags_abcdefghijklmnopqrstuvwxyz012345';
|
||||
const answer = { slot: 'flags', state: 'no_proof_yet', live: true, proof: null, next: 'Read a flag.', env: { NEXT_PUBLIC_FLAGS_KEY: KEY, EXPO_PUBLIC_FLAGS_KEY: KEY, VITE_FLAGS_KEY: KEY, FLAGS_URL: 'https://r.example/api/v1/flags/client' } };
|
||||
const t = io(answer);
|
||||
const reads = [];
|
||||
let polls = 0;
|
||||
let clock = 1790683200000;
|
||||
t.io.now = () => clock;
|
||||
t.io.sleep = async (ms) => void (clock += ms);
|
||||
t.io.fetch = async (url, init) => {
|
||||
if (url.startsWith('https://r.example/api/v1/flags/client')) {
|
||||
reads.push(url);
|
||||
return new Response(JSON.stringify({ env: 'prod', flags: {} }), { status: 200 });
|
||||
}
|
||||
if (init.method === 'GET') {
|
||||
polls += 1;
|
||||
const live = polls >= 2;
|
||||
return new Response(JSON.stringify({ slot: 'flags', state: live ? 'live' : 'no_proof_yet', live: true, proof: live ? { kind: 'first_flag_read', id: 'shop/prod', at: '2026-09-29T12:00:04.000Z' } : null, next: null }), { status: 200 });
|
||||
}
|
||||
return new Response(JSON.stringify(answer), { status: 200 });
|
||||
};
|
||||
const r = await railyardAddHandler('flags')(opts, t.io);
|
||||
assert.deepEqual(r.env_written.sort(), ['EXPO_PUBLIC_FLAGS_KEY', 'FLAGS_URL', 'NEXT_PUBLIC_FLAGS_KEY', 'VITE_FLAGS_KEY']);
|
||||
assert.deepEqual(reads, [`https://r.example/api/v1/flags/client?key=${KEY}`]);
|
||||
assert.deepEqual(r.proof, { kind: 'first_flag_read', id: 'shop/prod', at: 1790683204 });
|
||||
assert.ok(clock - 1790683200000 <= 60_000, 'within 60 s');
|
||||
const bad = io({ ...answer, env: { FLAGS_URL: 'https://r.example/x' } });
|
||||
await assert.rejects(railyardAddHandler('flags')(opts, bad.io), (e) => e.code === 'invalid_response');
|
||||
});
|
||||
|
||||
test('uptime (PY2.2): the site address from the env file is sent, the status page is printed, the first result is the proof', async () => {
|
||||
const answer = { slot: 'uptime', state: 'no_proof_yet', live: true, proof: null, next: 'The first result arrives within two minutes. Status page: https://r.example/status/shop-abc123', env: {} };
|
||||
const t = io(answer);
|
||||
t.files.set('/app/.env.local', 'NEXT_PUBLIC_SITE_URL=https://shop.example.com\n');
|
||||
const posted = [];
|
||||
let polls = 0;
|
||||
let clock = 1790683200000;
|
||||
t.io.now = () => clock;
|
||||
t.io.sleep = async (ms) => void (clock += ms);
|
||||
t.io.fetch = async (url, init) => {
|
||||
if (init.method === 'GET') {
|
||||
polls += 1;
|
||||
const live = polls >= 3;
|
||||
return new Response(JSON.stringify({ slot: 'uptime', state: live ? 'live' : 'no_proof_yet', live: true, proof: live ? { kind: 'check_result', id: 'c1', at: '2026-09-29T12:01:30.000Z' } : null, next: 'Status page: https://r.example/status/shop-abc123' }), { status: 200 });
|
||||
}
|
||||
posted.push(JSON.parse(init.body));
|
||||
return new Response(JSON.stringify(answer), { status: 200 });
|
||||
};
|
||||
const r = await railyardAddHandler('uptime')(opts, t.io);
|
||||
assert.deepEqual(posted, [{ url: 'https://shop.example.com' }]);
|
||||
assert.ok(t.logs.some((l) => l.includes('https://r.example/status/shop-abc123')));
|
||||
assert.deepEqual(r.proof, { kind: 'check_result', id: 'c1', at: 1790683290 });
|
||||
assert.ok(clock - 1790683200000 <= 180_000);
|
||||
const none = io(answer);
|
||||
none.files.delete('/app/.env.local');
|
||||
const bodies = [];
|
||||
none.io.fetch = async (url, init) => (bodies.push(init.body), new Response(JSON.stringify({ ...answer, state: 'live', proof: { kind: 'check_result', id: 'c1', at: 1 } }), { status: 200 }));
|
||||
await railyardAddHandler('uptime')(opts, none.io);
|
||||
assert.deepEqual(bodies, ['{}'], 'no address known: the project\'s latest live deploy is checked');
|
||||
});
|
||||
|
||||
test('billing (PY2.3): the connect page opens in the browser, no key is asked or written, and the connection is awaited', async () => {
|
||||
const answer = { slot: 'billing', state: 'needs_connect', live: false, proof: null, next: 'Open the connect link.', env: {}, connect_url: 'https://mint.example/mint/connect/' + 'a'.repeat(64) };
|
||||
const t = io(answer);
|
||||
const opened = [];
|
||||
let polls = 0;
|
||||
let clock = 1790683200000;
|
||||
t.io.now = () => clock;
|
||||
t.io.sleep = async (ms) => void (clock += ms);
|
||||
t.io.openBrowser = (u) => opened.push(u);
|
||||
t.io.fetch = async (url, init) => {
|
||||
if (init.method === 'GET') {
|
||||
polls += 1;
|
||||
return new Response(JSON.stringify({ slot: 'billing', state: polls >= 2 ? 'no_proof_yet' : 'needs_connect', live: polls >= 2, proof: null, next: null }), { status: 200 });
|
||||
}
|
||||
return new Response(JSON.stringify(answer), { status: 200 });
|
||||
};
|
||||
const r = await railyardAddHandler('billing')({ ...opts, browser: true, waitSeconds: 60 }, t.io);
|
||||
assert.deepEqual(opened, [answer.connect_url]);
|
||||
assert.match(r.next, /test purchase/);
|
||||
assert.deepEqual(r.env_written, []);
|
||||
assert.equal(t.files.get('/app/.env.local'), 'NEXT_PUBLIC_SUPABASE_URL=https://x\n', 'nothing is written');
|
||||
assert.ok(!t.logs.some((l) => /api_key|secret/i.test(l)));
|
||||
});
|
||||
|
||||
test('consent (PY2.5): the template files are copied, Next.js gets its banner, nothing is overwritten', async () => {
|
||||
const answer = { slot: 'consent', state: 'no_proof_yet', live: true, proof: null, next: null, env: { NEXT_PUBLIC_CONSENT_POLICY_VERSION: '1' } };
|
||||
const t = io(answer);
|
||||
t.files.set('/app/package.json', JSON.stringify({ dependencies: { next: '15.0.0' } }));
|
||||
t.files.set('/app/consent/banner.js', '// mine');
|
||||
const r = await railyardAddHandler('consent')(opts, t.io);
|
||||
assert.equal(r.ok, true);
|
||||
assert.ok(t.files.get('/app/consent/consent-core.js').includes('loadAnalyticsWhenAllowed'));
|
||||
assert.equal(t.files.get('/app/consent/banner.js'), '// mine', 'never overwritten');
|
||||
assert.ok(t.files.get('/app/components/ConsentBanner.tsx').includes('ConsentBanner'));
|
||||
assert.deepEqual(r.env_written, ['NEXT_PUBLIC_CONSENT_POLICY_VERSION']);
|
||||
const plain = io(answer);
|
||||
await railyardAddHandler('consent')(opts, plain.io);
|
||||
assert.equal(plain.files.get('/app/components/ConsentBanner.tsx'), undefined, 'no Next.js banner without Next.js');
|
||||
});
|
||||
|
||||
// The upstream monorepo (not shipped here) keeps canonical copies of these
|
||||
// templates under `templates/consent/**` and asserts `consent-files.ts`
|
||||
// stays byte-identical to them. This standalone repo ships only the
|
||||
// already-embedded `contents` strings in `consent-files.ts`, which is what
|
||||
// the CLI actually writes, so that cross-check has nothing to compare
|
||||
// against here and is intentionally not reproduced.
|
||||
55
src/cli/capabilities/railyard/uptime.ts
Normal file
55
src/cli/capabilities/railyard/uptime.ts
Normal file
@ -0,0 +1,55 @@
|
||||
/**
|
||||
* `npx scribase add uptime` (Wave P PY2.2): adds a check for the app's
|
||||
* address (SCRIBASE_UPTIME_URL, else the site URL in the env file, else the
|
||||
* project's latest live deploy), then waits for the first result, which is
|
||||
* the slot's proof, and prints the public status page. Two failures in a row
|
||||
* email the person who added it.
|
||||
*/
|
||||
import type { AddIo, AddOptions, AddResult } from '../../add.js';
|
||||
import { readEnvValue } from '../../envfile.js';
|
||||
import type { SlotAnswer, SlotContext } from './index.js';
|
||||
|
||||
export const WAIT_MS = 180_000;
|
||||
const POLL_MS = 10_000;
|
||||
/** Where the app's address is looked up, in order. */
|
||||
export const URL_NAMES = ['SCRIBASE_UPTIME_URL', 'NEXT_PUBLIC_SITE_URL', 'SITE_URL', 'APP_URL', 'PUBLIC_URL'] as const;
|
||||
const ENV_FILES = ['.env.local', '.env'] as const;
|
||||
|
||||
type ReadSlot = (io: AddIo, ctx: SlotContext) => Promise<SlotAnswer>;
|
||||
|
||||
function toSeconds(at: string | number): number {
|
||||
return typeof at === 'number' ? at : Math.floor(Date.parse(at) / 1000);
|
||||
}
|
||||
|
||||
/** The body of the add request: the app's https address when one is known. */
|
||||
export function uptimeBody(io: AddIo): Record<string, string> {
|
||||
for (const name of URL_NAMES) {
|
||||
const fromEnv = io.env[name]?.trim();
|
||||
if (fromEnv?.startsWith('https://')) return { url: fromEnv };
|
||||
for (const file of ENV_FILES) {
|
||||
const contents = io.readFile(`${io.cwd.replace(/\/+$/, '')}/${file}`);
|
||||
const value = contents ? readEnvValue(contents, name)?.trim() : undefined;
|
||||
if (value?.startsWith('https://')) return { url: value };
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
export async function uptimeFirstResult(result: AddResult, io: AddIo, options: AddOptions, ctx: SlotContext, readSlot: ReadSlot): Promise<AddResult> {
|
||||
if (result.status !== 'live') return result;
|
||||
if (ctx.answer.next) io.log(ctx.answer.next);
|
||||
if (ctx.answer.state === 'live' && ctx.answer.proof) return result;
|
||||
if (!options.wait) return result;
|
||||
io.log('Waiting for the first result...');
|
||||
const deadline = io.now() + WAIT_MS;
|
||||
for (;;) {
|
||||
await io.sleep(POLL_MS);
|
||||
const state = await readSlot(io, ctx);
|
||||
if (state.state === 'live' && state.proof) {
|
||||
return { ...result, live: true, proof: { kind: state.proof.kind, id: state.proof.id, at: toSeconds(state.proof.at) }, sent: true, next: state.next };
|
||||
}
|
||||
if (io.now() >= deadline) {
|
||||
return { ...result, next: 'The check is added; its first result shows in the Uptime tab shortly.' };
|
||||
}
|
||||
}
|
||||
}
|
||||
392
src/cli/connect.ts
Normal file
392
src/cli/connect.ts
Normal file
@ -0,0 +1,392 @@
|
||||
/**
|
||||
* `npx scribase connect [tool...]`: writes the Scribase remote MCP server
|
||||
* (`https://api.scribase.com/mcp`) into every AI coding tool this machine has
|
||||
* installed, in one command — the Neon `neon init` / Vercel `npx add-mcp`
|
||||
* pattern (see `research/scribase-ai-default-2026-11-11.md` P4).
|
||||
*
|
||||
* Supported tools and exactly what each one gets, matching its own documented
|
||||
* config shape (sources: `research/scribase-ai-default-2026-11-11.md` §4):
|
||||
*
|
||||
* claude-code `claude mcp add --transport http --scope user scribase <url>`
|
||||
* cursor ~/.cursor/mcp.json {"mcpServers":{"scribase":{"url":...}}}
|
||||
* vscode ./.vscode/mcp.json {"servers":{"scribase":{"type":"http","url":...}}}
|
||||
* codex ~/.codex/config.toml [mcp_servers.scribase]\n url = "..."\n auth = "oauth"
|
||||
* windsurf ~/.codeium/windsurf/mcp_config.json {"mcpServers":{"scribase":{"serverUrl":...}}}
|
||||
* zed ~/.config/zed/settings.json {"context_servers":{"scribase":{"url":...}}}
|
||||
*
|
||||
* No `Authorization` header is written for the JSON/TOML tools: the server
|
||||
* answers `tools/list` without a token and asks for OAuth only on the first
|
||||
* tool call that needs one, so the client's own OAuth flow (Claude Code,
|
||||
* Cursor, VS Code, Codex all support MCP OAuth) is what runs — never a pasted
|
||||
* token. Every write is idempotent: an identical entry already present is
|
||||
* left untouched and reported as `already_configured`, never duplicated.
|
||||
*
|
||||
* `--dry-run` runs every detection and diff but writes nothing. `--tool <id>`
|
||||
* (repeatable, or positional ids) configures exactly those tools, skipping
|
||||
* auto-detection for them. Auto mode (no `--tool`) only touches tools this
|
||||
* machine actually has (a config directory or a binary on PATH) so a clean
|
||||
* machine's filesystem is left alone.
|
||||
*/
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname } from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
|
||||
import { DEFAULT_API_URL } from './init.js';
|
||||
import { InitError } from './init.js';
|
||||
|
||||
export const TOOL_IDS = ['claude-code', 'cursor', 'vscode', 'codex', 'windsurf', 'zed'] as const;
|
||||
export type ToolId = (typeof TOOL_IDS)[number];
|
||||
|
||||
const TOOL_ALIASES: Record<string, ToolId> = {
|
||||
claude: 'claude-code',
|
||||
'claude-code': 'claude-code',
|
||||
'claude code': 'claude-code',
|
||||
cursor: 'cursor',
|
||||
vscode: 'vscode',
|
||||
'vs-code': 'vscode',
|
||||
'vs code': 'vscode',
|
||||
code: 'vscode',
|
||||
codex: 'codex',
|
||||
windsurf: 'windsurf',
|
||||
zed: 'zed',
|
||||
};
|
||||
|
||||
const TOOL_LABELS: Record<ToolId, string> = {
|
||||
'claude-code': 'Claude Code',
|
||||
cursor: 'Cursor',
|
||||
vscode: 'VS Code',
|
||||
codex: 'Codex',
|
||||
windsurf: 'Windsurf',
|
||||
zed: 'Zed',
|
||||
};
|
||||
|
||||
export interface ConnectOptions {
|
||||
json: boolean;
|
||||
dryRun: boolean;
|
||||
/** `null` = auto-detect every tool; otherwise configure exactly these, unconditionally. */
|
||||
tools: ToolId[] | null;
|
||||
apiUrl?: string;
|
||||
}
|
||||
|
||||
export interface RunOutcome {
|
||||
ok: boolean;
|
||||
output: string;
|
||||
}
|
||||
|
||||
export interface ConnectIo {
|
||||
cwd: string;
|
||||
home: string;
|
||||
env: Record<string, string | undefined>;
|
||||
readFile: (path: string) => string | null;
|
||||
writeFile: (path: string, contents: string) => void;
|
||||
exists: (path: string) => boolean;
|
||||
/** Is `command` runnable on PATH? (e.g. a plain `which`/`where` check.) */
|
||||
which: (command: string) => boolean;
|
||||
/** Runs `command` with `args`, no shell. Used only for the Claude Code CLI. */
|
||||
run: (command: string, args: string[]) => RunOutcome;
|
||||
}
|
||||
|
||||
export type ToolStatus = 'configured' | 'already_configured' | 'would_configure' | 'skipped_not_detected' | 'failed';
|
||||
|
||||
export interface ToolResult {
|
||||
tool: ToolId;
|
||||
label: string;
|
||||
detected: boolean;
|
||||
status: ToolStatus;
|
||||
path?: string;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
export interface ConnectResult {
|
||||
ok: true;
|
||||
mcp_url: string;
|
||||
dry_run: boolean;
|
||||
tools: ToolResult[];
|
||||
}
|
||||
|
||||
function join(root: string, relative: string): string {
|
||||
return `${root.replace(/\/+$/, '')}/${relative}`;
|
||||
}
|
||||
|
||||
/** Parses one `--tool` value (or positional argument) into a {@link ToolId}. */
|
||||
function parseToolId(raw: string): ToolId {
|
||||
const id = TOOL_ALIASES[raw.toLowerCase()];
|
||||
if (!id) {
|
||||
throw new InitError('invalid_argument', `"${raw}" is not a known tool`, `run \`npx scribase connect --help\` for the list (${TOOL_IDS.join(', ')})`);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Parses `connect` arguments. */
|
||||
export function parseConnectArgs(argv: string[]): ConnectOptions {
|
||||
const options: ConnectOptions = { json: false, dryRun: false, tools: null };
|
||||
const selected: ToolId[] = [];
|
||||
let anySelected = false;
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index] ?? '';
|
||||
if (arg === '--json') options.json = true;
|
||||
else if (arg === '--dry-run') options.dryRun = true;
|
||||
else if (arg === '--tool' || arg.startsWith('--tool=')) {
|
||||
const raw = arg.startsWith('--tool=') ? arg.slice('--tool='.length) : argv[++index];
|
||||
if (!raw) throw new InitError('invalid_argument', '--tool needs a value', `one of ${TOOL_IDS.join(', ')}`);
|
||||
anySelected = true;
|
||||
const id = parseToolId(raw);
|
||||
if (!selected.includes(id)) selected.push(id);
|
||||
} else if (arg === '--api-url' || arg.startsWith('--api-url=')) {
|
||||
const raw = arg.startsWith('--api-url=') ? arg.slice('--api-url='.length) : argv[++index];
|
||||
if (!raw) throw new InitError('invalid_argument', '--api-url needs a value');
|
||||
options.apiUrl = raw;
|
||||
} else if (arg.startsWith('--')) {
|
||||
throw new InitError('invalid_argument', `unknown option ${arg}`, 'run `npx scribase connect --help`');
|
||||
} else {
|
||||
anySelected = true;
|
||||
const id = parseToolId(arg);
|
||||
if (!selected.includes(id)) selected.push(id);
|
||||
}
|
||||
}
|
||||
if (anySelected) options.tools = selected;
|
||||
return options;
|
||||
}
|
||||
|
||||
function mcpUrl(options: ConnectOptions, io: Pick<ConnectIo, 'env'>): string {
|
||||
const apiUrl = (options.apiUrl ?? io.env.SCRIBASE_API_URL ?? DEFAULT_API_URL).replace(/\/+$/, '');
|
||||
return `${apiUrl}/mcp`;
|
||||
}
|
||||
|
||||
/** Deep-equal for the small plain-object entries this file writes; order-independent. */
|
||||
function sameEntry(a: unknown, b: unknown): boolean {
|
||||
if (a === b) return true;
|
||||
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
|
||||
const aKeys = Object.keys(a as Record<string, unknown>).sort();
|
||||
const bKeys = Object.keys(b as Record<string, unknown>).sort();
|
||||
if (aKeys.length !== bKeys.length || aKeys.some((key, index) => key !== bKeys[index])) return false;
|
||||
return aKeys.every((key) => sameEntry((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]));
|
||||
}
|
||||
|
||||
interface MergeOutcome {
|
||||
content: string;
|
||||
changed: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges `{ [topKey]: { [entryKey]: entry } }` into an existing JSON file's
|
||||
* text (or a fresh object when there is none yet), preserving every other
|
||||
* key. Throws {@link InitError} `invalid_config` when the existing file is
|
||||
* not valid JSON — this command never overwrites a file it cannot parse.
|
||||
*/
|
||||
export function mergeJsonServer(existing: string | null, path: string, topKey: string, entryKey: string, entry: Record<string, unknown>): MergeOutcome {
|
||||
let parsed: Record<string, unknown> = {};
|
||||
if (existing !== null && existing.trim().length > 0) {
|
||||
try {
|
||||
parsed = JSON.parse(existing) as Record<string, unknown>;
|
||||
} catch {
|
||||
throw new InitError('invalid_config', `${path} is not valid JSON`, 'fix or remove it, then run `npx scribase connect` again');
|
||||
}
|
||||
}
|
||||
const container = { ...((parsed[topKey] as Record<string, unknown> | undefined) ?? {}) };
|
||||
if (sameEntry(container[entryKey], entry)) {
|
||||
return { content: existing ?? `${JSON.stringify(parsed, null, 2)}\n`, changed: false };
|
||||
}
|
||||
container[entryKey] = entry;
|
||||
const next = { ...parsed, [topKey]: container };
|
||||
return { content: `${JSON.stringify(next, null, 2)}\n`, changed: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a `[header]` TOML table when it is not already present (checked by
|
||||
* a literal `[header]` line, not a full parse — safe because this command
|
||||
* only ever adds a brand-new table, never edits one). Idempotent: a file
|
||||
* that already declares the table is returned unchanged.
|
||||
*/
|
||||
export function mergeTomlSection(existing: string | null, header: string, lines: readonly string[]): MergeOutcome {
|
||||
const text = existing ?? '';
|
||||
const headerLine = `[${header}]`;
|
||||
if (text.split('\n').some((line) => line.trim() === headerLine)) {
|
||||
return { content: text, changed: false };
|
||||
}
|
||||
const prefix = text.length === 0 ? '' : text.endsWith('\n\n') ? '' : text.endsWith('\n') ? '\n' : '\n\n';
|
||||
return { content: `${text}${prefix}${headerLine}\n${lines.map((line) => `${line}\n`).join('')}`, changed: true };
|
||||
}
|
||||
|
||||
function detect(id: ToolId, io: ConnectIo): boolean {
|
||||
switch (id) {
|
||||
case 'claude-code':
|
||||
return io.which('claude');
|
||||
case 'cursor':
|
||||
return io.exists(join(io.home, '.cursor')) || io.exists(join(io.home, '.cursor/mcp.json'));
|
||||
case 'vscode':
|
||||
return io.which('code') || io.exists(join(io.cwd, '.vscode'));
|
||||
case 'codex':
|
||||
return io.exists(join(io.home, '.codex')) || io.which('codex');
|
||||
case 'windsurf':
|
||||
return io.exists(join(io.home, '.codeium/windsurf')) || io.exists(join(io.home, '.windsurf'));
|
||||
case 'zed':
|
||||
return io.exists(join(io.home, '.config/zed'));
|
||||
}
|
||||
}
|
||||
|
||||
function applyClaudeCode(io: ConnectIo, url: string, dryRun: boolean): ToolResult {
|
||||
const label = TOOL_LABELS['claude-code'];
|
||||
if (dryRun) {
|
||||
return { tool: 'claude-code', label, detected: true, status: 'would_configure', detail: `claude mcp add --transport http --scope user scribase ${url}` };
|
||||
}
|
||||
const outcome = io.run('claude', ['mcp', 'add', '--transport', 'http', '--scope', 'user', 'scribase', url]);
|
||||
if (outcome.ok) {
|
||||
const firstLine = outcome.output.trim().split('\n')[0];
|
||||
return firstLine ? { tool: 'claude-code', label, detected: true, status: 'configured', detail: firstLine } : { tool: 'claude-code', label, detected: true, status: 'configured' };
|
||||
}
|
||||
if (/already exists/i.test(outcome.output)) {
|
||||
return { tool: 'claude-code', label, detected: true, status: 'already_configured' };
|
||||
}
|
||||
return { tool: 'claude-code', label, detected: true, status: 'failed', detail: outcome.output.trim().slice(0, 300) || 'claude mcp add failed' };
|
||||
}
|
||||
|
||||
function applyJsonTool(io: ConnectIo, id: ToolId, path: string, topKey: string, entry: Record<string, unknown>, dryRun: boolean): ToolResult {
|
||||
const label = TOOL_LABELS[id];
|
||||
let merge: MergeOutcome;
|
||||
try {
|
||||
merge = mergeJsonServer(io.readFile(path), path, topKey, 'scribase', entry);
|
||||
} catch (error) {
|
||||
return { tool: id, label, detected: true, status: 'failed', path, detail: (error as Error).message };
|
||||
}
|
||||
if (!merge.changed) return { tool: id, label, detected: true, status: 'already_configured', path };
|
||||
if (dryRun) return { tool: id, label, detected: true, status: 'would_configure', path };
|
||||
io.writeFile(path, merge.content);
|
||||
return { tool: id, label, detected: true, status: 'configured', path };
|
||||
}
|
||||
|
||||
function applyCodex(io: ConnectIo, url: string, dryRun: boolean): ToolResult {
|
||||
const path = join(io.home, '.codex/config.toml');
|
||||
const merge = mergeTomlSection(io.readFile(path), 'mcp_servers.scribase', [`url = "${url}"`, 'auth = "oauth"']);
|
||||
if (!merge.changed) return { tool: 'codex', label: TOOL_LABELS.codex, detected: true, status: 'already_configured', path };
|
||||
if (dryRun) return { tool: 'codex', label: TOOL_LABELS.codex, detected: true, status: 'would_configure', path };
|
||||
io.writeFile(path, merge.content);
|
||||
return { tool: 'codex', label: TOOL_LABELS.codex, detected: true, status: 'configured', path };
|
||||
}
|
||||
|
||||
function applyTool(io: ConnectIo, id: ToolId, url: string, dryRun: boolean): ToolResult {
|
||||
switch (id) {
|
||||
case 'claude-code':
|
||||
return applyClaudeCode(io, url, dryRun);
|
||||
case 'cursor':
|
||||
return applyJsonTool(io, 'cursor', join(io.home, '.cursor/mcp.json'), 'mcpServers', { url }, dryRun);
|
||||
case 'vscode':
|
||||
return applyJsonTool(io, 'vscode', join(io.cwd, '.vscode/mcp.json'), 'servers', { type: 'http', url }, dryRun);
|
||||
case 'windsurf':
|
||||
return applyJsonTool(io, 'windsurf', join(io.home, '.codeium/windsurf/mcp_config.json'), 'mcpServers', { serverUrl: url }, dryRun);
|
||||
case 'zed':
|
||||
return applyJsonTool(io, 'zed', join(io.home, '.config/zed/settings.json'), 'context_servers', { url }, dryRun);
|
||||
case 'codex':
|
||||
return applyCodex(io, url, dryRun);
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs `connect` and returns its result. Never throws for a single tool's own failure. */
|
||||
export function runConnect(options: ConnectOptions, io: ConnectIo): ConnectResult {
|
||||
const url = mcpUrl(options, io);
|
||||
const targets = options.tools ?? [...TOOL_IDS];
|
||||
const tools: ToolResult[] = [];
|
||||
for (const id of targets) {
|
||||
const detected = detect(id, io);
|
||||
if (options.tools === null && !detected) {
|
||||
tools.push({ tool: id, label: TOOL_LABELS[id], detected: false, status: 'skipped_not_detected' });
|
||||
continue;
|
||||
}
|
||||
tools.push(applyTool(io, id, url, options.dryRun));
|
||||
}
|
||||
return { ok: true, mcp_url: url, dry_run: options.dryRun, tools };
|
||||
}
|
||||
|
||||
/** The human-readable output of {@link runConnect}. */
|
||||
export function formatConnect(result: ConnectResult): string {
|
||||
const lines: string[] = [`MCP server: ${result.mcp_url}${result.dry_run ? ' (dry run, nothing written)' : ''}`, ''];
|
||||
for (const tool of result.tools) {
|
||||
const mark =
|
||||
tool.status === 'configured'
|
||||
? 'done'
|
||||
: tool.status === 'already_configured'
|
||||
? 'already set up'
|
||||
: tool.status === 'would_configure'
|
||||
? 'would configure'
|
||||
: tool.status === 'skipped_not_detected'
|
||||
? 'not detected, skipped'
|
||||
: 'FAILED';
|
||||
lines.push(` ${tool.label.padEnd(12)} ${mark}${tool.path ? ` (${tool.path})` : ''}${tool.detail ? ` ${tool.detail}` : ''}`);
|
||||
}
|
||||
lines.push('');
|
||||
if (!result.dry_run && result.tools.some((tool) => tool.status === 'configured')) {
|
||||
lines.push('Restart or reload the configured tool(s) to pick up the new server.', '');
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export const CONNECT_HELP = `Usage: npx scribase connect [tool...] [--tool <id>]... [--dry-run] [--json] [--api-url <url>]
|
||||
|
||||
Writes the Scribase MCP server (https://api.scribase.com/mcp) into every AI
|
||||
coding tool this machine has installed: ${TOOL_IDS.join(', ')}.
|
||||
|
||||
With no tool named, only tools actually detected on this machine (a config
|
||||
directory or a binary on PATH) are configured; everything else is reported
|
||||
as "not detected, skipped". Naming one or more tools (as arguments or
|
||||
repeated --tool) configures exactly those, regardless of detection.
|
||||
|
||||
Every write is idempotent: an identical entry already there is left alone.
|
||||
No access token or secret is ever written; tools that support MCP OAuth
|
||||
(Claude Code, Cursor, VS Code, Codex) authenticate in the browser on first
|
||||
use instead.
|
||||
|
||||
--dry-run show what would change; write nothing
|
||||
--json print one JSON object
|
||||
--tool <id> configure only this tool (repeatable)
|
||||
--api-url <url> control plane (default: SCRIBASE_API_URL or https://api.scribase.com)
|
||||
`;
|
||||
|
||||
/** The real-process IO for `connect`. */
|
||||
export function nodeConnectIo(json: boolean): ConnectIo {
|
||||
const which = (command: string): boolean => {
|
||||
const probe =
|
||||
process.platform === 'win32' ? spawnSync('where', [command], { encoding: 'utf8' }) : spawnSync('command', ['-v', command], { encoding: 'utf8', shell: true });
|
||||
return probe.status === 0;
|
||||
};
|
||||
void json; // reserved: nothing is logged outside the one JSON/text result line today.
|
||||
return {
|
||||
cwd: process.cwd(),
|
||||
home: homedir(),
|
||||
env: process.env,
|
||||
readFile: (path) => (existsSync(path) ? readFileSync(path, 'utf8') : null),
|
||||
writeFile: (path, contents) => {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, contents);
|
||||
},
|
||||
exists: (path) => existsSync(path),
|
||||
which,
|
||||
run: (command, args) => {
|
||||
const result = spawnSync(command, args, { encoding: 'utf8' });
|
||||
return { ok: result.status === 0, output: `${result.stdout ?? ''}${result.stderr ?? ''}` };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Entry point for the `connect` command; returns the exit code. */
|
||||
export function connectMain(argv: string[], io: ConnectIo, write: (text: string) => void): number {
|
||||
if (argv.includes('--help') || argv.includes('-h')) {
|
||||
write(CONNECT_HELP);
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
const options = parseConnectArgs(argv);
|
||||
const result = runConnect(options, io);
|
||||
write(options.json ? `${JSON.stringify(result)}\n` : formatConnect(result));
|
||||
return result.tools.some((tool) => tool.status === 'failed') ? 1 : 0;
|
||||
} catch (error) {
|
||||
const failure =
|
||||
error instanceof InitError
|
||||
? { code: error.code, message: error.message, next: error.next ?? null }
|
||||
: { code: 'unexpected_error', message: (error as Error).message, next: null };
|
||||
const json = argv.includes('--json');
|
||||
write(json ? `${JSON.stringify({ ok: false, error: failure })}\n` : `scribase connect: ${failure.message}\n${failure.next ? ` next: ${failure.next}\n` : ''}`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
160
src/cli/credentials.ts
Normal file
160
src/cli/credentials.ts
Normal file
@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Stored CLI credentials, shared with the Rust `scribase` CLI:
|
||||
* `$XDG_CONFIG_HOME/scribase/credentials` (default `~/.config/scribase`),
|
||||
* mode 0600, holding `api_url` and either `access_token` or
|
||||
* `token_store=keychain`, in which case the token lives in the OS credential
|
||||
* store (macOS keychain via `security`, Linux Secret Service via
|
||||
* `secret-tool`) under service `scribase`, account = the API URL. The token
|
||||
* is handed to those tools on standard input, never as an argument.
|
||||
* `SCRIBASE_NO_KEYCHAIN=1` forces the file.
|
||||
*/
|
||||
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync, chmodSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
const SERVICE = 'scribase';
|
||||
|
||||
export interface StoredCredentials {
|
||||
apiUrl?: string;
|
||||
token?: string;
|
||||
}
|
||||
|
||||
export function configDir(env: NodeJS.ProcessEnv): string {
|
||||
return join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'scribase');
|
||||
}
|
||||
|
||||
export function credentialsPath(env: NodeJS.ProcessEnv): string {
|
||||
return join(configDir(env), 'credentials');
|
||||
}
|
||||
|
||||
/** Parses the credentials file (`key=value` lines). */
|
||||
export function parseCredentialsFile(text: string): { apiUrl?: string; token?: string; tokenStore?: string } {
|
||||
const out: { apiUrl?: string; token?: string; tokenStore?: string } = {};
|
||||
for (const line of text.split('\n')) {
|
||||
const at = line.indexOf('=');
|
||||
if (at < 0) continue;
|
||||
const key = line.slice(0, at).trim();
|
||||
const value = line.slice(at + 1).trim();
|
||||
if (!value) continue;
|
||||
if (key === 'api_url') out.apiUrl = value;
|
||||
if (key === 'access_token') out.token = value;
|
||||
if (key === 'token_store') out.tokenStore = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
type Store = 'mac' | 'secret-service';
|
||||
|
||||
function keychain(env: NodeJS.ProcessEnv): Store | null {
|
||||
if (env.SCRIBASE_NO_KEYCHAIN && env.SCRIBASE_NO_KEYCHAIN !== '0') return null;
|
||||
const store: Store | null = process.platform === 'darwin' ? 'mac' : process.platform === 'linux' ? 'secret-service' : null;
|
||||
if (!store) return null;
|
||||
const probe = spawnSync(store === 'mac' ? 'security' : 'secret-tool', ['--help'], { stdio: 'ignore' });
|
||||
return probe.error ? null : store;
|
||||
}
|
||||
|
||||
function safeAccount(account: string): boolean {
|
||||
return account.length > 0 && account.length <= 512 && !/["\\\u0000-\u001f]/.test(account);
|
||||
}
|
||||
|
||||
const TOKEN_SHAPE = /^[A-Za-z0-9._~+/=-]{1,16384}$/;
|
||||
|
||||
/** The `security -i` command that saves a token; the token rides on stdin. */
|
||||
export function macStoreCommand(account: string, token: string): string {
|
||||
return `add-generic-password -U -s ${SERVICE} -l "Scribase CLI" -a "${account}" -w "${token}"\n`;
|
||||
}
|
||||
|
||||
function keychainLoad(store: Store, account: string): string | undefined {
|
||||
if (!safeAccount(account)) return undefined;
|
||||
const result =
|
||||
store === 'mac'
|
||||
? spawnSync('security', ['find-generic-password', '-s', SERVICE, '-a', account, '-w'], { encoding: 'utf8' })
|
||||
: spawnSync('secret-tool', ['lookup', 'service', SERVICE, 'account', account], { encoding: 'utf8' });
|
||||
const token = (result.stdout ?? '').trim();
|
||||
return result.status === 0 && TOKEN_SHAPE.test(token) ? token : undefined;
|
||||
}
|
||||
|
||||
function keychainSave(store: Store, account: string, token: string): boolean {
|
||||
if (!safeAccount(account) || !TOKEN_SHAPE.test(token)) return false;
|
||||
const result =
|
||||
store === 'mac'
|
||||
? spawnSync('security', ['-i'], { input: macStoreCommand(account, token), stdio: ['pipe', 'ignore', 'ignore'] })
|
||||
: spawnSync('secret-tool', ['store', '--label=Scribase CLI', 'service', SERVICE, 'account', account], {
|
||||
input: token,
|
||||
stdio: ['pipe', 'ignore', 'ignore'],
|
||||
});
|
||||
// `security -i` exits 0 even when its command fails: read it back.
|
||||
return result.status === 0 && keychainLoad(store, account) === token;
|
||||
}
|
||||
|
||||
function writePrivate(path: string, contents: string): void {
|
||||
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(path, contents, { mode: 0o600 });
|
||||
// Tighten a file that existed with a wider mode.
|
||||
chmodSync(path, 0o600);
|
||||
}
|
||||
|
||||
/** Reads the stored API URL and token (from the keychain when recorded there). */
|
||||
export function readCredentials(env: NodeJS.ProcessEnv): StoredCredentials {
|
||||
const path = credentialsPath(env);
|
||||
if (!existsSync(path)) return {};
|
||||
const parsed = parseCredentialsFile(readFileSync(path, 'utf8'));
|
||||
const out: StoredCredentials = {};
|
||||
if (parsed.apiUrl) out.apiUrl = parsed.apiUrl;
|
||||
if (parsed.token) out.token = parsed.token;
|
||||
if (!out.token && parsed.tokenStore === 'keychain' && parsed.apiUrl) {
|
||||
const store = keychain(env);
|
||||
const token = store ? keychainLoad(store, parsed.apiUrl) : undefined;
|
||||
if (token) out.token = token;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Stores a token for `apiUrl`; returns where it went (for display). Never prints it. */
|
||||
export function storeCredentials(env: NodeJS.ProcessEnv, apiUrl: string, token: string): string {
|
||||
const path = credentialsPath(env);
|
||||
const store = keychain(env);
|
||||
if (store && keychainSave(store, apiUrl, token)) {
|
||||
writePrivate(path, `api_url=${apiUrl}\ntoken_store=keychain\n`);
|
||||
return store === 'mac' ? 'the macOS keychain' : 'the Secret Service keyring';
|
||||
}
|
||||
writePrivate(path, `api_url=${apiUrl}\naccess_token=${token}\n`);
|
||||
return path;
|
||||
}
|
||||
|
||||
/** The pending device login, kept between `--no-wait` runs (0600). */
|
||||
export function pendingStore(env: NodeJS.ProcessEnv): { read: () => string | null; write: (text: string) => void; clear: () => void } {
|
||||
const path = join(configDir(env), 'pending-login');
|
||||
return {
|
||||
read: () => (existsSync(path) ? readFileSync(path, 'utf8') : null),
|
||||
write: (text) => writePrivate(path, text),
|
||||
clear: () => rmSync(path, { force: true }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* This machine's anonymous CLI install id: a random id created once in
|
||||
* `<config dir>/install-id` (mode 0600). It rides on claim links as `?ref=`
|
||||
* so a claim can be credited to where the project came from. It carries no
|
||||
* personal data. `SCRIBASE_NO_REF=1` sends none. Returns null when the file
|
||||
* cannot be read or written.
|
||||
*/
|
||||
export function installId(env: NodeJS.ProcessEnv, random: () => string = () => randomUUID().replace(/-/g, '')): string | null {
|
||||
if (env.SCRIBASE_NO_REF === '1') return null;
|
||||
const path = join(configDir(env), 'install-id');
|
||||
try {
|
||||
if (existsSync(path)) {
|
||||
const value = readFileSync(path, 'utf8').trim();
|
||||
if (/^[A-Za-z0-9_-]{8,64}$/.test(value)) return value;
|
||||
}
|
||||
const value = random();
|
||||
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(path, `${value}\n`, { mode: 0o600 });
|
||||
return value;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
304
src/cli/doctor.ts
Normal file
304
src/cli/doctor.ts
Normal file
@ -0,0 +1,304 @@
|
||||
/**
|
||||
* `npx scribase doctor` — checks that this app can reach its Scribase backend
|
||||
* and prints one fix per problem:
|
||||
*
|
||||
* - the project link (`.scribase/project.json`) and the env file exist;
|
||||
* - the URL and publishable (anon) key variables are set and well formed;
|
||||
* - the secret (service-role) key is not in a variable the framework ships to
|
||||
* the browser or app bundle;
|
||||
* - the env file is ignored by git;
|
||||
* - the backend answers: Auth health and the REST API, with the app's key;
|
||||
* - a temporary project is not expired or about to expire.
|
||||
*
|
||||
* Values are never printed, only variable names. All I/O goes through
|
||||
* {@link DoctorIo} so the checks run offline in tests.
|
||||
*/
|
||||
|
||||
import { conventionsFor, detectFramework } from './framework.js';
|
||||
import type { Framework, ProjectFacts } from './framework.js';
|
||||
import { ensureIgnored, readEnvValue } from './envfile.js';
|
||||
|
||||
export type CheckStatus = 'ok' | 'problem' | 'warning';
|
||||
|
||||
export interface DoctorCheck {
|
||||
id: string;
|
||||
status: CheckStatus;
|
||||
detail: string;
|
||||
/** One concrete fix, set for problems and warnings. */
|
||||
fix?: string;
|
||||
}
|
||||
|
||||
export interface DoctorResult {
|
||||
ok: boolean;
|
||||
framework: Framework;
|
||||
env_file: string;
|
||||
checks: DoctorCheck[];
|
||||
}
|
||||
|
||||
export interface DoctorIo {
|
||||
cwd: string;
|
||||
fetch: typeof fetch;
|
||||
readFile: (path: string) => string | null;
|
||||
exists: (path: string) => boolean;
|
||||
/** Wall clock in milliseconds. */
|
||||
now: () => number;
|
||||
}
|
||||
|
||||
/** Prefixes a framework exposes to client bundles. */
|
||||
const PUBLIC_PREFIXES = ['NEXT_PUBLIC_', 'EXPO_PUBLIC_', 'VITE_', 'PUBLIC_', 'REACT_APP_'];
|
||||
const EXPIRY_WARNING_SECONDS = 24 * 3600;
|
||||
const PROBE_TIMEOUT_MS = 8000;
|
||||
|
||||
interface State {
|
||||
temporary?: boolean;
|
||||
claim_url?: string;
|
||||
expires_at?: number;
|
||||
organization_id?: string;
|
||||
project_id?: string;
|
||||
}
|
||||
|
||||
function join(root: string, relative: string): string {
|
||||
return `${root.replace(/\/+$/, '')}/${relative}`;
|
||||
}
|
||||
|
||||
/** The JWT payload's `role`, or null when `value` is not a readable JWT. */
|
||||
export function jwtRole(value: string): string | null {
|
||||
const parts = value.split('.');
|
||||
if (parts.length !== 3 || !parts[1]) return null;
|
||||
try {
|
||||
const json = Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
|
||||
const payload = JSON.parse(json) as { role?: unknown };
|
||||
return typeof payload.role === 'string' ? payload.role : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether `value` is shaped like a publishable key (a JWT, or an `sb_publishable_` key). */
|
||||
export function looksLikePublicKey(value: string): boolean {
|
||||
return value.startsWith('sb_publishable_') || value.split('.').length === 3;
|
||||
}
|
||||
|
||||
/** Every `NAME=value` pair in an env file (last one wins). */
|
||||
export function envEntries(contents: string): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
for (const line of contents.split(/\r?\n/)) {
|
||||
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
|
||||
const name = match?.[1];
|
||||
if (!name) continue;
|
||||
const value = readEnvValue(line, name);
|
||||
if (value !== undefined) out.set(name, value);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Public variables that hold a secret (service-role) key. */
|
||||
export function leakedSecretVars(entries: Map<string, string>, serviceKey: string | undefined): string[] {
|
||||
const leaked: string[] = [];
|
||||
for (const [name, value] of entries) {
|
||||
if (!PUBLIC_PREFIXES.some((prefix) => name.startsWith(prefix)) || value.length === 0) continue;
|
||||
if ((serviceKey && value === serviceKey) || jwtRole(value) === 'service_role' || value.startsWith('sb_secret_')) {
|
||||
leaked.push(name);
|
||||
}
|
||||
}
|
||||
return leaked.sort();
|
||||
}
|
||||
|
||||
async function probe(io: DoctorIo, url: string, key: string): Promise<{ status: number } | { error: string }> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await io.fetch(url, {
|
||||
method: 'GET',
|
||||
headers: { apikey: key, authorization: `Bearer ${key}`, accept: 'application/json', 'user-agent': 'scribase-doctor' },
|
||||
signal: controller.signal,
|
||||
});
|
||||
await response.text().catch(() => '');
|
||||
return { status: response.status };
|
||||
} catch (error) {
|
||||
return { error: (error as Error).name === 'AbortError' ? `no answer within ${PROBE_TIMEOUT_MS / 1000} s` : (error as Error).message };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
function readState(io: DoctorIo): State | null {
|
||||
const text = io.readFile(join(io.cwd, '.scribase/project.json'));
|
||||
if (!text) return null;
|
||||
try {
|
||||
return JSON.parse(text) as State;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function temporaryCheck(state: State, now: number): DoctorCheck | null {
|
||||
if (!state.temporary || !state.expires_at) return null;
|
||||
const left = state.expires_at - Math.floor(now / 1000);
|
||||
const keep = state.claim_url ? `open the claim link in .scribase/project.json (claim_url), sign up and add a card` : 'open the claim link init printed';
|
||||
if (left <= 0) {
|
||||
return {
|
||||
id: 'temporary_expiry',
|
||||
status: 'problem',
|
||||
detail: 'this temporary project expired and was deleted',
|
||||
fix: 'run `npx scribase init` again for a new one (or `npx scribase init --account` to use an account)',
|
||||
};
|
||||
}
|
||||
const hours = Math.floor(left / 3600);
|
||||
const minutes = Math.floor((left % 3600) / 60);
|
||||
const remaining = hours > 0 ? `${hours} h ${minutes} min` : `${minutes} min`;
|
||||
if (left < EXPIRY_WARNING_SECONDS) {
|
||||
return { id: 'temporary_expiry', status: 'warning', detail: `this temporary project is deleted in ${remaining}`, fix: `to keep it, ${keep}` };
|
||||
}
|
||||
return { id: 'temporary_expiry', status: 'ok', detail: `temporary project, deleted in ${remaining} unless claimed` };
|
||||
}
|
||||
|
||||
/** Runs every check. Never throws for a failed check; each becomes a result line. */
|
||||
export async function runDoctor(io: DoctorIo): Promise<DoctorResult> {
|
||||
const exists = (relative: string) => io.exists(join(io.cwd, relative));
|
||||
let packageJson: ProjectFacts['packageJson'] = null;
|
||||
const checks: DoctorCheck[] = [];
|
||||
const packageText = io.readFile(join(io.cwd, 'package.json'));
|
||||
if (packageText) {
|
||||
try {
|
||||
packageJson = JSON.parse(packageText) as ProjectFacts['packageJson'];
|
||||
} catch {
|
||||
checks.push({ id: 'package_json', status: 'problem', detail: 'package.json is not valid JSON', fix: 'fix the JSON syntax in package.json' });
|
||||
}
|
||||
}
|
||||
const facts = { packageJson, exists };
|
||||
const framework = detectFramework(facts);
|
||||
const conventions = conventionsFor(framework, facts);
|
||||
const done = (): DoctorResult => ({
|
||||
ok: checks.every((check) => check.status !== 'problem'),
|
||||
framework,
|
||||
env_file: conventions.envFile,
|
||||
checks,
|
||||
});
|
||||
|
||||
const state = readState(io);
|
||||
checks.push(
|
||||
state
|
||||
? { id: 'project_link', status: 'ok', detail: `linked to ${state.organization_id ?? '?'}/${state.project_id ?? '?'}` }
|
||||
: { id: 'project_link', status: 'warning', detail: 'no .scribase/project.json in this folder', fix: 'run `npx scribase init` here to link a backend' },
|
||||
);
|
||||
|
||||
const envText = io.readFile(join(io.cwd, conventions.envFile));
|
||||
if (envText === null) {
|
||||
checks.push({ id: 'env_file', status: 'problem', detail: `${conventions.envFile} is missing`, fix: 'run `npx scribase init` to write it' });
|
||||
return done();
|
||||
}
|
||||
checks.push({ id: 'env_file', status: 'ok', detail: `${conventions.envFile} found` });
|
||||
const entries = envEntries(envText);
|
||||
|
||||
const url = entries.get(conventions.urlVar) ?? '';
|
||||
let parsedUrl: URL | null = null;
|
||||
try {
|
||||
parsedUrl = url ? new URL(url) : null;
|
||||
} catch {
|
||||
parsedUrl = null;
|
||||
}
|
||||
if (!url) {
|
||||
checks.push({ id: 'url', status: 'problem', detail: `${conventions.urlVar} is not set`, fix: 'run `npx scribase init` to write it' });
|
||||
} else if (!parsedUrl || !/^https?:$/.test(parsedUrl.protocol)) {
|
||||
checks.push({ id: 'url', status: 'problem', detail: `${conventions.urlVar} is not a URL`, fix: 'run `npx scribase init` to rewrite it' });
|
||||
} else {
|
||||
checks.push({ id: 'url', status: 'ok', detail: `${conventions.urlVar} is set (${parsedUrl.host})` });
|
||||
}
|
||||
|
||||
const anon = entries.get(conventions.anonKeyVar) ?? '';
|
||||
const anonRole = anon ? jwtRole(anon) : null;
|
||||
if (!anon) {
|
||||
checks.push({ id: 'anon_key', status: 'problem', detail: `${conventions.anonKeyVar} is not set`, fix: 'run `npx scribase init` to write it' });
|
||||
} else if (anonRole === 'service_role' || anon.startsWith('sb_secret_')) {
|
||||
checks.push({
|
||||
id: 'anon_key',
|
||||
status: 'problem',
|
||||
detail: `${conventions.anonKeyVar} holds the secret key, not the publishable one`,
|
||||
fix: 'rotate the secret key in the console (API keys), then run `npx scribase init` to write the publishable key',
|
||||
});
|
||||
} else if (!looksLikePublicKey(anon)) {
|
||||
checks.push({ id: 'anon_key', status: 'problem', detail: `${conventions.anonKeyVar} does not look like a key`, fix: 'run `npx scribase init` to rewrite it' });
|
||||
} else {
|
||||
checks.push({ id: 'anon_key', status: 'ok', detail: `${conventions.anonKeyVar} is set` });
|
||||
}
|
||||
|
||||
const leaked = leakedSecretVars(entries, conventions.serviceRoleVar ? entries.get(conventions.serviceRoleVar) : undefined).filter(
|
||||
(name) => name !== conventions.anonKeyVar,
|
||||
);
|
||||
checks.push(
|
||||
leaked.length > 0
|
||||
? {
|
||||
id: 'secret_exposure',
|
||||
status: 'problem',
|
||||
detail: `the secret key is in ${leaked.join(', ')}, which ships to the browser or app bundle`,
|
||||
fix: `remove ${leaked.join(', ')} and rotate the secret key in the console (API keys)`,
|
||||
}
|
||||
: { id: 'secret_exposure', status: 'ok', detail: 'no secret key in a public variable' },
|
||||
);
|
||||
|
||||
const gitignore = io.readFile(join(io.cwd, '.gitignore')) ?? '';
|
||||
checks.push(
|
||||
ensureIgnored(gitignore, conventions.envFile) === null
|
||||
? { id: 'gitignore', status: 'ok', detail: `${conventions.envFile} is ignored by git` }
|
||||
: { id: 'gitignore', status: 'problem', detail: `${conventions.envFile} is not in .gitignore`, fix: `add ${conventions.envFile} to .gitignore before you commit` },
|
||||
);
|
||||
|
||||
if (state) {
|
||||
const expiry = temporaryCheck(state, io.now());
|
||||
if (expiry) checks.push(expiry);
|
||||
if (state.temporary && !entries.get('SCRIBASE_ACCESS_TOKEN')) {
|
||||
checks.push({
|
||||
id: 'agent_token',
|
||||
status: 'warning',
|
||||
detail: `SCRIBASE_ACCESS_TOKEN is not in ${conventions.envFile}, so migrations and SQL from this folder cannot reach the temporary project`,
|
||||
fix: 'run `npx scribase init` again to restore it',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (parsedUrl && anon && looksLikePublicKey(anon)) {
|
||||
const base = url.replace(/\/+$/, '');
|
||||
const auth = await probe(io, `${base}/auth/v1/health`, anon);
|
||||
if ('error' in auth) {
|
||||
checks.push({ id: 'reach_auth', status: 'problem', detail: `could not reach ${parsedUrl.host}: ${auth.error}`, fix: 'check your network, then the URL; a paused project wakes on this request, so try again in a minute' });
|
||||
} else if (auth.status >= 200 && auth.status < 300) {
|
||||
checks.push({ id: 'reach_auth', status: 'ok', detail: 'Auth answers' });
|
||||
} else {
|
||||
checks.push({
|
||||
id: 'reach_auth',
|
||||
status: 'problem',
|
||||
detail: `Auth answered HTTP ${auth.status}`,
|
||||
fix: auth.status === 404 ? 'the project no longer exists: run `npx scribase init`' : 'wait a minute (the project may be starting) and run doctor again',
|
||||
});
|
||||
}
|
||||
const rest = await probe(io, `${base}/rest/v1/`, anon);
|
||||
if ('error' in rest) {
|
||||
checks.push({ id: 'reach_rest', status: 'problem', detail: `the REST API did not answer: ${rest.error}`, fix: 'try again in a minute; if it persists, open the project in the console' });
|
||||
} else if (rest.status === 401 || rest.status === 403) {
|
||||
checks.push({ id: 'reach_rest', status: 'problem', detail: `the REST API refused ${conventions.anonKeyVar} (HTTP ${rest.status})`, fix: 'the key belongs to another project or was rotated: run `npx scribase init` to rewrite it' });
|
||||
} else if (rest.status >= 500) {
|
||||
checks.push({ id: 'reach_rest', status: 'problem', detail: `the REST API answered HTTP ${rest.status}`, fix: 'wait a minute (the project may be starting) and run doctor again' });
|
||||
} else {
|
||||
checks.push({ id: 'reach_rest', status: 'ok', detail: 'the REST API accepts the key' });
|
||||
}
|
||||
}
|
||||
return done();
|
||||
}
|
||||
|
||||
/** Plain-text report: one line per check, a fix under each problem. */
|
||||
export function formatDoctor(result: DoctorResult): string {
|
||||
const mark: Record<CheckStatus, string> = { ok: 'ok ', problem: 'PROBLEM', warning: 'warning' };
|
||||
const lines = result.checks.flatMap((check) => [
|
||||
` ${mark[check.status]} ${check.detail}`,
|
||||
...(check.fix && check.status !== 'ok' ? [` fix: ${check.fix}`] : []),
|
||||
]);
|
||||
const problems = result.checks.filter((check) => check.status === 'problem').length;
|
||||
return [
|
||||
`scribase doctor (${result.framework}, ${result.env_file})`,
|
||||
...lines,
|
||||
'',
|
||||
problems === 0 ? 'No problems found.' : `${problems} problem${problems === 1 ? '' : 's'} found.`,
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
159
src/cli/envfile.ts
Normal file
159
src/cli/envfile.ts
Normal file
@ -0,0 +1,159 @@
|
||||
/**
|
||||
* Minimal `.env` editing: set keys without disturbing anything else in the
|
||||
* file (comments, order, other variables), and make sure the file is ignored
|
||||
* by git. Pure string functions; the caller does the I/O.
|
||||
*/
|
||||
|
||||
const KEY = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
|
||||
|
||||
function quoteValue(value: string): string {
|
||||
return /^[A-Za-z0-9_./:@+-]*$/.test(value) ? value : JSON.stringify(value);
|
||||
}
|
||||
|
||||
const HEADER = '# Scribase (written by `npx scribase init`)';
|
||||
|
||||
/** The comment a temporary project's note starts with; re-runs replace it. */
|
||||
export const TEMPORARY_NOTE_PREFIX = '# Temporary project, deleted ';
|
||||
|
||||
/**
|
||||
* Returns `existing` with every key in `values` set: replaced in place when
|
||||
* present, appended (under a short header) when not. `notes` are comment
|
||||
* lines kept right under the header (a temporary project's expiry and claim
|
||||
* link); an earlier temporary note is replaced, never duplicated, so a re-run
|
||||
* of `init` leaves exactly one.
|
||||
*/
|
||||
export function mergeEnv(existing: string, values: Record<string, string>, notes: readonly string[] = []): string {
|
||||
const remaining = new Map(Object.entries(values));
|
||||
const lines = existing.length > 0 ? existing.replace(/\r\n/g, '\n').split('\n') : [];
|
||||
const updated = lines
|
||||
.filter((line) => !(notes.length > 0 && line.startsWith(TEMPORARY_NOTE_PREFIX)))
|
||||
.map((line) => {
|
||||
const match = KEY.exec(line);
|
||||
const key = match?.[1];
|
||||
if (key !== undefined && remaining.has(key)) {
|
||||
const value = remaining.get(key) ?? '';
|
||||
remaining.delete(key);
|
||||
return `${key}=${quoteValue(value)}`;
|
||||
}
|
||||
return line;
|
||||
});
|
||||
while (updated.length > 0 && updated[updated.length - 1] === '') {
|
||||
updated.pop();
|
||||
}
|
||||
const comments = notes.map((note) => (note.startsWith('#') ? note : `# ${note}`));
|
||||
const header = updated.indexOf(HEADER);
|
||||
if (remaining.size > 0) {
|
||||
if (header < 0) {
|
||||
if (updated.length > 0) updated.push('');
|
||||
updated.push(HEADER, ...comments);
|
||||
} else {
|
||||
updated.splice(header + 1, 0, ...comments);
|
||||
}
|
||||
for (const [key, value] of remaining) {
|
||||
updated.push(`${key}=${quoteValue(value)}`);
|
||||
}
|
||||
} else if (comments.length > 0) {
|
||||
if (header < 0) {
|
||||
if (updated.length > 0) updated.push('');
|
||||
updated.push(HEADER, ...comments);
|
||||
} else {
|
||||
updated.splice(header + 1, 0, ...comments);
|
||||
}
|
||||
}
|
||||
return `${updated.join('\n')}\n`;
|
||||
}
|
||||
|
||||
/** Reads one key from env file contents. */
|
||||
export function readEnvValue(contents: string, key: string): string | undefined {
|
||||
for (const line of contents.split(/\r?\n/)) {
|
||||
const match = KEY.exec(line);
|
||||
if (match?.[1] === key) {
|
||||
const raw = line.slice(line.indexOf('=') + 1).trim();
|
||||
if (raw.startsWith('"')) {
|
||||
try {
|
||||
return JSON.parse(raw) as string;
|
||||
} catch {
|
||||
return raw.slice(1, -1);
|
||||
}
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** `.gitignore` contents that ignore `envFile`, or null when already ignored. */
|
||||
export function ensureIgnored(gitignore: string, envFile: string): string | null {
|
||||
const patterns = gitignore.split(/\r?\n/).map((line) => line.trim());
|
||||
const covered = patterns.some(
|
||||
(pattern) =>
|
||||
pattern === envFile ||
|
||||
pattern === `/${envFile}` ||
|
||||
pattern === '.env*' ||
|
||||
(envFile.endsWith('.local') && (pattern === '*.local' || pattern === '.env*.local')),
|
||||
);
|
||||
if (covered) return null;
|
||||
const base = gitignore.length === 0 || gitignore.endsWith('\n') ? gitignore : `${gitignore}\n`;
|
||||
return `${base}${envFile}\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* `.gitignore` contents that also ignore the directory `dir` (e.g. `.scribase`,
|
||||
* which holds a temporary project's claim link), or null when already ignored.
|
||||
*/
|
||||
export function ensureDirIgnored(gitignore: string, dir: string): string | null {
|
||||
const name = dir.replace(/^\/+|\/+$/g, '');
|
||||
const covered = gitignore
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.some((pattern) => [name, `${name}/`, `/${name}`, `/${name}/`, `${name}/*`, `/${name}/*`].includes(pattern));
|
||||
if (covered) return null;
|
||||
const base = gitignore.length === 0 || gitignore.endsWith('\n') ? gitignore : `${gitignore}\n`;
|
||||
return `${base}${name}/\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Value shapes that are secrets whatever the variable is called: service-role
|
||||
* and secret keys, agent and access tokens, private keys, and URLs with a
|
||||
* password. `scribase add` never writes one of these (SP-D1).
|
||||
*/
|
||||
const SECRET_VALUE = [
|
||||
/^sb_secret_/,
|
||||
/^scb_(agt|pat|mt)_/,
|
||||
/-----BEGIN [A-Z ]*PRIVATE KEY-----/,
|
||||
/^[a-z][a-z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@/i,
|
||||
];
|
||||
/** Variable names that hold secrets. Public keys (anon, publishable) are allowed. */
|
||||
const SECRET_NAME = /(SECRET|PASSWORD|PASSWD|PRIVATE|SERVICE_ROLE|ACCESS_TOKEN|_PASS$|SMTP_PASS)/;
|
||||
|
||||
/** True when `name=value` would put a secret in an env file or terminal. */
|
||||
export function isSecretEnv(name: string, value: string): boolean {
|
||||
if (SECRET_NAME.test(name)) return true;
|
||||
if (SECRET_VALUE.some((pattern) => pattern.test(value))) return true;
|
||||
// A JWT whose payload says service_role.
|
||||
const parts = value.split('.');
|
||||
if (parts.length === 3 && /^eyJ/.test(value)) {
|
||||
try {
|
||||
const payload = JSON.parse(Buffer.from(parts[1] ?? '', 'base64url').toString('utf8')) as { role?: unknown };
|
||||
if (payload.role === 'service_role') return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The entries of `values` that are safe to write, and the names refused as
|
||||
* secrets. The caller writes only `safe`; refused names are reported by name,
|
||||
* never by value.
|
||||
*/
|
||||
export function publicEnvOnly(values: Record<string, string>): { safe: Record<string, string>; refused: string[] } {
|
||||
const safe: Record<string, string> = {};
|
||||
const refused: string[] = [];
|
||||
for (const [name, value] of Object.entries(values)) {
|
||||
if (isSecretEnv(name, value)) refused.push(name);
|
||||
else safe[name] = value;
|
||||
}
|
||||
return { safe, refused };
|
||||
}
|
||||
253
src/cli/framework.ts
Normal file
253
src/cli/framework.ts
Normal file
@ -0,0 +1,253 @@
|
||||
/**
|
||||
* Framework detection and the per-framework conventions `scribase init`
|
||||
* follows: which env file to write, which variable names the framework exposes
|
||||
* to client code, and where the client module goes. Pure: callers pass the
|
||||
* facts about the directory in.
|
||||
*/
|
||||
|
||||
export type Framework = 'next' | 'expo' | 'vite' | 'sveltekit' | 'node';
|
||||
|
||||
export interface ProjectFacts {
|
||||
/** Parsed package.json, or null when there is none. */
|
||||
packageJson: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> } | null;
|
||||
/** Whether a path relative to the project root exists. */
|
||||
exists: (relativePath: string) => boolean;
|
||||
}
|
||||
|
||||
export interface FrameworkConventions {
|
||||
framework: Framework;
|
||||
/** The env file the framework loads in development. */
|
||||
envFile: string;
|
||||
/** Variable holding the project URL. */
|
||||
urlVar: string;
|
||||
/** Variable holding the public (anon) key. */
|
||||
anonKeyVar: string;
|
||||
/**
|
||||
* Variable for the service-role key, or null where any env value can end up
|
||||
* in a client bundle by mistake (Expo, Vite) — those projects never get it.
|
||||
*/
|
||||
serviceRoleVar: string | null;
|
||||
/** Where the client module is written, relative to the root. */
|
||||
clientFile: string;
|
||||
/** How client code reads a variable (`process.env.X` or `import.meta.env.X`). */
|
||||
readEnv: (name: string) => string;
|
||||
}
|
||||
|
||||
function hasDependency(facts: ProjectFacts, name: string): boolean {
|
||||
const pkg = facts.packageJson;
|
||||
return Boolean(pkg?.dependencies?.[name] ?? pkg?.devDependencies?.[name]);
|
||||
}
|
||||
|
||||
/** Detects the framework from package.json dependencies and config files. */
|
||||
export function detectFramework(facts: ProjectFacts): Framework {
|
||||
if (
|
||||
hasDependency(facts, 'next') ||
|
||||
['next.config.js', 'next.config.mjs', 'next.config.ts'].some((file) => facts.exists(file))
|
||||
) {
|
||||
return 'next';
|
||||
}
|
||||
if (hasDependency(facts, 'expo') || facts.exists('app.json') && hasDependency(facts, 'react-native')) {
|
||||
return 'expo';
|
||||
}
|
||||
// SvelteKit is itself a Vite project (it ships vite.config.ts and depends
|
||||
// on vite), so this check must come before the plain-Vite one below, or a
|
||||
// SvelteKit app would get Vite's conventions (VITE_ vars read via
|
||||
// `import.meta.env`, no server-side client) instead of its own ($env
|
||||
// modules, and a real service-role key since SvelteKit has a server).
|
||||
if (
|
||||
hasDependency(facts, '@sveltejs/kit') ||
|
||||
['svelte.config.js', 'svelte.config.ts', 'svelte.config.mjs'].some((file) => facts.exists(file))
|
||||
) {
|
||||
return 'sveltekit';
|
||||
}
|
||||
if (
|
||||
hasDependency(facts, 'vite') ||
|
||||
['vite.config.ts', 'vite.config.js', 'vite.config.mjs'].some((file) => facts.exists(file))
|
||||
) {
|
||||
return 'vite';
|
||||
}
|
||||
return 'node';
|
||||
}
|
||||
|
||||
/** The conventions for a framework in a given directory layout. */
|
||||
export function conventionsFor(framework: Framework, facts: ProjectFacts): FrameworkConventions {
|
||||
const typescript = facts.exists('tsconfig.json');
|
||||
const extension = typescript ? 'ts' : 'js';
|
||||
const processEnv = (name: string) => `process.env.${name}`;
|
||||
switch (framework) {
|
||||
case 'next':
|
||||
return {
|
||||
framework,
|
||||
envFile: '.env.local',
|
||||
urlVar: 'NEXT_PUBLIC_SUPABASE_URL',
|
||||
anonKeyVar: 'NEXT_PUBLIC_SUPABASE_ANON_KEY',
|
||||
serviceRoleVar: 'SUPABASE_SERVICE_ROLE_KEY',
|
||||
clientFile: `${facts.exists('src') ? 'src/' : ''}lib/supabase.${extension}`,
|
||||
readEnv: processEnv,
|
||||
};
|
||||
case 'expo':
|
||||
return {
|
||||
framework,
|
||||
envFile: '.env',
|
||||
urlVar: 'EXPO_PUBLIC_SUPABASE_URL',
|
||||
anonKeyVar: 'EXPO_PUBLIC_SUPABASE_ANON_KEY',
|
||||
serviceRoleVar: null,
|
||||
clientFile: `${facts.exists('src') ? 'src/' : ''}lib/supabase.${extension}`,
|
||||
readEnv: processEnv,
|
||||
};
|
||||
case 'vite':
|
||||
return {
|
||||
framework,
|
||||
envFile: '.env.local',
|
||||
urlVar: 'VITE_SUPABASE_URL',
|
||||
anonKeyVar: 'VITE_SUPABASE_ANON_KEY',
|
||||
serviceRoleVar: null,
|
||||
clientFile: `src/lib/supabase.${extension}`,
|
||||
readEnv: (name) => `import.meta.env.${name}`,
|
||||
};
|
||||
case 'sveltekit':
|
||||
return {
|
||||
framework,
|
||||
// SvelteKit (via Vite) loads .env itself; unlike plain Vite, its own
|
||||
// $env/static/public convention (not VITE_-prefixed import.meta.env)
|
||||
// is what every SvelteKit + Supabase guide uses, so follow it exactly.
|
||||
envFile: '.env',
|
||||
urlVar: 'PUBLIC_SUPABASE_URL',
|
||||
anonKeyVar: 'PUBLIC_SUPABASE_ANON_KEY',
|
||||
// Unlike Vite/Expo (pure client bundles), SvelteKit has a real server
|
||||
// (hooks.server.ts, +page.server.ts) that can hold the secret key
|
||||
// behind $env/static/private, never shipped to the browser.
|
||||
serviceRoleVar: 'SUPABASE_SERVICE_ROLE_KEY',
|
||||
clientFile: `src/lib/supabase.${extension}`,
|
||||
// Unused for sveltekit: clientSource imports the $env/static/public
|
||||
// bindings by name instead of inlining a `readEnv` expression.
|
||||
readEnv: (name) => name,
|
||||
};
|
||||
case 'node':
|
||||
return {
|
||||
framework,
|
||||
envFile: '.env',
|
||||
urlVar: 'SUPABASE_URL',
|
||||
anonKeyVar: 'SUPABASE_ANON_KEY',
|
||||
serviceRoleVar: 'SUPABASE_SERVICE_ROLE_KEY',
|
||||
clientFile: `${facts.exists('src') ? 'src/' : ''}supabase.${typescript ? 'ts' : 'mjs'}`,
|
||||
readEnv: processEnv,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** The client module `scribase init` writes (Scribase speaks the supabase-js API). */
|
||||
export function clientSource(conventions: FrameworkConventions): string {
|
||||
const url = conventions.readEnv(conventions.urlVar);
|
||||
const key = conventions.readEnv(conventions.anonKeyVar);
|
||||
const typescript = conventions.clientFile.endsWith('.ts');
|
||||
// $env/static/public's exports are already typed `string` (SvelteKit fails
|
||||
// the build itself if one is missing), so a non-null assertion would just
|
||||
// be noise; every other framework's env read is typed as possibly
|
||||
// undefined, where the assertion earns its place.
|
||||
const bang = typescript && conventions.framework !== 'sveltekit' ? '!' : '';
|
||||
const lines = [
|
||||
"import { createClient } from '@supabase/supabase-js';",
|
||||
...(conventions.framework === 'sveltekit' ? [`import { ${conventions.urlVar}, ${conventions.anonKeyVar} } from '$env/static/public';`] : []),
|
||||
'',
|
||||
`// Written by \`npx scribase init\`. The values come from ${conventions.envFile}.`,
|
||||
`export const supabase = createClient(${url}${bang}, ${key}${bang});`,
|
||||
'',
|
||||
];
|
||||
if (conventions.framework === 'expo') {
|
||||
lines.splice(
|
||||
2,
|
||||
0,
|
||||
'// For sessions that survive app restarts, pass `auth: { storage: AsyncStorage }`',
|
||||
'// from @react-native-async-storage/async-storage as the third argument.',
|
||||
);
|
||||
}
|
||||
if (conventions.framework === 'node') {
|
||||
// Next.js/Vite/Expo each load their own env file before user code runs;
|
||||
// plain Node does not. Without this, `process.env.SUPABASE_URL` is
|
||||
// undefined the moment this file is imported and createClient throws
|
||||
// "supabaseUrl is required." — the exact next step `scribase init`
|
||||
// itself prints. `process.loadEnvFile` is a zero-dependency Node builtin
|
||||
// (stable since Node 20.12; this package already requires >=22.13).
|
||||
lines.splice(
|
||||
2,
|
||||
0,
|
||||
"// Plain Node has no built-in env-file loading (unlike Next.js/Vite/Expo), so load it here.",
|
||||
`try { process.loadEnvFile(); } catch { /* ${JSON.stringify(conventions.envFile)} is optional if the shell already sets these */ }`,
|
||||
);
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/** The package manager a project uses, from its lockfile. */
|
||||
export function packageManager(exists: (relativePath: string) => boolean): 'pnpm' | 'yarn' | 'bun' | 'npm' {
|
||||
if (exists('pnpm-lock.yaml')) return 'pnpm';
|
||||
if (exists('yarn.lock')) return 'yarn';
|
||||
if (exists('bun.lockb') || exists('bun.lock')) return 'bun';
|
||||
return 'npm';
|
||||
}
|
||||
|
||||
/** The install command for supabase-js with a package manager. */
|
||||
export function installCommand(manager: 'pnpm' | 'yarn' | 'bun' | 'npm'): [string, string[]] {
|
||||
const pkg = '@supabase/supabase-js';
|
||||
// npm's audit and funding lookups are extra registry round trips that add
|
||||
// seconds to init and change nothing about the install.
|
||||
return manager === 'npm' ? ['npm', ['install', pkg, '--no-audit', '--no-fund']] : [manager, ['add', pkg]];
|
||||
}
|
||||
|
||||
/* ------------------------- native projects (PS2.4) ------------------------- */
|
||||
|
||||
/** A native app platform `scribase init` recognises without a package.json. */
|
||||
export type NativePlatform = 'flutter' | 'swift' | 'android' | 'python';
|
||||
|
||||
/**
|
||||
* The native platform of a folder with no package.json: Flutter
|
||||
* (pubspec.yaml), Swift (Package.swift), Android or Kotlin (Gradle settings or
|
||||
* build files), Python (pyproject.toml or requirements.txt). A JavaScript
|
||||
* project is never native.
|
||||
*/
|
||||
export function detectNative(facts: ProjectFacts): NativePlatform | null {
|
||||
if (facts.packageJson) return null;
|
||||
if (facts.exists('pubspec.yaml')) return 'flutter';
|
||||
if (facts.exists('Package.swift')) return 'swift';
|
||||
if (['settings.gradle.kts', 'settings.gradle', 'build.gradle.kts', 'build.gradle'].some((file) => facts.exists(file))) {
|
||||
return 'android';
|
||||
}
|
||||
if (['pyproject.toml', 'requirements.txt', 'setup.py'].some((file) => facts.exists(file))) return 'python';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** What to do next in a native project: add the client library and type the tables. */
|
||||
export function nativeNextSteps(
|
||||
platform: NativePlatform,
|
||||
ref: { organization_id: string; project_id: string; environment_id: string },
|
||||
): string[] {
|
||||
const types = (lang: string, out: string) =>
|
||||
`type your tables: scribase gen types ${ref.organization_id} ${ref.project_id} ${ref.environment_id} --lang ${lang} --out ${out} (full CLI)`;
|
||||
switch (platform) {
|
||||
case 'flutter':
|
||||
return [
|
||||
'add the client: flutter pub add supabase_flutter',
|
||||
'pass SUPABASE_URL and SUPABASE_ANON_KEY from .env with --dart-define-from-file (never the service role key)',
|
||||
types('dart', 'lib/database_types.dart'),
|
||||
];
|
||||
case 'swift':
|
||||
return [
|
||||
'add the client: .package(url: "https://github.com/supabase/supabase-swift.git", from: "2.55.0")',
|
||||
'create SupabaseClient(supabaseURL:supabaseKey:) with SUPABASE_URL and SUPABASE_ANON_KEY from .env',
|
||||
types('swift', 'Sources/DatabaseTypes.swift'),
|
||||
];
|
||||
case 'android':
|
||||
return [
|
||||
'add the client: implementation(platform("io.github.jan-tennert.supabase:bom:3.8.0")) with postgrest-kt and auth-kt',
|
||||
'put SUPABASE_URL and SUPABASE_ANON_KEY from .env into BuildConfig fields (never the service role key)',
|
||||
types('kotlin', 'app/src/main/java/DatabaseTypes.kt'),
|
||||
];
|
||||
case 'python':
|
||||
return [
|
||||
'add the client: pip install supabase',
|
||||
'create_client(os.environ["SUPABASE_URL"], os.environ["SUPABASE_ANON_KEY"]) (the values are in .env)',
|
||||
types('python', 'database_types.py'),
|
||||
];
|
||||
}
|
||||
}
|
||||
411
src/cli/index.ts
Normal file
411
src/cli/index.ts
Normal file
@ -0,0 +1,411 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* The `scribase` npm binary: `init`, `add`, `sql`, `migrate`, `login` and
|
||||
* `doctor`. Everything else lives in the full Rust CLI (`scribase` from the
|
||||
* releases page), which this binary points to. Both share the stored
|
||||
* credentials (keychain or 0600 file).
|
||||
*/
|
||||
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
import { addMain, nodeAddIo } from './add.js';
|
||||
import { nodeOtaIo, otaMain } from './capabilities/ota.js';
|
||||
import { connectMain, nodeConnectIo } from './connect.js';
|
||||
import { expandAlias } from './aliases.js';
|
||||
import { installId, pendingStore, readCredentials, storeCredentials } from './credentials.js';
|
||||
import { formatDoctor, runDoctor } from './doctor.js';
|
||||
import { InitError, parseInitArgs, runInit } from './init.js';
|
||||
import { formatMigrate, MIGRATIONS_DIR, parseMigrateArgs, runMigrate } from './migrate.js';
|
||||
import { formatSql, parseSqlArgs, runSql } from './sql.js';
|
||||
import type { InitIo } from './init.js';
|
||||
import type { SpawnOutcome } from './vercel.js';
|
||||
import { vercelLine } from './vercel.js';
|
||||
import { DEFAULT_SCOPE, LoginError, parseLoginArgs, publicResult, runLogin } from './login.js';
|
||||
import type { LoginIo, LoginOptions } from './login.js';
|
||||
|
||||
const HELP = `Usage: npx scribase init [options]
|
||||
npx scribase add <capability> [--own] [--json] (see npx scribase add --help)
|
||||
npx scribase deploy [--json] (the same as npx scribase add deploy)
|
||||
npx scribase sql "<SQL>" [--file <path>] [--confirm] [--json]
|
||||
npx scribase migrate new <name> (scaffold a migration file)
|
||||
npx scribase migrate [--dry-run] [--json] (plan, lint and apply pending ones)
|
||||
npx scribase ota <deploy|rollback|status> [-p ios|android] (see npx scribase ota --help)
|
||||
npx scribase connect [tool...] [--dry-run] [--json] (see npx scribase connect --help)
|
||||
npx scribase doctor [--json]
|
||||
npx scribase login [--json] [--no-wait] [--scope <s>]... [--name <client>] [--api-url <url>] [--no-browser]
|
||||
|
||||
sql: runs SQL on the project this folder is connected to (after init), in one
|
||||
transaction; new tables are visible to the REST API at once. Statements that
|
||||
remove data (DROP, TRUNCATE, DELETE without WHERE) only run with --confirm.
|
||||
Uses SCRIBASE_ACCESS_TOKEN, the env file init wrote, or \`scribase login\`.
|
||||
|
||||
migrate: tracked, repeatable SQL migrations in ${MIGRATIONS_DIR}/*.sql.
|
||||
\`migrate new <name>\` scaffolds a timestamped file; \`migrate\` sends every
|
||||
local file, oldest first, to this folder's project, which plans, lints (a
|
||||
public table with no RLS policy blocks the whole run) and applies whatever
|
||||
is not already in that environment's migration ledger. Re-running is always
|
||||
safe: already-applied files are skipped. \`--dry-run\` plans and lints only.
|
||||
|
||||
connect: writes the Scribase MCP server into every AI coding tool this
|
||||
machine has (Claude Code, Cursor, VS Code, Codex, Windsurf, Zed) — one
|
||||
command, idempotent, no token ever written (OAuth runs in the client).
|
||||
Name one or more tools to configure exactly those; otherwise only tools
|
||||
actually detected on this machine are touched. See \`npx scribase connect --help\`.
|
||||
|
||||
doctor: checks this folder's env file, keys and the connection to the backend,
|
||||
and prints one fix per problem. Never prints key values. Exits 1 on a problem.
|
||||
|
||||
login: sign in without pasting a key. Prints a link and a code (and opens the
|
||||
browser); a person approves in the console; a scoped, expiring agent token is
|
||||
stored in the OS keychain (else ~/.config/scribase/credentials, mode 0600) and
|
||||
never printed. --json prints {"event":"device_authorization",...} at once and
|
||||
a final JSON line; --no-wait prints the link and exits (run again to finish).
|
||||
|
||||
init:
|
||||
|
||||
Connect this app to a Scribase backend in one step: detects Next.js, Expo,
|
||||
SvelteKit, Vite or Node, creates (or reuses) a project, writes the env file, installs
|
||||
@supabase/supabase-js and writes a client module. Not signed in? You get a
|
||||
temporary project for 72 hours, no account needed, and a claim link to keep it
|
||||
(sign up, free for 14 days, no card; the URL and keys stay the same).
|
||||
|
||||
Options:
|
||||
--temp always a temporary project, even when signed in
|
||||
--account not signed in: approve this app in the browser and use your
|
||||
account instead of a temporary project
|
||||
--watch after init, wait for your app's first request and say when
|
||||
it arrives (up to 10 minutes; --watch-seconds <n> to change)
|
||||
--yes, -y never prompt; use defaults
|
||||
--json print one JSON object (for coding agents and scripts)
|
||||
--name <name> project name (default: this directory's name)
|
||||
--org <org> organization (default: your first one)
|
||||
--region <id> region (default: eu-frankfurt)
|
||||
--api-url <url> control plane (default: SCRIBASE_API_URL or https://api.scribase.com)
|
||||
--token <token> access token (default: SCRIBASE_ACCESS_TOKEN or \`scribase login\`)
|
||||
--no-wait with --account: print the approval link and exit; run again after
|
||||
--no-install do not install @supabase/supabase-js
|
||||
--no-vercel do not touch the linked Vercel project (by default, when this
|
||||
folder is linked with \`vercel link\`, the URL and keys are set for
|
||||
development, preview and production with VERCEL_TOKEN or the
|
||||
signed-in vercel CLI)
|
||||
--wait <seconds> how long to wait for the database (default: 300)
|
||||
`;
|
||||
|
||||
function openBrowser(url: string): void {
|
||||
const [command, args] =
|
||||
process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
|
||||
try {
|
||||
spawn(command as string, args as string[], { stdio: 'ignore', detached: true }).unref();
|
||||
} catch {
|
||||
// The link is printed anyway.
|
||||
}
|
||||
}
|
||||
|
||||
function loginIo(json: boolean): LoginIo {
|
||||
return {
|
||||
env: process.env,
|
||||
fetch: globalThis.fetch.bind(globalThis),
|
||||
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
||||
now: () => Date.now(),
|
||||
log: (line) => (json ? process.stderr.write(`${line}\n`) : process.stdout.write(`${line}\n`)),
|
||||
emit: (value) => process.stdout.write(`${JSON.stringify(value)}\n`),
|
||||
openBrowser,
|
||||
interactive: Boolean(process.stdout.isTTY) && !json,
|
||||
store: (apiUrl, token) => storeCredentials(process.env, apiUrl, token),
|
||||
pending: pendingStore(process.env),
|
||||
storedApiUrl: () => readCredentials(process.env).apiUrl,
|
||||
};
|
||||
}
|
||||
|
||||
const SPAWN_TIMEOUT_MS = 60_000;
|
||||
const SPAWN_OUTPUT_LIMIT = 1024 * 1024;
|
||||
|
||||
/** Runs a program without a shell; `input` goes to stdin, never argv. */
|
||||
function spawnWithInput(command: string, args: string[], options: { cwd: string; input?: string }): Promise<SpawnOutcome> {
|
||||
return new Promise((resolve) => {
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
let child: ReturnType<typeof spawn>;
|
||||
try {
|
||||
child = spawn(command, args, { cwd: options.cwd, shell: false, stdio: ['pipe', 'pipe', 'pipe'], timeout: SPAWN_TIMEOUT_MS });
|
||||
} catch (error) {
|
||||
resolve({ code: null, stdout: '', stderr: (error as Error).message });
|
||||
return;
|
||||
}
|
||||
child.stdout?.on('data', (chunk: Buffer) => {
|
||||
if (stdout.length < SPAWN_OUTPUT_LIMIT) stdout += chunk.toString('utf8');
|
||||
});
|
||||
child.stderr?.on('data', (chunk: Buffer) => {
|
||||
if (stderr.length < SPAWN_OUTPUT_LIMIT) stderr += chunk.toString('utf8');
|
||||
});
|
||||
child.on('error', (error) => resolve({ code: null, stdout, stderr: error.message }));
|
||||
child.on('close', (code) => resolve({ code, stdout, stderr }));
|
||||
child.stdin?.on('error', () => {});
|
||||
child.stdin?.end(options.input ?? '');
|
||||
});
|
||||
}
|
||||
|
||||
function nodeIo(json: boolean): InitIo {
|
||||
return {
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
fetch: globalThis.fetch.bind(globalThis),
|
||||
readFile: (path) => (existsSync(path) ? readFileSync(path, 'utf8') : null),
|
||||
writeFile: (path, contents) => {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
// Env files hold keys: owner-only. Source files keep the default mode.
|
||||
writeFileSync(path, contents, /\.env(\.local)?$/.test(path) ? { mode: 0o600 } : {});
|
||||
},
|
||||
exists: (path) => existsSync(path),
|
||||
run: (command, args, cwd) => {
|
||||
const result = spawnSync(command, args, { cwd, encoding: 'utf8', shell: process.platform === 'win32' });
|
||||
return { ok: result.status === 0, output: `${result.stdout ?? ''}${result.stderr ?? ''}` };
|
||||
},
|
||||
spawn: spawnWithInput,
|
||||
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
||||
// In --json mode stdout carries exactly one JSON document; notes go to stderr.
|
||||
log: (line) => (json ? process.stderr.write(`${line}\n`) : process.stdout.write(`${line}\n`)),
|
||||
credentials: () => readCredentials(process.env),
|
||||
now: () => Date.now(),
|
||||
installId: () => installId(process.env),
|
||||
login: async (apiUrl, request) => {
|
||||
// Inside init, --json keeps stdout for init's own result: the approval
|
||||
// prompt goes to stderr as a JSON line.
|
||||
const io = loginIo(request.json);
|
||||
const options: LoginOptions = {
|
||||
apiUrl,
|
||||
json: request.json,
|
||||
noWait: request.noWait,
|
||||
browser: true,
|
||||
scopes: [`project:${request.project}:write`, ...DEFAULT_SCOPE.split(' ').filter((scope) => !scope.startsWith('project:'))],
|
||||
};
|
||||
const result = await runLogin(options, {
|
||||
...io,
|
||||
emit: (value) => process.stderr.write(`${JSON.stringify(value)}\n`),
|
||||
});
|
||||
return {
|
||||
status: result.status,
|
||||
...(result.token ? { token: result.token } : {}),
|
||||
...(result.organization_id ? { organizationId: result.organization_id } : {}),
|
||||
...(result.user_code ? { userCode: result.user_code } : {}),
|
||||
...(result.verification_uri_complete ? { verificationUriComplete: result.verification_uri_complete } : {}),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function login(argv: string[]): Promise<number> {
|
||||
const json = argv.includes('--json');
|
||||
try {
|
||||
const result = await runLogin(parseLoginArgs(argv), loginIo(json));
|
||||
if (json) {
|
||||
process.stdout.write(`${JSON.stringify(publicResult(result))}\n`);
|
||||
} else if (result.status === 'approved') {
|
||||
const project = result.project_id === '*' ? 'every project' : `project ${result.project_id}`;
|
||||
process.stdout.write(
|
||||
[
|
||||
`Logged in to ${result.organization_id} (${project}) with scopes: ${(result.scopes ?? []).join(', ')}.`,
|
||||
`Token stored in ${result.stored_in} (never printed).`,
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
} else {
|
||||
process.stdout.write(`Not waiting (--no-wait): ${result.next}.\n`);
|
||||
}
|
||||
return 0;
|
||||
} catch (error) {
|
||||
const failure =
|
||||
error instanceof LoginError
|
||||
? { code: error.code, message: error.message, ...error.details }
|
||||
: { code: 'unexpected_error', message: (error as Error).message };
|
||||
if (json) process.stdout.write(`${JSON.stringify({ ok: false, error: failure })}\n`);
|
||||
else process.stderr.write(`scribase login: ${failure.message}\n`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
async function doctor(argv: string[]): Promise<number> {
|
||||
const json = argv.includes('--json');
|
||||
const unknown = argv.filter((arg) => arg !== '--json');
|
||||
if (unknown.length > 0) {
|
||||
process.stderr.write(`scribase doctor: unknown option ${unknown[0]}\n`);
|
||||
return 2;
|
||||
}
|
||||
const result = await runDoctor({
|
||||
cwd: process.cwd(),
|
||||
fetch: globalThis.fetch.bind(globalThis),
|
||||
readFile: (path) => (existsSync(path) ? readFileSync(path, 'utf8') : null),
|
||||
exists: (path) => existsSync(path),
|
||||
now: () => Date.now(),
|
||||
});
|
||||
process.stdout.write(json ? `${JSON.stringify(result)}\n` : formatDoctor(result));
|
||||
return result.ok ? 0 : 1;
|
||||
}
|
||||
|
||||
async function sql(argv: string[]): Promise<number> {
|
||||
const json = argv.includes('--json');
|
||||
const readFile = (path: string) => (existsSync(path) ? readFileSync(path, 'utf8') : null);
|
||||
try {
|
||||
const result = await runSql(parseSqlArgs(argv, readFile), {
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
fetch: globalThis.fetch.bind(globalThis),
|
||||
readFile,
|
||||
credentials: () => readCredentials(process.env),
|
||||
});
|
||||
process.stdout.write(json ? `${JSON.stringify(result)}\n` : formatSql(result));
|
||||
return result.status === 'committed' ? 0 : 3;
|
||||
} catch (error) {
|
||||
const failure =
|
||||
error instanceof InitError
|
||||
? { code: error.code, message: error.message, next: error.next ?? null }
|
||||
: { code: 'unexpected_error', message: (error as Error).message, next: null };
|
||||
if (json) process.stdout.write(`${JSON.stringify({ ok: false, error: failure })}\n`);
|
||||
else process.stderr.write(`scribase sql: ${failure.message}\n${failure.next ? ` next: ${failure.next}\n` : ''}`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
async function migrate(argv: string[]): Promise<number> {
|
||||
const json = argv.includes('--json');
|
||||
const readFile = (path: string) => (existsSync(path) ? readFileSync(path, 'utf8') : null);
|
||||
try {
|
||||
const result = await runMigrate(parseMigrateArgs(argv), {
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
fetch: globalThis.fetch.bind(globalThis),
|
||||
readFile,
|
||||
writeFile: (path, contents) => {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, contents);
|
||||
},
|
||||
listMigrationFiles: () => {
|
||||
const dir = `${process.cwd()}/${MIGRATIONS_DIR}`;
|
||||
if (!existsSync(dir)) return [];
|
||||
return readdirSync(dir, { withFileTypes: true })
|
||||
.filter((entry) => entry.isFile())
|
||||
.map((entry) => entry.name);
|
||||
},
|
||||
credentials: () => readCredentials(process.env),
|
||||
now: () => new Date(),
|
||||
});
|
||||
process.stdout.write(json ? `${JSON.stringify(result)}\n` : formatMigrate(result));
|
||||
return result.action === 'run' && result.blocked ? 3 : 0;
|
||||
} catch (error) {
|
||||
const failure =
|
||||
error instanceof InitError
|
||||
? { code: error.code, message: error.message, next: error.next ?? null }
|
||||
: { code: 'unexpected_error', message: (error as Error).message, next: null };
|
||||
if (json) process.stdout.write(`${JSON.stringify({ ok: false, error: failure })}\n`);
|
||||
else process.stderr.write(`scribase migrate: ${failure.message}\n${failure.next ? ` next: ${failure.next}\n` : ''}`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
async function main(argv: string[]): Promise<number> {
|
||||
const [command, ...rest] = expandAlias(argv);
|
||||
if (!command || command === 'help' || command === '--help' || command === '-h') {
|
||||
process.stdout.write(HELP);
|
||||
return 0;
|
||||
}
|
||||
if (command === 'login') {
|
||||
if (rest.includes('--help') || rest.includes('-h')) {
|
||||
process.stdout.write(HELP);
|
||||
return 0;
|
||||
}
|
||||
return login(rest);
|
||||
}
|
||||
if (command === 'doctor') {
|
||||
if (rest.includes('--help') || rest.includes('-h')) {
|
||||
process.stdout.write(HELP);
|
||||
return 0;
|
||||
}
|
||||
return doctor(rest);
|
||||
}
|
||||
if (command === 'add') {
|
||||
return addMain(rest, nodeAddIo(rest.includes('--json')), (text) => process.stdout.write(text));
|
||||
}
|
||||
if (command === 'ota') {
|
||||
return otaMain(rest, nodeOtaIo(rest.includes('--json')), (text) => process.stdout.write(text));
|
||||
}
|
||||
if (command === 'connect') {
|
||||
const json = rest.includes('--json');
|
||||
return connectMain(rest, nodeConnectIo(json), (text) => process.stdout.write(text));
|
||||
}
|
||||
if (command === 'sql') {
|
||||
if (rest.includes('--help') || rest.includes('-h')) {
|
||||
process.stdout.write(HELP);
|
||||
return 0;
|
||||
}
|
||||
return sql(rest);
|
||||
}
|
||||
if (command === 'migrate') {
|
||||
if (rest.includes('--help') || rest.includes('-h')) {
|
||||
process.stdout.write(HELP);
|
||||
return 0;
|
||||
}
|
||||
return migrate(rest);
|
||||
}
|
||||
if (command !== 'init') {
|
||||
process.stderr.write(
|
||||
`scribase: the npm package has \`init\`, \`add\`, \`deploy\`, \`ota\`, \`connect\`, \`sql\`, \`migrate\`, \`doctor\` and \`login\`. For \`${command}\`, install the full CLI: https://scribase.com/docs/cli\n`,
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
if (rest.includes('--help') || rest.includes('-h')) {
|
||||
process.stdout.write(HELP);
|
||||
return 0;
|
||||
}
|
||||
const json = rest.includes('--json');
|
||||
try {
|
||||
const options = parseInitArgs(rest);
|
||||
const result = await runInit(options, nodeIo(json));
|
||||
if (json) {
|
||||
process.stdout.write(`${JSON.stringify(result)}\n`);
|
||||
} else {
|
||||
process.stdout.write(
|
||||
[
|
||||
`Live in ${result.live_in_seconds} s: ${result.api_url}`,
|
||||
` framework ${result.framework}`,
|
||||
` project ${result.organization_id}/${result.project_id} (${result.environment_id})${result.reused ? ', reused' : ''}`,
|
||||
` env file ${result.env_file} (${result.env_vars.join(', ')})`,
|
||||
result.client_file ? ` client ${result.client_file}` : ' client (kept your existing file)',
|
||||
...(result.vercel.status === 'disabled' ? [] : [` vercel ${vercelLine(result.vercel)}`]),
|
||||
...(result.claim_url
|
||||
? [
|
||||
` temporary deleted ${result.deleted_at_utc ?? new Date((result.expires_at ?? 0) * 1000).toISOString()} unless you keep it`,
|
||||
` keep it ${result.claim_url} (sign up + card, same URL and keys)`,
|
||||
]
|
||||
: []),
|
||||
...(result.first_request_at === undefined
|
||||
? []
|
||||
: result.first_request_at === null
|
||||
? [' watch no request arrived yet']
|
||||
: [` watch your app just talked to your backend (${new Date(result.first_request_at * 1000).toISOString()})`]),
|
||||
'',
|
||||
'Next:',
|
||||
...result.next_steps.map((step) => ` - ${step}`),
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
}
|
||||
return 0;
|
||||
} catch (error) {
|
||||
const failure =
|
||||
error instanceof InitError
|
||||
? { code: error.code, message: error.message, next: error.next ?? null, ...(error.details ?? {}) }
|
||||
: { code: 'unexpected_error', message: (error as Error).message, next: null };
|
||||
if (json) {
|
||||
process.stdout.write(`${JSON.stringify({ ok: false, error: failure })}\n`);
|
||||
} else {
|
||||
process.stderr.write(`scribase init: ${failure.message}\n${failure.next ? ` next: ${failure.next}\n` : ''}`);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
main(process.argv.slice(2)).then((code) => {
|
||||
process.exitCode = code;
|
||||
});
|
||||
816
src/cli/init.ts
Normal file
816
src/cli/init.ts
Normal file
@ -0,0 +1,816 @@
|
||||
/**
|
||||
* `npx scribase init` — one command from an empty app to a live backend,
|
||||
* built for coding agents (Claude Code, Codex, Cursor, Windsurf) as much as
|
||||
* for people:
|
||||
*
|
||||
* npx scribase init signed in (SCRIBASE_ACCESS_TOKEN or
|
||||
* `scribase login`): create or reuse a project in
|
||||
* your account. Not signed in: a temporary
|
||||
* project for 72 hours, with a claim link to keep it
|
||||
* npx scribase init --account not signed in, but use an account: approve this
|
||||
* app in the browser (no key is ever pasted)
|
||||
* npx scribase init --watch also wait for the app's first request
|
||||
*
|
||||
* It detects the framework (Next.js, Expo, SvelteKit, Vite, plain Node), provisions or
|
||||
* reuses a project, writes the framework's env file with the right variable
|
||||
* names, installs `@supabase/supabase-js` (Scribase speaks its API), writes a
|
||||
* small client module, and prints what to do next — as JSON with `--json`.
|
||||
*
|
||||
* All I/O goes through {@link InitIo} so the flow is testable offline.
|
||||
*/
|
||||
|
||||
import { clientSource, conventionsFor, detectFramework, detectNative, installCommand, nativeNextSteps, packageManager } from './framework.js';
|
||||
import type { Framework, FrameworkConventions, ProjectFacts } from './framework.js';
|
||||
import { ensureDirIgnored, ensureIgnored, mergeEnv, readEnvValue } from './envfile.js';
|
||||
import { solveChallenge } from './pow.js';
|
||||
import { syncVercel } from './vercel.js';
|
||||
import type { SpawnOutcome, VercelStatus, VercelTarget } from './vercel.js';
|
||||
|
||||
export const DEFAULT_API_URL = 'https://api.scribase.com';
|
||||
const STATE_DIR = '.scribase';
|
||||
export const STATE_FILE = `${STATE_DIR}/project.json`;
|
||||
/** Where hosted Scribase runs (the control plane's temporary-project default too). */
|
||||
export const DEFAULT_REGION = 'eu-frankfurt';
|
||||
const ENVIRONMENT_ID = 'production';
|
||||
/**
|
||||
* The first table the next steps suggest. A new project's database is empty,
|
||||
* so the first query must create something before it can read it back. Row
|
||||
* level security is on with a read-only policy, and the grant is explicit so
|
||||
* the anon key can read it whatever the default privileges are. No `!`, `$`
|
||||
* or backticks: the line is pasted inside double quotes in any shell.
|
||||
*/
|
||||
export const FIRST_TABLE_SQL =
|
||||
"create table notes (id bigint generated always as identity primary key, body text not null); " +
|
||||
"insert into notes (body) values ('hello from scribase'); " +
|
||||
'alter table notes enable row level security; ' +
|
||||
'create policy notes_read on notes for select using (true); ' +
|
||||
'grant select on notes to anon, authenticated';
|
||||
/** How long `--watch` waits for the first request by default (seconds). */
|
||||
const DEFAULT_WATCH_SECONDS = 600;
|
||||
|
||||
export interface InitOptions {
|
||||
yes: boolean;
|
||||
json: boolean;
|
||||
temp: boolean;
|
||||
name?: string;
|
||||
org?: string;
|
||||
region?: string;
|
||||
apiUrl?: string;
|
||||
token?: string;
|
||||
install: boolean;
|
||||
/** Seconds to wait for the database to become ready. */
|
||||
waitSeconds: number;
|
||||
/** With a device login: print the approval link and exit instead of waiting. */
|
||||
noWait: boolean;
|
||||
/** Push the keys into the linked Vercel project (default: on; `--no-vercel`). */
|
||||
vercel: boolean;
|
||||
/** Not signed in: approve an account in the browser instead of a temporary project. */
|
||||
account: boolean;
|
||||
/** Wait for the app's first request after init (`--watch`). */
|
||||
watch: boolean;
|
||||
/** Seconds `--watch` waits. */
|
||||
watchSeconds: number;
|
||||
/**
|
||||
* The monthly amount (cents) the person approved for a project that adds to
|
||||
* the bill (`--confirm-billable`, from a `402 confirm_billable`; SB4).
|
||||
* Never implied by `--yes`.
|
||||
*/
|
||||
confirmBillableCents?: number;
|
||||
}
|
||||
|
||||
/** What {@link InitIo.login} returns: a token approved in the browser. */
|
||||
export interface DeviceLoginOutcome {
|
||||
status: 'approved' | 'pending';
|
||||
token?: string;
|
||||
organizationId?: string;
|
||||
userCode?: string;
|
||||
verificationUriComplete?: string;
|
||||
}
|
||||
|
||||
export interface InitIo {
|
||||
cwd: string;
|
||||
env: Record<string, string | undefined>;
|
||||
fetch: typeof fetch;
|
||||
readFile: (path: string) => string | null;
|
||||
writeFile: (path: string, contents: string) => void;
|
||||
exists: (path: string) => boolean;
|
||||
run: (command: string, args: string[], cwd: string) => { ok: boolean; output: string };
|
||||
/** Runs a program without a shell, `input` on stdin (the signed-in `vercel` CLI). */
|
||||
spawn?: (command: string, args: string[], options: { cwd: string; input?: string }) => Promise<SpawnOutcome>;
|
||||
sleep: (ms: number) => Promise<void>;
|
||||
log: (line: string) => void;
|
||||
/** Stored CLI credentials (`scribase login`), if any. */
|
||||
credentials: () => { apiUrl?: string; token?: string };
|
||||
/**
|
||||
* Signs in through the browser (RFC 8628 device login) asking for write
|
||||
* access to `project`; absent in environments that cannot (then init asks
|
||||
* for `scribase login` or `--temp`).
|
||||
*/
|
||||
login?: (apiUrl: string, request: { project: string; json: boolean; noWait: boolean }) => Promise<DeviceLoginOutcome>;
|
||||
/** Wall clock in milliseconds (for "Live in N s"); defaults to `Date.now`. */
|
||||
now?: () => number;
|
||||
/**
|
||||
* This machine's anonymous CLI install id (a random id stored next to the
|
||||
* credentials), sent as `?ref=` on claim links; absent or null to send none.
|
||||
*/
|
||||
installId?: () => string | null;
|
||||
}
|
||||
|
||||
export interface InitResult {
|
||||
ok: true;
|
||||
framework: Framework;
|
||||
temporary: boolean;
|
||||
reused: boolean;
|
||||
organization_id: string;
|
||||
project_id: string;
|
||||
environment_id: string;
|
||||
api_url: string;
|
||||
env_file: string;
|
||||
env_vars: string[];
|
||||
client_file: string | null;
|
||||
installed: boolean;
|
||||
claim_url?: string;
|
||||
expires_at?: number;
|
||||
/** `expires_at` as "2026-11-15 10:00 UTC": when a temporary project is deleted. */
|
||||
deleted_at_utc?: string;
|
||||
/** The one line to show a person: "Temporary project, deleted <date>. Keep it: <claim_url>". */
|
||||
keep?: string;
|
||||
/** Measured seconds from the start of init until the backend answered ready. */
|
||||
live_in_seconds: number;
|
||||
/** With `--watch`: when the app's first request was served (epoch seconds), or null if none came in time. */
|
||||
first_request_at?: number | null;
|
||||
/** What happened with the linked Vercel project (never fails init). */
|
||||
vercel: { status: VercelStatus | 'disabled'; targets: VercelTarget[]; project_id?: string; error?: string };
|
||||
next_steps: string[];
|
||||
}
|
||||
|
||||
export class InitError extends Error {
|
||||
constructor(
|
||||
readonly code: string,
|
||||
message: string,
|
||||
readonly next?: string,
|
||||
readonly details?: Record<string, unknown>,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'InitError';
|
||||
}
|
||||
}
|
||||
|
||||
interface Keys {
|
||||
api_url: string | null;
|
||||
anon_key: string;
|
||||
service_role_key?: string | null;
|
||||
}
|
||||
|
||||
interface Provisioned {
|
||||
organization_id: string;
|
||||
project_id: string;
|
||||
environment_id: string;
|
||||
keys: Keys;
|
||||
reused: boolean;
|
||||
agentToken?: string;
|
||||
claimUrl?: string;
|
||||
expiresAt?: number;
|
||||
temporaryId?: string;
|
||||
}
|
||||
|
||||
/** Parses `init` arguments. Unknown flags are an error, so typos never pass silently. */
|
||||
export function parseInitArgs(argv: string[]): InitOptions {
|
||||
const options: InitOptions = {
|
||||
yes: false,
|
||||
json: false,
|
||||
temp: false,
|
||||
install: true,
|
||||
waitSeconds: 300,
|
||||
noWait: false,
|
||||
vercel: true,
|
||||
account: false,
|
||||
watch: false,
|
||||
watchSeconds: DEFAULT_WATCH_SECONDS,
|
||||
};
|
||||
const valueFlags: Record<string, (value: string) => void> = {
|
||||
'--name': (value) => (options.name = value),
|
||||
'--org': (value) => (options.org = value),
|
||||
'--region': (value) => (options.region = value),
|
||||
'--api-url': (value) => (options.apiUrl = value),
|
||||
'--token': (value) => (options.token = value),
|
||||
'--confirm-billable': (value) => {
|
||||
const cents = Number(value);
|
||||
if (!Number.isInteger(cents) || cents < 0 || cents > 10_000_000) {
|
||||
throw new InitError(
|
||||
'invalid_argument',
|
||||
'--confirm-billable takes the monthly_delta_cents the API named (a whole number of cents)',
|
||||
);
|
||||
}
|
||||
options.confirmBillableCents = cents;
|
||||
},
|
||||
'--wait': (value) => {
|
||||
const seconds = Number(value);
|
||||
if (!Number.isInteger(seconds) || seconds < 0 || seconds > 3600) {
|
||||
throw new InitError('invalid_argument', '--wait takes a number of seconds (0 to 3600)');
|
||||
}
|
||||
options.waitSeconds = seconds;
|
||||
},
|
||||
'--watch-seconds': (value) => {
|
||||
const seconds = Number(value);
|
||||
if (!Number.isInteger(seconds) || seconds < 1 || seconds > 3600) {
|
||||
throw new InitError('invalid_argument', '--watch-seconds takes a number of seconds (1 to 3600)');
|
||||
}
|
||||
options.watch = true;
|
||||
options.watchSeconds = seconds;
|
||||
},
|
||||
};
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index] ?? '';
|
||||
const [flag, inline] = arg.includes('=') ? [arg.slice(0, arg.indexOf('=')), arg.slice(arg.indexOf('=') + 1)] : [arg, undefined];
|
||||
if (flag === '--yes' || flag === '-y') options.yes = true;
|
||||
else if (flag === '--json') options.json = true;
|
||||
else if (flag === '--temp' || flag === '--temporary') options.temp = true;
|
||||
else if (flag === '--no-install') options.install = false;
|
||||
else if (flag === '--no-wait') options.noWait = true;
|
||||
else if (flag === '--no-vercel') options.vercel = false;
|
||||
else if (flag === '--account' || flag === '--login') options.account = true;
|
||||
else if (flag === '--watch') options.watch = true;
|
||||
else if (flag !== undefined && flag in valueFlags) {
|
||||
const value = inline ?? argv[++index];
|
||||
if (value === undefined || value.startsWith('--')) {
|
||||
throw new InitError('invalid_argument', `${flag} needs a value`);
|
||||
}
|
||||
valueFlags[flag]?.(value);
|
||||
} else {
|
||||
throw new InitError('invalid_argument', `unknown option ${arg}`, 'run `npx scribase init --help`');
|
||||
}
|
||||
}
|
||||
if (options.temp && options.account) {
|
||||
throw new InitError('invalid_argument', '--temp and --account exclude each other', 'pick one');
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
/** Lowercase letters, digits and hyphens, 3 to 40 characters, or `my-app`. */
|
||||
export function projectSlug(value: string | undefined): string {
|
||||
const slug = (value ?? '')
|
||||
.normalize('NFKD')
|
||||
.replace(/[̀-ͯ]/g, '')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 40)
|
||||
.replace(/-+$/g, '');
|
||||
return slug.length >= 3 ? slug : 'my-app';
|
||||
}
|
||||
|
||||
function join(root: string, relative: string): string {
|
||||
return `${root.replace(/\/+$/, '')}/${relative}`;
|
||||
}
|
||||
|
||||
class Api {
|
||||
constructor(
|
||||
private readonly io: InitIo,
|
||||
readonly baseUrl: string,
|
||||
private readonly token: string | undefined,
|
||||
) {}
|
||||
|
||||
async call<T>(method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<{ status: number; body: T }> {
|
||||
const init: RequestInit = {
|
||||
method,
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
'user-agent': 'scribase-init',
|
||||
...(body === undefined ? {} : { 'content-type': 'application/json' }),
|
||||
...(this.token ? { authorization: `Bearer ${this.token}` } : {}),
|
||||
...headers,
|
||||
},
|
||||
};
|
||||
if (body !== undefined) init.body = JSON.stringify(body);
|
||||
let response: Response;
|
||||
try {
|
||||
response = await this.io.fetch(`${this.baseUrl}${path}`, init);
|
||||
} catch (error) {
|
||||
throw new InitError('network_error', `could not reach ${this.baseUrl}: ${(error as Error).message}`, 'check --api-url or SCRIBASE_API_URL');
|
||||
}
|
||||
const text = await response.text();
|
||||
let parsed: unknown = null;
|
||||
try {
|
||||
parsed = text.length > 0 ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
parsed = { detail: text.slice(0, 200) };
|
||||
}
|
||||
return { status: response.status, body: parsed as T };
|
||||
}
|
||||
}
|
||||
|
||||
function problem(body: unknown): { code: string; detail: string } {
|
||||
const value = (body ?? {}) as { code?: unknown; detail?: unknown };
|
||||
return {
|
||||
code: typeof value.code === 'string' ? value.code : 'request_failed',
|
||||
detail: typeof value.detail === 'string' ? value.detail : 'the request failed',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The next step for a `402` on project create: a card (the free trial ended,
|
||||
* or was already used), or (SB4 and WP 3.6/3.8) the person's approval of what
|
||||
* the project adds, a spend cap, a plan's project cap or the agent project
|
||||
* limit.
|
||||
*/
|
||||
export function billingNextStep(problem: { code: string; detail: string }, consoleUrl: string): string {
|
||||
switch (problem.code) {
|
||||
case 'confirm_billable': {
|
||||
const cents = /monthly_delta_cents (\d+)/.exec(problem.detail)?.[1];
|
||||
return cents
|
||||
? `this project adds $${(Number(cents) / 100).toFixed(Number(cents) % 100 === 0 ? 0 : 2)} a month; if the person approves, run this again with --confirm-billable ${cents}`
|
||||
: 'ask the person to approve the charge, then run this again with --confirm-billable <monthly_delta_cents>';
|
||||
}
|
||||
case 'spend_cap_reached':
|
||||
return `raise the monthly spend cap in Billing at ${consoleUrl}, or delete a project`;
|
||||
case 'plan_project_cap':
|
||||
return `switch plans in Billing at ${consoleUrl}, or delete a project`;
|
||||
case 'agent_project_limit':
|
||||
return `a person can raise the agent project limit in Billing at ${consoleUrl}`;
|
||||
case 'email_verification_required':
|
||||
return 'confirm your email address (the link we sent) to start the free trial, then run this again';
|
||||
default:
|
||||
return problem.detail.toLowerCase().includes('trial')
|
||||
? `${problem.detail}: ${consoleUrl}/start, then run this again`
|
||||
: `add a card at ${consoleUrl}/start, then run this again`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The console that belongs to an API origin: SCRIBASE_CONSOLE_URL when set,
|
||||
* else `api.<domain>` -> `console.<domain>`, else hosted Scribase's console.
|
||||
*/
|
||||
export function consoleUrlFor(apiUrl: string, env: Record<string, string | undefined>): string {
|
||||
const explicit = env.SCRIBASE_CONSOLE_URL?.trim();
|
||||
if (explicit) return explicit.replace(/\/+$/, '');
|
||||
try {
|
||||
const url = new URL(apiUrl);
|
||||
if (url.hostname.startsWith('api.')) {
|
||||
return `${url.protocol}//console.${url.hostname.slice('api.'.length)}`;
|
||||
}
|
||||
} catch {
|
||||
// fall through to the hosted console
|
||||
}
|
||||
return 'https://console.scribase.com';
|
||||
}
|
||||
|
||||
function fail(status: number, body: unknown, next?: string): never {
|
||||
const { code, detail } = problem(body);
|
||||
throw new InitError(code, `${detail} (HTTP ${status})`, next);
|
||||
}
|
||||
|
||||
function randomKey(prefix: string): string {
|
||||
return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
}
|
||||
|
||||
async function waitUntil<T>(io: InitIo, seconds: number, probe: () => Promise<T | null>, what: string): Promise<T> {
|
||||
const deadline = Date.now() + seconds * 1000;
|
||||
let delay = 1000;
|
||||
for (;;) {
|
||||
const value = await probe();
|
||||
if (value !== null) return value;
|
||||
if (Date.now() >= deadline) {
|
||||
throw new InitError('timeout', `${what} is not ready yet`, 'run `npx scribase init` again in a minute; it picks up where it left off');
|
||||
}
|
||||
await io.sleep(delay);
|
||||
delay = Math.min(delay * 2, 5000);
|
||||
}
|
||||
}
|
||||
|
||||
async function provisionTemporary(io: InitIo, api: Api, options: InitOptions): Promise<Provisioned> {
|
||||
const challenge = await api.call<{ challenge: string; bits: number }>('POST', '/v1/temporary-projects/challenge', {});
|
||||
if (challenge.status !== 200) {
|
||||
fail(challenge.status, challenge.body, 'sign up and run `npx scribase init` without --temp');
|
||||
}
|
||||
const bits = challenge.body.bits;
|
||||
const payload: Record<string, string> = { name: projectSlug(options.name ?? io.cwd.split('/').pop()) };
|
||||
if (bits > 0) {
|
||||
payload.challenge = challenge.body.challenge;
|
||||
payload.nonce = solveChallenge(challenge.body.challenge, bits);
|
||||
}
|
||||
const created = await api.call<{
|
||||
id: string;
|
||||
organization_id: string;
|
||||
project_id: string;
|
||||
environment_id: string;
|
||||
agent_token: string;
|
||||
claim_url: string;
|
||||
expires_at: number;
|
||||
}>('POST', '/v1/temporary-projects', payload);
|
||||
if (created.status !== 201) fail(created.status, created.body);
|
||||
const project = created.body;
|
||||
const agentApi = new Api(io, api.baseUrl, project.agent_token);
|
||||
const keys = await waitUntil(
|
||||
io,
|
||||
options.waitSeconds,
|
||||
async () => {
|
||||
const status = await agentApi.call<{ status: string; keys: Keys | null }>('GET', `/v1/temporary-projects/${project.id}`);
|
||||
if (status.status !== 200) fail(status.status, status.body);
|
||||
if (status.body.status === 'failed') {
|
||||
throw new InitError('provisioning_failed', 'the temporary database could not be created', 'try again, or sign up');
|
||||
}
|
||||
return status.body.status === 'ready' && status.body.keys ? status.body.keys : null;
|
||||
},
|
||||
'the temporary database',
|
||||
);
|
||||
return {
|
||||
organization_id: project.organization_id,
|
||||
project_id: project.project_id,
|
||||
environment_id: project.environment_id,
|
||||
keys,
|
||||
reused: false,
|
||||
agentToken: project.agent_token,
|
||||
claimUrl: project.claim_url,
|
||||
expiresAt: project.expires_at,
|
||||
temporaryId: project.id,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The claim link with `?ref=<install id>` before the `#<claim token>`
|
||||
* fragment, so the claim page can credit where the project came from. An
|
||||
* existing `ref` is kept; an invalid id is not added.
|
||||
*/
|
||||
/** `2026-11-15 10:00 UTC` from epoch seconds; the time a temporary project is deleted. */
|
||||
export function deletedAtUtc(expiresAt: number): string {
|
||||
const iso = new Date(expiresAt * 1000).toISOString();
|
||||
return `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The one line every surface prints for a temporary project, so the claim
|
||||
* link is never only inside `.scribase/project.json`:
|
||||
* "Temporary project, deleted 2026-11-15 10:00 UTC. Keep it: <claim_url>".
|
||||
* Found 2026-11-12: 69 temporary projects created, 0 claimed.
|
||||
*/
|
||||
export function temporaryNote(expiresAt: number | undefined, claimUrl: string): string {
|
||||
const when = expiresAt ? deletedAtUtc(expiresAt) : 'when it expires';
|
||||
return `Temporary project, deleted ${when}. Keep it: ${claimUrl}`;
|
||||
}
|
||||
|
||||
export function claimUrlWithRef(claimUrl: string, ref: string | null | undefined): string {
|
||||
if (!ref || !/^[A-Za-z0-9_-]{8,64}$/.test(ref)) return claimUrl;
|
||||
const hash = claimUrl.indexOf('#');
|
||||
const base = hash < 0 ? claimUrl : claimUrl.slice(0, hash);
|
||||
const fragment = hash < 0 ? '' : claimUrl.slice(hash);
|
||||
if (/[?&]ref=/.test(base)) return claimUrl;
|
||||
return `${base}${base.includes('?') ? '&' : '?'}ref=${ref}${fragment}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* `--watch`: polls the environment's first served request (the gateway log
|
||||
* shipper records it) until it arrives or `seconds` pass. Never throws: a
|
||||
* watch that cannot read the answer reports `null`.
|
||||
*/
|
||||
async function watchFirstRequest(io: InitIo, api: Api, provisioned: Provisioned, seconds: number): Promise<number | null> {
|
||||
const path =
|
||||
`/v1/organizations/${encodeURIComponent(provisioned.organization_id)}` +
|
||||
`/projects/${encodeURIComponent(provisioned.project_id)}` +
|
||||
`/environments/${encodeURIComponent(provisioned.environment_id)}/first-request`;
|
||||
const now = io.now ?? Date.now;
|
||||
const deadline = now() + seconds * 1000;
|
||||
io.log(`Watching for your app's first request (up to ${seconds} s). Run your app now.`);
|
||||
for (;;) {
|
||||
let answer: { status: number; body: { first_request_at?: number | null } };
|
||||
try {
|
||||
answer = await api.call<{ first_request_at?: number | null }>('GET', path);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (answer.status !== 200) return null;
|
||||
const at = answer.body?.first_request_at;
|
||||
if (typeof at === 'number') return at;
|
||||
if (now() >= deadline) return null;
|
||||
await io.sleep(3000);
|
||||
}
|
||||
}
|
||||
|
||||
async function environmentKeys(api: Api, organization: string, project: string, environment: string): Promise<Keys | null> {
|
||||
const path = `/v1/organizations/${encodeURIComponent(organization)}/projects/${encodeURIComponent(project)}/environments/${encodeURIComponent(environment)}`;
|
||||
const env = await api.call<{ phase?: string }>('GET', path);
|
||||
if (env.status === 404) return null;
|
||||
if (env.status !== 200) fail(env.status, env.body);
|
||||
if (env.body.phase === 'failed_recoverable') {
|
||||
throw new InitError('provisioning_failed', 'the database failed to provision', 'open the console to see why');
|
||||
}
|
||||
if (env.body.phase !== 'ready') return null;
|
||||
const keys = await api.call<Keys>('GET', `${path}/api-keys`);
|
||||
if (keys.status !== 200) fail(keys.status, keys.body);
|
||||
return keys.body;
|
||||
}
|
||||
|
||||
async function provisionWithAccount(io: InitIo, api: Api, options: InitOptions): Promise<Provisioned> {
|
||||
let organization = options.org;
|
||||
if (!organization) {
|
||||
const orgs = await api.call<{ items?: { organization_id: string }[] }>('GET', '/v1/organizations');
|
||||
if (orgs.status === 401) {
|
||||
throw new InitError('unauthorized', 'the access token was refused', 'run `scribase login`, set SCRIBASE_ACCESS_TOKEN, or use --temp');
|
||||
}
|
||||
if (orgs.status !== 200) fail(orgs.status, orgs.body);
|
||||
organization = orgs.body.items?.[0]?.organization_id;
|
||||
if (!organization) {
|
||||
throw new InitError('no_organization', 'this account has no organization yet', 'finish sign-up in the console (it creates one), or use --temp');
|
||||
}
|
||||
}
|
||||
const project = projectSlug(options.name ?? io.cwd.split('/').pop());
|
||||
const region = options.region ?? DEFAULT_REGION;
|
||||
const put = await api.call('PUT', `/v1/organizations/${encodeURIComponent(organization)}/projects/${encodeURIComponent(project)}`, {
|
||||
region,
|
||||
postgres_major: 17,
|
||||
...(options.confirmBillableCents === undefined ? {} : { confirm_billable_cents: options.confirmBillableCents }),
|
||||
});
|
||||
if (put.status === 402) {
|
||||
fail(put.status, put.body, billingNextStep(problem(put.body), consoleUrlFor(api.baseUrl, io.env)));
|
||||
}
|
||||
if (put.status !== 200 && put.status !== 201) fail(put.status, put.body);
|
||||
const created = await api.call(
|
||||
'POST',
|
||||
'/v1/environments',
|
||||
{
|
||||
organization_id: organization,
|
||||
project_id: project,
|
||||
environment_id: ENVIRONMENT_ID,
|
||||
kind: 'production',
|
||||
data_mode: 'schema_only',
|
||||
region,
|
||||
postgres_major: 17,
|
||||
},
|
||||
{ 'idempotency-key': randomKey('init-env') },
|
||||
);
|
||||
const reused = created.status === 409;
|
||||
if (!reused && created.status !== 200 && created.status !== 201 && created.status !== 202) {
|
||||
fail(created.status, created.body);
|
||||
}
|
||||
const keys = await waitUntil(io, options.waitSeconds, () => environmentKeys(api, organization, project, ENVIRONMENT_ID), 'the database');
|
||||
return { organization_id: organization, project_id: project, environment_id: ENVIRONMENT_ID, keys, reused };
|
||||
}
|
||||
|
||||
interface SavedState {
|
||||
organization_id: string;
|
||||
project_id: string;
|
||||
environment_id: string;
|
||||
api_url: string;
|
||||
temporary: boolean;
|
||||
claim_url?: string;
|
||||
expires_at?: number;
|
||||
/** The temporary project's id (`tmp_...`), for its status and claim routes. */
|
||||
temporary_id?: string;
|
||||
}
|
||||
|
||||
function readState(io: InitIo): SavedState | null {
|
||||
const text = io.readFile(join(io.cwd, STATE_FILE));
|
||||
if (!text) return null;
|
||||
try {
|
||||
const value = JSON.parse(text) as SavedState;
|
||||
return value.organization_id && value.project_id && value.environment_id ? value : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function envValues(conventions: FrameworkConventions, provisioned: Provisioned, apiUrl: string): Record<string, string> {
|
||||
const projectUrl = provisioned.keys.api_url ?? '';
|
||||
const values: Record<string, string> = {
|
||||
[conventions.urlVar]: projectUrl,
|
||||
[conventions.anonKeyVar]: provisioned.keys.anon_key,
|
||||
};
|
||||
if (conventions.serviceRoleVar && provisioned.keys.service_role_key) {
|
||||
values[conventions.serviceRoleVar] = provisioned.keys.service_role_key;
|
||||
}
|
||||
values.SCRIBASE_API_URL = apiUrl;
|
||||
values.SCRIBASE_ORG = provisioned.organization_id;
|
||||
values.SCRIBASE_PROJECT = provisioned.project_id;
|
||||
values.SCRIBASE_ENV = provisioned.environment_id;
|
||||
if (provisioned.agentToken) {
|
||||
// The temporary project's own agent token (scoped to it, expires with it),
|
||||
// so the agent can keep running migrations and SQL.
|
||||
values.SCRIBASE_ACCESS_TOKEN = provisioned.agentToken;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/** Writes the keys into the linked Vercel project; never throws. */
|
||||
async function pushToVercel(io: InitIo, provisioned: Provisioned, projectUrl: string): Promise<InitResult['vercel']> {
|
||||
const result = await syncVercel(io, {
|
||||
organization: provisioned.organization_id,
|
||||
project: provisioned.project_id,
|
||||
environment: provisioned.environment_id,
|
||||
apiUrl: projectUrl,
|
||||
anonKey: provisioned.keys.anon_key,
|
||||
serviceRoleKey: provisioned.keys.service_role_key ?? null,
|
||||
});
|
||||
return {
|
||||
status: result.status,
|
||||
targets: result.targets,
|
||||
...(result.project_id ? { project_id: result.project_id } : {}),
|
||||
...(result.error ? { error: result.error } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Runs `scribase init`. Throws {@link InitError} with a code and a next step. */
|
||||
export async function runInit(initial: InitOptions, io: InitIo): Promise<InitResult> {
|
||||
let options = initial;
|
||||
const clock = io.now ?? Date.now;
|
||||
const startedAt = clock();
|
||||
const exists = (relative: string) => io.exists(join(io.cwd, relative));
|
||||
const packageText = io.readFile(join(io.cwd, 'package.json'));
|
||||
let packageJson: ProjectFacts['packageJson'] = null;
|
||||
if (packageText) {
|
||||
try {
|
||||
packageJson = JSON.parse(packageText) as ProjectFacts['packageJson'];
|
||||
} catch {
|
||||
throw new InitError('invalid_package_json', 'package.json is not valid JSON');
|
||||
}
|
||||
}
|
||||
const facts = { packageJson, exists };
|
||||
const framework = detectFramework(facts);
|
||||
// A Flutter, Swift, Android or Python project (PS2.4): the env file and
|
||||
// the project, but no JavaScript client and no npm install.
|
||||
const native = detectNative(facts);
|
||||
const conventions = conventionsFor(framework, facts);
|
||||
const stored = io.credentials();
|
||||
const apiUrl = (options.apiUrl ?? io.env.SCRIBASE_API_URL ?? stored.apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, '');
|
||||
let token = options.token ?? io.env.SCRIBASE_ACCESS_TOKEN ?? stored.token;
|
||||
const state = readState(io);
|
||||
|
||||
const envPath = join(io.cwd, conventions.envFile);
|
||||
const envContents = io.readFile(envPath) ?? '';
|
||||
|
||||
let provisioned: Provisioned | null = null;
|
||||
if (state) {
|
||||
// Re-running init reuses this directory's project. A temporary project is
|
||||
// reached with its own agent token from the env file.
|
||||
const reuseToken = state.temporary ? (readEnvValue(envContents, 'SCRIBASE_ACCESS_TOKEN') ?? token) : token;
|
||||
if (reuseToken) {
|
||||
try {
|
||||
const api = new Api(io, apiUrl, reuseToken);
|
||||
const keys = await waitUntil(
|
||||
io,
|
||||
options.waitSeconds,
|
||||
() => environmentKeys(api, state.organization_id, state.project_id, state.environment_id),
|
||||
'the database',
|
||||
);
|
||||
provisioned = { ...state, keys, reused: true };
|
||||
} catch (error) {
|
||||
const gone = error instanceof InitError && ['unauthorized', 'forbidden', 'insufficient_scope', 'not_found'].includes(error.code);
|
||||
if (!(state.temporary && gone)) throw error;
|
||||
io.log('The temporary project of this directory expired: creating a new one.');
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!provisioned && options.account && !token) {
|
||||
if (!io.login) {
|
||||
throw new InitError('not_signed_in', 'not signed in to Scribase', 'run `npx scribase login`, or drop --account for a 72-hour temporary project');
|
||||
}
|
||||
// Not signed in: ask the person to approve this app in the browser
|
||||
// instead of asking them for a key.
|
||||
const project = projectSlug(options.name ?? io.cwd.split('/').pop());
|
||||
const outcome = await io.login(apiUrl, { project, json: options.json, noWait: options.noWait });
|
||||
if (outcome.status === 'pending' || !outcome.token) {
|
||||
throw new InitError(
|
||||
'authorization_pending',
|
||||
`waiting for approval of code ${outcome.userCode ?? ''} at ${outcome.verificationUriComplete ?? 'the console'}`,
|
||||
`ask the person to open ${outcome.verificationUriComplete ?? 'the link'} and approve code ${outcome.userCode ?? ''}, then run this command again`,
|
||||
{ user_code: outcome.userCode, verification_uri_complete: outcome.verificationUriComplete },
|
||||
);
|
||||
}
|
||||
token = outcome.token;
|
||||
if (!options.org && outcome.organizationId) options = { ...options, org: outcome.organizationId };
|
||||
}
|
||||
if (!provisioned) {
|
||||
if (options.temp || !token) {
|
||||
// Temporary-first: no account needed to see it work. Claiming it later
|
||||
// (sign up + card) keeps the same URL and keys.
|
||||
if (!options.temp) io.log('Not signed in: creating a temporary project (72 hours; claim it to keep it, or use --account).');
|
||||
// Signed in and asking for --temp: the token makes the platform count
|
||||
// this account's temporary projects, not the (office) address's.
|
||||
provisioned = await provisionTemporary(io, new Api(io, apiUrl, token ?? undefined), options);
|
||||
} else {
|
||||
provisioned = await provisionWithAccount(io, new Api(io, apiUrl, token), options);
|
||||
}
|
||||
}
|
||||
if (!provisioned.keys.api_url) {
|
||||
throw new InitError('no_project_url', 'the deployment did not report a project URL', 'ask the operator to set SCRIBASE_GATEWAY_BASE_URL_TEMPLATE');
|
||||
}
|
||||
const liveInSeconds = Math.max(0, Math.round((clock() - startedAt) / 100) / 10);
|
||||
let installId: string | null = null;
|
||||
try {
|
||||
installId = io.installId?.() ?? null;
|
||||
} catch {
|
||||
installId = null;
|
||||
}
|
||||
const claimUrl = provisioned.claimUrl ? claimUrlWithRef(provisioned.claimUrl, installId) : undefined;
|
||||
|
||||
const values = envValues(conventions, provisioned, apiUrl);
|
||||
const temporary = Boolean(provisioned.agentToken) || Boolean(state?.temporary && provisioned.reused);
|
||||
const noteClaimUrl = claimUrl ?? state?.claim_url;
|
||||
const noteExpiresAt = provisioned.expiresAt ?? state?.expires_at;
|
||||
// The env file is gitignored below and already holds the agent token, so
|
||||
// the claim link (which is just as sensitive) belongs in the same place —
|
||||
// next to the keys the person will actually open.
|
||||
const notes = temporary && noteClaimUrl ? [temporaryNote(noteExpiresAt, noteClaimUrl)] : [];
|
||||
io.writeFile(envPath, mergeEnv(envContents, values, notes));
|
||||
// Ignore the env file (keys, the agent token) and .scribase/ (a temporary
|
||||
// project's claim link: whoever holds it can take the project over).
|
||||
const gitignorePath = join(io.cwd, '.gitignore');
|
||||
const currentIgnore = io.readFile(gitignorePath) ?? '';
|
||||
const withEnv = ensureIgnored(currentIgnore, conventions.envFile) ?? currentIgnore;
|
||||
const withState = ensureDirIgnored(withEnv, STATE_DIR) ?? withEnv;
|
||||
if (withState !== currentIgnore) io.writeFile(gitignorePath, withState);
|
||||
|
||||
const saved: SavedState = {
|
||||
organization_id: provisioned.organization_id,
|
||||
project_id: provisioned.project_id,
|
||||
environment_id: provisioned.environment_id,
|
||||
api_url: apiUrl,
|
||||
temporary,
|
||||
...(claimUrl ? { claim_url: claimUrl } : state?.claim_url ? { claim_url: state.claim_url } : {}),
|
||||
...(provisioned.expiresAt ? { expires_at: provisioned.expiresAt } : state?.expires_at ? { expires_at: state.expires_at } : {}),
|
||||
...(provisioned.temporaryId ? { temporary_id: provisioned.temporaryId } : state?.temporary_id ? { temporary_id: state.temporary_id } : {}),
|
||||
};
|
||||
io.writeFile(join(io.cwd, STATE_FILE), `${JSON.stringify(saved, null, 2)}\n`);
|
||||
|
||||
// The backend is live and the env file is written: say so, with the claim
|
||||
// link, before anything slow (the Vercel push, the dependency install).
|
||||
// First-time visitors see a working URL within seconds (SG-D8).
|
||||
io.log(`Backend ready in ${liveInSeconds} s: ${provisioned.keys.api_url} (keys written to ${conventions.envFile})`);
|
||||
if (saved.claim_url && saved.temporary) {
|
||||
io.log(temporaryNote(saved.expires_at, saved.claim_url));
|
||||
}
|
||||
|
||||
const vercel = options.vercel ? await pushToVercel(io, provisioned, provisioned.keys.api_url) : { status: 'disabled' as const, targets: [] };
|
||||
|
||||
let clientFile: string | null = null;
|
||||
if (!native && !exists(conventions.clientFile)) {
|
||||
io.writeFile(join(io.cwd, conventions.clientFile), clientSource(conventions));
|
||||
clientFile = conventions.clientFile;
|
||||
}
|
||||
|
||||
let installed = false;
|
||||
const alreadyInstalled = Boolean(
|
||||
packageJson?.dependencies?.['@supabase/supabase-js'] ?? packageJson?.devDependencies?.['@supabase/supabase-js'],
|
||||
);
|
||||
if (options.install && packageJson && !alreadyInstalled) {
|
||||
const [command, args] = installCommand(packageManager(exists));
|
||||
io.log(`Installing @supabase/supabase-js with ${command} (your backend is already live)...`);
|
||||
let outcome = io.run(command, args, io.cwd);
|
||||
// npm refuses on peer-dependency conflicts (ERESOLVE) that don't affect
|
||||
// supabase-js; retry once with npm's own escape hatch before giving up.
|
||||
if (!outcome.ok && command === 'npm' && /ERESOLVE|legacy-peer-deps/.test(outcome.output)) {
|
||||
outcome = io.run(command, [...args, '--legacy-peer-deps'], io.cwd);
|
||||
}
|
||||
if (!outcome.ok) {
|
||||
throw new InitError('install_failed', `${command} ${args.join(' ')} failed: ${outcome.output.slice(-400)}`, `run \`${command} ${args.join(' ')}\` yourself`);
|
||||
}
|
||||
installed = true;
|
||||
} else if (alreadyInstalled) {
|
||||
installed = true;
|
||||
}
|
||||
|
||||
const importPath = `./${conventions.clientFile.replace(/\.(ts|js|mjs)$/, '')}`;
|
||||
const nextSteps = [
|
||||
`create your first table (the database starts empty): npx scribase sql "${FIRST_TABLE_SQL}"`,
|
||||
`import { supabase } from '${importPath}' and query it: await supabase.from('notes').select()`,
|
||||
'more tables: `npx scribase sql "<SQL>"`, or tracked migrations with `npx scribase migrate new <name>` then `npx scribase migrate`, or the MCP server',
|
||||
];
|
||||
if (native) {
|
||||
nextSteps.splice(1, 1, ...nativeNextSteps(native, provisioned));
|
||||
} else if (!packageJson) {
|
||||
nextSteps.unshift('run `npm init -y && npm install @supabase/supabase-js` (no package.json here)');
|
||||
}
|
||||
if (saved.claim_url) {
|
||||
nextSteps.push(
|
||||
`keep this project (deleted ${saved.expires_at ? deletedAtUtc(saved.expires_at) : 'when it expires'}): open ${saved.claim_url} — sign up, free for 14 days, no card; same URL and keys`,
|
||||
);
|
||||
}
|
||||
let firstRequestAt: number | null | undefined;
|
||||
if (options.watch) {
|
||||
const watchToken = provisioned.agentToken ?? (saved.temporary ? (readEnvValue(envContents, 'SCRIBASE_ACCESS_TOKEN') ?? token) : token);
|
||||
firstRequestAt = await watchFirstRequest(io, new Api(io, apiUrl, watchToken), provisioned, options.watchSeconds);
|
||||
if (firstRequestAt === null) {
|
||||
nextSteps.push('no request reached the backend yet: run your app, then `npx scribase doctor` if it still cannot connect');
|
||||
}
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
framework,
|
||||
temporary: saved.temporary,
|
||||
reused: provisioned.reused,
|
||||
organization_id: provisioned.organization_id,
|
||||
project_id: provisioned.project_id,
|
||||
environment_id: provisioned.environment_id,
|
||||
api_url: provisioned.keys.api_url,
|
||||
env_file: conventions.envFile,
|
||||
env_vars: Object.keys(values),
|
||||
client_file: clientFile,
|
||||
installed,
|
||||
...(saved.claim_url ? { claim_url: saved.claim_url } : {}),
|
||||
...(saved.expires_at ? { expires_at: saved.expires_at, deleted_at_utc: deletedAtUtc(saved.expires_at) } : {}),
|
||||
...(saved.claim_url && saved.temporary ? { keep: temporaryNote(saved.expires_at, saved.claim_url) } : {}),
|
||||
live_in_seconds: liveInSeconds,
|
||||
...(firstRequestAt !== undefined ? { first_request_at: firstRequestAt } : {}),
|
||||
vercel,
|
||||
next_steps: nextSteps,
|
||||
};
|
||||
}
|
||||
359
src/cli/login.ts
Normal file
359
src/cli/login.ts
Normal file
@ -0,0 +1,359 @@
|
||||
/**
|
||||
* `npx scribase login` — sign in without pasting a key, through the OAuth 2.0
|
||||
* Device Authorization Grant (RFC 8628):
|
||||
*
|
||||
* 1. POST /v1/oauth/device/code → a user code (SCRB-7F3K-Q2MX) and a URL.
|
||||
* 2. The person opens the URL, signs in, checks the code, picks the
|
||||
* organization, project, access and lifetime, and approves.
|
||||
* 3. This command polls POST /v1/oauth/token and receives a scoped,
|
||||
* expiring agent token (`scb_agt_…`), stores it (OS keychain, else a
|
||||
* 0600 file) and never prints it.
|
||||
*
|
||||
* For coding agents: `--json` prints `{"event":"device_authorization",...}`
|
||||
* immediately, then one final JSON line. `--no-wait` prints the prompt and
|
||||
* exits; running `login` again resumes the same request. The pending request
|
||||
* is stored in the same format as the Rust CLI's, so either can finish it.
|
||||
*
|
||||
* All I/O goes through {@link LoginIo} so the flow is testable offline.
|
||||
*/
|
||||
|
||||
export const GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';
|
||||
export const DEFAULT_SCOPE = 'project:write sql:write migrations:write functions:deploy branches:write';
|
||||
|
||||
export interface LoginOptions {
|
||||
apiUrl?: string;
|
||||
json: boolean;
|
||||
noWait: boolean;
|
||||
browser: boolean;
|
||||
scopes: string[];
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export interface LoginIo {
|
||||
env: Record<string, string | undefined>;
|
||||
fetch: typeof fetch;
|
||||
sleep: (ms: number) => Promise<void>;
|
||||
/** Unix milliseconds. */
|
||||
now: () => number;
|
||||
/** A human-readable line (stderr in --json mode). */
|
||||
log: (line: string) => void;
|
||||
/** One machine-readable JSON line on stdout. */
|
||||
emit: (value: unknown) => void;
|
||||
openBrowser: (url: string) => void;
|
||||
/** Whether a person is at the terminal (a TTY). */
|
||||
interactive: boolean;
|
||||
/** Stores the token; returns where it went. Never prints the token. */
|
||||
store: (apiUrl: string, token: string) => string;
|
||||
pending: { read: () => string | null; write: (text: string) => void; clear: () => void };
|
||||
/** The API URL stored by an earlier login, if any. */
|
||||
storedApiUrl?: () => string | undefined;
|
||||
}
|
||||
|
||||
export interface Pending {
|
||||
api_url: string;
|
||||
device_code: string;
|
||||
user_code: string;
|
||||
verification_uri: string;
|
||||
verification_uri_complete: string;
|
||||
/** Unix seconds. */
|
||||
expires_at: number;
|
||||
interval: number;
|
||||
}
|
||||
|
||||
export interface Grant {
|
||||
access_token: string;
|
||||
expires_in?: number;
|
||||
scope: string;
|
||||
organization_id: string;
|
||||
project_id: string;
|
||||
}
|
||||
|
||||
export interface LoginResult {
|
||||
ok: true;
|
||||
status: 'approved' | 'pending';
|
||||
user_code?: string;
|
||||
verification_uri_complete?: string;
|
||||
organization_id?: string;
|
||||
project_id?: string;
|
||||
scopes?: string[];
|
||||
expires_at?: number | null;
|
||||
stored_in?: string;
|
||||
next?: string;
|
||||
/** Only returned to in-process callers (init), never printed. */
|
||||
token?: string;
|
||||
}
|
||||
|
||||
export class LoginError extends Error {
|
||||
constructor(
|
||||
readonly code: string,
|
||||
message: string,
|
||||
readonly details: Record<string, unknown> = {},
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'LoginError';
|
||||
}
|
||||
}
|
||||
|
||||
export const DEFAULT_API_URL = 'https://api.scribase.com';
|
||||
|
||||
/** Parses `login` arguments. */
|
||||
export function parseLoginArgs(argv: string[]): LoginOptions {
|
||||
const options: LoginOptions = { json: false, noWait: false, browser: true, scopes: [] };
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index] ?? '';
|
||||
const [flag, inline] = arg.includes('=') ? [arg.slice(0, arg.indexOf('=')), arg.slice(arg.indexOf('=') + 1)] : [arg, undefined];
|
||||
const value = (): string => {
|
||||
const next = inline ?? argv[++index];
|
||||
if (next === undefined || next.startsWith('--')) throw new LoginError('invalid_argument', `${flag} needs a value`);
|
||||
return next;
|
||||
};
|
||||
if (flag === '--json') options.json = true;
|
||||
else if (flag === '--no-wait') options.noWait = true;
|
||||
else if (flag === '--no-browser') options.browser = false;
|
||||
else if (flag === '--api-url') options.apiUrl = value();
|
||||
else if (flag === '--name') options.name = value();
|
||||
else if (flag === '--scope') options.scopes.push(...value().split(/[\s,]+/).filter(Boolean));
|
||||
else if (flag === '--token' || flag === '--with-token') {
|
||||
throw new LoginError('invalid_argument', 'the npm CLI signs in through the browser only; never paste a key', {
|
||||
next: 'run `npx scribase login` and approve the code in the browser',
|
||||
});
|
||||
} else throw new LoginError('invalid_argument', `unknown option ${arg}`);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
export function renderPending(pending: Pending): string {
|
||||
return [
|
||||
`api_url=${pending.api_url}`,
|
||||
`device_code=${pending.device_code}`,
|
||||
`user_code=${pending.user_code}`,
|
||||
`verification_uri=${pending.verification_uri}`,
|
||||
`verification_uri_complete=${pending.verification_uri_complete}`,
|
||||
`expires_at=${pending.expires_at}`,
|
||||
`interval=${pending.interval}`,
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
export function parsePending(text: string): Pending | null {
|
||||
const values = new Map<string, string>();
|
||||
for (const line of text.split('\n')) {
|
||||
const at = line.indexOf('=');
|
||||
if (at > 0) values.set(line.slice(0, at).trim(), line.slice(at + 1).trim());
|
||||
}
|
||||
const get = (key: string) => values.get(key) || undefined;
|
||||
const expires = Number(get('expires_at'));
|
||||
const interval = Number(get('interval'));
|
||||
const [api_url, device_code, user_code, verification_uri, verification_uri_complete] = [
|
||||
get('api_url'),
|
||||
get('device_code'),
|
||||
get('user_code'),
|
||||
get('verification_uri'),
|
||||
get('verification_uri_complete'),
|
||||
];
|
||||
if (!api_url || !device_code || !user_code || !verification_uri || !verification_uri_complete) return null;
|
||||
if (!Number.isFinite(expires) || !Number.isFinite(interval)) return null;
|
||||
return { api_url, device_code, user_code, verification_uri, verification_uri_complete, expires_at: expires, interval };
|
||||
}
|
||||
|
||||
function form(fields: Record<string, string>): string {
|
||||
return new URLSearchParams(fields).toString();
|
||||
}
|
||||
|
||||
async function post(io: LoginIo, url: string, fields: Record<string, string>): Promise<{ status: number; body: Record<string, unknown> }> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await io.fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json', 'user-agent': 'scribase-login' },
|
||||
body: form(fields),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new LoginError('network_error', `could not reach ${url}: ${(error as Error).message}`);
|
||||
}
|
||||
const text = await response.text();
|
||||
let body: Record<string, unknown> = {};
|
||||
try {
|
||||
const parsed: unknown = text ? JSON.parse(text) : {};
|
||||
if (parsed && typeof parsed === 'object') body = parsed as Record<string, unknown>;
|
||||
} catch {
|
||||
body = { error_description: text.slice(0, 200) };
|
||||
}
|
||||
return { status: response.status, body };
|
||||
}
|
||||
|
||||
const text = (value: unknown): string | undefined => (typeof value === 'string' ? value : undefined);
|
||||
const integer = (value: unknown): number | undefined => (typeof value === 'number' && Number.isInteger(value) ? value : undefined);
|
||||
|
||||
function defaultClientName(env: Record<string, string | undefined>): string {
|
||||
if (env.CLAUDECODE || env.CLAUDE_CODE_ENTRYPOINT) return 'Claude Code (npx scribase)';
|
||||
if (env.CURSOR_TRACE_ID) return 'Cursor (npx scribase)';
|
||||
if (env.CODEX_SANDBOX || env.CODEX_HOME) return 'Codex (npx scribase)';
|
||||
return 'Scribase CLI (npx scribase)';
|
||||
}
|
||||
|
||||
/** Starts a device login, or resumes the stored one for this API URL. */
|
||||
export async function startDeviceLogin(apiUrl: string, options: LoginOptions, io: LoginIo): Promise<Pending> {
|
||||
const nowSeconds = Math.floor(io.now() / 1000);
|
||||
const stored = io.pending.read();
|
||||
const resumed = stored ? parsePending(stored) : null;
|
||||
if (resumed && resumed.api_url === apiUrl && resumed.expires_at > nowSeconds + 5) return resumed;
|
||||
const scope = options.scopes.length > 0 ? options.scopes.join(' ') : DEFAULT_SCOPE;
|
||||
const name = (options.name ?? defaultClientName(io.env)).replace(/[\u0000-\u001f]/g, '').slice(0, 80);
|
||||
const answer = await post(io, `${apiUrl}/v1/oauth/device/code`, { client_id: 'scribase-cli', client_name: name, scope });
|
||||
const b = answer.body;
|
||||
const [device_code, user_code, verification_uri, verification_uri_complete] = [
|
||||
text(b.device_code),
|
||||
text(b.user_code),
|
||||
text(b.verification_uri),
|
||||
text(b.verification_uri_complete),
|
||||
];
|
||||
if (answer.status !== 200 || !device_code || !user_code || !verification_uri || !verification_uri_complete) {
|
||||
throw new LoginError(
|
||||
text(b.error) ?? text(b.code) ?? 'device_code_failed',
|
||||
`could not start the login: ${text(b.error_description) ?? text(b.detail) ?? `HTTP ${answer.status}`}`,
|
||||
);
|
||||
}
|
||||
const pending: Pending = {
|
||||
api_url: apiUrl,
|
||||
device_code,
|
||||
user_code,
|
||||
verification_uri,
|
||||
verification_uri_complete,
|
||||
expires_at: nowSeconds + (integer(b.expires_in) ?? 600),
|
||||
interval: integer(b.interval) ?? 5,
|
||||
};
|
||||
io.pending.write(renderPending(pending));
|
||||
return pending;
|
||||
}
|
||||
|
||||
const FINAL_MESSAGES: Record<string, string> = {
|
||||
access_denied: 'the login was denied in the console',
|
||||
expired_token: 'the code expired before it was approved; run `npx scribase login` again',
|
||||
invalid_grant: 'this login was already used or is unknown; run `npx scribase login` again',
|
||||
};
|
||||
|
||||
type PollAnswer = { grant: Grant } | { wait: number | null };
|
||||
|
||||
/** One token request: the grant, or how long to wait (`slow_down` may name a new interval). */
|
||||
async function pollOnce(pending: Pending, io: LoginIo): Promise<PollAnswer> {
|
||||
const answer = await post(io, `${pending.api_url}/v1/oauth/token`, { grant_type: GRANT_TYPE, device_code: pending.device_code });
|
||||
const b = answer.body;
|
||||
const token = text(b.access_token);
|
||||
if (answer.status === 200 && token) {
|
||||
const grant: Grant = {
|
||||
access_token: token,
|
||||
scope: text(b.scope) ?? '',
|
||||
organization_id: text(b.organization_id) ?? '',
|
||||
project_id: text(b.project_id) ?? '',
|
||||
};
|
||||
const expiresIn = integer(b.expires_in);
|
||||
if (expiresIn !== undefined) grant.expires_in = expiresIn;
|
||||
return { grant };
|
||||
}
|
||||
const code = text(b.error) ?? text(b.code) ?? `http_${answer.status}`;
|
||||
if (code === 'authorization_pending') return { wait: null };
|
||||
if (code === 'slow_down') return { wait: integer(b.interval) ?? -1 };
|
||||
throw new LoginError(code, FINAL_MESSAGES[code] ?? text(b.error_description) ?? text(b.detail) ?? `the token endpoint answered HTTP ${answer.status}`);
|
||||
}
|
||||
|
||||
/** Polls until the person decides. Honors `slow_down` (the new interval, else +5 s). */
|
||||
export async function pollDeviceLogin(pending: Pending, io: LoginIo): Promise<Grant> {
|
||||
let interval = Math.min(Math.max(pending.interval, 1), 60);
|
||||
for (;;) {
|
||||
if (io.now() / 1000 >= pending.expires_at) {
|
||||
throw new LoginError('expired_token', FINAL_MESSAGES.expired_token ?? 'expired');
|
||||
}
|
||||
await io.sleep(interval * 1000);
|
||||
const answer = await pollOnce(pending, io);
|
||||
if ('grant' in answer) return answer.grant;
|
||||
if (answer.wait !== null) interval = Math.min(Math.max(answer.wait < 0 ? interval + 5 : answer.wait, 1), 60);
|
||||
}
|
||||
}
|
||||
|
||||
function promptEvent(pending: Pending, nowMs: number): Record<string, unknown> {
|
||||
return {
|
||||
event: 'device_authorization',
|
||||
verification_uri: pending.verification_uri,
|
||||
verification_uri_complete: pending.verification_uri_complete,
|
||||
user_code: pending.user_code,
|
||||
expires_in: Math.max(0, pending.expires_at - Math.floor(nowMs / 1000)),
|
||||
message: `Ask the person to open ${pending.verification_uri_complete} and approve code ${pending.user_code}. Never ask them for a key.`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `login`. Resolves with the outcome (the token itself only in
|
||||
* `result.token`, for in-process callers); throws {@link LoginError}.
|
||||
*/
|
||||
export async function runLogin(options: LoginOptions, io: LoginIo): Promise<LoginResult> {
|
||||
const apiUrl = (options.apiUrl ?? io.env.SCRIBASE_API_URL ?? io.storedApiUrl?.() ?? DEFAULT_API_URL).replace(/\/+$/, '');
|
||||
if (!/^https:\/\/[^\s"\\?#]+$|^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?(\/[^\s"\\?#]*)?$/.test(apiUrl)) {
|
||||
throw new LoginError('invalid_argument', `${apiUrl} is not an https URL (http only for localhost)`);
|
||||
}
|
||||
const stored = io.pending.read();
|
||||
const pending = await startDeviceLogin(apiUrl, options, io);
|
||||
const resumed = stored !== null && parsePending(stored)?.device_code === pending.device_code;
|
||||
if (options.noWait && resumed) {
|
||||
// "Run the same command again": ask once whether the person approved in
|
||||
// the meantime, so a --no-wait rerun finishes instead of re-printing the link.
|
||||
let answer: PollAnswer;
|
||||
try {
|
||||
answer = await pollOnce(pending, io);
|
||||
} catch (error) {
|
||||
if (!(error instanceof LoginError && error.code === 'network_error')) io.pending.clear();
|
||||
throw error;
|
||||
}
|
||||
if ('grant' in answer) return finish(apiUrl, answer.grant, io);
|
||||
}
|
||||
if (options.json) {
|
||||
io.emit(promptEvent(pending, io.now()));
|
||||
} else {
|
||||
io.log('To sign in, open this page and approve the code:');
|
||||
io.log('');
|
||||
io.log(` ${pending.verification_uri_complete}`);
|
||||
io.log(` code: ${pending.user_code}`);
|
||||
io.log('');
|
||||
if (options.browser && io.interactive) io.openBrowser(pending.verification_uri_complete);
|
||||
}
|
||||
if (options.noWait) {
|
||||
return {
|
||||
ok: true,
|
||||
status: 'pending',
|
||||
user_code: pending.user_code,
|
||||
verification_uri_complete: pending.verification_uri_complete,
|
||||
next: 'after the person approves, run the same command again to finish',
|
||||
};
|
||||
}
|
||||
if (!options.json) io.log('Waiting for approval...');
|
||||
let grant: Grant;
|
||||
try {
|
||||
grant = await pollDeviceLogin(pending, io);
|
||||
} catch (error) {
|
||||
if (!(error instanceof LoginError && error.code === 'network_error')) io.pending.clear();
|
||||
throw error;
|
||||
}
|
||||
return finish(apiUrl, grant, io);
|
||||
}
|
||||
|
||||
/** Stores an approved grant and forgets the pending request. */
|
||||
function finish(apiUrl: string, grant: Grant, io: LoginIo): LoginResult {
|
||||
io.pending.clear();
|
||||
const storedIn = io.store(apiUrl, grant.access_token);
|
||||
return {
|
||||
ok: true,
|
||||
status: 'approved',
|
||||
organization_id: grant.organization_id,
|
||||
project_id: grant.project_id,
|
||||
scopes: grant.scope.split(' ').filter(Boolean),
|
||||
expires_at: grant.expires_in === undefined ? null : Math.floor(io.now() / 1000) + grant.expires_in,
|
||||
stored_in: storedIn,
|
||||
token: grant.access_token,
|
||||
};
|
||||
}
|
||||
|
||||
/** The result as printed: never the token. */
|
||||
export function publicResult(result: LoginResult): Omit<LoginResult, 'token'> {
|
||||
const { token: _token, ...rest } = result;
|
||||
return rest;
|
||||
}
|
||||
312
src/cli/migrate.ts
Normal file
312
src/cli/migrate.ts
Normal file
@ -0,0 +1,312 @@
|
||||
/**
|
||||
* `npx scribase migrate`: real SQL migration files for the project this
|
||||
* folder is connected to (after `init`), tracked on disk in `supabase/
|
||||
* migrations/*.sql` and run through the control plane's own plan/lint/apply
|
||||
* route — the same route the generated SDK's `client.migrations` resource
|
||||
* wraps (`POST .../migrations`), finally wired to this binary.
|
||||
*
|
||||
* npx scribase migrate new <name> scaffold a timestamped migration file
|
||||
* npx scribase migrate plan, lint and apply every migration
|
||||
* not yet in this environment's ledger
|
||||
* npx scribase migrate --dry-run plan and lint only; nothing runs
|
||||
*
|
||||
* This replaces the old next-step dead end ("SQL migrations ... with
|
||||
* `scribase db push` from the full CLI") with something that works from this
|
||||
* same npm package: every local `.sql` file under `supabase/migrations/` is
|
||||
* sent, oldest first, every time; the server skips versions already applied
|
||||
* (and refuses if an applied file's SQL changed underneath it — checksum
|
||||
* drift), so this is always safe to re-run. A table in the `public` schema
|
||||
* with no RLS policy is blocked before anything executes (`missing_rls`),
|
||||
* same as it would be for a hand-written `scribase sql` script.
|
||||
*/
|
||||
|
||||
import { readEnvValue } from './envfile.js';
|
||||
import { InitError, STATE_FILE } from './init.js';
|
||||
import type { MigrationInput, MigrationLintFinding, RunMigrationsResult } from '../types.gen.js';
|
||||
|
||||
const DEFAULT_API_URL = 'https://api.scribase.com';
|
||||
/** Env files init may have written, most specific first. */
|
||||
const ENV_FILES = ['.env.local', '.env'] as const;
|
||||
/** Where migration files live, relative to the project root. */
|
||||
export const MIGRATIONS_DIR = 'supabase/migrations';
|
||||
/** `<version>_<name>.sql`: version sorts and parses as the server's i64. */
|
||||
const FILE_PATTERN = /^(\d+)_(.+)\.sql$/;
|
||||
/** Splits a file into its up and (optional) down SQL. */
|
||||
const DOWN_MARKER = /^[ \t]*--[ \t]*down[ \t]*$/im;
|
||||
|
||||
export interface MigrateOptions {
|
||||
action: 'new' | 'run';
|
||||
/** `new` only: the name given on the command line. */
|
||||
name?: string;
|
||||
dryRun: boolean;
|
||||
json: boolean;
|
||||
}
|
||||
|
||||
export interface MigrateIo {
|
||||
cwd: string;
|
||||
env: Record<string, string | undefined>;
|
||||
fetch: typeof fetch;
|
||||
readFile: (path: string) => string | null;
|
||||
writeFile: (path: string, contents: string) => void;
|
||||
/** Filenames directly inside {@link MIGRATIONS_DIR}; empty if it does not exist. */
|
||||
listMigrationFiles: () => string[];
|
||||
credentials: () => { apiUrl?: string; token?: string };
|
||||
now: () => Date;
|
||||
}
|
||||
|
||||
export type MigrateResult =
|
||||
| { ok: true; action: 'new'; version: string; name: string; path: string }
|
||||
| {
|
||||
ok: true;
|
||||
action: 'run';
|
||||
dryRun: boolean;
|
||||
/** How many local `.sql` files were sent (0 when the folder has none yet). */
|
||||
files: number;
|
||||
plan: RunMigrationsResult['plan'];
|
||||
lintFindings: MigrationLintFinding[];
|
||||
applied: number[];
|
||||
/** True when a `BLOCK` finding stopped every pending migration from applying. */
|
||||
blocked: boolean;
|
||||
};
|
||||
|
||||
interface ProjectState {
|
||||
organization_id: string;
|
||||
project_id: string;
|
||||
environment_id: string;
|
||||
api_url?: string;
|
||||
}
|
||||
|
||||
/** Parses `migrate` arguments: `new <name>`, or the default run, plus `--dry-run`/`--json`. */
|
||||
export function parseMigrateArgs(argv: string[]): MigrateOptions {
|
||||
const flags = new Set(argv.filter((arg) => arg.startsWith('--')));
|
||||
const positional = argv.filter((arg) => !arg.startsWith('--'));
|
||||
const unknown = [...flags].find((flag) => flag !== '--dry-run' && flag !== '--json');
|
||||
if (unknown) throw new InitError('invalid_argument', `unknown option ${unknown}`, 'run `npx scribase migrate --help`');
|
||||
const json = flags.has('--json');
|
||||
const dryRun = flags.has('--dry-run');
|
||||
if (positional[0] === 'new') {
|
||||
const name = positional[1];
|
||||
if (!name) throw new InitError('invalid_argument', 'no migration name given', 'run `npx scribase migrate new <name>`, e.g. `npx scribase migrate new add_notes`');
|
||||
return { action: 'new', name, dryRun: false, json };
|
||||
}
|
||||
if (positional.length > 0 && positional[0] !== 'up') {
|
||||
throw new InitError('invalid_argument', `unknown argument ${positional[0]}`, 'run `npx scribase migrate --help`');
|
||||
}
|
||||
return { action: 'run', dryRun, json };
|
||||
}
|
||||
|
||||
/** A filename-safe, lowercase slug; never empty. */
|
||||
function slugify(name: string): string {
|
||||
const slug = name
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '_')
|
||||
.replace(/^_+|_+$/g, '');
|
||||
return slug || 'migration';
|
||||
}
|
||||
|
||||
/** `YYYYMMDDHHMMSS` in UTC: sorts lexically, parses as the server's i64 version. */
|
||||
function versionFor(now: Date): string {
|
||||
const pad = (value: number, length = 2): string => String(value).padStart(length, '0');
|
||||
return (
|
||||
`${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}` +
|
||||
`${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}`
|
||||
);
|
||||
}
|
||||
|
||||
function join(root: string, relative: string): string {
|
||||
return `${root.replace(/\/+$/, '')}/${relative}`;
|
||||
}
|
||||
|
||||
/** The scaffold `npx scribase migrate new <name>` writes. Both the up and down
|
||||
* examples are commented out, so an unedited file applies as a real, valid,
|
||||
* no-op migration (it reserves the version; it changes nothing) rather than
|
||||
* creating a table the caller never asked for. */
|
||||
function scaffold(name: string, slug: string): string {
|
||||
return [
|
||||
`-- ${name}`,
|
||||
'--',
|
||||
'-- Edit the SQL below, then run `npx scribase migrate` (or `--dry-run` to',
|
||||
'-- preview first). Every local file in this folder is sent in version',
|
||||
'-- order every time; already-applied ones are skipped, so re-running is',
|
||||
'-- always safe.',
|
||||
'--',
|
||||
'-- Scribase blocks a migration before anything runs if it leaves a',
|
||||
'-- `public`-schema table with no RLS policy (rule `missing_rls`) -- an',
|
||||
'-- exposed table with RLS off is readable and writable by anyone through',
|
||||
'-- the REST API. Uncomment and adapt this example, or write your own:',
|
||||
'--',
|
||||
`-- create table public.${slug} (`,
|
||||
'-- id uuid primary key default gen_random_uuid(),',
|
||||
'-- created_at timestamptz not null default now()',
|
||||
'-- );',
|
||||
'--',
|
||||
`-- alter table public.${slug} enable row level security;`,
|
||||
'--',
|
||||
`-- create policy "${slug}_select_own" on public.${slug}`,
|
||||
'-- for select',
|
||||
'-- using (auth.uid() is not null);',
|
||||
'',
|
||||
'-- down',
|
||||
'-- SQL here undoes the migration above. Optional: only a future rollback',
|
||||
'-- command reads it; `npx scribase migrate` never runs it. Example for the',
|
||||
'-- table above:',
|
||||
'--',
|
||||
`-- drop table if exists public.${slug};`,
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/** `new`: writes the scaffold and returns where it went. Pure filesystem, no network. */
|
||||
function runNew(name: string, io: MigrateIo): MigrateResult {
|
||||
const slug = slugify(name);
|
||||
const version = versionFor(io.now());
|
||||
const filename = `${version}_${slug}.sql`;
|
||||
const path = join(join(io.cwd, MIGRATIONS_DIR), filename);
|
||||
io.writeFile(path, scaffold(name, slug));
|
||||
return { ok: true, action: 'new', version, name: slug, path };
|
||||
}
|
||||
|
||||
function readProject(io: MigrateIo): ProjectState {
|
||||
const text = io.readFile(join(io.cwd, STATE_FILE));
|
||||
let state: Partial<ProjectState> | null = null;
|
||||
try {
|
||||
state = text ? (JSON.parse(text) as Partial<ProjectState>) : null;
|
||||
} catch {
|
||||
state = null;
|
||||
}
|
||||
if (!state?.organization_id || !state.project_id || !state.environment_id) {
|
||||
throw new InitError('not_initialized', 'this folder is not connected to a Scribase project', 'run `npx scribase init` here first');
|
||||
}
|
||||
return state as ProjectState;
|
||||
}
|
||||
|
||||
function findToken(io: MigrateIo): string | undefined {
|
||||
const fromEnv = io.env.SCRIBASE_ACCESS_TOKEN?.trim();
|
||||
if (fromEnv) return fromEnv;
|
||||
for (const file of ENV_FILES) {
|
||||
const contents = io.readFile(join(io.cwd, file));
|
||||
const value = contents ? readEnvValue(contents, 'SCRIBASE_ACCESS_TOKEN')?.trim() : undefined;
|
||||
if (value) return value;
|
||||
}
|
||||
return io.credentials().token;
|
||||
}
|
||||
|
||||
function failure(status: number, body: unknown): InitError {
|
||||
const value = (body ?? {}) as { code?: unknown; detail?: unknown };
|
||||
const code = typeof value.code === 'string' ? value.code : 'request_failed';
|
||||
const detail = typeof value.detail === 'string' ? value.detail : 'the request failed';
|
||||
const next =
|
||||
status === 401 || status === 403
|
||||
? 'run `npx scribase login`, or `npx scribase init` again if the temporary project expired'
|
||||
: undefined;
|
||||
return new InitError(code, `${detail} (HTTP ${status})`, next);
|
||||
}
|
||||
|
||||
/** Reads every `<version>_<name>.sql` file, oldest version first, splitting each on the `-- down` marker. */
|
||||
function readLocalMigrations(io: MigrateIo): MigrationInput[] {
|
||||
const files = io.listMigrationFiles().filter((name) => FILE_PATTERN.test(name));
|
||||
const parsed = files
|
||||
.map((filename) => {
|
||||
const match = FILE_PATTERN.exec(filename);
|
||||
const version = match?.[1];
|
||||
const name = match?.[2];
|
||||
if (version === undefined || name === undefined) return null;
|
||||
const contents = io.readFile(join(join(io.cwd, MIGRATIONS_DIR), filename)) ?? '';
|
||||
const splitAt = contents.search(DOWN_MARKER);
|
||||
const up = (splitAt === -1 ? contents : contents.slice(0, splitAt)).trim();
|
||||
const downText = splitAt === -1 ? '' : contents.slice(splitAt).replace(DOWN_MARKER, '').trim();
|
||||
// exactOptionalPropertyTypes: omit `down` entirely rather than setting it to undefined.
|
||||
return { version, name, up, ...(downText.length > 0 ? { down: downText } : {}) } satisfies MigrationInput;
|
||||
})
|
||||
.filter((migration): migration is MigrationInput => migration !== null);
|
||||
return parsed.sort((left, right) => (BigInt(left.version) < BigInt(right.version) ? -1 : BigInt(left.version) > BigInt(right.version) ? 1 : 0));
|
||||
}
|
||||
|
||||
/** `run`: sends every local migration file to this folder's project; the server plans, lints and (unless `--dry-run`) applies. */
|
||||
async function runRun(options: MigrateOptions, io: MigrateIo): Promise<MigrateResult> {
|
||||
const migrations = readLocalMigrations(io);
|
||||
if (migrations.length === 0) {
|
||||
return { ok: true, action: 'run', dryRun: options.dryRun, files: 0, plan: { steps: [] }, lintFindings: [], applied: [], blocked: false };
|
||||
}
|
||||
const project = readProject(io);
|
||||
const token = findToken(io);
|
||||
if (!token) {
|
||||
throw new InitError('not_signed_in', 'no Scribase token for this folder', 'run `npx scribase login`, or `npx scribase init` here');
|
||||
}
|
||||
const apiUrl = (io.env.SCRIBASE_API_URL ?? project.api_url ?? io.credentials().apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, '');
|
||||
const path =
|
||||
`/v1/organizations/${encodeURIComponent(project.organization_id)}` +
|
||||
`/projects/${encodeURIComponent(project.project_id)}` +
|
||||
`/environments/${encodeURIComponent(project.environment_id)}/migrations`;
|
||||
let response: Response;
|
||||
try {
|
||||
response = await io.fetch(`${apiUrl}${path}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
'content-type': 'application/json',
|
||||
'user-agent': 'scribase-migrate',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({ migrations, apply: !options.dryRun }),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new InitError('network_error', `could not reach ${apiUrl}: ${(error as Error).message}`, 'check your connection or SCRIBASE_API_URL');
|
||||
}
|
||||
const text = await response.text();
|
||||
let body: unknown = null;
|
||||
try {
|
||||
body = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
body = { detail: text.slice(0, 200) };
|
||||
}
|
||||
if (response.status !== 200) throw failure(response.status, body);
|
||||
const value = (body ?? {}) as Partial<RunMigrationsResult>;
|
||||
const plan = value.plan && Array.isArray(value.plan.steps) ? value.plan : { steps: [] };
|
||||
const lintFindings = Array.isArray(value.lintFindings) ? value.lintFindings : [];
|
||||
const applied = Array.isArray(value.applied) ? value.applied : [];
|
||||
const blocking = lintFindings.some((finding) => finding.severity === 'BLOCK');
|
||||
const blocked = !options.dryRun && plan.steps.length > 0 && applied.length === 0 && blocking;
|
||||
return { ok: true, action: 'run', dryRun: options.dryRun, files: migrations.length, plan, lintFindings, applied, blocked };
|
||||
}
|
||||
|
||||
/** Runs `new` (pure filesystem) or `run` (plan/lint/apply against the control plane). */
|
||||
export async function runMigrate(options: MigrateOptions, io: MigrateIo): Promise<MigrateResult> {
|
||||
if (options.action === 'new') return runNew(options.name as string, io);
|
||||
return runRun(options, io);
|
||||
}
|
||||
|
||||
/** The human-readable output of {@link runMigrate}. */
|
||||
export function formatMigrate(result: MigrateResult): string {
|
||||
if (result.action === 'new') {
|
||||
return [`Created ${MIGRATIONS_DIR}/${result.version}_${result.name}.sql`, 'Edit it, then run `npx scribase migrate` (or `--dry-run` to preview first).', ''].join('\n');
|
||||
}
|
||||
if (result.files === 0) {
|
||||
return [`No migration files in ${MIGRATIONS_DIR}/. Run \`npx scribase migrate new <name>\` to create one.`, ''].join('\n');
|
||||
}
|
||||
const lines: string[] = [];
|
||||
const direction = result.dryRun ? 'would run' : 'ran';
|
||||
const pending = result.plan.steps.filter((step) => step.direction === 'up');
|
||||
if (pending.length === 0) {
|
||||
lines.push(`Up to date: all ${result.files} local migration(s) are already applied.`);
|
||||
} else {
|
||||
lines.push(`${pending.length} migration(s) ${result.dryRun ? 'pending' : result.blocked ? 'blocked' : direction}:`);
|
||||
for (const step of pending) {
|
||||
const state = result.dryRun ? 'planned' : result.applied.includes(step.version) ? 'applied' : 'not applied';
|
||||
lines.push(` ${step.version}_${step.name} (${state})`);
|
||||
}
|
||||
}
|
||||
for (const finding of result.lintFindings) {
|
||||
lines.push(` [${finding.severity}] ${finding.rule}: ${finding.message} (${finding.subject}:${finding.line})`);
|
||||
}
|
||||
if (result.blocked) {
|
||||
lines.push('Nothing applied: a BLOCK finding above stops every pending migration until it is fixed.');
|
||||
} else if (result.dryRun && pending.length > 0) {
|
||||
lines.push('Dry run: nothing applied. Run the same command without --dry-run to apply it.');
|
||||
} else if (pending.length > 0 && !result.blocked) {
|
||||
lines.push('The REST API reloads its schema right after; if a query still says the table is not found, retry in a few seconds.');
|
||||
}
|
||||
lines.push('');
|
||||
return lines.join('\n');
|
||||
}
|
||||
31
src/cli/pow.ts
Normal file
31
src/cli/pow.ts
Normal file
@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Solves the proof-of-work challenge a Scribase deployment may ask for before
|
||||
* it creates an anonymous temporary project: find a nonce so that
|
||||
* `sha256("<challenge>:<nonce>")` starts with `bits` zero bits.
|
||||
*/
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
export function leadingZeroBits(digest: Uint8Array): number {
|
||||
let bits = 0;
|
||||
for (const byte of digest) {
|
||||
if (byte === 0) {
|
||||
bits += 8;
|
||||
continue;
|
||||
}
|
||||
bits += Math.clz32(byte) - 24;
|
||||
break;
|
||||
}
|
||||
return bits;
|
||||
}
|
||||
|
||||
/** Returns a nonce solving the challenge (digits only), or throws after `maxAttempts`. */
|
||||
export function solveChallenge(challenge: string, bits: number, maxAttempts = 1 << 28): string {
|
||||
if (bits <= 0) return '0';
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
||||
const nonce = attempt.toString(36);
|
||||
const digest = createHash('sha256').update(`${challenge}:${nonce}`).digest();
|
||||
if (leadingZeroBits(digest) >= bits) return nonce;
|
||||
}
|
||||
throw new Error(`no proof-of-work solution within ${maxAttempts} attempts`);
|
||||
}
|
||||
204
src/cli/sql.ts
Normal file
204
src/cli/sql.ts
Normal file
@ -0,0 +1,204 @@
|
||||
/**
|
||||
* `npx scribase sql "<script>"`: runs SQL against the project this folder is
|
||||
* connected to (the one `npx scribase init` wrote to `.scribase/project.json`).
|
||||
*
|
||||
* It exists so the first thing a new user tries after init works on an empty
|
||||
* database: create a table here, then query it from the app. The script runs
|
||||
* in one transaction on the control plane (`POST .../database/execute`), which
|
||||
* also makes the REST API see new tables at once. Destructive statements
|
||||
* (DROP, TRUNCATE, DELETE without WHERE, ...) only run with `--confirm`.
|
||||
*
|
||||
* The token comes from SCRIBASE_ACCESS_TOKEN, else the env file init wrote (a
|
||||
* temporary project's own agent token), else `scribase login`. It is never
|
||||
* printed.
|
||||
*/
|
||||
|
||||
import { readEnvValue } from './envfile.js';
|
||||
import { InitError, STATE_FILE } from './init.js';
|
||||
|
||||
const DEFAULT_API_URL = 'https://api.scribase.com';
|
||||
/** Env files init may have written, most specific first. */
|
||||
const ENV_FILES = ['.env.local', '.env'] as const;
|
||||
/** Rows shown per statement in the human output. */
|
||||
const ROWS_SHOWN = 20;
|
||||
/** Command tags that change the schema the REST API serves. */
|
||||
const SCHEMA_COMMAND = /^(CREATE|ALTER|DROP|COMMENT|GRANT|REVOKE)\b/;
|
||||
|
||||
export interface SqlOptions {
|
||||
query: string;
|
||||
json: boolean;
|
||||
confirm: boolean;
|
||||
}
|
||||
|
||||
export interface SqlIo {
|
||||
cwd: string;
|
||||
env: Record<string, string | undefined>;
|
||||
fetch: typeof fetch;
|
||||
readFile: (path: string) => string | null;
|
||||
credentials: () => { apiUrl?: string; token?: string };
|
||||
}
|
||||
|
||||
export interface SqlStatementResult {
|
||||
index: number;
|
||||
command: string;
|
||||
statement: string;
|
||||
kind: string;
|
||||
affected_rows?: number | null;
|
||||
row_count?: number;
|
||||
rows?: Record<string, unknown>[];
|
||||
}
|
||||
|
||||
export type SqlResult =
|
||||
| { ok: true; status: 'committed'; statements: SqlStatementResult[]; duration_ms: number }
|
||||
| { ok: true; status: 'confirmation_required'; destructive: { command: string; statement: string; reason: string }[] };
|
||||
|
||||
interface ProjectState {
|
||||
organization_id: string;
|
||||
project_id: string;
|
||||
environment_id: string;
|
||||
api_url?: string;
|
||||
}
|
||||
|
||||
/** Parses `sql` arguments: one SQL script (or `--file <path>`), `--json`, `--confirm`. */
|
||||
export function parseSqlArgs(argv: string[], readFile: (path: string) => string | null): SqlOptions {
|
||||
let json = false;
|
||||
let confirm = false;
|
||||
const parts: string[] = [];
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index] ?? '';
|
||||
if (arg === '--json') json = true;
|
||||
else if (arg === '--confirm') confirm = true;
|
||||
else if (arg === '--file' || arg.startsWith('--file=')) {
|
||||
const path = arg.startsWith('--file=') ? arg.slice('--file='.length) : argv[++index];
|
||||
if (!path) throw new InitError('invalid_argument', '--file needs a path');
|
||||
const text = readFile(path);
|
||||
if (text === null) throw new InitError('file_not_found', `cannot read ${path}`);
|
||||
parts.push(text);
|
||||
} else if (arg.startsWith('--')) {
|
||||
throw new InitError('invalid_argument', `unknown option ${arg}`, 'run `npx scribase sql --help`');
|
||||
} else parts.push(arg);
|
||||
}
|
||||
const query = parts.join(' ').trim();
|
||||
if (!query) {
|
||||
throw new InitError('invalid_argument', 'no SQL given', 'run `npx scribase sql "select now()"`, or `--file <path>`');
|
||||
}
|
||||
return { query, json, confirm };
|
||||
}
|
||||
|
||||
function join(root: string, relative: string): string {
|
||||
return `${root.replace(/\/+$/, '')}/${relative}`;
|
||||
}
|
||||
|
||||
function readProject(io: SqlIo): ProjectState {
|
||||
const text = io.readFile(join(io.cwd, STATE_FILE));
|
||||
let state: Partial<ProjectState> | null = null;
|
||||
try {
|
||||
state = text ? (JSON.parse(text) as Partial<ProjectState>) : null;
|
||||
} catch {
|
||||
state = null;
|
||||
}
|
||||
if (!state?.organization_id || !state.project_id || !state.environment_id) {
|
||||
throw new InitError('not_initialized', 'this folder is not connected to a Scribase project', 'run `npx scribase init` here first');
|
||||
}
|
||||
return state as ProjectState;
|
||||
}
|
||||
|
||||
function findToken(io: SqlIo): string | undefined {
|
||||
const fromEnv = io.env.SCRIBASE_ACCESS_TOKEN?.trim();
|
||||
if (fromEnv) return fromEnv;
|
||||
for (const file of ENV_FILES) {
|
||||
const contents = io.readFile(join(io.cwd, file));
|
||||
const value = contents ? readEnvValue(contents, 'SCRIBASE_ACCESS_TOKEN')?.trim() : undefined;
|
||||
if (value) return value;
|
||||
}
|
||||
return io.credentials().token;
|
||||
}
|
||||
|
||||
function failure(status: number, body: unknown): InitError {
|
||||
const value = (body ?? {}) as { code?: unknown; detail?: unknown };
|
||||
const code = typeof value.code === 'string' ? value.code : 'request_failed';
|
||||
const detail = typeof value.detail === 'string' ? value.detail : 'the request failed';
|
||||
const next =
|
||||
status === 401 || status === 403
|
||||
? 'run `npx scribase login`, or `npx scribase init` again if the temporary project expired'
|
||||
: undefined;
|
||||
return new InitError(code, `${detail} (HTTP ${status})`, next);
|
||||
}
|
||||
|
||||
/** Runs the script against this folder's project and returns what happened. */
|
||||
export async function runSql(options: SqlOptions, io: SqlIo): Promise<SqlResult> {
|
||||
const project = readProject(io);
|
||||
const token = findToken(io);
|
||||
if (!token) {
|
||||
throw new InitError('not_signed_in', 'no Scribase token for this folder', 'run `npx scribase login`, or `npx scribase init` here');
|
||||
}
|
||||
const apiUrl = (io.env.SCRIBASE_API_URL ?? project.api_url ?? io.credentials().apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, '');
|
||||
const path =
|
||||
`/v1/organizations/${encodeURIComponent(project.organization_id)}` +
|
||||
`/projects/${encodeURIComponent(project.project_id)}` +
|
||||
`/environments/${encodeURIComponent(project.environment_id)}/database/execute`;
|
||||
let response: Response;
|
||||
try {
|
||||
response = await io.fetch(`${apiUrl}${path}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
'content-type': 'application/json',
|
||||
'user-agent': 'scribase-sql',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({ query: options.query, ...(options.confirm ? { confirm: true } : {}) }),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new InitError('network_error', `could not reach ${apiUrl}: ${(error as Error).message}`, 'check your connection or SCRIBASE_API_URL');
|
||||
}
|
||||
const text = await response.text();
|
||||
let body: unknown = null;
|
||||
try {
|
||||
body = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
body = { detail: text.slice(0, 200) };
|
||||
}
|
||||
if (response.status !== 200) throw failure(response.status, body);
|
||||
const value = (body ?? {}) as Record<string, unknown>;
|
||||
if (value.status === 'confirmation_required') {
|
||||
return {
|
||||
ok: true,
|
||||
status: 'confirmation_required',
|
||||
destructive: Array.isArray(value.destructive) ? (value.destructive as { command: string; statement: string; reason: string }[]) : [],
|
||||
};
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
status: 'committed',
|
||||
statements: Array.isArray(value.statements) ? (value.statements as SqlStatementResult[]) : [],
|
||||
duration_ms: typeof value.duration_ms === 'number' ? value.duration_ms : 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** The human-readable output of {@link runSql}. */
|
||||
export function formatSql(result: SqlResult): string {
|
||||
if (result.status === 'confirmation_required') {
|
||||
return [
|
||||
'Nothing ran: these statements remove data.',
|
||||
...result.destructive.map((entry) => ` - ${entry.command}: ${entry.reason} (${entry.statement})`),
|
||||
'Run the same command with --confirm to apply the whole script.',
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
const lines = [`Done in ${result.duration_ms} ms (one transaction).`];
|
||||
for (const statement of result.statements) {
|
||||
if (statement.kind === 'rows' && Array.isArray(statement.rows)) {
|
||||
lines.push(` ${statement.command}: ${statement.row_count ?? statement.rows.length} row(s)`);
|
||||
for (const row of statement.rows.slice(0, ROWS_SHOWN)) lines.push(` ${JSON.stringify(row)}`);
|
||||
} else {
|
||||
const count = typeof statement.affected_rows === 'number' ? ` (${statement.affected_rows})` : '';
|
||||
lines.push(` ${statement.command}${count}`);
|
||||
}
|
||||
}
|
||||
if (result.statements.some((statement) => SCHEMA_COMMAND.test(statement.command))) {
|
||||
lines.push('The REST API reloads its schema right after; if a query still says the table is not found, retry in a few seconds.');
|
||||
}
|
||||
lines.push('');
|
||||
return lines.join('\n');
|
||||
}
|
||||
281
src/cli/vercel.ts
Normal file
281
src/cli/vercel.ts
Normal file
@ -0,0 +1,281 @@
|
||||
/**
|
||||
* Zero-config Vercel sync for `npx scribase init`: when the folder is linked
|
||||
* to a Vercel project, write the backend's URL and keys into that project's
|
||||
* environment variables for development, preview and production.
|
||||
*
|
||||
* Port of `scribase vercel env push` (crates/scribase-cli/src/vercel.rs):
|
||||
*
|
||||
* 1. **Which project.** `VERCEL_PROJECT_ID` (+ `VERCEL_ORG_ID`), else
|
||||
* `.vercel/project.json` written by `vercel link` / `vercel deploy`.
|
||||
* 2. **How to authenticate.** `VERCEL_TOKEN` calls the REST API with fetch
|
||||
* (the token is only ever sent in the Authorization header, never logged).
|
||||
* Without it, a signed-in `vercel` CLI sends the same request with
|
||||
* `vercel api … --input -`, spawned without a shell with the body on
|
||||
* stdin, so its own session is used and no token is read by Scribase.
|
||||
*
|
||||
* One request: `POST /v10/projects/{id}/env?upsert=true[&teamId=]`, so a rerun
|
||||
* (after a key rotation) updates in place. Variable names match the console's
|
||||
* integration (`apps/console/lib/vercel-integration.ts`); the service-role key
|
||||
* is server-only (no `NEXT_PUBLIC_`) and `sensitive`, on preview and production
|
||||
* only (Vercel refuses sensitive values on development).
|
||||
*
|
||||
* {@link syncVercel} never throws: the result says what happened.
|
||||
*/
|
||||
|
||||
export const VERCEL_API = 'https://api.vercel.com';
|
||||
const REQUEST_TIMEOUT_MS = 60_000;
|
||||
const RESPONSE_LIMIT_CHARS = 1024 * 1024;
|
||||
|
||||
export type VercelTarget = 'development' | 'preview' | 'production';
|
||||
export const ALL_TARGETS: readonly VercelTarget[] = ['development', 'preview', 'production'];
|
||||
const DEPLOYED_TARGETS: readonly VercelTarget[] = ['preview', 'production'];
|
||||
|
||||
export type VercelStatus = 'updated' | 'not_linked' | 'no_credentials' | 'failed';
|
||||
|
||||
export interface VercelSyncResult {
|
||||
status: VercelStatus;
|
||||
/** Targets written (empty unless `updated`). */
|
||||
targets: VercelTarget[];
|
||||
project_id?: string;
|
||||
via?: 'VERCEL_TOKEN' | 'vercel CLI';
|
||||
/** Variable names written (never values). */
|
||||
keys?: string[];
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface SpawnOutcome {
|
||||
code: number | null;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}
|
||||
|
||||
export interface VercelIo {
|
||||
cwd: string;
|
||||
env: Record<string, string | undefined>;
|
||||
fetch: typeof fetch;
|
||||
readFile: (path: string) => string | null;
|
||||
/** Runs a program without a shell, writing `input` to its stdin. */
|
||||
spawn?: (command: string, args: string[], options: { cwd: string; input?: string }) => Promise<SpawnOutcome>;
|
||||
}
|
||||
|
||||
export interface VercelLink {
|
||||
projectId: string;
|
||||
orgId?: string;
|
||||
}
|
||||
|
||||
export interface VercelEnvVar {
|
||||
key: string;
|
||||
value: string;
|
||||
type: 'plain' | 'sensitive';
|
||||
target: readonly VercelTarget[];
|
||||
comment: string;
|
||||
}
|
||||
|
||||
export interface SyncInput {
|
||||
organization: string;
|
||||
project: string;
|
||||
environment: string;
|
||||
apiUrl: string;
|
||||
anonKey: string;
|
||||
serviceRoleKey?: string | null;
|
||||
}
|
||||
|
||||
const VALID_ID = /^[A-Za-z0-9_.-]{1,128}$/;
|
||||
|
||||
/** The Vercel project for `cwd`, `null` when not linked. Throws on a malformed link. */
|
||||
export function resolveLink(io: Pick<VercelIo, 'cwd' | 'env' | 'readFile'>): VercelLink | null {
|
||||
const projectId = io.env.VERCEL_PROJECT_ID?.trim();
|
||||
if (projectId) {
|
||||
if (!VALID_ID.test(projectId)) throw new Error('VERCEL_PROJECT_ID is not a Vercel project id or name');
|
||||
const orgId = io.env.VERCEL_ORG_ID?.trim();
|
||||
return orgId && VALID_ID.test(orgId) ? { projectId, orgId } : { projectId };
|
||||
}
|
||||
const text = io.readFile(`${io.cwd.replace(/\/+$/, '')}/.vercel/project.json`);
|
||||
if (text === null) return null;
|
||||
let parsed: { projectId?: unknown; orgId?: unknown };
|
||||
try {
|
||||
parsed = JSON.parse(text) as typeof parsed;
|
||||
} catch {
|
||||
throw new Error('.vercel/project.json is not valid JSON; run `vercel link` again');
|
||||
}
|
||||
if (typeof parsed.projectId !== 'string' || !VALID_ID.test(parsed.projectId)) {
|
||||
throw new Error('.vercel/project.json has no valid projectId; run `vercel link` again');
|
||||
}
|
||||
const orgId = typeof parsed.orgId === 'string' && VALID_ID.test(parsed.orgId) ? parsed.orgId : undefined;
|
||||
return orgId ? { projectId: parsed.projectId, orgId } : { projectId: parsed.projectId };
|
||||
}
|
||||
|
||||
/** The variables for an environment; mirrors `vercelEnvVars` in the console. */
|
||||
export function vercelEnvVars(input: SyncInput): VercelEnvVar[] {
|
||||
const url = input.apiUrl.replace(/\/+$/, '');
|
||||
const note = `Scribase ${input.organization}/${input.project}/${input.environment}`;
|
||||
const plain = (key: string, value: string, what?: string): VercelEnvVar => ({
|
||||
key,
|
||||
value,
|
||||
type: 'plain',
|
||||
target: ALL_TARGETS,
|
||||
comment: what ? `${note}: ${what}` : note,
|
||||
});
|
||||
const vars = [
|
||||
plain('NEXT_PUBLIC_SUPABASE_URL', url, 'project URL'),
|
||||
plain('NEXT_PUBLIC_SUPABASE_ANON_KEY', input.anonKey, 'public anon key (RLS applies)'),
|
||||
plain('NEXT_PUBLIC_SCRIBASE_URL', url, 'project URL'),
|
||||
plain('NEXT_PUBLIC_SCRIBASE_ANON_KEY', input.anonKey, 'public anon key (RLS applies)'),
|
||||
plain('SCRIBASE_ORG', input.organization),
|
||||
plain('SCRIBASE_PROJECT', input.project),
|
||||
plain('SCRIBASE_ENV', input.environment),
|
||||
];
|
||||
if (input.serviceRoleKey) {
|
||||
const comment = `${note}: server-only, bypasses RLS. Never expose to the browser.`;
|
||||
for (const key of ['SUPABASE_SERVICE_ROLE_KEY', 'SCRIBASE_SERVICE_ROLE_KEY']) {
|
||||
vars.push({ key, value: input.serviceRoleKey, type: 'sensitive', target: DEPLOYED_TARGETS, comment });
|
||||
}
|
||||
}
|
||||
return vars;
|
||||
}
|
||||
|
||||
/** `/v10/projects/{id}/env?upsert=true`, with `teamId` for team projects only. */
|
||||
export function requestPath(link: VercelLink): string {
|
||||
const team = link.orgId?.startsWith('team_') ? `&teamId=${encodeURIComponent(link.orgId)}` : '';
|
||||
return `/v10/projects/${encodeURIComponent(link.projectId)}/env?upsert=true${team}`;
|
||||
}
|
||||
|
||||
function vercelMessage(body: string): string | null {
|
||||
try {
|
||||
const parsed = JSON.parse(body) as { error?: { message?: unknown }; message?: unknown; failed?: { error?: { message?: unknown } }[] };
|
||||
const candidates = [parsed.error?.message, parsed.message, parsed.failed?.[0]?.error?.message];
|
||||
const found = candidates.find((value) => typeof value === 'string' && value.length > 0);
|
||||
return typeof found === 'string' ? found : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** A 2xx whose `failed` array is empty; otherwise an error with Vercel's message. */
|
||||
export function checkResponse(status: number, body: string): string | null {
|
||||
if (status < 200 || status >= 300) {
|
||||
const message = vercelMessage(body) ?? body.trim().slice(0, 300);
|
||||
const hint =
|
||||
status === 401 || status === 403
|
||||
? " (the Vercel token or CLI session cannot write this project's environment variables)"
|
||||
: status === 404
|
||||
? ' (the linked Vercel project was not found; run `vercel link` again)'
|
||||
: '';
|
||||
return `Vercel returned HTTP ${status}: ${message}${hint}`;
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(body) as { failed?: unknown };
|
||||
if (Array.isArray(parsed.failed) && parsed.failed.length > 0) {
|
||||
return `Vercel refused some variables: ${vercelMessage(body) ?? 'see the Vercel dashboard'}`;
|
||||
}
|
||||
} catch {
|
||||
// A 2xx without JSON (the CLI with --raw may print nothing): accepted.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function vercelBinary(io: VercelIo): string {
|
||||
return io.env.SCRIBASE_VERCEL_BINARY ?? (process.platform === 'win32' ? 'vercel.cmd' : 'vercel');
|
||||
}
|
||||
|
||||
async function sendWithToken(io: VercelIo, token: string, path: string, body: string): Promise<string | null> {
|
||||
if (/[\s\x00-\x1f\x7f]/.test(token)) return 'VERCEL_TOKEN contains whitespace or control characters';
|
||||
const api = (io.env.SCRIBASE_VERCEL_API_URL ?? VERCEL_API).replace(/\/+$/, '');
|
||||
let response: Response;
|
||||
try {
|
||||
response = await io.fetch(`${api}${path}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
'content-type': 'application/json',
|
||||
'user-agent': 'scribase-init',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
body,
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
} catch (error) {
|
||||
return `the request to Vercel failed: ${(error as Error).message}`;
|
||||
}
|
||||
const text = (await response.text().catch(() => '')).slice(0, RESPONSE_LIMIT_CHARS);
|
||||
return checkResponse(response.status, text);
|
||||
}
|
||||
|
||||
async function signedInCli(io: VercelIo): Promise<boolean> {
|
||||
if (!io.spawn) return false;
|
||||
try {
|
||||
const outcome = await io.spawn(vercelBinary(io), ['whoami', '--non-interactive'], { cwd: io.cwd });
|
||||
return outcome.code === 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function sendWithCli(io: VercelIo, path: string, body: string): Promise<string | null> {
|
||||
const spawn = io.spawn;
|
||||
if (!spawn) return 'no way to run the vercel CLI here';
|
||||
let outcome: SpawnOutcome;
|
||||
try {
|
||||
outcome = await spawn(
|
||||
vercelBinary(io),
|
||||
['api', path, '-X', 'POST', '--input', '-', '--raw', '--non-interactive', '--cwd', io.cwd],
|
||||
{ cwd: io.cwd, input: body },
|
||||
);
|
||||
} catch {
|
||||
return 'could not start the vercel CLI';
|
||||
}
|
||||
if (outcome.code === 0) return checkResponse(201, outcome.stdout.slice(0, RESPONSE_LIMIT_CHARS));
|
||||
const detail = (outcome.stderr.trim() || outcome.stdout.trim()).slice(0, 300);
|
||||
return `\`vercel api\` failed (${detail}); update the CLI with \`npm i -g vercel@latest\` or export VERCEL_TOKEN`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pushes the environment's variables into the linked Vercel project.
|
||||
* Never throws; the outcome says what happened.
|
||||
*/
|
||||
export async function syncVercel(io: VercelIo, input: SyncInput): Promise<VercelSyncResult> {
|
||||
let link: VercelLink | null;
|
||||
try {
|
||||
link = resolveLink(io);
|
||||
} catch (error) {
|
||||
return { status: 'failed', targets: [], error: (error as Error).message };
|
||||
}
|
||||
if (!link) return { status: 'not_linked', targets: [] };
|
||||
const vars = vercelEnvVars(input);
|
||||
const path = requestPath(link);
|
||||
const body = JSON.stringify(vars.map((v) => ({ key: v.key, value: v.value, type: v.type, target: v.target, comment: v.comment })));
|
||||
const token = io.env.VERCEL_TOKEN?.trim();
|
||||
let via: VercelSyncResult['via'];
|
||||
let error: string | null;
|
||||
try {
|
||||
if (token) {
|
||||
via = 'VERCEL_TOKEN';
|
||||
error = await sendWithToken(io, token, path, body);
|
||||
} else if (await signedInCli(io)) {
|
||||
via = 'vercel CLI';
|
||||
error = await sendWithCli(io, path, body);
|
||||
} else {
|
||||
return { status: 'no_credentials', targets: [], project_id: link.projectId };
|
||||
}
|
||||
} catch (unexpected) {
|
||||
return { status: 'failed', targets: [], project_id: link.projectId, error: (unexpected as Error).message };
|
||||
}
|
||||
if (error !== null) return { status: 'failed', targets: [], project_id: link.projectId, via, error };
|
||||
return { status: 'updated', targets: [...ALL_TARGETS], project_id: link.projectId, via, keys: vars.map((v) => v.key) };
|
||||
}
|
||||
|
||||
/** The one line init prints. */
|
||||
export function vercelLine(result: { status: VercelStatus | 'disabled'; targets: readonly VercelTarget[]; error?: string }): string {
|
||||
switch (result.status) {
|
||||
case 'disabled':
|
||||
return 'Vercel sync off (--no-vercel)';
|
||||
case 'updated':
|
||||
return `Vercel env updated for ${result.targets.join(', ')}`;
|
||||
case 'not_linked':
|
||||
return 'Not linked to Vercel — skipped';
|
||||
case 'no_credentials':
|
||||
return 'No Vercel credentials — skipped';
|
||||
case 'failed':
|
||||
return `Vercel env not updated: ${result.error ?? 'unknown error'} (retry with \`scribase vercel env push\`)`;
|
||||
}
|
||||
}
|
||||
423
src/client.ts
Normal file
423
src/client.ts
Normal file
@ -0,0 +1,423 @@
|
||||
import {
|
||||
NetworkError,
|
||||
ScribaseApiError,
|
||||
TimeoutError,
|
||||
errorFromResponse,
|
||||
} from './errors.js';
|
||||
import { resolveIdempotencyKey } from './idempotency.js';
|
||||
import type { Operation } from './types.gen.js';
|
||||
import { OrganizationsResource } from './resources/organizations.js';
|
||||
import { ProjectsResource } from './resources/projects.js';
|
||||
import { EnvironmentsResource } from './resources/environments.js';
|
||||
import { PreviewsResource } from './resources/previews.js';
|
||||
import { BackupsResource } from './resources/backups.js';
|
||||
import { RestoresResource } from './resources/restores.js';
|
||||
import { OperationsResource } from './resources/operations.js';
|
||||
import { UsageResource } from './resources/usage.js';
|
||||
import { ExportResource } from './resources/export.js';
|
||||
import { MigrationsResource } from './resources/migrations.js';
|
||||
import { AuditResource } from './resources/audit.js';
|
||||
import { ImportsResource } from './resources/imports.js';
|
||||
import { InsightsResource } from './resources/insights.js';
|
||||
import { QueuesResource } from './resources/queues.js';
|
||||
import { BranchesResource } from './resources/branches.js';
|
||||
import { AuthResource } from './resources/auth.js';
|
||||
import { StorageResource } from './resources/storage.js';
|
||||
import { FunctionsResource } from './resources/functions.js';
|
||||
import { MetricsResource } from './resources/metrics.js';
|
||||
import { RealtimeResource } from './resources/realtime.js';
|
||||
import { DatabaseResource } from './resources/database.js';
|
||||
import { AccountResource } from './resources/account.js';
|
||||
|
||||
/** A bearer token, or a (possibly async) provider that returns a fresh one. */
|
||||
export type TokenProvider = string | (() => string | Promise<string>);
|
||||
|
||||
export interface ScribaseClientOptions {
|
||||
/**
|
||||
* Installation management endpoint, e.g. `https://api.scribase.com`. The
|
||||
* `openapi.yaml` server URL is a placeholder; there is no default here on
|
||||
* purpose — pointing an SDK at the wrong control plane is never a convenience.
|
||||
*/
|
||||
baseUrl: string;
|
||||
/** Bearer credential presented on every authenticated request. */
|
||||
token: TokenProvider;
|
||||
/** Override the transport (tests, proxies, non-global fetch). */
|
||||
fetch?: typeof fetch;
|
||||
/** Per-attempt timeout in milliseconds. Default 30000. */
|
||||
timeoutMs?: number;
|
||||
/** Max automatic retries for 429/503/network failures. Default 3. */
|
||||
maxRetries?: number;
|
||||
/** Base delay for exponential backoff in milliseconds. Default 250. */
|
||||
retryBaseDelayMs?: number;
|
||||
/** Ceiling for a single backoff wait in milliseconds. Default 20000. */
|
||||
retryMaxDelayMs?: number;
|
||||
/** Extra headers merged into every request (lowest precedence). */
|
||||
defaultHeaders?: Record<string, string>;
|
||||
/** `User-Agent` value. Default identifies this SDK and version. */
|
||||
userAgent?: string;
|
||||
/** Injectable clock/sleep for deterministic backoff in tests. */
|
||||
sleep?: (ms: number) => Promise<void>;
|
||||
}
|
||||
|
||||
/** Internal request description handed to {@link ScribaseClient.send}. */
|
||||
export interface RequestOptions {
|
||||
method: 'GET' | 'PUT' | 'POST' | 'PATCH' | 'DELETE';
|
||||
path: string;
|
||||
query?: Record<string, string | number | boolean | undefined>;
|
||||
body?: unknown;
|
||||
/** Attach an `Idempotency-Key` header (required by mutating endpoints). */
|
||||
idempotencyKey?: string;
|
||||
/** Send the `X-Scribase-Organization-ID` scope header. */
|
||||
organizationHeader?: string;
|
||||
/** Caller cancellation, composed with the per-attempt timeout. */
|
||||
signal?: AbortSignal;
|
||||
/** Expect a 204 with no body. */
|
||||
expectNoContent?: boolean;
|
||||
}
|
||||
|
||||
/** The decoded result of one request, including headers callers care about. */
|
||||
export interface ApiResult<T> {
|
||||
data: T;
|
||||
status: number;
|
||||
/** `Idempotency-Replayed: true` — the server replayed a prior acceptance. */
|
||||
idempotencyReplayed: boolean;
|
||||
headers: Headers;
|
||||
}
|
||||
|
||||
/** Minimal transport surface the resource classes depend on. */
|
||||
export interface HttpTransport {
|
||||
send<T>(options: RequestOptions): Promise<ApiResult<T>>;
|
||||
/**
|
||||
* Fetch a binary resource at an API-relative `path` whose query carries its
|
||||
* own authorization (e.g. a signed export download link). Optional so custom
|
||||
* transports without binary support keep compiling.
|
||||
*/
|
||||
downloadBlob?(path: string, options?: { signal?: AbortSignal }): Promise<Blob>;
|
||||
}
|
||||
|
||||
/**
|
||||
* An accepted mutation (HTTP 202). Every state-changing endpoint returns the
|
||||
* async {@link Operation} to poll plus whether this was an idempotent replay.
|
||||
*/
|
||||
export interface AcceptedOperation {
|
||||
operation: Operation;
|
||||
idempotencyReplayed: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_RETRIES = 3;
|
||||
const DEFAULT_RETRY_BASE_MS = 250;
|
||||
const DEFAULT_RETRY_MAX_MS = 20_000;
|
||||
const SDK_VERSION = '0.1.0';
|
||||
|
||||
const defaultSleep = (ms: number): Promise<void> =>
|
||||
new Promise((resolve) => {
|
||||
setTimeout(resolve, ms);
|
||||
});
|
||||
|
||||
/**
|
||||
* The Scribase control-plane client. Zero runtime dependencies: it is a typed
|
||||
* wrapper over `fetch` that handles auth, idempotency keys, `problem+json`
|
||||
* decoding, and bounded retry with backoff. Resource groups hang off it
|
||||
* (`client.environments`, `client.export`, …).
|
||||
*/
|
||||
export class ScribaseClient implements HttpTransport {
|
||||
readonly #baseUrl: string;
|
||||
readonly #token: TokenProvider;
|
||||
readonly #fetch: typeof fetch;
|
||||
readonly #timeoutMs: number;
|
||||
readonly #maxRetries: number;
|
||||
readonly #retryBaseMs: number;
|
||||
readonly #retryMaxMs: number;
|
||||
readonly #defaultHeaders: Record<string, string>;
|
||||
readonly #userAgent: string;
|
||||
readonly #sleep: (ms: number) => Promise<void>;
|
||||
|
||||
readonly organizations: OrganizationsResource;
|
||||
readonly projects: ProjectsResource;
|
||||
readonly environments: EnvironmentsResource;
|
||||
readonly previews: PreviewsResource;
|
||||
readonly backups: BackupsResource;
|
||||
readonly restores: RestoresResource;
|
||||
readonly operations: OperationsResource;
|
||||
readonly usage: UsageResource;
|
||||
readonly export: ExportResource;
|
||||
readonly migrations: MigrationsResource;
|
||||
readonly audit: AuditResource;
|
||||
readonly imports: ImportsResource;
|
||||
readonly insights: InsightsResource;
|
||||
readonly queues: QueuesResource;
|
||||
readonly branches: BranchesResource;
|
||||
readonly auth: AuthResource;
|
||||
readonly storage: StorageResource;
|
||||
readonly functions: FunctionsResource;
|
||||
readonly metrics: MetricsResource;
|
||||
readonly realtime: RealtimeResource;
|
||||
readonly database: DatabaseResource;
|
||||
readonly account: AccountResource;
|
||||
|
||||
constructor(options: ScribaseClientOptions) {
|
||||
const fetchImpl = options.fetch ?? globalThis.fetch;
|
||||
if (typeof fetchImpl !== 'function') {
|
||||
throw new TypeError(
|
||||
'no global fetch found; pass `fetch` in ScribaseClientOptions (Node >= 22.13 has it built in)',
|
||||
);
|
||||
}
|
||||
this.#baseUrl = normalizeBaseUrl(options.baseUrl);
|
||||
this.#token = options.token;
|
||||
this.#fetch = fetchImpl;
|
||||
this.#timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
this.#maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
|
||||
this.#retryBaseMs = options.retryBaseDelayMs ?? DEFAULT_RETRY_BASE_MS;
|
||||
this.#retryMaxMs = options.retryMaxDelayMs ?? DEFAULT_RETRY_MAX_MS;
|
||||
this.#defaultHeaders = options.defaultHeaders ?? {};
|
||||
this.#userAgent = options.userAgent ?? `scribase-js/${SDK_VERSION}`;
|
||||
this.#sleep = options.sleep ?? defaultSleep;
|
||||
|
||||
this.organizations = new OrganizationsResource(this);
|
||||
this.projects = new ProjectsResource(this);
|
||||
this.environments = new EnvironmentsResource(this);
|
||||
this.previews = new PreviewsResource(this);
|
||||
this.backups = new BackupsResource(this);
|
||||
this.restores = new RestoresResource(this);
|
||||
this.operations = new OperationsResource(this);
|
||||
this.usage = new UsageResource(this);
|
||||
this.export = new ExportResource(this);
|
||||
this.migrations = new MigrationsResource(this);
|
||||
this.audit = new AuditResource(this);
|
||||
this.imports = new ImportsResource(this);
|
||||
this.insights = new InsightsResource(this);
|
||||
this.queues = new QueuesResource(this);
|
||||
this.branches = new BranchesResource(this);
|
||||
this.auth = new AuthResource(this);
|
||||
this.storage = new StorageResource(this);
|
||||
this.functions = new FunctionsResource(this);
|
||||
this.metrics = new MetricsResource(this);
|
||||
this.realtime = new RealtimeResource(this);
|
||||
this.database = new DatabaseResource(this);
|
||||
this.account = new AccountResource(this);
|
||||
}
|
||||
|
||||
/** Mint an idempotency key using the same generator resources use. */
|
||||
idempotencyKey(explicit?: string): string {
|
||||
return resolveIdempotencyKey(explicit);
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET` a binary resource at an API-relative path (signed links carry their
|
||||
* own authorization, so no bearer header is sent) and return its bytes.
|
||||
*/
|
||||
async downloadBlob(path: string, options: { signal?: AbortSignal } = {}): Promise<Blob> {
|
||||
if (!path.startsWith('/v1/')) {
|
||||
throw new TypeError('downloadBlob only follows API-relative /v1/ paths');
|
||||
}
|
||||
let response: Response;
|
||||
try {
|
||||
response = await this.#fetch(this.#baseUrl + path, {
|
||||
method: 'GET',
|
||||
headers: { 'user-agent': this.#userAgent },
|
||||
...(options.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
} catch (error) {
|
||||
if (options.signal?.aborted) {
|
||||
throw options.signal.reason ?? error;
|
||||
}
|
||||
throw new NetworkError(`download from ${path} failed`, error);
|
||||
}
|
||||
if (!response.ok) {
|
||||
const body = await readBody(response);
|
||||
throw errorFromResponse(
|
||||
response.status,
|
||||
body,
|
||||
parseRetryAfter(response.headers.get('retry-after')),
|
||||
);
|
||||
}
|
||||
return response.blob();
|
||||
}
|
||||
|
||||
async send<T>(options: RequestOptions): Promise<ApiResult<T>> {
|
||||
const url = this.#buildUrl(options.path, options.query);
|
||||
let attempt = 0;
|
||||
for (;;) {
|
||||
try {
|
||||
return await this.#attempt<T>(url, options);
|
||||
} catch (error) {
|
||||
const retryAfterMs = this.#retryDelay(error, attempt);
|
||||
if (retryAfterMs === null || attempt >= this.#maxRetries) {
|
||||
throw error;
|
||||
}
|
||||
await this.#sleep(retryAfterMs);
|
||||
attempt += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async #attempt<T>(url: string, options: RequestOptions): Promise<ApiResult<T>> {
|
||||
const headers = await this.#buildHeaders(options);
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => {
|
||||
controller.abort(new TimeoutError(this.#timeoutMs));
|
||||
}, this.#timeoutMs);
|
||||
const onExternalAbort = (): void => controller.abort(options.signal?.reason);
|
||||
if (options.signal) {
|
||||
if (options.signal.aborted) {
|
||||
controller.abort(options.signal.reason);
|
||||
} else {
|
||||
options.signal.addEventListener('abort', onExternalAbort, { once: true });
|
||||
}
|
||||
}
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
// Build init conditionally: exactOptionalPropertyTypes forbids `body: undefined`.
|
||||
const init: RequestInit = { method: options.method, headers, signal: controller.signal };
|
||||
if (options.body !== undefined) {
|
||||
init.body = JSON.stringify(options.body);
|
||||
}
|
||||
response = await this.#fetch(url, init);
|
||||
} catch (error) {
|
||||
if (error instanceof TimeoutError) {
|
||||
throw error;
|
||||
}
|
||||
// The per-attempt timeout aborts with a TimeoutError as the reason.
|
||||
if (controller.signal.reason instanceof TimeoutError) {
|
||||
throw controller.signal.reason;
|
||||
}
|
||||
// Caller cancellation: surface their reason unchanged, never as a
|
||||
// retryable NetworkError.
|
||||
if (options.signal?.aborted) {
|
||||
throw options.signal.reason ?? error;
|
||||
}
|
||||
throw new NetworkError(`request to ${url} failed`, error);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
options.signal?.removeEventListener('abort', onExternalAbort);
|
||||
}
|
||||
|
||||
return this.#decode<T>(response, options);
|
||||
}
|
||||
|
||||
async #decode<T>(
|
||||
response: Response,
|
||||
options: RequestOptions,
|
||||
): Promise<ApiResult<T>> {
|
||||
const idempotencyReplayed =
|
||||
(response.headers.get('idempotency-replayed') ?? '').toLowerCase() === 'true';
|
||||
|
||||
if (!response.ok) {
|
||||
const body = await readBody(response);
|
||||
throw errorFromResponse(
|
||||
response.status,
|
||||
body,
|
||||
parseRetryAfter(response.headers.get('retry-after')),
|
||||
);
|
||||
}
|
||||
|
||||
if (response.status === 204 || options.expectNoContent) {
|
||||
return {
|
||||
data: undefined as T,
|
||||
status: response.status,
|
||||
idempotencyReplayed,
|
||||
headers: response.headers,
|
||||
};
|
||||
}
|
||||
|
||||
const body = (await readBody(response)) as T;
|
||||
return { data: body, status: response.status, idempotencyReplayed, headers: response.headers };
|
||||
}
|
||||
|
||||
/** Returns a delay in ms to retry, or `null` if the error is not retryable. */
|
||||
#retryDelay(error: unknown, attempt: number): number | null {
|
||||
if (error instanceof ScribaseApiError && error.retryable) {
|
||||
if (error.retryAfterSeconds !== undefined) {
|
||||
return Math.min(error.retryAfterSeconds * 1000, this.#retryMaxMs);
|
||||
}
|
||||
return this.#backoff(attempt);
|
||||
}
|
||||
if (error instanceof NetworkError) {
|
||||
return this.#backoff(attempt);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
#backoff(attempt: number): number {
|
||||
const exponential = this.#retryBaseMs * 2 ** attempt;
|
||||
const capped = Math.min(exponential, this.#retryMaxMs);
|
||||
// Full jitter avoids synchronized retries across a fleet of agents.
|
||||
return Math.round(Math.random() * capped);
|
||||
}
|
||||
|
||||
async #buildHeaders(options: RequestOptions): Promise<Headers> {
|
||||
const headers = new Headers(this.#defaultHeaders);
|
||||
headers.set('accept', 'application/json');
|
||||
headers.set('user-agent', this.#userAgent);
|
||||
headers.set('authorization', `Bearer ${await this.#resolveToken()}`);
|
||||
if (options.body !== undefined) {
|
||||
headers.set('content-type', 'application/json');
|
||||
}
|
||||
if (options.idempotencyKey !== undefined) {
|
||||
headers.set('idempotency-key', options.idempotencyKey);
|
||||
}
|
||||
if (options.organizationHeader !== undefined) {
|
||||
headers.set('x-scribase-organization-id', options.organizationHeader);
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
async #resolveToken(): Promise<string> {
|
||||
const token = typeof this.#token === 'function' ? await this.#token() : this.#token;
|
||||
if (!token) {
|
||||
throw new TypeError('token provider returned an empty credential');
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
#buildUrl(path: string, query?: RequestOptions['query']): string {
|
||||
const url = new URL(this.#baseUrl + path);
|
||||
if (query) {
|
||||
for (const [key, value] of Object.entries(query)) {
|
||||
if (value !== undefined) {
|
||||
url.searchParams.set(key, String(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeBaseUrl(raw: string): string {
|
||||
let candidate: URL;
|
||||
try {
|
||||
candidate = new URL(raw);
|
||||
} catch {
|
||||
throw new TypeError(`invalid baseUrl: ${JSON.stringify(raw)}`);
|
||||
}
|
||||
if (candidate.protocol !== 'https:' && candidate.protocol !== 'http:') {
|
||||
throw new TypeError(`baseUrl must be http(s), got ${candidate.protocol}`);
|
||||
}
|
||||
return raw.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
async function readBody(response: Response): Promise<unknown> {
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
const text = await response.text();
|
||||
if (text.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
if (contentType.includes('json')) {
|
||||
try {
|
||||
return JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function parseRetryAfter(value: string | null): number | undefined {
|
||||
if (value === null) {
|
||||
return undefined;
|
||||
}
|
||||
const seconds = Number.parseInt(value, 10);
|
||||
return Number.isFinite(seconds) && seconds >= 0 ? seconds : undefined;
|
||||
}
|
||||
162
src/errors.ts
Normal file
162
src/errors.ts
Normal file
@ -0,0 +1,162 @@
|
||||
import type { Operation, Problem } from './types.gen.js';
|
||||
|
||||
/**
|
||||
* Base class for every error the client raises. Carrying a discriminant
|
||||
* (`name`) plus the parsed {@link Problem} lets callers branch without
|
||||
* string-matching messages.
|
||||
*/
|
||||
export class ScribaseError extends Error {
|
||||
override readonly name: string = 'ScribaseError';
|
||||
|
||||
constructor(message: string, options?: { cause?: unknown }) {
|
||||
super(message, options);
|
||||
// Restore the prototype chain across the TS `extends Error` downlevel gap.
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The API replied with a non-2xx status and a `application/problem+json`
|
||||
* (RFC 9457) body. Subclasses narrow by status; `problem.code` is the stable,
|
||||
* machine-readable discriminator the contract guarantees.
|
||||
*/
|
||||
export class ScribaseApiError extends ScribaseError {
|
||||
override readonly name: string = 'ScribaseApiError';
|
||||
readonly status: number;
|
||||
readonly code: string;
|
||||
readonly problem: Problem;
|
||||
readonly requestId: string | undefined;
|
||||
/** `Retry-After` seconds when the server supplied it (429 / 503). */
|
||||
readonly retryAfterSeconds: number | undefined;
|
||||
|
||||
constructor(problem: Problem, retryAfterSeconds?: number) {
|
||||
super(`${problem.status} ${problem.code}: ${problem.title}`);
|
||||
this.status = problem.status;
|
||||
this.code = problem.code;
|
||||
this.problem = problem;
|
||||
this.requestId = problem.request_id;
|
||||
this.retryAfterSeconds = retryAfterSeconds;
|
||||
}
|
||||
|
||||
/** True for statuses that are safe to retry with the same idempotency key. */
|
||||
get retryable(): boolean {
|
||||
return this.status === 429 || this.status === 503;
|
||||
}
|
||||
}
|
||||
|
||||
export class BadRequestError extends ScribaseApiError {
|
||||
override readonly name = 'BadRequestError';
|
||||
}
|
||||
export class UnauthorizedError extends ScribaseApiError {
|
||||
override readonly name = 'UnauthorizedError';
|
||||
}
|
||||
export class ForbiddenError extends ScribaseApiError {
|
||||
override readonly name = 'ForbiddenError';
|
||||
}
|
||||
export class NotFoundError extends ScribaseApiError {
|
||||
override readonly name = 'NotFoundError';
|
||||
}
|
||||
export class ConflictError extends ScribaseApiError {
|
||||
override readonly name = 'ConflictError';
|
||||
}
|
||||
export class QuotaExceededError extends ScribaseApiError {
|
||||
override readonly name = 'QuotaExceededError';
|
||||
}
|
||||
export class ServiceUnavailableError extends ScribaseApiError {
|
||||
override readonly name = 'ServiceUnavailableError';
|
||||
}
|
||||
|
||||
/** Transport failed before a response arrived (DNS, connection, TLS, abort). */
|
||||
export class NetworkError extends ScribaseError {
|
||||
override readonly name = 'NetworkError';
|
||||
constructor(message: string, cause: unknown) {
|
||||
super(message, { cause });
|
||||
}
|
||||
}
|
||||
|
||||
/** A request exceeded the configured per-attempt timeout. */
|
||||
export class TimeoutError extends ScribaseError {
|
||||
override readonly name = 'TimeoutError';
|
||||
readonly timeoutMs: number;
|
||||
constructor(timeoutMs: number) {
|
||||
super(`request timed out after ${timeoutMs}ms`);
|
||||
this.timeoutMs = timeoutMs;
|
||||
}
|
||||
}
|
||||
|
||||
/** A polled {@link Operation} reached a terminal non-success state. */
|
||||
export class OperationFailedError extends ScribaseError {
|
||||
override readonly name = 'OperationFailedError';
|
||||
readonly operation: Operation;
|
||||
constructor(operation: Operation) {
|
||||
super(
|
||||
operation.state === 'cancelled'
|
||||
? `operation ${operation.id} was cancelled`
|
||||
: `operation ${operation.id} failed: ${operation.error ?? 'unknown error'}`,
|
||||
);
|
||||
this.operation = operation;
|
||||
}
|
||||
}
|
||||
|
||||
/** Polling a long-running resource exceeded the caller's deadline. */
|
||||
export class PollTimeoutError extends ScribaseError {
|
||||
override readonly name = 'PollTimeoutError';
|
||||
constructor(what: string, timeoutMs: number) {
|
||||
super(`gave up waiting for ${what} after ${timeoutMs}ms`);
|
||||
}
|
||||
}
|
||||
|
||||
const BY_STATUS: Record<number, new (problem: Problem, retryAfter?: number) => ScribaseApiError> = {
|
||||
400: BadRequestError,
|
||||
401: UnauthorizedError,
|
||||
403: ForbiddenError,
|
||||
404: NotFoundError,
|
||||
409: ConflictError,
|
||||
429: QuotaExceededError,
|
||||
503: ServiceUnavailableError,
|
||||
};
|
||||
|
||||
/**
|
||||
* Build the most specific {@link ScribaseApiError} for a response. When the
|
||||
* body is not a well-formed Problem (a proxy 502, an HTML error page) we
|
||||
* synthesize one so callers still get a typed `status`/`code` to branch on.
|
||||
*/
|
||||
export function errorFromResponse(
|
||||
status: number,
|
||||
body: unknown,
|
||||
retryAfterSeconds?: number,
|
||||
): ScribaseApiError {
|
||||
const problem = coerceProblem(status, body);
|
||||
const Ctor = BY_STATUS[problem.status] ?? ScribaseApiError;
|
||||
return new Ctor(problem, retryAfterSeconds);
|
||||
}
|
||||
|
||||
function coerceProblem(status: number, body: unknown): Problem {
|
||||
if (isProblem(body)) {
|
||||
return body;
|
||||
}
|
||||
const detail =
|
||||
typeof body === 'string' && body.length > 0
|
||||
? body.slice(0, 2048)
|
||||
: undefined;
|
||||
return {
|
||||
type: 'about:blank',
|
||||
title: 'Unexpected error response',
|
||||
status,
|
||||
code: 'unexpected_response',
|
||||
...(detail !== undefined ? { detail } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function isProblem(value: unknown): value is Problem {
|
||||
if (typeof value !== 'object' || value === null) {
|
||||
return false;
|
||||
}
|
||||
const candidate = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof candidate['type'] === 'string' &&
|
||||
typeof candidate['title'] === 'string' &&
|
||||
typeof candidate['status'] === 'number' &&
|
||||
typeof candidate['code'] === 'string'
|
||||
);
|
||||
}
|
||||
108
src/evidence.ts
Normal file
108
src/evidence.ts
Normal file
@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Verification evidence — the shared trust model behind the product's two
|
||||
* money surfaces: the restore-evidence viewer and the export/import report.
|
||||
*
|
||||
* "Verified restore" and "runnable export" are only worth anything if the
|
||||
* client can render *proof*: row counts that match, checksums that match,
|
||||
* every RLS policy accounted for, and a real login that succeeded. These types
|
||||
* carry that proof to the console verbatim; they are intentionally rich so the
|
||||
* UI never has to guess what passed and what needs a human.
|
||||
*
|
||||
* These planned surfaces are not yet in `openapi.yaml`; they follow BUILDOUT
|
||||
* §9 and ROADMAP §3-4 and mirror the contract's naming (epoch-second integers,
|
||||
* portable identifiers, additive-only optional fields).
|
||||
*/
|
||||
|
||||
/** Per-relation row-count comparison between a source and its verified copy. */
|
||||
export interface RowCountDiff {
|
||||
relation: string;
|
||||
source: number;
|
||||
target: number;
|
||||
matched: boolean;
|
||||
}
|
||||
|
||||
/** Per-relation content checksum comparison. */
|
||||
export interface ChecksumMatch {
|
||||
relation: string;
|
||||
algorithm: 'sha256';
|
||||
source_digest: string;
|
||||
target_digest: string;
|
||||
matched: boolean;
|
||||
}
|
||||
|
||||
/** Whether a specific RLS policy survived the copy on both sides. */
|
||||
export interface PolicyParity {
|
||||
policy: string;
|
||||
relation: string;
|
||||
present_in_source: boolean;
|
||||
present_in_target: boolean;
|
||||
matched: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A real authentication performed against the verified copy — the strongest
|
||||
* possible evidence that auth data (users, identities, MFA factors, and the
|
||||
* user IDs the JWTs are signed against) moved intact.
|
||||
*/
|
||||
export interface LoginProof {
|
||||
subject: string;
|
||||
method: 'password' | 'oauth' | 'magic_link' | 'otp';
|
||||
succeeded: boolean;
|
||||
checked_at_epoch_seconds: number;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
export type VerificationCheckStatus = 'passed' | 'failed' | 'skipped';
|
||||
|
||||
/** A single named assertion in the verification run. */
|
||||
export interface VerificationCheck {
|
||||
name: string;
|
||||
status: VerificationCheckStatus;
|
||||
detail?: string;
|
||||
observed?: string;
|
||||
expected?: string;
|
||||
}
|
||||
|
||||
export type VerificationState = 'unverified' | 'verifying' | 'verified' | 'failed';
|
||||
|
||||
/**
|
||||
* The complete verification record for a backup, restore, or import. Rendered
|
||||
* as the evidence card the product sells on. `state === 'verified'` is the only
|
||||
* value that should present a green result; everything else demands attention.
|
||||
*/
|
||||
export interface VerificationSummary {
|
||||
state: VerificationState;
|
||||
verified_at_epoch_seconds?: number;
|
||||
checks: VerificationCheck[];
|
||||
row_counts: RowCountDiff[];
|
||||
checksums: ChecksumMatch[];
|
||||
policy_parity: PolicyParity[];
|
||||
login_proof: LoginProof[];
|
||||
}
|
||||
|
||||
/** True only when the summary is fully verified with no failed check. */
|
||||
export function isFullyVerified(summary: VerificationSummary): boolean {
|
||||
return (
|
||||
summary.state === 'verified' &&
|
||||
summary.checks.every((check) => check.status !== 'failed') &&
|
||||
summary.row_counts.every((diff) => diff.matched) &&
|
||||
summary.checksums.every((match) => match.matched) &&
|
||||
summary.policy_parity.every((parity) => parity.matched) &&
|
||||
summary.login_proof.every((proof) => proof.succeeded)
|
||||
);
|
||||
}
|
||||
|
||||
/** Count checks by status for a compact headline in the evidence viewer. */
|
||||
export function summarizeChecks(
|
||||
summary: VerificationSummary,
|
||||
): Record<VerificationCheckStatus, number> {
|
||||
const tally: Record<VerificationCheckStatus, number> = {
|
||||
passed: 0,
|
||||
failed: 0,
|
||||
skipped: 0,
|
||||
};
|
||||
for (const check of summary.checks) {
|
||||
tally[check.status] += 1;
|
||||
}
|
||||
return tally;
|
||||
}
|
||||
71
src/idempotency.ts
Normal file
71
src/idempotency.ts
Normal file
@ -0,0 +1,71 @@
|
||||
/**
|
||||
* Idempotency keys. Every mutating /v1 endpoint requires an `Idempotency-Key`
|
||||
* header (1..128 chars) so a retried request replays the first outcome instead
|
||||
* of duplicating work. The client mints one automatically when a caller does
|
||||
* not supply their own; agents are encouraged to pass a stable, meaningful key
|
||||
* (e.g. derived from a plan step) so a re-run is a no-op.
|
||||
*/
|
||||
|
||||
/** Contract bound from `parameters.IdempotencyKey`. */
|
||||
export const MAX_IDEMPOTENCY_KEY_LENGTH = 128;
|
||||
export const MIN_IDEMPOTENCY_KEY_LENGTH = 1;
|
||||
|
||||
/**
|
||||
* Generate a fresh RFC 4122 v4 idempotency key. Uses the platform
|
||||
* `crypto.randomUUID` (Node >= 22 and every modern runtime expose it globally),
|
||||
* falling back to `crypto.getRandomValues` if a host stubs the former out.
|
||||
*/
|
||||
export function newIdempotencyKey(): string {
|
||||
const c: Crypto | undefined = globalThis.crypto;
|
||||
if (c && typeof c.randomUUID === 'function') {
|
||||
return c.randomUUID();
|
||||
}
|
||||
if (c && typeof c.getRandomValues === 'function') {
|
||||
return uuidFromRandomBytes(c);
|
||||
}
|
||||
throw new Error(
|
||||
'no Web Crypto available to generate an idempotency key; pass an explicit `idempotencyKey`',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a caller-supplied key against the contract bounds. Returns the key
|
||||
* unchanged so it can be used inline; throws {@link RangeError} otherwise.
|
||||
*/
|
||||
export function assertIdempotencyKey(key: string): string {
|
||||
if (
|
||||
key.length < MIN_IDEMPOTENCY_KEY_LENGTH ||
|
||||
key.length > MAX_IDEMPOTENCY_KEY_LENGTH
|
||||
) {
|
||||
throw new RangeError(
|
||||
`idempotency key must be ${MIN_IDEMPOTENCY_KEY_LENGTH}..${MAX_IDEMPOTENCY_KEY_LENGTH} characters, got ${key.length}`,
|
||||
);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
/** Resolve an effective key: validate an explicit one, or mint a new one. */
|
||||
export function resolveIdempotencyKey(explicit?: string): string {
|
||||
return explicit === undefined
|
||||
? newIdempotencyKey()
|
||||
: assertIdempotencyKey(explicit);
|
||||
}
|
||||
|
||||
function uuidFromRandomBytes(c: Crypto): string {
|
||||
const bytes = new Uint8Array(16);
|
||||
c.getRandomValues(bytes);
|
||||
// Set version (4) and variant (10xx) bits per RFC 4122 §4.4.
|
||||
bytes[6] = ((bytes[6] as number) & 0x0f) | 0x40;
|
||||
bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80;
|
||||
const hex: string[] = [];
|
||||
for (let i = 0; i < bytes.length; i += 1) {
|
||||
hex.push((bytes[i] as number).toString(16).padStart(2, '0'));
|
||||
}
|
||||
return (
|
||||
`${hex[0]}${hex[1]}${hex[2]}${hex[3]}-` +
|
||||
`${hex[4]}${hex[5]}-` +
|
||||
`${hex[6]}${hex[7]}-` +
|
||||
`${hex[8]}${hex[9]}-` +
|
||||
`${hex[10]}${hex[11]}${hex[12]}${hex[13]}${hex[14]}${hex[15]}`
|
||||
);
|
||||
}
|
||||
379
src/importers/firebase.ts
Normal file
379
src/importers/firebase.ts
Normal file
@ -0,0 +1,379 @@
|
||||
/**
|
||||
* Export a Firebase project into the folder layout `POST /v1/imports` reads
|
||||
* with `source: 'firebase'`:
|
||||
*
|
||||
* ```text
|
||||
* <dir>/firestore.ndjson one Firestore REST Document per line
|
||||
* <dir>/auth.json copy of `firebase auth:export auth.json --format=JSON`
|
||||
* <dir>/hash-config.json the console's password hash parameters (optional)
|
||||
* <dir>/storage/<bucket>/… every Cloud Storage object
|
||||
* ```
|
||||
*
|
||||
* Only Google's public REST APIs are used (Firestore v1, Cloud Storage JSON v1,
|
||||
* OAuth 2.0 JWT bearer), with the runtime's `fetch` and WebCrypto — no Google
|
||||
* SDK dependency. Auth users are exported with the Firebase CLI because their
|
||||
* password hashes are only available through it.
|
||||
*/
|
||||
|
||||
const FIRESTORE_API = 'https://firestore.googleapis.com/v1';
|
||||
const STORAGE_API = 'https://storage.googleapis.com/storage/v1';
|
||||
const DEFAULT_TOKEN_URI = 'https://oauth2.googleapis.com/token';
|
||||
const SCOPES = [
|
||||
'https://www.googleapis.com/auth/datastore',
|
||||
'https://www.googleapis.com/auth/devstorage.read_only',
|
||||
].join(' ');
|
||||
const PAGE_SIZE = 300;
|
||||
|
||||
/** The fields of a Google service-account key file this module uses. */
|
||||
export interface GoogleServiceAccount {
|
||||
client_email: string;
|
||||
private_key: string;
|
||||
token_uri?: string;
|
||||
}
|
||||
|
||||
export interface FirebaseAccess {
|
||||
/** Firebase / Google Cloud project id. */
|
||||
projectId: string;
|
||||
/** A service-account key with Firestore and Storage read access. */
|
||||
serviceAccount?: GoogleServiceAccount;
|
||||
/** Or a ready OAuth access token, e.g. from `gcloud auth print-access-token`. */
|
||||
accessToken?: string;
|
||||
/** Firestore database id. Defaults to `(default)`. */
|
||||
databaseId?: string;
|
||||
/** Injected for tests; defaults to the global `fetch`. */
|
||||
fetch?: typeof fetch;
|
||||
}
|
||||
|
||||
/** One Firestore REST `Document`, exactly as the API returns it. */
|
||||
export interface FirestoreDocument {
|
||||
name: string;
|
||||
fields?: Record<string, unknown>;
|
||||
createTime?: string;
|
||||
updateTime?: string;
|
||||
}
|
||||
|
||||
/** A failure talking to a Google API. The message never includes tokens or keys. */
|
||||
export class FirebaseExportError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(message: string, status = 0) {
|
||||
super(message);
|
||||
this.name = 'FirebaseExportError';
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
function base64Url(bytes: Uint8Array | string): string {
|
||||
const buffer = typeof bytes === 'string' ? new TextEncoder().encode(bytes) : bytes;
|
||||
let binary = '';
|
||||
for (const byte of buffer) {
|
||||
binary += String.fromCharCode(byte);
|
||||
}
|
||||
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
function pemToDer(pem: string): ArrayBuffer {
|
||||
const body = pem
|
||||
.replace(/-----BEGIN [^-]+-----/, '')
|
||||
.replace(/-----END [^-]+-----/, '')
|
||||
.replace(/\\n/g, '')
|
||||
.replace(/\s+/g, '');
|
||||
const binary = atob(body);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index += 1) {
|
||||
bytes[index] = binary.charCodeAt(index);
|
||||
}
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exchanges a service-account key for an OAuth access token (RFC 7523 JWT
|
||||
* bearer grant), signing the assertion with WebCrypto RS256.
|
||||
*/
|
||||
export async function googleAccessToken(
|
||||
account: GoogleServiceAccount,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<string> {
|
||||
if (!account.client_email || !account.private_key) {
|
||||
throw new FirebaseExportError('the service account needs client_email and private_key');
|
||||
}
|
||||
const tokenUri = account.token_uri ?? DEFAULT_TOKEN_URI;
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const header = base64Url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }));
|
||||
const claims = base64Url(
|
||||
JSON.stringify({ iss: account.client_email, scope: SCOPES, aud: tokenUri, iat: now, exp: now + 3600 }),
|
||||
);
|
||||
const key = await crypto.subtle.importKey(
|
||||
'pkcs8',
|
||||
pemToDer(account.private_key),
|
||||
{ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
|
||||
false,
|
||||
['sign'],
|
||||
);
|
||||
const signature = new Uint8Array(
|
||||
await crypto.subtle.sign('RSASSA-PKCS1-v1_5', key, new TextEncoder().encode(`${header}.${claims}`)),
|
||||
);
|
||||
const response = await fetchImpl(tokenUri, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({
|
||||
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
|
||||
assertion: `${header}.${claims}.${base64Url(signature)}`,
|
||||
}).toString(),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new FirebaseExportError('Google rejected the service-account token request', response.status);
|
||||
}
|
||||
const body = (await response.json()) as { access_token?: string };
|
||||
if (!body.access_token) {
|
||||
throw new FirebaseExportError('Google returned no access token');
|
||||
}
|
||||
return body.access_token;
|
||||
}
|
||||
|
||||
async function resolveToken(access: FirebaseAccess, fetchImpl: typeof fetch): Promise<string> {
|
||||
if (access.accessToken) {
|
||||
return access.accessToken;
|
||||
}
|
||||
if (access.serviceAccount) {
|
||||
return googleAccessToken(access.serviceAccount, fetchImpl);
|
||||
}
|
||||
throw new FirebaseExportError('provide serviceAccount or accessToken');
|
||||
}
|
||||
|
||||
async function googleJson<T>(
|
||||
fetchImpl: typeof fetch,
|
||||
token: string,
|
||||
url: string,
|
||||
init: { method?: string; body?: unknown } = {},
|
||||
): Promise<T> {
|
||||
const response = await fetchImpl(url, {
|
||||
method: init.method ?? 'GET',
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
...(init.body !== undefined ? { 'content-type': 'application/json' } : {}),
|
||||
},
|
||||
...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new FirebaseExportError(
|
||||
`Google API request failed (${response.status}) for ${new URL(url).pathname}`,
|
||||
response.status,
|
||||
);
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Streams every Firestore document — every collection and every nested
|
||||
* subcollection — in the REST `Document` shape the importer reads.
|
||||
*/
|
||||
export async function* exportFirestoreDocuments(
|
||||
access: FirebaseAccess,
|
||||
): AsyncGenerator<FirestoreDocument> {
|
||||
const fetchImpl = access.fetch ?? fetch;
|
||||
const token = await resolveToken(access, fetchImpl);
|
||||
const database = encodeURIComponent(access.databaseId ?? '(default)');
|
||||
const root = `projects/${encodeURIComponent(access.projectId)}/databases/${database}/documents`;
|
||||
|
||||
const listCollectionIds = async (parent: string): Promise<string[]> => {
|
||||
const ids: string[] = [];
|
||||
let pageToken: string | undefined;
|
||||
do {
|
||||
const page = await googleJson<{ collectionIds?: string[]; nextPageToken?: string }>(
|
||||
fetchImpl,
|
||||
token,
|
||||
`${FIRESTORE_API}/${parent}:listCollectionIds`,
|
||||
{ method: 'POST', body: { pageSize: PAGE_SIZE, ...(pageToken ? { pageToken } : {}) } },
|
||||
);
|
||||
ids.push(...(page.collectionIds ?? []));
|
||||
pageToken = page.nextPageToken;
|
||||
} while (pageToken);
|
||||
return ids;
|
||||
};
|
||||
|
||||
// Depth-first over (parent document path, collection id). `showMissing`
|
||||
// surfaces documents that exist only as parents of subcollections; they are
|
||||
// walked but not emitted, because they have no fields of their own.
|
||||
const pending: string[] = (await listCollectionIds(root)).map((id) => `${root}/${encodeURIComponent(id)}`);
|
||||
while (pending.length > 0) {
|
||||
const collection = pending.pop() as string;
|
||||
let pageToken: string | undefined;
|
||||
do {
|
||||
const query = new URLSearchParams({ pageSize: String(PAGE_SIZE), showMissing: 'true' });
|
||||
if (pageToken) {
|
||||
query.set('pageToken', pageToken);
|
||||
}
|
||||
const page = await googleJson<{ documents?: FirestoreDocument[]; nextPageToken?: string }>(
|
||||
fetchImpl,
|
||||
token,
|
||||
`${FIRESTORE_API}/${collection}?${query.toString()}`,
|
||||
);
|
||||
for (const document of page.documents ?? []) {
|
||||
if (document.createTime) {
|
||||
yield document;
|
||||
}
|
||||
for (const child of await listCollectionIds(document.name)) {
|
||||
pending.push(`${document.name}/${encodeURIComponent(child)}`);
|
||||
}
|
||||
}
|
||||
pageToken = page.nextPageToken;
|
||||
} while (pageToken);
|
||||
}
|
||||
}
|
||||
|
||||
/** One Cloud Storage object's metadata. */
|
||||
export interface StorageObjectInfo {
|
||||
name: string;
|
||||
size: number;
|
||||
contentType?: string;
|
||||
}
|
||||
|
||||
/** Lists every object in a Cloud Storage bucket. */
|
||||
export async function listStorageObjects(
|
||||
access: FirebaseAccess,
|
||||
bucket: string,
|
||||
): Promise<StorageObjectInfo[]> {
|
||||
const fetchImpl = access.fetch ?? fetch;
|
||||
const token = await resolveToken(access, fetchImpl);
|
||||
const objects: StorageObjectInfo[] = [];
|
||||
let pageToken: string | undefined;
|
||||
do {
|
||||
const query = new URLSearchParams({ maxResults: '1000', fields: 'items(name,size,contentType),nextPageToken' });
|
||||
if (pageToken) {
|
||||
query.set('pageToken', pageToken);
|
||||
}
|
||||
const page = await googleJson<{
|
||||
items?: { name: string; size: string; contentType?: string }[];
|
||||
nextPageToken?: string;
|
||||
}>(fetchImpl, token, `${STORAGE_API}/b/${encodeURIComponent(bucket)}/o?${query.toString()}`);
|
||||
for (const item of page.items ?? []) {
|
||||
if (item.name.endsWith('/')) {
|
||||
continue; // folder placeholder objects hold no data
|
||||
}
|
||||
objects.push({
|
||||
name: item.name,
|
||||
size: Number(item.size),
|
||||
...(item.contentType ? { contentType: item.contentType } : {}),
|
||||
});
|
||||
}
|
||||
pageToken = page.nextPageToken;
|
||||
} while (pageToken);
|
||||
return objects;
|
||||
}
|
||||
|
||||
export interface WriteFirebaseExportOptions extends FirebaseAccess {
|
||||
/** Destination folder; created if missing. */
|
||||
directory: string;
|
||||
/** Path to the file written by `firebase auth:export auth.json --format=JSON`. */
|
||||
authExportPath?: string;
|
||||
/** The console's password hash parameters, written to hash-config.json. */
|
||||
hashConfig?: {
|
||||
base64_signer_key: string;
|
||||
base64_salt_separator: string;
|
||||
rounds: number;
|
||||
mem_cost: number;
|
||||
};
|
||||
/** Buckets to copy, e.g. `my-app.appspot.com` or `my-app.firebasestorage.app`. */
|
||||
buckets?: string[];
|
||||
/** Progress callback. */
|
||||
onProgress?: (event: { phase: 'firestore' | 'storage'; count: number; detail?: string }) => void;
|
||||
}
|
||||
|
||||
/** Summary of what {@link writeFirebaseExport} wrote. */
|
||||
export interface FirebaseExportSummary {
|
||||
directory: string;
|
||||
documents: number;
|
||||
objects: number;
|
||||
bytes: number;
|
||||
auth: boolean;
|
||||
hashConfig: boolean;
|
||||
}
|
||||
|
||||
function safeObjectPath(name: string): boolean {
|
||||
return (
|
||||
name.length > 0 &&
|
||||
!name.startsWith('/') &&
|
||||
!name.includes('\\') &&
|
||||
!name.includes('\0') &&
|
||||
name.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a complete Firebase export folder (Node only). Place the folder in the
|
||||
* control plane's `SCRIBASE_IMPORT_EXPORTS_DIR`, then import it with
|
||||
* `scribase.imports.createFrom({ source: 'firebase', sourceExportDir: '<folder>', … })`.
|
||||
*/
|
||||
export async function writeFirebaseExport(
|
||||
options: WriteFirebaseExportOptions,
|
||||
): Promise<FirebaseExportSummary> {
|
||||
const fs = await import('node:fs/promises');
|
||||
const path = await import('node:path');
|
||||
const fetchImpl = options.fetch ?? fetch;
|
||||
const token = await resolveToken(options, fetchImpl);
|
||||
const access: FirebaseAccess = { ...options, accessToken: token };
|
||||
await fs.mkdir(options.directory, { recursive: true });
|
||||
|
||||
const firestore = await fs.open(path.join(options.directory, 'firestore.ndjson'), 'w');
|
||||
let documents = 0;
|
||||
try {
|
||||
for await (const document of exportFirestoreDocuments(access)) {
|
||||
await firestore.write(`${JSON.stringify(document)}\n`);
|
||||
documents += 1;
|
||||
if (documents % 500 === 0) {
|
||||
options.onProgress?.({ phase: 'firestore', count: documents });
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await firestore.close();
|
||||
}
|
||||
options.onProgress?.({ phase: 'firestore', count: documents });
|
||||
|
||||
if (options.authExportPath) {
|
||||
await fs.copyFile(options.authExportPath, path.join(options.directory, 'auth.json'));
|
||||
}
|
||||
if (options.hashConfig) {
|
||||
await fs.writeFile(
|
||||
path.join(options.directory, 'hash-config.json'),
|
||||
JSON.stringify({ algorithm: 'SCRYPT', ...options.hashConfig }, null, 2),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
}
|
||||
|
||||
let objects = 0;
|
||||
let bytes = 0;
|
||||
for (const bucket of options.buckets ?? []) {
|
||||
if (!/^[a-z0-9][a-z0-9._-]{1,220}[a-z0-9]$/.test(bucket) || bucket.includes('..')) {
|
||||
throw new FirebaseExportError(`"${bucket}" is not a valid Cloud Storage bucket name`);
|
||||
}
|
||||
for (const object of await listStorageObjects(access, bucket)) {
|
||||
if (!safeObjectPath(object.name)) {
|
||||
throw new FirebaseExportError(`refusing unsafe object path in bucket ${bucket}`);
|
||||
}
|
||||
const response = await fetchImpl(
|
||||
`${STORAGE_API}/b/${encodeURIComponent(bucket)}/o/${encodeURIComponent(object.name)}?alt=media`,
|
||||
{ headers: { authorization: `Bearer ${token}` } },
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new FirebaseExportError(`could not download an object from ${bucket}`, response.status);
|
||||
}
|
||||
const target = path.join(options.directory, 'storage', bucket, ...object.name.split('/'));
|
||||
await fs.mkdir(path.dirname(target), { recursive: true });
|
||||
const data = new Uint8Array(await response.arrayBuffer());
|
||||
await fs.writeFile(target, data);
|
||||
objects += 1;
|
||||
bytes += data.byteLength;
|
||||
options.onProgress?.({ phase: 'storage', count: objects, detail: `${bucket}/${object.name}` });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
directory: options.directory,
|
||||
documents,
|
||||
objects,
|
||||
bytes,
|
||||
auth: Boolean(options.authExportPath),
|
||||
hashConfig: Boolean(options.hashConfig),
|
||||
};
|
||||
}
|
||||
31
src/importers/index.ts
Normal file
31
src/importers/index.ts
Normal file
@ -0,0 +1,31 @@
|
||||
/**
|
||||
* `scribase/importers` — build export folders for `POST /v1/imports` from
|
||||
* sources that have no Postgres to connect to: Firebase (Firestore, Auth,
|
||||
* Cloud Storage) and InstantDB. Kept off the main entry because the folder
|
||||
* writers use Node's filesystem.
|
||||
*/
|
||||
|
||||
export {
|
||||
exportFirestoreDocuments,
|
||||
googleAccessToken,
|
||||
listStorageObjects,
|
||||
writeFirebaseExport,
|
||||
FirebaseExportError,
|
||||
} from './firebase.js';
|
||||
export type {
|
||||
FirebaseAccess,
|
||||
FirebaseExportSummary,
|
||||
FirestoreDocument,
|
||||
GoogleServiceAccount,
|
||||
StorageObjectInfo,
|
||||
WriteFirebaseExportOptions,
|
||||
} from './firebase.js';
|
||||
|
||||
export { exportInstantApp, writeInstantExport, InstantExportError } from './instantdb.js';
|
||||
export type {
|
||||
InstantAccess,
|
||||
InstantExportDocument,
|
||||
InstantExportOptions,
|
||||
InstantExportSummary,
|
||||
WriteInstantExportOptions,
|
||||
} from './instantdb.js';
|
||||
224
src/importers/instantdb.ts
Normal file
224
src/importers/instantdb.ts
Normal file
@ -0,0 +1,224 @@
|
||||
/**
|
||||
* Export an InstantDB app into the layout `POST /v1/imports` reads with
|
||||
* `source: 'instantdb'`:
|
||||
*
|
||||
* ```text
|
||||
* <dir>/instant-export.json { appId, exportedAt, namespaces, users, files }
|
||||
* <dir>/files/<path> the bytes of every $files entity
|
||||
* ```
|
||||
*
|
||||
* Instant's hosted cloud shuts down on 2027-08-31. This uses Instant's admin
|
||||
* HTTP API (`POST /admin/query`, the same endpoint `@instantdb/admin` calls)
|
||||
* with your app id and admin token, so no Instant SDK is required.
|
||||
*/
|
||||
|
||||
const DEFAULT_API_URL = 'https://api.instantdb.com';
|
||||
|
||||
export interface InstantAccess {
|
||||
/** The Instant app id (a UUID). */
|
||||
appId: string;
|
||||
/** The app's admin token (Instant dashboard → Admin). Never logged. */
|
||||
adminToken: string;
|
||||
/** Override for self-hosted Instant. */
|
||||
apiUrl?: string;
|
||||
/** Injected for tests; defaults to the global `fetch`. */
|
||||
fetch?: typeof fetch;
|
||||
}
|
||||
|
||||
export interface InstantExportOptions extends InstantAccess {
|
||||
/** Namespaces to export, e.g. `['todos', 'projects']`. `$users`/`$files` are always included. */
|
||||
namespaces: string[];
|
||||
/**
|
||||
* Links to flatten per namespace, e.g. `{ todos: ['owner', 'tags'] }`. Each
|
||||
* link is stored on the entity as an array of linked ids under the label.
|
||||
*/
|
||||
links?: Record<string, string[]>;
|
||||
}
|
||||
|
||||
/** The `instant-export.json` document. */
|
||||
export interface InstantExportDocument {
|
||||
appId: string;
|
||||
exportedAt: string;
|
||||
namespaces: Record<string, Record<string, unknown>[]>;
|
||||
users: Record<string, unknown>[];
|
||||
files: { id: string; path: string; url?: string; contentType?: string }[];
|
||||
}
|
||||
|
||||
/** A failure talking to Instant. The message never includes the admin token. */
|
||||
export class InstantExportError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(message: string, status = 0) {
|
||||
super(message);
|
||||
this.name = 'InstantExportError';
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
const NAMESPACE_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]{0,127}$/;
|
||||
|
||||
async function adminQuery(
|
||||
access: InstantAccess,
|
||||
query: Record<string, unknown>,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const fetchImpl = access.fetch ?? fetch;
|
||||
const base = (access.apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, '');
|
||||
const response = await fetchImpl(`${base}/admin/query?app_id=${encodeURIComponent(access.appId)}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'app-id': access.appId,
|
||||
authorization: `Bearer ${access.adminToken}`,
|
||||
},
|
||||
body: JSON.stringify({ query, 'inference?': false }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new InstantExportError(
|
||||
response.status === 401 || response.status === 403
|
||||
? 'Instant rejected the admin token for this app'
|
||||
: `Instant admin query failed (${response.status})`,
|
||||
response.status,
|
||||
);
|
||||
}
|
||||
return (await response.json()) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function entities(result: Record<string, unknown>, namespace: string): Record<string, unknown>[] {
|
||||
const value = result[namespace];
|
||||
return Array.isArray(value) ? (value as Record<string, unknown>[]) : [];
|
||||
}
|
||||
|
||||
/** Replaces nested linked entities with their ids so rows stay flat and joinable. */
|
||||
function flattenLinks(entity: Record<string, unknown>, labels: string[]): Record<string, unknown> {
|
||||
const flat: Record<string, unknown> = { ...entity };
|
||||
for (const label of labels) {
|
||||
const linked = entity[label];
|
||||
const list = Array.isArray(linked) ? linked : linked ? [linked] : [];
|
||||
flat[label] = list
|
||||
.map((item) => (item && typeof item === 'object' ? (item as { id?: unknown }).id : undefined))
|
||||
.filter((id): id is string => typeof id === 'string');
|
||||
}
|
||||
return flat;
|
||||
}
|
||||
|
||||
/** Reads every requested namespace plus `$users` and `$files`. */
|
||||
export async function exportInstantApp(options: InstantExportOptions): Promise<InstantExportDocument> {
|
||||
if (!options.appId || !options.adminToken) {
|
||||
throw new InstantExportError('appId and adminToken are required');
|
||||
}
|
||||
const namespaces: Record<string, Record<string, unknown>[]> = {};
|
||||
for (const namespace of options.namespaces) {
|
||||
if (!NAMESPACE_PATTERN.test(namespace) || namespace.startsWith('$')) {
|
||||
throw new InstantExportError(`"${namespace}" is not an exportable namespace name`);
|
||||
}
|
||||
const labels = options.links?.[namespace] ?? [];
|
||||
for (const label of labels) {
|
||||
if (!NAMESPACE_PATTERN.test(label)) {
|
||||
throw new InstantExportError(`"${label}" is not a valid link label`);
|
||||
}
|
||||
}
|
||||
const query: Record<string, unknown> = {
|
||||
[namespace]: Object.fromEntries(labels.map((label) => [label, {}])),
|
||||
};
|
||||
const result = await adminQuery(options, query);
|
||||
namespaces[namespace] = entities(result, namespace).map((entity) => flattenLinks(entity, labels));
|
||||
}
|
||||
const users = entities(await adminQuery(options, { $users: {} }), '$users');
|
||||
const files = entities(await adminQuery(options, { $files: {} }), '$files')
|
||||
.map((file) => ({
|
||||
id: String(file.id ?? ''),
|
||||
path: String(file.path ?? ''),
|
||||
...(typeof file.url === 'string' ? { url: file.url } : {}),
|
||||
...(typeof file['content-type'] === 'string' ? { contentType: file['content-type'] as string } : {}),
|
||||
}))
|
||||
.filter((file) => file.id && file.path);
|
||||
|
||||
return {
|
||||
appId: options.appId,
|
||||
exportedAt: new Date().toISOString(),
|
||||
namespaces,
|
||||
users,
|
||||
files,
|
||||
};
|
||||
}
|
||||
|
||||
export interface WriteInstantExportOptions extends InstantExportOptions {
|
||||
/** Destination folder; created if missing. */
|
||||
directory: string;
|
||||
onProgress?: (event: { phase: 'data' | 'files'; count: number; detail?: string }) => void;
|
||||
}
|
||||
|
||||
export interface InstantExportSummary {
|
||||
directory: string;
|
||||
namespaces: number;
|
||||
entities: number;
|
||||
users: number;
|
||||
files: number;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
function safePath(value: string): boolean {
|
||||
return (
|
||||
value.length > 0 &&
|
||||
!value.startsWith('/') &&
|
||||
!value.includes('\\') &&
|
||||
!value.includes('\0') &&
|
||||
value.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a complete Instant export folder, downloading every `$files` object
|
||||
* (Node only). Import it with
|
||||
* `scribase.imports.createFrom({ source: 'instantdb', sourceExportDir: '<folder>', … })`.
|
||||
*/
|
||||
export async function writeInstantExport(
|
||||
options: WriteInstantExportOptions,
|
||||
): Promise<InstantExportSummary> {
|
||||
const fs = await import('node:fs/promises');
|
||||
const path = await import('node:path');
|
||||
const fetchImpl = options.fetch ?? fetch;
|
||||
const document = await exportInstantApp(options);
|
||||
await fs.mkdir(options.directory, { recursive: true });
|
||||
|
||||
const entityCount = Object.values(document.namespaces).reduce((sum, rows) => sum + rows.length, 0);
|
||||
options.onProgress?.({ phase: 'data', count: entityCount });
|
||||
|
||||
let files = 0;
|
||||
let bytes = 0;
|
||||
for (const file of document.files) {
|
||||
if (!file.url || !safePath(file.path)) {
|
||||
continue;
|
||||
}
|
||||
const response = await fetchImpl(file.url);
|
||||
if (!response.ok) {
|
||||
throw new InstantExportError(`could not download ${file.path}`, response.status);
|
||||
}
|
||||
const data = new Uint8Array(await response.arrayBuffer());
|
||||
const target = path.join(options.directory, 'files', ...file.path.split('/'));
|
||||
await fs.mkdir(path.dirname(target), { recursive: true });
|
||||
await fs.writeFile(target, data);
|
||||
files += 1;
|
||||
bytes += data.byteLength;
|
||||
options.onProgress?.({ phase: 'files', count: files, detail: file.path });
|
||||
}
|
||||
|
||||
// Signed download URLs expire and are not needed by the importer.
|
||||
const persisted: InstantExportDocument = {
|
||||
...document,
|
||||
files: document.files.map(({ url: _url, ...rest }) => rest),
|
||||
};
|
||||
await fs.writeFile(
|
||||
path.join(options.directory, 'instant-export.json'),
|
||||
JSON.stringify(persisted, null, 2),
|
||||
);
|
||||
|
||||
return {
|
||||
directory: options.directory,
|
||||
namespaces: Object.keys(document.namespaces).length,
|
||||
entities: entityCount,
|
||||
users: document.users.length,
|
||||
files,
|
||||
bytes,
|
||||
};
|
||||
}
|
||||
298
src/index.ts
Normal file
298
src/index.ts
Normal file
@ -0,0 +1,298 @@
|
||||
/**
|
||||
* `scribase` — the typed TypeScript client for the Scribase control-plane /v1
|
||||
* API. Import the client and call typed resource methods:
|
||||
*
|
||||
* ```ts
|
||||
* import { ScribaseClient } from 'scribase';
|
||||
*
|
||||
* const scribase = new ScribaseClient({
|
||||
* baseUrl: 'https://api.scribase.com',
|
||||
* token: process.env.SCRIBASE_ACCESS_TOKEN ?? '',
|
||||
* });
|
||||
*
|
||||
* const { operation } = await scribase.environments.create({
|
||||
* organization_id: 'acme',
|
||||
* project_id: 'store',
|
||||
* environment_id: 'production',
|
||||
* kind: 'production',
|
||||
* data_mode: 'snapshot',
|
||||
* region: 'us-east',
|
||||
* postgres_major: 17,
|
||||
* });
|
||||
* await scribase.operations.wait(operation.id, 'acme');
|
||||
* ```
|
||||
*/
|
||||
|
||||
export { ScribaseClient } from './client.js';
|
||||
export type {
|
||||
ScribaseClientOptions,
|
||||
TokenProvider,
|
||||
RequestOptions,
|
||||
ApiResult,
|
||||
HttpTransport,
|
||||
AcceptedOperation,
|
||||
} from './client.js';
|
||||
|
||||
export {
|
||||
ScribaseError,
|
||||
ScribaseApiError,
|
||||
BadRequestError,
|
||||
UnauthorizedError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ConflictError,
|
||||
QuotaExceededError,
|
||||
ServiceUnavailableError,
|
||||
NetworkError,
|
||||
TimeoutError,
|
||||
OperationFailedError,
|
||||
PollTimeoutError,
|
||||
errorFromResponse,
|
||||
} from './errors.js';
|
||||
|
||||
export {
|
||||
newIdempotencyKey,
|
||||
assertIdempotencyKey,
|
||||
resolveIdempotencyKey,
|
||||
MAX_IDEMPOTENCY_KEY_LENGTH,
|
||||
MIN_IDEMPOTENCY_KEY_LENGTH,
|
||||
} from './idempotency.js';
|
||||
|
||||
export { Paginator } from './pagination.js';
|
||||
export type { Page, PageFetcher } from './pagination.js';
|
||||
|
||||
export { isFullyVerified, summarizeChecks } from './evidence.js';
|
||||
export type {
|
||||
RowCountDiff,
|
||||
ChecksumMatch,
|
||||
PolicyParity,
|
||||
LoginProof,
|
||||
VerificationCheck,
|
||||
VerificationCheckStatus,
|
||||
VerificationState,
|
||||
VerificationSummary,
|
||||
} from './evidence.js';
|
||||
|
||||
// Resource classes and their request/response types.
|
||||
export { OrganizationsResource } from './resources/organizations.js';
|
||||
export { ProjectsResource } from './resources/projects.js';
|
||||
export { EnvironmentsResource, environmentPath } from './resources/environments.js';
|
||||
export type {
|
||||
EnvironmentRef,
|
||||
ListEnvironmentsParams,
|
||||
MutationOptions,
|
||||
RenewedEnvironment,
|
||||
EnvironmentConnection,
|
||||
LogLevel,
|
||||
LogEntry,
|
||||
LogPage,
|
||||
ListLogsParams,
|
||||
} from './resources/environments.js';
|
||||
export { PreviewsResource, DEFAULT_PREVIEW_TTL_HOURS } from './resources/previews.js';
|
||||
export type { CreatePreviewRequest, ListPreviewsParams } from './resources/previews.js';
|
||||
export { BackupsResource, isRestorable } from './resources/backups.js';
|
||||
export type {
|
||||
Backup,
|
||||
BackupStatus,
|
||||
BackupObjectLocation,
|
||||
CreateBackupOptions,
|
||||
ListBackupsParams,
|
||||
ListBackupsResponse,
|
||||
} from './resources/backups.js';
|
||||
export { RestoresResource, restoreEvidence } from './resources/restores.js';
|
||||
export type {
|
||||
Restore,
|
||||
RestoreStatus,
|
||||
RestoreRequest,
|
||||
RestoreEvidence,
|
||||
AcceptedRestore,
|
||||
} from './resources/restores.js';
|
||||
export { OperationsResource, isTerminal } from './resources/operations.js';
|
||||
export type { WaitOptions } from './resources/operations.js';
|
||||
export { UsageResource, linesNearingCap } from './resources/usage.js';
|
||||
export type {
|
||||
UsageEnvelope,
|
||||
UsageLine,
|
||||
CapacityPack,
|
||||
Invoice,
|
||||
BillingOverview,
|
||||
} from './resources/usage.js';
|
||||
export { ExportResource } from './resources/export.js';
|
||||
export type {
|
||||
ExportRequest,
|
||||
ProjectExportRequest,
|
||||
ListExportsResponse,
|
||||
ExportRecord,
|
||||
ExportState,
|
||||
ExportFormat,
|
||||
ExportResult,
|
||||
ExportManifest,
|
||||
ExportManifestSignature,
|
||||
ExportDatabaseArtifact,
|
||||
ExportStorageSummary,
|
||||
ExportIntegrityClaim,
|
||||
} from './resources/export.js';
|
||||
export { MigrationsResource } from './resources/migrations.js';
|
||||
export type {
|
||||
MigrationInput,
|
||||
RunMigrationsRequest,
|
||||
RunMigrationsResult,
|
||||
MigrationPlan,
|
||||
MigrationPlanStep,
|
||||
MigrationDirection,
|
||||
MigrationLintFinding,
|
||||
MigrationLintSeverity,
|
||||
} from './resources/migrations.js';
|
||||
export { AuditResource } from './resources/audit.js';
|
||||
export type { ListAuditEventsParams } from './resources/audit.js';
|
||||
export type {
|
||||
OrganizationSummary,
|
||||
UpdateOrganizationRequest,
|
||||
ScheduledDeletion,
|
||||
NotificationSettings,
|
||||
PutNotificationSettingsRequest,
|
||||
ApiKey,
|
||||
ApiKeyScope,
|
||||
CreateApiKeyRequest,
|
||||
RevokedApiKey,
|
||||
OrgPolicy,
|
||||
McpTool,
|
||||
EventDelivery,
|
||||
EventDeliveryList,
|
||||
EventSigningSecret,
|
||||
} from './resources/organizations.js';
|
||||
export type {
|
||||
CustomDomain,
|
||||
QuotaMetric,
|
||||
ProjectQuotaOverride,
|
||||
ProjectQuotas,
|
||||
QuotaOverrides,
|
||||
} from './resources/projects.js';
|
||||
export { ImportsResource, ImportFailedError, tableParity } from './resources/imports.js';
|
||||
export type {
|
||||
AnyImportSource,
|
||||
SupabaseImportSource,
|
||||
FirebaseImportSource,
|
||||
InstantImportSource,
|
||||
FirebaseHashParameters,
|
||||
ImportLoginProof,
|
||||
ImportTableParity,
|
||||
ImportSummary,
|
||||
ImportRecord,
|
||||
ImportHistoryParams,
|
||||
ImportRequest,
|
||||
ImportSource,
|
||||
ImportDestination,
|
||||
ImportReport,
|
||||
ImportDryRun,
|
||||
ImportTally,
|
||||
ImportFinding,
|
||||
ImportCategory,
|
||||
ImportSeverity,
|
||||
ImportVerification,
|
||||
ImportVerificationCheck,
|
||||
ImportCheckStatus,
|
||||
ImportJob,
|
||||
ImportJobError,
|
||||
ImportWaitOptions,
|
||||
} from './resources/imports.js';
|
||||
export { InsightsResource } from './resources/insights.js';
|
||||
export type {
|
||||
InsightSeverity,
|
||||
InsightConfidence,
|
||||
InsightRemediation,
|
||||
InsightFinding,
|
||||
InsightsReport,
|
||||
} from './resources/insights.js';
|
||||
export { QueuesResource } from './resources/queues.js';
|
||||
export type {
|
||||
QueueSummary,
|
||||
PeekOptions,
|
||||
QueueCreated,
|
||||
SentMessage,
|
||||
QueueMessage,
|
||||
ReadMessages,
|
||||
ArchivedMessage,
|
||||
DeletedMessage,
|
||||
PurgedQueue,
|
||||
SendOptions,
|
||||
ReadOptions,
|
||||
} from './resources/queues.js';
|
||||
export { BranchesResource, branchesPath } from './resources/branches.js';
|
||||
export type {
|
||||
ProjectRef,
|
||||
BranchRecord,
|
||||
BranchList,
|
||||
RegisterBranchRequest,
|
||||
RegisteredBranch,
|
||||
SchemaObject,
|
||||
ChangedObject,
|
||||
BranchDiffRequest,
|
||||
SchemaDiff,
|
||||
BranchMergeRequest,
|
||||
MergeChange,
|
||||
MergeConflict,
|
||||
MergeResult,
|
||||
PullRequestProvider,
|
||||
LinkPullRequestRequest,
|
||||
LinkedPullRequest,
|
||||
} from './resources/branches.js';
|
||||
export { AuthResource } from './resources/auth.js';
|
||||
export type {
|
||||
AuthPolicy,
|
||||
AuthPolicies,
|
||||
AuthUsers,
|
||||
AuthUsersData,
|
||||
AuthProviders,
|
||||
AuthProvidersData,
|
||||
AuthConfig,
|
||||
AuthSettingsPatch,
|
||||
AuthProviderSettings,
|
||||
} from './resources/auth.js';
|
||||
export { StorageResource } from './resources/storage.js';
|
||||
export type { BucketList, ObjectList, ListObjectsOptions } from './resources/storage.js';
|
||||
export { FunctionsResource } from './resources/functions.js';
|
||||
export type {
|
||||
FunctionsList,
|
||||
DeployFunctionRequest,
|
||||
FunctionResult,
|
||||
} from './resources/functions.js';
|
||||
export { MetricsResource } from './resources/metrics.js';
|
||||
export type {
|
||||
MetricsReport,
|
||||
MetricSeries,
|
||||
MetricPoint,
|
||||
MetricsRange,
|
||||
} from './resources/metrics.js';
|
||||
export { RealtimeResource } from './resources/realtime.js';
|
||||
export type { Channel, ChannelList } from './resources/realtime.js';
|
||||
export { DatabaseResource } from './resources/database.js';
|
||||
export type {
|
||||
DatabaseColumn,
|
||||
DatabaseTable,
|
||||
DatabaseNote,
|
||||
DatabaseTables,
|
||||
TableAccess,
|
||||
QueryOptions,
|
||||
QueryRows,
|
||||
QueryExplain,
|
||||
QueryResult,
|
||||
GenerateTypesOptions,
|
||||
EnvironmentTypes,
|
||||
} from './resources/database.js';
|
||||
export { AccountResource } from './resources/account.js';
|
||||
export type {
|
||||
AccountProfile,
|
||||
UpdateAccountProfileRequest,
|
||||
PersonalAccessToken,
|
||||
CreatedPersonalAccessToken,
|
||||
CreatePersonalAccessTokenRequest,
|
||||
MfaFactor,
|
||||
MfaEnrollment,
|
||||
MfaChallengeResult,
|
||||
AccountSession,
|
||||
AccountSecurity,
|
||||
} from './resources/account.js';
|
||||
|
||||
// The generated wire contract.
|
||||
export type * from './types.gen.js';
|
||||
89
src/pagination.ts
Normal file
89
src/pagination.ts
Normal file
@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Pagination helpers. The /v1 contract paginates two ways:
|
||||
* - cursor pagination over an int64 sequence (`audit-events`, `after`);
|
||||
* - bounded single-page listing (`environments`, `limit` only).
|
||||
*
|
||||
* Both are wrapped by {@link Paginator}, an `AsyncIterable` that lazily walks
|
||||
* pages so a caller can `for await` an entire log without buffering it, or ask
|
||||
* for the whole thing with {@link Paginator.all}.
|
||||
*/
|
||||
|
||||
/** One fetched page: its items plus the cursor to fetch the next page, if any. */
|
||||
export interface Page<TItem, TCursor> {
|
||||
items: TItem[];
|
||||
/** Cursor for the next page, or `undefined`/`null` when the list is exhausted. */
|
||||
nextCursor: TCursor | null | undefined;
|
||||
}
|
||||
|
||||
/** Fetches a single page given the cursor returned by the previous one. */
|
||||
export type PageFetcher<TItem, TCursor> = (
|
||||
cursor: TCursor | undefined,
|
||||
) => Promise<Page<TItem, TCursor>>;
|
||||
|
||||
/**
|
||||
* Lazily iterates every item across pages. Safe to `break` out of early — the
|
||||
* next page is only requested when the current one is drained.
|
||||
*/
|
||||
export class Paginator<TItem, TCursor> implements AsyncIterable<TItem> {
|
||||
readonly #fetchPage: PageFetcher<TItem, TCursor>;
|
||||
readonly #maxItems: number | undefined;
|
||||
|
||||
constructor(
|
||||
fetchPage: PageFetcher<TItem, TCursor>,
|
||||
options?: { maxItems?: number },
|
||||
) {
|
||||
this.#fetchPage = fetchPage;
|
||||
this.#maxItems = options?.maxItems;
|
||||
}
|
||||
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<TItem> {
|
||||
let cursor: TCursor | undefined;
|
||||
let yielded = 0;
|
||||
for (;;) {
|
||||
const page = await this.#fetchPage(cursor);
|
||||
for (const item of page.items) {
|
||||
yield item;
|
||||
yielded += 1;
|
||||
if (this.#maxItems !== undefined && yielded >= this.#maxItems) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (page.nextCursor === null || page.nextCursor === undefined) {
|
||||
return;
|
||||
}
|
||||
// An empty page with a cursor would loop forever; treat it as the end.
|
||||
if (page.items.length === 0) {
|
||||
return;
|
||||
}
|
||||
cursor = page.nextCursor;
|
||||
}
|
||||
}
|
||||
|
||||
/** Walk one page at a time (each yield is an array), for batch processing. */
|
||||
async *pages(): AsyncGenerator<TItem[]> {
|
||||
let cursor: TCursor | undefined;
|
||||
for (;;) {
|
||||
const page = await this.#fetchPage(cursor);
|
||||
if (page.items.length > 0) {
|
||||
yield page.items;
|
||||
}
|
||||
if (
|
||||
page.nextCursor === null ||
|
||||
page.nextCursor === undefined ||
|
||||
page.items.length === 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
cursor = page.nextCursor;
|
||||
}
|
||||
}
|
||||
|
||||
/** Materialize every item into a single array. Respects `maxItems`. */
|
||||
async all(): Promise<TItem[]> {
|
||||
const out: TItem[] = [];
|
||||
for await (const item of this) {
|
||||
out.push(item);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
242
src/resources/account.ts
Normal file
242
src/resources/account.ts
Normal file
@ -0,0 +1,242 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { resolveIdempotencyKey } from '../idempotency.js';
|
||||
import type { MutationOptions } from './environments.js';
|
||||
|
||||
/** The caller's profile. Unset fields are `null`, not absent. */
|
||||
export interface AccountProfile {
|
||||
subject: string;
|
||||
display_name: string | null;
|
||||
full_name: string | null;
|
||||
}
|
||||
|
||||
/** Fields to change; an omitted field is left as it is. */
|
||||
export interface UpdateAccountProfileRequest {
|
||||
display_name?: string;
|
||||
full_name?: string;
|
||||
}
|
||||
|
||||
/** Personal access token metadata (never the secret). */
|
||||
export interface PersonalAccessToken {
|
||||
id: string;
|
||||
name: string;
|
||||
/** The first characters of the token, to recognize it in a list. */
|
||||
token_prefix: string;
|
||||
created_at: number | null;
|
||||
last_used_at: number | null;
|
||||
expires_at: number | null;
|
||||
revoked_at: number | null;
|
||||
}
|
||||
|
||||
/** A newly minted token. `token` is shown exactly once. */
|
||||
export interface CreatedPersonalAccessToken {
|
||||
id: string;
|
||||
name: string;
|
||||
token: string;
|
||||
token_prefix: string;
|
||||
created_at: number | null;
|
||||
expires_at: number | null;
|
||||
}
|
||||
|
||||
export interface CreatePersonalAccessTokenRequest {
|
||||
/** 1..200 characters. */
|
||||
name: string;
|
||||
/** Lifetime in whole days; omit for a non-expiring token. */
|
||||
expires_in_days?: number;
|
||||
}
|
||||
|
||||
export interface MfaFactor {
|
||||
id: string;
|
||||
type: string;
|
||||
created_at: number | null;
|
||||
/** Label chosen at enrollment, e.g. "Work phone". */
|
||||
friendly_name?: string | null;
|
||||
/** Only `verified` factors protect the account. */
|
||||
status?: 'verified' | 'unverified';
|
||||
last_used_at?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A started TOTP enrollment. `secret` and `otpauth_uri` are returned exactly
|
||||
* once: render the URI as a QR code (or show the secret for manual entry), then
|
||||
* confirm with {@link AccountResource.verifyFactor}.
|
||||
*/
|
||||
export interface MfaEnrollment {
|
||||
id: string;
|
||||
type: 'totp';
|
||||
status: 'unverified';
|
||||
friendly_name: string | null;
|
||||
secret: string;
|
||||
otpauth_uri: string;
|
||||
issuer: string;
|
||||
account_name: string;
|
||||
algorithm: 'SHA1';
|
||||
digits: number;
|
||||
period: number;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
/** Result of {@link AccountResource.challenge}: the session is stepped up. */
|
||||
export interface MfaChallengeResult {
|
||||
aal: 'aal2';
|
||||
factor_id: string;
|
||||
verified_at: number;
|
||||
expires_at: number;
|
||||
}
|
||||
|
||||
export interface AccountSession {
|
||||
id: string;
|
||||
created_at: number | null;
|
||||
last_seen_epoch_seconds: number | null;
|
||||
user_agent: string | null;
|
||||
ip: string | null;
|
||||
}
|
||||
|
||||
/** MFA and session overview. Both may be delegated to the OIDC provider. */
|
||||
export interface AccountSecurity {
|
||||
subject: string;
|
||||
mfa: { managed_externally: boolean; provider: string | null; factors: MfaFactor[] };
|
||||
sessions: { managed_externally: boolean; provider: string | null; items: AccountSession[] };
|
||||
notes: string;
|
||||
/** Control-plane mode only: which listed session made this request. */
|
||||
current_session_id?: string | null;
|
||||
/** Control-plane mode only: until when this session satisfies MFA step-up. */
|
||||
step_up_expires_at?: number | null;
|
||||
step_up_window_seconds?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Account — the caller's own identity: profile, security overview, and
|
||||
* personal access tokens. Org-less: these routes authenticate identity only.
|
||||
*/
|
||||
export class AccountResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `GET /v1/account`. */
|
||||
async get(): Promise<AccountProfile> {
|
||||
const result = await this.#http.send<AccountProfile>({ method: 'GET', path: '/v1/account' });
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `PATCH /v1/account` — change the given profile fields. */
|
||||
async update(
|
||||
body: UpdateAccountProfileRequest,
|
||||
options?: MutationOptions,
|
||||
): Promise<AccountProfile> {
|
||||
const result = await this.#http.send<AccountProfile>({
|
||||
method: 'PATCH',
|
||||
path: '/v1/account',
|
||||
body,
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `GET /v1/account/security` — MFA factors and active sessions. */
|
||||
async security(): Promise<AccountSecurity> {
|
||||
const result = await this.#http.send<AccountSecurity>({
|
||||
method: 'GET',
|
||||
path: '/v1/account/security',
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `DELETE /v1/account/security/sessions/{id}` — sign one session out. */
|
||||
async revokeSession(sessionId: string): Promise<{ id: string; removed: true }> {
|
||||
const result = await this.#http.send<{ id: string; removed: true }>({
|
||||
method: 'DELETE',
|
||||
path: `/v1/account/security/sessions/${encodeURIComponent(sessionId)}`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `DELETE /v1/account/security/factors/{id}` — unenroll a factor. Requires a
|
||||
* recent {@link challenge} while the account has a verified factor.
|
||||
*/
|
||||
async removeFactor(factorId: string): Promise<{ id: string; removed: true }> {
|
||||
const result = await this.#http.send<{ id: string; removed: true }>({
|
||||
method: 'DELETE',
|
||||
path: `/v1/account/security/factors/${encodeURIComponent(factorId)}`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `POST /v1/account/security/factors` — start TOTP (authenticator app) enrollment. */
|
||||
async enrollFactor(body: { friendly_name?: string } = {}): Promise<MfaEnrollment> {
|
||||
const result = await this.#http.send<MfaEnrollment>({
|
||||
method: 'POST',
|
||||
path: '/v1/account/security/factors',
|
||||
body: { factor_type: 'totp', ...body },
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `POST /v1/account/security/factors/{id}/verify` — confirm the first code. */
|
||||
async verifyFactor(
|
||||
factorId: string,
|
||||
body: { code: string; friendly_name?: string },
|
||||
): Promise<MfaFactor> {
|
||||
const result = await this.#http.send<MfaFactor>({
|
||||
method: 'POST',
|
||||
path: `/v1/account/security/factors/${encodeURIComponent(factorId)}/verify`,
|
||||
body,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST /v1/account/security/challenge` — verify a code to step up the current
|
||||
* session for sensitive operations (token creation, factor removal).
|
||||
*/
|
||||
async challenge(body: { code: string; factor_id?: string }): Promise<MfaChallengeResult> {
|
||||
const result = await this.#http.send<MfaChallengeResult>({
|
||||
method: 'POST',
|
||||
path: '/v1/account/security/challenge',
|
||||
body,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `GET /v1/account/tokens` — personal access tokens (metadata only). */
|
||||
async listTokens(): Promise<PersonalAccessToken[]> {
|
||||
const result = await this.#http.send<{ tokens: PersonalAccessToken[] }>({
|
||||
method: 'GET',
|
||||
path: '/v1/account/tokens',
|
||||
});
|
||||
return result.data.tokens;
|
||||
}
|
||||
|
||||
/** `POST /v1/account/tokens` — mint a token; the secret is returned once. */
|
||||
async createToken(
|
||||
body: CreatePersonalAccessTokenRequest,
|
||||
options?: MutationOptions,
|
||||
): Promise<CreatedPersonalAccessToken> {
|
||||
const result = await this.#http.send<CreatedPersonalAccessToken>({
|
||||
method: 'POST',
|
||||
path: '/v1/account/tokens',
|
||||
body,
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `DELETE /v1/account/tokens/{id}` — revoke a token. */
|
||||
async revokeToken(
|
||||
tokenId: string,
|
||||
options?: MutationOptions,
|
||||
): Promise<{ id: string; revoked: true }> {
|
||||
const result = await this.#http.send<{ id: string; revoked: true }>({
|
||||
method: 'DELETE',
|
||||
path: `/v1/account/tokens/${encodeURIComponent(tokenId)}`,
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
66
src/resources/audit.ts
Normal file
66
src/resources/audit.ts
Normal file
@ -0,0 +1,66 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { Paginator } from '../pagination.js';
|
||||
import type {
|
||||
AuditEvent,
|
||||
ListAuditEventsResponse,
|
||||
PortableIdentifier,
|
||||
} from '../types.gen.js';
|
||||
|
||||
export interface ListAuditEventsParams {
|
||||
/** Return events with a sequence strictly greater than this cursor. */
|
||||
after?: number;
|
||||
/** 1..200, default 50. */
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The organization-scoped, immutable audit log. Events carry a monotonically
|
||||
* increasing int64 `sequence` which is also the pagination cursor.
|
||||
*/
|
||||
export class AuditResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{org}/audit-events` — one page, newest cursor first. */
|
||||
async list(
|
||||
organizationId: PortableIdentifier,
|
||||
params?: ListAuditEventsParams,
|
||||
): Promise<AuditEvent[]> {
|
||||
const result = await this.#http.send<ListAuditEventsResponse>({
|
||||
method: 'GET',
|
||||
path: `/v1/organizations/${encodeURIComponent(organizationId)}/audit-events`,
|
||||
query: { after: params?.after, limit: params?.limit },
|
||||
});
|
||||
return result.data.items;
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate the entire audit log lazily, advancing the `after` cursor by the
|
||||
* highest `sequence` on each page. `for await (const ev of client.audit
|
||||
* .paginate(org))` streams events without buffering the whole log.
|
||||
*/
|
||||
paginate(
|
||||
organizationId: PortableIdentifier,
|
||||
params?: ListAuditEventsParams,
|
||||
): Paginator<AuditEvent, number> {
|
||||
const limit = params?.limit ?? 50;
|
||||
const start = params?.after;
|
||||
return new Paginator<AuditEvent, number>(async (cursor) => {
|
||||
const after = cursor ?? start;
|
||||
const items = await this.list(organizationId, {
|
||||
limit,
|
||||
...(after !== undefined ? { after } : {}),
|
||||
});
|
||||
// The next cursor is the max sequence seen; the events arrive ascending
|
||||
// by sequence, but we take the max defensively rather than assume order.
|
||||
const nextCursor =
|
||||
items.length < limit
|
||||
? undefined
|
||||
: items.reduce((max, event) => Math.max(max, event.sequence), Number.NEGATIVE_INFINITY);
|
||||
return { items, nextCursor };
|
||||
});
|
||||
}
|
||||
}
|
||||
202
src/resources/auth.ts
Normal file
202
src/resources/auth.ts
Normal file
@ -0,0 +1,202 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { resolveIdempotencyKey } from '../idempotency.js';
|
||||
import { environmentPath } from './environments.js';
|
||||
import type { EnvironmentRef } from './environments.js';
|
||||
|
||||
/** The GoTrue-shaped users document embedded under `data` by the users route. */
|
||||
export interface AuthUsersData {
|
||||
/**
|
||||
* The environment's auth users, opaque GoTrue user records. Empty when the
|
||||
* auth service is unreachable or has no users yet.
|
||||
*/
|
||||
users: unknown[];
|
||||
}
|
||||
|
||||
/** Response of {@link AuthResource.listUsers}. */
|
||||
export interface AuthUsers {
|
||||
/** The GoTrue-shaped users document. */
|
||||
data: AuthUsersData;
|
||||
/** Human-readable notes; non-empty only when the list was degraded to empty. */
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
/** The GoTrue settings document embedded under `data` by the providers route. */
|
||||
export interface AuthProvidersData {
|
||||
/**
|
||||
* Configured external providers, keyed by provider name. The value is the
|
||||
* provider's opaque configuration flag or object as GoTrue reports it.
|
||||
*/
|
||||
external: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Response of {@link AuthResource.listProviders}. */
|
||||
export interface AuthProviders {
|
||||
/** The GoTrue-shaped settings document. */
|
||||
data: AuthProvidersData;
|
||||
/** Human-readable notes; non-empty only when the settings were degraded. */
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
/** One row-level-security policy defined in the tenant database. */
|
||||
export interface AuthPolicy {
|
||||
schema: string;
|
||||
table: string;
|
||||
name: string;
|
||||
/** `SELECT`, `INSERT`, `UPDATE`, `DELETE`, or `ALL`. */
|
||||
command: string;
|
||||
roles: string[];
|
||||
permissive: boolean;
|
||||
/** The `USING` expression, or `null` when the policy has none. */
|
||||
using: string | null;
|
||||
/** The `WITH CHECK` expression, or `null` when the policy has none. */
|
||||
check: string | null;
|
||||
}
|
||||
|
||||
/** Response of {@link AuthResource.listPolicies}. */
|
||||
export interface AuthPolicies {
|
||||
policies: AuthPolicy[];
|
||||
}
|
||||
|
||||
/** One external provider in {@link AuthSettingsPatch.external}. */
|
||||
export interface AuthProviderSettings {
|
||||
enabled?: boolean;
|
||||
/**
|
||||
* The OAuth client id. For native Apple / Google `signInWithIdToken`, every
|
||||
* id the app's tokens may carry as `aud`, comma-joined (iOS bundle id; iOS,
|
||||
* web and Android Google client ids).
|
||||
*/
|
||||
client_id?: string;
|
||||
/** Client secret. Write-only: sealed and never returned; `null` removes it. */
|
||||
secret?: string | null;
|
||||
/** Skip the id-token nonce check (Google iOS SDK flows without a nonce). */
|
||||
skip_nonce_check?: boolean;
|
||||
[field: string]: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* A partial auth settings document for {@link AuthResource.updateConfig}. A
|
||||
* field set to `null` is cleared. Each field renders to one `GOTRUE_*` setting
|
||||
* of the environment's auth service.
|
||||
*/
|
||||
export interface AuthSettingsPatch {
|
||||
/**
|
||||
* Exposed schemas: the schemas the REST API serves. Unset means
|
||||
* `public, graphql_public`. List every schema an app queries with
|
||||
* `createClient(url, key, { db: { schema } })`.
|
||||
*/
|
||||
db_schemas?: string[] | null;
|
||||
site_url?: string | null;
|
||||
uri_allow_list?: string[] | null;
|
||||
jwt_exp?: number | null;
|
||||
disable_signup?: boolean | null;
|
||||
mailer_autoconfirm?: boolean | null;
|
||||
sms_autoconfirm?: boolean | null;
|
||||
external_email_enabled?: boolean | null;
|
||||
external_phone_enabled?: boolean | null;
|
||||
external_anonymous_users_enabled?: boolean | null;
|
||||
smtp_host?: string | null;
|
||||
smtp_port?: number | null;
|
||||
smtp_user?: string | null;
|
||||
/** Write-only: sealed and never returned. */
|
||||
smtp_pass?: string | null;
|
||||
smtp_admin_email?: string | null;
|
||||
smtp_sender_name?: string | null;
|
||||
external?: Record<string, AuthProviderSettings | null>;
|
||||
}
|
||||
|
||||
/** Response of {@link AuthResource.getConfig} and {@link AuthResource.updateConfig}. */
|
||||
export interface AuthConfig {
|
||||
/** The saved, non-secret settings. */
|
||||
settings: Record<string, unknown>;
|
||||
/** Which secrets are set (never their values). */
|
||||
secrets: { smtp_pass: boolean; external: Record<string, boolean> };
|
||||
supported_providers: string[];
|
||||
apply: {
|
||||
version: number;
|
||||
applied_version: number;
|
||||
status: string;
|
||||
/** True until the saved version is live on the auth service. */
|
||||
pending: boolean;
|
||||
error: string | null;
|
||||
operation_id: string | null;
|
||||
[field: string]: unknown;
|
||||
};
|
||||
/** The auth service's live `/settings`, when reachable. */
|
||||
live: unknown;
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Auth — the auth surface for an environment. Lists the environment's
|
||||
* auth users and its configured external providers via the control plane's
|
||||
* server-side proxy to the per-env GoTrue admin API. Both reads degrade softly:
|
||||
* an unreachable or not-yet-deployed auth service yields an empty document plus
|
||||
* `notes` explaining the empty state.
|
||||
*/
|
||||
export class AuthResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/auth/users` — the environment's auth users. */
|
||||
async listUsers(ref: EnvironmentRef): Promise<AuthUsers> {
|
||||
const result = await this.#http.send<AuthUsers>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/auth/users`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/auth/providers` — configured external providers. */
|
||||
async listProviders(ref: EnvironmentRef): Promise<AuthProviders> {
|
||||
const result = await this.#http.send<AuthProviders>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/auth/providers`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/auth/config` — saved settings, which secrets are set, live state. */
|
||||
async getConfig(ref: EnvironmentRef): Promise<AuthConfig> {
|
||||
const result = await this.#http.send<AuthConfig>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/auth/config`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `PATCH …/environments/{env}/auth/config` — merge settings, then deliver
|
||||
* them to the environment's auth service. Owner or admin. Poll
|
||||
* {@link getConfig} until `apply.pending` is false to know they are live.
|
||||
*/
|
||||
async updateConfig(ref: EnvironmentRef, patch: AuthSettingsPatch): Promise<AuthConfig> {
|
||||
const result = await this.#http.send<AuthConfig>({
|
||||
method: 'PATCH',
|
||||
path: `${environmentPath(ref)}/auth/config`,
|
||||
body: patch,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `POST …/environments/{env}/auth/config/apply` — re-deliver the saved settings. */
|
||||
async applyConfig(ref: EnvironmentRef, options?: { idempotencyKey?: string }): Promise<AuthConfig> {
|
||||
const result = await this.#http.send<AuthConfig>({
|
||||
method: 'POST',
|
||||
path: `${environmentPath(ref)}/auth/config/apply`,
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/auth/policies` — the database's RLS policies. */
|
||||
async listPolicies(ref: EnvironmentRef): Promise<AuthPolicy[]> {
|
||||
const result = await this.#http.send<AuthPolicies>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/auth/policies`,
|
||||
});
|
||||
return result.data.policies;
|
||||
}
|
||||
}
|
||||
199
src/resources/backups.ts
Normal file
199
src/resources/backups.ts
Normal file
@ -0,0 +1,199 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { resolveIdempotencyKey } from '../idempotency.js';
|
||||
import { environmentPath } from './environments.js';
|
||||
import type { EnvironmentRef, MutationOptions } from './environments.js';
|
||||
import type { EnvironmentReference, PortableIdentifier } from '../types.gen.js';
|
||||
|
||||
/**
|
||||
* Lifecycle of a durable backup record. Only `available` backups can be
|
||||
* restored: the control plane refuses to restore a backup that has not
|
||||
* produced verified evidence (`backup_not_restorable`).
|
||||
*/
|
||||
export type BackupStatus = 'pending' | 'available' | 'failed' | 'deleted';
|
||||
|
||||
/** Where the backup's bytes were uploaded, when object storage is configured. */
|
||||
export interface BackupObjectLocation {
|
||||
bucket: string;
|
||||
key: string;
|
||||
uploaded_at_epoch_seconds: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* One durable backup, exactly as `crates/control-api` renders it
|
||||
* (`backup_json`). Optional fields are omitted by the server — never `null` —
|
||||
* until the backup worker has produced them.
|
||||
*/
|
||||
export interface Backup {
|
||||
backup_id: PortableIdentifier;
|
||||
environment: EnvironmentReference;
|
||||
status: BackupStatus;
|
||||
/** Dump format, e.g. `pg_dump-custom`. */
|
||||
format: string;
|
||||
size_bytes: number;
|
||||
created_at_epoch_seconds: number;
|
||||
/** Lowercase hex SHA-256 of the backup artifact. */
|
||||
sha256?: string;
|
||||
object?: BackupObjectLocation;
|
||||
/** When the backup's integrity was verified; absent until verified. */
|
||||
verified_at_epoch_seconds?: number;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/backups` body. */
|
||||
export interface ListBackupsResponse {
|
||||
items: Backup[];
|
||||
}
|
||||
|
||||
export interface ListBackupsParams {
|
||||
/** 1..200, server default 50. */
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface CreateBackupOptions extends MutationOptions {
|
||||
/**
|
||||
* Portable backup identifier. The server takes it from the `Idempotency-Key`
|
||||
* header, so a retried create with the same id is a no-op rather than a new
|
||||
* row. Defaults to a freshly minted key.
|
||||
*/
|
||||
backupId?: PortableIdentifier;
|
||||
}
|
||||
|
||||
/** Status of a restore request (`restore_json`). */
|
||||
export type RestoreStatus = 'pending' | 'restored' | 'failed';
|
||||
|
||||
/**
|
||||
* A restore of a verified backup into a target environment, as the control
|
||||
* plane records it. A restore never overwrites its source: `source` is where the
|
||||
* backup was taken, `target` is where it lands. Evidence fields appear once the
|
||||
* restore worker has finished and proven the result.
|
||||
*/
|
||||
export interface Restore {
|
||||
id: PortableIdentifier;
|
||||
source: EnvironmentReference;
|
||||
target: EnvironmentReference;
|
||||
source_backup_id: PortableIdentifier;
|
||||
status: RestoreStatus;
|
||||
created_at_epoch_seconds: number;
|
||||
/** Relations present after restore (evidence). */
|
||||
relation_count?: number;
|
||||
/** Relations with row-level security enabled after restore (evidence). */
|
||||
rls_relation_count?: number;
|
||||
/** Lowercase hex SHA-256 of the restore evidence document. */
|
||||
evidence_sha256?: string;
|
||||
restored_at_epoch_seconds?: number;
|
||||
}
|
||||
|
||||
/** An accepted restore (HTTP 202) plus whether it was an idempotent replay. */
|
||||
export interface AcceptedRestore {
|
||||
restore: Restore;
|
||||
idempotencyReplayed: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Backups for one environment: list them, record a new one, read one, and
|
||||
* restore a verified backup into another environment in the same project.
|
||||
*/
|
||||
export class BackupsResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/backups` — newest first. */
|
||||
async list(ref: EnvironmentRef, params?: ListBackupsParams): Promise<Backup[]> {
|
||||
const result = await this.#http.send<ListBackupsResponse>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/backups`,
|
||||
query: { limit: params?.limit },
|
||||
});
|
||||
return result.data.items;
|
||||
}
|
||||
|
||||
/** `POST …/environments/{env}/backups` — record a new pending backup. */
|
||||
async create(ref: EnvironmentRef, options?: CreateBackupOptions): Promise<Backup> {
|
||||
const result = await this.#http.send<Backup>({
|
||||
method: 'POST',
|
||||
path: `${environmentPath(ref)}/backups`,
|
||||
body: {},
|
||||
idempotencyKey: resolveIdempotencyKey(options?.backupId ?? options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET /v1/organizations/{org}/projects/{project}/backups/{backupId}?environment={env}`
|
||||
* — one backup record. A backup id is unique only within its environment, so
|
||||
* the environment travels as a query parameter.
|
||||
*/
|
||||
async get(ref: EnvironmentRef, backupId: PortableIdentifier): Promise<Backup> {
|
||||
const result = await this.#http.send<Backup>({
|
||||
method: 'GET',
|
||||
path: backupPath(ref, backupId),
|
||||
query: { environment: ref.environmentId },
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST …/environments/{env}/backups/{backupId}/verify` — queue an isolated
|
||||
* restore of an `available` backup into a scratch database. The worker
|
||||
* records relation and RLS counts as evidence; poll {@link get} for the
|
||||
* outcome.
|
||||
*/
|
||||
async verify(
|
||||
ref: EnvironmentRef,
|
||||
backupId: PortableIdentifier,
|
||||
options?: MutationOptions,
|
||||
): Promise<{ backup_id: PortableIdentifier; verify_state: 'queued' }> {
|
||||
const result = await this.#http.send<{ backup_id: PortableIdentifier; verify_state: 'queued' }>({
|
||||
method: 'POST',
|
||||
path:
|
||||
`/v1/organizations/${encodeURIComponent(ref.organizationId)}` +
|
||||
`/projects/${encodeURIComponent(ref.projectId)}` +
|
||||
`/environments/${encodeURIComponent(ref.environmentId)}` +
|
||||
`/backups/${encodeURIComponent(backupId)}/verify`,
|
||||
body: {},
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST …/projects/{project}/backups/{backupId}/restore?environment={source}`
|
||||
* — restore an `available` backup taken in `ref` into
|
||||
* `targetEnvironmentId` (same organization and project). The server answers
|
||||
* 202 with a `pending` {@link Restore}; the restore worker fills in the
|
||||
* evidence fields when it completes.
|
||||
*/
|
||||
async restore(
|
||||
ref: EnvironmentRef,
|
||||
backupId: PortableIdentifier,
|
||||
targetEnvironmentId: PortableIdentifier,
|
||||
options?: MutationOptions,
|
||||
): Promise<AcceptedRestore> {
|
||||
const result = await this.#http.send<Restore>({
|
||||
method: 'POST',
|
||||
path: `${backupPath(ref, backupId)}/restore`,
|
||||
query: { environment: ref.environmentId },
|
||||
body: { target_environment_id: targetEnvironmentId },
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return { restore: result.data, idempotencyReplayed: result.idempotencyReplayed };
|
||||
}
|
||||
}
|
||||
|
||||
/** True when a backup can be restored (the server refuses anything else). */
|
||||
export function isRestorable(backup: Backup): boolean {
|
||||
return backup.status === 'available';
|
||||
}
|
||||
|
||||
function backupPath(ref: EnvironmentRef, backupId: PortableIdentifier): string {
|
||||
return (
|
||||
`/v1/organizations/${encodeURIComponent(ref.organizationId)}` +
|
||||
`/projects/${encodeURIComponent(ref.projectId)}` +
|
||||
`/backups/${encodeURIComponent(backupId)}`
|
||||
);
|
||||
}
|
||||
219
src/resources/branches.ts
Normal file
219
src/resources/branches.ts
Normal file
@ -0,0 +1,219 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import type { PortableIdentifier } from '../types.gen.js';
|
||||
|
||||
/** The two portable identifiers that address one project. */
|
||||
export interface ProjectRef {
|
||||
organizationId: PortableIdentifier;
|
||||
projectId: PortableIdentifier;
|
||||
}
|
||||
|
||||
/** One recorded branch, as returned by {@link BranchesResource.list}. */
|
||||
export interface BranchRecord {
|
||||
/** The branch environment identifier. */
|
||||
environment_id: string;
|
||||
/** Epoch seconds the branch was recorded. */
|
||||
created_at: number;
|
||||
/** The parent environment, when this branch forked from one. */
|
||||
base?: string;
|
||||
/** The linked pull request reference, when one is attached. */
|
||||
pull_request?: string;
|
||||
/** The rendered preview URL, when one is set. */
|
||||
preview_url?: string;
|
||||
}
|
||||
|
||||
/** The recorded branches for a project. */
|
||||
export interface BranchList {
|
||||
branches: BranchRecord[];
|
||||
}
|
||||
|
||||
/** Body for recording a branch's lineage. */
|
||||
export interface RegisterBranchRequest {
|
||||
/** The branch environment to record. */
|
||||
environment_id: string;
|
||||
/** The parent environment. Omit for a root branch (forks from an empty base). */
|
||||
base_environment_id?: string;
|
||||
}
|
||||
|
||||
/** Result of {@link BranchesResource.register}. */
|
||||
export interface RegisteredBranch {
|
||||
/** Always true on success. */
|
||||
registered: boolean;
|
||||
/** The branch environment that was recorded. */
|
||||
environment_id: string;
|
||||
/** How many schema objects were captured as the fork base. */
|
||||
fork_base_objects: number;
|
||||
}
|
||||
|
||||
/** A schema object as it appears in a diff: identity and fingerprint only. */
|
||||
export interface SchemaObject {
|
||||
/** Object kind (`view`, `materialized_view`, `index`, `function`, `trigger`). */
|
||||
kind: string;
|
||||
/** Schema the object belongs to. */
|
||||
schema: string;
|
||||
/** Object name. */
|
||||
name: string;
|
||||
/** `md5` fingerprint of the object's canonical definition. */
|
||||
fingerprint: string;
|
||||
}
|
||||
|
||||
/** A changed object in a diff: its state on each side. */
|
||||
export interface ChangedObject {
|
||||
before: SchemaObject;
|
||||
after: SchemaObject;
|
||||
}
|
||||
|
||||
/** Body for a two-way schema diff. */
|
||||
export interface BranchDiffRequest {
|
||||
/** The base branch environment. */
|
||||
base: string;
|
||||
/** The head branch environment. */
|
||||
head: string;
|
||||
}
|
||||
|
||||
/** A two-way schema diff between two branches. */
|
||||
export interface SchemaDiff {
|
||||
/** Objects present on head but not base. */
|
||||
added: SchemaObject[];
|
||||
/** Objects present on base but not head. */
|
||||
removed: SchemaObject[];
|
||||
/** Objects present on both whose definition differs. */
|
||||
changed: ChangedObject[];
|
||||
}
|
||||
|
||||
/** Body for a three-way merge of `head` into `base`. */
|
||||
export interface BranchMergeRequest {
|
||||
/** The base branch the merge applies to. */
|
||||
base: string;
|
||||
/** The head branch being merged in. */
|
||||
head: string;
|
||||
/** Apply a conflicting plan anyway. A clean plan applies without this. */
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
/** One planned change in a merge. */
|
||||
export interface MergeChange {
|
||||
/** The qualified object the change applies to. */
|
||||
object: string;
|
||||
/** The merge action (for example `apply` or `drop`). */
|
||||
action: string;
|
||||
}
|
||||
|
||||
/** One conflict in a merge plan. */
|
||||
export interface MergeConflict {
|
||||
/** The qualified object in conflict. */
|
||||
object: string;
|
||||
/** The conflict kind. */
|
||||
kind: string;
|
||||
}
|
||||
|
||||
/** The outcome of a three-way merge. */
|
||||
export interface MergeResult {
|
||||
/** Whether the plan's statements were applied to the base branch. */
|
||||
applied: boolean;
|
||||
/** Whether the plan was conflict-free. */
|
||||
clean: boolean;
|
||||
changes: MergeChange[];
|
||||
conflicts: MergeConflict[];
|
||||
}
|
||||
|
||||
/** The pull-request provider a branch is linked to. */
|
||||
export type PullRequestProvider = 'github' | 'gitlab' | 'bitbucket' | 'generic';
|
||||
|
||||
/** Body for linking a branch to a pull request. */
|
||||
export interface LinkPullRequestRequest {
|
||||
provider: PullRequestProvider;
|
||||
/** The repository the pull request lives in. */
|
||||
repository: string;
|
||||
/** The pull-request number. */
|
||||
number: number;
|
||||
/**
|
||||
* Optional preview-URL template. `{organization}`, `{project}`, and
|
||||
* `{environment}` are substituted.
|
||||
*/
|
||||
url_template?: string;
|
||||
}
|
||||
|
||||
/** The result of linking a branch to a pull request. */
|
||||
export interface LinkedPullRequest {
|
||||
/** The branch environment that was linked. */
|
||||
branch: string;
|
||||
/** The canonical pull-request reference. */
|
||||
pull_request: string;
|
||||
/** The rendered preview URL, when a template was provided. */
|
||||
preview_url?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Branches — copy-on-write database branches for a project. `register` records a
|
||||
* branch's lineage (the fork base a later `merge` needs); `diff` is a two-way
|
||||
* schema diff between any two branches; `merge` is a three-way merge; `linkPr`
|
||||
* attaches a branch to a pull request and renders its preview URL.
|
||||
*/
|
||||
export class BranchesResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `GET …/projects/{project}/branches` — the recorded branches. */
|
||||
async list(ref: ProjectRef): Promise<BranchRecord[]> {
|
||||
const result = await this.#http.send<BranchList>({
|
||||
method: 'GET',
|
||||
path: branchesPath(ref),
|
||||
});
|
||||
return result.data.branches;
|
||||
}
|
||||
|
||||
/** `POST …/branches` — record a branch's lineage and fork base. */
|
||||
async register(ref: ProjectRef, request: RegisterBranchRequest): Promise<RegisteredBranch> {
|
||||
const result = await this.#http.send<RegisteredBranch>({
|
||||
method: 'POST',
|
||||
path: branchesPath(ref),
|
||||
body: request,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `POST …/branches/diff` — a two-way schema diff between two branches. */
|
||||
async diff(ref: ProjectRef, request: BranchDiffRequest): Promise<SchemaDiff> {
|
||||
const result = await this.#http.send<SchemaDiff>({
|
||||
method: 'POST',
|
||||
path: `${branchesPath(ref)}/diff`,
|
||||
body: request,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `POST …/branches/merge` — a three-way merge of `head` into `base`. */
|
||||
async merge(ref: ProjectRef, request: BranchMergeRequest): Promise<MergeResult> {
|
||||
const result = await this.#http.send<MergeResult>({
|
||||
method: 'POST',
|
||||
path: `${branchesPath(ref)}/merge`,
|
||||
body: request,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `POST …/branches/{branch}/pr` — link a branch to a pull request. */
|
||||
async linkPullRequest(
|
||||
ref: ProjectRef,
|
||||
branch: string,
|
||||
request: LinkPullRequestRequest,
|
||||
): Promise<LinkedPullRequest> {
|
||||
const result = await this.#http.send<LinkedPullRequest>({
|
||||
method: 'POST',
|
||||
path: `${branchesPath(ref)}/${encodeURIComponent(branch)}/pr`,
|
||||
body: request,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
|
||||
/** Build the canonical branches path, encoding each portable identifier. */
|
||||
export function branchesPath(ref: ProjectRef): string {
|
||||
return (
|
||||
`/v1/organizations/${encodeURIComponent(ref.organizationId)}` +
|
||||
`/projects/${encodeURIComponent(ref.projectId)}/branches`
|
||||
);
|
||||
}
|
||||
155
src/resources/database.ts
Normal file
155
src/resources/database.ts
Normal file
@ -0,0 +1,155 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { environmentPath } from './environments.js';
|
||||
import type { EnvironmentRef } from './environments.js';
|
||||
|
||||
/** One column of an introspected table. Optional fields are omitted, never null. */
|
||||
export interface DatabaseColumn {
|
||||
name: string;
|
||||
/** SQL type, e.g. `uuid`, `text`, `timestamptz`. */
|
||||
type: string;
|
||||
nullable: boolean;
|
||||
unique: boolean;
|
||||
/** `table(column)` this column references, when it is a foreign key. */
|
||||
references?: string;
|
||||
/** SQL default expression. */
|
||||
default?: string;
|
||||
}
|
||||
|
||||
/** The access rule derived from the table's RLS policies. */
|
||||
export type TableAccess =
|
||||
| { rule: 'owner'; column: string }
|
||||
| { rule: 'public_read'; owner_column: string }
|
||||
| {
|
||||
rule: 'tenant';
|
||||
column: string;
|
||||
membership_model: string;
|
||||
membership_tenant_column: string;
|
||||
membership_user_column: string;
|
||||
}
|
||||
| { rule: 'internal' };
|
||||
|
||||
export interface DatabaseTable {
|
||||
name: string;
|
||||
access: TableAccess;
|
||||
/** True when an anonymous (anon-key) client can read rows. */
|
||||
anonymous_readable: boolean;
|
||||
columns: DatabaseColumn[];
|
||||
}
|
||||
|
||||
/** A fidelity or security note produced while introspecting. */
|
||||
export interface DatabaseNote {
|
||||
model: string;
|
||||
kind: string;
|
||||
detail: string;
|
||||
/** The introspected model cannot represent this faithfully. */
|
||||
loses_information: boolean;
|
||||
/** The note is a security finding about the database (e.g. RLS disabled). */
|
||||
security_finding: boolean;
|
||||
column?: string;
|
||||
}
|
||||
|
||||
/** Response of {@link DatabaseResource.tables}. */
|
||||
export interface DatabaseTables {
|
||||
tables: DatabaseTable[];
|
||||
notes: DatabaseNote[];
|
||||
/** True when no note loses information. */
|
||||
faithful: boolean;
|
||||
}
|
||||
|
||||
export interface QueryOptions {
|
||||
/** Row cap; the server clamps it to its own maximum. */
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/** Rows from a `SELECT`/`WITH` statement, capped at `applied_limit`. */
|
||||
export interface QueryRows<Row = Record<string, unknown>> {
|
||||
kind: 'rows';
|
||||
/** Total rows the statement produced. */
|
||||
row_count: number;
|
||||
/** Rows actually returned (≤ `applied_limit`). */
|
||||
returned: number;
|
||||
applied_limit: number;
|
||||
truncated: boolean;
|
||||
rows: Row[];
|
||||
}
|
||||
|
||||
/** The text plan of an `EXPLAIN` (never `ANALYZE`). */
|
||||
export interface QueryExplain {
|
||||
kind: 'explain';
|
||||
plan: string[];
|
||||
}
|
||||
|
||||
export type QueryResult<Row = Record<string, unknown>> = QueryRows<Row> | QueryExplain;
|
||||
|
||||
export interface GenerateTypesOptions {
|
||||
/** Schemas to include, in order. Defaults to `['public']`. */
|
||||
schemas?: readonly string[];
|
||||
}
|
||||
|
||||
/** Response of {@link DatabaseResource.generateTypes}. */
|
||||
export interface EnvironmentTypes {
|
||||
/** A TypeScript module exporting `Database`, `Json`, `Tables<>`, `Enums<>` and `Constants`. */
|
||||
types: string;
|
||||
schemas: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Database — introspection and a bounded, read-only SQL console for one
|
||||
* environment. `query` accepts a single `SELECT`, `WITH`, or `EXPLAIN`; writes
|
||||
* and DDL are rejected before execution and again by the database's read-only
|
||||
* transaction. Schema changes go through `client.migrations`, never here.
|
||||
*/
|
||||
export class DatabaseResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/database/tables` — public tables and access rules. */
|
||||
async tables(ref: EnvironmentRef): Promise<DatabaseTables> {
|
||||
const result = await this.#http.send<DatabaseTables>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/database/tables`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET …/environments/{env}/types` — supabase-js `Database` types for the
|
||||
* environment, identical to `scribase gen types`. Write `result.types` to a
|
||||
* `.ts` file and pass `Database` to `createClient<Database>()`.
|
||||
*/
|
||||
async generateTypes(ref: EnvironmentRef, options?: GenerateTypesOptions): Promise<EnvironmentTypes> {
|
||||
const schemas = options?.schemas ?? ['public'];
|
||||
if (schemas.length === 0 || schemas.some((schema) => schema.trim().length === 0 || schema.includes(','))) {
|
||||
throw new RangeError('schemas must be non-empty names without commas');
|
||||
}
|
||||
const result = await this.#http.send<EnvironmentTypes>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/types`,
|
||||
query: { schema: schemas.join(',') },
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `POST …/environments/{env}/database/query` — run one read-only statement. */
|
||||
async query<Row = Record<string, unknown>>(
|
||||
ref: EnvironmentRef,
|
||||
sql: string,
|
||||
options?: QueryOptions,
|
||||
): Promise<QueryResult<Row>> {
|
||||
if (sql.trim().length === 0) {
|
||||
throw new RangeError('query must not be empty');
|
||||
}
|
||||
const result = await this.#http.send<QueryResult<Row>>({
|
||||
method: 'POST',
|
||||
path: `${environmentPath(ref)}/database/query`,
|
||||
body: {
|
||||
query: sql,
|
||||
...(options?.limit !== undefined ? { limit: options.limit } : {}),
|
||||
},
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
232
src/resources/environments.ts
Normal file
232
src/resources/environments.ts
Normal file
@ -0,0 +1,232 @@
|
||||
import type { AcceptedOperation, HttpTransport } from '../client.js';
|
||||
import { resolveIdempotencyKey } from '../idempotency.js';
|
||||
import type {
|
||||
CreateEnvironmentRequest,
|
||||
Environment,
|
||||
EnvironmentApiKeys,
|
||||
ListEnvironmentsResponse,
|
||||
Operation,
|
||||
PortableIdentifier,
|
||||
} from '../types.gen.js';
|
||||
|
||||
/** The three portable identifiers that address one environment. */
|
||||
export interface EnvironmentRef {
|
||||
organizationId: PortableIdentifier;
|
||||
projectId: PortableIdentifier;
|
||||
environmentId: PortableIdentifier;
|
||||
}
|
||||
|
||||
export interface ListEnvironmentsParams {
|
||||
organizationId: PortableIdentifier;
|
||||
/** Narrow to a single project. */
|
||||
projectId?: PortableIdentifier;
|
||||
/** 1..200, default 100. */
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/** Options common to mutating environment calls. */
|
||||
export interface MutationOptions {
|
||||
/** Explicit idempotency key; one is minted when omitted. */
|
||||
idempotencyKey?: string;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/** Result of {@link EnvironmentsResource.renew}. */
|
||||
export interface RenewedEnvironment {
|
||||
organization_id: PortableIdentifier;
|
||||
project_id: PortableIdentifier;
|
||||
environment_id: PortableIdentifier;
|
||||
ttl_hours: number;
|
||||
last_activity_epoch_seconds: number;
|
||||
expires_at_epoch_seconds: number;
|
||||
}
|
||||
|
||||
/** Result of {@link EnvironmentsResource.connection}. Server-side only. */
|
||||
export interface EnvironmentConnection {
|
||||
connection_uri: string;
|
||||
}
|
||||
|
||||
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
||||
|
||||
/** One service log line. */
|
||||
export interface LogEntry {
|
||||
timestamp_epoch_ms: number;
|
||||
level: LogLevel;
|
||||
/** Emitting service, e.g. `postgres`, `auth`, `storage`. */
|
||||
service: string;
|
||||
message: string;
|
||||
request_id?: string;
|
||||
}
|
||||
|
||||
/** A page of log lines; pass `next_cursor` back as `cursor` for older lines. */
|
||||
export interface LogPage {
|
||||
items: LogEntry[];
|
||||
next_cursor?: string;
|
||||
}
|
||||
|
||||
export interface ListLogsParams {
|
||||
/** 1..1000, default 200. */
|
||||
limit?: number;
|
||||
level?: LogLevel;
|
||||
/** Opaque cursor from a previous page's `next_cursor`. */
|
||||
cursor?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Environments — the reconciled, provisioned instances of a project spec. Reads
|
||||
* return the full desired/observed state; every mutation returns an
|
||||
* {@link AcceptedOperation} to poll via `client.operations.wait`.
|
||||
*/
|
||||
export class EnvironmentsResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `GET /v1/environments` — the fleet view across one organization. */
|
||||
async list(params: ListEnvironmentsParams): Promise<Environment[]> {
|
||||
const result = await this.#http.send<ListEnvironmentsResponse>({
|
||||
method: 'GET',
|
||||
path: '/v1/environments',
|
||||
query: {
|
||||
organization_id: params.organizationId,
|
||||
project_id: params.projectId,
|
||||
limit: params.limit,
|
||||
},
|
||||
});
|
||||
return result.data.environments;
|
||||
}
|
||||
|
||||
/** `POST /v1/environments` — provision an environment (async). */
|
||||
async create(
|
||||
body: CreateEnvironmentRequest,
|
||||
options?: MutationOptions,
|
||||
): Promise<AcceptedOperation> {
|
||||
const result = await this.#http.send<Operation>({
|
||||
method: 'POST',
|
||||
path: '/v1/environments',
|
||||
body,
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return { operation: result.data, idempotencyReplayed: result.idempotencyReplayed };
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{org}/projects/{project}/environments/{env}`. */
|
||||
async get(ref: EnvironmentRef): Promise<Environment> {
|
||||
const result = await this.#http.send<Environment>({
|
||||
method: 'GET',
|
||||
path: environmentPath(ref),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `DELETE …/environments/{env}` — tear down (async). */
|
||||
async delete(ref: EnvironmentRef, options?: MutationOptions): Promise<AcceptedOperation> {
|
||||
const result = await this.#http.send<Operation>({
|
||||
method: 'DELETE',
|
||||
path: environmentPath(ref),
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return { operation: result.data, idempotencyReplayed: result.idempotencyReplayed };
|
||||
}
|
||||
|
||||
/** `POST …/environments/{env}/suspend` — stop compute, keep state (async). */
|
||||
async suspend(ref: EnvironmentRef, options?: MutationOptions): Promise<AcceptedOperation> {
|
||||
return this.#transition(ref, 'suspend', options);
|
||||
}
|
||||
|
||||
/** `POST …/environments/{env}/resume` — bring a suspended env back (async). */
|
||||
async resume(ref: EnvironmentRef, options?: MutationOptions): Promise<AcceptedOperation> {
|
||||
return this.#transition(ref, 'resume', options);
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST …/environments/{env}/renew` — extend an auto-expiring environment's
|
||||
* lifetime to `ttlHours` from now. Returns the new expiry window.
|
||||
*/
|
||||
async renew(
|
||||
ref: EnvironmentRef,
|
||||
ttlHours: number,
|
||||
options?: { signal?: AbortSignal },
|
||||
): Promise<RenewedEnvironment> {
|
||||
if (!Number.isInteger(ttlHours) || ttlHours < 1 || ttlHours > 65_535) {
|
||||
throw new RangeError(`ttlHours must be a positive integer, got ${ttlHours}`);
|
||||
}
|
||||
const result = await this.#http.send<RenewedEnvironment>({
|
||||
method: 'POST',
|
||||
path: `${environmentPath(ref)}/renew`,
|
||||
body: { ttl_hours: ttlHours },
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET …/environments/{env}/connection` — the tenant Postgres connection URI.
|
||||
* SERVER-SIDE ONLY: the DSN carries a database credential and must never be
|
||||
* sent to a browser or logged.
|
||||
*/
|
||||
async connection(ref: EnvironmentRef): Promise<EnvironmentConnection> {
|
||||
const result = await this.#http.send<EnvironmentConnection>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/connection`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET …/environments/{env}/api-keys` — the client keys an app needs: the API
|
||||
* URL, the anon JWT and `sb_publishable_` key (safe to ship in an app), and,
|
||||
* for members above viewer, the service_role JWT and `sb_secret_` key.
|
||||
* The last two bypass row-level security: keep them server-side.
|
||||
* `revealJwtSecret` (owners and admins) also returns the JWT signing secret,
|
||||
* for servers that verify session tokens themselves.
|
||||
*/
|
||||
async apiKeys(
|
||||
ref: EnvironmentRef,
|
||||
options?: { revealJwtSecret?: boolean },
|
||||
): Promise<EnvironmentApiKeys> {
|
||||
const result = await this.#http.send<EnvironmentApiKeys>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/api-keys`,
|
||||
...(options?.revealJwtSecret ? { query: { reveal: 'jwt_secret' } } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/logs` — most-recent service log lines, newest first. */
|
||||
async logs(ref: EnvironmentRef, params?: ListLogsParams): Promise<LogPage> {
|
||||
const result = await this.#http.send<LogPage>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/logs`,
|
||||
query: { limit: params?.limit, level: params?.level, from: params?.cursor },
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
async #transition(
|
||||
ref: EnvironmentRef,
|
||||
action: 'suspend' | 'resume',
|
||||
options?: MutationOptions,
|
||||
): Promise<AcceptedOperation> {
|
||||
const result = await this.#http.send<Operation>({
|
||||
method: 'POST',
|
||||
path: `${environmentPath(ref)}/${action}`,
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return { operation: result.data, idempotencyReplayed: result.idempotencyReplayed };
|
||||
}
|
||||
}
|
||||
|
||||
/** Build the canonical environment path, encoding each portable identifier. */
|
||||
export function environmentPath(ref: EnvironmentRef): string {
|
||||
return (
|
||||
`/v1/organizations/${encodeURIComponent(ref.organizationId)}` +
|
||||
`/projects/${encodeURIComponent(ref.projectId)}` +
|
||||
`/environments/${encodeURIComponent(ref.environmentId)}`
|
||||
);
|
||||
}
|
||||
194
src/resources/export.ts
Normal file
194
src/resources/export.ts
Normal file
@ -0,0 +1,194 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { environmentPath } from './environments.js';
|
||||
import type { EnvironmentRef } from './environments.js';
|
||||
import type {
|
||||
CreateExportRequest,
|
||||
ExportFormat,
|
||||
ExportManifest,
|
||||
ExportResult,
|
||||
PortableIdentifier,
|
||||
} from '../types.gen.js';
|
||||
import type { ProjectRef } from './branches.js';
|
||||
|
||||
/** Body of {@link ExportResource.createForProject}. */
|
||||
export interface ProjectExportRequest {
|
||||
/** The environment whose database is dumped into the bundle. */
|
||||
sourceEnvironmentId: PortableIdentifier;
|
||||
/** Defaults to `compose` on the server. */
|
||||
format?: ExportFormat;
|
||||
}
|
||||
|
||||
/** Lifecycle of a registered export bundle. */
|
||||
export type ExportState = 'requested' | 'running' | 'available' | 'failed' | 'expired';
|
||||
|
||||
/**
|
||||
* One export in the control plane's export registry
|
||||
* (`GET …/projects/{project}/exports`, `GET /v1/organizations/{org}/exports/{id}`).
|
||||
* `download_url` is an API-relative, time-limited signed link present once the
|
||||
* bundle is `available`; follow it with {@link ExportResource.download}.
|
||||
*/
|
||||
export interface ExportRecord {
|
||||
export_id: PortableIdentifier;
|
||||
project: { organization_id: PortableIdentifier; project_id: PortableIdentifier };
|
||||
source_environment_id: PortableIdentifier;
|
||||
state: ExportState | (string & {});
|
||||
format: ExportFormat | (string & {});
|
||||
include_data: boolean;
|
||||
include_storage: boolean;
|
||||
created_at_epoch_seconds: number;
|
||||
total_size_bytes: number;
|
||||
sha256: string;
|
||||
postgres_major: number;
|
||||
artifacts: unknown[];
|
||||
boots_elsewhere: boolean;
|
||||
storage_object_count: number;
|
||||
expires_at_epoch_seconds?: number;
|
||||
boot_check?: string;
|
||||
error?: string;
|
||||
download_url?: string;
|
||||
}
|
||||
|
||||
/** `GET …/projects/{project}/exports` body. */
|
||||
export interface ListExportsResponse {
|
||||
items: ExportRecord[];
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST …/environments/{env}/exports` body. The wire model is the generated
|
||||
* {@link CreateExportRequest}; this is the client-facing name for it.
|
||||
*
|
||||
* "No export path" is the competitor's structural weakness; a *runnable* export
|
||||
* is the answer, so a bundle boots from either a Docker Compose file or a
|
||||
* Kustomize overlay (see {@link ExportFormat}).
|
||||
*/
|
||||
export type ExportRequest = CreateExportRequest;
|
||||
|
||||
// The export wire models live in the generated contract, re-exported here so a
|
||||
// consumer imports one definition that mirrors `crates/export`'s manifest.
|
||||
export type {
|
||||
ExportFormat,
|
||||
ExportIntegrityClaim,
|
||||
ExportDatabaseArtifact,
|
||||
ExportStorageSummary,
|
||||
ExportManifestSignature,
|
||||
ExportManifest,
|
||||
ExportResult,
|
||||
} from '../types.gen.js';
|
||||
|
||||
/**
|
||||
* Export bundles for one environment. `create` assembles a runnable bundle and
|
||||
* a signed manifest and returns both. Backs `scribase export`.
|
||||
*/
|
||||
export class ExportResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `POST …/environments/{env}/exports` — assemble a signed, runnable bundle. */
|
||||
async create(
|
||||
ref: EnvironmentRef,
|
||||
request: ExportRequest,
|
||||
options?: { signal?: AbortSignal },
|
||||
): Promise<ExportResult> {
|
||||
const result = await this.#http.send<ExportResult>({
|
||||
method: 'POST',
|
||||
path: `${environmentPath(ref)}/exports`,
|
||||
body: request,
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST /v1/organizations/{org}/projects/{project}/export` — the
|
||||
* project-scoped form: the source environment travels in the body.
|
||||
*/
|
||||
async createForProject(
|
||||
ref: ProjectRef,
|
||||
request: ProjectExportRequest,
|
||||
options?: { signal?: AbortSignal },
|
||||
): Promise<ExportResult> {
|
||||
const result = await this.#http.send<ExportResult>({
|
||||
method: 'POST',
|
||||
path: `${projectPath(ref)}/export`,
|
||||
body: {
|
||||
source_environment_id: request.sourceEnvironmentId,
|
||||
...(request.format !== undefined ? { format: request.format } : {}),
|
||||
},
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET /v1/organizations/{org}/projects/{project}/exports` — the project's
|
||||
* registered exports, newest first, each with its state and (once available)
|
||||
* a signed `download_url`.
|
||||
*/
|
||||
async list(ref: ProjectRef): Promise<ExportRecord[]> {
|
||||
const result = await this.#http.send<ListExportsResponse>({
|
||||
method: 'GET',
|
||||
path: `${projectPath(ref)}/exports`,
|
||||
});
|
||||
return result.data.items;
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET /v1/organizations/{org}/exports/{exportId}` — one registered export,
|
||||
* with a freshly signed `download_url` when the bundle is available.
|
||||
*/
|
||||
async getManifest(
|
||||
organizationId: PortableIdentifier,
|
||||
exportId: PortableIdentifier,
|
||||
): Promise<ExportRecord> {
|
||||
const result = await this.#http.send<ExportRecord>({
|
||||
method: 'GET',
|
||||
path: `/v1/organizations/${encodeURIComponent(organizationId)}/exports/${encodeURIComponent(
|
||||
exportId,
|
||||
)}`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* The absolute-path signed download link for an available export, or `null`
|
||||
* while the bundle is still being built (or after it failed or expired).
|
||||
* Links are short-lived; call this right before downloading.
|
||||
*/
|
||||
async downloadUrl(
|
||||
organizationId: PortableIdentifier,
|
||||
exportId: PortableIdentifier,
|
||||
): Promise<string | null> {
|
||||
const record = await this.getManifest(organizationId, exportId);
|
||||
return record.state === 'available' && record.download_url ? record.download_url : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Download an available export bundle (`.tar.gz`) as a Blob by following a
|
||||
* freshly signed `GET /v1/organizations/{org}/exports/{id}/download` link.
|
||||
* Rejects when the export is not available yet.
|
||||
*/
|
||||
async download(
|
||||
organizationId: PortableIdentifier,
|
||||
exportId: PortableIdentifier,
|
||||
options?: { signal?: AbortSignal },
|
||||
): Promise<Blob> {
|
||||
const url = await this.downloadUrl(organizationId, exportId);
|
||||
if (url === null) {
|
||||
throw new Error(`export ${exportId} is not available for download yet`);
|
||||
}
|
||||
if (!this.#http.downloadBlob) {
|
||||
throw new TypeError('the configured transport cannot download binary content');
|
||||
}
|
||||
return this.#http.downloadBlob(url, options);
|
||||
}
|
||||
}
|
||||
|
||||
function projectPath(ref: ProjectRef): string {
|
||||
return (
|
||||
`/v1/organizations/${encodeURIComponent(ref.organizationId)}` +
|
||||
`/projects/${encodeURIComponent(ref.projectId)}`
|
||||
);
|
||||
}
|
||||
119
src/resources/functions.ts
Normal file
119
src/resources/functions.ts
Normal file
@ -0,0 +1,119 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import type { EnvironmentReference } from '../types.gen.js';
|
||||
import { environmentPath } from './environments.js';
|
||||
import type { EnvironmentRef } from './environments.js';
|
||||
|
||||
/** Response of {@link FunctionsResource.list}. */
|
||||
export interface FunctionsList {
|
||||
/** The environment the inventory belongs to. */
|
||||
environment: EnvironmentReference;
|
||||
/**
|
||||
* The deployed edge functions, opaque function records. Empty when the runtime
|
||||
* is unreachable or has no functions deployed yet.
|
||||
*/
|
||||
functions: unknown[];
|
||||
/**
|
||||
* Present only when the list was degraded to empty; explains why. `null` on a
|
||||
* healthy, populated response.
|
||||
*/
|
||||
notes: string | null;
|
||||
}
|
||||
|
||||
/** Body of {@link FunctionsResource.deploy}. Pass `source`, `files`, or both. */
|
||||
export interface DeployFunctionRequest {
|
||||
/** Letters, digits, hyphens, or underscores. */
|
||||
name: string;
|
||||
/** The entrypoint's source code. */
|
||||
source?: string;
|
||||
/**
|
||||
* Every module of a multi-file function, keyed by path relative to
|
||||
* `supabase/functions` (`hello/index.ts`, `_shared/cors.ts`), with
|
||||
* `entrypoint: 'hello/index.ts'`. No `..` segments.
|
||||
*/
|
||||
files?: Record<string, string>;
|
||||
/** `index.ts` (default) or `<directory>/index.ts` inside `files`. */
|
||||
entrypoint?: string;
|
||||
/** A Deno import map (`{ imports: { ... } }`). */
|
||||
import_map?: { imports?: Record<string, string>; scopes?: Record<string, Record<string, string>> };
|
||||
/**
|
||||
* Require a valid project JWT (`apikey` or `Authorization`) on every call.
|
||||
* Defaults to true on the runtime, like `verify_jwt` in `supabase/config.toml`.
|
||||
*/
|
||||
verify_jwt?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Envelope of a deploy or invoke: the function name and the runtime's reply.
|
||||
* `result` is the runtime's JSON verbatim, or its text body as a string.
|
||||
*/
|
||||
export interface FunctionResult<T = unknown> {
|
||||
function: string;
|
||||
result: T;
|
||||
}
|
||||
|
||||
const FUNCTION_NAME = /^[A-Za-z0-9_-]+$/;
|
||||
|
||||
/**
|
||||
* Functions — the edge-functions inventory for an environment. Lists
|
||||
* the environment's deployed functions and their status via the control plane's
|
||||
* server-side proxy to the per-env functions runtime admin API. The read degrades
|
||||
* softly: an unreachable or not-yet-deployed runtime yields an empty list plus a
|
||||
* `notes` string explaining the empty state.
|
||||
*/
|
||||
export class FunctionsResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/functions` — the environment's edge functions. */
|
||||
async list(ref: EnvironmentRef): Promise<FunctionsList> {
|
||||
const result = await this.#http.send<FunctionsList>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/functions`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST …/environments/{env}/functions` — deploy (create or replace) a
|
||||
* function. Unlike the list, a failed deploy surfaces as an error.
|
||||
*/
|
||||
async deploy(ref: EnvironmentRef, request: DeployFunctionRequest): Promise<FunctionResult> {
|
||||
assertFunctionName(request.name);
|
||||
if (request.source === undefined && request.files === undefined) {
|
||||
throw new RangeError('deploy needs source or files');
|
||||
}
|
||||
const result = await this.#http.send<FunctionResult>({
|
||||
method: 'POST',
|
||||
path: `${environmentPath(ref)}/functions`,
|
||||
body: request,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST …/environments/{env}/functions/{name}/invoke` — invoke a deployed
|
||||
* function with an optional JSON payload.
|
||||
*/
|
||||
async invoke<T = unknown>(
|
||||
ref: EnvironmentRef,
|
||||
name: string,
|
||||
payload: Record<string, unknown> = {},
|
||||
): Promise<FunctionResult<T>> {
|
||||
assertFunctionName(name);
|
||||
const result = await this.#http.send<FunctionResult<T>>({
|
||||
method: 'POST',
|
||||
path: `${environmentPath(ref)}/functions/${encodeURIComponent(name)}/invoke`,
|
||||
body: payload,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
|
||||
function assertFunctionName(name: string): void {
|
||||
if (!FUNCTION_NAME.test(name)) {
|
||||
throw new RangeError('function name must be letters, digits, hyphens, or underscores');
|
||||
}
|
||||
}
|
||||
354
src/resources/imports.ts
Normal file
354
src/resources/imports.ts
Normal file
@ -0,0 +1,354 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { resolveIdempotencyKey } from '../idempotency.js';
|
||||
import type {
|
||||
CreateImportRequest,
|
||||
ImportDestination,
|
||||
ImportDryRun,
|
||||
ImportJob,
|
||||
ImportReport,
|
||||
PortableIdentifier,
|
||||
} from '../types.gen.js';
|
||||
|
||||
/** One persisted import run, as listed by {@link ImportsResource.history}. */
|
||||
export interface ImportSummary {
|
||||
import_id: PortableIdentifier;
|
||||
project_id: PortableIdentifier;
|
||||
environment_id: PortableIdentifier;
|
||||
source_project_ref: string;
|
||||
dry_run: boolean;
|
||||
/** Epoch seconds the run was recorded. */
|
||||
created_at: number;
|
||||
/** Whether verification passed; absent for dry runs. */
|
||||
passed?: boolean;
|
||||
}
|
||||
|
||||
/** A persisted run in full: the summary plus the exact body the import returned. */
|
||||
export interface ImportRecord extends ImportSummary {
|
||||
report: ImportReport | ImportDryRun;
|
||||
}
|
||||
|
||||
export interface ImportHistoryParams {
|
||||
/** 1..200. */
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/** Where an import reads from. */
|
||||
export type ImportSource = 'supabase' | 'firebase' | 'instantdb';
|
||||
|
||||
/**
|
||||
* Optional login proof: `email` alone checks the user's id and password hash
|
||||
* arrived unchanged; with `password` it proves a real sign-in succeeds.
|
||||
*/
|
||||
export interface ImportLoginProof {
|
||||
email: string;
|
||||
password?: string;
|
||||
}
|
||||
|
||||
interface ImportRequestCommon {
|
||||
destination: ImportDestination;
|
||||
/** Copy storage buckets and objects (default true). */
|
||||
includeStorage?: boolean;
|
||||
verifyLogin?: ImportLoginProof;
|
||||
}
|
||||
|
||||
/** A live Supabase project (the classic request, with optional extras). */
|
||||
export interface SupabaseImportSource extends ImportRequestCommon {
|
||||
source: 'supabase';
|
||||
sourceProjectRef: string;
|
||||
sourceConnectionString: string;
|
||||
sourceServiceKey: string;
|
||||
}
|
||||
|
||||
/** Firebase's project password hash parameters. */
|
||||
export interface FirebaseHashParameters {
|
||||
base64_signer_key: string;
|
||||
base64_salt_separator: string;
|
||||
rounds: number;
|
||||
mem_cost: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Firebase export: inline text (Firestore NDJSON + `firebase auth:export`
|
||||
* JSON) or a folder written by `writeFirebaseExport` under the control plane's
|
||||
* `SCRIBASE_IMPORT_EXPORTS_DIR`.
|
||||
*/
|
||||
export interface FirebaseImportSource extends ImportRequestCommon {
|
||||
source: 'firebase';
|
||||
sourceFirebaseProjectId: string;
|
||||
sourceExport?: { firestore?: string; auth?: string };
|
||||
sourceExportDir?: string;
|
||||
sourceHashConfig?: FirebaseHashParameters;
|
||||
}
|
||||
|
||||
/** An InstantDB export: inline `instant-export.json` text or a folder. */
|
||||
export interface InstantImportSource extends ImportRequestCommon {
|
||||
source: 'instantdb';
|
||||
sourceInstantAppId: string;
|
||||
sourceExport?: { document: string };
|
||||
sourceExportDir?: string;
|
||||
}
|
||||
|
||||
export type AnyImportSource = SupabaseImportSource | FirebaseImportSource | InstantImportSource;
|
||||
|
||||
/**
|
||||
* One table, source versus Scribase, as returned in `verification.tables` of a
|
||||
* completed report: the evidence behind the row-count and checksum checks.
|
||||
*/
|
||||
export interface ImportTableParity {
|
||||
table: string;
|
||||
sourceRows: number;
|
||||
targetRows: number;
|
||||
sourceChecksum: string;
|
||||
targetChecksum: string;
|
||||
rowsMatch: boolean;
|
||||
checksumMatch: boolean;
|
||||
}
|
||||
|
||||
/** Reads the per-table parity from a report, or `[]` when it has none. */
|
||||
export function tableParity(report: ImportReport): ImportTableParity[] {
|
||||
const verification = report.verification as { tables?: unknown } | null | undefined;
|
||||
return Array.isArray(verification?.tables) ? (verification.tables as ImportTableParity[]) : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST /v1/imports` body. Credentials are sent once to run the migration and
|
||||
* are never logged or echoed back in the report.
|
||||
*
|
||||
* The wire model is the generated {@link CreateImportRequest}; this is the
|
||||
* client-facing name for it, so the request shape has one definition.
|
||||
*/
|
||||
export type ImportRequest = CreateImportRequest;
|
||||
|
||||
// The wire models this resource returns live in the generated contract, and are
|
||||
// re-exported here so `import { ImportReport } from 'scribase'` keeps working
|
||||
// without a second, hand-maintained copy that could drift from the OpenAPI.
|
||||
export type {
|
||||
ImportDestination,
|
||||
ImportFinding,
|
||||
ImportTally,
|
||||
ImportVerification,
|
||||
ImportVerificationCheck,
|
||||
ImportDryRun,
|
||||
ImportReport,
|
||||
ImportCategory,
|
||||
ImportSeverity,
|
||||
ImportCheckStatus,
|
||||
ImportJob,
|
||||
ImportJobError,
|
||||
} from '../types.gen.js';
|
||||
|
||||
/** Options for following a background import to completion. */
|
||||
export interface ImportWaitOptions {
|
||||
/** Poll interval in milliseconds (default 2000, minimum 250). */
|
||||
intervalMs?: number;
|
||||
/** Called with every progress snapshot, including the final one. */
|
||||
onProgress?: (job: ImportJob) => void;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/** Thrown by {@link ImportsResource.wait} when a background import fails. */
|
||||
export class ImportFailedError extends Error {
|
||||
readonly job: ImportJob;
|
||||
|
||||
constructor(job: ImportJob) {
|
||||
const first = job.errors[0];
|
||||
super(
|
||||
first
|
||||
? `import ${job.import_id} failed: ${first.detail}`
|
||||
: `import ${job.import_id} failed`,
|
||||
);
|
||||
this.name = 'ImportFailedError';
|
||||
this.job = job;
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (signal?.aborted) {
|
||||
reject(signal.reason ?? new Error('aborted'));
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
reject(signal?.reason ?? new Error('aborted'));
|
||||
};
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Imports: migrate a Supabase project, a Firebase export, or an InstantDB
|
||||
* export into a Scribase environment, or dry-run the plan first. Everything
|
||||
* hits `POST /v1/imports`. A dry run answers with the plan; a full run starts
|
||||
* in the background and answers with an {@link ImportJob} whose progress
|
||||
* `GET /v1/imports/{id}` reports. Backs
|
||||
* `scribase import supabase --project-ref <ref> [--dry-run]`.
|
||||
*/
|
||||
export class ImportsResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST /v1/imports` with `dryRun: false` — start the migration in the
|
||||
* background and return its {@link ImportJob} (use {@link wait} or
|
||||
* {@link run} to follow it).
|
||||
*/
|
||||
async create(
|
||||
request: Omit<ImportRequest, 'dryRun'>,
|
||||
options?: { signal?: AbortSignal; idempotencyKey?: string },
|
||||
): Promise<ImportJob> {
|
||||
return this.#start({ ...request, dryRun: false } satisfies ImportRequest, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST /v1/imports` with `dryRun: true` — plan the move and return the
|
||||
* {@link ImportDryRun} without writing anything.
|
||||
*/
|
||||
async dryRun(
|
||||
request: Omit<ImportRequest, 'dryRun'>,
|
||||
options?: { signal?: AbortSignal },
|
||||
): Promise<ImportDryRun> {
|
||||
const result = await this.#http.send<ImportDryRun>({
|
||||
method: 'POST',
|
||||
path: '/v1/imports',
|
||||
body: { ...request, dryRun: true } satisfies ImportRequest,
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST /v1/imports` for any source — Supabase, Firebase, or InstantDB —
|
||||
* started in the background. Returns the {@link ImportJob}.
|
||||
*/
|
||||
async createFrom(
|
||||
request: AnyImportSource,
|
||||
options?: { signal?: AbortSignal; idempotencyKey?: string },
|
||||
): Promise<ImportJob> {
|
||||
return this.#start({ ...request, dryRun: false }, options);
|
||||
}
|
||||
|
||||
/** `POST /v1/imports` for any source with `dryRun: true`. Writes nothing. */
|
||||
async dryRunFrom(
|
||||
request: AnyImportSource,
|
||||
options?: { signal?: AbortSignal },
|
||||
): Promise<ImportDryRun> {
|
||||
const result = await this.#http.send<ImportDryRun>({
|
||||
method: 'POST',
|
||||
path: '/v1/imports',
|
||||
body: { ...request, dryRun: true },
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET /v1/imports/{importId}` — a background run's status, phase, counts
|
||||
* moved so far, findings, errors, and (once finished) its report. Pass the
|
||||
* organization to read a run the control plane has since restarted past
|
||||
* from the import history.
|
||||
*/
|
||||
async progress(
|
||||
importId: string,
|
||||
options?: { organizationId?: PortableIdentifier; signal?: AbortSignal },
|
||||
): Promise<ImportJob> {
|
||||
const result = await this.#http.send<ImportJob>({
|
||||
method: 'GET',
|
||||
path: `/v1/imports/${encodeURIComponent(importId)}`,
|
||||
query: { organization_id: options?.organizationId },
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls {@link progress} until the run finishes. Resolves with the final
|
||||
* job (its `report` carries the fail-closed `verdict` and, in
|
||||
* `verification.tables`, per-table row counts and checksums); rejects with
|
||||
* {@link ImportFailedError} when the run failed.
|
||||
*/
|
||||
async wait(
|
||||
importId: string,
|
||||
options?: ImportWaitOptions & { organizationId?: PortableIdentifier },
|
||||
): Promise<ImportJob> {
|
||||
const interval = Math.max(250, options?.intervalMs ?? 2000);
|
||||
for (;;) {
|
||||
const job = await this.progress(importId, {
|
||||
...(options?.organizationId ? { organizationId: options.organizationId } : {}),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
options?.onProgress?.(job);
|
||||
if (job.status === 'succeeded') {
|
||||
return job;
|
||||
}
|
||||
if (job.status === 'failed') {
|
||||
throw new ImportFailedError(job);
|
||||
}
|
||||
await sleep(interval, options?.signal);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a run for any source and follows it to the end: the one-call form
|
||||
* of {@link createFrom} plus {@link wait}. Resolves with the finished report.
|
||||
*/
|
||||
async run(request: AnyImportSource, options?: ImportWaitOptions): Promise<ImportReport> {
|
||||
const started = await this.createFrom(request, options?.signal ? { signal: options.signal } : {});
|
||||
const job = await this.wait(started.import_id, {
|
||||
...options,
|
||||
organizationId: request.destination.organizationId,
|
||||
});
|
||||
if (!job.report) {
|
||||
throw new ImportFailedError(job);
|
||||
}
|
||||
return job.report;
|
||||
}
|
||||
|
||||
async #start(
|
||||
body: unknown,
|
||||
options?: { signal?: AbortSignal; idempotencyKey?: string },
|
||||
): Promise<ImportJob> {
|
||||
const result = await this.#http.send<ImportJob>({
|
||||
method: 'POST',
|
||||
path: '/v1/imports',
|
||||
body,
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{org}/imports` — persisted runs, newest first. */
|
||||
async history(
|
||||
organizationId: PortableIdentifier,
|
||||
params?: ImportHistoryParams,
|
||||
): Promise<ImportSummary[]> {
|
||||
const result = await this.#http.send<{ imports: ImportSummary[] }>({
|
||||
method: 'GET',
|
||||
path: `/v1/organizations/${encodeURIComponent(organizationId)}/imports`,
|
||||
query: { limit: params?.limit },
|
||||
});
|
||||
return result.data.imports;
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{org}/imports/{importId}` — one run in full. */
|
||||
async report(
|
||||
organizationId: PortableIdentifier,
|
||||
importId: PortableIdentifier,
|
||||
): Promise<ImportRecord> {
|
||||
const result = await this.#http.send<ImportRecord>({
|
||||
method: 'GET',
|
||||
path: `/v1/organizations/${encodeURIComponent(organizationId)}/imports/${encodeURIComponent(
|
||||
importId,
|
||||
)}`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
66
src/resources/insights.ts
Normal file
66
src/resources/insights.ts
Normal file
@ -0,0 +1,66 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { environmentPath } from './environments.js';
|
||||
import type { EnvironmentRef } from './environments.js';
|
||||
|
||||
/** How much a finding is likely to matter. */
|
||||
export type InsightSeverity = 'info' | 'warning' | 'critical';
|
||||
|
||||
/** How sure the analyzer is, given it works from statistics rather than traces. */
|
||||
export type InsightConfidence = 'certain' | 'likely' | 'possible';
|
||||
|
||||
/** A change an agent can apply without asking a human to interpret anything. */
|
||||
export interface InsightRemediation {
|
||||
/** One sentence describing the change. */
|
||||
summary: string;
|
||||
/** SQL to apply; `null` when the fix is a code change, not a schema change. */
|
||||
sql: string | null;
|
||||
/** True when applying this can block writes or rewrite a table. */
|
||||
requires_review: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* One advisor result: a machine-applicable change plus the query that proves
|
||||
* whether it worked.
|
||||
*/
|
||||
export interface InsightFinding {
|
||||
/** Stable machine identifier, e.g. `rls.per_row_subquery`. */
|
||||
code: string;
|
||||
severity: InsightSeverity;
|
||||
confidence: InsightConfidence;
|
||||
/** Short human title. */
|
||||
title: string;
|
||||
/** The object this is about, e.g. `public.documents`. */
|
||||
subject: string;
|
||||
/** Measured facts the finding was derived from. */
|
||||
evidence: Record<string, string>;
|
||||
remediation: InsightRemediation;
|
||||
/** SQL that returns the metric to re-check after applying the remediation. */
|
||||
verification: string | null;
|
||||
}
|
||||
|
||||
/** The advisor report for an environment: the analyzed findings, worst first. */
|
||||
export interface InsightsReport {
|
||||
findings: InsightFinding[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Insights — the read-only workload advisor. It collects the workload from the
|
||||
* tenant database and returns machine-actionable findings, each carrying the
|
||||
* evidence, remediation SQL, and verification SQL an agent needs.
|
||||
*/
|
||||
export class InsightsResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/insights` — the analyzed advisor findings. */
|
||||
async get(ref: EnvironmentRef): Promise<InsightsReport> {
|
||||
const result = await this.#http.send<InsightsReport>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/insights`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
76
src/resources/metrics.ts
Normal file
76
src/resources/metrics.ts
Normal file
@ -0,0 +1,76 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import type { EnvironmentReference } from '../types.gen.js';
|
||||
import { environmentPath } from './environments.js';
|
||||
import type { EnvironmentRef } from './environments.js';
|
||||
|
||||
/** One sample in a metric series. */
|
||||
export interface MetricPoint {
|
||||
/** Sample time, epoch seconds. */
|
||||
epoch_seconds: number;
|
||||
/** Measured value at the sample time. */
|
||||
value: number;
|
||||
}
|
||||
|
||||
/** One named metric and its samples over the reported range. */
|
||||
export interface MetricSeries {
|
||||
/**
|
||||
* Stable metric identifier, e.g. `requests`, `latency_ms`, `errors`,
|
||||
* `db_connections`.
|
||||
*/
|
||||
metric: string;
|
||||
/** Human-readable unit, e.g. `count` or `ms`. */
|
||||
unit: string;
|
||||
/** The samples, oldest first. Empty when no sample is available. */
|
||||
points: MetricPoint[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The time range the series cover, in epoch seconds. A single-sample series
|
||||
* reports `start === end` and a zero step.
|
||||
*/
|
||||
export interface MetricsRange {
|
||||
/** Inclusive range start. */
|
||||
start_epoch_seconds: number;
|
||||
/** Inclusive range end. */
|
||||
end_epoch_seconds: number;
|
||||
/** Step between samples; `0` for a single point-in-time snapshot. */
|
||||
step_seconds: number;
|
||||
}
|
||||
|
||||
/** Response of {@link MetricsResource.get}. */
|
||||
export interface MetricsReport {
|
||||
/** The environment the metrics belong to. */
|
||||
environment: EnvironmentReference;
|
||||
/** Where the sample came from, e.g. `postgres` or `unavailable`. */
|
||||
source: string;
|
||||
/** The time range the series cover. */
|
||||
range: MetricsRange;
|
||||
/** The metric series, one entry per tracked metric. */
|
||||
series: MetricSeries[];
|
||||
/** Human-readable note about the sample source or an empty state. */
|
||||
notes: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Metrics — the read-only operational metrics surface for an environment.
|
||||
* Returns a small time-series envelope (request volume, latency, errors, database
|
||||
* connections) via the control plane's metrics proxy. The read degrades softly:
|
||||
* an unconfigured or unreachable environment yields empty series plus a `notes`
|
||||
* string explaining the empty state.
|
||||
*/
|
||||
export class MetricsResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/metrics` — recent operational metrics. */
|
||||
async get(ref: EnvironmentRef): Promise<MetricsReport> {
|
||||
const result = await this.#http.send<MetricsReport>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/metrics`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
61
src/resources/migrations.ts
Normal file
61
src/resources/migrations.ts
Normal file
@ -0,0 +1,61 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { environmentPath } from './environments.js';
|
||||
import type { EnvironmentRef } from './environments.js';
|
||||
import type {
|
||||
MigrationInput,
|
||||
RunMigrationsRequest,
|
||||
RunMigrationsResult,
|
||||
} from '../types.gen.js';
|
||||
|
||||
// The migration wire models live in the generated contract. They are re-exported
|
||||
// here so callers keep importing them from this resource, with one definition
|
||||
// that tracks `api/openapi.yaml`.
|
||||
export type {
|
||||
MigrationInput,
|
||||
RunMigrationsRequest,
|
||||
RunMigrationsResult,
|
||||
MigrationDirection,
|
||||
MigrationPlanStep,
|
||||
MigrationPlan,
|
||||
MigrationLintSeverity,
|
||||
MigrationLintFinding,
|
||||
} from '../types.gen.js';
|
||||
|
||||
/**
|
||||
* Migrations for one environment: plan → lint → apply. A blocking lint finding
|
||||
* refuses the migration before a single statement runs. Backs `scribase migrate`.
|
||||
*/
|
||||
export class MigrationsResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `POST …/migrations` — plan, lint, and (when `apply`) run the migrations. */
|
||||
async run(
|
||||
ref: EnvironmentRef,
|
||||
request: RunMigrationsRequest,
|
||||
options?: { signal?: AbortSignal },
|
||||
): Promise<RunMigrationsResult> {
|
||||
const result = await this.#http.send<RunMigrationsResult>({
|
||||
method: 'POST',
|
||||
path: `${environmentPath(ref)}/migrations`,
|
||||
body: request,
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan-and-lint only: forces `apply: false` so nothing is executed. Use this
|
||||
* to preview the plan and surface blocking findings before committing.
|
||||
*/
|
||||
async plan(
|
||||
ref: EnvironmentRef,
|
||||
migrations: MigrationInput[],
|
||||
options?: { signal?: AbortSignal },
|
||||
): Promise<RunMigrationsResult> {
|
||||
return this.run(ref, { migrations, apply: false }, options);
|
||||
}
|
||||
}
|
||||
114
src/resources/operations.ts
Normal file
114
src/resources/operations.ts
Normal file
@ -0,0 +1,114 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { OperationFailedError, PollTimeoutError } from '../errors.js';
|
||||
import type { Operation, OperationState, PortableIdentifier } from '../types.gen.js';
|
||||
|
||||
const TERMINAL_STATES: ReadonlySet<OperationState> = new Set<OperationState>([
|
||||
'succeeded',
|
||||
'failed',
|
||||
'cancelled',
|
||||
]);
|
||||
|
||||
/** True once an operation can no longer change state. */
|
||||
export function isTerminal(state: OperationState): boolean {
|
||||
return TERMINAL_STATES.has(state);
|
||||
}
|
||||
|
||||
export interface WaitOptions {
|
||||
/** Poll interval in milliseconds. Default 1000. */
|
||||
intervalMs?: number;
|
||||
/** Give up after this many milliseconds. Default 300000 (5 min). */
|
||||
timeoutMs?: number;
|
||||
/** Invoked on every poll with the latest operation snapshot. */
|
||||
onUpdate?: (operation: Operation) => void;
|
||||
/** Throw {@link OperationFailedError} on failed/cancelled. Default true. */
|
||||
throwOnFailure?: boolean;
|
||||
/** Caller cancellation for the whole poll loop. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Asynchronous operations — the handle every mutation returns. `wait` polls
|
||||
* until the operation is terminal, so agents can turn "accepted" into "done"
|
||||
* without re-implementing backoff at each call site.
|
||||
*/
|
||||
export class OperationsResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET /v1/operations/{id}` — requires the organization scope header
|
||||
* (`X-Scribase-Organization-ID`) for membership resolution.
|
||||
*/
|
||||
async get(
|
||||
operationId: PortableIdentifier,
|
||||
organizationId: PortableIdentifier,
|
||||
): Promise<Operation> {
|
||||
const result = await this.#http.send<Operation>({
|
||||
method: 'GET',
|
||||
path: `/v1/operations/${encodeURIComponent(operationId)}`,
|
||||
organizationHeader: organizationId,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll `get` until the operation reaches a terminal state. Resolves with the
|
||||
* terminal {@link Operation}; by default throws {@link OperationFailedError}
|
||||
* when it terminates as `failed`/`cancelled`.
|
||||
*/
|
||||
async wait(
|
||||
operationId: PortableIdentifier,
|
||||
organizationId: PortableIdentifier,
|
||||
options?: WaitOptions,
|
||||
): Promise<Operation> {
|
||||
const intervalMs = options?.intervalMs ?? 1000;
|
||||
const timeoutMs = options?.timeoutMs ?? 300_000;
|
||||
const throwOnFailure = options?.throwOnFailure ?? true;
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
for (;;) {
|
||||
options?.signal?.throwIfAborted();
|
||||
const operation = await this.get(operationId, organizationId);
|
||||
options?.onUpdate?.(operation);
|
||||
|
||||
if (isTerminal(operation.state)) {
|
||||
if (
|
||||
throwOnFailure &&
|
||||
(operation.state === 'failed' || operation.state === 'cancelled')
|
||||
) {
|
||||
throw new OperationFailedError(operation);
|
||||
}
|
||||
return operation;
|
||||
}
|
||||
|
||||
if (Date.now() + intervalMs > deadline) {
|
||||
throw new PollTimeoutError(`operation ${operationId}`, timeoutMs);
|
||||
}
|
||||
await sleep(intervalMs, options?.signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
const onAbort = (): void => {
|
||||
clearTimeout(timer);
|
||||
reject(signal?.reason ?? new Error('aborted'));
|
||||
};
|
||||
if (signal) {
|
||||
if (signal.aborted) {
|
||||
clearTimeout(timer);
|
||||
reject(signal.reason ?? new Error('aborted'));
|
||||
return;
|
||||
}
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
366
src/resources/organizations.ts
Normal file
366
src/resources/organizations.ts
Normal file
@ -0,0 +1,366 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { resolveIdempotencyKey } from '../idempotency.js';
|
||||
import type { MutationOptions } from './environments.js';
|
||||
import type {
|
||||
Membership,
|
||||
Role,
|
||||
Organization,
|
||||
PortableIdentifier,
|
||||
PutMembershipRequest,
|
||||
PutOrganizationRequest,
|
||||
} from '../types.gen.js';
|
||||
|
||||
/** An organization the caller belongs to, with the caller's role in it. */
|
||||
export interface OrganizationSummary {
|
||||
organization_id: PortableIdentifier;
|
||||
display_name: string;
|
||||
role: Role;
|
||||
}
|
||||
|
||||
/** Body of {@link OrganizationsResource.update}. */
|
||||
export interface UpdateOrganizationRequest {
|
||||
/** New human-readable name, 1..200 characters. */
|
||||
display_name: string;
|
||||
}
|
||||
|
||||
/** Result of {@link OrganizationsResource.scheduleDeletion}. */
|
||||
export interface ScheduledDeletion {
|
||||
scheduled: true;
|
||||
organization_id: PortableIdentifier;
|
||||
replayed: boolean;
|
||||
}
|
||||
|
||||
export interface NotificationSettings {
|
||||
emails_enabled: boolean;
|
||||
security_alerts_enabled: boolean;
|
||||
/** Epoch seconds of the last change. */
|
||||
updated_at: number;
|
||||
webhook_url?: string;
|
||||
updated_by?: string;
|
||||
}
|
||||
|
||||
export interface PutNotificationSettingsRequest {
|
||||
emails_enabled: boolean;
|
||||
security_alerts_enabled: boolean;
|
||||
/** HTTPS endpoint for operational notifications; omit to clear. */
|
||||
webhook_url?: string;
|
||||
}
|
||||
|
||||
export type ApiKeyScope = 'read' | 'deploy' | 'admin';
|
||||
|
||||
/** A scoped agent token. The cleartext `secret` is present only on create. */
|
||||
export interface ApiKey {
|
||||
api_key_id: PortableIdentifier;
|
||||
organization_id: PortableIdentifier;
|
||||
name: string;
|
||||
scopes: ApiKeyScope[];
|
||||
created_at_epoch_seconds: number;
|
||||
last_used_epoch_seconds?: number;
|
||||
/** Returned exactly once, by {@link OrganizationsResource.createApiKey}. */
|
||||
secret?: string;
|
||||
}
|
||||
|
||||
export interface CreateApiKeyRequest {
|
||||
/** 1..120 characters. */
|
||||
name: string;
|
||||
/** Non-empty subset of `read`, `deploy`, `admin`. */
|
||||
scopes: ApiKeyScope[];
|
||||
}
|
||||
|
||||
export interface RevokedApiKey {
|
||||
api_key_id: PortableIdentifier;
|
||||
revoked: true;
|
||||
replayed: boolean;
|
||||
}
|
||||
|
||||
/** An operational governance rule (which actions need approval or are denied). */
|
||||
export interface OrgPolicy {
|
||||
policy_id: PortableIdentifier;
|
||||
action: string;
|
||||
description: string;
|
||||
effect: string;
|
||||
applies_to_kinds: string[];
|
||||
}
|
||||
|
||||
/** One MCP tool this deployment exposes to agents. */
|
||||
export interface McpTool {
|
||||
name: string;
|
||||
description?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Organizations and their memberships.
|
||||
*
|
||||
* `put` is the bootstrap: it idempotently creates an organization with the
|
||||
* caller as initial owner and requires only a verified identity, not a
|
||||
* pre-existing membership. `putMembership` idempotently sets one subject's role.
|
||||
*/
|
||||
/** One signed delivery of a control-plane event to the notification webhook. */
|
||||
export interface EventDelivery {
|
||||
delivery_id: string;
|
||||
event_id: string;
|
||||
/** `usage.threshold_reached`, `usage.cap_reached`, or `webhook.test`. */
|
||||
event_type: string;
|
||||
target_url: string;
|
||||
status: 'pending' | 'delivered' | 'failed';
|
||||
attempts: number;
|
||||
last_status_code: number | null;
|
||||
last_error: string | null;
|
||||
created_epoch_seconds: number;
|
||||
delivered_epoch_seconds: number | null;
|
||||
next_attempt_epoch_seconds: number | null;
|
||||
/** The exact signed body. */
|
||||
payload: {
|
||||
id: string;
|
||||
type: string;
|
||||
created_epoch_seconds: number;
|
||||
organization_id: string;
|
||||
project_id: string | null;
|
||||
environment_id: string | null;
|
||||
data: Record<string, unknown>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface EventDeliveryList {
|
||||
deliveries: EventDelivery[];
|
||||
webhook_configured: boolean;
|
||||
max_attempts: number;
|
||||
}
|
||||
|
||||
/** The HMAC key for `Scribase-Signature` (`t=<unix>,v1=<hex HMAC-SHA256(secret, t.body)>`). */
|
||||
export interface EventSigningSecret {
|
||||
secret: string;
|
||||
rotated: boolean;
|
||||
header: string;
|
||||
scheme: string;
|
||||
}
|
||||
|
||||
export class OrganizationsResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `PUT /v1/organizations/{id}` — create-or-confirm; caller becomes owner. */
|
||||
async put(
|
||||
organizationId: PortableIdentifier,
|
||||
body: PutOrganizationRequest,
|
||||
): Promise<Organization> {
|
||||
const result = await this.#http.send<Organization>({
|
||||
method: 'PUT',
|
||||
path: `/v1/organizations/${encodeURIComponent(organizationId)}`,
|
||||
body,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `PATCH /v1/organizations/{id}` — rename an organization (owner or admin).
|
||||
* Returns the updated organization record.
|
||||
*/
|
||||
async update(
|
||||
organizationId: PortableIdentifier,
|
||||
body: UpdateOrganizationRequest,
|
||||
options?: MutationOptions,
|
||||
): Promise<Organization> {
|
||||
const result = await this.#http.send<Organization>({
|
||||
method: 'PATCH',
|
||||
path: `/v1/organizations/${encodeURIComponent(organizationId)}`,
|
||||
body,
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{id}` — visible to a current member. */
|
||||
async get(organizationId: PortableIdentifier): Promise<Organization> {
|
||||
const result = await this.#http.send<Organization>({
|
||||
method: 'GET',
|
||||
path: `/v1/organizations/${encodeURIComponent(organizationId)}`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `PUT /v1/organizations/{id}/memberships` — add or change a subject's role. */
|
||||
async putMembership(
|
||||
organizationId: PortableIdentifier,
|
||||
body: PutMembershipRequest,
|
||||
): Promise<Membership> {
|
||||
const result = await this.#http.send<Membership>({
|
||||
method: 'PUT',
|
||||
path: `/v1/organizations/${encodeURIComponent(organizationId)}/memberships`,
|
||||
body,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations` — every organization the caller belongs to. */
|
||||
async list(): Promise<OrganizationSummary[]> {
|
||||
const result = await this.#http.send<{ items: OrganizationSummary[] }>({
|
||||
method: 'GET',
|
||||
path: '/v1/organizations',
|
||||
});
|
||||
return result.data.items;
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{id}/memberships` — every member and role. */
|
||||
async listMemberships(organizationId: PortableIdentifier): Promise<Membership[]> {
|
||||
const result = await this.#http.send<{ items: Membership[] }>({
|
||||
method: 'GET',
|
||||
path: `${orgPath(organizationId)}/memberships`,
|
||||
});
|
||||
return result.data.items;
|
||||
}
|
||||
|
||||
/**
|
||||
* `DELETE /v1/organizations/{id}` — schedule the organization for deletion
|
||||
* (owner only). Irreversible once the grace window lapses; confirm with a
|
||||
* human before calling.
|
||||
*/
|
||||
async scheduleDeletion(
|
||||
organizationId: PortableIdentifier,
|
||||
options?: MutationOptions,
|
||||
): Promise<ScheduledDeletion> {
|
||||
const result = await this.#http.send<ScheduledDeletion>({
|
||||
method: 'DELETE',
|
||||
path: orgPath(organizationId),
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{id}/notification-settings`. */
|
||||
async getNotificationSettings(organizationId: PortableIdentifier): Promise<NotificationSettings> {
|
||||
const result = await this.#http.send<NotificationSettings>({
|
||||
method: 'GET',
|
||||
path: `${orgPath(organizationId)}/notification-settings`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `PUT /v1/organizations/{id}/notification-settings` — replace preferences. */
|
||||
async putNotificationSettings(
|
||||
organizationId: PortableIdentifier,
|
||||
body: PutNotificationSettingsRequest,
|
||||
options?: MutationOptions,
|
||||
): Promise<NotificationSettings> {
|
||||
const result = await this.#http.send<NotificationSettings>({
|
||||
method: 'PUT',
|
||||
path: `${orgPath(organizationId)}/notification-settings`,
|
||||
body,
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{id}/api-keys` — active scoped agent tokens. */
|
||||
async listApiKeys(organizationId: PortableIdentifier): Promise<ApiKey[]> {
|
||||
const result = await this.#http.send<{ items: ApiKey[] }>({
|
||||
method: 'GET',
|
||||
path: `${orgPath(organizationId)}/api-keys`,
|
||||
});
|
||||
return result.data.items;
|
||||
}
|
||||
|
||||
/**
|
||||
* `POST /v1/organizations/{id}/api-keys` — mint a scoped agent token. The
|
||||
* returned `secret` is shown exactly once; store it in a secret manager.
|
||||
*/
|
||||
async createApiKey(
|
||||
organizationId: PortableIdentifier,
|
||||
body: CreateApiKeyRequest,
|
||||
options?: MutationOptions,
|
||||
): Promise<ApiKey> {
|
||||
if (body.scopes.length === 0) {
|
||||
throw new RangeError('an API key needs at least one scope');
|
||||
}
|
||||
// The control plane requires an Idempotency-Key on API key creation.
|
||||
const result = await this.#http.send<ApiKey>({
|
||||
method: 'POST',
|
||||
path: `${orgPath(organizationId)}/api-keys`,
|
||||
body,
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `DELETE /v1/organizations/{id}/api-keys/{keyId}` — revoke a token. */
|
||||
async revokeApiKey(
|
||||
organizationId: PortableIdentifier,
|
||||
apiKeyId: PortableIdentifier,
|
||||
options?: MutationOptions,
|
||||
): Promise<RevokedApiKey> {
|
||||
const result = await this.#http.send<RevokedApiKey>({
|
||||
method: 'DELETE',
|
||||
path: `${orgPath(organizationId)}/api-keys/${encodeURIComponent(apiKeyId)}`,
|
||||
idempotencyKey: resolveIdempotencyKey(options?.idempotencyKey),
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{id}/policies` — governance policies. */
|
||||
async listPolicies(organizationId: PortableIdentifier): Promise<OrgPolicy[]> {
|
||||
const result = await this.#http.send<{ items: OrgPolicy[] }>({
|
||||
method: 'GET',
|
||||
path: `${orgPath(organizationId)}/policies`,
|
||||
});
|
||||
return result.data.items;
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{id}/mcp/tools` — MCP tools this deployment exposes. */
|
||||
async listMcpTools(organizationId: PortableIdentifier): Promise<McpTool[]> {
|
||||
const result = await this.#http.send<{ tools: McpTool[] }>({
|
||||
method: 'GET',
|
||||
path: `${orgPath(organizationId)}/mcp/tools`,
|
||||
});
|
||||
return result.data.tools;
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{org}/event-deliveries` — recent usage-event deliveries. */
|
||||
async eventDeliveries(
|
||||
organizationId: PortableIdentifier,
|
||||
options?: { limit?: number },
|
||||
): Promise<EventDeliveryList> {
|
||||
const result = await this.#http.send<EventDeliveryList>({
|
||||
method: 'GET',
|
||||
path: `${orgPath(organizationId)}/event-deliveries`,
|
||||
...(options?.limit !== undefined ? { query: { limit: options.limit } } : {}),
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `POST /v1/organizations/{org}/event-deliveries/test` — send a signed `webhook.test` now. */
|
||||
async sendTestEvent(organizationId: PortableIdentifier): Promise<EventDelivery> {
|
||||
const result = await this.#http.send<EventDelivery>({
|
||||
method: 'POST',
|
||||
path: `${orgPath(organizationId)}/event-deliveries/test`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reveal (`GET`, created on first use) or rotate (`POST`) the secret that
|
||||
* signs event deliveries. Owner or admin.
|
||||
*/
|
||||
async eventSigningSecret(
|
||||
organizationId: PortableIdentifier,
|
||||
options?: { rotate?: boolean },
|
||||
): Promise<EventSigningSecret> {
|
||||
const result = await this.#http.send<EventSigningSecret>({
|
||||
method: options?.rotate === true ? 'POST' : 'GET',
|
||||
path: `${orgPath(organizationId)}/notification-settings/signing-secret`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
|
||||
function orgPath(organizationId: PortableIdentifier): string {
|
||||
return `/v1/organizations/${encodeURIComponent(organizationId)}`;
|
||||
}
|
||||
100
src/resources/previews.ts
Normal file
100
src/resources/previews.ts
Normal file
@ -0,0 +1,100 @@
|
||||
import type { AcceptedOperation, HttpTransport } from '../client.js';
|
||||
import { EnvironmentsResource } from './environments.js';
|
||||
import type { EnvironmentRef, MutationOptions, RenewedEnvironment } from './environments.js';
|
||||
import type { DataMode, Environment, PortableIdentifier } from '../types.gen.js';
|
||||
|
||||
/** Default lifetime for a preview when the caller does not set one (24h). */
|
||||
export const DEFAULT_PREVIEW_TTL_HOURS = 24;
|
||||
|
||||
export interface CreatePreviewRequest {
|
||||
organizationId: PortableIdentifier;
|
||||
projectId: PortableIdentifier;
|
||||
environmentId: PortableIdentifier;
|
||||
region: PortableIdentifier;
|
||||
postgres_major: 17;
|
||||
/** How much data the preview carries. Defaults to `sanitized`. */
|
||||
dataMode?: DataMode;
|
||||
/** 1..720 hours; defaults to {@link DEFAULT_PREVIEW_TTL_HOURS}. */
|
||||
ttlHours?: number;
|
||||
}
|
||||
|
||||
export interface ListPreviewsParams {
|
||||
organizationId: PortableIdentifier;
|
||||
projectId?: PortableIdentifier;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Previews — ephemeral, TTL-swept environments (`kind: 'preview'`), the
|
||||
* per-branch answer to metered branching. This resource is a typed convenience
|
||||
* over the environment contract: it forces `kind: 'preview'`, defaults the data
|
||||
* mode to `sanitized` (never raw production data by accident), and always sets a
|
||||
* TTL so a forgotten preview cannot run forever.
|
||||
*/
|
||||
export class PreviewsResource {
|
||||
readonly #environments: EnvironmentsResource;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#environments = new EnvironmentsResource(http);
|
||||
}
|
||||
|
||||
/** Provision a preview environment (async). */
|
||||
async create(
|
||||
request: CreatePreviewRequest,
|
||||
options?: MutationOptions,
|
||||
): Promise<AcceptedOperation> {
|
||||
return this.#environments.create(
|
||||
{
|
||||
organization_id: request.organizationId,
|
||||
project_id: request.projectId,
|
||||
environment_id: request.environmentId,
|
||||
kind: 'preview',
|
||||
data_mode: request.dataMode ?? 'sanitized',
|
||||
region: request.region,
|
||||
postgres_major: request.postgres_major,
|
||||
ttl_hours: request.ttlHours ?? DEFAULT_PREVIEW_TTL_HOURS,
|
||||
},
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
/** List only the preview environments in the organization/project. */
|
||||
async list(params: ListPreviewsParams): Promise<Environment[]> {
|
||||
const environments = await this.#environments.list({
|
||||
organizationId: params.organizationId,
|
||||
...(params.projectId !== undefined ? { projectId: params.projectId } : {}),
|
||||
...(params.limit !== undefined ? { limit: params.limit } : {}),
|
||||
});
|
||||
return environments.filter((environment) => environment.kind === 'preview');
|
||||
}
|
||||
|
||||
/** Fetch a single preview environment. */
|
||||
async get(ref: EnvironmentRef): Promise<Environment> {
|
||||
return this.#environments.get(ref);
|
||||
}
|
||||
|
||||
/** Delete a preview immediately rather than waiting for TTL sweep (async). */
|
||||
async delete(ref: EnvironmentRef, options?: MutationOptions): Promise<AcceptedOperation> {
|
||||
return this.#environments.delete(ref, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extend a preview's lifetime to `ttlHours` (default
|
||||
* {@link DEFAULT_PREVIEW_TTL_HOURS}) from now, so an active branch is not
|
||||
* swept mid-review.
|
||||
*/
|
||||
async renew(
|
||||
ref: EnvironmentRef,
|
||||
ttlHours: number = DEFAULT_PREVIEW_TTL_HOURS,
|
||||
): Promise<RenewedEnvironment> {
|
||||
return this.#environments.renew(ref, ttlHours);
|
||||
}
|
||||
|
||||
/** Remaining lifetime in seconds, or `null` if the preview has no expiry set. */
|
||||
remainingSeconds(environment: Environment, now: number = Date.now()): number | null {
|
||||
if (environment.expires_at_epoch_seconds === undefined) {
|
||||
return null;
|
||||
}
|
||||
return Math.max(0, environment.expires_at_epoch_seconds - Math.floor(now / 1000));
|
||||
}
|
||||
}
|
||||
169
src/resources/projects.ts
Normal file
169
src/resources/projects.ts
Normal file
@ -0,0 +1,169 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import type {
|
||||
PortableIdentifier,
|
||||
Project,
|
||||
PutProjectRequest,
|
||||
} from '../types.gen.js';
|
||||
|
||||
/** A custom domain bound to one of the project's environments. */
|
||||
export interface CustomDomain {
|
||||
domain: string;
|
||||
environment_id: PortableIdentifier;
|
||||
verified: boolean;
|
||||
certificate_state: string;
|
||||
/** The DNS TXT record to publish, while verification is pending. */
|
||||
verification_txt_record?: string;
|
||||
}
|
||||
|
||||
/** Metrics a per-project override can cap. */
|
||||
export type QuotaMetric =
|
||||
| 'database_gb'
|
||||
| 'storage_gb'
|
||||
| 'backup_gb'
|
||||
| 'preview_environments'
|
||||
| 'egress_gb'
|
||||
| 'compute_hours'
|
||||
| 'rows'
|
||||
| 'function_invocations';
|
||||
|
||||
export interface ProjectQuotaOverride {
|
||||
metric: QuotaMetric;
|
||||
label: string;
|
||||
unit: string;
|
||||
/** Hard cap applied to every environment of the project. */
|
||||
cap: number;
|
||||
updated_by: string;
|
||||
updated_at_epoch_seconds: number;
|
||||
}
|
||||
|
||||
/** Response of {@link ProjectsResource.getQuotas} / {@link ProjectsResource.setQuotas}. */
|
||||
export interface ProjectQuotas {
|
||||
organization_id: string;
|
||||
project_id: string;
|
||||
overrides: ProjectQuotaOverride[];
|
||||
/** Every metric that can be capped, with its label and unit. */
|
||||
metrics: Array<{ metric: QuotaMetric; label: string; unit: string }>;
|
||||
/** Fraction of a cap at which `usage.threshold_reached` fires (0.8). */
|
||||
threshold: number;
|
||||
}
|
||||
|
||||
/** `metric -> cap`, or `null` to remove that override. */
|
||||
export type QuotaOverrides = Partial<Record<QuotaMetric, number | null>>;
|
||||
|
||||
/**
|
||||
* Projects — the immutable specification (region + Postgres major) that
|
||||
* environments are provisioned against. `put` is idempotent create; the spec
|
||||
* cannot be mutated afterwards, only re-confirmed.
|
||||
*/
|
||||
export class ProjectsResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `PUT /v1/organizations/{org}/projects/{project}` — idempotent create. */
|
||||
async put(
|
||||
organizationId: PortableIdentifier,
|
||||
projectId: PortableIdentifier,
|
||||
body: PutProjectRequest,
|
||||
): Promise<Project> {
|
||||
const result = await this.#http.send<Project>({
|
||||
method: 'PUT',
|
||||
path: `/v1/organizations/${encodeURIComponent(
|
||||
organizationId,
|
||||
)}/projects/${encodeURIComponent(projectId)}`,
|
||||
body,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{org}/projects/{project}`. */
|
||||
async get(
|
||||
organizationId: PortableIdentifier,
|
||||
projectId: PortableIdentifier,
|
||||
): Promise<Project> {
|
||||
const result = await this.#http.send<Project>({
|
||||
method: 'GET',
|
||||
path: `/v1/organizations/${encodeURIComponent(
|
||||
organizationId,
|
||||
)}/projects/${encodeURIComponent(projectId)}`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{org}/projects` — every project the caller may read. */
|
||||
async list(organizationId: PortableIdentifier): Promise<Project[]> {
|
||||
const result = await this.#http.send<{ items: Project[] }>({
|
||||
method: 'GET',
|
||||
path: `/v1/organizations/${encodeURIComponent(organizationId)}/projects`,
|
||||
});
|
||||
return result.data.items;
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{org}/projects/{project}/domains` — custom domains. */
|
||||
async listDomains(
|
||||
organizationId: PortableIdentifier,
|
||||
projectId: PortableIdentifier,
|
||||
): Promise<CustomDomain[]> {
|
||||
const result = await this.#http.send<{ items: CustomDomain[] }>({
|
||||
method: 'GET',
|
||||
path: `/v1/organizations/${encodeURIComponent(
|
||||
organizationId,
|
||||
)}/projects/${encodeURIComponent(projectId)}/domains`,
|
||||
});
|
||||
return result.data.items;
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET /v1/organizations/{org}/projects/{project}/quotas` — per-project hard
|
||||
* caps. The effective cap on each environment is the lower of the plan cap
|
||||
* and the override; `rows` and `function_invocations` are capped only here.
|
||||
*/
|
||||
async getQuotas(
|
||||
organizationId: PortableIdentifier,
|
||||
projectId: PortableIdentifier,
|
||||
): Promise<ProjectQuotas> {
|
||||
const result = await this.#http.send<ProjectQuotas>({
|
||||
method: 'GET',
|
||||
path: `/v1/organizations/${encodeURIComponent(
|
||||
organizationId,
|
||||
)}/projects/${encodeURIComponent(projectId)}/quotas`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `PUT /v1/organizations/{org}/projects/{project}/quotas` — set (number) or
|
||||
* clear (`null`) overrides. Owner or admin. Takes effect immediately, and
|
||||
* `usage.threshold_reached` / `usage.cap_reached` events are signed and sent
|
||||
* to the organization's notification webhook when a tenant crosses them.
|
||||
*
|
||||
* ```ts
|
||||
* await client.projects.setQuotas('agency', 'customer-42', { storage_gb: 5, rows: 100_000 });
|
||||
* ```
|
||||
*/
|
||||
async setQuotas(
|
||||
organizationId: PortableIdentifier,
|
||||
projectId: PortableIdentifier,
|
||||
overrides: QuotaOverrides,
|
||||
): Promise<ProjectQuotas> {
|
||||
const entries = Object.entries(overrides);
|
||||
if (entries.length === 0) {
|
||||
throw new RangeError('overrides must name at least one metric');
|
||||
}
|
||||
for (const [metric, cap] of entries) {
|
||||
if (cap !== null && (typeof cap !== 'number' || !Number.isFinite(cap) || cap < 0)) {
|
||||
throw new RangeError(`${metric} must be a non-negative number or null`);
|
||||
}
|
||||
}
|
||||
const result = await this.#http.send<ProjectQuotas>({
|
||||
method: 'PUT',
|
||||
path: `/v1/organizations/${encodeURIComponent(
|
||||
organizationId,
|
||||
)}/projects/${encodeURIComponent(projectId)}/quotas`,
|
||||
body: { overrides },
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
173
src/resources/queues.ts
Normal file
173
src/resources/queues.ts
Normal file
@ -0,0 +1,173 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { environmentPath } from './environments.js';
|
||||
import type { EnvironmentRef } from './environments.js';
|
||||
|
||||
/** Result of {@link QueuesResource.create}. */
|
||||
export interface QueueCreated {
|
||||
/** True once the queue is present (creation is idempotent). */
|
||||
created: boolean;
|
||||
}
|
||||
|
||||
/** Result of {@link QueuesResource.send}. */
|
||||
export interface SentMessage {
|
||||
/** The queue-assigned message identifier. */
|
||||
msg_id: number;
|
||||
}
|
||||
|
||||
/** A leased message returned by {@link QueuesResource.read}. */
|
||||
export interface QueueMessage {
|
||||
/** The queue-assigned identifier. */
|
||||
msg_id: number;
|
||||
/** How many times the message has been read (delivery attempts). */
|
||||
read_ct: number;
|
||||
/** When the message was first enqueued, in Unix seconds. */
|
||||
enqueued_at: number;
|
||||
/** The current visibility deadline, in Unix seconds. */
|
||||
vt: number;
|
||||
/** The opaque message payload. */
|
||||
message: unknown;
|
||||
}
|
||||
|
||||
/** Result of {@link QueuesResource.read}: the leased batch, possibly empty. */
|
||||
export interface ReadMessages {
|
||||
messages: QueueMessage[];
|
||||
}
|
||||
|
||||
/** Result of {@link QueuesResource.archive}. */
|
||||
export interface ArchivedMessage {
|
||||
/** True when the message existed and was archived. */
|
||||
archived: boolean;
|
||||
}
|
||||
|
||||
/** Result of {@link QueuesResource.delete}. */
|
||||
export interface DeletedMessage {
|
||||
/** True when the message existed and was deleted. */
|
||||
deleted: boolean;
|
||||
}
|
||||
|
||||
/** Result of {@link QueuesResource.purge}. */
|
||||
export interface PurgedQueue {
|
||||
/** The number of messages removed. */
|
||||
purged: number;
|
||||
}
|
||||
|
||||
/** Options for {@link QueuesResource.send}. */
|
||||
export interface SendOptions {
|
||||
/** Delay before the message becomes visible, in seconds. */
|
||||
delaySeconds?: number;
|
||||
}
|
||||
|
||||
/** Options for {@link QueuesResource.read}. */
|
||||
export interface ReadOptions {
|
||||
/** How long each leased message stays invisible, in seconds (default 30). */
|
||||
visibilityTimeoutSeconds?: number;
|
||||
/** How many messages to lease (default 1). */
|
||||
quantity?: number;
|
||||
}
|
||||
|
||||
/** One queue and its current depth, from {@link QueuesResource.list}. */
|
||||
export interface QueueSummary {
|
||||
queue_name: string;
|
||||
/** Messages currently on the queue. */
|
||||
length: number;
|
||||
/** Present when the queue is non-empty. */
|
||||
oldest_msg_id?: number;
|
||||
newest_msg_id?: number;
|
||||
}
|
||||
|
||||
/** Options for {@link QueuesResource.peek}. */
|
||||
export interface PeekOptions {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queues — pgmq message queues under an environment. Every verb is a single
|
||||
* `POST …/queues/{queue}` whose body carries the action; the queue name is the
|
||||
* only value in the path. Message bodies are opaque JSON, sent as-is and
|
||||
* returned verbatim.
|
||||
*/
|
||||
export class QueuesResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/queues` — every queue with its depth. Read-only. */
|
||||
async list(ref: EnvironmentRef): Promise<QueueSummary[]> {
|
||||
const result = await this.#http.send<{ queues: QueueSummary[] }>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/queues`,
|
||||
});
|
||||
return result.data.queues;
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET …/queues/{queue}/messages` — look at messages without leasing them
|
||||
* (visibility and read count are unchanged).
|
||||
*/
|
||||
async peek(ref: EnvironmentRef, queue: string, options?: PeekOptions): Promise<QueueMessage[]> {
|
||||
const result = await this.#http.send<ReadMessages>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/queues/${encodeURIComponent(queue)}/messages`,
|
||||
query: { limit: options?.limit, offset: options?.offset },
|
||||
});
|
||||
return result.data.messages;
|
||||
}
|
||||
|
||||
/** `POST …/queues/{queue}` `create` — create the queue if it does not exist. */
|
||||
async create(ref: EnvironmentRef, queue: string): Promise<QueueCreated> {
|
||||
return this.#post<QueueCreated>(ref, queue, { action: 'create' });
|
||||
}
|
||||
|
||||
/** `POST …/queues/{queue}` `send` — enqueue one message. */
|
||||
async send(
|
||||
ref: EnvironmentRef,
|
||||
queue: string,
|
||||
message: unknown,
|
||||
options?: SendOptions,
|
||||
): Promise<SentMessage> {
|
||||
return this.#post<SentMessage>(ref, queue, {
|
||||
action: 'send',
|
||||
message,
|
||||
...(options?.delaySeconds !== undefined ? { delay_seconds: options.delaySeconds } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
/** `POST …/queues/{queue}` `read` — lease up to `quantity` visible messages. */
|
||||
async read(ref: EnvironmentRef, queue: string, options?: ReadOptions): Promise<QueueMessage[]> {
|
||||
const result = await this.#post<ReadMessages>(ref, queue, {
|
||||
action: 'read',
|
||||
...(options?.visibilityTimeoutSeconds !== undefined
|
||||
? { visibility_timeout_seconds: options.visibilityTimeoutSeconds }
|
||||
: {}),
|
||||
...(options?.quantity !== undefined ? { quantity: options.quantity } : {}),
|
||||
});
|
||||
return result.messages;
|
||||
}
|
||||
|
||||
/** `POST …/queues/{queue}` `archive` — move one message to the archive table. */
|
||||
async archive(ref: EnvironmentRef, queue: string, msgId: number): Promise<ArchivedMessage> {
|
||||
return this.#post<ArchivedMessage>(ref, queue, { action: 'archive', msg_id: msgId });
|
||||
}
|
||||
|
||||
/** `POST …/queues/{queue}` `delete` — delete one message outright. */
|
||||
async delete(ref: EnvironmentRef, queue: string, msgId: number): Promise<DeletedMessage> {
|
||||
return this.#post<DeletedMessage>(ref, queue, { action: 'delete', msg_id: msgId });
|
||||
}
|
||||
|
||||
/** `POST …/queues/{queue}` `purge` — delete every message on the queue. */
|
||||
async purge(ref: EnvironmentRef, queue: string): Promise<PurgedQueue> {
|
||||
return this.#post<PurgedQueue>(ref, queue, { action: 'purge' });
|
||||
}
|
||||
|
||||
async #post<T>(ref: EnvironmentRef, queue: string, body: Record<string, unknown>): Promise<T> {
|
||||
const result = await this.#http.send<T>({
|
||||
method: 'POST',
|
||||
path: `${environmentPath(ref)}/queues/${encodeURIComponent(queue)}`,
|
||||
body,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
50
src/resources/realtime.ts
Normal file
50
src/resources/realtime.ts
Normal file
@ -0,0 +1,50 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { environmentPath } from './environments.js';
|
||||
import type { EnvironmentRef } from './environments.js';
|
||||
|
||||
/** One active Realtime channel and its live subscription count. */
|
||||
export interface Channel {
|
||||
/** The channel's display name, e.g. `room:1`. */
|
||||
name: string;
|
||||
/** The channel's live subscription count. */
|
||||
subscriptions: number;
|
||||
}
|
||||
|
||||
/** Response of {@link RealtimeResource.channels}. */
|
||||
export interface ChannelList {
|
||||
/** The active channels. Empty when Realtime is unreachable or idle. */
|
||||
channels: Channel[];
|
||||
/** Number of active channels (the length of `channels`). */
|
||||
total_channels: number;
|
||||
/** Sum of subscriptions across all active channels. */
|
||||
total_subscriptions: number;
|
||||
/**
|
||||
* Present only when the list was degraded to empty; explains why. `null` on a
|
||||
* healthy response.
|
||||
*/
|
||||
notes: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Realtime — the read-only Realtime surface for an environment. Lists the
|
||||
* environment Realtime service's active channels and their subscription counts
|
||||
* via the control plane's Realtime proxy. The read degrades softly: an undeployed,
|
||||
* unreachable, or unconfigured Realtime service yields a valid empty document
|
||||
* whose `notes` field explains the empty state.
|
||||
*/
|
||||
export class RealtimeResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/realtime/channels` — the active channels. */
|
||||
async channels(ref: EnvironmentRef): Promise<ChannelList> {
|
||||
const result = await this.#http.send<ChannelList>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/realtime/channels`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
137
src/resources/restores.ts
Normal file
137
src/resources/restores.ts
Normal file
@ -0,0 +1,137 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { BackupsResource } from './backups.js';
|
||||
import type { AcceptedRestore, Restore } from './backups.js';
|
||||
import { environmentPath } from './environments.js';
|
||||
import type { EnvironmentRef, MutationOptions } from './environments.js';
|
||||
import type { PortableIdentifier } from '../types.gen.js';
|
||||
|
||||
export type { Restore, RestoreStatus, AcceptedRestore } from './backups.js';
|
||||
|
||||
/** Body of {@link RestoresResource.start}. */
|
||||
export interface RestoreRequest {
|
||||
/** The `available` backup to restore, taken in the source environment. */
|
||||
backupId: PortableIdentifier;
|
||||
/**
|
||||
* The environment the backup lands in (same organization and project). A
|
||||
* restore never overwrites its source in place; restore into a fresh preview
|
||||
* to prove a backup, and into production only with human approval.
|
||||
*/
|
||||
targetEnvironmentId: PortableIdentifier;
|
||||
}
|
||||
|
||||
/** The evidence a finished restore carries, when the worker has produced it. */
|
||||
export interface RestoreEvidence {
|
||||
relationCount: number;
|
||||
rlsRelationCount: number;
|
||||
evidenceSha256: string;
|
||||
restoredAtEpochSeconds: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verified restore — the restore half of the backup contract. This is a
|
||||
* restore-shaped convenience over
|
||||
* `POST …/projects/{project}/backups/{backup}/restore?environment={source}`
|
||||
* (the same call as {@link BackupsResource.restore}), so callers can think in
|
||||
* "restore X into Y" terms.
|
||||
*/
|
||||
export class RestoresResource {
|
||||
readonly #http: HttpTransport;
|
||||
readonly #backups: BackupsResource;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
this.#backups = new BackupsResource(http);
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET …/environments/{env}/restores` — every restore whose target is `target`,
|
||||
* newest first (up to 200).
|
||||
*/
|
||||
async list(target: EnvironmentRef): Promise<Restore[]> {
|
||||
const result = await this.#http.send<{ items: Restore[] }>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(target)}/restores`,
|
||||
});
|
||||
return result.data.items;
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET …/environments/{env}/restores/{restoreId}` — one restore into `target`.
|
||||
* Poll this until `status` leaves `pending`, then read {@link restoreEvidence}.
|
||||
*/
|
||||
async get(target: EnvironmentRef, restoreId: PortableIdentifier): Promise<Restore> {
|
||||
const result = await this.#http.send<Restore>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(target)}/restores/${encodeURIComponent(restoreId)}`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll {@link get} until the restore is no longer `pending`, then resolve with
|
||||
* the final record. Rejects when `timeoutMs` elapses first.
|
||||
*/
|
||||
async waitForCompletion(
|
||||
target: EnvironmentRef,
|
||||
restoreId: PortableIdentifier,
|
||||
options: { intervalMs?: number; timeoutMs?: number; signal?: AbortSignal } = {},
|
||||
): Promise<Restore> {
|
||||
const interval = options.intervalMs ?? 2000;
|
||||
const deadline = Date.now() + (options.timeoutMs ?? 30 * 60 * 1000);
|
||||
for (;;) {
|
||||
if (options.signal?.aborted) {
|
||||
throw options.signal.reason ?? new Error('restore wait aborted');
|
||||
}
|
||||
const restore = await this.get(target, restoreId);
|
||||
if (restore.status !== 'pending') {
|
||||
return restore;
|
||||
}
|
||||
if (Date.now() + interval > deadline) {
|
||||
throw new Error(`restore ${restoreId} did not finish before the timeout`);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, interval));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Request a restore of `request.backupId` (taken in `source`) into
|
||||
* `request.targetEnvironmentId`. Resolves with the accepted, `pending`
|
||||
* {@link Restore}.
|
||||
*/
|
||||
async start(
|
||||
source: EnvironmentRef,
|
||||
request: RestoreRequest,
|
||||
options?: MutationOptions,
|
||||
): Promise<AcceptedRestore> {
|
||||
return this.#backups.restore(
|
||||
source,
|
||||
request.backupId,
|
||||
request.targetEnvironmentId,
|
||||
options,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The restore's proof, or `null` while it is still pending or when it failed.
|
||||
* A restore counts as proven only when it reached `restored` with every
|
||||
* evidence field present — the same contract the control plane enforces before
|
||||
* it will mark a record `restored`.
|
||||
*/
|
||||
export function restoreEvidence(restore: Restore): RestoreEvidence | null {
|
||||
if (
|
||||
restore.status !== 'restored' ||
|
||||
restore.relation_count === undefined ||
|
||||
restore.rls_relation_count === undefined ||
|
||||
restore.evidence_sha256 === undefined ||
|
||||
restore.restored_at_epoch_seconds === undefined
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
relationCount: restore.relation_count,
|
||||
rlsRelationCount: restore.rls_relation_count,
|
||||
evidenceSha256: restore.evidence_sha256,
|
||||
restoredAtEpochSeconds: restore.restored_at_epoch_seconds,
|
||||
};
|
||||
}
|
||||
79
src/resources/storage.ts
Normal file
79
src/resources/storage.ts
Normal file
@ -0,0 +1,79 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { environmentPath } from './environments.js';
|
||||
import type { EnvironmentRef } from './environments.js';
|
||||
|
||||
/** Response of {@link StorageResource.listBuckets}. */
|
||||
export interface BucketList {
|
||||
/**
|
||||
* The environment's Storage buckets, opaque Storage bucket records. Empty when
|
||||
* Storage is unreachable or has no buckets yet.
|
||||
*/
|
||||
buckets: unknown[];
|
||||
/** Present only when the list was degraded to empty; explains why. */
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
/** Response of {@link StorageResource.listObjects}. */
|
||||
export interface ObjectList {
|
||||
/** The bucket the objects were listed from. */
|
||||
bucket: string;
|
||||
/**
|
||||
* The bucket's objects, opaque Storage object records. Empty when Storage is
|
||||
* unreachable or the bucket has no objects under the prefix.
|
||||
*/
|
||||
objects: unknown[];
|
||||
/** Present only when the list was degraded to empty; explains why. */
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
/** Optional paging controls for {@link StorageResource.listObjects}. */
|
||||
export interface ListObjectsOptions {
|
||||
/** Restrict the listing to object keys under this prefix. */
|
||||
prefix?: string;
|
||||
/** Cap the number of objects returned. The service bounds this server-side. */
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Storage — the read-only Storage surface for an environment. Lists the
|
||||
* environment's buckets and the objects in one bucket via the control plane's
|
||||
* server-side proxy to the per-env Storage admin API. Both reads degrade softly:
|
||||
* an undeployed or unreachable Storage service yields an empty list plus a
|
||||
* `notes` string explaining the empty state.
|
||||
*/
|
||||
export class StorageResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/storage/buckets` — the environment's buckets. */
|
||||
async listBuckets(ref: EnvironmentRef): Promise<BucketList> {
|
||||
const result = await this.#http.send<BucketList>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/storage/buckets`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET …/environments/{env}/storage/buckets/{bucket}/objects` — the objects in
|
||||
* one bucket, optionally filtered by `prefix` and capped by `limit`.
|
||||
*/
|
||||
async listObjects(
|
||||
ref: EnvironmentRef,
|
||||
bucket: string,
|
||||
options?: ListObjectsOptions,
|
||||
): Promise<ObjectList> {
|
||||
const result = await this.#http.send<ObjectList>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/storage/buckets/${encodeURIComponent(bucket)}/objects`,
|
||||
query: {
|
||||
...(options?.prefix !== undefined ? { prefix: options.prefix } : {}),
|
||||
...(options?.limit !== undefined ? { limit: options.limit } : {}),
|
||||
},
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
115
src/resources/usage.ts
Normal file
115
src/resources/usage.ts
Normal file
@ -0,0 +1,115 @@
|
||||
import type { HttpTransport } from '../client.js';
|
||||
import { environmentPath } from './environments.js';
|
||||
import type { EnvironmentRef } from './environments.js';
|
||||
import type { EnvironmentReference, PortableIdentifier } from '../types.gen.js';
|
||||
|
||||
/**
|
||||
* One capped resource line of the envelope. The product rule is binding: we
|
||||
* never bill a metered line item. Exceeding `cap` is enforced, not charged; the
|
||||
* customer buys a {@link CapacityPack} to raise it.
|
||||
*/
|
||||
export interface UsageLine {
|
||||
/** Stable metric key, e.g. `database_bytes`. */
|
||||
metric: string;
|
||||
/** Human label for the console. */
|
||||
label: string;
|
||||
used: number;
|
||||
/** Amount included in the flat price. */
|
||||
included: number;
|
||||
/** Hard ceiling (included plus any active packs). */
|
||||
cap: number;
|
||||
unit: string;
|
||||
}
|
||||
|
||||
/** A discrete capacity increment attached to the environment's plan. */
|
||||
export interface CapacityPack {
|
||||
pack_id: PortableIdentifier;
|
||||
metric: string;
|
||||
label: string;
|
||||
/** How much one pack adds to the metric's cap. */
|
||||
amount: number;
|
||||
unit: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The flat-price usage envelope for one environment, exactly as
|
||||
* `crates/control-api/src/adapters/usage.rs` renders it. There is deliberately
|
||||
* no metered line item: a flat price, hard caps, and optional capacity packs.
|
||||
*/
|
||||
export interface UsageEnvelope {
|
||||
environment: EnvironmentReference;
|
||||
plan: string;
|
||||
/** Flat monthly price in US dollars (e.g. `25.99`). */
|
||||
flat_price_usd: number;
|
||||
period_start_epoch_seconds: number;
|
||||
period_end_epoch_seconds: number;
|
||||
lines: UsageLine[];
|
||||
packs: CapacityPack[];
|
||||
}
|
||||
|
||||
/** One invoice from the organization's billing provider. */
|
||||
export interface Invoice {
|
||||
invoice_id: string;
|
||||
status: string;
|
||||
amount_usd: number;
|
||||
period_start_epoch_seconds: number;
|
||||
period_end_epoch_seconds: number;
|
||||
/** Provider-hosted invoice PDF, when the provider exposes one. */
|
||||
download_url?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET /v1/organizations/{org}/billing`. An external billing provider is
|
||||
* optional; when none is connected `configured` is false and `notes` says so.
|
||||
*/
|
||||
export interface BillingOverview {
|
||||
organization_id: PortableIdentifier;
|
||||
configured: boolean;
|
||||
provider: string | null;
|
||||
invoices: Invoice[];
|
||||
/** Display form of the payment method on file, e.g. `visa ending 4242`. */
|
||||
payment_method: string | null;
|
||||
notes: string;
|
||||
}
|
||||
|
||||
/** Usage (per environment) and billing (per organization). */
|
||||
export class UsageResource {
|
||||
readonly #http: HttpTransport;
|
||||
|
||||
constructor(http: HttpTransport) {
|
||||
this.#http = http;
|
||||
}
|
||||
|
||||
/** `GET …/environments/{env}/usage` — the environment's flat-price envelope. */
|
||||
async get(ref: EnvironmentRef): Promise<UsageEnvelope> {
|
||||
const result = await this.#http.send<UsageEnvelope>({
|
||||
method: 'GET',
|
||||
path: `${environmentPath(ref)}/usage`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lines at or above a utilization threshold (default 0.8) of their cap — the
|
||||
* console's "approaching a cap, consider a pack" signal.
|
||||
*/
|
||||
async capsNearingLimit(ref: EnvironmentRef, threshold = 0.8): Promise<UsageLine[]> {
|
||||
const envelope = await this.get(ref);
|
||||
return linesNearingCap(envelope, threshold);
|
||||
}
|
||||
|
||||
/** `GET /v1/organizations/{org}/billing` — provider status and invoices. */
|
||||
async billing(organizationId: PortableIdentifier): Promise<BillingOverview> {
|
||||
const result = await this.#http.send<BillingOverview>({
|
||||
method: 'GET',
|
||||
path: `/v1/organizations/${encodeURIComponent(organizationId)}/billing`,
|
||||
});
|
||||
return result.data;
|
||||
}
|
||||
}
|
||||
|
||||
/** Pure form of {@link UsageResource.capsNearingLimit} for an envelope in hand. */
|
||||
export function linesNearingCap(envelope: UsageEnvelope, threshold = 0.8): UsageLine[] {
|
||||
return envelope.lines.filter((line) => line.cap > 0 && line.used / line.cap >= threshold);
|
||||
}
|
||||
571
src/types.gen.ts
Normal file
571
src/types.gen.ts
Normal file
@ -0,0 +1,571 @@
|
||||
/**
|
||||
* DO NOT EDIT BY HAND.
|
||||
*
|
||||
* Generated from `api/openapi.yaml` by `scripts/generate.ts`.
|
||||
* Run `pnpm generate` to refresh after the contract changes.
|
||||
*/
|
||||
|
||||
export interface TokenIntrospection {
|
||||
active: boolean;
|
||||
kind: "personal_access_token" | "organization_api_key" | "oidc" | "sso_session" | "builtin_session";
|
||||
subject: string;
|
||||
organization_id?: string;
|
||||
role?: "owner" | "admin" | "developer" | "viewer" | null;
|
||||
}
|
||||
|
||||
export type QuotaMetric = "database_gb" | "storage_gb" | "backup_gb" | "preview_environments" | "egress_gb" | "compute_hours" | "rows" | "function_invocations";
|
||||
|
||||
export interface ProjectQuotaOverride {
|
||||
metric: QuotaMetric;
|
||||
label: string;
|
||||
unit: string;
|
||||
cap: number;
|
||||
updated_by: string;
|
||||
updated_at_epoch_seconds: number;
|
||||
}
|
||||
|
||||
export interface ProjectQuotas {
|
||||
organization_id: string;
|
||||
project_id: string;
|
||||
overrides: ProjectQuotaOverride[];
|
||||
metrics: {
|
||||
metric: QuotaMetric;
|
||||
label: string;
|
||||
unit: string;
|
||||
}[];
|
||||
/** Fraction of the cap at which usage.threshold_reached fires. */
|
||||
threshold: number;
|
||||
}
|
||||
|
||||
export interface PutProjectQuotasRequest {
|
||||
/** metric -> cap (non-negative number) or null to remove the override. */
|
||||
overrides: {
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
export interface EventDelivery {
|
||||
delivery_id: string;
|
||||
event_id: string;
|
||||
event_type: string;
|
||||
target_url: string;
|
||||
status: "pending" | "delivered" | "failed";
|
||||
attempts: number;
|
||||
last_status_code?: number;
|
||||
last_error?: string;
|
||||
created_epoch_seconds: number;
|
||||
delivered_epoch_seconds?: number;
|
||||
next_attempt_epoch_seconds?: number;
|
||||
/** The signed body: {id, type, created_epoch_seconds, organization_id, project_id, environment_id, data}. */
|
||||
payload: {
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
export interface EventDeliveryList {
|
||||
deliveries: EventDelivery[];
|
||||
webhook_configured: boolean;
|
||||
max_attempts: number;
|
||||
}
|
||||
|
||||
export interface EventSigningSecret {
|
||||
secret: string;
|
||||
rotated: boolean;
|
||||
header: string;
|
||||
scheme: string;
|
||||
}
|
||||
|
||||
export interface EnvironmentTypes {
|
||||
/** The TypeScript module source. */
|
||||
types: string;
|
||||
schemas: string[];
|
||||
}
|
||||
|
||||
export interface JsonObject {
|
||||
|
||||
}
|
||||
|
||||
export interface ItemPage {
|
||||
items: {
|
||||
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface Teardown {
|
||||
organization_id: PortableIdentifier;
|
||||
project_id?: PortableIdentifier;
|
||||
scheduled: boolean;
|
||||
deleted: boolean;
|
||||
state: "deleted" | "deleting_environments";
|
||||
environments: {
|
||||
project_id?: string;
|
||||
environment_id?: string;
|
||||
phase?: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface CreateInvitationRequest {
|
||||
email: string;
|
||||
role?: "owner" | "admin" | "developer" | "viewer";
|
||||
}
|
||||
|
||||
export interface Invitation {
|
||||
invitation_id?: string;
|
||||
organization_id?: string;
|
||||
email?: string;
|
||||
role?: string;
|
||||
invited_by?: string;
|
||||
created_at_epoch_seconds?: number;
|
||||
expires_at_epoch_seconds?: number;
|
||||
status?: "pending" | "accepted" | "revoked" | "expired";
|
||||
accept_url?: string;
|
||||
token?: string;
|
||||
delivery?: "email" | "link";
|
||||
}
|
||||
|
||||
export interface EnvironmentApiKeys {
|
||||
organization_id?: string;
|
||||
project_id?: string;
|
||||
environment_id?: string;
|
||||
api_url?: unknown;
|
||||
/** Legacy anon JWT; works as the client key of any supabase-js v2 app. */
|
||||
anon_key: string;
|
||||
/** Opaque `sb_publishable_` key; the project router swaps it for the anon JWT. */
|
||||
publishable_key?: string;
|
||||
/** Bypasses row-level security. Null for viewers. */
|
||||
service_role_key?: unknown;
|
||||
/** Opaque `sb_secret_` key for the service role. Null for viewers. */
|
||||
secret_key?: unknown;
|
||||
jwt_secret_version: number;
|
||||
jwt_secret_source: "control_plane" | "operator";
|
||||
jwt_secret?: string;
|
||||
}
|
||||
|
||||
export interface AuthUserActionResult {
|
||||
user_id: string;
|
||||
applied: boolean;
|
||||
}
|
||||
|
||||
export interface WebhookConfig {
|
||||
url: string;
|
||||
method?: "POST";
|
||||
headers?: {
|
||||
|
||||
};
|
||||
timeout_ms?: number;
|
||||
retry_count?: number;
|
||||
}
|
||||
|
||||
export interface CreateWebhookRequest {
|
||||
name: string;
|
||||
table_schema: string;
|
||||
table_name: string;
|
||||
events: "INSERT" | "UPDATE" | "DELETE" | "TRUNCATE"[];
|
||||
config: WebhookConfig;
|
||||
}
|
||||
|
||||
export interface Webhook {
|
||||
webhook_id?: string;
|
||||
name?: string;
|
||||
table_schema?: string;
|
||||
table_name?: string;
|
||||
events?: string[];
|
||||
config?: WebhookConfig;
|
||||
status?: "active" | "paused" | "error";
|
||||
created_at_epoch_seconds?: number;
|
||||
last_fired_epoch_seconds?: number;
|
||||
failure_count?: number;
|
||||
}
|
||||
|
||||
export interface WebhookList {
|
||||
webhooks: Webhook[];
|
||||
notes: unknown;
|
||||
}
|
||||
|
||||
export type PortableIdentifier = string;
|
||||
|
||||
export type Role = "owner" | "admin" | "developer" | "viewer";
|
||||
|
||||
export interface PutOrganizationRequest {
|
||||
display_name: string;
|
||||
}
|
||||
|
||||
export interface Organization {
|
||||
organization_id: PortableIdentifier;
|
||||
display_name: string;
|
||||
}
|
||||
|
||||
export interface PutMembershipRequest {
|
||||
subject: string;
|
||||
role: Role;
|
||||
}
|
||||
|
||||
export interface Membership {
|
||||
organization_id: PortableIdentifier;
|
||||
subject: string;
|
||||
role: Role;
|
||||
}
|
||||
|
||||
export interface PutProjectRequest {
|
||||
region: PortableIdentifier;
|
||||
postgres_major: 17;
|
||||
/** SB4. With a machine token (agent token, personal access token or organization API key), a new project that adds to this month's bill is refused with 402 confirm_billable naming monthly_delta_cents; send that amount here after the person approves. Past the organization's max_projects_by_agent the answer is 402 agent_project_limit. Console sessions never need it. */
|
||||
confirm_billable_cents?: number;
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
organization_id: PortableIdentifier;
|
||||
project_id: PortableIdentifier;
|
||||
region: PortableIdentifier;
|
||||
postgres_major: 17;
|
||||
}
|
||||
|
||||
export interface CreateEnvironmentRequest {
|
||||
organization_id: PortableIdentifier;
|
||||
project_id: PortableIdentifier;
|
||||
environment_id: PortableIdentifier;
|
||||
kind: EnvironmentKind;
|
||||
data_mode: DataMode;
|
||||
region: PortableIdentifier;
|
||||
postgres_major: 17;
|
||||
ttl_hours?: number;
|
||||
}
|
||||
|
||||
export type EnvironmentKind = "preview" | "staging" | "production";
|
||||
|
||||
export type DataMode = "schema_only" | "sanitized" | "snapshot";
|
||||
|
||||
export type EnvironmentPhase = "requested" | "provisioning" | "ready" | "updating" | "suspended" | "failed_recoverable" | "deleting" | "deleted";
|
||||
|
||||
export interface Environment {
|
||||
organization_id: PortableIdentifier;
|
||||
project_id: PortableIdentifier;
|
||||
environment_id: PortableIdentifier;
|
||||
kind: EnvironmentKind;
|
||||
data_mode: DataMode;
|
||||
region: PortableIdentifier;
|
||||
postgres_major: number;
|
||||
ttl_hours?: number;
|
||||
phase: EnvironmentPhase;
|
||||
desired_generation: number;
|
||||
observed_generation: number;
|
||||
retry_count: number;
|
||||
last_error?: ProviderError;
|
||||
last_activity_epoch_seconds: number;
|
||||
/** Present only for expiring preview environments. */
|
||||
expires_at_epoch_seconds?: number;
|
||||
finalizers: string[];
|
||||
}
|
||||
|
||||
export type OperationState = "pending" | "running" | "waiting_retry" | "succeeded" | "failed" | "cancelled";
|
||||
|
||||
export interface Operation {
|
||||
id: PortableIdentifier;
|
||||
kind: "create_environment" | "suspend_environment" | "resume_environment" | "delete_environment" | "rollout_environment";
|
||||
environment: EnvironmentReference;
|
||||
state: OperationState;
|
||||
attempt_count: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface EnvironmentReference {
|
||||
organization_id: PortableIdentifier;
|
||||
project_id: PortableIdentifier;
|
||||
environment_id: PortableIdentifier;
|
||||
}
|
||||
|
||||
export interface ProviderError {
|
||||
code: string;
|
||||
message: string;
|
||||
retryable: boolean;
|
||||
}
|
||||
|
||||
export interface AuditEvent {
|
||||
sequence: number;
|
||||
actor_subject: string;
|
||||
action: string;
|
||||
organization_id: PortableIdentifier;
|
||||
project_id?: PortableIdentifier;
|
||||
environment_id?: PortableIdentifier;
|
||||
operation_id?: PortableIdentifier;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface Problem {
|
||||
type: string;
|
||||
title: string;
|
||||
status: number;
|
||||
code: string;
|
||||
detail?: string;
|
||||
request_id?: string;
|
||||
}
|
||||
|
||||
export interface ImportDestination {
|
||||
organizationId: PortableIdentifier;
|
||||
projectId: PortableIdentifier;
|
||||
environmentId: PortableIdentifier;
|
||||
}
|
||||
|
||||
export interface CreateImportRequest {
|
||||
/** The source Supabase project reference. */
|
||||
sourceProjectRef: string;
|
||||
/** Source Postgres connection string; used once, never returned. */
|
||||
sourceConnectionString: string;
|
||||
/** Source service key; used once, never returned. */
|
||||
sourceServiceKey: string;
|
||||
destination: ImportDestination;
|
||||
/** When true, plan the move and report — nothing is written. */
|
||||
dryRun: boolean;
|
||||
}
|
||||
|
||||
export type ImportCategory = "schema" | "auth users" | "data" | "policies" | "storage" | "edge functions" | "secrets";
|
||||
|
||||
export type ImportSeverity = "info" | "action" | "warning";
|
||||
|
||||
export interface ImportFinding {
|
||||
category: ImportCategory;
|
||||
severity: ImportSeverity;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface ImportTally {
|
||||
tables: number;
|
||||
rows: number;
|
||||
authUsers: number;
|
||||
identities: number;
|
||||
mfaFactors: number;
|
||||
policies: number;
|
||||
buckets: number;
|
||||
objects: number;
|
||||
objectBytes: number;
|
||||
edgeFunctions: number;
|
||||
/** Signing keys reissued (never copied). */
|
||||
signingKeysReissued: number;
|
||||
/** User secrets left for the operator to re-enter. */
|
||||
secretsDeferred: number;
|
||||
}
|
||||
|
||||
export type ImportCheckStatus = "pass" | "fail" | "warn" | "skipped";
|
||||
|
||||
export interface ImportVerificationCheck {
|
||||
name: string;
|
||||
status: ImportCheckStatus;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface ImportVerification {
|
||||
checks: ImportVerificationCheck[];
|
||||
}
|
||||
|
||||
export interface ImportDryRun {
|
||||
projectRef: string;
|
||||
destination: string;
|
||||
planned: ImportTally;
|
||||
tables: string[];
|
||||
findings: ImportFinding[];
|
||||
}
|
||||
|
||||
export interface ImportReport {
|
||||
projectRef: string;
|
||||
destination: string;
|
||||
moved: ImportTally;
|
||||
findings: ImportFinding[];
|
||||
/** Populated once the verifier has run; null when unverifiable. */
|
||||
verification?: ImportVerification | null;
|
||||
}
|
||||
|
||||
export interface ImportJobError {
|
||||
code: string;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface ImportJob {
|
||||
import_id: string;
|
||||
status: "running" | "succeeded" | "failed" | "interrupted";
|
||||
/** The phase in progress: schema, auth_users, data, policies, storage_objects, edge_functions, secrets, verify, done. */
|
||||
phase: string;
|
||||
/** Every phase in run order. */
|
||||
phases?: string[];
|
||||
organization_id?: string;
|
||||
project_id?: string;
|
||||
environment_id?: string;
|
||||
source?: "supabase" | "firebase" | "instantdb";
|
||||
source_ref?: string;
|
||||
dry_run?: boolean;
|
||||
counts?: ImportTally;
|
||||
/** Findings raised so far. */
|
||||
findings?: number;
|
||||
errors: ImportJobError[];
|
||||
/** Whether `POST /v1/imports/{import_id}/resume` can continue the run (it stopped after at least one committed step). */
|
||||
resumable?: boolean;
|
||||
/** How many times the run has been started (1 + resumes). */
|
||||
attempts?: number;
|
||||
/** Epoch seconds. */
|
||||
started_at: number;
|
||||
/** Epoch seconds. */
|
||||
updated_at: number;
|
||||
/** Epoch seconds of the running replica's last liveness signal (durable progress only). */
|
||||
heartbeat_at?: number;
|
||||
/** Epoch seconds; absent while running. */
|
||||
finished_at?: number;
|
||||
/** Whether the fail-closed parity verdict passed. */
|
||||
passed?: boolean;
|
||||
/** Whether the report was stored in the import history under `import_id` (readable at /v1/organizations/{org}/imports/{id}). */
|
||||
report_recorded?: boolean;
|
||||
report?: ImportReport;
|
||||
}
|
||||
|
||||
export interface OrganizationPlanProjects {
|
||||
used?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface OrganizationPlanUpgrade {
|
||||
plan: string;
|
||||
name: string;
|
||||
price_usd?: number;
|
||||
projects?: number;
|
||||
}
|
||||
|
||||
export interface OrganizationPlan {
|
||||
organization_id: string;
|
||||
plan: string;
|
||||
name: string;
|
||||
catalog?: "legacy" | "tiered";
|
||||
/** True only on a flat plan with a project cap (Studio). */
|
||||
project_limits_enforced: boolean;
|
||||
projects: OrganizationPlanProjects;
|
||||
}
|
||||
|
||||
export interface MigrationInput {
|
||||
version: string;
|
||||
name: string;
|
||||
up: string;
|
||||
down?: string;
|
||||
}
|
||||
|
||||
export interface RunMigrationsRequest {
|
||||
migrations: MigrationInput[];
|
||||
/** When false, plan and lint only — nothing is executed. */
|
||||
apply: boolean;
|
||||
}
|
||||
|
||||
export interface AppendMigrationRequest {
|
||||
migration: MigrationInput;
|
||||
/** When false or absent, lint only — nothing is executed. */
|
||||
apply?: boolean;
|
||||
}
|
||||
|
||||
export interface MigrationLedger {
|
||||
migrations: {
|
||||
version: number;
|
||||
name: string;
|
||||
sha256: string;
|
||||
applied_at?: unknown;
|
||||
}[];
|
||||
}
|
||||
|
||||
export type MigrationDirection = "up" | "down";
|
||||
|
||||
export interface MigrationPlanStep {
|
||||
version: number;
|
||||
name: string;
|
||||
direction: MigrationDirection;
|
||||
checksum: string;
|
||||
}
|
||||
|
||||
export interface MigrationPlan {
|
||||
steps: MigrationPlanStep[];
|
||||
}
|
||||
|
||||
export type MigrationLintSeverity = "BLOCK" | "WARN";
|
||||
|
||||
export interface MigrationLintFinding {
|
||||
rule: string;
|
||||
severity: MigrationLintSeverity;
|
||||
message: string;
|
||||
subject: string;
|
||||
line: number;
|
||||
}
|
||||
|
||||
export interface RunMigrationsResult {
|
||||
plan: MigrationPlan;
|
||||
lintFindings: MigrationLintFinding[];
|
||||
/** Versions actually applied; empty when apply was false or a finding blocked. */
|
||||
applied: number[];
|
||||
}
|
||||
|
||||
export type ExportFormat = "compose" | "kustomize";
|
||||
|
||||
export interface CreateExportRequest {
|
||||
format: ExportFormat;
|
||||
}
|
||||
|
||||
export interface ExportIntegrityClaim {
|
||||
path: string;
|
||||
sha256: string;
|
||||
size_bytes: number;
|
||||
}
|
||||
|
||||
export interface ExportDatabaseArtifact {
|
||||
path: string;
|
||||
format: string;
|
||||
sha256: string;
|
||||
size_bytes: number;
|
||||
postgres_major: number;
|
||||
}
|
||||
|
||||
export interface ExportStorageSummary {
|
||||
root: string;
|
||||
object_count: number;
|
||||
total_bytes: number;
|
||||
}
|
||||
|
||||
export interface ExportManifestSignature {
|
||||
algorithm: string;
|
||||
/** Non-secret identifier of the key used, so a verifier can select it. */
|
||||
key_id: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface ExportManifest {
|
||||
schema_version: number;
|
||||
bundle_id: string;
|
||||
organization_id: string;
|
||||
project_id: string;
|
||||
environment_id: string;
|
||||
created_at_epoch_seconds: number;
|
||||
database: ExportDatabaseArtifact;
|
||||
storage: ExportStorageSummary;
|
||||
render_targets: string[];
|
||||
artifacts: ExportIntegrityClaim[];
|
||||
signature?: ExportManifestSignature;
|
||||
}
|
||||
|
||||
export interface ExportResult {
|
||||
manifest: ExportManifest;
|
||||
/** Reference to the assembled bundle (its addressable root/id). */
|
||||
bundleRef: string;
|
||||
}
|
||||
|
||||
/** Inline 200 body of `getPlans`. */
|
||||
export interface GetPlansResponse {
|
||||
billing: {
|
||||
|
||||
};
|
||||
order: string[];
|
||||
fallback: string;
|
||||
plans: {
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
/** Inline 200 body of `listEnvironments`. */
|
||||
export interface ListEnvironmentsResponse {
|
||||
environments: Environment[];
|
||||
}
|
||||
|
||||
/** Inline 200 body of `listAuditEvents`. */
|
||||
export interface ListAuditEventsResponse {
|
||||
items: AuditEvent[];
|
||||
}
|
||||
221
tests/add.test.ts
Normal file
221
tests/add.test.ts
Normal file
@ -0,0 +1,221 @@
|
||||
/**
|
||||
* Tests for `npx scribase add` (SP-D1): argument parsing, the add request,
|
||||
* the connect-link wait, proof output, and that no secret ever reaches stdout
|
||||
* or the env file (no network, in-memory files).
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { addMain, formatAdd, parseAddArgs, runAdd } from '../src/cli/add.js';
|
||||
import type { AddIo } from '../src/cli/add.js';
|
||||
import { isSecretEnv, publicEnvOnly } from '../src/cli/envfile.js';
|
||||
import { InitError } from '../src/cli/init.js';
|
||||
|
||||
const ROOT = '/work/app';
|
||||
const TOKEN = 'scb_agt_live_token_value_never_printed';
|
||||
const SECRET_KEY = 'sb_secret_abcdefghijklmnop';
|
||||
const STATE = JSON.stringify({
|
||||
organization_id: 'acme',
|
||||
project_id: 'shop',
|
||||
environment_id: 'production',
|
||||
api_url: 'https://api.example.test',
|
||||
});
|
||||
|
||||
interface Call {
|
||||
method: string;
|
||||
url: string;
|
||||
auth: string | null;
|
||||
body: unknown;
|
||||
}
|
||||
|
||||
function harness(answers: { status: number; body: unknown }[], files: Record<string, string> = {}) {
|
||||
const calls: Call[] = [];
|
||||
const logs: string[] = [];
|
||||
const opened: string[] = [];
|
||||
const written: Record<string, string> = {};
|
||||
let clock = 1_700_000_000_000;
|
||||
const store: Record<string, string> = { [`${ROOT}/.scribase/project.json`]: STATE, ...files };
|
||||
const io: AddIo = {
|
||||
cwd: ROOT,
|
||||
env: {},
|
||||
fetch: (async (url: string | URL | Request, init?: RequestInit) => {
|
||||
calls.push({
|
||||
method: init?.method ?? 'GET',
|
||||
url: String(url),
|
||||
auth: new Headers(init?.headers).get('authorization'),
|
||||
body: init?.body ? JSON.parse(String(init.body)) : undefined,
|
||||
});
|
||||
const answer = answers.shift() ?? { status: 500, body: { code: 'no_answer', detail: 'test ran out of answers' } };
|
||||
return new Response(JSON.stringify(answer.body), { status: answer.status });
|
||||
}) as typeof fetch,
|
||||
readFile: (path) => store[path] ?? null,
|
||||
writeFile: (path, contents) => {
|
||||
store[path] = contents;
|
||||
written[path] = contents;
|
||||
},
|
||||
credentials: () => ({ token: TOKEN }),
|
||||
sleep: async (ms) => {
|
||||
clock += ms;
|
||||
},
|
||||
now: () => clock,
|
||||
log: (line) => logs.push(line),
|
||||
openBrowser: (url) => opened.push(url),
|
||||
};
|
||||
return { io, calls, logs, opened, written, store };
|
||||
}
|
||||
|
||||
const LIVE = {
|
||||
slot: 'email',
|
||||
title: 'Email',
|
||||
status: 'live',
|
||||
state: 'live',
|
||||
live: true,
|
||||
configured: true,
|
||||
provider: 'scribase',
|
||||
proof: { kind: 'email_sent', id: '42', at: 1_700_000_001, detail: 'a***@example.com' },
|
||||
connect_url: null,
|
||||
next: null,
|
||||
env: {},
|
||||
sent: true,
|
||||
};
|
||||
|
||||
const CONNECT_URL = 'https://console.example.test/connect/email?org=acme&project=shop&env=production';
|
||||
|
||||
describe('scribase add', () => {
|
||||
it('parses a slot and flags, and refuses bad input', () => {
|
||||
const options = parseAddArgs(['email', '--own', '--json', '--wait', '30', '--no-browser']);
|
||||
assert.equal(options.slot, 'email');
|
||||
assert.equal(options.own, true);
|
||||
assert.equal(options.json, true);
|
||||
assert.equal(options.waitSeconds, 30);
|
||||
assert.equal(options.browser, false);
|
||||
assert.equal(parseAddArgs(['--list']).list, true);
|
||||
assert.throws(() => parseAddArgs([]), InitError);
|
||||
assert.throws(() => parseAddArgs(['Email!']), InitError);
|
||||
assert.throws(() => parseAddArgs(['email', '--wait', '0']), InitError);
|
||||
assert.throws(() => parseAddArgs(['email', '--password', 'x']), InitError);
|
||||
});
|
||||
|
||||
it('adds email and prints the proof, never the token', async () => {
|
||||
const { io, calls } = harness([{ status: 200, body: LIVE }]);
|
||||
const out: string[] = [];
|
||||
const code = await addMain(['email', '--json'], io, (text) => out.push(text));
|
||||
assert.equal(code, 0);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0]?.method, 'POST');
|
||||
assert.equal(calls[0]?.url, 'https://api.example.test/v1/organizations/acme/projects/shop/environments/production/capabilities/email');
|
||||
assert.equal(calls[0]?.auth, `Bearer ${TOKEN}`);
|
||||
assert.deepEqual(calls[0]?.body, {});
|
||||
const result = JSON.parse(out.join('')) as { live: boolean; proof: { kind: string; id: string; at: number } };
|
||||
assert.equal(result.live, true);
|
||||
assert.deepEqual([result.proof.kind, result.proof.id, result.proof.at], ['email_sent', '42', 1_700_000_001]);
|
||||
assert.ok(!out.join('').includes(TOKEN));
|
||||
});
|
||||
|
||||
it('with --own opens the connect link, waits for a fresh proof, and prints no secret', async () => {
|
||||
const needsConnect = { ...LIVE, state: 'needs_connect', live: false, provider: null, proof: null, connect_url: CONNECT_URL, sent: false };
|
||||
const stale = { ...LIVE, proof: { ...LIVE.proof, at: 1_600_000_000 } };
|
||||
const fresh = { ...LIVE, provider: 'own', proof: { ...LIVE.proof, id: '43', at: 1_700_000_010 } };
|
||||
const { io, calls, logs, opened } = harness([
|
||||
{ status: 200, body: needsConnect },
|
||||
{ status: 200, body: needsConnect },
|
||||
{ status: 200, body: stale },
|
||||
{ status: 200, body: fresh },
|
||||
]);
|
||||
const out: string[] = [];
|
||||
const code = await addMain(['email', '--own'], io, (text) => out.push(text));
|
||||
assert.equal(code, 0);
|
||||
assert.deepEqual(calls[0]?.body, { provider: 'own' });
|
||||
assert.deepEqual(opened, [CONNECT_URL]);
|
||||
assert.equal(calls.filter((call) => call.method === 'GET').length, 3);
|
||||
const printed = `${logs.join('\n')}\n${out.join('')}`;
|
||||
assert.match(printed, /email_sent #43/);
|
||||
assert.match(printed, /your mail server/);
|
||||
for (const secret of [TOKEN, 'smtp_pass', 'password']) assert.ok(!printed.includes(secret), secret);
|
||||
});
|
||||
|
||||
it('with --no-wait prints the link and exits 3', async () => {
|
||||
const needsConnect = { ...LIVE, state: 'needs_connect', live: false, provider: null, proof: null, connect_url: CONNECT_URL, sent: false };
|
||||
const { io } = harness([{ status: 200, body: needsConnect }]);
|
||||
const out: string[] = [];
|
||||
assert.equal(await addMain(['email', '--own', '--no-wait', '--no-browser', '--json'], io, (text) => out.push(text)), 3);
|
||||
const result = JSON.parse(out.join('')) as { status: string; connect_url: string };
|
||||
assert.equal(result.status, 'needs_connect');
|
||||
assert.equal(result.connect_url, CONNECT_URL);
|
||||
});
|
||||
|
||||
it('times out with a next step when no proof arrives', async () => {
|
||||
const needsConnect = { ...LIVE, state: 'needs_connect', live: false, provider: null, proof: null, connect_url: CONNECT_URL, sent: false };
|
||||
const { io } = harness(Array.from({ length: 50 }, () => ({ status: 200, body: needsConnect })));
|
||||
await assert.rejects(
|
||||
runAdd({ ...parseAddArgs(['email', '--own', '--no-browser']), waitSeconds: 6 }, io),
|
||||
(error: unknown) => error instanceof InitError && error.code === 'connect_timeout',
|
||||
);
|
||||
});
|
||||
|
||||
it('writes public env values only, and refuses secrets by name', async () => {
|
||||
const body = { ...LIVE, env: { PUBLIC_DSN_HOST: 'errors.example.test', SERVICE_SECRET: SECRET_KEY, OTHER: SECRET_KEY } };
|
||||
const { io, written } = harness([{ status: 200, body }], { [`${ROOT}/.env.local`]: 'EXISTING=1\n' });
|
||||
const out: string[] = [];
|
||||
await addMain(['email'], io, (text) => out.push(text));
|
||||
const file = written[`${ROOT}/.env.local`] ?? '';
|
||||
assert.match(file, /EXISTING=1/);
|
||||
assert.match(file, /PUBLIC_DSN_HOST=errors.example.test/);
|
||||
assert.ok(!file.includes(SECRET_KEY));
|
||||
const printed = out.join('');
|
||||
assert.match(printed, /refused \(secret\): SERVICE_SECRET, OTHER/);
|
||||
assert.ok(!printed.includes(SECRET_KEY));
|
||||
});
|
||||
|
||||
it('reports server refusals with a next step', async () => {
|
||||
const { io } = harness([{ status: 409, body: { code: 'capability_arriving', detail: 'S3 protocol for Storage is arriving' } }]);
|
||||
const out: string[] = [];
|
||||
assert.equal(await addMain(['storage-s3', '--json'], io, (text) => out.push(text)), 1);
|
||||
const failure = JSON.parse(out.join('')) as { ok: boolean; error: { code: string; next: string } };
|
||||
assert.equal(failure.error.code, 'capability_arriving');
|
||||
assert.match(failure.error.next, /--list/);
|
||||
});
|
||||
|
||||
it('lists the registry without a token', async () => {
|
||||
const { io, calls } = harness([
|
||||
{ status: 200, body: { capabilities: [{ slot: 'email', title: 'Email', summary: 'Auth email.', status: 'live', compat: ['17-capabilities:email add'] }] } },
|
||||
]);
|
||||
const result = await runAdd(parseAddArgs(['--list']), io);
|
||||
assert.equal(calls[0]?.auth, null);
|
||||
assert.equal(calls[0]?.url, 'https://api.example.test/v1/capabilities');
|
||||
assert.match(formatAdd(result), /email\s+Live/);
|
||||
});
|
||||
|
||||
it('needs a connected folder and a token', async () => {
|
||||
const { io } = harness([]);
|
||||
await assert.rejects(runAdd(parseAddArgs(['email']), { ...io, readFile: () => null }), (error: unknown) => error instanceof InitError && error.code === 'not_initialized');
|
||||
await assert.rejects(runAdd(parseAddArgs(['email']), { ...io, credentials: () => ({}) }), (error: unknown) => error instanceof InitError && error.code === 'not_signed_in');
|
||||
});
|
||||
});
|
||||
|
||||
describe('secret guard', () => {
|
||||
it('flags secret names and secret-shaped values', () => {
|
||||
assert.equal(isSecretEnv('SMTP_PASS', 'x'), true);
|
||||
assert.equal(isSecretEnv('SUPABASE_SERVICE_ROLE_KEY', 'x'), true);
|
||||
assert.equal(isSecretEnv('ANYTHING', SECRET_KEY), true);
|
||||
assert.equal(isSecretEnv('ANYTHING', TOKEN), true);
|
||||
assert.equal(isSecretEnv('DATABASE_URL', 'postgres://user:pw@host/db'), true);
|
||||
const serviceJwt = `eyJhbGciOiJIUzI1NiJ9.${Buffer.from(JSON.stringify({ role: 'service_role' })).toString('base64url')}.sig`;
|
||||
const anonJwt = `eyJhbGciOiJIUzI1NiJ9.${Buffer.from(JSON.stringify({ role: 'anon' })).toString('base64url')}.sig`;
|
||||
assert.equal(isSecretEnv('X', serviceJwt), true);
|
||||
assert.equal(isSecretEnv('NEXT_PUBLIC_SUPABASE_ANON_KEY', anonJwt), false);
|
||||
assert.equal(isSecretEnv('NEXT_PUBLIC_SUPABASE_URL', 'https://x.scribase.app'), false);
|
||||
assert.deepEqual(publicEnvOnly({ A: 'https://x', B: SECRET_KEY }), { safe: { A: 'https://x' }, refused: ['B'] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('command aliases (PS2.0, P-Y4)', () => {
|
||||
it('`scribase deploy` runs `scribase add deploy` with its options', async () => {
|
||||
const { expandAlias } = await import('../src/cli/aliases.js');
|
||||
assert.deepEqual(expandAlias(['deploy']), ['add', 'deploy']);
|
||||
assert.deepEqual(expandAlias(['deploy', '--json', '--no-wait']), ['add', 'deploy', '--json', '--no-wait']);
|
||||
assert.deepEqual(expandAlias(['add', 'email']), ['add', 'email']);
|
||||
assert.deepEqual(expandAlias([]), []);
|
||||
});
|
||||
});
|
||||
620
tests/cli.test.ts
Normal file
620
tests/cli.test.ts
Normal file
@ -0,0 +1,620 @@
|
||||
/**
|
||||
* Tests for `npx scribase init`: framework detection, env-file merging, the
|
||||
* proof of work, and the whole flow against an in-memory filesystem and a
|
||||
* fake control plane (no network, no child processes).
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
import { clientSource, conventionsFor, detectFramework, installCommand, packageManager } from '../src/cli/framework.js';
|
||||
import { ensureDirIgnored, ensureIgnored, mergeEnv, readEnvValue } from '../src/cli/envfile.js';
|
||||
import { leadingZeroBits, solveChallenge } from '../src/cli/pow.js';
|
||||
import { DEFAULT_REGION, InitError, billingNextStep, consoleUrlFor, parseInitArgs, projectSlug, runInit } from '../src/cli/init.js';
|
||||
import type { InitIo } from '../src/cli/init.js';
|
||||
|
||||
const ROOT = '/work/app';
|
||||
|
||||
function facts(pkg: Record<string, unknown> | null, files: string[] = []) {
|
||||
return {
|
||||
packageJson: pkg as never,
|
||||
exists: (path: string) => files.includes(path),
|
||||
};
|
||||
}
|
||||
|
||||
describe('framework detection', () => {
|
||||
it('detects Next.js, Expo, Vite and falls back to Node', () => {
|
||||
assert.equal(detectFramework(facts({ dependencies: { next: '15' } })), 'next');
|
||||
assert.equal(detectFramework(facts(null, ['next.config.mjs'])), 'next');
|
||||
assert.equal(detectFramework(facts({ dependencies: { expo: '52', 'react-native': '0.76' } })), 'expo');
|
||||
assert.equal(detectFramework(facts({ devDependencies: { vite: '6' } })), 'vite');
|
||||
assert.equal(detectFramework(facts({ dependencies: { express: '5' } })), 'node');
|
||||
assert.equal(detectFramework(facts(null)), 'node');
|
||||
});
|
||||
|
||||
it('detects SvelteKit before plain Vite, even though every SvelteKit app is also a Vite app', () => {
|
||||
// A real `npm create svelte@latest` package.json: @sveltejs/kit plus vite,
|
||||
// both as devDependencies, and a vite.config.ts on disk.
|
||||
assert.equal(
|
||||
detectFramework(facts({ devDependencies: { '@sveltejs/kit': '2', vite: '6' } }, ['vite.config.ts', 'svelte.config.js'])),
|
||||
'sveltekit',
|
||||
);
|
||||
// svelte.config.js alone (no package.json dependency read, e.g. a
|
||||
// monorepo workspace root) is still enough.
|
||||
assert.equal(detectFramework(facts(null, ['svelte.config.js'])), 'sveltekit');
|
||||
// A plain Vite app with neither signal still falls through to 'vite'.
|
||||
assert.equal(detectFramework(facts({ devDependencies: { vite: '6' } }, ['vite.config.ts'])), 'vite');
|
||||
});
|
||||
|
||||
it('uses each framework’s public variable prefix and never ships the service key to a bundle', () => {
|
||||
const next = conventionsFor('next', facts({}, ['tsconfig.json', 'src']));
|
||||
assert.equal(next.envFile, '.env.local');
|
||||
assert.equal(next.urlVar, 'NEXT_PUBLIC_SUPABASE_URL');
|
||||
assert.equal(next.serviceRoleVar, 'SUPABASE_SERVICE_ROLE_KEY');
|
||||
assert.equal(next.clientFile, 'src/lib/supabase.ts');
|
||||
|
||||
const expo = conventionsFor('expo', facts({}));
|
||||
assert.equal(expo.urlVar, 'EXPO_PUBLIC_SUPABASE_URL');
|
||||
assert.equal(expo.anonKeyVar, 'EXPO_PUBLIC_SUPABASE_ANON_KEY');
|
||||
assert.equal(expo.serviceRoleVar, null);
|
||||
|
||||
const vite = conventionsFor('vite', facts({}, ['tsconfig.json']));
|
||||
assert.equal(vite.urlVar, 'VITE_SUPABASE_URL');
|
||||
assert.equal(vite.serviceRoleVar, null);
|
||||
assert.match(clientSource(vite), /import\.meta\.env\.VITE_SUPABASE_URL!/);
|
||||
|
||||
const node = conventionsFor('node', facts({}));
|
||||
assert.equal(node.envFile, '.env');
|
||||
assert.equal(node.clientFile, 'supabase.mjs');
|
||||
assert.match(clientSource(node), /process\.env\.SUPABASE_ANON_KEY\)/);
|
||||
// Unlike Next.js/Vite/Expo, plain Node never auto-loads its env file:
|
||||
// without this, `createClient` sees undefined env vars and throws
|
||||
// "supabaseUrl is required." the moment a fresh `scribase init` user
|
||||
// imports the generated client, before any query ever runs.
|
||||
assert.match(clientSource(node), /process\.loadEnvFile\(\)/);
|
||||
assert.doesNotMatch(clientSource(next), /process\.loadEnvFile\(\)/);
|
||||
assert.doesNotMatch(clientSource(vite), /process\.loadEnvFile\(\)/);
|
||||
assert.doesNotMatch(clientSource(expo), /process\.loadEnvFile\(\)/);
|
||||
|
||||
// SvelteKit: real $env/static/public bindings (not VITE_-prefixed
|
||||
// import.meta.env like plain Vite), and a real service-role var since
|
||||
// SvelteKit has a server runtime, unlike Vite/Expo's pure client bundles.
|
||||
const sveltekit = conventionsFor('sveltekit', facts({}, ['tsconfig.json']));
|
||||
assert.equal(sveltekit.envFile, '.env');
|
||||
assert.equal(sveltekit.urlVar, 'PUBLIC_SUPABASE_URL');
|
||||
assert.equal(sveltekit.anonKeyVar, 'PUBLIC_SUPABASE_ANON_KEY');
|
||||
assert.equal(sveltekit.serviceRoleVar, 'SUPABASE_SERVICE_ROLE_KEY');
|
||||
assert.equal(sveltekit.clientFile, 'src/lib/supabase.ts');
|
||||
const sveltekitSource = clientSource(sveltekit);
|
||||
assert.match(sveltekitSource, /import \{ PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY \} from '\$env\/static\/public';/);
|
||||
assert.match(sveltekitSource, /createClient\(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY\);/);
|
||||
// $env/static/public is already typed `string` (SvelteKit fails the
|
||||
// build itself if a value is missing), so a `!` non-null assertion here
|
||||
// would just be noise unlike every other framework's env read.
|
||||
assert.doesNotMatch(sveltekitSource, /PUBLIC_SUPABASE_URL!/);
|
||||
assert.doesNotMatch(sveltekitSource, /process\.loadEnvFile\(\)/);
|
||||
});
|
||||
|
||||
it('picks the package manager from the lockfile', () => {
|
||||
assert.equal(packageManager((p) => p === 'pnpm-lock.yaml'), 'pnpm');
|
||||
assert.equal(packageManager((p) => p === 'yarn.lock'), 'yarn');
|
||||
assert.equal(packageManager(() => false), 'npm');
|
||||
assert.deepEqual(installCommand('npm'), ['npm', ['install', '@supabase/supabase-js', '--no-audit', '--no-fund']]);
|
||||
assert.deepEqual(installCommand('pnpm'), ['pnpm', ['add', '@supabase/supabase-js']]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('env files', () => {
|
||||
it('replaces keys in place, keeps everything else, appends new keys', () => {
|
||||
const before = '# mine\nOTHER=1\nNEXT_PUBLIC_SUPABASE_URL=https://old\n';
|
||||
const after = mergeEnv(before, {
|
||||
NEXT_PUBLIC_SUPABASE_URL: 'https://new.example.com',
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY: 'eyJ.x.y',
|
||||
});
|
||||
assert.equal(
|
||||
after,
|
||||
'# mine\nOTHER=1\nNEXT_PUBLIC_SUPABASE_URL=https://new.example.com\n\n# Scribase (written by `npx scribase init`)\nNEXT_PUBLIC_SUPABASE_ANON_KEY=eyJ.x.y\n',
|
||||
);
|
||||
assert.equal(readEnvValue(after, 'NEXT_PUBLIC_SUPABASE_URL'), 'https://new.example.com');
|
||||
assert.equal(readEnvValue(mergeEnv('', { A: 'has space' }), 'A'), 'has space');
|
||||
});
|
||||
|
||||
it('adds the env file to .gitignore unless a pattern already covers it', () => {
|
||||
assert.equal(ensureIgnored('node_modules\n', '.env'), 'node_modules\n.env\n');
|
||||
assert.equal(ensureIgnored('.env*.local\n', '.env.local'), null);
|
||||
assert.equal(ensureIgnored('.env*', '.env'), null);
|
||||
assert.equal(ensureIgnored('', '.env.local'), '.env.local\n');
|
||||
});
|
||||
|
||||
it('adds .scribase/ (the claim link) to .gitignore unless already ignored', () => {
|
||||
assert.equal(ensureDirIgnored('.env\n', '.scribase'), '.env\n.scribase/\n');
|
||||
assert.equal(ensureDirIgnored('.env', '.scribase'), '.env\n.scribase/\n');
|
||||
assert.equal(ensureDirIgnored('/.scribase\n', '.scribase'), null);
|
||||
assert.equal(ensureDirIgnored('.scribase/\n', '.scribase/'), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('proof of work', () => {
|
||||
it('finds a nonce with the requested leading zero bits', () => {
|
||||
const nonce = solveChallenge('123.abc.def', 10);
|
||||
const digest = createHash('sha256').update(`123.abc.def:${nonce}`).digest();
|
||||
assert.ok(leadingZeroBits(digest) >= 10);
|
||||
assert.match(nonce, /^[a-z0-9]+$/);
|
||||
assert.equal(leadingZeroBits(new Uint8Array([0, 0x0f])), 12);
|
||||
});
|
||||
});
|
||||
|
||||
describe('argument parsing', () => {
|
||||
it('parses flags and rejects unknown ones', () => {
|
||||
const options = parseInitArgs(['--temp', '--yes', '--json', '--name', 'My App', '--wait=10', '--no-install']);
|
||||
assert.equal(options.temp, true);
|
||||
assert.equal(options.yes, true);
|
||||
assert.equal(options.json, true);
|
||||
assert.equal(options.name, 'My App');
|
||||
assert.equal(options.waitSeconds, 10);
|
||||
assert.equal(options.install, false);
|
||||
assert.throws(() => parseInitArgs(['--bogus']), InitError);
|
||||
assert.throws(() => parseInitArgs(['--name']), InitError);
|
||||
assert.equal(projectSlug('My Cool App!'), 'my-cool-app');
|
||||
assert.equal(projectSlug('x'), 'my-app');
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------ full flow ------------------------------- */
|
||||
|
||||
interface Call {
|
||||
method: string;
|
||||
path: string;
|
||||
auth: string | null;
|
||||
body: unknown;
|
||||
}
|
||||
|
||||
function memoryIo(
|
||||
files: Record<string, string>,
|
||||
handler: (call: Call) => { status: number; body: unknown },
|
||||
env: Record<string, string> = {},
|
||||
) {
|
||||
const calls: Call[] = [];
|
||||
const runs: string[] = [];
|
||||
const io: InitIo = {
|
||||
cwd: ROOT,
|
||||
env,
|
||||
fetch: (async (url: string | URL | Request, init?: RequestInit) => {
|
||||
const target = new URL(String(url));
|
||||
const headers = new Headers(init?.headers);
|
||||
const call: Call = {
|
||||
method: init?.method ?? 'GET',
|
||||
path: target.pathname,
|
||||
auth: headers.get('authorization'),
|
||||
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
||||
};
|
||||
calls.push(call);
|
||||
const answer = handler(call);
|
||||
return new Response(JSON.stringify(answer.body), { status: answer.status });
|
||||
}) as typeof fetch,
|
||||
readFile: (path) => files[path] ?? null,
|
||||
writeFile: (path, contents) => {
|
||||
files[path] = contents;
|
||||
},
|
||||
exists: (path) => path in files || Object.keys(files).some((file) => file.startsWith(`${path}/`)),
|
||||
run: (command, args) => {
|
||||
runs.push(`${command} ${args.join(' ')}`);
|
||||
return { ok: true, output: '' };
|
||||
},
|
||||
sleep: async () => {},
|
||||
log: () => {},
|
||||
credentials: () => ({}),
|
||||
};
|
||||
return { io, calls, runs, files };
|
||||
}
|
||||
|
||||
const KEYS = {
|
||||
api_url: 'https://tmp-abc-my-app-production.scribase.app',
|
||||
anon_key: 'eyJanon',
|
||||
service_role_key: 'eyJservice',
|
||||
};
|
||||
|
||||
describe('init --temp', () => {
|
||||
it('creates a temporary project, writes Next.js env vars, the client and installs supabase-js', async () => {
|
||||
let polls = 0;
|
||||
const { io, calls, runs, files } = memoryIo(
|
||||
{ [`${ROOT}/package.json`]: JSON.stringify({ name: 'shop', dependencies: { next: '15' } }), [`${ROOT}/tsconfig.json`]: '{}' },
|
||||
(call) => {
|
||||
if (call.path === '/v1/temporary-projects/challenge') {
|
||||
return { status: 200, body: { challenge: '9999999999.aa.bb', bits: 4 } };
|
||||
}
|
||||
if (call.path === '/v1/temporary-projects' && call.method === 'POST') {
|
||||
return {
|
||||
status: 201,
|
||||
body: {
|
||||
id: 'tmp_0123456789abcdef01234567',
|
||||
organization_id: 'tmp-0123456789abcdef01234567',
|
||||
project_id: 'shop',
|
||||
environment_id: 'production',
|
||||
agent_token: 'scb_agt_secret',
|
||||
claim_url: 'https://console.scribase.com/claim/tmp_0123456789abcdef01234567#scb_claim_x',
|
||||
expires_at: 1_900_000_000,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (call.path === '/v1/temporary-projects/tmp_0123456789abcdef01234567') {
|
||||
polls += 1;
|
||||
return polls < 2
|
||||
? { status: 200, body: { status: 'provisioning', keys: null } }
|
||||
: { status: 200, body: { status: 'ready', keys: KEYS } };
|
||||
}
|
||||
return { status: 404, body: { code: 'not_found' } };
|
||||
},
|
||||
);
|
||||
const result = await runInit(parseInitArgs(['--temp', '--yes', '--json', '--name', 'shop']), io);
|
||||
|
||||
assert.equal(result.framework, 'next');
|
||||
assert.equal(result.temporary, true);
|
||||
assert.equal(result.api_url, KEYS.api_url);
|
||||
assert.equal(result.claim_url, 'https://console.scribase.com/claim/tmp_0123456789abcdef01234567#scb_claim_x');
|
||||
assert.equal(result.client_file, 'lib/supabase.ts');
|
||||
assert.equal(result.installed, true);
|
||||
assert.deepEqual(runs, ['npm install @supabase/supabase-js --no-audit --no-fund']);
|
||||
|
||||
// The first next step works on an empty database: it creates the table
|
||||
// the second step queries. No step reads a table nobody created.
|
||||
assert.match(result.next_steps[0] ?? '', /^create your first table .*npx scribase sql "create table notes /);
|
||||
assert.match(result.next_steps[1] ?? '', /supabase\.from\('notes'\)\.select\(\)/);
|
||||
assert.ok(result.next_steps.every((step) => !/todos/.test(step)), 'no step queries a table that does not exist');
|
||||
|
||||
const create = calls.find((call) => call.path === '/v1/temporary-projects');
|
||||
const body = create?.body as { challenge: string; nonce: string; name: string };
|
||||
assert.equal(body.name, 'shop');
|
||||
const digest = createHash('sha256').update(`${body.challenge}:${body.nonce}`).digest();
|
||||
assert.ok(leadingZeroBits(digest) >= 4, 'the nonce solves the challenge');
|
||||
assert.equal(create?.auth, null, 'creation is anonymous');
|
||||
assert.ok(calls.filter((call) => call.path.startsWith('/v1/temporary-projects/tmp_')).every((call) => call.auth === 'Bearer scb_agt_secret'));
|
||||
|
||||
const env = files[`${ROOT}/.env.local`] ?? '';
|
||||
assert.equal(readEnvValue(env, 'NEXT_PUBLIC_SUPABASE_URL'), KEYS.api_url);
|
||||
assert.equal(readEnvValue(env, 'NEXT_PUBLIC_SUPABASE_ANON_KEY'), KEYS.anon_key);
|
||||
assert.equal(readEnvValue(env, 'SUPABASE_SERVICE_ROLE_KEY'), KEYS.service_role_key);
|
||||
assert.equal(readEnvValue(env, 'SCRIBASE_ACCESS_TOKEN'), 'scb_agt_secret');
|
||||
assert.match(files[`${ROOT}/.gitignore`] ?? '', /\.env\.local/);
|
||||
assert.match(files[`${ROOT}/.gitignore`] ?? '', /^\.scribase\/$/m, 'the claim link is never committed');
|
||||
assert.match(files[`${ROOT}/lib/supabase.ts`] ?? '', /createClient\(process\.env\.NEXT_PUBLIC_SUPABASE_URL!/);
|
||||
const state = JSON.parse(files[`${ROOT}/.scribase/project.json`] ?? '{}') as Record<string, unknown>;
|
||||
assert.equal(state.temporary, true);
|
||||
assert.equal(state.agent_token, undefined, 'no secret in the state file');
|
||||
});
|
||||
|
||||
it('detects a SvelteKit project and writes $env/static/public-style env vars plus a real service-role key', async () => {
|
||||
let polls = 0;
|
||||
const { io, files } = memoryIo(
|
||||
{
|
||||
[`${ROOT}/package.json`]: JSON.stringify({ name: 'shop', devDependencies: { '@sveltejs/kit': '2', vite: '6' } }),
|
||||
[`${ROOT}/svelte.config.js`]: 'export default {};\n',
|
||||
[`${ROOT}/tsconfig.json`]: '{}',
|
||||
},
|
||||
(call) => {
|
||||
if (call.path === '/v1/temporary-projects/challenge') {
|
||||
return { status: 200, body: { challenge: '9999999999.aa.bb', bits: 4 } };
|
||||
}
|
||||
if (call.path === '/v1/temporary-projects' && call.method === 'POST') {
|
||||
return {
|
||||
status: 201,
|
||||
body: {
|
||||
id: 'tmp_0123456789abcdef01234567',
|
||||
organization_id: 'tmp-0123456789abcdef01234567',
|
||||
project_id: 'shop',
|
||||
environment_id: 'production',
|
||||
agent_token: 'scb_agt_secret',
|
||||
claim_url: 'https://console.scribase.com/claim/tmp_0123456789abcdef01234567#scb_claim_x',
|
||||
expires_at: 1_900_000_000,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (call.path === '/v1/temporary-projects/tmp_0123456789abcdef01234567') {
|
||||
polls += 1;
|
||||
return polls < 2 ? { status: 200, body: { status: 'provisioning', keys: null } } : { status: 200, body: { status: 'ready', keys: KEYS } };
|
||||
}
|
||||
return { status: 404, body: { code: 'not_found' } };
|
||||
},
|
||||
);
|
||||
const result = await runInit(parseInitArgs(['--temp', '--yes', '--json', '--name', 'shop']), io);
|
||||
|
||||
assert.equal(result.framework, 'sveltekit');
|
||||
assert.equal(result.env_file, '.env');
|
||||
assert.equal(result.client_file, 'src/lib/supabase.ts');
|
||||
|
||||
const env = files[`${ROOT}/.env`] ?? '';
|
||||
assert.equal(readEnvValue(env, 'PUBLIC_SUPABASE_URL'), KEYS.api_url);
|
||||
assert.equal(readEnvValue(env, 'PUBLIC_SUPABASE_ANON_KEY'), KEYS.anon_key);
|
||||
// Unlike Vite/Expo, SvelteKit has a real server, so the temporary
|
||||
// project's service-role key is written (never to a PUBLIC_ variable).
|
||||
assert.equal(readEnvValue(env, 'SUPABASE_SERVICE_ROLE_KEY'), KEYS.service_role_key);
|
||||
assert.match(files[`${ROOT}/.gitignore`] ?? '', /^\.env$/m);
|
||||
|
||||
const client = files[`${ROOT}/src/lib/supabase.ts`] ?? '';
|
||||
assert.match(client, /import \{ PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY \} from '\$env\/static\/public';/);
|
||||
assert.match(client, /createClient\(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY\);/);
|
||||
});
|
||||
|
||||
it('prints the project URL and the claim link before the client install starts (SG-D8)', async () => {
|
||||
const timeline: string[] = [];
|
||||
const { io } = memoryIo(
|
||||
{ [`${ROOT}/package.json`]: JSON.stringify({ name: 'shop', dependencies: { next: '15' } }) },
|
||||
(call) => {
|
||||
if (call.path === '/v1/temporary-projects/challenge') return { status: 200, body: { challenge: '9999999999.aa.bb', bits: 4 } };
|
||||
if (call.path === '/v1/temporary-projects' && call.method === 'POST') {
|
||||
return {
|
||||
status: 201,
|
||||
body: {
|
||||
id: 'tmp_0123456789abcdef01234567',
|
||||
organization_id: 'tmp-0123456789abcdef01234567',
|
||||
project_id: 'shop',
|
||||
environment_id: 'production',
|
||||
agent_token: 'scb_agt_secret',
|
||||
claim_url: 'https://console.scribase.com/claim/tmp_0123456789abcdef01234567#scb_claim_x',
|
||||
expires_at: 1_900_000_000,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (call.path === '/v1/temporary-projects/tmp_0123456789abcdef01234567') return { status: 200, body: { status: 'ready', keys: KEYS } };
|
||||
return { status: 404, body: {} };
|
||||
},
|
||||
);
|
||||
const logged: InitIo = {
|
||||
...io,
|
||||
log: (line: string) => timeline.push(`log ${line}`),
|
||||
run: (command, args, cwd) => {
|
||||
timeline.push(`run ${command}`);
|
||||
return io.run(command, args, cwd);
|
||||
},
|
||||
};
|
||||
await runInit(parseInitArgs(['--temp', '--yes', '--name', 'shop']), logged);
|
||||
const urlAt = timeline.findIndex((entry) => entry.startsWith('log ') && entry.includes(KEYS.api_url));
|
||||
const claimAt = timeline.findIndex((entry) => entry.startsWith('log ') && entry.includes('/claim/tmp_0123456789abcdef01234567'));
|
||||
const installAt = timeline.findIndex((entry) => entry.startsWith('run '));
|
||||
assert.ok(urlAt >= 0, `the URL is printed: ${timeline.join(' | ')}`);
|
||||
assert.ok(claimAt >= 0, `the claim link is printed: ${timeline.join(' | ')}`);
|
||||
assert.ok(installAt > urlAt && installAt > claimAt, `both come before the install: ${timeline.join(' | ')}`);
|
||||
assert.ok(!timeline.some((entry) => entry.includes('scb_agt_secret')), 'the agent token is never printed');
|
||||
});
|
||||
|
||||
it('sends the signed-in token with --temp so limits count per account (SX-D5)', async () => {
|
||||
const { io, calls } = memoryIo({}, (call) => {
|
||||
if (call.path === '/v1/temporary-projects/challenge') return { status: 200, body: { challenge: '9999999999.aa.bb', bits: 1 } };
|
||||
return { status: 503, body: { code: 'temporary_projects_disabled' } };
|
||||
}, { SCRIBASE_ACCESS_TOKEN: 'scb_pat_person' });
|
||||
await assert.rejects(runInit(parseInitArgs(['--temp', '--yes']), io));
|
||||
const create = calls.find((call) => call.path === '/v1/temporary-projects');
|
||||
assert.equal(create?.auth, 'Bearer scb_pat_person');
|
||||
});
|
||||
|
||||
it('asks for a region id that names no hosting provider', async () => {
|
||||
const { io, calls } = memoryIo({}, () => ({ status: 503, body: { code: 'temporary_projects_disabled' } }));
|
||||
await assert.rejects(runInit(parseInitArgs(['--temp', '--yes']), io));
|
||||
const text = JSON.stringify(calls);
|
||||
assert.ok(!/oci|oracle|hetzner|contabo|aws|gcp|azure/i.test(text), text);
|
||||
assert.equal(DEFAULT_REGION, 'eu-frankfurt');
|
||||
});
|
||||
|
||||
it('reuses the directory’s temporary project on a second run', async () => {
|
||||
const files: Record<string, string> = {
|
||||
[`${ROOT}/package.json`]: JSON.stringify({ dependencies: { vite: '6', '@supabase/supabase-js': '2' } }),
|
||||
[`${ROOT}/.env.local`]: 'SCRIBASE_ACCESS_TOKEN=scb_agt_kept\n',
|
||||
[`${ROOT}/.scribase/project.json`]: JSON.stringify({
|
||||
organization_id: 'tmp-1',
|
||||
project_id: 'shop',
|
||||
environment_id: 'production',
|
||||
api_url: 'https://api.scribase.com',
|
||||
temporary: true,
|
||||
claim_url: 'https://console.scribase.com/claim/x#y',
|
||||
}),
|
||||
};
|
||||
const { io, calls, runs } = memoryIo(files, (call) => {
|
||||
if (call.path.endsWith('/environments/production')) return { status: 200, body: { phase: 'ready' } };
|
||||
if (call.path.endsWith('/api-keys')) return { status: 200, body: KEYS };
|
||||
return { status: 500, body: {} };
|
||||
});
|
||||
const result = await runInit(parseInitArgs(['--temp', '--json']), io);
|
||||
assert.equal(result.reused, true);
|
||||
assert.equal(result.framework, 'vite');
|
||||
assert.ok(calls.every((call) => call.auth === 'Bearer scb_agt_kept'));
|
||||
assert.ok(!calls.some((call) => call.path === '/v1/temporary-projects'), 'no new project');
|
||||
assert.deepEqual(runs, [], 'supabase-js already installed');
|
||||
assert.equal(readEnvValue(files[`${ROOT}/.env.local`] ?? '', 'VITE_SUPABASE_ANON_KEY'), KEYS.anon_key);
|
||||
assert.equal(readEnvValue(files[`${ROOT}/.env.local`] ?? '', 'SUPABASE_SERVICE_ROLE_KEY'), undefined);
|
||||
});
|
||||
|
||||
it('reports a disabled deployment as a coded error with a next step', async () => {
|
||||
const { io } = memoryIo({}, () => ({
|
||||
status: 503,
|
||||
body: { code: 'temporary_projects_disabled', detail: 'temporary projects are not enabled' },
|
||||
}));
|
||||
await assert.rejects(runInit(parseInitArgs(['--temp', '--yes']), io), (error: unknown) => {
|
||||
assert.ok(error instanceof InitError);
|
||||
assert.equal(error.code, 'temporary_projects_disabled');
|
||||
assert.ok(error.next);
|
||||
return true;
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('init with an account', () => {
|
||||
it('creates the project and production environment, then writes Expo variables', async () => {
|
||||
let envReads = 0;
|
||||
const { io, calls, files } = memoryIo(
|
||||
{ [`${ROOT}/package.json`]: JSON.stringify({ dependencies: { expo: '52', '@supabase/supabase-js': '2' } }) },
|
||||
(call) => {
|
||||
if (call.path === '/v1/organizations') return { status: 200, body: { items: [{ organization_id: 'acme' }] } };
|
||||
if (call.path === '/v1/organizations/acme/projects/mobile' && call.method === 'PUT') return { status: 200, body: {} };
|
||||
if (call.path === '/v1/environments') return { status: 202, body: { id: 'op-1' } };
|
||||
if (call.path.endsWith('/environments/production')) {
|
||||
envReads += 1;
|
||||
return { status: 200, body: { phase: envReads > 1 ? 'ready' : 'provisioning' } };
|
||||
}
|
||||
if (call.path.endsWith('/api-keys')) return { status: 200, body: KEYS };
|
||||
return { status: 404, body: {} };
|
||||
},
|
||||
{ SCRIBASE_ACCESS_TOKEN: 'scb_pat_user', SCRIBASE_API_URL: 'https://api.example.com/' },
|
||||
);
|
||||
const result = await runInit(parseInitArgs(['--yes', '--name', 'mobile']), io);
|
||||
assert.equal(result.framework, 'expo');
|
||||
assert.equal(result.temporary, false);
|
||||
assert.equal(result.organization_id, 'acme');
|
||||
const env = files[`${ROOT}/.env`] ?? '';
|
||||
assert.equal(readEnvValue(env, 'EXPO_PUBLIC_SUPABASE_URL'), KEYS.api_url);
|
||||
assert.equal(readEnvValue(env, 'SUPABASE_SERVICE_ROLE_KEY'), undefined, 'never in an app bundle');
|
||||
assert.equal(readEnvValue(env, 'SCRIBASE_API_URL'), 'https://api.example.com');
|
||||
const createEnv = calls.find((call) => call.path === '/v1/environments');
|
||||
assert.deepEqual(createEnv?.body, {
|
||||
organization_id: 'acme',
|
||||
project_id: 'mobile',
|
||||
environment_id: 'production',
|
||||
kind: 'production',
|
||||
data_mode: 'schema_only',
|
||||
region: 'eu-frankfurt',
|
||||
postgres_major: 17,
|
||||
});
|
||||
assert.ok(calls.every((call) => call.auth === 'Bearer scb_pat_user'));
|
||||
});
|
||||
|
||||
it('turns a card requirement into a clear next step', async () => {
|
||||
const { io } = memoryIo({}, (call) =>
|
||||
call.path === '/v1/organizations'
|
||||
? { status: 200, body: { items: [{ organization_id: 'acme' }] } }
|
||||
: { status: 402, body: { code: 'card_required', detail: 'add a card to start' } },
|
||||
{ SCRIBASE_ACCESS_TOKEN: 'scb_pat_user' },
|
||||
);
|
||||
await assert.rejects(runInit(parseInitArgs(['--yes']), io), (error: unknown) => {
|
||||
assert.ok(error instanceof InitError);
|
||||
assert.equal(error.code, 'card_required');
|
||||
assert.match(error.next ?? '', /card/);
|
||||
assert.match(error.next ?? '', /https:\/\/console\.scribase\.com\/start/);
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
it('asks the person to approve a billable project and sends the amount they approved (SB4)', async () => {
|
||||
const puts: unknown[] = [];
|
||||
const { io } = memoryIo({}, (call) => {
|
||||
if (call.path === '/v1/organizations') return { status: 200, body: { items: [{ organization_id: 'acme' }] } };
|
||||
if (call.method === 'PUT') {
|
||||
puts.push(call.body);
|
||||
return {
|
||||
status: 402,
|
||||
body: {
|
||||
code: 'confirm_billable',
|
||||
detail: "creating this project adds $25 to this month's bill (monthly_delta_cents 2500).",
|
||||
},
|
||||
};
|
||||
}
|
||||
return { status: 404, body: {} };
|
||||
}, { SCRIBASE_ACCESS_TOKEN: 'scb_agt_x' });
|
||||
await assert.rejects(runInit(parseInitArgs(['--yes', '--name', 'shop']), io), (error: unknown) => {
|
||||
assert.ok(error instanceof InitError);
|
||||
assert.equal(error.code, 'confirm_billable');
|
||||
assert.match(error.next ?? '', /adds \$25 a month/);
|
||||
assert.match(error.next ?? '', /--confirm-billable 2500/);
|
||||
return true;
|
||||
});
|
||||
// --yes alone never confirms money.
|
||||
assert.equal((puts[0] as Record<string, unknown>).confirm_billable_cents, undefined);
|
||||
await assert.rejects(runInit(parseInitArgs(['--name', 'shop', '--confirm-billable', '2500']), io));
|
||||
assert.equal((puts[1] as Record<string, unknown>).confirm_billable_cents, 2500);
|
||||
});
|
||||
|
||||
it('names the way out of the other billing refusals', () => {
|
||||
const consoleUrl = 'https://console.scribase.com';
|
||||
assert.match(billingNextStep({ code: 'spend_cap_reached', detail: '' }, consoleUrl), /spend cap/);
|
||||
assert.match(billingNextStep({ code: 'plan_project_cap', detail: '' }, consoleUrl), /switch plans/);
|
||||
assert.match(billingNextStep({ code: 'agent_project_limit', detail: '' }, consoleUrl), /agent project limit/);
|
||||
assert.match(billingNextStep({ code: 'card_required', detail: '' }, consoleUrl), /\/start/);
|
||||
assert.throws(() => parseInitArgs(['--confirm-billable', 'lots']));
|
||||
});
|
||||
|
||||
it('points card_required at the console that matches the API origin', () => {
|
||||
assert.equal(consoleUrlFor('https://api.scribase.com', {}), 'https://console.scribase.com');
|
||||
assert.equal(consoleUrlFor('https://api.example.com', {}), 'https://console.example.com');
|
||||
assert.equal(consoleUrlFor('http://127.0.0.1:8080', {}), 'https://console.scribase.com');
|
||||
assert.equal(consoleUrlFor('https://api.example.com', { SCRIBASE_CONSOLE_URL: 'https://c.example.com/' }), 'https://c.example.com');
|
||||
});
|
||||
|
||||
it('without a token and without --account, creates a temporary project (temporary-first)', async () => {
|
||||
const { io, calls } = memoryIo({}, (call) => {
|
||||
if (call.path === '/v1/temporary-projects/challenge') return { status: 200, body: { challenge: 'c', bits: 0 } };
|
||||
if (call.path === '/v1/temporary-projects') return { status: 503, body: { code: 'temporary_projects_disabled', detail: 'off' } };
|
||||
return { status: 500, body: {} };
|
||||
});
|
||||
await assert.rejects(runInit(parseInitArgs([]), io), (error: unknown) => {
|
||||
assert.ok(error instanceof InitError);
|
||||
assert.equal(error.code, 'temporary_projects_disabled');
|
||||
return true;
|
||||
});
|
||||
assert.ok(calls.some((call) => call.path === '/v1/temporary-projects'), 'went for a temporary project');
|
||||
});
|
||||
|
||||
it('with --account but no browser sign-in available, says how to sign in', async () => {
|
||||
const { io } = memoryIo({}, () => ({ status: 500, body: {} }));
|
||||
await assert.rejects(runInit(parseInitArgs(['--account']), io), (error: unknown) => {
|
||||
assert.ok(error instanceof InitError);
|
||||
assert.equal(error.code, 'not_signed_in');
|
||||
assert.match(error.next ?? '', /scribase login/);
|
||||
return true;
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('native projects (PS2.4)', () => {
|
||||
it('detects Flutter, Swift, Android and Python projects without a package.json', async () => {
|
||||
const { detectNative, nativeNextSteps } = await import('../src/cli/framework.js');
|
||||
const at = (...files: string[]) => facts(null, files);
|
||||
assert.equal(detectNative(at('pubspec.yaml')), 'flutter');
|
||||
assert.equal(detectNative(at('Package.swift')), 'swift');
|
||||
assert.equal(detectNative(at('settings.gradle.kts')), 'android');
|
||||
assert.equal(detectNative(at('build.gradle')), 'android');
|
||||
assert.equal(detectNative(at('pyproject.toml')), 'python');
|
||||
assert.equal(detectNative(at('requirements.txt')), 'python');
|
||||
assert.equal(detectNative(at()), null);
|
||||
// A JavaScript project is never native, whatever else the folder holds.
|
||||
assert.equal(detectNative(facts({ dependencies: { next: '15' } }, ['requirements.txt'])), null);
|
||||
const steps = nativeNextSteps('swift', { organization_id: 'acme', project_id: 'app', environment_id: 'production' });
|
||||
assert.ok(steps.some((step) => step.includes('https://github.com/supabase/supabase-swift.git')));
|
||||
assert.ok(steps.some((step) => step.includes('scribase gen types acme app production --lang swift')));
|
||||
assert.ok(nativeNextSteps('python', { organization_id: 'a', project_id: 'b', environment_id: 'c' }).some((step) => step.includes('pip install supabase')));
|
||||
assert.ok(nativeNextSteps('flutter', { organization_id: 'a', project_id: 'b', environment_id: 'c' }).some((step) => step.includes('flutter pub add supabase_flutter')));
|
||||
assert.ok(nativeNextSteps('android', { organization_id: 'a', project_id: 'b', environment_id: 'c' }).some((step) => step.includes('io.github.jan-tennert.supabase')));
|
||||
});
|
||||
});
|
||||
|
||||
describe('init in a native project (PS2.4)', () => {
|
||||
it('a Flutter folder gets the project and the env file, no JavaScript client and no npm install', async () => {
|
||||
let polls = 0;
|
||||
const { io, runs, files } = memoryIo({ [`${ROOT}/pubspec.yaml`]: 'name: app\n' }, (call) => {
|
||||
if (call.path === '/v1/temporary-projects/challenge') return { status: 200, body: { challenge: '9999999999.aa.bb', bits: 4 } };
|
||||
if (call.path === '/v1/temporary-projects' && call.method === 'POST') {
|
||||
return {
|
||||
status: 201,
|
||||
body: {
|
||||
id: 'tmp_0123456789abcdef01234567',
|
||||
organization_id: 'tmp-0123456789abcdef01234567',
|
||||
project_id: 'app',
|
||||
environment_id: 'production',
|
||||
agent_token: 'scb_agt_secret',
|
||||
expires_at: 1_900_000_000,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (call.path === '/v1/temporary-projects/tmp_0123456789abcdef01234567') {
|
||||
polls += 1;
|
||||
return polls < 2 ? { status: 200, body: { status: 'provisioning', keys: null } } : { status: 200, body: { status: 'ready', keys: KEYS } };
|
||||
}
|
||||
return { status: 404, body: { code: 'not_found' } };
|
||||
});
|
||||
const result = await runInit(parseInitArgs(['--temp', '--yes', '--json', '--name', 'app']), io);
|
||||
assert.equal(result.client_file, null);
|
||||
assert.deepEqual(runs, []);
|
||||
assert.equal(readEnvValue(files[`${ROOT}/.env`] ?? '', 'SUPABASE_URL'), KEYS.api_url);
|
||||
assert.ok(result.next_steps.some((step) => step.includes('flutter pub add supabase_flutter')));
|
||||
assert.ok(result.next_steps.some((step) => step.includes('--lang dart')));
|
||||
assert.ok(!result.next_steps.some((step) => step.includes('npm init')));
|
||||
});
|
||||
});
|
||||
450
tests/client.test.ts
Normal file
450
tests/client.test.ts
Normal file
@ -0,0 +1,450 @@
|
||||
/**
|
||||
* Tests for ScribaseClient — construction, URL building, header injection,
|
||||
* success/error decoding, and retry logic. All tests use an injected `fetch`
|
||||
* function so no network is required.
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { ScribaseClient } from '../src/client.js';
|
||||
import {
|
||||
ScribaseApiError,
|
||||
BadRequestError,
|
||||
UnauthorizedError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
QuotaExceededError,
|
||||
ServiceUnavailableError,
|
||||
NetworkError,
|
||||
TimeoutError,
|
||||
} from '../src/errors.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Build a mock `fetch` that returns a fixed JSON body with the given status. */
|
||||
function stubFetch(
|
||||
status: number,
|
||||
body: unknown,
|
||||
headers?: Record<string, string>
|
||||
): typeof fetch {
|
||||
return async (_url: string | URL | Request, _init?: RequestInit): Promise<Response> => {
|
||||
const bodyStr = body === undefined ? '' : JSON.stringify(body);
|
||||
const responseHeaders: Record<string, string> = {
|
||||
'content-type': 'application/json',
|
||||
...headers,
|
||||
};
|
||||
return new Response(bodyStr, { status, headers: responseHeaders });
|
||||
};
|
||||
}
|
||||
|
||||
/** Build a mock fetch that throws a network error. */
|
||||
function throwingFetch(message: string): typeof fetch {
|
||||
return async (): Promise<Response> => {
|
||||
throw new Error(message);
|
||||
};
|
||||
}
|
||||
|
||||
/** A no-op sleep for testing retry logic without actual delays. */
|
||||
const noSleep = async (_ms: number): Promise<void> => {};
|
||||
|
||||
function makeClient(fetchFn: typeof fetch, opts?: { timeoutMs?: number; maxRetries?: number }) {
|
||||
return new ScribaseClient({
|
||||
baseUrl: 'https://api.example.com',
|
||||
token: 'test-token',
|
||||
fetch: fetchFn,
|
||||
timeoutMs: opts?.timeoutMs ?? 5_000,
|
||||
maxRetries: opts?.maxRetries ?? 0,
|
||||
sleep: noSleep,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Construction
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('ScribaseClient construction', () => {
|
||||
it('accepts a valid https URL', () => {
|
||||
assert.doesNotThrow(() =>
|
||||
makeClient(stubFetch(200, {}))
|
||||
);
|
||||
});
|
||||
|
||||
it('accepts a valid http URL (non-TLS deployment)', () => {
|
||||
assert.doesNotThrow(() =>
|
||||
new ScribaseClient({
|
||||
baseUrl: 'http://localhost:8080',
|
||||
token: 'tok',
|
||||
fetch: stubFetch(200, {}),
|
||||
sleep: noSleep,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects an invalid URL', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
new ScribaseClient({
|
||||
baseUrl: 'not-a-url',
|
||||
token: 'tok',
|
||||
fetch: stubFetch(200, {}),
|
||||
sleep: noSleep,
|
||||
}),
|
||||
TypeError
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a non-http(s) scheme', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
new ScribaseClient({
|
||||
baseUrl: 'ftp://example.com',
|
||||
token: 'tok',
|
||||
fetch: stubFetch(200, {}),
|
||||
sleep: noSleep,
|
||||
}),
|
||||
TypeError
|
||||
);
|
||||
});
|
||||
|
||||
it('strips trailing slashes from baseUrl', async () => {
|
||||
let capturedUrl = '';
|
||||
const spy: typeof fetch = async (url, _init) => {
|
||||
capturedUrl = url as string;
|
||||
return new Response(JSON.stringify({ environments: [] }), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
};
|
||||
const client = new ScribaseClient({
|
||||
baseUrl: 'https://api.example.com///',
|
||||
token: 'tok',
|
||||
fetch: spy,
|
||||
sleep: noSleep,
|
||||
});
|
||||
await client.environments.list({ organizationId: 'org-1' });
|
||||
assert.ok(!capturedUrl.includes('///'), 'URL should not have triple slash');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Successful responses
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('ScribaseClient.send — success path', () => {
|
||||
it('returns parsed JSON for a 200 response', async () => {
|
||||
const payload = { environments: [{ environment_id: 'env-1' }] };
|
||||
const client = makeClient(stubFetch(200, payload));
|
||||
|
||||
const result = await client.send<typeof payload>({ method: 'GET', path: '/v1/test' });
|
||||
assert.deepEqual(result.data, payload);
|
||||
assert.equal(result.status, 200);
|
||||
assert.equal(result.idempotencyReplayed, false);
|
||||
});
|
||||
|
||||
it('detects an idempotency-replayed header', async () => {
|
||||
const client = makeClient(
|
||||
stubFetch(200, { ok: true }, { 'idempotency-replayed': 'true' })
|
||||
);
|
||||
const result = await client.send<{ ok: boolean }>({ method: 'GET', path: '/v1/test' });
|
||||
assert.equal(result.idempotencyReplayed, true);
|
||||
});
|
||||
|
||||
it('handles a 204 no-content response', async () => {
|
||||
const fetchFn: typeof fetch = async () =>
|
||||
new Response(null, { status: 204 });
|
||||
const client = makeClient(fetchFn);
|
||||
const result = await client.send<undefined>({
|
||||
method: 'DELETE',
|
||||
path: '/v1/test',
|
||||
expectNoContent: true,
|
||||
});
|
||||
assert.equal(result.status, 204);
|
||||
assert.equal(result.data, undefined);
|
||||
});
|
||||
|
||||
it('attaches the authorization header', async () => {
|
||||
let capturedHeaders: Headers | undefined;
|
||||
const spy: typeof fetch = async (_url, init) => {
|
||||
capturedHeaders = new Headers(init?.headers as HeadersInit);
|
||||
return new Response('{}', {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
};
|
||||
const client = new ScribaseClient({
|
||||
baseUrl: 'https://api.example.com',
|
||||
token: 'my-secret-token',
|
||||
fetch: spy,
|
||||
sleep: noSleep,
|
||||
});
|
||||
await client.send({ method: 'GET', path: '/v1/test' });
|
||||
assert.equal(capturedHeaders?.get('authorization'), 'Bearer my-secret-token');
|
||||
});
|
||||
|
||||
it('resolves an async token provider', async () => {
|
||||
let capturedAuth = '';
|
||||
const spy: typeof fetch = async (_url, init) => {
|
||||
const h = new Headers(init?.headers as HeadersInit);
|
||||
capturedAuth = h.get('authorization') ?? '';
|
||||
return new Response('{}', {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
};
|
||||
const client = new ScribaseClient({
|
||||
baseUrl: 'https://api.example.com',
|
||||
token: async () => 'async-token',
|
||||
fetch: spy,
|
||||
sleep: noSleep,
|
||||
});
|
||||
await client.send({ method: 'GET', path: '/v1/test' });
|
||||
assert.equal(capturedAuth, 'Bearer async-token');
|
||||
});
|
||||
|
||||
it('serializes the request body as JSON and sets content-type', async () => {
|
||||
let capturedInit: RequestInit | undefined;
|
||||
const spy: typeof fetch = async (_url, init) => {
|
||||
capturedInit = init;
|
||||
return new Response('{}', {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
};
|
||||
const client = makeClient(spy);
|
||||
await client.send({ method: 'POST', path: '/v1/test', body: { foo: 'bar' } });
|
||||
assert.equal(capturedInit?.body, JSON.stringify({ foo: 'bar' }));
|
||||
const h = new Headers(capturedInit?.headers as HeadersInit);
|
||||
assert.equal(h.get('content-type'), 'application/json');
|
||||
});
|
||||
|
||||
it('attaches the idempotency key header when provided', async () => {
|
||||
let capturedKey = '';
|
||||
const spy: typeof fetch = async (_url, init) => {
|
||||
const h = new Headers(init?.headers as HeadersInit);
|
||||
capturedKey = h.get('idempotency-key') ?? '';
|
||||
return new Response('{}', {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
};
|
||||
const client = makeClient(spy);
|
||||
await client.send({
|
||||
method: 'POST',
|
||||
path: '/v1/test',
|
||||
body: {},
|
||||
idempotencyKey: 'my-idem-key',
|
||||
});
|
||||
assert.equal(capturedKey, 'my-idem-key');
|
||||
});
|
||||
|
||||
it('appends query parameters to the URL', async () => {
|
||||
let capturedUrl = '';
|
||||
const spy: typeof fetch = async (url) => {
|
||||
capturedUrl = url as string;
|
||||
return new Response('{}', {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
};
|
||||
const client = makeClient(spy);
|
||||
await client.send({
|
||||
method: 'GET',
|
||||
path: '/v1/test',
|
||||
query: { organization_id: 'org-1', limit: 10 },
|
||||
});
|
||||
const u = new URL(capturedUrl);
|
||||
assert.equal(u.searchParams.get('organization_id'), 'org-1');
|
||||
assert.equal(u.searchParams.get('limit'), '10');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Error decoding
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('ScribaseClient.send — error decoding', () => {
|
||||
const problem = (status: number, code: string) => ({
|
||||
type: 'about:blank',
|
||||
title: 'Error',
|
||||
status,
|
||||
code,
|
||||
});
|
||||
|
||||
it('throws BadRequestError for 400', async () => {
|
||||
const client = makeClient(stubFetch(400, problem(400, 'bad_request')));
|
||||
await assert.rejects(
|
||||
() => client.send({ method: 'GET', path: '/v1/test' }),
|
||||
BadRequestError
|
||||
);
|
||||
});
|
||||
|
||||
it('throws UnauthorizedError for 401', async () => {
|
||||
const client = makeClient(stubFetch(401, problem(401, 'unauthorized')));
|
||||
await assert.rejects(
|
||||
() => client.send({ method: 'GET', path: '/v1/test' }),
|
||||
UnauthorizedError
|
||||
);
|
||||
});
|
||||
|
||||
it('throws ForbiddenError for 403', async () => {
|
||||
const client = makeClient(stubFetch(403, problem(403, 'forbidden')));
|
||||
await assert.rejects(
|
||||
() => client.send({ method: 'GET', path: '/v1/test' }),
|
||||
ForbiddenError
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NotFoundError for 404', async () => {
|
||||
const client = makeClient(stubFetch(404, problem(404, 'not_found')));
|
||||
await assert.rejects(
|
||||
() => client.send({ method: 'GET', path: '/v1/test' }),
|
||||
NotFoundError
|
||||
);
|
||||
});
|
||||
|
||||
it('throws QuotaExceededError for 429', async () => {
|
||||
const client = makeClient(stubFetch(429, problem(429, 'quota_exceeded')));
|
||||
await assert.rejects(
|
||||
() => client.send({ method: 'GET', path: '/v1/test' }),
|
||||
QuotaExceededError
|
||||
);
|
||||
});
|
||||
|
||||
it('throws ServiceUnavailableError for 503', async () => {
|
||||
const client = makeClient(stubFetch(503, problem(503, 'service_unavailable')));
|
||||
await assert.rejects(
|
||||
() => client.send({ method: 'GET', path: '/v1/test' }),
|
||||
ServiceUnavailableError
|
||||
);
|
||||
});
|
||||
|
||||
it('synthesizes a problem for a non-JSON error body', async () => {
|
||||
const fetchFn: typeof fetch = async () =>
|
||||
new Response('Internal Server Error', {
|
||||
status: 500,
|
||||
headers: { 'content-type': 'text/plain' },
|
||||
});
|
||||
const client = makeClient(fetchFn);
|
||||
await assert.rejects(
|
||||
() => client.send({ method: 'GET', path: '/v1/test' }),
|
||||
(err: unknown) => {
|
||||
assert.ok(err instanceof ScribaseApiError);
|
||||
assert.equal(err.status, 500);
|
||||
return true;
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
it('throws NetworkError when fetch throws a non-abort error', async () => {
|
||||
const client = makeClient(throwingFetch('ECONNREFUSED'), { maxRetries: 0 });
|
||||
await assert.rejects(
|
||||
() => client.send({ method: 'GET', path: '/v1/test' }),
|
||||
NetworkError
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Retry
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('ScribaseClient — retry', () => {
|
||||
it('retries on 503 up to maxRetries times', async () => {
|
||||
let calls = 0;
|
||||
const fetchFn: typeof fetch = async () => {
|
||||
calls += 1;
|
||||
return new Response(
|
||||
JSON.stringify({ type: 'about:blank', title: 'Unavailable', status: 503, code: 'unavailable' }),
|
||||
{ status: 503, headers: { 'content-type': 'application/json' } }
|
||||
);
|
||||
};
|
||||
const client = new ScribaseClient({
|
||||
baseUrl: 'https://api.example.com',
|
||||
token: 'tok',
|
||||
fetch: fetchFn,
|
||||
maxRetries: 2,
|
||||
retryBaseDelayMs: 0,
|
||||
sleep: noSleep,
|
||||
});
|
||||
await assert.rejects(
|
||||
() => client.send({ method: 'GET', path: '/v1/test' }),
|
||||
ServiceUnavailableError
|
||||
);
|
||||
// 1 initial attempt + 2 retries
|
||||
assert.equal(calls, 3);
|
||||
});
|
||||
|
||||
it('does not retry on 404', async () => {
|
||||
let calls = 0;
|
||||
const fetchFn: typeof fetch = async () => {
|
||||
calls += 1;
|
||||
return new Response(
|
||||
JSON.stringify({ type: 'about:blank', title: 'Not Found', status: 404, code: 'not_found' }),
|
||||
{ status: 404, headers: { 'content-type': 'application/json' } }
|
||||
);
|
||||
};
|
||||
const client = new ScribaseClient({
|
||||
baseUrl: 'https://api.example.com',
|
||||
token: 'tok',
|
||||
fetch: fetchFn,
|
||||
maxRetries: 3,
|
||||
sleep: noSleep,
|
||||
});
|
||||
await assert.rejects(
|
||||
() => client.send({ method: 'GET', path: '/v1/test' }),
|
||||
NotFoundError
|
||||
);
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
it('retries on network errors', async () => {
|
||||
let calls = 0;
|
||||
const fetchFn: typeof fetch = async () => {
|
||||
calls += 1;
|
||||
throw new Error('ECONNRESET');
|
||||
};
|
||||
const client = new ScribaseClient({
|
||||
baseUrl: 'https://api.example.com',
|
||||
token: 'tok',
|
||||
fetch: fetchFn,
|
||||
maxRetries: 1,
|
||||
retryBaseDelayMs: 0,
|
||||
sleep: noSleep,
|
||||
});
|
||||
await assert.rejects(
|
||||
() => client.send({ method: 'GET', path: '/v1/test' }),
|
||||
NetworkError
|
||||
);
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// AbortSignal / cancellation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('ScribaseClient — cancellation', () => {
|
||||
it('propagates an already-aborted signal without retrying', async () => {
|
||||
let calls = 0;
|
||||
// The mock fetch honours the abort signal so the client propagation logic is exercised.
|
||||
const fetchFn: typeof fetch = async (_url, init) => {
|
||||
calls += 1;
|
||||
const signal = init?.signal;
|
||||
if (signal?.aborted) {
|
||||
throw signal.reason as Error;
|
||||
}
|
||||
return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } });
|
||||
};
|
||||
const controller = new AbortController();
|
||||
controller.abort(new Error('cancelled'));
|
||||
const client = makeClient(fetchFn, { maxRetries: 3 });
|
||||
await assert.rejects(() =>
|
||||
client.send({ method: 'GET', path: '/v1/test', signal: controller.signal })
|
||||
);
|
||||
// The abort should propagate before any retries are attempted.
|
||||
assert.ok(calls <= 1);
|
||||
});
|
||||
});
|
||||
302
tests/connect.test.ts
Normal file
302
tests/connect.test.ts
Normal file
@ -0,0 +1,302 @@
|
||||
/**
|
||||
* Tests for `npx scribase connect`: detection, idempotent JSON/TOML merges,
|
||||
* the Claude Code CLI path, --dry-run, --tool filtering, and that no token or
|
||||
* secret is ever written to any config file.
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { connectMain, formatConnect, mergeJsonServer, mergeTomlSection, parseConnectArgs, runConnect } from '../src/cli/connect.js';
|
||||
import type { ConnectIo, RunOutcome } from '../src/cli/connect.js';
|
||||
import { InitError } from '../src/cli/init.js';
|
||||
|
||||
const HOME = '/home/dev';
|
||||
const CWD = '/work/app';
|
||||
|
||||
function harness(options: {
|
||||
files?: Record<string, string>;
|
||||
which?: Record<string, boolean>;
|
||||
exists?: Record<string, boolean>;
|
||||
run?: (command: string, args: string[]) => RunOutcome;
|
||||
}) {
|
||||
const files: Record<string, string> = { ...(options.files ?? {}) };
|
||||
const runCalls: { command: string; args: string[] }[] = [];
|
||||
const io: ConnectIo = {
|
||||
cwd: CWD,
|
||||
home: HOME,
|
||||
env: {},
|
||||
readFile: (path) => files[path] ?? null,
|
||||
writeFile: (path, contents) => {
|
||||
files[path] = contents;
|
||||
},
|
||||
exists: (path) => options.exists?.[path] ?? false,
|
||||
which: (command) => options.which?.[command] ?? false,
|
||||
run: (command, args) => {
|
||||
runCalls.push({ command, args });
|
||||
return options.run?.(command, args) ?? { ok: false, output: 'not found' };
|
||||
},
|
||||
};
|
||||
return { io, files, runCalls };
|
||||
}
|
||||
|
||||
describe('parseConnectArgs', () => {
|
||||
it('defaults to auto-detect (tools: null)', () => {
|
||||
assert.deepEqual(parseConnectArgs([]), { json: false, dryRun: false, tools: null });
|
||||
});
|
||||
|
||||
it('reads --dry-run and --json', () => {
|
||||
const options = parseConnectArgs(['--dry-run', '--json']);
|
||||
assert.equal(options.dryRun, true);
|
||||
assert.equal(options.json, true);
|
||||
});
|
||||
|
||||
it('accepts positional tool names and --tool, deduped, with aliases', () => {
|
||||
const options = parseConnectArgs(['cursor', '--tool', 'claude', '--tool=vs-code', 'cursor']);
|
||||
assert.deepEqual(options.tools, ['cursor', 'claude-code', 'vscode']);
|
||||
});
|
||||
|
||||
it('rejects an unknown tool name', () => {
|
||||
assert.throws(() => parseConnectArgs(['not-a-real-tool']), InitError);
|
||||
});
|
||||
|
||||
it('rejects an unknown flag', () => {
|
||||
assert.throws(() => parseConnectArgs(['--nope']), InitError);
|
||||
});
|
||||
|
||||
it('reads --api-url', () => {
|
||||
assert.equal(parseConnectArgs(['--api-url', 'https://api.example.test']).apiUrl, 'https://api.example.test');
|
||||
});
|
||||
});
|
||||
|
||||
describe('mergeJsonServer', () => {
|
||||
it('creates a fresh file when none exists', () => {
|
||||
const result = mergeJsonServer(null, '/x/mcp.json', 'mcpServers', 'scribase', { url: 'https://api.scribase.com/mcp' });
|
||||
assert.equal(result.changed, true);
|
||||
assert.deepEqual(JSON.parse(result.content), { mcpServers: { scribase: { url: 'https://api.scribase.com/mcp' } } });
|
||||
});
|
||||
|
||||
it('preserves every other key and every other server', () => {
|
||||
const existing = JSON.stringify({ mcpServers: { other: { url: 'https://other.example/mcp' } }, unrelatedTopLevelKey: 42 });
|
||||
const result = mergeJsonServer(existing, '/x/mcp.json', 'mcpServers', 'scribase', { url: 'https://api.scribase.com/mcp' });
|
||||
assert.equal(result.changed, true);
|
||||
assert.deepEqual(JSON.parse(result.content), {
|
||||
mcpServers: { other: { url: 'https://other.example/mcp' }, scribase: { url: 'https://api.scribase.com/mcp' } },
|
||||
unrelatedTopLevelKey: 42,
|
||||
});
|
||||
});
|
||||
|
||||
it('is idempotent: an identical entry already present changes nothing', () => {
|
||||
const existing = JSON.stringify({ mcpServers: { scribase: { url: 'https://api.scribase.com/mcp' } } });
|
||||
const result = mergeJsonServer(existing, '/x/mcp.json', 'mcpServers', 'scribase', { url: 'https://api.scribase.com/mcp' });
|
||||
assert.equal(result.changed, false);
|
||||
});
|
||||
|
||||
it('is order-independent when comparing the existing entry', () => {
|
||||
const existing = JSON.stringify({ mcpServers: { scribase: { url: 'https://api.scribase.com/mcp', type: 'http' } } });
|
||||
const result = mergeJsonServer(existing, '/x/mcp.json', 'mcpServers', 'scribase', { type: 'http', url: 'https://api.scribase.com/mcp' });
|
||||
assert.equal(result.changed, false);
|
||||
});
|
||||
|
||||
it('updates a stale URL for the same entry', () => {
|
||||
const existing = JSON.stringify({ mcpServers: { scribase: { url: 'https://old.example/mcp' } } });
|
||||
const result = mergeJsonServer(existing, '/x/mcp.json', 'mcpServers', 'scribase', { url: 'https://api.scribase.com/mcp' });
|
||||
assert.equal(result.changed, true);
|
||||
assert.equal((JSON.parse(result.content).mcpServers as Record<string, { url: string }>).scribase.url, 'https://api.scribase.com/mcp');
|
||||
});
|
||||
|
||||
it('refuses to clobber a file it cannot parse', () => {
|
||||
assert.throws(() => mergeJsonServer('{ not json', '/x/mcp.json', 'mcpServers', 'scribase', { url: 'x' }), InitError);
|
||||
});
|
||||
|
||||
it('never writes a token, header or secret-shaped key', () => {
|
||||
const result = mergeJsonServer(null, '/x/mcp.json', 'mcpServers', 'scribase', { url: 'https://api.scribase.com/mcp' });
|
||||
assert.equal(/authorization|bearer|token|scb_agt_/i.test(result.content), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mergeTomlSection', () => {
|
||||
it('creates a fresh file when none exists', () => {
|
||||
const result = mergeTomlSection(null, 'mcp_servers.scribase', ['url = "https://api.scribase.com/mcp"', 'auth = "oauth"']);
|
||||
assert.equal(result.changed, true);
|
||||
assert.equal(result.content, '[mcp_servers.scribase]\nurl = "https://api.scribase.com/mcp"\nauth = "oauth"\n');
|
||||
});
|
||||
|
||||
it('appends after existing content without touching it', () => {
|
||||
const existing = '[other_table]\nkey = "value"\n';
|
||||
const result = mergeTomlSection(existing, 'mcp_servers.scribase', ['url = "https://api.scribase.com/mcp"']);
|
||||
assert.equal(result.changed, true);
|
||||
assert.equal(result.content, '[other_table]\nkey = "value"\n\n[mcp_servers.scribase]\nurl = "https://api.scribase.com/mcp"\n');
|
||||
});
|
||||
|
||||
it('is idempotent: the header already present changes nothing', () => {
|
||||
const existing = '[mcp_servers.scribase]\nurl = "https://old.example/mcp"\n';
|
||||
const result = mergeTomlSection(existing, 'mcp_servers.scribase', ['url = "https://api.scribase.com/mcp"']);
|
||||
assert.equal(result.changed, false);
|
||||
assert.equal(result.content, existing);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runConnect — detection', () => {
|
||||
it('auto mode skips every tool with no trace on this machine', () => {
|
||||
const { io } = harness({});
|
||||
const result = runConnect({ json: false, dryRun: false, tools: null }, io);
|
||||
assert.equal(result.tools.every((tool) => tool.status === 'skipped_not_detected'), true);
|
||||
assert.equal(result.tools.every((tool) => !tool.detected), true);
|
||||
});
|
||||
|
||||
it('auto mode configures only tools actually detected', () => {
|
||||
const { io, files } = harness({ which: { claude: true }, exists: { [`${HOME}/.cursor`]: true }, run: () => ({ ok: true, output: 'Added' }) });
|
||||
const result = runConnect({ json: false, dryRun: false, tools: null }, io);
|
||||
const byTool = Object.fromEntries(result.tools.map((tool) => [tool.tool, tool]));
|
||||
assert.equal(byTool['claude-code']?.status, 'configured');
|
||||
assert.equal(byTool.cursor?.status, 'configured');
|
||||
assert.equal(byTool.vscode?.status, 'skipped_not_detected');
|
||||
assert.equal(byTool.zed?.status, 'skipped_not_detected');
|
||||
assert.equal(JSON.parse(files[`${HOME}/.cursor/mcp.json`] ?? '{}').mcpServers.scribase.url, 'https://api.scribase.com/mcp');
|
||||
});
|
||||
|
||||
it('naming a tool configures it even when not detected', () => {
|
||||
const { io, files } = harness({});
|
||||
const result = runConnect({ json: false, dryRun: false, tools: ['zed'] }, io);
|
||||
assert.equal(result.tools.length, 1);
|
||||
assert.equal(result.tools[0]?.status, 'configured');
|
||||
assert.equal(JSON.parse(files[`${HOME}/.config/zed/settings.json`] ?? '{}').context_servers.scribase.url, 'https://api.scribase.com/mcp');
|
||||
});
|
||||
});
|
||||
|
||||
describe('runConnect — per-tool shapes', () => {
|
||||
it('vscode writes ./.vscode/mcp.json with the "servers" key and type "http"', () => {
|
||||
const { io, files } = harness({});
|
||||
runConnect({ json: false, dryRun: false, tools: ['vscode'] }, io);
|
||||
assert.deepEqual(JSON.parse(files[`${CWD}/.vscode/mcp.json`] ?? '{}'), { servers: { scribase: { type: 'http', url: 'https://api.scribase.com/mcp' } } });
|
||||
});
|
||||
|
||||
it('windsurf writes mcp_config.json with "serverUrl"', () => {
|
||||
const { io, files } = harness({});
|
||||
runConnect({ json: false, dryRun: false, tools: ['windsurf'] }, io);
|
||||
assert.deepEqual(JSON.parse(files[`${HOME}/.codeium/windsurf/mcp_config.json`] ?? '{}'), { mcpServers: { scribase: { serverUrl: 'https://api.scribase.com/mcp' } } });
|
||||
});
|
||||
|
||||
it('codex appends a [mcp_servers.scribase] TOML table with auth = "oauth"', () => {
|
||||
const { io, files } = harness({});
|
||||
runConnect({ json: false, dryRun: false, tools: ['codex'] }, io);
|
||||
assert.equal(files[`${HOME}/.codex/config.toml`], '[mcp_servers.scribase]\nurl = "https://api.scribase.com/mcp"\nauth = "oauth"\n');
|
||||
});
|
||||
|
||||
it('respects a custom --api-url', () => {
|
||||
const { io, files } = harness({});
|
||||
runConnect({ json: false, dryRun: false, tools: ['cursor'], apiUrl: 'https://api.example.test' }, io);
|
||||
assert.equal(JSON.parse(files[`${HOME}/.cursor/mcp.json`] ?? '{}').mcpServers.scribase.url, 'https://api.example.test/mcp');
|
||||
});
|
||||
});
|
||||
|
||||
describe('runConnect — Claude Code', () => {
|
||||
it('runs the documented claude mcp add command', () => {
|
||||
const { io, runCalls } = harness({ run: () => ({ ok: true, output: 'Added stdio MCP server scribase\n' }) });
|
||||
const result = runConnect({ json: false, dryRun: false, tools: ['claude-code'] }, io);
|
||||
assert.deepEqual(runCalls[0], { command: 'claude', args: ['mcp', 'add', '--transport', 'http', '--scope', 'user', 'scribase', 'https://api.scribase.com/mcp'] });
|
||||
assert.equal(result.tools[0]?.status, 'configured');
|
||||
});
|
||||
|
||||
it('treats "already exists" as already_configured, not a failure', () => {
|
||||
const { io } = harness({ run: () => ({ ok: false, output: 'Error: MCP server "scribase" already exists\n' }) });
|
||||
const result = runConnect({ json: false, dryRun: false, tools: ['claude-code'] }, io);
|
||||
assert.equal(result.tools[0]?.status, 'already_configured');
|
||||
});
|
||||
|
||||
it('reports a real failure without crashing the whole run', () => {
|
||||
const { io } = harness({ run: () => ({ ok: false, output: 'command not found' }) });
|
||||
const result = runConnect({ json: false, dryRun: false, tools: ['claude-code'] }, io);
|
||||
assert.equal(result.tools[0]?.status, 'failed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('runConnect — --dry-run', () => {
|
||||
it('never calls writeFile or run', () => {
|
||||
let wrote = false;
|
||||
let ran = false;
|
||||
const io: ConnectIo = {
|
||||
cwd: CWD,
|
||||
home: HOME,
|
||||
env: {},
|
||||
readFile: () => null,
|
||||
writeFile: () => {
|
||||
wrote = true;
|
||||
},
|
||||
exists: () => false,
|
||||
which: () => false,
|
||||
run: () => {
|
||||
ran = true;
|
||||
return { ok: true, output: '' };
|
||||
},
|
||||
};
|
||||
const result = runConnect({ json: false, dryRun: true, tools: ['cursor', 'claude-code'] }, io);
|
||||
assert.equal(wrote, false);
|
||||
assert.equal(ran, false);
|
||||
assert.equal(result.tools.every((tool) => tool.status === 'would_configure'), true);
|
||||
assert.equal(result.dry_run, true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runConnect — idempotency across two runs', () => {
|
||||
it('the second run reports already_configured for every tool and writes nothing new', () => {
|
||||
const { io, files } = harness({ which: { claude: true }, run: () => ({ ok: true, output: 'Added' }) });
|
||||
runConnect({ json: false, dryRun: false, tools: ['cursor', 'windsurf', 'zed', 'vscode', 'codex'] }, io);
|
||||
const snapshot = { ...files };
|
||||
const second = runConnect({ json: false, dryRun: false, tools: ['cursor', 'windsurf', 'zed', 'vscode', 'codex'] }, io);
|
||||
assert.equal(second.tools.every((tool) => tool.status === 'already_configured'), true);
|
||||
assert.deepEqual(files, snapshot);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatConnect', () => {
|
||||
it('prints the MCP url and one line per tool', () => {
|
||||
const text = formatConnect({
|
||||
ok: true,
|
||||
mcp_url: 'https://api.scribase.com/mcp',
|
||||
dry_run: false,
|
||||
tools: [
|
||||
{ tool: 'cursor', label: 'Cursor', detected: true, status: 'configured', path: '/home/dev/.cursor/mcp.json' },
|
||||
{ tool: 'zed', label: 'Zed', detected: false, status: 'skipped_not_detected' },
|
||||
],
|
||||
});
|
||||
assert.match(text, /https:\/\/api\.scribase\.com\/mcp/);
|
||||
assert.match(text, /Cursor\s+done/);
|
||||
assert.match(text, /Zed\s+not detected, skipped/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('connectMain', () => {
|
||||
it('prints JSON with --json and exits 0', () => {
|
||||
const { io } = harness({});
|
||||
const lines: string[] = [];
|
||||
const code = connectMain(['zed', '--json'], io, (text) => lines.push(text));
|
||||
assert.equal(code, 0);
|
||||
const parsed = JSON.parse(lines.join(''));
|
||||
assert.equal(parsed.ok, true);
|
||||
assert.equal(parsed.tools[0].status, 'configured');
|
||||
});
|
||||
|
||||
it('prints help and exits 0 for --help', () => {
|
||||
const { io } = harness({});
|
||||
const lines: string[] = [];
|
||||
const code = connectMain(['--help'], io, (text) => lines.push(text));
|
||||
assert.equal(code, 0);
|
||||
assert.match(lines.join(''), /Usage: npx scribase connect/);
|
||||
});
|
||||
|
||||
it('exits 1 and reports a clear error for an invalid argument', () => {
|
||||
const { io } = harness({});
|
||||
const lines: string[] = [];
|
||||
const code = connectMain(['--nope'], io, (text) => lines.push(text));
|
||||
assert.equal(code, 1);
|
||||
assert.match(lines.join(''), /unknown option/);
|
||||
});
|
||||
|
||||
it('exits 1 when a named tool fails', () => {
|
||||
const { io } = harness({ run: () => ({ ok: false, output: 'boom' }) });
|
||||
const code = connectMain(['claude-code', '--json'], io, () => {});
|
||||
assert.equal(code, 1);
|
||||
});
|
||||
});
|
||||
218
tests/front-door.test.ts
Normal file
218
tests/front-door.test.ts
Normal file
@ -0,0 +1,218 @@
|
||||
/**
|
||||
* WP 1.6 (temporary-first CLI): the measured "Live in N s", the claim link's
|
||||
* `?ref=`, `--watch` for the first request, and `scribase doctor`.
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, readFileSync, statSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
import { claimUrlWithRef, parseInitArgs, runInit } from '../src/cli/init.js';
|
||||
import type { InitIo } from '../src/cli/init.js';
|
||||
import { envEntries, formatDoctor, jwtRole, leakedSecretVars, runDoctor } from '../src/cli/doctor.js';
|
||||
import type { DoctorIo } from '../src/cli/doctor.js';
|
||||
import { installId } from '../src/cli/credentials.js';
|
||||
|
||||
const ROOT = '/work/app';
|
||||
const TMP_ID = 'tmp_0123456789abcdef01234567';
|
||||
const KEYS = { api_url: 'https://tmp-abc-shop-production.scribase.app', anon_key: 'eyJ.anon.key', service_role_key: 'eyJ.service.key' };
|
||||
|
||||
function jwt(payload: Record<string, unknown>): string {
|
||||
const part = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url');
|
||||
return `${part({ alg: 'HS256' })}.${part(payload)}.sig`;
|
||||
}
|
||||
|
||||
function temporaryIo(extra: Partial<InitIo> = {}, firstRequestAfter = 2) {
|
||||
const files: Record<string, string> = { [`${ROOT}/package.json`]: JSON.stringify({ dependencies: { next: '15', '@supabase/supabase-js': '2' } }) };
|
||||
const logs: string[] = [];
|
||||
let clock = 1_000_000;
|
||||
let watches = 0;
|
||||
const paths: string[] = [];
|
||||
const io: InitIo = {
|
||||
cwd: ROOT,
|
||||
env: {},
|
||||
fetch: (async (url: string | URL | Request, init?: RequestInit) => {
|
||||
const path = new URL(String(url)).pathname;
|
||||
paths.push(`${init?.method ?? 'GET'} ${path}`);
|
||||
const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status });
|
||||
if (path === '/v1/temporary-projects/challenge') return json(200, { challenge: 'c', bits: 0 });
|
||||
if (path === '/v1/temporary-projects') {
|
||||
return json(201, {
|
||||
id: TMP_ID,
|
||||
organization_id: 'tmp-0123456789abcdef01234567',
|
||||
project_id: 'shop',
|
||||
environment_id: 'production',
|
||||
agent_token: 'scb_agt_secret',
|
||||
claim_url: `https://console.scribase.com/claim/${TMP_ID}#scb_claim_x`,
|
||||
expires_at: 1_900_000_000,
|
||||
});
|
||||
}
|
||||
if (path === `/v1/temporary-projects/${TMP_ID}`) {
|
||||
clock += 4_200; // the database takes a while
|
||||
return json(200, { status: 'ready', keys: KEYS });
|
||||
}
|
||||
if (path.endsWith('/first-request')) {
|
||||
watches += 1;
|
||||
return json(200, { first_request_at: watches >= firstRequestAfter ? 1_800_000_000 : null });
|
||||
}
|
||||
return json(404, {});
|
||||
}) as typeof fetch,
|
||||
readFile: (path) => files[path] ?? null,
|
||||
writeFile: (path, contents) => {
|
||||
files[path] = contents;
|
||||
},
|
||||
exists: (path) => path in files,
|
||||
run: () => ({ ok: true, output: '' }),
|
||||
sleep: async (ms) => {
|
||||
clock += ms;
|
||||
},
|
||||
log: (line) => logs.push(line),
|
||||
credentials: () => ({}),
|
||||
now: () => clock,
|
||||
installId: () => 'install0123abcd',
|
||||
...extra,
|
||||
};
|
||||
return { io, files, logs, paths };
|
||||
}
|
||||
|
||||
describe('init: temporary-first front door', () => {
|
||||
it('measures "live in" seconds, adds ?ref= before the claim fragment and saves the temporary id', async () => {
|
||||
const { io, files, paths } = temporaryIo();
|
||||
const result = await runInit(parseInitArgs(['--json', '--name', 'shop']), io);
|
||||
assert.equal(result.temporary, true);
|
||||
assert.equal(result.live_in_seconds, 4.2);
|
||||
assert.equal(result.claim_url, `https://console.scribase.com/claim/${TMP_ID}?ref=install0123abcd#scb_claim_x`);
|
||||
assert.equal(result.first_request_at, undefined, 'no watch unless asked');
|
||||
assert.ok(!paths.some((path) => path.endsWith('/first-request')));
|
||||
const state = JSON.parse(files[`${ROOT}/.scribase/project.json`] ?? '{}') as Record<string, unknown>;
|
||||
assert.equal(state.temporary_id, TMP_ID);
|
||||
assert.equal(state.claim_url, result.claim_url);
|
||||
assert.ok(!JSON.stringify(result).includes('scb_agt_secret'), 'the agent token is never in the output');
|
||||
});
|
||||
|
||||
it('--watch waits for the first request and reports when it came', async () => {
|
||||
const { io, logs } = temporaryIo({}, 3);
|
||||
const result = await runInit(parseInitArgs(['--json', '--watch']), io);
|
||||
assert.equal(result.first_request_at, 1_800_000_000);
|
||||
assert.ok(logs.some((line) => /first request/.test(line)));
|
||||
});
|
||||
|
||||
it('--watch gives up after --watch-seconds with a next step, never an error', async () => {
|
||||
const { io } = temporaryIo({}, 1_000);
|
||||
const result = await runInit(parseInitArgs(['--json', '--watch-seconds', '10']), io);
|
||||
assert.equal(result.first_request_at, null);
|
||||
assert.ok(result.next_steps.some((step) => /scribase doctor/.test(step)));
|
||||
});
|
||||
|
||||
it('sends no ref when there is no install id', async () => {
|
||||
const { io } = temporaryIo({ installId: () => null });
|
||||
const result = await runInit(parseInitArgs(['--json']), io);
|
||||
assert.equal(result.claim_url, `https://console.scribase.com/claim/${TMP_ID}#scb_claim_x`);
|
||||
});
|
||||
|
||||
it('rejects --temp together with --account', () => {
|
||||
assert.throws(() => parseInitArgs(['--temp', '--account']));
|
||||
assert.equal(parseInitArgs(['--login']).account, true);
|
||||
assert.throws(() => parseInitArgs(['--watch-seconds', '0']));
|
||||
});
|
||||
});
|
||||
|
||||
describe('claimUrlWithRef', () => {
|
||||
it('puts ref in the query, before the fragment, once', () => {
|
||||
assert.equal(claimUrlWithRef('https://c/claim/x#tok', 'abcdefgh1'), 'https://c/claim/x?ref=abcdefgh1#tok');
|
||||
assert.equal(claimUrlWithRef('https://c/claim/x?a=1#tok', 'abcdefgh1'), 'https://c/claim/x?a=1&ref=abcdefgh1#tok');
|
||||
assert.equal(claimUrlWithRef('https://c/claim/x?ref=old#tok', 'abcdefgh1'), 'https://c/claim/x?ref=old#tok');
|
||||
assert.equal(claimUrlWithRef('https://c/claim/x#tok', 'bad id!'), 'https://c/claim/x#tok');
|
||||
assert.equal(claimUrlWithRef('https://c/claim/x#tok', null), 'https://c/claim/x#tok');
|
||||
});
|
||||
});
|
||||
|
||||
describe('installId', () => {
|
||||
it('creates one random id, keeps it, file mode 0600, and honours SCRIBASE_NO_REF', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'scribase-install-'));
|
||||
const env = { XDG_CONFIG_HOME: dir };
|
||||
const first = installId(env, () => 'abcdef0123456789');
|
||||
assert.equal(first, 'abcdef0123456789');
|
||||
assert.equal(installId(env, () => 'different0000000'), 'abcdef0123456789');
|
||||
const path = join(dir, 'scribase', 'install-id');
|
||||
assert.equal(readFileSync(path, 'utf8').trim(), 'abcdef0123456789');
|
||||
assert.equal(statSync(path).mode & 0o777, 0o600);
|
||||
assert.equal(installId({ ...env, SCRIBASE_NO_REF: '1' }), null);
|
||||
});
|
||||
});
|
||||
|
||||
/* --------------------------------- doctor --------------------------------- */
|
||||
|
||||
function doctorIo(files: Record<string, string>, answer: (url: string) => number | Error, now = 1_000_000_000_000): DoctorIo {
|
||||
return {
|
||||
cwd: ROOT,
|
||||
fetch: (async (url: string | URL | Request) => {
|
||||
const outcome = answer(String(url));
|
||||
if (outcome instanceof Error) throw outcome;
|
||||
return new Response('{}', { status: outcome });
|
||||
}) as typeof fetch,
|
||||
readFile: (path) => files[path] ?? null,
|
||||
exists: (path) => path in files,
|
||||
now: () => now,
|
||||
};
|
||||
}
|
||||
|
||||
const ANON = jwt({ role: 'anon' });
|
||||
const SERVICE = jwt({ role: 'service_role' });
|
||||
|
||||
describe('scribase doctor', () => {
|
||||
it('passes a healthy Next.js app and never prints key values', async () => {
|
||||
const files = {
|
||||
[`${ROOT}/package.json`]: JSON.stringify({ dependencies: { next: '15' } }),
|
||||
[`${ROOT}/.env.local`]: `NEXT_PUBLIC_SUPABASE_URL=https://x.scribase.app\nNEXT_PUBLIC_SUPABASE_ANON_KEY=${ANON}\nSUPABASE_SERVICE_ROLE_KEY=${SERVICE}\n`,
|
||||
[`${ROOT}/.gitignore`]: '.env.local\n',
|
||||
[`${ROOT}/.scribase/project.json`]: JSON.stringify({ organization_id: 'acme', project_id: 'shop', temporary: false }),
|
||||
};
|
||||
const result = await runDoctor(doctorIo(files, () => 200));
|
||||
assert.equal(result.ok, true, JSON.stringify(result.checks));
|
||||
const text = formatDoctor(result) + JSON.stringify(result);
|
||||
assert.ok(!text.includes(ANON) && !text.includes(SERVICE), 'no key values');
|
||||
assert.match(formatDoctor(result), /No problems found/);
|
||||
});
|
||||
|
||||
it('prints one fix per problem: missing key, leaked secret, not ignored, refused key', async () => {
|
||||
const files = {
|
||||
[`${ROOT}/package.json`]: JSON.stringify({ devDependencies: { vite: '6' } }),
|
||||
[`${ROOT}/.env.local`]: `VITE_SUPABASE_URL=https://x.scribase.app\nVITE_SUPABASE_ANON_KEY=${ANON}\nVITE_ADMIN_KEY=${SERVICE}\n`,
|
||||
};
|
||||
const result = await runDoctor(doctorIo(files, (url) => (url.endsWith('/rest/v1/') ? 401 : 200)));
|
||||
assert.equal(result.ok, false);
|
||||
const problems = result.checks.filter((check) => check.status === 'problem');
|
||||
assert.deepEqual(problems.map((check) => check.id).sort(), ['gitignore', 'reach_rest', 'secret_exposure']);
|
||||
assert.ok(problems.every((check) => typeof check.fix === 'string' && check.fix.length > 0));
|
||||
assert.match(problems.find((check) => check.id === 'secret_exposure')?.detail ?? '', /VITE_ADMIN_KEY/);
|
||||
});
|
||||
|
||||
it('reports a missing env file, an unreachable host and a temporary project close to expiry', async () => {
|
||||
const now = 1_800_000_000_000;
|
||||
const missing = await runDoctor(doctorIo({ [`${ROOT}/package.json`]: '{}' }, () => 200, now));
|
||||
assert.equal(missing.checks.find((check) => check.id === 'env_file')?.status, 'problem');
|
||||
|
||||
const files = {
|
||||
[`${ROOT}/.env`]: `SUPABASE_URL=https://x.scribase.app\nSUPABASE_ANON_KEY=${ANON}\n`,
|
||||
[`${ROOT}/.gitignore`]: '.env*\n',
|
||||
[`${ROOT}/.scribase/project.json`]: JSON.stringify({ temporary: true, expires_at: now / 1000 + 3600, claim_url: 'https://c/claim/x#t' }),
|
||||
};
|
||||
const result = await runDoctor(doctorIo(files, () => new Error('getaddrinfo ENOTFOUND'), now));
|
||||
const byId = new Map(result.checks.map((check) => [check.id, check]));
|
||||
assert.equal(byId.get('reach_auth')?.status, 'problem');
|
||||
assert.equal(byId.get('temporary_expiry')?.status, 'warning');
|
||||
assert.match(byId.get('temporary_expiry')?.detail ?? '', /1 h 0 min/);
|
||||
assert.equal(byId.get('agent_token')?.status, 'warning');
|
||||
});
|
||||
|
||||
it('reads roles and env entries', () => {
|
||||
assert.equal(jwtRole(SERVICE), 'service_role');
|
||||
assert.equal(jwtRole('nope'), null);
|
||||
const entries = envEntries(`A=1\nexport NEXT_PUBLIC_X="${SERVICE}"\n# c\n`);
|
||||
assert.equal(entries.get('A'), '1');
|
||||
assert.deepEqual(leakedSecretVars(entries, undefined), ['NEXT_PUBLIC_X']);
|
||||
});
|
||||
});
|
||||
79
tests/importers.test.ts
Normal file
79
tests/importers.test.ts
Normal file
@ -0,0 +1,79 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { exportFirestoreDocuments, exportInstantApp, InstantExportError } from '../src/importers/index.js';
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
||||
}
|
||||
|
||||
test('exportInstantApp queries each namespace and flattens links to ids', async () => {
|
||||
const calls: { url: string; body: unknown; headers: Record<string, string> }[] = [];
|
||||
const fakeFetch = (async (url: string, init: RequestInit) => {
|
||||
const body = JSON.parse(String(init.body)) as { query: Record<string, unknown> };
|
||||
calls.push({ url, body, headers: init.headers as Record<string, string> });
|
||||
if ('todos' in body.query) {
|
||||
return jsonResponse({ todos: [{ id: 't1', title: 'ship', owner: [{ id: 'u1', email: 'a@b.co' }] }] });
|
||||
}
|
||||
if ('$users' in body.query) {
|
||||
return jsonResponse({ $users: [{ id: 'u1', email: 'a@b.co' }] });
|
||||
}
|
||||
return jsonResponse({ $files: [{ id: 'f1', path: 'a.png', url: 'https://x/a.png' }, { id: 'f2' }] });
|
||||
}) as typeof fetch;
|
||||
|
||||
const document = await exportInstantApp({
|
||||
appId: 'app-1',
|
||||
adminToken: 'secret',
|
||||
namespaces: ['todos'],
|
||||
links: { todos: ['owner'] },
|
||||
fetch: fakeFetch,
|
||||
});
|
||||
assert.deepEqual(document.namespaces.todos, [{ id: 't1', title: 'ship', owner: ['u1'] }]);
|
||||
assert.equal(document.users.length, 1);
|
||||
assert.deepEqual(document.files, [{ id: 'f1', path: 'a.png', url: 'https://x/a.png' }]);
|
||||
assert.equal(calls[0]?.headers['app-id'], 'app-1');
|
||||
assert.equal(calls[0]?.headers.authorization, 'Bearer secret');
|
||||
assert.match(calls[0]?.url ?? '', /\/admin\/query\?app_id=app-1$/);
|
||||
});
|
||||
|
||||
test('exportInstantApp refuses $-namespaces and reports auth failures without the token', async () => {
|
||||
await assert.rejects(
|
||||
exportInstantApp({ appId: 'a', adminToken: 't', namespaces: ['$users'], fetch: fetch }),
|
||||
InstantExportError,
|
||||
);
|
||||
const denied = (async () => jsonResponse({}, 401)) as unknown as typeof fetch;
|
||||
await assert.rejects(
|
||||
exportInstantApp({ appId: 'a', adminToken: 'super-secret', namespaces: ['todos'], fetch: denied }),
|
||||
(error: unknown) => error instanceof InstantExportError && !error.message.includes('super-secret'),
|
||||
);
|
||||
});
|
||||
|
||||
test('exportFirestoreDocuments walks collections and subcollections, skipping missing parents', async () => {
|
||||
const root = 'projects/p/databases/(default)/documents';
|
||||
const fakeFetch = (async (url: string) => {
|
||||
const path = decodeURIComponent(new URL(url).pathname.replace('/v1/', ''));
|
||||
if (path === `${root}:listCollectionIds`) {
|
||||
return jsonResponse({ collectionIds: ['users'] });
|
||||
}
|
||||
if (path === `${root}/users`) {
|
||||
return jsonResponse({
|
||||
documents: [
|
||||
{ name: `${root}/users/u1`, fields: { a: { stringValue: 'x' } }, createTime: 't', updateTime: 't' },
|
||||
{ name: `${root}/users/ghost` },
|
||||
],
|
||||
});
|
||||
}
|
||||
if (path === `${root}/users/ghost:listCollectionIds`) {
|
||||
return jsonResponse({ collectionIds: ['orders'] });
|
||||
}
|
||||
if (path === `${root}/users/ghost/orders`) {
|
||||
return jsonResponse({ documents: [{ name: `${root}/users/ghost/orders/o1`, createTime: 't' }] });
|
||||
}
|
||||
return jsonResponse({});
|
||||
}) as typeof fetch;
|
||||
|
||||
const names: string[] = [];
|
||||
for await (const document of exportFirestoreDocuments({ projectId: 'p', accessToken: 'tok', fetch: fakeFetch })) {
|
||||
names.push(document.name);
|
||||
}
|
||||
assert.deepEqual(names.sort(), [`${root}/users/ghost/orders/o1`, `${root}/users/u1`]);
|
||||
});
|
||||
359
tests/login.test.ts
Normal file
359
tests/login.test.ts
Normal file
@ -0,0 +1,359 @@
|
||||
/**
|
||||
* Tests for `npx scribase login` (RFC 8628 device login) and for `init`
|
||||
* signing in through it: a scripted control plane, a fake clock, an
|
||||
* in-memory pending store. No network, no keychain.
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import {
|
||||
GRANT_TYPE,
|
||||
LoginError,
|
||||
parseLoginArgs,
|
||||
parsePending,
|
||||
publicResult,
|
||||
renderPending,
|
||||
runLogin,
|
||||
} from '../src/cli/login.js';
|
||||
import type { LoginIo, Pending } from '../src/cli/login.js';
|
||||
import { macStoreCommand, parseCredentialsFile } from '../src/cli/credentials.js';
|
||||
import { InitError, parseInitArgs, runInit } from '../src/cli/init.js';
|
||||
import type { InitIo } from '../src/cli/init.js';
|
||||
|
||||
const API = 'https://api.example.test';
|
||||
const TOKEN = 'scb_agt_1p-rw-sqlw-mig-x2609260412_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
|
||||
|
||||
const DEVICE = {
|
||||
device_code: 'scb_dc_secret',
|
||||
user_code: 'SCRB-7F3K-Q2MX',
|
||||
verification_uri: 'https://console.example.test/device',
|
||||
verification_uri_complete: 'https://console.example.test/device?code=SCRB-7F3K-Q2MX',
|
||||
expires_in: 600,
|
||||
interval: 5,
|
||||
};
|
||||
|
||||
const GRANTED = {
|
||||
access_token: TOKEN,
|
||||
token_type: 'Bearer',
|
||||
expires_in: 28800,
|
||||
scope: 'project:web:write sql:write migrations:write',
|
||||
organization_id: 'acme',
|
||||
project_id: 'web',
|
||||
token_id: 'pat-1',
|
||||
};
|
||||
|
||||
interface Posted {
|
||||
path: string;
|
||||
contentType: string | null;
|
||||
fields: Record<string, string>;
|
||||
}
|
||||
|
||||
function harness(tokenAnswers: { status: number; body: unknown }[], deviceAnswer: { status: number; body: unknown } = { status: 200, body: DEVICE }) {
|
||||
let clock = 1_790_000_000_000;
|
||||
const posted: Posted[] = [];
|
||||
const sleeps: number[] = [];
|
||||
const emitted: unknown[] = [];
|
||||
const logs: string[] = [];
|
||||
const opened: string[] = [];
|
||||
const stored: [string, string][] = [];
|
||||
let pendingText: string | null = null;
|
||||
let polls = 0;
|
||||
const io: LoginIo = {
|
||||
env: {},
|
||||
fetch: (async (url: string | URL | Request, init?: RequestInit) => {
|
||||
const target = new URL(String(url));
|
||||
const headers = new Headers(init?.headers);
|
||||
const fields = Object.fromEntries(new URLSearchParams(String(init?.body ?? '')));
|
||||
posted.push({ path: target.pathname, contentType: headers.get('content-type'), fields });
|
||||
if (target.pathname === '/v1/oauth/device/code') {
|
||||
return new Response(JSON.stringify(deviceAnswer.body), { status: deviceAnswer.status });
|
||||
}
|
||||
const answer = tokenAnswers[polls] ?? { status: 400, body: { error: 'authorization_pending' } };
|
||||
polls += 1;
|
||||
return new Response(JSON.stringify(answer.body), { status: answer.status });
|
||||
}) as typeof fetch,
|
||||
sleep: async (ms) => {
|
||||
sleeps.push(ms / 1000);
|
||||
clock += ms;
|
||||
},
|
||||
now: () => clock,
|
||||
log: (line) => logs.push(line),
|
||||
emit: (value) => emitted.push(value),
|
||||
openBrowser: (url) => opened.push(url),
|
||||
interactive: true,
|
||||
store: (apiUrl, token) => {
|
||||
stored.push([apiUrl, token]);
|
||||
return 'the test keychain';
|
||||
},
|
||||
pending: {
|
||||
read: () => pendingText,
|
||||
write: (text) => {
|
||||
pendingText = text;
|
||||
},
|
||||
clear: () => {
|
||||
pendingText = null;
|
||||
},
|
||||
},
|
||||
};
|
||||
return {
|
||||
io,
|
||||
posted,
|
||||
sleeps,
|
||||
emitted,
|
||||
logs,
|
||||
opened,
|
||||
stored,
|
||||
pending: () => pendingText,
|
||||
setPending: (text: string | null) => {
|
||||
pendingText = text;
|
||||
},
|
||||
advance: (ms: number) => {
|
||||
clock += ms;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('login arguments', () => {
|
||||
it('parses flags, repeats scopes, and refuses pasted tokens', () => {
|
||||
const options = parseLoginArgs(['--json', '--no-wait', '--scope', 'project:read,sql:read', '--scope=org:read', '--name', 'Claude Code', '--no-browser']);
|
||||
assert.equal(options.json, true);
|
||||
assert.equal(options.noWait, true);
|
||||
assert.equal(options.browser, false);
|
||||
assert.deepEqual(options.scopes, ['project:read', 'sql:read', 'org:read']);
|
||||
assert.equal(options.name, 'Claude Code');
|
||||
assert.throws(() => parseLoginArgs(['--token', 'scb_pat_x']), LoginError);
|
||||
assert.throws(() => parseLoginArgs(['--bogus']), LoginError);
|
||||
assert.throws(() => parseLoginArgs(['--api-url']), LoginError);
|
||||
});
|
||||
|
||||
it('keeps the pending request in the Rust CLI format', () => {
|
||||
const pending: Pending = {
|
||||
api_url: API,
|
||||
device_code: 'scb_dc_x',
|
||||
user_code: 'SCRB-7F3K-Q2MX',
|
||||
verification_uri: DEVICE.verification_uri,
|
||||
verification_uri_complete: DEVICE.verification_uri_complete,
|
||||
expires_at: 1_790_000_600,
|
||||
interval: 5,
|
||||
};
|
||||
const text = renderPending(pending);
|
||||
assert.match(text, /^api_url=https:\/\/api\.example\.test\ndevice_code=scb_dc_x\n/);
|
||||
assert.deepEqual(parsePending(text), pending);
|
||||
assert.equal(parsePending('api_url=x\n'), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('device login', () => {
|
||||
it('prints the prompt, polls through pending and slow_down, stores the token and never prints it', async () => {
|
||||
const h = harness([
|
||||
{ status: 400, body: { error: 'authorization_pending' } },
|
||||
{ status: 400, body: { error: 'slow_down', interval: 10 } },
|
||||
{ status: 200, body: GRANTED },
|
||||
]);
|
||||
const result = await runLogin(parseLoginArgs(['--json', '--api-url', API, '--name', 'Claude Code']), h.io);
|
||||
assert.equal(result.status, 'approved');
|
||||
assert.equal(result.organization_id, 'acme');
|
||||
assert.equal(result.project_id, 'web');
|
||||
assert.deepEqual(result.scopes, ['project:web:write', 'sql:write', 'migrations:write']);
|
||||
assert.equal(result.stored_in, 'the test keychain');
|
||||
assert.deepEqual(h.stored, [[API, TOKEN]]);
|
||||
assert.deepEqual(h.sleeps, [5, 5, 10], 'slow_down raises the interval');
|
||||
assert.equal(h.pending(), null, 'finished logins are forgotten');
|
||||
|
||||
const [device, ...polls] = h.posted;
|
||||
assert.equal(device?.path, '/v1/oauth/device/code');
|
||||
assert.equal(device?.contentType, 'application/x-www-form-urlencoded');
|
||||
assert.equal(device?.fields.client_name, 'Claude Code');
|
||||
assert.equal(device?.fields.scope, 'project:write sql:write migrations:write functions:deploy branches:write');
|
||||
for (const poll of polls) {
|
||||
assert.equal(poll.path, '/v1/oauth/token');
|
||||
assert.deepEqual(poll.fields, { grant_type: GRANT_TYPE, device_code: 'scb_dc_secret' });
|
||||
}
|
||||
|
||||
assert.deepEqual(h.emitted[0], {
|
||||
event: 'device_authorization',
|
||||
verification_uri: DEVICE.verification_uri,
|
||||
verification_uri_complete: DEVICE.verification_uri_complete,
|
||||
user_code: 'SCRB-7F3K-Q2MX',
|
||||
expires_in: 600,
|
||||
message: `Ask the person to open ${DEVICE.verification_uri_complete} and approve code SCRB-7F3K-Q2MX. Never ask them for a key.`,
|
||||
});
|
||||
assert.equal(h.opened.length, 0, 'no browser in --json mode');
|
||||
const printed = JSON.stringify([h.emitted, h.logs, publicResult(result)]);
|
||||
assert.ok(!printed.includes(TOKEN), 'the token is never printed');
|
||||
assert.ok(!printed.includes('scb_dc_secret'), 'the device code is never printed');
|
||||
});
|
||||
|
||||
it('opens the browser for a person at a terminal', async () => {
|
||||
const h = harness([{ status: 200, body: GRANTED }]);
|
||||
await runLogin(parseLoginArgs(['--api-url', API]), h.io);
|
||||
assert.deepEqual(h.opened, [DEVICE.verification_uri_complete]);
|
||||
assert.ok(h.logs.some((line) => line.includes('SCRB-7F3K-Q2MX')));
|
||||
});
|
||||
|
||||
it('--no-wait returns the link, and the next run resumes the same request', async () => {
|
||||
const h = harness([{ status: 200, body: GRANTED }]);
|
||||
const first = await runLogin(parseLoginArgs(['--json', '--no-wait', '--api-url', API]), h.io);
|
||||
assert.equal(first.status, 'pending');
|
||||
assert.equal(first.user_code, 'SCRB-7F3K-Q2MX');
|
||||
assert.ok(h.pending(), 'the pending request is remembered');
|
||||
h.advance(60_000);
|
||||
const second = await runLogin(parseLoginArgs(['--json', '--api-url', API]), h.io);
|
||||
assert.equal(second.status, 'approved');
|
||||
assert.equal(h.posted.filter((call) => call.path === '/v1/oauth/device/code').length, 1, 'no second code');
|
||||
assert.equal((h.emitted[1] as { expires_in: number }).expires_in, 540);
|
||||
});
|
||||
|
||||
it('a --no-wait rerun finishes once approved, and stays pending until then', async () => {
|
||||
const h = harness([{ status: 400, body: { error: 'authorization_pending' } }, { status: 200, body: GRANTED }]);
|
||||
const first = await runLogin(parseLoginArgs(['--json', '--no-wait', '--api-url', API]), h.io);
|
||||
assert.equal(first.status, 'pending');
|
||||
const second = await runLogin(parseLoginArgs(['--json', '--no-wait', '--api-url', API]), h.io);
|
||||
assert.equal(second.status, 'pending', 'not approved yet');
|
||||
assert.ok(h.pending(), 'still remembered');
|
||||
const third = await runLogin(parseLoginArgs(['--json', '--no-wait', '--api-url', API]), h.io);
|
||||
assert.equal(third.status, 'approved');
|
||||
assert.deepEqual(h.stored, [[API, TOKEN]]);
|
||||
assert.equal(h.pending(), null);
|
||||
assert.equal(h.posted.filter((call) => call.path === '/v1/oauth/device/code').length, 1, 'one code for all three runs');
|
||||
assert.deepEqual(h.sleeps, [], 'never sleeps with --no-wait');
|
||||
});
|
||||
|
||||
it('starts over when the remembered request expired or is for another API', async () => {
|
||||
const h = harness([{ status: 200, body: GRANTED }]);
|
||||
h.setPending(
|
||||
renderPending({
|
||||
api_url: 'https://other.test',
|
||||
device_code: 'x',
|
||||
user_code: 'y',
|
||||
verification_uri: 'z',
|
||||
verification_uri_complete: 'w',
|
||||
expires_at: 9_999_999_999,
|
||||
interval: 5,
|
||||
}),
|
||||
);
|
||||
await runLogin(parseLoginArgs(['--api-url', API]), h.io);
|
||||
assert.equal(h.posted[0]?.path, '/v1/oauth/device/code');
|
||||
});
|
||||
|
||||
for (const [code, pattern] of [
|
||||
['access_denied', /denied/],
|
||||
['expired_token', /expired/],
|
||||
['invalid_grant', /already used/],
|
||||
] as const) {
|
||||
it(`stops on ${code}`, async () => {
|
||||
const h = harness([{ status: 400, body: { error: code } }, { status: 200, body: GRANTED }]);
|
||||
await assert.rejects(runLogin(parseLoginArgs(['--api-url', API]), h.io), (error: unknown) => {
|
||||
assert.ok(error instanceof LoginError);
|
||||
assert.equal(error.code, code);
|
||||
assert.match(error.message, pattern);
|
||||
return true;
|
||||
});
|
||||
assert.equal(h.stored.length, 0);
|
||||
assert.equal(h.pending(), null);
|
||||
});
|
||||
}
|
||||
|
||||
it('gives up locally when the code runs out', async () => {
|
||||
const h = harness([], { status: 200, body: { ...DEVICE, expires_in: 12 } });
|
||||
await assert.rejects(runLogin(parseLoginArgs(['--api-url', API]), h.io), (error: unknown) => {
|
||||
assert.ok(error instanceof LoginError);
|
||||
assert.equal(error.code, 'expired_token');
|
||||
return true;
|
||||
});
|
||||
assert.equal(h.posted.filter((call) => call.path === '/v1/oauth/token').length, 3);
|
||||
});
|
||||
|
||||
it('reports a refused device-code request and insecure URLs', async () => {
|
||||
const h = harness([], { status: 429, body: { error: 'slow_down', error_description: 'too many login requests' } });
|
||||
await assert.rejects(runLogin(parseLoginArgs(['--api-url', API]), h.io), /too many login requests/);
|
||||
await assert.rejects(runLogin(parseLoginArgs(['--api-url', 'http://api.example.test']), harness([]).io), /https/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('credentials', () => {
|
||||
it('reads the shared credentials file and keeps secrets off the command line', () => {
|
||||
assert.deepEqual(parseCredentialsFile('api_url=https://a\ntoken_store=keychain\n'), { apiUrl: 'https://a', tokenStore: 'keychain' });
|
||||
assert.deepEqual(parseCredentialsFile('api_url=https://a\naccess_token=scb_agt_x\n'), { apiUrl: 'https://a', token: 'scb_agt_x' });
|
||||
const command = macStoreCommand('https://a', 'scb_agt_x');
|
||||
assert.match(command, /^add-generic-password -U -s scribase .* -a "https:\/\/a" -w "scb_agt_x"\n$/);
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------ init + login ------------------------------ */
|
||||
|
||||
const KEYS = { api_url: 'https://acme-shop-production.scribase.app', anon_key: 'eyJanon', service_role_key: null };
|
||||
|
||||
function initIo(login: InitIo['login']) {
|
||||
const files: Record<string, string> = { '/work/shop/package.json': JSON.stringify({ dependencies: { '@supabase/supabase-js': '2' } }) };
|
||||
const calls: { method: string; path: string; auth: string | null }[] = [];
|
||||
const io: InitIo = {
|
||||
cwd: '/work/shop',
|
||||
env: {},
|
||||
fetch: (async (url: string | URL | Request, init?: RequestInit) => {
|
||||
const target = new URL(String(url));
|
||||
const auth = new Headers(init?.headers).get('authorization');
|
||||
calls.push({ method: init?.method ?? 'GET', path: target.pathname, auth });
|
||||
if (target.pathname.endsWith('/projects/shop') && init?.method === 'PUT') return new Response('{}', { status: 201 });
|
||||
if (target.pathname === '/v1/environments') return new Response('{}', { status: 202 });
|
||||
if (target.pathname.endsWith('/environments/production')) return new Response('{"phase":"ready"}', { status: 200 });
|
||||
if (target.pathname.endsWith('/api-keys')) return new Response(JSON.stringify(KEYS), { status: 200 });
|
||||
return new Response('{}', { status: 404 });
|
||||
}) as typeof fetch,
|
||||
readFile: (path) => files[path] ?? null,
|
||||
writeFile: (path, contents) => {
|
||||
files[path] = contents;
|
||||
},
|
||||
exists: (path) => path in files,
|
||||
run: () => ({ ok: true, output: '' }),
|
||||
sleep: async () => {},
|
||||
log: () => {},
|
||||
credentials: () => ({}),
|
||||
...(login ? { login } : {}),
|
||||
};
|
||||
return { io, calls, files };
|
||||
}
|
||||
|
||||
describe('init when not signed in', () => {
|
||||
it('with --account, asks for a browser approval for this app’s project, then provisions with that token', async () => {
|
||||
const requests: unknown[] = [];
|
||||
const { io, calls } = initIo(async (apiUrl, request) => {
|
||||
requests.push({ apiUrl, ...request });
|
||||
return { status: 'approved', token: TOKEN, organizationId: 'acme' };
|
||||
});
|
||||
const result = await runInit(parseInitArgs(['--account', '--yes', '--json', '--api-url', API]), io);
|
||||
assert.deepEqual(requests, [{ apiUrl: API, project: 'shop', json: true, noWait: false }]);
|
||||
assert.equal(result.organization_id, 'acme');
|
||||
assert.equal(result.project_id, 'shop');
|
||||
assert.equal(result.temporary, false);
|
||||
assert.ok(calls.length > 0 && calls.every((call) => call.auth === `Bearer ${TOKEN}`));
|
||||
assert.ok(!calls.some((call) => call.path === '/v1/organizations'), 'the approved organization is used');
|
||||
assert.ok(!calls.some((call) => call.path.startsWith('/v1/temporary-projects')), 'no temporary project');
|
||||
});
|
||||
|
||||
it('with --no-wait, returns the link as a coded error the agent can show', async () => {
|
||||
const { io } = initIo(async () => ({
|
||||
status: 'pending',
|
||||
userCode: 'SCRB-7F3K-Q2MX',
|
||||
verificationUriComplete: DEVICE.verification_uri_complete,
|
||||
}));
|
||||
await assert.rejects(runInit(parseInitArgs(['--account', '--yes', '--json', '--no-wait', '--api-url', API]), io), (error: unknown) => {
|
||||
assert.ok(error instanceof InitError);
|
||||
assert.equal(error.code, 'authorization_pending');
|
||||
assert.equal(error.details?.user_code, 'SCRB-7F3K-Q2MX');
|
||||
assert.match(error.next ?? '', /approve code SCRB-7F3K-Q2MX/);
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
it('never signs in for --temp', async () => {
|
||||
let asked = false;
|
||||
const { io } = initIo(async () => {
|
||||
asked = true;
|
||||
return { status: 'approved', token: TOKEN };
|
||||
});
|
||||
await assert.rejects(runInit(parseInitArgs(['--temp', '--yes', '--api-url', API]), io));
|
||||
assert.equal(asked, false);
|
||||
});
|
||||
});
|
||||
217
tests/migrate.test.ts
Normal file
217
tests/migrate.test.ts
Normal file
@ -0,0 +1,217 @@
|
||||
/**
|
||||
* Tests for `npx scribase migrate`: scaffolding a new file, reading and
|
||||
* splitting local `.sql` files, which project/token it uses, the plan/lint
|
||||
* request, dry-run, a BLOCK finding stopping apply, and errors (no network,
|
||||
* in-memory files).
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { InitError } from '../src/cli/init.js';
|
||||
import { formatMigrate, MIGRATIONS_DIR, parseMigrateArgs, runMigrate } from '../src/cli/migrate.js';
|
||||
import type { MigrateIo } from '../src/cli/migrate.js';
|
||||
|
||||
const ROOT = '/work/app';
|
||||
const STATE = JSON.stringify({
|
||||
organization_id: 'tmp-1',
|
||||
project_id: 'shop',
|
||||
environment_id: 'production',
|
||||
api_url: 'https://api.example.test',
|
||||
});
|
||||
|
||||
interface Seen {
|
||||
url: string;
|
||||
auth: string | null;
|
||||
body: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface Written {
|
||||
path: string;
|
||||
contents: string;
|
||||
}
|
||||
|
||||
function io(
|
||||
files: Record<string, string>,
|
||||
migrationFiles: string[],
|
||||
answer: { status: number; body: unknown } | null,
|
||||
env: Record<string, string> = {},
|
||||
stored: { token?: string } = {},
|
||||
) {
|
||||
const seen: Seen[] = [];
|
||||
const written: Written[] = [];
|
||||
const value: MigrateIo = {
|
||||
cwd: ROOT,
|
||||
env,
|
||||
fetch: (async (url: string | URL | Request, init?: RequestInit) => {
|
||||
seen.push({
|
||||
url: String(url),
|
||||
auth: new Headers(init?.headers).get('authorization'),
|
||||
body: JSON.parse(String(init?.body)) as Record<string, unknown>,
|
||||
});
|
||||
if (!answer) throw new Error('unexpected network call');
|
||||
return new Response(JSON.stringify(answer.body), { status: answer.status });
|
||||
}) as typeof fetch,
|
||||
readFile: (path) => files[path] ?? null,
|
||||
writeFile: (path, contents) => {
|
||||
written.push({ path, contents });
|
||||
files[path] = contents;
|
||||
},
|
||||
listMigrationFiles: () => migrationFiles,
|
||||
credentials: () => stored,
|
||||
now: () => new Date('2026-10-29T12:34:56Z'),
|
||||
};
|
||||
return { io: value, seen, written };
|
||||
}
|
||||
|
||||
const COMMITTED = {
|
||||
plan: { steps: [{ version: 20261029123456, name: 'add_notes', direction: 'up', checksum: 'abc' }] },
|
||||
lintFindings: [],
|
||||
applied: [20261029123456],
|
||||
};
|
||||
|
||||
describe('scribase migrate arguments', () => {
|
||||
it('parses `new <name>`, the default run, --dry-run and --json', () => {
|
||||
assert.deepEqual(parseMigrateArgs(['new', 'add notes']), { action: 'new', name: 'add notes', dryRun: false, json: false });
|
||||
assert.deepEqual(parseMigrateArgs([]), { action: 'run', dryRun: false, json: false });
|
||||
assert.deepEqual(parseMigrateArgs(['up', '--dry-run', '--json']), { action: 'run', dryRun: true, json: true });
|
||||
});
|
||||
|
||||
it('rejects `new` with no name, an unknown argument and an unknown flag', () => {
|
||||
assert.throws(() => parseMigrateArgs(['new']), (error: unknown) => error instanceof InitError && error.code === 'invalid_argument' && /name/.test(error.message));
|
||||
assert.throws(() => parseMigrateArgs(['down']), (error: unknown) => error instanceof InitError && error.code === 'invalid_argument');
|
||||
assert.throws(() => parseMigrateArgs(['--force']), (error: unknown) => error instanceof InitError && /--force/.test(error.message));
|
||||
});
|
||||
});
|
||||
|
||||
describe('scribase migrate new', () => {
|
||||
it('scaffolds a timestamped file with a slugified name and both markers', async () => {
|
||||
const { io: value, written } = io({}, [], null);
|
||||
const result = await runMigrate({ action: 'new', name: 'Add Notes!', dryRun: false, json: false }, value);
|
||||
assert.equal(result.action, 'new');
|
||||
if (result.action !== 'new') throw new Error('unreachable');
|
||||
assert.equal(result.version, '20261029123456');
|
||||
assert.equal(result.name, 'add_notes');
|
||||
assert.equal(result.path, `${ROOT}/${MIGRATIONS_DIR}/20261029123456_add_notes.sql`);
|
||||
assert.equal(written.length, 1);
|
||||
assert.match(written[0]?.contents ?? '', /^-- Add Notes!/);
|
||||
assert.match(written[0]?.contents ?? '', /missing_rls/);
|
||||
assert.match(written[0]?.contents ?? '', /\n-- down\n/);
|
||||
assert.match(written[0]?.contents ?? '', /create table public\.add_notes/);
|
||||
// Unedited, it is a real no-op: every SQL line is commented out.
|
||||
for (const line of (written[0]?.contents ?? '').split('\n')) {
|
||||
if (line.trim().length > 0) assert.match(line, /^--/, `expected a comment line, got: ${line}`);
|
||||
}
|
||||
});
|
||||
|
||||
it('never produces an empty slug, even from punctuation-only input', async () => {
|
||||
const { io: value } = io({}, [], null);
|
||||
const result = await runMigrate({ action: 'new', name: '!!!', dryRun: false, json: false }, value);
|
||||
if (result.action !== 'new') throw new Error('unreachable');
|
||||
assert.equal(result.name, 'migration');
|
||||
});
|
||||
});
|
||||
|
||||
describe('scribase migrate (run)', () => {
|
||||
it('reports no files without making a network call when the folder has none', async () => {
|
||||
const { io: value, seen } = io({}, [], null);
|
||||
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
|
||||
if (result.action !== 'run') throw new Error('unreachable');
|
||||
assert.equal(result.files, 0);
|
||||
assert.equal(seen.length, 0);
|
||||
assert.match(formatMigrate(result), /No migration files/);
|
||||
});
|
||||
|
||||
it('reads local files in version order, splits up/down on the marker, and sends them with apply:true', async () => {
|
||||
const files = {
|
||||
[`${ROOT}/.scribase/project.json`]: STATE,
|
||||
[`${ROOT}/.env.local`]: 'SCRIBASE_ACCESS_TOKEN=scb_agt_tmp\n',
|
||||
[`${ROOT}/${MIGRATIONS_DIR}/2_second.sql`]: 'create table second (id int);\n-- down\ndrop table second;\n',
|
||||
[`${ROOT}/${MIGRATIONS_DIR}/1_first.sql`]: 'create table first (id int);',
|
||||
};
|
||||
const { io: value, seen } = io(files, ['2_second.sql', '1_first.sql', 'README.md'], { status: 200, body: COMMITTED });
|
||||
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
|
||||
if (result.action !== 'run') throw new Error('unreachable');
|
||||
assert.equal(result.files, 2);
|
||||
assert.equal(seen[0]?.url, 'https://api.example.test/v1/organizations/tmp-1/projects/shop/environments/production/migrations');
|
||||
assert.equal(seen[0]?.auth, 'Bearer scb_agt_tmp');
|
||||
const sent = seen[0]?.body.migrations as { version: string; up: string; down?: string }[];
|
||||
assert.deepEqual(sent.map((m) => m.version), ['1', '2'], 'oldest version first, regardless of filesystem order');
|
||||
assert.equal(sent[0]?.up, 'create table first (id int);');
|
||||
assert.equal(sent[0]?.down, undefined, 'no marker, no down key');
|
||||
assert.equal(sent[1]?.up, 'create table second (id int);');
|
||||
assert.equal(sent[1]?.down, 'drop table second;');
|
||||
assert.equal(seen[0]?.body.apply, true);
|
||||
assert.equal(result.blocked, false);
|
||||
const text = formatMigrate(result);
|
||||
assert.match(text, /1 migration\(s\) ran/);
|
||||
assert.doesNotMatch(text, /scb_agt_tmp/, 'the token is never printed');
|
||||
});
|
||||
|
||||
it('sends apply:false with --dry-run and never reports anything applied', async () => {
|
||||
const files = { [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' };
|
||||
const { io: value, seen } = io(files, ['1_x.sql'], { status: 200, body: { plan: COMMITTED.plan, lintFindings: [], applied: [] } }, { SCRIBASE_ACCESS_TOKEN: 't' });
|
||||
const result = await runMigrate({ action: 'run', dryRun: true, json: false }, value);
|
||||
if (result.action !== 'run') throw new Error('unreachable');
|
||||
assert.equal(seen[0]?.body.apply, false);
|
||||
assert.equal(result.blocked, false, '--dry-run is never "blocked", it never tried to apply');
|
||||
assert.match(formatMigrate(result), /Dry run: nothing applied/);
|
||||
});
|
||||
|
||||
it('marks the run blocked when a BLOCK finding stops every pending migration, and exits non-zero', async () => {
|
||||
const files = { [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'create table t (id int);' };
|
||||
const blocked = {
|
||||
plan: { steps: [{ version: 1, name: 'x', direction: 'up', checksum: 'c' }] },
|
||||
lintFindings: [{ rule: 'missing_rls', severity: 'BLOCK', subject: 'public.t', line: 1, message: 'has neither RLS enabled nor any policy' }],
|
||||
applied: [],
|
||||
};
|
||||
const { io: value } = io(files, ['1_x.sql'], { status: 200, body: blocked }, { SCRIBASE_ACCESS_TOKEN: 't' });
|
||||
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
|
||||
if (result.action !== 'run') throw new Error('unreachable');
|
||||
assert.equal(result.blocked, true);
|
||||
const text = formatMigrate(result);
|
||||
assert.match(text, /\[BLOCK\] missing_rls/);
|
||||
assert.match(text, /Nothing applied/);
|
||||
});
|
||||
|
||||
it('skips the network call and says up to date when every local file is already applied', async () => {
|
||||
const files = { [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' };
|
||||
const upToDate = { plan: { steps: [] }, lintFindings: [], applied: [] };
|
||||
const { io: value } = io(files, ['1_x.sql'], { status: 200, body: upToDate }, { SCRIBASE_ACCESS_TOKEN: 't' });
|
||||
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
|
||||
assert.match(formatMigrate(result), /Up to date/);
|
||||
});
|
||||
|
||||
it('says what to do when the folder is not initialized, has no token, or the token is refused', async () => {
|
||||
await assert.rejects(
|
||||
runMigrate({ action: 'run', dryRun: false, json: false }, io({ [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' }, ['1_x.sql'], { status: 200, body: {} }).io),
|
||||
(error: unknown) => error instanceof InitError && error.code === 'not_initialized' && /scribase init/.test(error.next ?? ''),
|
||||
);
|
||||
await assert.rejects(
|
||||
runMigrate(
|
||||
{ action: 'run', dryRun: false, json: false },
|
||||
io({ [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' }, ['1_x.sql'], { status: 200, body: {} }).io,
|
||||
),
|
||||
(error: unknown) => error instanceof InitError && error.code === 'not_signed_in',
|
||||
);
|
||||
const refused = io(
|
||||
{ [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' },
|
||||
['1_x.sql'],
|
||||
{ status: 401, body: { code: 'unauthorized', detail: 'token expired' } },
|
||||
{ SCRIBASE_ACCESS_TOKEN: 'old' },
|
||||
);
|
||||
await assert.rejects(
|
||||
runMigrate({ action: 'run', dryRun: false, json: false }, refused.io),
|
||||
(error: unknown) => error instanceof InitError && error.code === 'unauthorized' && /HTTP 401/.test(error.message) && /init/.test(error.next ?? ''),
|
||||
);
|
||||
});
|
||||
|
||||
it('ignores files that do not match <version>_<name>.sql', async () => {
|
||||
const files = { [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/${MIGRATIONS_DIR}/1_x.sql`]: 'select 1;' };
|
||||
const { io: value, seen } = io(files, ['1_x.sql', 'README.md', 'notes.sql', '.gitignore'], { status: 200, body: COMMITTED }, { SCRIBASE_ACCESS_TOKEN: 't' });
|
||||
const result = await runMigrate({ action: 'run', dryRun: false, json: false }, value);
|
||||
if (result.action !== 'run') throw new Error('unreachable');
|
||||
assert.equal(result.files, 1);
|
||||
assert.equal((seen[0]?.body.migrations as unknown[]).length, 1);
|
||||
});
|
||||
});
|
||||
194
tests/ota.test.ts
Normal file
194
tests/ota.test.ts
Normal file
@ -0,0 +1,194 @@
|
||||
/**
|
||||
* Tests for `npx scribase ota` (PS3.1): arguments, the deploy flow (set up
|
||||
* when needed, config and env written once, the secret key only in the child
|
||||
* process), roll back and status, with no network and in-memory files.
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { CONFIG_FILE, CONFIG_TEMPLATE, formatOta, otaMain, parseOtaArgs, runOta } from '../src/cli/capabilities/ota.js';
|
||||
import type { OtaIo, OtaStatus } from '../src/cli/capabilities/ota.js';
|
||||
import { InitError } from '../src/cli/init.js';
|
||||
|
||||
const ROOT = '/work/app';
|
||||
const STATE = JSON.stringify({ organization_id: 'acme', project_id: 'shop', environment_id: 'production', api_url: 'https://api.example.test' });
|
||||
const SECRET = 'sb_secret_abcdefghijklmnopqrstuvwxyz0123456789';
|
||||
const URL_BASE = 'https://api.example.test/v1/organizations/acme/projects/shop/environments/production';
|
||||
const RELEASE = {
|
||||
id: '0199a000-0000-7000-8000-000000000002',
|
||||
platform: 'ios',
|
||||
channel: 'production',
|
||||
target_app_version: '1.x.x',
|
||||
fingerprint_hash: null,
|
||||
enabled: true,
|
||||
force_update: false,
|
||||
rollout_percent: 100,
|
||||
message: 'fix login',
|
||||
created_at_epoch_seconds: 1759200000,
|
||||
};
|
||||
|
||||
function status(overrides: Partial<OtaStatus> = {}): OtaStatus {
|
||||
return {
|
||||
enabled: true,
|
||||
conflict: false,
|
||||
update_url: 'https://acme-shop.scribase.app/functions/v1/ota',
|
||||
bucket: 'ota-bundles',
|
||||
releases: 1,
|
||||
latest: [RELEASE as OtaStatus['latest'][number]],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
type Answer = { status: number; body: unknown };
|
||||
|
||||
function fakeIo(routes: Record<string, Answer | Answer[]>, files: Record<string, string> = {}, runCode = 0) {
|
||||
const store: Record<string, string> = { [`${ROOT}/.scribase/project.json`]: STATE, ...files };
|
||||
const calls: { method: string; url: string; body: unknown; auth: string | null }[] = [];
|
||||
const runs: { command: string; args: string[]; env: Record<string, string> }[] = [];
|
||||
const logs: string[] = [];
|
||||
const io: OtaIo = {
|
||||
cwd: ROOT,
|
||||
env: { SCRIBASE_ACCESS_TOKEN: 'pat_token' },
|
||||
fetch: (async (url: string | URL | Request, init?: RequestInit) => {
|
||||
const method = init?.method ?? 'GET';
|
||||
const path = String(url).slice(URL_BASE.length);
|
||||
calls.push({ method, url: String(url), body: init?.body ? JSON.parse(String(init.body)) : undefined, auth: new Headers(init?.headers).get('authorization') });
|
||||
const entry = routes[`${method} ${path}`];
|
||||
const answer = Array.isArray(entry) ? entry.shift() : entry;
|
||||
if (!answer) return new Response('{"code":"not_found","detail":"no route"}', { status: 404 });
|
||||
return new Response(JSON.stringify(answer.body), { status: answer.status });
|
||||
}) as typeof fetch,
|
||||
readFile: (path) => store[path] ?? null,
|
||||
writeFile: (path, contents) => {
|
||||
store[path] = contents;
|
||||
},
|
||||
credentials: () => ({}),
|
||||
log: (line) => logs.push(line),
|
||||
run: async (command, args, env) => {
|
||||
runs.push({ command, args, env });
|
||||
return runCode;
|
||||
},
|
||||
};
|
||||
return { io, calls, runs, store, logs };
|
||||
}
|
||||
|
||||
describe('scribase ota arguments', () => {
|
||||
it('reads the action, platform, channel and deploy flags', () => {
|
||||
assert.deepEqual(parseOtaArgs(['deploy', '-p', 'ios', '-m', 'fix', '-r', '25', '-f']), {
|
||||
action: 'deploy',
|
||||
platform: 'ios',
|
||||
channel: 'production',
|
||||
passthrough: ['-m', 'fix', '-r', '25', '-f'],
|
||||
json: false,
|
||||
});
|
||||
assert.equal(parseOtaArgs(['rollback', '--platform', 'android', '-c', 'beta']).channel, 'beta');
|
||||
assert.equal(parseOtaArgs(['status', '--json']).json, true);
|
||||
});
|
||||
|
||||
it('refuses a missing platform, an unknown one, a bad channel and unknown flags', () => {
|
||||
assert.throws(() => parseOtaArgs(['deploy']), InitError);
|
||||
assert.throws(() => parseOtaArgs(['deploy', '-p', 'web']), InitError);
|
||||
assert.throws(() => parseOtaArgs(['rollback', '-p', 'ios', '-c', 'a/b']), InitError);
|
||||
assert.throws(() => parseOtaArgs(['status', '--secret', 'x']), InitError);
|
||||
assert.throws(() => parseOtaArgs(['rollback', '-p', 'ios', '-m', 'x']), InitError);
|
||||
assert.throws(() => parseOtaArgs(['publish']), InitError);
|
||||
assert.throws(() => parseOtaArgs(['deploy', '-p']), InitError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('scribase ota deploy', () => {
|
||||
it('sets OTA up when needed, writes the config and the public URL, and gives the key only to the child', async () => {
|
||||
const { io, calls, runs, store } = fakeIo({
|
||||
'GET /ota': [
|
||||
{ status: 200, body: status({ enabled: false, latest: [], releases: 0 }) },
|
||||
{ status: 200, body: status() },
|
||||
],
|
||||
'POST /ota': { status: 200, body: status({ latest: [], releases: 0 }) },
|
||||
'GET /api-keys': { status: 200, body: { api_url: 'https://acme-shop.scribase.app/', secret_key: SECRET, anon_key: 'anon' } },
|
||||
});
|
||||
const result = await runOta(parseOtaArgs(['deploy', '-p', 'ios', '-m', 'fix login']), io);
|
||||
assert.equal(result.action, 'deploy');
|
||||
assert.ok(result.action === 'deploy' && result.set_up && result.config_written);
|
||||
assert.deepEqual(result.action === 'deploy' && result.env_written, ['EXPO_PUBLIC_HOT_UPDATER_URL']);
|
||||
assert.equal(result.action === 'deploy' && result.release?.id, RELEASE.id);
|
||||
assert.equal(store[`${ROOT}/${CONFIG_FILE}`], CONFIG_TEMPLATE);
|
||||
assert.match(store[`${ROOT}/.env`] ?? '', /EXPO_PUBLIC_HOT_UPDATER_URL=.*functions\/v1\/ota/);
|
||||
for (const contents of Object.values(store)) assert.ok(!contents.includes(SECRET), 'the secret key is never written');
|
||||
assert.equal(runs.length, 1);
|
||||
assert.deepEqual(runs[0]?.args, ['--yes', 'hot-updater@0.36.16', 'deploy', '-p', 'ios', '-c', 'production', '-m', 'fix login']);
|
||||
assert.equal(runs[0]?.env.HOT_UPDATER_SUPABASE_SERVICE_ROLE_KEY, SECRET);
|
||||
assert.equal(runs[0]?.env.HOT_UPDATER_SUPABASE_URL, 'https://acme-shop.scribase.app');
|
||||
assert.equal(runs[0]?.env.HOT_UPDATER_SUPABASE_BUCKET_NAME, 'ota-bundles');
|
||||
assert.ok(calls.every((call) => call.auth === 'Bearer pat_token'));
|
||||
assert.deepEqual(calls.map((call) => `${call.method} ${call.url.slice(URL_BASE.length)}`), ['GET /ota', 'POST /ota', 'GET /api-keys', 'GET /ota']);
|
||||
});
|
||||
|
||||
it('keeps an existing config and env value and does not set up twice', async () => {
|
||||
const { io, calls, store } = fakeIo(
|
||||
{
|
||||
'GET /ota': { status: 200, body: status() },
|
||||
'GET /api-keys': { status: 200, body: { api_url: 'https://acme-shop.scribase.app', service_role_key: 'eyJ.service.jwt' } },
|
||||
},
|
||||
{
|
||||
[`${ROOT}/${CONFIG_FILE}`]: '// mine',
|
||||
[`${ROOT}/.env.local`]: 'EXPO_PUBLIC_HOT_UPDATER_URL=https://acme-shop.scribase.app/functions/v1/ota\n',
|
||||
},
|
||||
);
|
||||
const result = await runOta(parseOtaArgs(['deploy', '-p', 'ios']), io);
|
||||
assert.ok(result.action === 'deploy' && !result.set_up && !result.config_written && result.env_written.length === 0);
|
||||
assert.equal(store[`${ROOT}/${CONFIG_FILE}`], '// mine');
|
||||
assert.ok(!calls.some((call) => call.method === 'POST'));
|
||||
});
|
||||
|
||||
it('stops on a foreign bundles table, a role without the key, or a failed upload', async () => {
|
||||
await assert.rejects(
|
||||
runOta(parseOtaArgs(['deploy', '-p', 'ios']), fakeIo({ 'GET /ota': { status: 200, body: status({ enabled: false, conflict: true }) } }).io),
|
||||
/own public.bundles/,
|
||||
);
|
||||
await assert.rejects(
|
||||
runOta(
|
||||
parseOtaArgs(['deploy', '-p', 'ios']),
|
||||
fakeIo({ 'GET /ota': { status: 200, body: status() }, 'GET /api-keys': { status: 200, body: { api_url: 'https://x', secret_key: null } } }).io,
|
||||
),
|
||||
/secret key/,
|
||||
);
|
||||
await assert.rejects(
|
||||
runOta(
|
||||
parseOtaArgs(['deploy', '-p', 'android']),
|
||||
fakeIo({ 'GET /ota': { status: 200, body: status() }, 'GET /api-keys': { status: 200, body: { api_url: 'https://x', secret_key: SECRET } } }, {}, 1).io,
|
||||
),
|
||||
/exited with code 1/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('scribase ota rollback and status', () => {
|
||||
it('rolls back the newest release and names what devices go back to', async () => {
|
||||
const { io, calls } = fakeIo({
|
||||
'POST /ota/rollback': { status: 200, body: { turned_off: RELEASE.id, now_serving: null, platform: 'ios', channel: 'production' } },
|
||||
});
|
||||
const result = await runOta(parseOtaArgs(['rollback', '-p', 'ios']), io);
|
||||
assert.deepEqual(calls[0]?.body, { platform: 'ios', channel: 'production' });
|
||||
assert.match(formatOta(result), /go back to the bundle built into the app/);
|
||||
});
|
||||
|
||||
it('prints the published releases, or how to start', async () => {
|
||||
const on = await runOta(parseOtaArgs(['status']), fakeIo({ 'GET /ota': { status: 200, body: status() } }).io);
|
||||
assert.match(formatOta(on), /ios production: 0199a000-0000-7000-8000-000000000002 \(on for 100% of devices, app 1\.x\.x\)/);
|
||||
const off = await runOta(parseOtaArgs(['status']), fakeIo({ 'GET /ota': { status: 200, body: status({ enabled: false }) } }).io);
|
||||
assert.match(formatOta(off), /not set up yet/);
|
||||
});
|
||||
|
||||
it('prints the API refusal and exits 1; help exits 0', async () => {
|
||||
const lines: string[] = [];
|
||||
const code = await otaMain(
|
||||
['rollback', '-p', 'ios'],
|
||||
fakeIo({ 'POST /ota/rollback': { status: 409, body: { code: 'nothing_to_roll_back', detail: 'no release is on for ios on the production channel' } } }).io,
|
||||
(text) => lines.push(text),
|
||||
);
|
||||
assert.equal(code, 1);
|
||||
assert.match(lines.join(''), /no release is on for ios \(HTTP 409\)|no release is on for ios on the production channel \(HTTP 409\)/);
|
||||
assert.equal(await otaMain(['--help'], fakeIo({}).io, () => undefined), 0);
|
||||
});
|
||||
});
|
||||
548
tests/resources.test.ts
Normal file
548
tests/resources.test.ts
Normal file
@ -0,0 +1,548 @@
|
||||
/**
|
||||
* Tests for key resource classes — validates that each resource method builds
|
||||
* the correct HTTP path and returns the correct shaped data. All tests use a
|
||||
* mock `HttpTransport` (no network, no ScribaseClient construction).
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import type { HttpTransport, ApiResult, RequestOptions } from '../src/client.js';
|
||||
import { EnvironmentsResource } from '../src/resources/environments.js';
|
||||
import { ProjectsResource } from '../src/resources/projects.js';
|
||||
import { AuthResource } from '../src/resources/auth.js';
|
||||
import { StorageResource } from '../src/resources/storage.js';
|
||||
import { FunctionsResource } from '../src/resources/functions.js';
|
||||
import { UsageResource } from '../src/resources/usage.js';
|
||||
import { MetricsResource } from '../src/resources/metrics.js';
|
||||
import { AuditResource } from '../src/resources/audit.js';
|
||||
import { DatabaseResource } from '../src/resources/database.js';
|
||||
import type {
|
||||
Environment,
|
||||
Project,
|
||||
Operation,
|
||||
AuditEvent,
|
||||
} from '../src/types.gen.js';
|
||||
import { NotFoundError } from '../src/errors.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock transport
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface CapturedRequest {
|
||||
options: RequestOptions;
|
||||
}
|
||||
|
||||
function makeTransport(data: unknown, status = 200, idempotencyReplayed = false): {
|
||||
transport: HttpTransport;
|
||||
calls: CapturedRequest[];
|
||||
} {
|
||||
const calls: CapturedRequest[] = [];
|
||||
const transport: HttpTransport = {
|
||||
async send<T>(options: RequestOptions): Promise<ApiResult<T>> {
|
||||
calls.push({ options });
|
||||
return {
|
||||
data: data as T,
|
||||
status,
|
||||
idempotencyReplayed,
|
||||
headers: new Headers(),
|
||||
};
|
||||
},
|
||||
};
|
||||
return { transport, calls };
|
||||
}
|
||||
|
||||
function makeFailing(status: number, code: string): HttpTransport {
|
||||
const problem = { type: 'about:blank', title: 'Error', status, code };
|
||||
return {
|
||||
async send<T>(_options: RequestOptions): Promise<ApiResult<T>> {
|
||||
const { errorFromResponse } = await import('../src/errors.js');
|
||||
throw errorFromResponse(status, problem);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// EnvironmentsResource
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('EnvironmentsResource', () => {
|
||||
const ref = {
|
||||
organizationId: 'acme',
|
||||
projectId: 'store',
|
||||
environmentId: 'production',
|
||||
};
|
||||
|
||||
const sampleEnv: Environment = {
|
||||
organization_id: 'acme',
|
||||
project_id: 'store',
|
||||
environment_id: 'production',
|
||||
kind: 'production',
|
||||
data_mode: 'snapshot',
|
||||
region: 'us-east',
|
||||
postgres_major: 17,
|
||||
phase: 'ready',
|
||||
desired_generation: 1,
|
||||
observed_generation: 1,
|
||||
retry_count: 0,
|
||||
last_activity_epoch_seconds: 0,
|
||||
finalizers: [],
|
||||
};
|
||||
|
||||
it('list calls GET /v1/environments with org query param', async () => {
|
||||
const { transport, calls } = makeTransport({ environments: [sampleEnv] });
|
||||
const resource = new EnvironmentsResource(transport);
|
||||
const envs = await resource.list({ organizationId: 'acme' });
|
||||
|
||||
assert.equal(calls.length, 1);
|
||||
const call = calls[0]!;
|
||||
assert.equal(call.options.method, 'GET');
|
||||
assert.equal(call.options.path, '/v1/environments');
|
||||
assert.equal(call.options.query?.['organization_id'], 'acme');
|
||||
assert.equal(envs.length, 1);
|
||||
assert.equal(envs[0]?.environment_id, 'production');
|
||||
});
|
||||
|
||||
it('list narrows to a project when projectId is provided', async () => {
|
||||
const { transport, calls } = makeTransport({ environments: [] });
|
||||
const resource = new EnvironmentsResource(transport);
|
||||
await resource.list({ organizationId: 'acme', projectId: 'store' });
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.equal(call.options.query?.['project_id'], 'store');
|
||||
});
|
||||
|
||||
it('get calls the correct environment path', async () => {
|
||||
const { transport, calls } = makeTransport(sampleEnv);
|
||||
const resource = new EnvironmentsResource(transport);
|
||||
const env = await resource.get(ref);
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.equal(call.options.method, 'GET');
|
||||
assert.ok(call.options.path.includes('/organizations/acme/projects/store/environments/production'));
|
||||
assert.equal(env.environment_id, 'production');
|
||||
});
|
||||
|
||||
it('delete calls DELETE and returns an AcceptedOperation', async () => {
|
||||
const op: Operation = {
|
||||
id: 'op-1',
|
||||
kind: 'delete_environment',
|
||||
environment: { organization_id: 'acme', project_id: 'store', environment_id: 'production' },
|
||||
state: 'pending',
|
||||
attempt_count: 0,
|
||||
};
|
||||
const { transport, calls } = makeTransport(op);
|
||||
const resource = new EnvironmentsResource(transport);
|
||||
const accepted = await resource.delete(ref, { idempotencyKey: 'idem-1' });
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.equal(call.options.method, 'DELETE');
|
||||
assert.equal(call.options.idempotencyKey, 'idem-1');
|
||||
assert.equal(accepted.operation.id, 'op-1');
|
||||
assert.equal(accepted.idempotencyReplayed, false);
|
||||
});
|
||||
|
||||
it('suspend calls POST …/suspend', async () => {
|
||||
const op: Operation = {
|
||||
id: 'op-2',
|
||||
kind: 'suspend_environment',
|
||||
environment: ref,
|
||||
state: 'pending',
|
||||
attempt_count: 0,
|
||||
};
|
||||
const { transport, calls } = makeTransport(op);
|
||||
const resource = new EnvironmentsResource(transport);
|
||||
await resource.suspend(ref, { idempotencyKey: 'idem-2' });
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.ok(call.options.path.endsWith('/suspend'));
|
||||
});
|
||||
|
||||
it('resume calls POST …/resume', async () => {
|
||||
const op: Operation = {
|
||||
id: 'op-3',
|
||||
kind: 'resume_environment',
|
||||
environment: ref,
|
||||
state: 'pending',
|
||||
attempt_count: 0,
|
||||
};
|
||||
const { transport, calls } = makeTransport(op);
|
||||
const resource = new EnvironmentsResource(transport);
|
||||
await resource.resume(ref);
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.ok(call.options.path.endsWith('/resume'));
|
||||
});
|
||||
|
||||
it('propagates errors from the transport', async () => {
|
||||
const transport = makeFailing(404, 'not_found');
|
||||
const resource = new EnvironmentsResource(transport);
|
||||
await assert.rejects(() => resource.get(ref), NotFoundError);
|
||||
});
|
||||
|
||||
it('apiKeys() GETs the environment client keys', async () => {
|
||||
const keys = {
|
||||
api_url: 'https://acme-store-production-1a2b3c4d.scribase.com',
|
||||
anon_key: 'eyJ.anon.sig',
|
||||
publishable_key: 'sb_publishable_abc',
|
||||
service_role_key: null,
|
||||
secret_key: null,
|
||||
jwt_secret_version: 1,
|
||||
jwt_secret_source: 'control_plane' as const,
|
||||
};
|
||||
const { transport, calls } = makeTransport(keys);
|
||||
const resource = new EnvironmentsResource(transport);
|
||||
const result = await resource.apiKeys(ref);
|
||||
assert.equal(calls[0]!.options.method, 'GET');
|
||||
assert.equal(
|
||||
calls[0]!.options.path,
|
||||
'/v1/organizations/acme/projects/store/environments/production/api-keys',
|
||||
);
|
||||
assert.equal(result.publishable_key, 'sb_publishable_abc');
|
||||
assert.equal(result.service_role_key, null);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ProjectsResource
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('ProjectsResource', () => {
|
||||
const sampleProject: Project = {
|
||||
organization_id: 'acme',
|
||||
project_id: 'store',
|
||||
region: 'us-east',
|
||||
postgres_major: 17,
|
||||
};
|
||||
|
||||
it('get calls GET on the correct project path', async () => {
|
||||
const { transport, calls } = makeTransport(sampleProject);
|
||||
const resource = new ProjectsResource(transport);
|
||||
const project = await resource.get('acme', 'store');
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.equal(call.options.method, 'GET');
|
||||
assert.ok(call.options.path.includes('/organizations/acme/projects/store'));
|
||||
assert.equal(project.project_id, 'store');
|
||||
});
|
||||
|
||||
it('put calls PUT with the request body', async () => {
|
||||
const { transport, calls } = makeTransport(sampleProject);
|
||||
const resource = new ProjectsResource(transport);
|
||||
await resource.put('acme', 'store', { region: 'us-east', postgres_major: 17 });
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.equal(call.options.method, 'PUT');
|
||||
assert.deepEqual(call.options.body, { region: 'us-east', postgres_major: 17 });
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// AuthResource
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('AuthResource', () => {
|
||||
const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'prod' };
|
||||
|
||||
it('updateConfig PATCHes auth/config and applyConfig POSTs with an idempotency key', async () => {
|
||||
const config = {
|
||||
settings: { external_anonymous_users_enabled: true },
|
||||
secrets: { smtp_pass: false, external: {} },
|
||||
supported_providers: ['apple', 'google'],
|
||||
apply: { version: 2, applied_version: 2, status: 'applied', pending: false, error: null, operation_id: null },
|
||||
live: null,
|
||||
notes: [],
|
||||
};
|
||||
const { transport, calls } = makeTransport(config);
|
||||
const resource = new AuthResource(transport);
|
||||
const saved = await resource.updateConfig(ref, {
|
||||
external_anonymous_users_enabled: true,
|
||||
external: { apple: { enabled: true, client_id: 'com.example.app' } },
|
||||
});
|
||||
assert.equal(calls[0]!.options.method, 'PATCH');
|
||||
assert.ok(calls[0]!.options.path.endsWith('/environments/prod/auth/config'));
|
||||
assert.equal(saved.apply.pending, false);
|
||||
await resource.applyConfig(ref);
|
||||
assert.equal(calls[1]!.options.method, 'POST');
|
||||
assert.ok(calls[1]!.options.path.endsWith('/auth/config/apply'));
|
||||
assert.ok((calls[1]!.options.idempotencyKey ?? '').length > 0);
|
||||
});
|
||||
|
||||
it('listUsers calls the correct auth/users path', async () => {
|
||||
const result = { data: { users: [{ id: 'u-1' }] }, notes: [] };
|
||||
const { transport, calls } = makeTransport(result);
|
||||
const resource = new AuthResource(transport);
|
||||
const users = await resource.listUsers(ref);
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.ok(call.options.path.endsWith('/auth/users'));
|
||||
assert.equal(users.data.users.length, 1);
|
||||
});
|
||||
|
||||
it('listProviders calls the correct auth/providers path', async () => {
|
||||
const result = { data: { external: { google: true } }, notes: [] };
|
||||
const { transport, calls } = makeTransport(result);
|
||||
const resource = new AuthResource(transport);
|
||||
await resource.listProviders(ref);
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.ok(call.options.path.endsWith('/auth/providers'));
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// StorageResource
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('StorageResource', () => {
|
||||
const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'prod' };
|
||||
|
||||
it('listBuckets calls the correct storage/buckets path', async () => {
|
||||
const result = { buckets: [{ id: 'b-1', name: 'assets' }] };
|
||||
const { transport, calls } = makeTransport(result);
|
||||
const resource = new StorageResource(transport);
|
||||
const buckets = await resource.listBuckets(ref);
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.ok(call.options.path.endsWith('/storage/buckets'));
|
||||
assert.equal(buckets.buckets.length, 1);
|
||||
});
|
||||
|
||||
it('listObjects calls the correct buckets/{bucket}/objects path', async () => {
|
||||
const result = { bucket: 'assets', objects: [{ name: 'logo.png' }] };
|
||||
const { transport, calls } = makeTransport(result);
|
||||
const resource = new StorageResource(transport);
|
||||
const objects = await resource.listObjects(ref, 'assets');
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.ok(call.options.path.endsWith('/storage/buckets/assets/objects'));
|
||||
assert.equal(objects.objects.length, 1);
|
||||
});
|
||||
|
||||
it('listObjects passes prefix and limit as query params', async () => {
|
||||
const result = { bucket: 'assets', objects: [] };
|
||||
const { transport, calls } = makeTransport(result);
|
||||
const resource = new StorageResource(transport);
|
||||
await resource.listObjects(ref, 'assets', { prefix: 'images/', limit: 10 });
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.equal(call.options.query?.['prefix'], 'images/');
|
||||
assert.equal(call.options.query?.['limit'], 10);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FunctionsResource
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('FunctionsResource', () => {
|
||||
const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'prod' };
|
||||
|
||||
it('list calls the correct functions path', async () => {
|
||||
const result = {
|
||||
environment: ref,
|
||||
functions: [{ slug: 'hello-world' }],
|
||||
notes: null,
|
||||
};
|
||||
const { transport, calls } = makeTransport(result);
|
||||
const resource = new FunctionsResource(transport);
|
||||
const list = await resource.list(ref);
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.ok(call.options.path.endsWith('/functions'));
|
||||
assert.equal(list.functions.length, 1);
|
||||
assert.equal(list.notes, null);
|
||||
});
|
||||
|
||||
it('deploy sends multi-file bodies with verify_jwt and refuses an empty one', async () => {
|
||||
const { transport, calls } = makeTransport({ function: 'hello', result: { ok: true } });
|
||||
const resource = new FunctionsResource(transport);
|
||||
await resource.deploy(ref, {
|
||||
name: 'hello',
|
||||
files: { 'hello/index.ts': 'Deno.serve(() => new Response("hi"))', '_shared/a.ts': 'export {}' },
|
||||
entrypoint: 'hello/index.ts',
|
||||
verify_jwt: false,
|
||||
});
|
||||
const body = calls[0]!.options.body as Record<string, unknown>;
|
||||
assert.equal(calls[0]!.options.method, 'POST');
|
||||
assert.equal(body['verify_jwt'], false);
|
||||
assert.ok((body['files'] as Record<string, string>)['_shared/a.ts'] !== undefined);
|
||||
await assert.rejects(() => resource.deploy(ref, { name: 'hello' }), RangeError);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// UsageResource
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('UsageResource', () => {
|
||||
const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'prod' };
|
||||
const envelope = {
|
||||
environment: { organization_id: 'acme', project_id: 'store', environment_id: 'prod' },
|
||||
plan: 'base',
|
||||
flat_price_usd: 25,
|
||||
period_start_epoch_seconds: 0,
|
||||
period_end_epoch_seconds: 86400,
|
||||
lines: [
|
||||
{ metric: 'database_bytes', label: 'Database', used: 5, included: 8, cap: 8, unit: 'GB' },
|
||||
{ metric: 'storage_bytes', label: 'Storage', used: 10, included: 100, cap: 100, unit: 'GB' },
|
||||
],
|
||||
packs: [],
|
||||
};
|
||||
|
||||
it('get calls the env-scoped usage path', async () => {
|
||||
const { transport, calls } = makeTransport(envelope);
|
||||
const resource = new UsageResource(transport);
|
||||
const usage = await resource.get(ref);
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.ok(call.options.path.endsWith('/projects/store/environments/prod/usage'));
|
||||
assert.equal(usage.plan, 'base');
|
||||
});
|
||||
|
||||
it('capsNearingLimit filters by threshold', async () => {
|
||||
const { transport } = makeTransport(envelope);
|
||||
const resource = new UsageResource(transport);
|
||||
const nearing = await resource.capsNearingLimit(ref, 0.8);
|
||||
assert.equal(nearing.length, 0);
|
||||
});
|
||||
|
||||
it('capsNearingLimit finds lines above threshold', async () => {
|
||||
const nearFull = {
|
||||
...envelope,
|
||||
lines: [{ metric: 'database_bytes', label: 'Database', used: 7, included: 8, cap: 8, unit: 'GB' }],
|
||||
};
|
||||
const { transport } = makeTransport(nearFull);
|
||||
const resource = new UsageResource(transport);
|
||||
const nearing = await resource.capsNearingLimit(ref, 0.8);
|
||||
assert.equal(nearing.length, 1);
|
||||
assert.equal(nearing[0]!.metric, 'database_bytes');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MetricsResource
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('MetricsResource', () => {
|
||||
const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'prod' };
|
||||
|
||||
it('get calls the correct metrics path', async () => {
|
||||
const report = {
|
||||
environment: ref,
|
||||
source: 'postgres',
|
||||
range: { start_epoch_seconds: 0, end_epoch_seconds: 300, step_seconds: 60 },
|
||||
series: [
|
||||
{ metric: 'requests', unit: 'count', points: [{ epoch_seconds: 0, value: 42 }] },
|
||||
],
|
||||
notes: '',
|
||||
};
|
||||
const { transport, calls } = makeTransport(report);
|
||||
const resource = new MetricsResource(transport);
|
||||
const result = await resource.get(ref);
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.ok(call.options.path.endsWith('/metrics'));
|
||||
assert.equal(result.source, 'postgres');
|
||||
assert.equal(result.series.length, 1);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// AuditResource
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('AuditResource', () => {
|
||||
const sampleEvent: AuditEvent = {
|
||||
sequence: 1,
|
||||
actor_subject: 'user@example.com',
|
||||
action: 'create_environment',
|
||||
organization_id: 'acme',
|
||||
detail: 'environment store/production created',
|
||||
};
|
||||
|
||||
it('list calls the correct audit-events path', async () => {
|
||||
const { transport, calls } = makeTransport({ items: [sampleEvent] });
|
||||
const resource = new AuditResource(transport);
|
||||
const events = await resource.list('acme');
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.ok(call.options.path.includes('/audit-events'));
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0]!.action, 'create_environment');
|
||||
});
|
||||
|
||||
it('list passes after and limit query params', async () => {
|
||||
const { transport, calls } = makeTransport({ items: [] });
|
||||
const resource = new AuditResource(transport);
|
||||
await resource.list('acme', { after: 5, limit: 20 });
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.equal(call.options.query?.['after'], 5);
|
||||
assert.equal(call.options.query?.['limit'], 20);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DatabaseResource.generateTypes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('DatabaseResource.generateTypes', () => {
|
||||
const ref = { organizationId: 'acme', projectId: 'app', environmentId: 'production' };
|
||||
|
||||
it('calls the environment types path with the schema list', async () => {
|
||||
const { transport, calls } = makeTransport({ types: 'export type Database = {}', schemas: ['public', 'app'] });
|
||||
const resource = new DatabaseResource(transport);
|
||||
const result = await resource.generateTypes(ref, { schemas: ['public', 'app'] });
|
||||
|
||||
const call = calls[0]!;
|
||||
assert.equal(call.options.method, 'GET');
|
||||
assert.ok(call.options.path.endsWith('/environments/production/types'));
|
||||
assert.equal(call.options.query?.['schema'], 'public,app');
|
||||
assert.equal(result.types, 'export type Database = {}');
|
||||
});
|
||||
|
||||
it('defaults to the public schema and rejects empty or comma names', async () => {
|
||||
const { transport, calls } = makeTransport({ types: '', schemas: ['public'] });
|
||||
const resource = new DatabaseResource(transport);
|
||||
await resource.generateTypes(ref);
|
||||
assert.equal(calls[0]!.options.query?.['schema'], 'public');
|
||||
await assert.rejects(resource.generateTypes(ref, { schemas: [] }), RangeError);
|
||||
await assert.rejects(resource.generateTypes(ref, { schemas: ['a,b'] }), RangeError);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ProjectsResource quotas
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('ProjectsResource quotas', () => {
|
||||
const quotas = {
|
||||
organization_id: 'agency',
|
||||
project_id: 'customer-42',
|
||||
overrides: [
|
||||
{ metric: 'storage_gb', label: 'File storage', unit: 'GB', cap: 5, updated_by: 'u', updated_at_epoch_seconds: 1 },
|
||||
],
|
||||
metrics: [],
|
||||
threshold: 0.8,
|
||||
};
|
||||
|
||||
it('getQuotas reads the project quotas path', async () => {
|
||||
const { transport, calls } = makeTransport(quotas);
|
||||
const resource = new ProjectsResource(transport);
|
||||
const result = await resource.getQuotas('agency', 'customer-42');
|
||||
assert.equal(calls[0]!.options.method, 'GET');
|
||||
assert.equal(calls[0]!.options.path, '/v1/organizations/agency/projects/customer-42/quotas');
|
||||
assert.equal(result.overrides[0]!.cap, 5);
|
||||
});
|
||||
|
||||
it('setQuotas PUTs the overrides and validates caps', async () => {
|
||||
const { transport, calls } = makeTransport(quotas);
|
||||
const resource = new ProjectsResource(transport);
|
||||
await resource.setQuotas('agency', 'customer-42', { storage_gb: 5, rows: null });
|
||||
assert.equal(calls[0]!.options.method, 'PUT');
|
||||
assert.deepEqual(calls[0]!.options.body, { overrides: { storage_gb: 5, rows: null } });
|
||||
await assert.rejects(resource.setQuotas('agency', 'customer-42', {}), RangeError);
|
||||
await assert.rejects(resource.setQuotas('agency', 'customer-42', { rows: -1 }), RangeError);
|
||||
});
|
||||
});
|
||||
153
tests/sql.test.ts
Normal file
153
tests/sql.test.ts
Normal file
@ -0,0 +1,153 @@
|
||||
/**
|
||||
* Tests for `npx scribase sql`: argument parsing, which project and token it
|
||||
* uses, the execute request, destructive-statement confirmation, errors, and
|
||||
* the first-table SQL that init suggests (no network, in-memory files).
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { FIRST_TABLE_SQL, InitError } from '../src/cli/init.js';
|
||||
import { formatSql, parseSqlArgs, runSql } from '../src/cli/sql.js';
|
||||
import type { SqlIo } from '../src/cli/sql.js';
|
||||
|
||||
const ROOT = '/work/app';
|
||||
const STATE = JSON.stringify({
|
||||
organization_id: 'tmp-1',
|
||||
project_id: 'shop',
|
||||
environment_id: 'production',
|
||||
api_url: 'https://api.example.test',
|
||||
temporary: true,
|
||||
});
|
||||
|
||||
interface Seen {
|
||||
url: string;
|
||||
auth: string | null;
|
||||
body: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function io(files: Record<string, string>, answer: { status: number; body: unknown }, env: Record<string, string> = {}, stored: { token?: string } = {}) {
|
||||
const seen: Seen[] = [];
|
||||
const value: SqlIo = {
|
||||
cwd: ROOT,
|
||||
env,
|
||||
fetch: (async (url: string | URL | Request, init?: RequestInit) => {
|
||||
seen.push({
|
||||
url: String(url),
|
||||
auth: new Headers(init?.headers).get('authorization'),
|
||||
body: JSON.parse(String(init?.body)) as Record<string, unknown>,
|
||||
});
|
||||
return new Response(JSON.stringify(answer.body), { status: answer.status });
|
||||
}) as typeof fetch,
|
||||
readFile: (path) => files[path] ?? null,
|
||||
credentials: () => stored,
|
||||
};
|
||||
return { io: value, seen };
|
||||
}
|
||||
|
||||
const COMMITTED = {
|
||||
status: 'committed',
|
||||
duration_ms: 12,
|
||||
statements: [
|
||||
{ index: 0, command: 'CREATE TABLE', statement: 'create table notes (...)', kind: 'command', affected_rows: null },
|
||||
{ index: 1, command: 'SELECT', statement: 'select * from notes', kind: 'rows', row_count: 1, rows: [{ id: 1, body: 'hello from scribase' }] },
|
||||
],
|
||||
};
|
||||
|
||||
describe('scribase sql arguments', () => {
|
||||
it('joins the script, reads --file and takes --json and --confirm', () => {
|
||||
assert.deepEqual(parseSqlArgs(['select', '1'], () => null), { query: 'select 1', json: false, confirm: false });
|
||||
const files: Record<string, string> = { 'schema.sql': 'create table t (id int);' };
|
||||
assert.deepEqual(parseSqlArgs(['--file', 'schema.sql', '--json', '--confirm'], (path) => files[path] ?? null), {
|
||||
query: 'create table t (id int);',
|
||||
json: true,
|
||||
confirm: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects an empty script, a missing file and unknown flags', () => {
|
||||
assert.throws(() => parseSqlArgs([], () => null), (error: unknown) => error instanceof InitError && error.code === 'invalid_argument');
|
||||
assert.throws(() => parseSqlArgs(['--file', 'nope.sql'], () => null), (error: unknown) => error instanceof InitError && error.code === 'file_not_found');
|
||||
assert.throws(() => parseSqlArgs(['select 1', '--force'], () => null), /unknown option --force/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('scribase sql', () => {
|
||||
it('runs on this folder’s project with the temporary project’s token from the env file', async () => {
|
||||
const { io: value, seen } = io(
|
||||
{ [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/.env.local`]: 'SCRIBASE_ACCESS_TOKEN=scb_agt_tmp\n' },
|
||||
{ status: 200, body: COMMITTED },
|
||||
{},
|
||||
{ token: 'scb_stored' },
|
||||
);
|
||||
const result = await runSql({ query: FIRST_TABLE_SQL, json: false, confirm: false }, value);
|
||||
assert.equal(result.status, 'committed');
|
||||
assert.equal(seen[0]?.url, 'https://api.example.test/v1/organizations/tmp-1/projects/shop/environments/production/database/execute');
|
||||
assert.equal(seen[0]?.auth, 'Bearer scb_agt_tmp', 'the env file token wins over the stored login');
|
||||
assert.deepEqual(seen[0]?.body, { query: FIRST_TABLE_SQL });
|
||||
const text = formatSql(result);
|
||||
assert.match(text, /CREATE TABLE/);
|
||||
assert.match(text, /"body":"hello from scribase"/);
|
||||
assert.doesNotMatch(text, /scb_agt_tmp/, 'the token is never printed');
|
||||
assert.match(text, /reloads its schema/, 'a schema change says when the REST API sees it');
|
||||
});
|
||||
|
||||
it('prefers SCRIBASE_ACCESS_TOKEN and falls back to the stored login', async () => {
|
||||
const files = { [`${ROOT}/.scribase/project.json`]: STATE };
|
||||
const fromEnv = io(files, { status: 200, body: COMMITTED }, { SCRIBASE_ACCESS_TOKEN: 'scb_env' }, { token: 'scb_stored' });
|
||||
await runSql({ query: 'select 1', json: true, confirm: false }, fromEnv.io);
|
||||
assert.equal(fromEnv.seen[0]?.auth, 'Bearer scb_env');
|
||||
const stored = io(files, { status: 200, body: COMMITTED }, {}, { token: 'scb_stored' });
|
||||
await runSql({ query: 'select 1', json: true, confirm: false }, stored.io);
|
||||
assert.equal(stored.seen[0]?.auth, 'Bearer scb_stored');
|
||||
});
|
||||
|
||||
it('passes --confirm and reports statements that need it', async () => {
|
||||
const pending = io(
|
||||
{ [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/.env`]: 'SCRIBASE_ACCESS_TOKEN=t\n' },
|
||||
{ status: 200, body: { status: 'confirmation_required', statement_count: 1, destructive: [{ index: 0, command: 'DROP TABLE', statement: 'drop table notes', reason: 'drops a table' }] } },
|
||||
);
|
||||
const result = await runSql({ query: 'drop table notes', json: false, confirm: false }, pending.io);
|
||||
assert.equal(result.status, 'confirmation_required');
|
||||
assert.match(formatSql(result), /Nothing ran.*\n.*DROP TABLE: drops a table[\s\S]*--confirm/);
|
||||
const confirmed = io({ [`${ROOT}/.scribase/project.json`]: STATE, [`${ROOT}/.env`]: 'SCRIBASE_ACCESS_TOKEN=t\n' }, { status: 200, body: COMMITTED });
|
||||
await runSql({ query: 'drop table notes', json: false, confirm: true }, confirmed.io);
|
||||
assert.equal(confirmed.seen[0]?.body.confirm, true);
|
||||
});
|
||||
|
||||
it('says what to do when the folder is not initialized, has no token, or the token is refused', async () => {
|
||||
await assert.rejects(
|
||||
runSql({ query: 'select 1', json: false, confirm: false }, io({}, { status: 200, body: {} }).io),
|
||||
(error: unknown) => error instanceof InitError && error.code === 'not_initialized' && /scribase init/.test(error.next ?? ''),
|
||||
);
|
||||
await assert.rejects(
|
||||
runSql({ query: 'select 1', json: false, confirm: false }, io({ [`${ROOT}/.scribase/project.json`]: STATE }, { status: 200, body: {} }).io),
|
||||
(error: unknown) => error instanceof InitError && error.code === 'not_signed_in',
|
||||
);
|
||||
const refused = io(
|
||||
{ [`${ROOT}/.scribase/project.json`]: STATE },
|
||||
{ status: 401, body: { code: 'unauthorized', detail: 'token expired' } },
|
||||
{ SCRIBASE_ACCESS_TOKEN: 'old' },
|
||||
);
|
||||
await assert.rejects(
|
||||
runSql({ query: 'select 1', json: false, confirm: false }, refused.io),
|
||||
(error: unknown) => error instanceof InitError && error.code === 'unauthorized' && /HTTP 401/.test(error.message) && /init/.test(error.next ?? ''),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the first table init suggests', () => {
|
||||
it('creates, fills and exposes read-only the table the next step queries', () => {
|
||||
assert.match(FIRST_TABLE_SQL, /^create table notes \(/);
|
||||
assert.match(FIRST_TABLE_SQL, /insert into notes/);
|
||||
assert.match(FIRST_TABLE_SQL, /enable row level security/);
|
||||
assert.match(FIRST_TABLE_SQL, /for select using \(true\)/);
|
||||
assert.match(FIRST_TABLE_SQL, /grant select on notes to anon, authenticated/);
|
||||
assert.doesNotMatch(FIRST_TABLE_SQL, /\b(drop|truncate|delete)\b/i, 'never needs --confirm');
|
||||
assert.doesNotMatch(FIRST_TABLE_SQL, /grant (insert|update|delete|all)/i, 'the public key can only read');
|
||||
});
|
||||
|
||||
it('pastes safely inside double quotes in any shell', () => {
|
||||
assert.doesNotMatch(FIRST_TABLE_SQL, /["`$!\\]/);
|
||||
});
|
||||
});
|
||||
255
tests/vercel.test.ts
Normal file
255
tests/vercel.test.ts
Normal file
@ -0,0 +1,255 @@
|
||||
/**
|
||||
* Tests for the zero-config Vercel push in `npx scribase init`: link
|
||||
* detection, the request (token via fetch, signed-in CLI via spawn with the
|
||||
* body on stdin), outcomes that never fail init, and no secret in output.
|
||||
*/
|
||||
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { parseInitArgs, runInit } from '../src/cli/init.js';
|
||||
import type { InitIo } from '../src/cli/init.js';
|
||||
import { requestPath, resolveLink, syncVercel, vercelEnvVars, vercelLine } from '../src/cli/vercel.js';
|
||||
import type { SpawnOutcome, VercelIo } from '../src/cli/vercel.js';
|
||||
|
||||
const ROOT = '/work/app';
|
||||
const LINK = JSON.stringify({ projectId: 'prj_abc123', orgId: 'team_xyz' });
|
||||
const INPUT = {
|
||||
organization: 'acme',
|
||||
project: 'shop',
|
||||
environment: 'production',
|
||||
apiUrl: 'https://shop-production.scribase.app/',
|
||||
anonKey: 'eyJanon',
|
||||
serviceRoleKey: 'eyJservice',
|
||||
};
|
||||
|
||||
interface FetchCall {
|
||||
url: string;
|
||||
method: string;
|
||||
auth: string | null;
|
||||
body: unknown;
|
||||
}
|
||||
|
||||
interface SpawnCall {
|
||||
command: string;
|
||||
args: string[];
|
||||
input?: string;
|
||||
}
|
||||
|
||||
function vercelIo(options: {
|
||||
files?: Record<string, string>;
|
||||
env?: Record<string, string>;
|
||||
respond?: (call: FetchCall) => { status: number; body: unknown };
|
||||
spawn?: (call: SpawnCall) => SpawnOutcome;
|
||||
}) {
|
||||
const fetches: FetchCall[] = [];
|
||||
const spawns: SpawnCall[] = [];
|
||||
const files = options.files ?? {};
|
||||
const io: VercelIo = {
|
||||
cwd: ROOT,
|
||||
env: options.env ?? {},
|
||||
fetch: (async (url: string | URL | Request, init?: RequestInit) => {
|
||||
const call: FetchCall = {
|
||||
url: String(url),
|
||||
method: init?.method ?? 'GET',
|
||||
auth: new Headers(init?.headers).get('authorization'),
|
||||
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
||||
};
|
||||
fetches.push(call);
|
||||
const answer = options.respond?.(call) ?? { status: 201, body: { created: [], failed: [] } };
|
||||
return new Response(JSON.stringify(answer.body), { status: answer.status });
|
||||
}) as typeof fetch,
|
||||
readFile: (path) => files[path] ?? null,
|
||||
spawn: async (command, args, spawnOptions) => {
|
||||
const call: SpawnCall = { command, args, ...(spawnOptions.input !== undefined ? { input: spawnOptions.input } : {}) };
|
||||
spawns.push(call);
|
||||
return options.spawn?.(call) ?? { code: 1, stdout: '', stderr: 'not signed in' };
|
||||
},
|
||||
};
|
||||
return { io, fetches, spawns };
|
||||
}
|
||||
|
||||
describe('Vercel link detection', () => {
|
||||
it('reads .vercel/project.json, prefers VERCEL_PROJECT_ID, and is null when unlinked', () => {
|
||||
const readFile = (path: string) => (path === `${ROOT}/.vercel/project.json` ? LINK : null);
|
||||
assert.deepEqual(resolveLink({ cwd: ROOT, env: {}, readFile }), { projectId: 'prj_abc123', orgId: 'team_xyz' });
|
||||
assert.deepEqual(resolveLink({ cwd: ROOT, env: { VERCEL_PROJECT_ID: 'prj_env' }, readFile }), { projectId: 'prj_env' });
|
||||
assert.equal(resolveLink({ cwd: ROOT, env: {}, readFile: () => null }), null);
|
||||
assert.throws(() => resolveLink({ cwd: ROOT, env: {}, readFile: () => '{"projectId":"a b"}' }), /projectId/);
|
||||
assert.throws(() => resolveLink({ cwd: ROOT, env: { VERCEL_PROJECT_ID: '../x' }, readFile }), /VERCEL_PROJECT_ID/);
|
||||
});
|
||||
|
||||
it('sends teamId only for team projects', () => {
|
||||
assert.equal(requestPath({ projectId: 'prj_1', orgId: 'team_2' }), '/v10/projects/prj_1/env?upsert=true&teamId=team_2');
|
||||
assert.equal(requestPath({ projectId: 'prj_1', orgId: 'user_2' }), '/v10/projects/prj_1/env?upsert=true');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vercel variables', () => {
|
||||
it('matches the console names; the service key is sensitive, server-only and not on development', () => {
|
||||
const vars = vercelEnvVars(INPUT);
|
||||
assert.deepEqual(
|
||||
vars.map((v) => v.key),
|
||||
[
|
||||
'NEXT_PUBLIC_SUPABASE_URL',
|
||||
'NEXT_PUBLIC_SUPABASE_ANON_KEY',
|
||||
'NEXT_PUBLIC_SCRIBASE_URL',
|
||||
'NEXT_PUBLIC_SCRIBASE_ANON_KEY',
|
||||
'SCRIBASE_ORG',
|
||||
'SCRIBASE_PROJECT',
|
||||
'SCRIBASE_ENV',
|
||||
'SUPABASE_SERVICE_ROLE_KEY',
|
||||
'SCRIBASE_SERVICE_ROLE_KEY',
|
||||
],
|
||||
);
|
||||
assert.equal(vars[0]?.value, 'https://shop-production.scribase.app');
|
||||
for (const v of vars.filter((item) => item.value === 'eyJservice')) {
|
||||
assert.equal(v.type, 'sensitive');
|
||||
assert.ok(!v.key.startsWith('NEXT_PUBLIC_'));
|
||||
assert.deepEqual(v.target, ['preview', 'production']);
|
||||
}
|
||||
assert.equal(vercelEnvVars({ ...INPUT, serviceRoleKey: null }).length, 7);
|
||||
});
|
||||
});
|
||||
|
||||
describe('syncVercel', () => {
|
||||
it('pushes with VERCEL_TOKEN in one upsert request', async () => {
|
||||
const { io, fetches, spawns } = vercelIo({
|
||||
files: { [`${ROOT}/.vercel/project.json`]: LINK },
|
||||
env: { VERCEL_TOKEN: 'vt_secret' },
|
||||
});
|
||||
const result = await syncVercel(io, INPUT);
|
||||
assert.equal(result.status, 'updated');
|
||||
assert.deepEqual(result.targets, ['development', 'preview', 'production']);
|
||||
assert.equal(result.via, 'VERCEL_TOKEN');
|
||||
assert.equal(fetches.length, 1);
|
||||
assert.equal(fetches[0]?.url, 'https://api.vercel.com/v10/projects/prj_abc123/env?upsert=true&teamId=team_xyz');
|
||||
assert.equal(fetches[0]?.method, 'POST');
|
||||
assert.equal(fetches[0]?.auth, 'Bearer vt_secret');
|
||||
assert.equal((fetches[0]?.body as unknown[]).length, 9);
|
||||
assert.equal(spawns.length, 0, 'no CLI with a token');
|
||||
assert.equal(vercelLine(result), 'Vercel env updated for development, preview, production');
|
||||
assert.ok(!JSON.stringify(result).includes('vt_secret'));
|
||||
});
|
||||
|
||||
it('uses the signed-in vercel CLI without a token, body on stdin, never argv', async () => {
|
||||
const { io, fetches, spawns } = vercelIo({
|
||||
files: { [`${ROOT}/.vercel/project.json`]: LINK },
|
||||
spawn: (call) => ({ code: 0, stdout: call.args[0] === 'api' ? '{"created":[],"failed":[]}' : 'me', stderr: '' }),
|
||||
});
|
||||
const result = await syncVercel(io, INPUT);
|
||||
assert.equal(result.status, 'updated');
|
||||
assert.equal(result.via, 'vercel CLI');
|
||||
assert.equal(fetches.length, 0);
|
||||
assert.deepEqual(spawns[0]?.args, ['whoami', '--non-interactive']);
|
||||
const api = spawns[1];
|
||||
assert.deepEqual(api?.args.slice(0, 7), ['api', '/v10/projects/prj_abc123/env?upsert=true&teamId=team_xyz', '-X', 'POST', '--input', '-', '--raw']);
|
||||
assert.ok(!api?.args.some((arg) => arg.includes('eyJ')), 'no key in argv');
|
||||
assert.match(api?.input ?? '', /eyJservice/);
|
||||
});
|
||||
|
||||
it('skips when not linked or without credentials, and reports Vercel errors without throwing', async () => {
|
||||
const unlinked = await syncVercel(vercelIo({ env: { VERCEL_TOKEN: 'vt' } }).io, INPUT);
|
||||
assert.deepEqual(unlinked, { status: 'not_linked', targets: [] });
|
||||
assert.equal(vercelLine(unlinked), 'Not linked to Vercel — skipped');
|
||||
|
||||
const noCreds = await syncVercel(vercelIo({ files: { [`${ROOT}/.vercel/project.json`]: LINK } }).io, INPUT);
|
||||
assert.equal(noCreds.status, 'no_credentials');
|
||||
assert.equal(vercelLine(noCreds), 'No Vercel credentials — skipped');
|
||||
|
||||
const refused = await syncVercel(
|
||||
vercelIo({
|
||||
files: { [`${ROOT}/.vercel/project.json`]: LINK },
|
||||
env: { VERCEL_TOKEN: 'vt_secret' },
|
||||
respond: () => ({ status: 403, body: { error: { code: 'forbidden', message: 'Not authorized' } } }),
|
||||
}).io,
|
||||
INPUT,
|
||||
);
|
||||
assert.equal(refused.status, 'failed');
|
||||
assert.match(refused.error ?? '', /HTTP 403: Not authorized/);
|
||||
assert.ok(!(refused.error ?? '').includes('vt_secret'));
|
||||
|
||||
const partial = await syncVercel(
|
||||
vercelIo({
|
||||
files: { [`${ROOT}/.vercel/project.json`]: LINK },
|
||||
env: { VERCEL_TOKEN: 'vt' },
|
||||
respond: () => ({ status: 201, body: { created: [], failed: [{ error: { message: 'bad key' } }] } }),
|
||||
}).io,
|
||||
INPUT,
|
||||
);
|
||||
assert.equal(partial.status, 'failed');
|
||||
assert.match(partial.error ?? '', /bad key/);
|
||||
|
||||
const broken = await syncVercel(vercelIo({ files: { [`${ROOT}/.vercel/project.json`]: 'nope' }, env: { VERCEL_TOKEN: 'vt' } }).io, INPUT);
|
||||
assert.equal(broken.status, 'failed');
|
||||
|
||||
const badToken = await syncVercel(vercelIo({ files: { [`${ROOT}/.vercel/project.json`]: LINK }, env: { VERCEL_TOKEN: 'a\nb' } }).io, INPUT);
|
||||
assert.equal(badToken.status, 'failed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('init pushes to a linked Vercel project', () => {
|
||||
const KEYS = { api_url: 'https://shop-production.scribase.app', anon_key: 'eyJanon', service_role_key: 'eyJservice' };
|
||||
|
||||
function initIo(files: Record<string, string>, env: Record<string, string>, vercelStatus = 201) {
|
||||
const vercelCalls: string[] = [];
|
||||
const io: InitIo = {
|
||||
cwd: ROOT,
|
||||
env,
|
||||
fetch: (async (url: string | URL | Request) => {
|
||||
const target = new URL(String(url));
|
||||
if (target.hostname === 'api.vercel.com') {
|
||||
vercelCalls.push(`${target.pathname}${target.search}`);
|
||||
return new Response(JSON.stringify(vercelStatus === 201 ? { failed: [] } : { error: { message: 'nope' } }), { status: vercelStatus });
|
||||
}
|
||||
const path = target.pathname;
|
||||
if (path === '/v1/organizations') return Response.json({ items: [{ organization_id: 'acme' }] });
|
||||
if (path.endsWith('/environments/production')) return Response.json({ phase: 'ready' });
|
||||
if (path.endsWith('/api-keys')) return Response.json(KEYS);
|
||||
return Response.json({}, { status: path === '/v1/environments' ? 202 : 200 });
|
||||
}) as typeof fetch,
|
||||
readFile: (path) => files[path] ?? null,
|
||||
writeFile: (path, contents) => {
|
||||
files[path] = contents;
|
||||
},
|
||||
exists: (path) => path in files,
|
||||
run: () => ({ ok: true, output: '' }),
|
||||
sleep: async () => {},
|
||||
log: () => {},
|
||||
credentials: () => ({}),
|
||||
};
|
||||
return { io, vercelCalls };
|
||||
}
|
||||
|
||||
const PKG = JSON.stringify({ dependencies: { next: '15', '@supabase/supabase-js': '2' } });
|
||||
|
||||
it('after writing .env, updates Vercel and reports {status, targets}', async () => {
|
||||
const files = { [`${ROOT}/package.json`]: PKG, [`${ROOT}/.vercel/project.json`]: LINK };
|
||||
const { io, vercelCalls } = initIo(files, { SCRIBASE_ACCESS_TOKEN: 'scb_pat', VERCEL_TOKEN: 'vt_secret' });
|
||||
const result = await runInit(parseInitArgs(['--yes', '--json', '--name', 'shop']), io);
|
||||
assert.deepEqual(result.vercel, { status: 'updated', targets: ['development', 'preview', 'production'], project_id: 'prj_abc123' });
|
||||
assert.deepEqual(vercelCalls, ['/v10/projects/prj_abc123/env?upsert=true&teamId=team_xyz']);
|
||||
assert.ok(files[`${ROOT}/.env.local`], 'env file written');
|
||||
assert.ok(!JSON.stringify(result).includes('vt_secret'));
|
||||
});
|
||||
|
||||
it('never fails init when Vercel refuses, and --no-vercel skips it', async () => {
|
||||
const files = { [`${ROOT}/package.json`]: PKG, [`${ROOT}/.vercel/project.json`]: LINK };
|
||||
const refused = initIo({ ...files }, { SCRIBASE_ACCESS_TOKEN: 'scb_pat', VERCEL_TOKEN: 'vt' }, 403);
|
||||
const result = await runInit(parseInitArgs(['--yes', '--name', 'shop']), refused.io);
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.vercel.status, 'failed');
|
||||
assert.deepEqual(result.vercel.targets, []);
|
||||
|
||||
const off = initIo({ ...files }, { SCRIBASE_ACCESS_TOKEN: 'scb_pat', VERCEL_TOKEN: 'vt' });
|
||||
const skipped = await runInit(parseInitArgs(['--yes', '--no-vercel', '--name', 'shop']), off.io);
|
||||
assert.equal(skipped.vercel.status, 'disabled');
|
||||
assert.equal(off.vercelCalls.length, 0);
|
||||
});
|
||||
|
||||
it('reports not_linked for an unlinked folder', async () => {
|
||||
const { io } = initIo({ [`${ROOT}/package.json`]: PKG }, { SCRIBASE_ACCESS_TOKEN: 'scb_pat' });
|
||||
const result = await runInit(parseInitArgs(['--yes', '--name', 'shop']), io);
|
||||
assert.deepEqual(result.vercel, { status: 'not_linked', targets: [] });
|
||||
});
|
||||
});
|
||||
25
tsconfig.json
Normal file
25
tsconfig.json
Normal file
@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022", "DOM"],
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"exactOptionalPropertyTypes": true,
|
||||
"noImplicitOverride": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noImplicitReturns": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"skipLibCheck": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"isolatedModules": true
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["dist", "node_modules", "scripts", "tests"]
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user