@timmo001/effect-gh 0.1.0-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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,299 @@
1
+ # effect-gh
2
+
3
+ An Effect v4 SDK for the GitHub CLI (`gh`).
4
+
5
+ Inspired by the Effect-native API in
6
+ [dmmulroy/herdr-ts-sdk](https://github.com/dmmulroy/herdr-ts-sdk).
7
+
8
+ ## Requirements
9
+
10
+ - Effect matching `peerDependencies.effect` in [package.json](package.json), with
11
+ a compatible consumer-chosen platform adapter.
12
+ - GitHub CLI installed and authenticated through `gh auth login` or its standard
13
+ token environment variables.
14
+ - An ESM consumer. Bun runs the TypeScript source directly; Node uses the compiled
15
+ JavaScript in a built package. The platform adapter stays a consumer dependency.
16
+
17
+ ## Install
18
+
19
+ The commands below read Effect and Node adapter versions from the installed SDK's
20
+ `package.json`. The Node adapter also works in Bun.
21
+
22
+ ### Bun
23
+
24
+ Run from your application directory:
25
+
26
+ ```sh
27
+ bun add github:timmo001/effect-gh
28
+ bun add "effect@$(bun -p 'require("@timmo001/effect-gh/package.json").peerDependencies.effect')" \
29
+ "@effect/platform-node@$(bun -p 'require("@timmo001/effect-gh/package.json").devDependencies["@effect/platform-node"]')"
30
+ ```
31
+
32
+ Commit `package.json` and `bun.lock` in your application to preserve the resolved
33
+ GitHub revision and dependency versions. The `bun` export resolves to
34
+ `src/index.ts`, and types resolve to the same source. GitHub installs need no
35
+ build step or consumer patch.
36
+
37
+ ### Node
38
+
39
+ Run from your application directory to build and install a package from source
40
+ with the [mise](https://mise.jdx.dev/getting-started.html)-pinned tools:
41
+
42
+ ```sh
43
+ git clone https://github.com/timmo001/effect-gh.git .effect-gh
44
+ (
45
+ cd .effect-gh &&
46
+ mise install &&
47
+ mise run install &&
48
+ mise exec -- npm pack --pack-destination ..
49
+ )
50
+ bun add ./timmo001-effect-gh-*.tgz
51
+ bun add "effect@$(bun -p 'require("@timmo001/effect-gh/package.json").peerDependencies.effect')" \
52
+ "@effect/platform-node@$(bun -p 'require("@timmo001/effect-gh/package.json").devDependencies["@effect/platform-node"]')"
53
+ ```
54
+
55
+ Keep the archive with your application for repeatable installs. The `.effect-gh`
56
+ checkout is only needed to build it.
57
+
58
+ The first npm publication is pending. After publication, either runtime can
59
+ install directly from npm:
60
+
61
+ ```sh
62
+ bun add @timmo001/effect-gh
63
+ bun add "effect@$(bun -p 'require("@timmo001/effect-gh/package.json").peerDependencies.effect')" \
64
+ "@effect/platform-node@$(bun -p 'require("@timmo001/effect-gh/package.json").devDependencies["@effect/platform-node"]')"
65
+ ```
66
+
67
+ ### GitHub authentication
68
+
69
+ Install [GitHub CLI](https://cli.github.com/) separately, then authenticate:
70
+
71
+ ```sh
72
+ gh auth login
73
+ gh auth status
74
+ ```
75
+
76
+ For automation, supply `GH_TOKEN` or another gh-supported authentication
77
+ configuration through the environment. The SDK uses it without a separate login.
78
+
79
+ ## Agent skill
80
+
81
+ [The effect-gh skill](https://github.com/timmo001/effect-gh/blob/main/skills/effect-gh/SKILL.md)
82
+ guides Effect integrations towards the package and its current documentation.
83
+ It follows the [Agent Skills specification](https://agentskills.io/specification).
84
+ Import the complete `skills/effect-gh/` directory unchanged into your skill
85
+ collection; it has no client-specific configuration or local path dependencies.
86
+
87
+ ## Core SDK
88
+
89
+ `Gh` is the service tag. `layer(options?)` captures the consumer-provided
90
+ `ChildProcessSpawner` and starts no processes until an operation runs. Consumers
91
+ choose their platform layer and runtime. For example, with `@effect/platform-node`:
92
+
93
+ ```ts
94
+ import { NodeServices } from "@effect/platform-node";
95
+ import { Effect, Layer, Schema } from "effect";
96
+ import { Gh, layer } from "@timmo001/effect-gh";
97
+
98
+ const ghLayer = layer({ timeout: "30 seconds" }).pipe(
99
+ Layer.provide(NodeServices.layer),
100
+ );
101
+
102
+ const program = Effect.gen(function* () {
103
+ const gh = yield* Gh;
104
+ return yield* gh.json(
105
+ ["api", "user"],
106
+ Schema.Struct({ login: Schema.String }),
107
+ );
108
+ }).pipe(Effect.provide(ghLayer));
109
+ ```
110
+
111
+ - `execute(args, options?)` returns `{ stdout, stderr, exitCode }` on exit zero.
112
+ It buffers both UTF-8 outputs in memory, so use `stream` for large output.
113
+ - `json(args, schema, options?)` decodes stdout as JSON through the supplied
114
+ Schema, preserving its decoding service requirements. Supply any `--json`
115
+ fields required by the selected `gh` command yourself.
116
+ - `stream(args, options?)` emits `{ _tag: "Stdout" | "Stderr", text }` chunks.
117
+ It drains both pipes concurrently with backpressure and preserves order within
118
+ each pipe, with no ordering guarantee between pipes. Chunk boundaries are not
119
+ line boundaries. Completion waits for both pipes and a successful exit.
120
+
121
+ `GhOptions` accepts `executable` (default `gh`), `cwd`, `env`, `stdin` (string or
122
+ `Uint8Array`) and `timeout` (an Effect duration). Call options override layer
123
+ defaults; environment entries merge. `timeout: null` disables a layer timeout.
124
+ Timeouts cover spawning, execution and output draining, rather than idle time.
125
+ There is no timeout by default. Schema decoding runs after the subprocess timeout.
126
+
127
+ Commands pass literal argv without a shell. The platform inherits the environment,
128
+ including existing `gh` authentication and configuration. Supplied environment
129
+ entries override inherited values; `undefined` removes a value. The SDK always
130
+ disables prompts, colour, forced TTY and spinners, and selects `cat` as the pager.
131
+ Stdin is closed unless supplied explicitly. No operation is automatically retried.
132
+
133
+ Errors are tagged `GhCommandError` (nonzero exit with exit code and stderr),
134
+ `GhPlatformError` (spawn or pipe failure), `GhTimeoutError`, or `GhDecodeError`
135
+ (invalid JSON or a schema mismatch). Command errors retain only the last 65,536
136
+ UTF-16 code units of stderr and flag truncation with `stderrTruncated`.
137
+ The stream emits trailing output before reporting a nonzero exit.
138
+
139
+ Interruption, timeout and early stream termination close the child scope. The
140
+ platform terminates the child, escalating after one second if needed. An early
141
+ consumer stop does not validate the final exit code. Interruptions remain Effect
142
+ interruptions rather than being converted into SDK errors.
143
+
144
+ ## API requests
145
+
146
+ `Api.raw(request)` returns buffered output, including empty or non-JSON responses.
147
+ `Api.json(request, schema)` decodes one JSON response. Every request specifies a
148
+ method, which the SDK passes explicitly to `gh api`.
149
+
150
+ ```ts
151
+ import { Api } from "@timmo001/effect-gh";
152
+ import { Schema } from "effect";
153
+
154
+ const viewer = Api.json(
155
+ { endpoint: "user", method: "GET" },
156
+ Schema.Struct({ login: Schema.String }),
157
+ );
158
+
159
+ const subscription = Api.raw({
160
+ endpoint: "notifications/threads/123/subscription",
161
+ method: "PUT",
162
+ body: { ignored: true },
163
+ });
164
+ ```
165
+
166
+ Requests accept `hostname`, `headers`, `query`, a JSON `body`, and core overrides
167
+ under `options`. Query values are URL-encoded; arrays repeat the key. JSON bodies
168
+ go through stdin rather than CLI field interpolation. Bodyless calls clear any
169
+ layer-level stdin.
170
+
171
+ `Api.pages(request, pageSchema)` runs a bodyless REST GET with
172
+ `--paginate --slurp`. The result is an array of decoded **pages**, not flattened
173
+ items: use an array schema for array endpoints, or an object schema for envelopes
174
+ such as `{ workflow_runs: [...] }`. It buffers all pages and does not provide a
175
+ snapshot-consistency guarantee. GraphQL cursor pagination remains available
176
+ through the raw `Gh` interface.
177
+
178
+ ### Retries
179
+
180
+ No SDK operation retries automatically. Mutations can have taken effect even
181
+ when the CLI times out or loses the connection. Consumers can apply Effect
182
+ `Schedule` and `Effect.retry` to known-idempotent reads with a bounded policy and
183
+ their own transient-error classification. Decode errors, authentication failures
184
+ and check-status exits are not transient errors. Do not transparently replay a
185
+ stream after it has emitted output.
186
+
187
+ ## Repository and issues
188
+
189
+ ```ts
190
+ import { Issue, Repository } from "@timmo001/effect-gh";
191
+
192
+ const repository = Repository.view("owner/repo");
193
+ const issues = Issue.list({ repo: "owner/repo", state: "open", limit: 50 });
194
+ const issue = Issue.view(42, { repo: "owner/repo" });
195
+ ```
196
+
197
+ `Repository.view(repo?, options?)` returns the repository name, URL, privacy and
198
+ nullable default branch. Omitting the selector uses gh's working-directory
199
+ context. Issue list/view also accept an optional `repo`, plus core execution
200
+ options as their final argument. Lists default to 30 open issues, and support
201
+ state, limit, labels, assignee and search filters. `Issue.view` includes the body.
202
+ Invalid numeric limits and selectors fail with `IssueInvalidInput` before spawning.
203
+
204
+ ## Pull requests
205
+
206
+ ```ts
207
+ import { PullRequest } from "@timmo001/effect-gh";
208
+
209
+ const pullRequests = PullRequest.list({ repository: "owner/repo" });
210
+ const pullRequest = PullRequest.view(42, { repository: "owner/repo" });
211
+ const checks = PullRequest.checks(42, {
212
+ repository: "owner/repo",
213
+ required: true,
214
+ });
215
+ ```
216
+
217
+ Pull request options require `repository` and accept core execution overrides.
218
+ Lists default to 30 open PRs, with optional state, limit, base and head filters.
219
+ List/view return number, title, URL, state, draft status, head branch and head SHA.
220
+
221
+ `PullRequest.checks` returns `{ checks, status, exitCode }`. Valid check output
222
+ from exits 0, 1 and 8 is data with status `success`, `failure` or `pending`.
223
+ Genuine command failures retain their typed error; no command is re-executed to
224
+ retrieve its output.
225
+
226
+ ## Workflow runs
227
+
228
+ ```ts
229
+ import { Workflow } from "@timmo001/effect-gh";
230
+
231
+ const runs = Workflow.list({ repo: "owner/repo", branch: "main", limit: 20 });
232
+ const run = Workflow.view({ repo: "owner/repo", runId: 123, attempt: 2 });
233
+ const logs = Workflow.logs({
234
+ repo: "owner/repo",
235
+ runId: 123,
236
+ attempt: 2,
237
+ failedOnly: true,
238
+ });
239
+ const progress = Workflow.watch(
240
+ { repo: "owner/repo", runId: 123, interval: 3 },
241
+ { timeout: null },
242
+ );
243
+ ```
244
+
245
+ Workflow operations require `repo` and accept core options as a final argument.
246
+ Lists default to at most 20 runs, with branch, commit, workflow and status filters.
247
+ Run data uses gh's camelCase JSON fields, including `databaseId` and `attempt`.
248
+ Log retrieval supports an explicit attempt and job, and returns buffered text.
249
+ Invalid selectors and numeric options fail with `WorkflowInvalidOptions`.
250
+
251
+ `Workflow.watch` emits core stdout/stderr chunks using
252
+ `gh run watch --compact --exit-status`. It defaults to a three-second refresh
253
+ interval, fails when the run fails and inherits the core timeout. It requires a
254
+ gh version with `--compact` support; gh watch does not support fine-grained PATs.
255
+ Use REST page schemas through `Api` when a consumer needs snake_case fields,
256
+ page envelopes or attempt-specific jobs.
257
+
258
+ ## Consumer examples
259
+
260
+ - [Notifications](https://github.com/timmo001/effect-gh/blob/main/examples/notifications.ts): nullable notification fields,
261
+ single-page counts, mark-read/done and subscription requests with empty
262
+ responses, plus consumer-side NodeServices composition.
263
+ - [Workflow runs](https://github.com/timmo001/effect-gh/blob/main/examples/workflow-runs.ts): REST page envelopes, branch and SHA
264
+ filtering, retained run attempts, attempt-specific jobs and failed logs.
265
+
266
+ These examples are typechecked and tested against fixtures matching the dotfiles
267
+ and Herdr Workflow Watch contracts. They preserve the data needed by those
268
+ consumers; filtering policy, reconciliation, completeness checks and runtime
269
+ ownership stay with the application. They are migration references, not drop-in
270
+ replacements for either existing service.
271
+
272
+ ## Development
273
+
274
+ Use the tool versions pinned in [mise.toml](mise.toml) and Bun for dependencies.
275
+
276
+ ```sh
277
+ mise run install
278
+ mise run check
279
+ mise run build
280
+ ```
281
+
282
+ ## Releases
283
+
284
+ To inspect the package locally, run `mise exec -- npm pack --dry-run`; the pack
285
+ hook builds `dist/`.
286
+ The package includes only the ESM build, declarations, README, licence and package
287
+ metadata.
288
+
289
+ Before the first automated publication, configure npm trusted publishing for
290
+ `timmo001/effect-gh` and workflow filename `release.yml`. An initial package
291
+ publication may be needed before that configuration is available. The release
292
+ workflow uses the shared npm publisher and resolves Bun and Node versions from
293
+ `mise.toml` through mise.
294
+
295
+ For a release, set the package version, keep `bun.lock` in sync, and pass
296
+ `mise run check` and `mise run build`. Commit and push the reviewed version, then
297
+ publish a GitHub release with a tag matching the version exactly, such as `0.1.0`.
298
+ The publisher verifies the tag against the package version, validates and builds
299
+ the package, then publishes to npm with provenance.
package/dist/api.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { type GhError } from "./errors.js";
3
+ import { Gh, type GhOptions, type GhOutput } from "./gh.js";
4
+ export declare const Method: Schema.Literals<readonly ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE", "CONNECT"]>;
5
+ export type Method = typeof Method.Type;
6
+ declare const requestSchema: Schema.Struct<{
7
+ readonly endpoint: Schema.NonEmptyString;
8
+ readonly method: Schema.Literals<readonly ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE", "CONNECT"]>;
9
+ readonly hostname: Schema.optionalKey<Schema.NonEmptyString>;
10
+ readonly query: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Union<readonly [Schema.Union<readonly [Schema.String, Schema.Finite, Schema.Boolean]>, Schema.$Array<Schema.Union<readonly [Schema.String, Schema.Finite, Schema.Boolean]>>]>>>;
11
+ readonly headers: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
12
+ readonly body: Schema.optionalKey<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
13
+ }>;
14
+ export interface Request extends Schema.Schema.Type<typeof requestSchema> {
15
+ /** Gh overrides. Stdin is owned by body; bodyless calls clear any layer stdin. */
16
+ readonly options?: Omit<GhOptions, "stdin">;
17
+ }
18
+ export interface PageRequest extends Omit<Request, "method" | "body"> {
19
+ readonly method: "GET";
20
+ readonly body?: never;
21
+ }
22
+ /** Returns stdout, stderr and the CLI exit code, including empty or non-JSON responses. Never retries. */
23
+ export declare const raw: (request: Request) => Effect.Effect<GhOutput, GhError, Gh>;
24
+ /** Decodes one JSON response. Encoding and decoding failures are GhDecodeError; requests never retry. */
25
+ export declare const json: <S extends Schema.Constraint>(request: Request, schema: S) => Effect.Effect<S["Type"], GhError, Gh | S["DecodingServices"]>;
26
+ /** Fetches REST GET pages with --paginate --slurp. The schema describes each page, preserving envelopes. Never retries. */
27
+ export declare const pages: <S extends Schema.Constraint>(request: PageRequest, schema: S) => Effect.Effect<readonly S["Type"][], GhError, Gh | S["DecodingServices"]>;
28
+ export {};
package/dist/api.js ADDED
@@ -0,0 +1,87 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { GhDecodeError } from "./errors.js";
3
+ import { Gh } from "./gh.js";
4
+ export const Method = Schema.Literals([
5
+ "GET",
6
+ "HEAD",
7
+ "POST",
8
+ "PUT",
9
+ "PATCH",
10
+ "DELETE",
11
+ "OPTIONS",
12
+ "TRACE",
13
+ "CONNECT",
14
+ ]);
15
+ const queryValue = Schema.Union([Schema.String, Schema.Finite, Schema.Boolean]);
16
+ const requestSchema = Schema.Struct({
17
+ endpoint: Schema.NonEmptyString,
18
+ method: Method,
19
+ hostname: Schema.optionalKey(Schema.NonEmptyString),
20
+ query: Schema.optionalKey(Schema.Record(Schema.String, Schema.Union([queryValue, Schema.Array(queryValue)]))),
21
+ headers: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
22
+ body: Schema.optionalKey(Schema.Json),
23
+ });
24
+ const pageRequestSchema = Schema.Struct({
25
+ ...requestSchema.fields,
26
+ endpoint: Schema.NonEmptyString.check(Schema.isPattern(/^(?!\/?graphql(?:[?#]|$))/)),
27
+ method: Schema.Literal("GET"),
28
+ body: Schema.optionalKey(Schema.Never),
29
+ });
30
+ const prepare = Effect.fn("Api.prepare")(function* (request) {
31
+ const input = yield* Schema.decodeEffect(requestSchema)(request).pipe(Effect.mapError((cause) => new GhDecodeError({ cause })));
32
+ const endpoint = yield* Effect.try({
33
+ try: () => {
34
+ const query = [];
35
+ for (const [key, value] of Object.entries(input.query ?? {})) {
36
+ for (const item of Array.isArray(value) ? value : [value]) {
37
+ query.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(item))}`);
38
+ }
39
+ }
40
+ if (query.length === 0)
41
+ return input.endpoint;
42
+ const fragmentIndex = input.endpoint.indexOf("#");
43
+ const path = fragmentIndex === -1
44
+ ? input.endpoint
45
+ : input.endpoint.slice(0, fragmentIndex);
46
+ const fragment = fragmentIndex === -1 ? "" : input.endpoint.slice(fragmentIndex);
47
+ const separator = !path.includes("?")
48
+ ? "?"
49
+ : path.endsWith("?") || path.endsWith("&")
50
+ ? ""
51
+ : "&";
52
+ return `${path}${separator}${query.join("&")}${fragment}`;
53
+ },
54
+ catch: (cause) => new GhDecodeError({ cause }),
55
+ });
56
+ const args = ["api", "--method", input.method];
57
+ if (input.hostname !== undefined)
58
+ args.push(`--hostname=${input.hostname}`);
59
+ for (const [name, value] of Object.entries(input.headers ?? {})) {
60
+ args.push(`--header=${name}: ${value}`);
61
+ }
62
+ let stdin;
63
+ if (input.body !== undefined) {
64
+ stdin = yield* Schema.encodeEffect(Schema.fromJsonString(Schema.Json))(input.body).pipe(Effect.mapError((cause) => new GhDecodeError({ cause })));
65
+ args.push("--input", "-");
66
+ }
67
+ return { args, endpoint, options: { ...request.options, stdin } };
68
+ });
69
+ /** Returns stdout, stderr and the CLI exit code, including empty or non-JSON responses. Never retries. */
70
+ export const raw = Effect.fn("Api.raw")(function* (request) {
71
+ const command = yield* prepare(request);
72
+ const gh = yield* Gh;
73
+ return yield* gh.execute([...command.args, "--", command.endpoint], command.options);
74
+ });
75
+ /** Decodes one JSON response. Encoding and decoding failures are GhDecodeError; requests never retry. */
76
+ export const json = Effect.fn("Api.json")(function* (request, schema) {
77
+ const command = yield* prepare(request);
78
+ const gh = yield* Gh;
79
+ return yield* gh.json([...command.args, "--", command.endpoint], schema, command.options);
80
+ });
81
+ /** Fetches REST GET pages with --paginate --slurp. The schema describes each page, preserving envelopes. Never retries. */
82
+ export const pages = Effect.fn("Api.pages")(function* (request, schema) {
83
+ yield* Schema.decodeEffect(pageRequestSchema)(request).pipe(Effect.mapError((cause) => new GhDecodeError({ cause })));
84
+ const command = yield* prepare(request);
85
+ const gh = yield* Gh;
86
+ return yield* gh.json([...command.args, "--paginate", "--slurp", "--", command.endpoint], Schema.Array(schema), command.options);
87
+ });
@@ -0,0 +1,28 @@
1
+ import { Schema } from "effect";
2
+ declare const GhCommandError_base: Schema.Class<GhCommandError, Schema.TaggedStruct<"GhCommandError", {
3
+ readonly executable: Schema.String;
4
+ readonly exitCode: Schema.Int;
5
+ readonly stderr: Schema.String;
6
+ readonly stderrTruncated: Schema.Boolean;
7
+ }>, import("effect/Cause").YieldableError>;
8
+ export declare class GhCommandError extends GhCommandError_base {
9
+ }
10
+ declare const GhPlatformError_base: Schema.Class<GhPlatformError, Schema.TaggedStruct<"GhPlatformError", {
11
+ readonly executable: Schema.String;
12
+ readonly cause: Schema.Defect;
13
+ }>, import("effect/Cause").YieldableError>;
14
+ export declare class GhPlatformError extends GhPlatformError_base {
15
+ }
16
+ declare const GhTimeoutError_base: Schema.Class<GhTimeoutError, Schema.TaggedStruct<"GhTimeoutError", {
17
+ readonly executable: Schema.String;
18
+ readonly timeoutMs: Schema.Finite;
19
+ }>, import("effect/Cause").YieldableError>;
20
+ export declare class GhTimeoutError extends GhTimeoutError_base {
21
+ }
22
+ declare const GhDecodeError_base: Schema.Class<GhDecodeError, Schema.TaggedStruct<"GhDecodeError", {
23
+ readonly cause: Schema.Defect;
24
+ }>, import("effect/Cause").YieldableError>;
25
+ export declare class GhDecodeError extends GhDecodeError_base {
26
+ }
27
+ export type GhError = GhCommandError | GhPlatformError | GhTimeoutError | GhDecodeError;
28
+ export {};
package/dist/errors.js ADDED
@@ -0,0 +1,14 @@
1
+ import { Schema } from "effect";
2
+ export class GhCommandError extends Schema.TaggedError()("GhCommandError", {
3
+ executable: Schema.String,
4
+ exitCode: Schema.Int,
5
+ stderr: Schema.String,
6
+ stderrTruncated: Schema.Boolean,
7
+ }) {
8
+ }
9
+ export class GhPlatformError extends Schema.TaggedError()("GhPlatformError", { executable: Schema.String, cause: Schema.Defect() }) {
10
+ }
11
+ export class GhTimeoutError extends Schema.TaggedError()("GhTimeoutError", { executable: Schema.String, timeoutMs: Schema.Finite }) {
12
+ }
13
+ export class GhDecodeError extends Schema.TaggedError()("GhDecodeError", { cause: Schema.Defect() }) {
14
+ }