@toshicloud/sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +201 -2
  3. package/dist/client.d.ts +78 -0
  4. package/dist/client.js +42 -0
  5. package/dist/errors.d.ts +20 -0
  6. package/dist/errors.js +55 -0
  7. package/dist/execute.d.ts +6 -0
  8. package/dist/execute.js +380 -0
  9. package/dist/gen/toshi/workspace/v1/artifacts_pb.d.ts +841 -0
  10. package/dist/gen/toshi/workspace/v1/artifacts_pb.js +96 -0
  11. package/dist/gen/toshi/workspace/v1/display_pb.d.ts +1142 -0
  12. package/dist/gen/toshi/workspace/v1/display_pb.js +214 -0
  13. package/dist/gen/toshi/workspace/v1/projects_pb.d.ts +1386 -0
  14. package/dist/gen/toshi/workspace/v1/projects_pb.js +207 -0
  15. package/dist/gen/toshi/workspace/v1/recordings_pb.d.ts +948 -0
  16. package/dist/gen/toshi/workspace/v1/recordings_pb.js +201 -0
  17. package/dist/gen/toshi/workspace/v1/secrets_pb.d.ts +1062 -0
  18. package/dist/gen/toshi/workspace/v1/secrets_pb.js +182 -0
  19. package/dist/gen/toshi/workspace/v1/volumes_pb.d.ts +406 -0
  20. package/dist/gen/toshi/workspace/v1/volumes_pb.js +107 -0
  21. package/dist/gen/toshi/workspace/v1/webhook_pb.d.ts +974 -0
  22. package/dist/gen/toshi/workspace/v1/webhook_pb.js +153 -0
  23. package/dist/gen/toshi/workspace/v1/workspace_pb.d.ts +6133 -0
  24. package/dist/gen/toshi/workspace/v1/workspace_pb.js +892 -0
  25. package/dist/index.d.ts +10 -0
  26. package/dist/index.js +9 -0
  27. package/dist/interceptors.d.ts +10 -0
  28. package/dist/interceptors.js +159 -0
  29. package/dist/output.d.ts +6 -0
  30. package/dist/output.js +77 -0
  31. package/dist/retry.d.ts +42 -0
  32. package/dist/retry.js +213 -0
  33. package/dist/stream.d.ts +21 -0
  34. package/dist/stream.js +84 -0
  35. package/dist/wait.d.ts +8 -0
  36. package/dist/wait.js +29 -0
  37. package/dist/watch.d.ts +8 -0
  38. package/dist/watch.js +224 -0
  39. package/package.json +47 -4
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,202 @@
1
- # Temporary Holding Version
1
+ # toshi-ts
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A TypeScript client for the Toshi Workspace API, `toshi.workspace.v1`,
4
+ published as ES modules with type declarations.
5
+
6
+ ```sh
7
+ npm install @toshicloud/sdk @connectrpc/connect @connectrpc/connect-node
8
+ ```
9
+
10
+ Versions up to 0.1.2 were published as `@toshicloud/toshi-ts`.
11
+
12
+ ## Using the client
13
+
14
+ `createToshiClient` takes one set of options. The transport belongs to
15
+ the caller: the client hands its interceptors to the `transport`
16
+ function, and that function builds a transport with them. Every call then
17
+ gets the same token, scope and retries: the helpers below and the
18
+ generated clients alike.
19
+
20
+ In Node, with `@connectrpc/connect-node`:
21
+
22
+ ```ts
23
+ import { readFileSync } from "node:fs";
24
+ import { createConnectTransport } from "@connectrpc/connect-node";
25
+ import { createToshiClient } from "@toshicloud/sdk";
26
+
27
+ const toshi = createToshiClient({
28
+ transport: (interceptors) =>
29
+ createConnectTransport({
30
+ baseUrl: "https://toshi.example.com",
31
+ httpVersion: "2",
32
+ interceptors,
33
+ // Only for a server whose certificate a private CA signed.
34
+ nodeOptions: { ca: readFileSync("ca.pem") },
35
+ }),
36
+ token: process.env.TOSHI_TOKEN,
37
+ project: "default",
38
+ });
39
+
40
+ const { projects } = await toshi.projects.listProjects({});
41
+ ```
42
+
43
+ In a browser, with `@connectrpc/connect-web`:
44
+
45
+ ```ts
46
+ import { createConnectTransport } from "@connectrpc/connect-web";
47
+ import { createToshiClient } from "@toshicloud/sdk";
48
+
49
+ const toshi = createToshiClient({
50
+ transport: (interceptors) =>
51
+ createConnectTransport({ baseUrl: "https://toshi.example.com", interceptors }),
52
+ token,
53
+ project: "default",
54
+ });
55
+ ```
56
+
57
+ To add interceptors of your own, put them before the client's:
58
+ `interceptors: [...mine, ...interceptors]`.
59
+
60
+ The package reads no environment variable and no file. The token, the
61
+ server and any CA come from the caller.
62
+
63
+ ### Options
64
+
65
+ - `token`: sent as `Authorization: Bearer <token>` on every call.
66
+ - `project`, `environment`: fill the request's `project` and
67
+ `environment` fields when they are empty. A value in the request wins.
68
+ `environment` is left empty on a request with `shared: true`.
69
+ - `retry`: `{ maxAttempts, initialBackoffMs, maxBackoffMs }`, by default
70
+ 5, 200 ms and 10 s, with full jitter. `retry: false` turns off retries
71
+ and watch reconnects.
72
+
73
+ ### Retries
74
+
75
+ The client retries a read, and a write that carries a request key, when
76
+ the connection fails: a `ConnectError` with code `Unavailable`, a
77
+ connection reset or destroyed stream that `@connectrpc/connect-node`
78
+ reports, or a stream the server refused before reading it
79
+ (`REFUSED_STREAM`). A write that takes a request key gets a random one when the
80
+ request has none, so the server applies a retried write once. Other
81
+ writes are never retried. An error the server sends, including
82
+ `Aborted`, `InvalidArgument` and `ResourceExhausted`, reaches the caller
83
+ unchanged. So does any connection failure the client cannot tell apart
84
+ from a server error.
85
+
86
+ ### Waiting and watching
87
+
88
+ - `waitWorkload(req)` and `waitOperation(req)` ask again until the
89
+ workload reaches the state or the operation is done.
90
+ - `watchWorkloads(req)`, `watchEvents(req)` and `watchOutput(req)`
91
+ resolve to a watch you read with `for await`. A watch opens its stream
92
+ when you start reading and reconnects after a connection failure from
93
+ where it stopped: `cursor` for workloads and events, `offsets` (bytes,
94
+ as `bigint`) for output. With no cursor, `watchWorkloads` lists the
95
+ workloads first, and `snapshot` holds them once its promise resolves;
96
+ `watchEvents` yields the past events page by page before the live ones.
97
+ `close()` or leaving the loop ends the stream. The output watch ends at
98
+ the output's end.
99
+
100
+ ```ts
101
+ const watch = await toshi.watchEvents({ workloadId: id });
102
+ for await (const event of watch) {
103
+ console.log(event.name);
104
+ }
105
+ // watch.cursor resumes a later watch after the last event read.
106
+ ```
107
+
108
+ Every helper takes `{ signal }`, an `AbortSignal` that ends it.
109
+
110
+ ### Running a command
111
+
112
+ `execute(start)` runs a command and resolves once the server has started
113
+ it. The process is one stream of output chunks, `{ stream: "stdout" |
114
+ "stderr", data: Uint8Array }`. `write` sends standard input in frames of
115
+ at most 64 KiB and resolves once the stream has taken the last one; await
116
+ it before the next `write`, which is refused while one is pending, so the
117
+ client holds at most one buffer of input. `closeStdin` ends standard input
118
+ after a pending write, and a later `write` is refused. `wait` settles when
119
+ the command ends.
120
+
121
+ ```ts
122
+ const proc = await toshi.execute({ workloadId: id, command: { argv: ["cat"] } });
123
+ await proc.write("hello\n");
124
+ await proc.closeStdin();
125
+ for await (const chunk of proc) {
126
+ process[chunk.stream].write(chunk.data);
127
+ }
128
+ await proc.wait(); // rejects with ExitError on a non-zero exit
129
+ ```
130
+
131
+ Without a loop, `wait()` reads and drops the output itself. It rejects
132
+ with `ExitError` when the command fails, is cancelled or ends without an
133
+ exit status, and with `StreamLostError` when the stream ends first. The
134
+ client never runs a command again by itself. Standard input cannot be
135
+ replayed, so the caller decides whether to start again with the same
136
+ `requestKey`. Leaving the loop early cancels the stream, and `wait()`
137
+ then rejects with a `Canceled` error.
138
+
139
+ Execute needs a bidirectional stream: `@connectrpc/connect-node` with
140
+ `httpVersion: "2"`. In a browser, `execute` rejects at once and makes no
141
+ call. Over a transport without HTTP/2, the call fails with the
142
+ transport's or the server's error.
143
+
144
+ ## Generated code
145
+
146
+ `src/gen/toshi/workspace/v1/` is generated by
147
+ [`protoc-gen-es`](https://github.com/bufbuild/protobuf-es) from the protos
148
+ in `proto/toshi/workspace/v1` of the
149
+ [toshi-api](https://github.com/toshicloud/toshi-api) repository, one
150
+ `*_pb.ts` file per proto. The generated code is committed and imports
151
+ only `@bufbuild/protobuf`, so installing the package needs no generator.
152
+
153
+ `pin.env` names the toshi-api commit (or, once one exists, the release
154
+ tag) the code is generated from. `mise.toml` pins the versions of Node,
155
+ pnpm, `buf` and `protoc-gen-es`.
156
+
157
+ To regenerate:
158
+
159
+ ```sh
160
+ mise install
161
+ mise exec -- scripts/generate.sh
162
+ ```
163
+
164
+ Moving to another commit or tag is one pull request that changes
165
+ `pin.env` and `src/gen/` together. CI regenerates the code from `pin.env`
166
+ and fails if the result differs from what is committed
167
+ (`scripts/check-generated.sh`).
168
+
169
+ ## Versions
170
+
171
+ The package's major version follows the API's: `1.x` will serve
172
+ `toshi.workspace.v1`, and a `toshi.workspace.v2` gets a new major
173
+ version. Until a Toshi release serves the API, the package stays at
174
+ `0.x` and is generated from a pinned commit.
175
+
176
+ ## Publishing
177
+
178
+ Releases are published to npm by the publish workflow
179
+ (`.github/workflows/publish.yml`) through npm trusted publishing: the
180
+ workflow authenticates with its GitHub OIDC token, and no npm token
181
+ exists. It runs on a `vX.Y.Z` tag that matches the version in
182
+ `package.json`. A new version is a commit on `main` that sets the version
183
+ in `package.json`, followed by its tag.
184
+
185
+ ## Integration test
186
+
187
+ `test/integration/` runs the client against a real `toshi serve` over
188
+ HTTPS with a test CA it mints itself. `TOSHI_INTEGRATION_BIN` names the
189
+ `toshi` binary it runs; when `TOSHI_INTEGRATION_EXPECT_COMMIT` is set, the
190
+ binary must report that commit:
191
+
192
+ ```sh
193
+ TOSHI_INTEGRATION_BIN=/path/to/toshi mise exec -- pnpm vitest run test/integration
194
+ ```
195
+
196
+ The Toshi server's CI runs it against each server change. Without
197
+ `TOSHI_INTEGRATION_BIN`, `pnpm test` skips the integration test and says
198
+ why.
199
+
200
+ ## Licence
201
+
202
+ Apache License 2.0, see LICENSE.
@@ -0,0 +1,78 @@
1
+ import type { MessageInitShape } from "@bufbuild/protobuf";
2
+ import type { Client, Interceptor, Transport } from "@connectrpc/connect";
3
+ import { DisplayService } from "./gen/toshi/workspace/v1/display_pb.js";
4
+ import { ExecuteStartSchema, WaitOperationRequestSchema, WaitWorkloadRequestSchema, WatchEventsRequestSchema, WatchOutputRequestSchema, WatchWorkloadsRequestSchema, WorkspaceService } from "./gen/toshi/workspace/v1/workspace_pb.js";
5
+ import type { Event, Operation, WaitWorkloadResponse, WatchOutputResponse, WatchWorkloadsResponse, Workload } from "./gen/toshi/workspace/v1/workspace_pb.js";
6
+ import { ProjectService } from "./gen/toshi/workspace/v1/projects_pb.js";
7
+ import { SecretService } from "./gen/toshi/workspace/v1/secrets_pb.js";
8
+ import { WebhookService } from "./gen/toshi/workspace/v1/webhook_pb.js";
9
+ import type { RetryPolicy } from "./retry.js";
10
+ /** How the client is configured; the caller builds the transport. */
11
+ export interface ToshiOptions {
12
+ /** Builds the caller's transport (connect-node or connect-web) with the client's interceptors. */
13
+ transport: (interceptors: Interceptor[]) => Transport;
14
+ token?: string;
15
+ project?: string;
16
+ environment?: string;
17
+ /** false turns off retries and watch reconnects. */
18
+ retry?: Partial<RetryPolicy> | false;
19
+ }
20
+ /** Per-call options. */
21
+ export interface CallOptions {
22
+ signal?: AbortSignal;
23
+ }
24
+ /** The five generated clients plus the helpers that live on top of them. */
25
+ export interface ToshiClient {
26
+ readonly workspace: Client<typeof WorkspaceService>;
27
+ readonly projects: Client<typeof ProjectService>;
28
+ readonly secrets: Client<typeof SecretService>;
29
+ readonly webhooks: Client<typeof WebhookService>;
30
+ readonly displays: Client<typeof DisplayService>;
31
+ waitWorkload(req: MessageInitShape<typeof WaitWorkloadRequestSchema>, opts?: CallOptions): Promise<WaitWorkloadResponse>;
32
+ waitOperation(req: MessageInitShape<typeof WaitOperationRequestSchema>, opts?: CallOptions): Promise<Operation>;
33
+ watchWorkloads(req: MessageInitShape<typeof WatchWorkloadsRequestSchema>, opts?: CallOptions): Promise<WorkloadWatch>;
34
+ watchEvents(req: MessageInitShape<typeof WatchEventsRequestSchema>, opts?: CallOptions): Promise<EventWatch>;
35
+ watchOutput(req: MessageInitShape<typeof WatchOutputRequestSchema>, opts?: CallOptions): Promise<OutputWatch>;
36
+ execute(start: MessageInitShape<typeof ExecuteStartSchema>, opts?: CallOptions): Promise<Process>;
37
+ }
38
+ /** A live stream of workload changes (watch.go:40-60). */
39
+ export interface WorkloadWatch extends AsyncIterable<WatchWorkloadsResponse> {
40
+ readonly cursor: string;
41
+ readonly snapshot: Workload[] | undefined;
42
+ close(): void;
43
+ }
44
+ /** A live stream of events (watch.go:261-460). */
45
+ export interface EventWatch extends AsyncIterable<Event> {
46
+ readonly cursor: string;
47
+ close(): void;
48
+ }
49
+ /** A live stream of a job's output (output.go). */
50
+ export interface OutputWatch extends AsyncIterable<WatchOutputResponse> {
51
+ readonly offsets: {
52
+ readonly stdout: bigint;
53
+ readonly stderr: bigint;
54
+ };
55
+ close(): void;
56
+ }
57
+ /** One chunk of an execution's output. */
58
+ export type OutputChunk = {
59
+ stream: "stdout";
60
+ data: Uint8Array;
61
+ } | {
62
+ stream: "stderr";
63
+ data: Uint8Array;
64
+ };
65
+ /** A running execution (execute.go). */
66
+ export interface Process extends AsyncIterable<OutputChunk> {
67
+ readonly executionId: string;
68
+ readonly requestKey: string;
69
+ write(data: Uint8Array | string): Promise<void>;
70
+ closeStdin(): Promise<void>;
71
+ wait(): Promise<void>;
72
+ }
73
+ /**
74
+ * Creates the client: one normalized retry setting, the auth, scope, key and
75
+ * retry interceptors (auth outermost, retry innermost), one transport for every
76
+ * client and helper (client.go:40-93).
77
+ */
78
+ export declare function createToshiClient(options: ToshiOptions): ToshiClient;
package/dist/client.js ADDED
@@ -0,0 +1,42 @@
1
+ import { create } from "@bufbuild/protobuf";
2
+ import { createClient } from "@connectrpc/connect";
3
+ import { executeCommand } from "./execute.js";
4
+ import { DisplayService } from "./gen/toshi/workspace/v1/display_pb.js";
5
+ import { ExecuteStartSchema, WaitOperationRequestSchema, WaitWorkloadRequestSchema, WatchEventsRequestSchema, WatchOutputRequestSchema, WatchWorkloadsRequestSchema, WorkspaceService, } from "./gen/toshi/workspace/v1/workspace_pb.js";
6
+ import { ProjectService } from "./gen/toshi/workspace/v1/projects_pb.js";
7
+ import { SecretService } from "./gen/toshi/workspace/v1/secrets_pb.js";
8
+ import { WebhookService } from "./gen/toshi/workspace/v1/webhook_pb.js";
9
+ import { openOutputWatch } from "./output.js";
10
+ import { authInterceptor, keyInterceptor, retryInterceptor, scopeInterceptor } from "./interceptors.js";
11
+ import { normalizeRetry } from "./retry.js";
12
+ import { openEventWatch, openWorkloadWatch } from "./watch.js";
13
+ import { waitOperation, waitWorkload } from "./wait.js";
14
+ /**
15
+ * Creates the client: one normalized retry setting, the auth, scope, key and
16
+ * retry interceptors (auth outermost, retry innermost), one transport for every
17
+ * client and helper (client.go:40-93).
18
+ */
19
+ export function createToshiClient(options) {
20
+ const retry = normalizeRetry(options.retry);
21
+ const interceptors = [
22
+ authInterceptor(options.token ?? ""),
23
+ scopeInterceptor(options.project ?? "", options.environment ?? ""),
24
+ keyInterceptor(),
25
+ retryInterceptor(retry),
26
+ ];
27
+ const transport = options.transport(interceptors);
28
+ const workspace = createClient(WorkspaceService, transport);
29
+ return {
30
+ workspace,
31
+ projects: createClient(ProjectService, transport),
32
+ secrets: createClient(SecretService, transport),
33
+ webhooks: createClient(WebhookService, transport),
34
+ displays: createClient(DisplayService, transport),
35
+ waitWorkload: (req, opts) => waitWorkload(workspace, create(WaitWorkloadRequestSchema, req), opts),
36
+ waitOperation: (req, opts) => waitOperation(workspace, create(WaitOperationRequestSchema, req), opts),
37
+ watchWorkloads: (req, opts) => openWorkloadWatch(workspace, retry, create(WatchWorkloadsRequestSchema, req), opts),
38
+ watchEvents: (req, opts) => openEventWatch(workspace, retry, create(WatchEventsRequestSchema, req), opts),
39
+ watchOutput: (req, opts) => openOutputWatch(workspace, retry, create(WatchOutputRequestSchema, req), opts),
40
+ execute: (start, opts) => executeCommand(workspace, start, opts),
41
+ };
42
+ }
@@ -0,0 +1,20 @@
1
+ import type { ExecutionExit } from "./gen/toshi/workspace/v1/workspace_pb.js";
2
+ /** A command that ended non-zero, or was cancelled before it had a status (errors.go:9-26). */
3
+ export declare class ExitError extends Error {
4
+ /** The execution the exit belongs to. */
5
+ readonly executionId: string;
6
+ /** The execution's exit message. */
7
+ readonly exit: ExecutionExit;
8
+ constructor(executionId: string, exit: ExecutionExit);
9
+ }
10
+ /**
11
+ * An Execute stream that ended before its exit message; stdin cannot be replayed
12
+ * (errors.go:28-49). The cause is the error that ended the stream.
13
+ */
14
+ export declare class StreamLostError extends Error {
15
+ /** Empty when the stream was lost before the start was acknowledged. */
16
+ readonly executionId: string;
17
+ /** The request key of the start, so the caller may start again deliberately. */
18
+ readonly requestKey: string;
19
+ constructor(executionId: string, requestKey: string, cause?: unknown);
20
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,55 @@
1
+ /** A command that ended non-zero, or was cancelled before it had a status (errors.go:9-26). */
2
+ export class ExitError extends Error {
3
+ /** The execution the exit belongs to. */
4
+ executionId;
5
+ /** The execution's exit message. */
6
+ exit;
7
+ constructor(executionId, exit) {
8
+ super(exitMessage(executionId, exit));
9
+ this.name = "ExitError";
10
+ this.executionId = executionId;
11
+ this.exit = exit;
12
+ }
13
+ }
14
+ function exitMessage(executionId, exit) {
15
+ if (exit.cancelled) {
16
+ return `toshi: execution ${executionId} was cancelled`;
17
+ }
18
+ if (exit.exitCode === undefined) {
19
+ return `toshi: execution ${executionId} ended without an exit status`;
20
+ }
21
+ return `toshi: execution ${executionId} exited with status ${exit.exitCode}`;
22
+ }
23
+ /**
24
+ * An Execute stream that ended before its exit message; stdin cannot be replayed
25
+ * (errors.go:28-49). The cause is the error that ended the stream.
26
+ */
27
+ export class StreamLostError extends Error {
28
+ /** Empty when the stream was lost before the start was acknowledged. */
29
+ executionId;
30
+ /** The request key of the start, so the caller may start again deliberately. */
31
+ requestKey;
32
+ constructor(executionId, requestKey, cause) {
33
+ super(lostMessage(executionId, requestKey, cause), cause === undefined ? undefined : { cause });
34
+ this.name = "StreamLostError";
35
+ this.executionId = executionId;
36
+ this.requestKey = requestKey;
37
+ }
38
+ }
39
+ function lostMessage(executionId, requestKey, cause) {
40
+ const detail = cause === undefined ? "" : `: ${describe(cause)}`;
41
+ if (executionId === "") {
42
+ return `toshi: execution stream lost before the start was acknowledged (request key ${requestKey})${detail}`;
43
+ }
44
+ return `toshi: execution ${executionId} stream lost (request key ${requestKey})${detail}`;
45
+ }
46
+ // The way Go's %v would print it, without stringifying an object as [object Object].
47
+ function describe(cause) {
48
+ if (cause instanceof Error) {
49
+ return cause.message;
50
+ }
51
+ if (typeof cause === "string" || typeof cause === "number" || typeof cause === "boolean") {
52
+ return String(cause);
53
+ }
54
+ return "the stream ended";
55
+ }
@@ -0,0 +1,6 @@
1
+ import type { MessageInitShape } from "@bufbuild/protobuf";
2
+ import type { Client } from "@connectrpc/connect";
3
+ import type { CallOptions, Process } from "./client.js";
4
+ import { ExecuteStartSchema, WorkspaceService } from "./gen/toshi/workspace/v1/workspace_pb.js";
5
+ /** Starts a command and returns its process; the only export of this module. */
6
+ export declare function executeCommand(workspace: Client<typeof WorkspaceService>, start: MessageInitShape<typeof ExecuteStartSchema> | undefined, opts?: CallOptions): Promise<Process>;