@firstdraft.com/cli 0.1.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +267 -0
- package/bin/firstdraft.js +19 -0
- package/package.json +49 -0
- package/src/api-authentication.js +37 -0
- package/src/api-response.js +158 -0
- package/src/application-identity.js +149 -0
- package/src/cli.js +2056 -0
- package/src/commands/compilation.js +823 -0
- package/src/commands/plan-compile.js +150 -0
- package/src/commands/plan-init.js +79 -0
- package/src/commands/plan-publish.js +994 -0
- package/src/commands/plan-push.js +302 -0
- package/src/commands/plan-status.js +485 -0
- package/src/compilation-artifact.js +717 -0
- package/src/file-system.js +12 -0
- package/src/plan-state.js +214 -0
- package/src/uuid-v7.js +55 -0
- package/src/version.js +11 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 First Draft contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
# First Draft CLI
|
|
2
|
+
|
|
3
|
+
`firstdraft` is the command-line client for [First Draft](https://github.com/firstdraft/firstdraft). It is being
|
|
4
|
+
built for agents that author and review Foundation Plans with their users.
|
|
5
|
+
|
|
6
|
+
Public alpha releases use npm's `next` tag. This release line contains the auditable command shell, local Foundation
|
|
7
|
+
Plan initialization, local application-key and UUID generation, conditional whole-document push, whole-graph
|
|
8
|
+
analysis status polling, compile-and-publish orchestration, and read-only retained-Compilation download.
|
|
9
|
+
Interfaces may change between prereleases, and publishing the CLI does not make the wider First Draft service
|
|
10
|
+
generally available.
|
|
11
|
+
|
|
12
|
+
## Requirements
|
|
13
|
+
|
|
14
|
+
- Running the CLI: Node.js 22.0.0 or newer
|
|
15
|
+
- Working on this repository: Node.js 24.18.0 (pinned in `.tool-versions`)
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
Once npm reports a public alpha, install the current prerelease explicitly:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm install --global @firstdraft.com/cli@next
|
|
23
|
+
firstdraft --version
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
The npm package is `@firstdraft.com/cli`; it installs the `firstdraft` executable.
|
|
27
|
+
|
|
28
|
+
There is intentionally no stable `latest` release yet. Pin an exact prerelease version instead of `next` when a
|
|
29
|
+
repeatable installation matters. Remote Plan and Compilation commands require a
|
|
30
|
+
compatible First Draft service and are currently intended for coordinated trials.
|
|
31
|
+
|
|
32
|
+
## Authenticate API commands
|
|
33
|
+
|
|
34
|
+
Create an API token in First Draft and provide it only through the environment when running a network command:
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
export FIRSTDRAFT_API_TOKEN="your-token"
|
|
38
|
+
firstdraft plan push
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`plan push`, `plan status`, `plan compile`, and `compilation` subcommands send the token as a Bearer credential on
|
|
42
|
+
every API request. The CLI does not save it in `.firstdraft`, print it, or require it for local commands such as
|
|
43
|
+
`plan init` and `generate`. Revoke the token in First Draft if it is exposed. A missing token, or First Draft's validated
|
|
44
|
+
`401` problem response with the `authentication_required` code, produces that stable CLI error.
|
|
45
|
+
|
|
46
|
+
## Development
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
npm ci
|
|
50
|
+
npm run check
|
|
51
|
+
npm run pack:check
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
To reproduce the length-delimited SHA-256 used by external evidence to identify the packaged JavaScript runtime
|
|
55
|
+
inputs (`package.json`, `bin/firstdraft.js`, and every `.js` file under `src/`), run from the repository root:
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
node scripts/runtime-digest.js
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Start a Foundation Plan
|
|
62
|
+
|
|
63
|
+
From the project that the Plan describes:
|
|
64
|
+
|
|
65
|
+
```sh
|
|
66
|
+
firstdraft plan init --name "Oscar Party"
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
This creates an empty `sketch/0.19` Plan and client-generated Project ID under `.firstdraft/`. A nested ignore file
|
|
70
|
+
keeps that local scratch area out of Git without changing the project's own `.gitignore`. Initialization makes no
|
|
71
|
+
network request and refuses to replace an existing `.firstdraft` path.
|
|
72
|
+
|
|
73
|
+
Provide either `--name`, `--application-key`, or both. Name-only initialization derives a lower-snake key. Key-only
|
|
74
|
+
initialization derives a humanized display name. Supplying both preserves both values exactly after
|
|
75
|
+
validating them against the Foundation Plan schema. To inspect the name-to-key derivation without initializing a
|
|
76
|
+
project, run:
|
|
77
|
+
|
|
78
|
+
```sh
|
|
79
|
+
firstdraft generate application-key --name "Oscar Party"
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
The generated key is deterministic, starts with a letter, contains only lowercase ASCII letters, digits, and
|
|
83
|
+
underscores, and is at most 63 bytes so it can lower to the current iOS application identifier component. Names
|
|
84
|
+
without a readable ASCII form receive a stable digest-based key. Longer readable names are shortened to a readable
|
|
85
|
+
prefix plus a stable digest suffix. Explicit application keys retain the Foundation Plan's broader
|
|
86
|
+
`^[a-z][a-z0-9_]*$` boundary and are left for target analysis rather than silently rewritten.
|
|
87
|
+
|
|
88
|
+
## Add Foundation Plan subjects
|
|
89
|
+
|
|
90
|
+
Generate an identity before adding each new independently mutable authored subject:
|
|
91
|
+
|
|
92
|
+
```sh
|
|
93
|
+
firstdraft generate uuid
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
The command prints one UUIDv7 for the subject's `subject_uuid`. It does not read or modify the Plan, reserve the
|
|
97
|
+
value, or make a network request. Preserve that UUID when renaming the subject or moving it to a different semantic
|
|
98
|
+
owner without changing its kind. Use a new UUID for a replacement concept. Readable keys and paths may change and
|
|
99
|
+
remain the document's links; the UUID preserves continuity between complete-document pushes.
|
|
100
|
+
|
|
101
|
+
Use `--count <n>` to print several independently generated UUIDv7 values, one per line.
|
|
102
|
+
|
|
103
|
+
## Push a Foundation Plan
|
|
104
|
+
|
|
105
|
+
From the initialized project:
|
|
106
|
+
|
|
107
|
+
```sh
|
|
108
|
+
firstdraft plan push
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
The command sends the exact bytes in `.firstdraft/foundation-plan.json`. The first push conditionally creates the
|
|
112
|
+
Project; later pushes replay the complete ETag saved in `.firstdraft/state.json` so a stale writer cannot replace a
|
|
113
|
+
newer Plan. Successful responses and server diagnostics are printed as JSON for an agent to inspect.
|
|
114
|
+
|
|
115
|
+
The initial API origin defaults to `https://firstdraft.com`. Set `FIRSTDRAFT_API_URL` to use another HTTPS origin
|
|
116
|
+
or a loopback HTTP development server. The first successful push pins the normalized origin in local state, and a
|
|
117
|
+
later override must match it.
|
|
118
|
+
|
|
119
|
+
If a failure happens after sending the request, the CLI reports that the outcome may be ambiguous and leaves local
|
|
120
|
+
state unchanged. It never constructs an ETag from the Plan digest or trusts an ETag from a response it could not
|
|
121
|
+
fully verify. Until First Draft has a Foundation Plan head reconciliation endpoint, an accepted request whose
|
|
122
|
+
response cannot be verified may require manual recovery. If a verified response cannot replace local state,
|
|
123
|
+
preserve the printed recovery state; an adjacent `.tmp` file may contain the same private recovery copy.
|
|
124
|
+
|
|
125
|
+
## Read analysis status
|
|
126
|
+
|
|
127
|
+
After a successful push:
|
|
128
|
+
|
|
129
|
+
```sh
|
|
130
|
+
firstdraft plan status
|
|
131
|
+
firstdraft plan status --wait
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Without `--wait`, the command makes one `GET` and prints the current analysis as one JSON object. With `--wait`, it
|
|
135
|
+
polls sequentially once per second for at most two minutes and stops at `valid`, `issues_found`, `analysis_failed`,
|
|
136
|
+
or `superseded`. Every validated analysis status is a successful read with exit 0; agents should branch on the
|
|
137
|
+
`analysis.status` value and inspect `analysis.diagnostics` rather than treating a completed analysis with issues as
|
|
138
|
+
a transport failure.
|
|
139
|
+
|
|
140
|
+
Status reads require the API origin pinned by a successful push. They never select an origin from the current
|
|
141
|
+
environment, expose the private ETag, follow redirects, or modify local state. Each request has a bounded timeout,
|
|
142
|
+
every response is byte-bounded and fully validated, and polling will not silently switch to a replacement analysis.
|
|
143
|
+
The wait repeats only validated `processing` responses and stops on its first failed read. A network failure is safe
|
|
144
|
+
to retry a bounded number of times because the command sends only `GET` requests. If `status_unavailable` persists,
|
|
145
|
+
inspect the API origin pinned in `.firstdraft/state.json`; an invalid server response instead requires reconciling the
|
|
146
|
+
CLI and server contract.
|
|
147
|
+
|
|
148
|
+
## Compile and publish the current Plan
|
|
149
|
+
|
|
150
|
+
When the candidate is ready, run:
|
|
151
|
+
|
|
152
|
+
```sh
|
|
153
|
+
firstdraft plan compile
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
`plan compile` is the single terminal action. It first pushes the exact current bytes in
|
|
157
|
+
`.firstdraft/foundation-plan.json`, even when those bytes are unchanged, and saves the accepted ETag using the same
|
|
158
|
+
contract as `plan push`. It then waits up to two minutes for an analysis whose graph version exactly matches that
|
|
159
|
+
accepted push, polling past a terminal result retained for an older Head. Invalid JSON, schema diagnostics,
|
|
160
|
+
semantic diagnostics, a failed analysis, a superseded analysis, or a recurring diagnostic stop the command with
|
|
161
|
+
structured output; no Compilation or Publication is requested.
|
|
162
|
+
|
|
163
|
+
Only a `valid` analysis proceeds to the internal GitHub Publication lifecycle. Invoking `plan compile` is the
|
|
164
|
+
authorization to request that lifecycle. Immediately before its conditional mutation, the CLI re-reads the local
|
|
165
|
+
Plan and requires its exact bytes to match the accepted Head, so bytes changed after analysis cannot be published.
|
|
166
|
+
It extracts the accepted source SHA-256 from the saved ETag, hashes the current local bytes, and then sends that
|
|
167
|
+
complete ETag in `If-Match`.
|
|
168
|
+
The command writes no progress output to stdout. Success is exactly one validated JSON object containing the
|
|
169
|
+
retained `project`, `compilation`, and `publication`, including the private GitHub repository URL.
|
|
170
|
+
|
|
171
|
+
The internal Publication is a Project singleton in this release. A repeat safely receives the same Publication
|
|
172
|
+
instead of creating another. If the first conditional `PUT` has an ambiguous result, the CLI reconciles it with
|
|
173
|
+
one read-only singleton `GET` and never automatically repeats the mutation. Rerunning `plan compile` safely
|
|
174
|
+
replays the singleton request. Publication polling is sequential, bounded to ten minutes, and pinned to the
|
|
175
|
+
retained Project Head, Compilation input, Publication identity, and repository identity.
|
|
176
|
+
|
|
177
|
+
This release cannot repoint a Project's Publication to a later accepted Head. The public CLI therefore has no
|
|
178
|
+
`plan publish` command and no local-start `plan compile --output` mode. Use the standalone retained-Compilation
|
|
179
|
+
commands below when local generated source is useful.
|
|
180
|
+
|
|
181
|
+
## Inspect a retained Compilation
|
|
182
|
+
|
|
183
|
+
Read one Compilation ID returned by `plan compile`:
|
|
184
|
+
|
|
185
|
+
```sh
|
|
186
|
+
firstdraft compilation status 01900000-0000-7000-8000-000000000001
|
|
187
|
+
firstdraft compilation status 01900000-0000-7000-8000-000000000001 --wait
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Without `--wait`, the command makes exactly one metadata-only `GET`. With `--wait`, it polls that same
|
|
191
|
+
Compilation sequentially for at most ten minutes and rejects changes to its identity, Head provenance, target, or
|
|
192
|
+
lifecycle progression. `failed` and `cancelled` are successfully read terminal states with exit 0; branch on
|
|
193
|
+
`compilation.status` and inspect its validated `failure`.
|
|
194
|
+
|
|
195
|
+
## Download a retained Compilation
|
|
196
|
+
|
|
197
|
+
Materialize an already successful Compilation into an absent path:
|
|
198
|
+
|
|
199
|
+
```sh
|
|
200
|
+
firstdraft compilation download 01900000-0000-7000-8000-000000000001 --output ../movie-catalog
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
The command validates the UUID and output path before network access, makes one status `GET`, requires
|
|
204
|
+
`succeeded`, and makes one artifact `GET`. It never starts work or polls. Historical artifact validation uses
|
|
205
|
+
the retained `compilation.head_source_sha256`, not the current local Plan or ETag, to pin the artifact's exact
|
|
206
|
+
`head_source_sha256`. The artifact's canonical `foundation_plan.sha256` may differ because it identifies the
|
|
207
|
+
normalized Compiler input. It is validated as a SHA-256 digest inside the exact artifact bytes authenticated by
|
|
208
|
+
the status response's `artifact.sha256`; it is not equated to the submitted Head digest.
|
|
209
|
+
|
|
210
|
+
Before materialization, the CLI verifies the artifact media type, declared and actual byte sizes, strong digest
|
|
211
|
+
ETag, exact-byte SHA-256, canonical UTF-8 JSON envelope, provenance, metadata-only manifest digest, portable paths,
|
|
212
|
+
strict Base64 contents, file digests, modes, owners, and source-subject UUIDs. It writes only into a uniquely
|
|
213
|
+
created sibling directory, verifies the complete tree, and atomically renames it into the still-absent destination.
|
|
214
|
+
On POSIX, directories use mode `0755` and files use artifact-declared `0644` or `0755`; Windows verifies
|
|
215
|
+
structure, contents, and digests without claiming POSIX mode bits.
|
|
216
|
+
|
|
217
|
+
## Handled failures
|
|
218
|
+
|
|
219
|
+
Every handled subcommand failure writes exactly one JSON object to standard error. Branch on its stable `error`
|
|
220
|
+
value rather than the human-readable `detail`; `plan compile` also supplies `phase: "push" | "publication"` when
|
|
221
|
+
`request_outcome_unknown` requires phase-specific recovery:
|
|
222
|
+
|
|
223
|
+
- `phase: "push"` means the Plan mutation may have been accepted; stop and reconcile local Head state.
|
|
224
|
+
- `phase: "publication"` means the singleton Publication mutation was not resolved; rerunning `plan compile` is a
|
|
225
|
+
safe replay.
|
|
226
|
+
|
|
227
|
+
| Commands | `error` | Exit | Meaning |
|
|
228
|
+
| -------------------------------------------- | -------------------------------------------------------------------------------------------------- | ---: | -------------------------------------------------------------------------------------------------------------- |
|
|
229
|
+
| Any leaf command | `invalid_arguments` | 2 | Syntax was invalid; no request was made. |
|
|
230
|
+
| `plan init` | `local_initialization_failed` | 1 | Initialization failed without overwriting an existing path. |
|
|
231
|
+
| `plan push`, `plan compile` | `invalid_configuration` | 2 | API origin or saved Head state is incompatible. |
|
|
232
|
+
| Network commands | `authentication_required` | 1 | The token is missing or First Draft returned a validated authentication problem. |
|
|
233
|
+
| Plan commands, `compilation *` | `local_input_unreadable` | 1 | Required local Plan or private state could not be read. |
|
|
234
|
+
| Status, Compile, Compilation commands | `project_not_pushed` | 1 | No API origin is pinned for the local Project. |
|
|
235
|
+
| `plan push`, `plan compile` | `request_outcome_unknown` | 1 | A mutation or its response could not be verified; `plan compile` identifies its `push` or `publication` phase. |
|
|
236
|
+
| `plan push`, `plan compile` | `local_state_not_saved` | 1 | The Plan was accepted but the private ETag state could not be replaced; includes `recovery_state`. |
|
|
237
|
+
| `plan push`, `plan compile` | `server_rejected` | 1 | First Draft returned validated Plan diagnostics or a validated problem. |
|
|
238
|
+
| `plan status` | `status_unavailable`, `invalid_server_response` | 1 | The analysis read failed or violated its protocol. |
|
|
239
|
+
| `plan compile` | `analysis_status_unavailable`, `invalid_analysis_status`, `analysis_status_rejected` | 1 | The bounded analysis read failed, was invalid, or was rejected. |
|
|
240
|
+
| Analysis waits | `analysis_changed`, `wait_timed_out`, `analysis_wait_timed_out` | 1 | The pinned analysis changed or remained processing at the deadline. |
|
|
241
|
+
| `plan compile` | `plan_not_valid` | 1 | Analysis completed without `valid`; `current` contains diagnostics and status. |
|
|
242
|
+
| `plan compile` | `local_plan_changed` | 1 | Local bytes changed after acceptance or analysis, before Publication mutation. |
|
|
243
|
+
| `plan compile` | `publication_start_rejected`, `publication_status_unavailable`, `invalid_publication_status` | 1 | Publication start or status failed its validated transport contract. |
|
|
244
|
+
| `plan compile` | `publication_changed`, `publication_wait_timed_out`, `publication_failed`, `publication_cancelled` | 1 | The pinned Publication changed, timed out, or reached a non-success terminal state. |
|
|
245
|
+
| `compilation status`, `compilation download` | `compilation_status_unavailable`, `invalid_compilation_status` | 1 | The retained status could not be read or violated its exact contract. |
|
|
246
|
+
| `compilation status --wait` | `compilation_changed`, `compilation_wait_timed_out` | 1 | Retained identity/provenance changed or the wait ended. |
|
|
247
|
+
| `compilation download` | `compilation_not_succeeded` | 1 | Status was not `succeeded`; no artifact request was made. |
|
|
248
|
+
| `compilation download` | `artifact_unavailable`, `invalid_artifact` | 1 | Artifact transport or integrity validation failed before materialization. |
|
|
249
|
+
| `compilation download` | `invalid_output_path` | 2 | The destination was not an absent path beneath an existing real directory. |
|
|
250
|
+
| `compilation download` | `materialization_failed` | 1 | The output raced or the verified tree could not be atomically installed. |
|
|
251
|
+
|
|
252
|
+
Handled output never includes command arguments, local Plan bytes, raw artifact bytes, raw filesystem or network
|
|
253
|
+
errors, or unvalidated response bodies. `local_state_not_saved` is the sole exception to private-state redaction:
|
|
254
|
+
its `recovery_state` is required to repair the accepted ETag locally. Root-level and command-group usage failures
|
|
255
|
+
remain human-readable text on standard error with exit 2. Unexpected programming defects remain loud.
|
|
256
|
+
|
|
257
|
+
## Trust model
|
|
258
|
+
|
|
259
|
+
- The published CLI will run the reviewed JavaScript source directly, without generated or bundled code.
|
|
260
|
+
- The CLI has no runtime dependencies, install scripts, telemetry, update checks, or network activity except an
|
|
261
|
+
explicitly invoked API command.
|
|
262
|
+
- Package contents are allowlisted and checked before release.
|
|
263
|
+
- CI exercises the exact minimum Node.js version separately from current development tooling.
|
|
264
|
+
- Public packages carry npm provenance linking their registry bytes to the reviewed GitHub workflow and commit.
|
|
265
|
+
|
|
266
|
+
Security issues should follow the
|
|
267
|
+
[private reporting instructions](https://github.com/firstdraft/cli/security/advisories/new).
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { run } from "../src/cli.js";
|
|
4
|
+
|
|
5
|
+
process.stdout.on("error", handleStreamError);
|
|
6
|
+
process.stderr.on("error", handleStreamError);
|
|
7
|
+
|
|
8
|
+
process.exitCode = await run({
|
|
9
|
+
argv: process.argv.slice(2),
|
|
10
|
+
stdout: process.stdout,
|
|
11
|
+
stderr: process.stderr,
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
/** @param {Error} error */
|
|
15
|
+
function handleStreamError(error) {
|
|
16
|
+
if ("code" in error && error.code === "EPIPE") return;
|
|
17
|
+
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@firstdraft.com/cli",
|
|
3
|
+
"version": "0.1.0-alpha.2",
|
|
4
|
+
"description": "Command-line interface for First Draft",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"firstdraft": "bin/firstdraft.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"bin",
|
|
12
|
+
"src"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=22.0.0"
|
|
16
|
+
},
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/firstdraft/cli.git"
|
|
20
|
+
},
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/firstdraft/cli/issues"
|
|
23
|
+
},
|
|
24
|
+
"homepage": "https://github.com/firstdraft/cli#readme",
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public",
|
|
27
|
+
"provenance": true,
|
|
28
|
+
"registry": "https://registry.npmjs.org/",
|
|
29
|
+
"tag": "next"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"check": "npm run typecheck && npm run lint && npm run format:check && npm test && npm run pack:check && npm run pack:smoke",
|
|
33
|
+
"format": "prettier --write .",
|
|
34
|
+
"format:check": "prettier --check .",
|
|
35
|
+
"lint": "eslint .",
|
|
36
|
+
"pack:check": "node scripts/check-pack.js",
|
|
37
|
+
"pack:smoke": "node scripts/smoke-package.js",
|
|
38
|
+
"test": "node scripts/run-tests.js",
|
|
39
|
+
"typecheck": "tsc --project jsconfig.json"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@eslint/js": "10.0.1",
|
|
43
|
+
"@types/node": "22.20.1",
|
|
44
|
+
"eslint": "10.8.0",
|
|
45
|
+
"globals": "17.8.0",
|
|
46
|
+
"prettier": "3.9.6",
|
|
47
|
+
"typescript": "7.0.2"
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @param {typeof globalThis.fetch | undefined} fetchFunction
|
|
3
|
+
* @param {string | undefined} apiToken
|
|
4
|
+
* @returns {typeof globalThis.fetch | null}
|
|
5
|
+
*/
|
|
6
|
+
export function authenticatedFetch(fetchFunction, apiToken) {
|
|
7
|
+
if (apiToken === undefined || apiToken.trim().length === 0) return null;
|
|
8
|
+
|
|
9
|
+
const request = fetchFunction ?? globalThis.fetch;
|
|
10
|
+
return (input, init) =>
|
|
11
|
+
request(input, {
|
|
12
|
+
...init,
|
|
13
|
+
headers: {
|
|
14
|
+
...init?.headers,
|
|
15
|
+
Authorization: `Bearer ${apiToken}`,
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {number | undefined} status
|
|
22
|
+
* @param {unknown} response
|
|
23
|
+
* @returns {response is Record<string, unknown>}
|
|
24
|
+
*/
|
|
25
|
+
export function isAuthenticationProblem(status, response) {
|
|
26
|
+
return (
|
|
27
|
+
status === 401 &&
|
|
28
|
+
isRecord(response) &&
|
|
29
|
+
response.status === 401 &&
|
|
30
|
+
response.code === "authentication_required"
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @param {unknown} value @returns {value is Record<string, unknown>} */
|
|
35
|
+
function isRecord(value) {
|
|
36
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
37
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
const MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
|
|
2
|
+
|
|
3
|
+
export class FirstDraftNetworkError extends Error {
|
|
4
|
+
/**
|
|
5
|
+
* @param {string} message
|
|
6
|
+
* @param {{cause?: Error, status?: number}} [options]
|
|
7
|
+
*/
|
|
8
|
+
constructor(message, options = {}) {
|
|
9
|
+
super(message, { cause: options.cause });
|
|
10
|
+
this.status = options.status;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class FirstDraftProtocolError extends Error {
|
|
15
|
+
/** @param {string} message @param {{status: number}} options */
|
|
16
|
+
constructor(message, options) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.status = options.status;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param {typeof globalThis.fetch} fetchFunction
|
|
24
|
+
* @param {URL} endpoint
|
|
25
|
+
* @param {RequestInit} request
|
|
26
|
+
*/
|
|
27
|
+
export async function sendRequest(fetchFunction, endpoint, request) {
|
|
28
|
+
try {
|
|
29
|
+
return await fetchFunction(endpoint, request);
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if (!(error instanceof Error)) throw error;
|
|
32
|
+
|
|
33
|
+
throw new FirstDraftNetworkError("The First Draft request failed.", {
|
|
34
|
+
cause: error,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** @param {Response} response */
|
|
40
|
+
export async function readResponseBody(response) {
|
|
41
|
+
const bytes = await readResponseBytes(response);
|
|
42
|
+
|
|
43
|
+
let text;
|
|
44
|
+
try {
|
|
45
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (!(error instanceof TypeError)) throw error;
|
|
48
|
+
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
try {
|
|
53
|
+
return JSON.parse(text);
|
|
54
|
+
} catch (error) {
|
|
55
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
56
|
+
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** @param {Response} response */
|
|
62
|
+
export function responseMediaType(response) {
|
|
63
|
+
return (
|
|
64
|
+
response.headers
|
|
65
|
+
.get("content-type")
|
|
66
|
+
?.split(";", 1)[0]
|
|
67
|
+
?.trim()
|
|
68
|
+
.toLowerCase() ?? ""
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** @param {Response} response @param {unknown} body */
|
|
73
|
+
export function isProblemBody(response, body) {
|
|
74
|
+
return (
|
|
75
|
+
responseMediaType(response) === "application/problem+json" &&
|
|
76
|
+
isRecord(body) &&
|
|
77
|
+
(body.type === undefined || body.type === "about:blank") &&
|
|
78
|
+
typeof body.title === "string" &&
|
|
79
|
+
body.status === response.status &&
|
|
80
|
+
typeof body.code === "string" &&
|
|
81
|
+
typeof body.detail === "string"
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @param {unknown} value
|
|
87
|
+
* @returns {value is Record<string, unknown> & {severity: "error" | "warning"}}
|
|
88
|
+
*/
|
|
89
|
+
export function isDiagnostic(value) {
|
|
90
|
+
return (
|
|
91
|
+
isRecord(value) &&
|
|
92
|
+
typeof value.code === "string" &&
|
|
93
|
+
(value.severity === "error" || value.severity === "warning") &&
|
|
94
|
+
typeof value.message === "string"
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* @param {Response} response
|
|
100
|
+
* @param {number} [maximumBytes]
|
|
101
|
+
*/
|
|
102
|
+
export async function readResponseBytes(
|
|
103
|
+
response,
|
|
104
|
+
maximumBytes = MAX_RESPONSE_BYTES,
|
|
105
|
+
) {
|
|
106
|
+
const declaredLength = response.headers.get("content-length");
|
|
107
|
+
if (
|
|
108
|
+
declaredLength !== null &&
|
|
109
|
+
/^\d+$/.test(declaredLength) &&
|
|
110
|
+
Number(declaredLength) > maximumBytes
|
|
111
|
+
) {
|
|
112
|
+
if (response.body !== null) {
|
|
113
|
+
await response.body.cancel().catch(() => undefined);
|
|
114
|
+
}
|
|
115
|
+
throw new FirstDraftProtocolError(
|
|
116
|
+
"The First Draft response is too large.",
|
|
117
|
+
{ status: response.status },
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (response.body === null) return Buffer.alloc(0);
|
|
122
|
+
|
|
123
|
+
const reader = response.body.getReader();
|
|
124
|
+
const chunks = [];
|
|
125
|
+
let byteLength = 0;
|
|
126
|
+
|
|
127
|
+
try {
|
|
128
|
+
while (true) {
|
|
129
|
+
const { done, value } = await reader.read();
|
|
130
|
+
if (done) break;
|
|
131
|
+
|
|
132
|
+
byteLength += value.byteLength;
|
|
133
|
+
if (byteLength > maximumBytes) {
|
|
134
|
+
await reader.cancel().catch(() => undefined);
|
|
135
|
+
throw new FirstDraftProtocolError(
|
|
136
|
+
"The First Draft response is too large.",
|
|
137
|
+
{ status: response.status },
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
chunks.push(Buffer.from(value));
|
|
141
|
+
}
|
|
142
|
+
} catch (error) {
|
|
143
|
+
if (error instanceof FirstDraftProtocolError) throw error;
|
|
144
|
+
if (!(error instanceof Error)) throw error;
|
|
145
|
+
|
|
146
|
+
throw new FirstDraftNetworkError("The First Draft response failed.", {
|
|
147
|
+
cause: error,
|
|
148
|
+
status: response.status,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return Buffer.concat(chunks, byteLength);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** @param {unknown} value @returns {value is Record<string, unknown>} */
|
|
156
|
+
function isRecord(value) {
|
|
157
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
158
|
+
}
|