ref0-git 0.6.0 → 0.7.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/app/apps/github/README.md +3 -7
  2. package/app/apps/github/generated/git-rest.ts +12 -12
  3. package/app/apps/github/src/clients/allowed.ts +7 -9
  4. package/app/apps/github/src/clients/avatars.ts +5 -3
  5. package/app/apps/github/src/clients/graphql.ts +12 -2
  6. package/app/apps/github/src/clients/host-calls.ts +2 -1
  7. package/app/apps/github/src/clients/transfers.ts +56 -19
  8. package/app/apps/github/src/context/context.ts +5 -5
  9. package/app/apps/github/src/context/host.ts +115 -0
  10. package/app/apps/github/src/ingress.ts +28 -0
  11. package/app/apps/github/src/policy.ts +113 -78
  12. package/app/apps/github/src/private-repos.ts +7 -7
  13. package/app/apps/github/src/pulls/review.ts +2 -1
  14. package/app/apps/github/src/releases/release-form.tsx +40 -4
  15. package/app/apps/github/src/releases/releases.ts +148 -22
  16. package/app/apps/github/src/routes/uploads/$owner/$repo/$release.tsx +9 -2
  17. package/app/apps/github/src/seed/seed.ts +9 -2
  18. package/app/apps/github/src/server.ts +28 -11
  19. package/app/apps/github/src/signin/approval.ts +20 -15
  20. package/app/apps/github/src/signin/attempts.ts +306 -0
  21. package/app/apps/github/src/signin/auth.ts +9 -0
  22. package/app/apps/github/src/signin/host-session.ts +30 -18
  23. package/app/apps/github/src/signin/limits.ts +35 -0
  24. package/app/pnpm-workspace.yaml +37 -36
  25. package/dist/cli/setup.mjs +1 -1
  26. package/dist/init/app.mjs +43 -23
  27. package/dist/init/cloudflare.mjs +8 -4
  28. package/dist/init/create.mjs +1 -1
  29. package/dist/init/detect.mjs +5 -3
  30. package/dist/init/files.mjs +6 -1
  31. package/dist/init/git-module.mjs +4 -6
  32. package/dist/init/metadata.mjs +6 -6
  33. package/dist/init/node-app.mjs +5 -2
  34. package/dist/init/stores.mjs +3 -2
  35. package/dist/init/template.mjs +13 -7
  36. package/dist/init/templates.mjs +51 -39
  37. package/dist/init/vercel.mjs +1 -1
  38. package/dist/init/versions.mjs +1 -1
  39. package/package.json +13 -13
@@ -39,19 +39,15 @@ A build for deploying holds none of the demo, so it starts with no repos and no
39
39
  | File | What it decides |
40
40
  | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
41
41
  | `src/policy.ts` | Who may read and write what: by default, anyone reads a public repo, a person writes under their own login, an org's members write under its login, and a repo is made only under a login someone holds |
42
- | `src/git.ts` | Git's options: each repo's `main` has a merge queue beside the merge button, and the checks the queue waits on |
42
+ | `src/git.ts` | Git's features and the drop-in's, a line each: each repo's `main` has a merge queue beside the merge button, and the checks the queue waits on |
43
43
  | `wrangler.jsonc` | The Worker's name, its two Durable Object classes, its R2 bucket, its D1, `APP_ORIGIN` and `SIGN_UP` |
44
44
 
45
45
  ## Require a check before the queue merges
46
46
 
47
- The queue waits on no check, so an entry merges once its candidate is built. To make it wait on CI's `ci` check, add one line, `requiredChecks`, to the drop-in's options in `src/git.ts`:
47
+ The queue waits on no check, so an entry merges once its candidate is built. To make it wait on CI's `ci` check, give the drop-in's Layer in `src/git.ts` one option, `requiredChecks`:
48
48
 
49
49
  ```ts
50
- export const github = createGitHubHandler(git, {
51
- authorize: policy.authorizeGitHub,
52
- people: policy.people,
53
- requiredChecks: () => ['ci'],
54
- });
50
+ Layer.provideMerge(GitHub.layer({ requiredChecks: () => ['ci'] })),
55
51
  ```
56
52
 
57
53
  ## Its typed client
@@ -889,7 +889,7 @@ export interface components {
889
889
  message: string;
890
890
  hint?: string;
891
891
  context?: {
892
- reason?: ("graph-length" | "merge-incomplete") | string;
892
+ reason?: ("event-version" | "graph-length" | "merge-incomplete") | string;
893
893
  } & {
894
894
  [key: string]: string | number | ("Infinity" | "-Infinity" | "NaN") | boolean | string[] | null;
895
895
  };
@@ -925,7 +925,7 @@ export interface components {
925
925
  message: string;
926
926
  hint?: string;
927
927
  context?: {
928
- reason?: ("too-large" | "rate-limited" | "walk-limit" | "diff-limit" | "object-too-large" | "delta-too-large" | "response-too-large" | "too-many-pointers" | "fetch-plan-too-large" | "too-many-store-calls" | "call-budget" | "events-undelivered" | "events-waiting" | "name-churn" | "queue-full" | "queue-targets-full" | "too-many-gitmodules-and-gitattributes" | "prune-walk-too-large") | string;
928
+ reason?: ("too-large" | "rate-limited" | "walk-limit" | "diff-limit" | "object-too-large" | "delta-too-large" | "response-too-large" | "too-many-pointers" | "fetch-plan-too-large" | "too-many-store-calls" | "call-budget" | "events-undelivered" | "events-waiting" | "name-churn" | "queue-full" | "queue-targets-full" | "too-many-gitmodules-and-gitattributes" | "prune-walk-too-large" | "job-step-calls" | "job-step-yielded") | string;
929
929
  indexBytes?: number | ("Infinity" | "-Infinity" | "NaN");
930
930
  pushBytes?: number | ("Infinity" | "-Infinity" | "NaN");
931
931
  most?: number | ("Infinity" | "-Infinity" | "NaN");
@@ -951,7 +951,7 @@ export interface components {
951
951
  message: string;
952
952
  hint?: string;
953
953
  context?: {
954
- reason?: ("cursor-expired" | "diverged" | "merge-conflict" | "candidate-superseded" | "candidate-cancelled" | "entry-gone" | "ref-conflict" | "newer-format" | "changed-while-checked" | "unsupported-attribute" | "unrelated-histories" | "unsupported-virtual-base" | "own-repo" | "not-a-fork" | "no-copy-rows" | "shallow-root" | "shallow-upload" | "sync-unbound" | "import-cancelled" | "importing" | "history-not-imported" | "stage-gone" | "remote-refused" | "atomic-partner" | "merges-off") | string;
954
+ reason?: ("cursor-expired" | "diverged" | "merge-conflict" | "candidate-superseded" | "candidate-cancelled" | "entry-gone" | "ref-conflict" | "newer-format" | "changed-while-checked" | "unsupported-attribute" | "unrelated-histories" | "unsupported-virtual-base" | "own-repo" | "not-a-fork" | "no-copy-rows" | "shallow-root" | "shallow-upload" | "import-cancelled" | "importing" | "history-not-imported" | "stage-gone" | "remote-refused" | "atomic-partner" | "merges-off" | "no-releases") | string;
955
955
  /** @enum {string} */
956
956
  importState?: "running" | "cancelled" | "failed";
957
957
  attribute?: string;
@@ -981,7 +981,7 @@ export interface components {
981
981
  message: string;
982
982
  hint?: string;
983
983
  context?: {
984
- reason?: ("no-queue" | "no-topics" | "ambiguous") | string;
984
+ reason?: ("no-queue" | "no-sync" | "no-topics" | "ambiguous") | string;
985
985
  target?: string;
986
986
  } & {
987
987
  [key: string]: string | number | ("Infinity" | "-Infinity" | "NaN") | boolean | string[] | null;
@@ -993,7 +993,7 @@ export interface components {
993
993
  message: string;
994
994
  hint?: string;
995
995
  context?: {
996
- reason?: ("files-refused" | "entry-unpublishable") | string;
996
+ reason?: ("files-refused" | "entry-unpublishable" | "fetch-depth-unsupported") | string;
997
997
  entries?: string[];
998
998
  paths?: string[];
999
999
  total?: number | ("Infinity" | "-Infinity" | "NaN");
@@ -1525,16 +1525,16 @@ export interface components {
1525
1525
  stats: {
1526
1526
  repo: string;
1527
1527
  refs: number | ("Infinity" | "-Infinity" | "NaN");
1528
- packs: number | ("Infinity" | "-Infinity" | "NaN");
1529
- packBytes: number | ("Infinity" | "-Infinity" | "NaN");
1530
- ownBytes: number | ("Infinity" | "-Infinity" | "NaN");
1531
- looseObjects: number | ("Infinity" | "-Infinity" | "NaN");
1532
- looseBytes: number | ("Infinity" | "-Infinity" | "NaN");
1533
- leavingBytes: number | ("Infinity" | "-Infinity" | "NaN");
1528
+ packs?: number | ("Infinity" | "-Infinity" | "NaN");
1529
+ packBytes?: number | ("Infinity" | "-Infinity" | "NaN");
1530
+ ownBytes?: number | ("Infinity" | "-Infinity" | "NaN");
1531
+ looseObjects?: number | ("Infinity" | "-Infinity" | "NaN");
1532
+ looseBytes?: number | ("Infinity" | "-Infinity" | "NaN");
1533
+ leavingBytes?: number | ("Infinity" | "-Infinity" | "NaN");
1534
1534
  pushedAt?: number | ("Infinity" | "-Infinity" | "NaN");
1535
1535
  maintainedAt?: number | ("Infinity" | "-Infinity" | "NaN");
1536
1536
  };
1537
- work: {
1537
+ work?: {
1538
1538
  waiting: number | ("Infinity" | "-Infinity" | "NaN");
1539
1539
  oldestDue?: number | ("Infinity" | "-Infinity" | "NaN");
1540
1540
  failed: number | ("Infinity" | "-Infinity" | "NaN");
@@ -1,4 +1,4 @@
1
- import type { GitAuthorize, RepoAccess, TokenScope } from '@ref0/git';
1
+ import type { Policy, RepoAccess, TokenScope } from '@ref0/git';
2
2
  import type { GitHubOperationKind } from '@ref0/github';
3
3
  import { authorizeOperation, credentialCeiling, repoOfNodeId } from '@ref0/github';
4
4
  import { createServerFn } from '@tanstack/react-start';
@@ -10,7 +10,7 @@ import type { AppContext } from '../context/context.ts';
10
10
  import { forward } from './calls.ts';
11
11
 
12
12
  /**
13
- * The writes a page makes through a host call (Q520), which Git's `authorize` decides for the
13
+ * The writes a page makes through a host call (Q520), which Git's `Policy` decides for the
14
14
  * session's person, since no token reaches them: a repo's General settings and its deletion. A
15
15
  * `push` with no updates asks whether Git would let the person push at all, for the controls that
16
16
  * make and delete branches.
@@ -19,7 +19,7 @@ export const hostOperations = [
19
19
  'repo.update',
20
20
  'repo.delete',
21
21
  'push',
22
- ] as const satisfies readonly Parameters<GitAuthorize>[0]['operation']['kind'][];
22
+ ] as const satisfies readonly Policy.Input['operation']['kind'][];
23
23
 
24
24
  type HostOperation = (typeof hostOperations)[number];
25
25
 
@@ -250,12 +250,10 @@ export const allowedFor = async (
250
250
  kind === 'push'
251
251
  ? { kind, repo: repo.full_name, updates: [] }
252
252
  : { kind, repo: repo.full_name };
253
- const decided = await context.authorize({
254
- actor: caller.actor,
255
- operation,
256
- repo: visibility,
257
- signal,
258
- });
253
+ const decided = await Effect.runPromise(
254
+ context.authorize({ caller: { actor: caller.actor }, operation, repo: visibility }),
255
+ { signal },
256
+ );
259
257
 
260
258
  return decided.kind === 'accept';
261
259
  }
@@ -158,8 +158,9 @@ const matches = (header: string | null, etag: string) =>
158
158
  * their sniffed type, never sniffed again by the browser, and sandboxed. A private repo's icon is
159
159
  * cached only by the browser, and so is a picture of an account the lookup hides from anyone
160
160
  * signed out; a public repo's icon, and every other picture, by anyone.
161
- * With the avatar's own hash as `v`, it's cached for a year; otherwise it's revalidated by its ETag
162
- * each time, which answers 304 for the one the browser holds.
161
+ * A private icon with the avatar's own hash as `v` is cached for a year. Every other is revalidated
162
+ * by its ETag each time, a public one at its hash too, which answers 304 for the one the browser
163
+ * holds, so a repo made private answers its icon's URL 404 to those it hides it from (Q1156).
163
164
  */
164
165
  export const serveAvatar = async (
165
166
  context: AvatarContext,
@@ -176,7 +177,8 @@ export const serveAvatar = async (
176
177
 
177
178
  const etag = `"${icon.hash}"`;
178
179
  const scope = cachedFor(target);
179
- const kept = url.searchParams.get('v') === icon.hash ? 'max-age=31536000, immutable' : 'no-cache';
180
+ const atHash = url.searchParams.get('v') === icon.hash;
181
+ const kept = scope === 'private' && atHash ? 'max-age=31536000, immutable' : 'no-cache';
180
182
  const headers = new Headers({ etag, 'cache-control': `${scope}, ${kept}` });
181
183
  if (matches(request.headers.get('if-none-match'), etag))
182
184
  return new Response(null, { status: 304, headers });
@@ -14,13 +14,23 @@ const GraphQLAnswer = Schema.Struct({
14
14
  const decodeGraphQLAnswer = Schema.decodeUnknownOption(Schema.fromJsonString(GraphQLAnswer));
15
15
 
16
16
  /** An operation's variables: its strings, its numbers, and `null` for one it leaves out. */
17
- export type Variables = Readonly<Record<string, string | number | null>>;
17
+ const Variables = Schema.Record(
18
+ Schema.String,
19
+ Schema.Union([Schema.String, Schema.Number, Schema.Null]),
20
+ );
21
+
22
+ export type Variables = typeof Variables.Type;
23
+
24
+ /** What `/api/graphql` takes: the operation's text and its variables. */
25
+ const GraphQLRequest = Schema.Struct({ query: Schema.String, variables: Variables });
26
+
27
+ const encodeGraphQLRequest = Schema.encodeSync(Schema.fromJsonString(GraphQLRequest));
18
28
 
19
29
  /** `operation` with `variables`, as `/api/graphql` takes a request. */
20
30
  export const graphqlRequest = (operation: string, variables: Variables): RequestInit => ({
21
31
  method: 'POST',
22
32
  headers: { 'content-type': 'application/json' },
23
- body: JSON.stringify({ query: operation, variables }),
33
+ body: encodeGraphQLRequest({ query: operation, variables }),
24
34
  });
25
35
 
26
36
  /**
@@ -1,5 +1,6 @@
1
1
  import { createServerFn } from '@tanstack/react-start';
2
2
  import { getRequest } from '@tanstack/react-start/server';
3
+ import * as Effect from 'effect/Effect';
3
4
  import * as Option from 'effect/Option';
4
5
  import * as Schema from 'effect/Schema';
5
6
 
@@ -162,7 +163,7 @@ const callAs = async (
162
163
  call: { readonly method: string; readonly path: string; readonly json?: string },
163
164
  ) => {
164
165
  const headers = new Headers({ accept: 'application/json' });
165
- headers.set(hostSessionHeader, await hostSessionFor(context.sealKey, login));
166
+ headers.set(hostSessionHeader, await Effect.runPromise(hostSessionFor(context.sealKey, login)));
166
167
 
167
168
  if (call.json !== undefined) headers.set('content-type', 'application/json');
168
169
 
@@ -18,6 +18,12 @@ export type TransferContext = Pick<AppContext, 'api' | 'session'>;
18
18
  /** The drop-in's limit on one asset, as GitHub's: under 2 GiB. */
19
19
  export const assetBytesMost = 2 * 1024 ** 3;
20
20
 
21
+ /**
22
+ * The drop-in's part, as its begin answers `part_bytes`: a file past it uploads in parts, each a
23
+ * request a host's platform takes, as Cloudflare's cap of 100 MB on a request's body.
24
+ */
25
+ export const partBytes = 64 * 1024 ** 2;
26
+
21
27
  /** An owner or a repo in a transfer's path: a name, never `.` or `..`, and never a `/`. */
22
28
  const PathName = Schema.String.check(Schema.isPattern(/^(?!\.\.?$)[A-Za-z0-9_.-]{1,100}$/));
23
29
 
@@ -39,28 +45,62 @@ export type UploadPlace = typeof UploadPlace.Type;
39
45
 
40
46
  const uploadPlace = Schema.decodeUnknownOption(UploadPlace);
41
47
 
48
+ /** An upload in parts' ID, as the drop-in makes it, and a part's number. */
49
+ const uploadIdForm = /^[0-9a-f]{32}$/;
50
+
51
+ const partForm = /^(?:0|[1-9][0-9]{0,2})$/;
52
+
42
53
  /**
43
- * The drop-in's URL for an upload to the release: `/api/uploads/repos/{owner}/{repo}/releases/
44
- * {id}/assets`, with the asset's `name` and perhaps its `label`, and `undefined` for anything else.
54
+ * The drop-in's URL for a step of an upload to the release, by the app route's method and search,
55
+ * and `undefined` for anything else:
56
+ *
57
+ * - `POST ?name=&label=`: the one request, to `/api/uploads/repos/{owner}/{repo}/releases/{id}/assets`.
58
+ * - `POST ?name=&label=&parts`: begins an upload in parts, to `…/assets/uploads`.
59
+ * - `PUT ?upload=&part=`: a part, to `…/assets/uploads/{upload}/parts/{part}`.
60
+ * - `POST ?upload=`: the complete, to `…/assets/uploads/{upload}/complete`.
61
+ * - `DELETE ?upload=`: the abort, to `…/assets/uploads/{upload}`.
45
62
  */
46
- export const uploadUrl = (origin: string, place: UploadPlace, search: URLSearchParams) => {
63
+ export const uploadUrl = (
64
+ origin: string,
65
+ place: UploadPlace,
66
+ method: string,
67
+ search: URLSearchParams,
68
+ ) => {
47
69
  const parts = Option.getOrUndefined(uploadPlace(place));
48
- const name = search.get('name');
49
- if (parts === undefined || name === null || name === '') return undefined;
70
+ if (parts === undefined) return undefined;
50
71
 
51
72
  const { owner, repo, release } = parts;
52
- const url = new URL(`/api/uploads/repos/${owner}/${repo}/releases/${release}/assets`, origin);
53
- url.searchParams.set('name', name);
54
- const label = search.get('label');
55
- if (label !== null) url.searchParams.set('label', label);
73
+ const assets = `/api/uploads/repos/${owner}/${repo}/releases/${release}/assets`;
74
+ const upload = search.get('upload');
75
+
76
+ if (upload === null) {
77
+ const name = search.get('name');
78
+ if (method !== 'POST' || name === null || name === '') return undefined;
56
79
 
57
- return url;
80
+ const url = new URL(search.has('parts') ? `${assets}/uploads` : assets, origin);
81
+ url.searchParams.set('name', name);
82
+ const label = search.get('label');
83
+ if (label !== null) url.searchParams.set('label', label);
84
+
85
+ return url;
86
+ }
87
+
88
+ if (!uploadIdForm.test(upload)) return undefined;
89
+
90
+ const at = `${assets}/uploads/${upload}`;
91
+ const part = search.get('part') ?? '';
92
+ if (method === 'PUT')
93
+ return partForm.test(part) ? new URL(`${at}/parts/${part}`, origin) : undefined;
94
+
95
+ if (method === 'POST') return new URL(`${at}/complete`, origin);
96
+
97
+ return method === 'DELETE' ? new URL(at, origin) : undefined;
58
98
  };
59
99
 
60
100
  /**
61
- * `POST /uploads/{owner}/{repo}/{release}?name=` from the app's own page: the body streamed to the
62
- * drop-in's upload for that release, as the session's holder, and the drop-in's answer. A
63
- * cross-site post uploads nothing, and a redirect isn't followed.
101
+ * An upload's step from the app's own page, `/uploads/{owner}/{repo}/{release}`, as `uploadUrl`
102
+ * names them: the body streamed to the drop-in's route for that step, as the session's holder,
103
+ * and the drop-in's answer. A cross-site request uploads nothing, and a redirect isn't followed.
64
104
  */
65
105
  export const forwardUpload = async (
66
106
  context: TransferContext,
@@ -68,12 +108,9 @@ export const forwardUpload = async (
68
108
  place: UploadPlace,
69
109
  ): Promise<Response> => {
70
110
  const url = new URL(request.url);
111
+ if (request.headers.get('origin') !== url.origin) return refused(403, 'Upload from the app');
71
112
 
72
- if (request.method !== 'POST' || request.headers.get('origin') !== url.origin) {
73
- return refused(403, 'Upload from the app');
74
- }
75
-
76
- const target = uploadUrl(url.origin, place, url.searchParams);
113
+ const target = uploadUrl(url.origin, place, request.method, url.searchParams);
77
114
  if (target === undefined) return refused(400, 'Not a release upload');
78
115
 
79
116
  const headers = new Headers({ accept: 'application/json' });
@@ -87,7 +124,7 @@ export const forwardUpload = async (
87
124
 
88
125
  // A streamed body is sent as it's read: Node's fetch asks for `duplex`, which the DOM's types lack.
89
126
  const streamed: RequestInit & { readonly duplex: 'half' } = {
90
- method: 'POST',
127
+ method: request.method,
91
128
  headers,
92
129
  body: request.body,
93
130
  duplex: 'half',
@@ -1,4 +1,4 @@
1
- import type { Caller, GitAuthorize, GitServer, Result, TokenCalls } from '@ref0/git';
1
+ import type { Caller, Policy, RepoCalls, Result, TokenCalls } from '@ref0/git';
2
2
  import type { GitHubAuthorize } from '@ref0/github';
3
3
  import type {} from '@tanstack/react-start';
4
4
 
@@ -103,8 +103,8 @@ export interface AppContext {
103
103
  readonly sessionCookie: () => Promise<SessionCookie>;
104
104
  /** Git's `identify`: the caller a request's credential names, as the drop-in finds it. */
105
105
  readonly identify: (request: Request) => Promise<Result<Caller>>;
106
- /** The host's say on Git's own operations, which a host call is held to: Git's `authorize`. */
107
- readonly authorize: GitAuthorize;
106
+ /** The host's say on Git's own operations, which a host call is held to: its `Policy`'s. */
107
+ readonly authorize: Policy.PolicyService['authorize'];
108
108
  /** The host's say on a GitHub operation: the `authorize` the drop-in was made with. */
109
109
  readonly authorizeGitHub: GitHubAuthorize;
110
110
  /** The push rules Git was made with, each by name and the refs it covers on every repo. */
@@ -133,9 +133,9 @@ export interface ImageSigner {
133
133
  readonly sign: (urls: readonly string[]) => Promise<ReadonlyMap<string, string>>;
134
134
  }
135
135
 
136
- /** Git's direct calls a host call reads with, as host code. */
136
+ /** Git's direct calls a host call reads with, as host code, each an Effect on Git's runtime. */
137
137
  export interface HostGit {
138
- readonly repos: Pick<GitServer['repos'], 'list'>;
138
+ readonly repos: Pick<RepoCalls, 'list'>;
139
139
  readonly tokens?: Pick<TokenCalls, 'list'> | undefined;
140
140
  }
141
141
 
@@ -0,0 +1,115 @@
1
+ import { Auth, Git, Objects, Policy, RepoRecords, Repos, Rules, Tokens } from '@ref0/git';
2
+ import type { GitError, PushRule, RepoCalls, Result, TokenCalls } from '@ref0/git';
3
+ import { JoinedCalls } from '@ref0/git/extend';
4
+ import { GitHubPolicy, People } from '@ref0/github';
5
+ import type { GitHubAuthorize, PeopleFor } from '@ref0/github';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Exit from 'effect/Exit';
8
+ import * as Layer from 'effect/Layer';
9
+ import type * as ManagedRuntime from 'effect/ManagedRuntime';
10
+ import * as Option from 'effect/Option';
11
+
12
+ /** The host's say, which the starter's Git is made with: who calls, what they may do, and its push rules. */
13
+ export interface HostParts {
14
+ /** Git's `Policy`'s decision. */
15
+ readonly authorize: Policy.PolicyService['authorize'];
16
+ /** Who is calling, past Git's own tokens: the admin's bearer and the app's host session. */
17
+ readonly auth: Auth.AuthService;
18
+ /** The drop-in's `authorize`. */
19
+ readonly authorizeGitHub: GitHubAuthorize;
20
+ /** The host's push rules. */
21
+ readonly rules: readonly PushRule[];
22
+ }
23
+
24
+ /**
25
+ * The host's directory as the drop-in's `People`, made over Git's host calls, each an Effect, which
26
+ * its own lookups don't list through.
27
+ */
28
+ export const peopleOver = (people: PeopleFor) =>
29
+ People.layer(
30
+ Effect.map(Effect.service(JoinedCalls), (joined) => people({ git: joined.effectHostCalls })),
31
+ );
32
+
33
+ /**
34
+ * What host code reads of the runtime past its adapter's own services: Git, its tokens, its repos
35
+ * and its repos' records. The rest of Git's and the drop-in's services stay inside the Layer.
36
+ */
37
+ export type HostServices = Git.Git | Tokens.Tokens | Repos.Repos | RepoRecords.RepoRecords;
38
+
39
+ /** `HostServices`, out of the whole host's. */
40
+ const hostServices = Layer.effectContext(Effect.context<HostServices>());
41
+
42
+ /**
43
+ * The starter's whole host: Git with `features`, over `objects` and `adapter`'s records, jobs and
44
+ * bucket, with `parts` deciding. It gives `HostServices` and the adapter's own services, so a
45
+ * platform's objects and job runner run on the same runtime.
46
+ */
47
+ export const hostLayer = <A, E, O, OE, OR, F, FE, FR>(
48
+ adapter: Layer.Layer<A, E>,
49
+ objects: Layer.Layer<Objects.Storage | O, OE, OR>,
50
+ features: Layer.Layer<F, FE, FR>,
51
+ parts: HostParts,
52
+ ) =>
53
+ hostServices.pipe(
54
+ Layer.provide(Git.layer({}, features)),
55
+ Layer.provide(
56
+ Layer.mergeAll(
57
+ Policy.layer(Policy.make(parts.authorize)),
58
+ GitHubPolicy.layer(GitHubPolicy.make(parts.authorizeGitHub)),
59
+ Auth.layer(parts.auth),
60
+ Rules.layer(parts.rules),
61
+ ),
62
+ ),
63
+ Layer.provide(objects),
64
+ Layer.provideMerge(adapter),
65
+ );
66
+
67
+ /**
68
+ * Git's routes on `runtime`, the drop-in's among them, as the server's ingress reads them: `route`
69
+ * answers `undefined` for a URL none owns, and `fetch` answers it Git's JSON `404`. Neither
70
+ * rejects: a runtime whose build failed answers `fetch`'s refusal.
71
+ */
72
+ export const routeOn = <E>(runtime: ManagedRuntime.ManagedRuntime<Git.Git, E>) => {
73
+ const fetch = Git.toFetch(runtime);
74
+
75
+ const route = async (request: Request) => {
76
+ const routed = await runtime.runPromiseExit(Git.route(request), { signal: request.signal });
77
+
78
+ return Exit.isSuccess(routed) ? Option.getOrUndefined(routed.value) : fetch(request);
79
+ };
80
+
81
+ return { route, fetch };
82
+ };
83
+
84
+ /** An Effect on the host's runtime, answered as Git's Promise calls answer: a `Result`. */
85
+ export type HostRun<R> = <A>(
86
+ effect: Effect.Effect<A, GitError, R>,
87
+ signal?: AbortSignal,
88
+ ) => Promise<Result<A>>;
89
+
90
+ /** `HostRun` on `runtime`: a failure is the answer's error, never a rejection. */
91
+ export const runOn =
92
+ <R, E>(runtime: ManagedRuntime.ManagedRuntime<R, E>): HostRun<R> =>
93
+ (effect, signal) =>
94
+ runtime.runPromise(
95
+ Effect.match(effect, {
96
+ onFailure: (error): Result<never> => ({ kind: 'error', error }),
97
+ onSuccess: (value) => ({ kind: 'success', value }) as const,
98
+ }),
99
+ signal === undefined ? undefined : { signal },
100
+ );
101
+
102
+ /** Git's own tokens on `run`, as host code calls them: Better Auth's sessions mint theirs here. */
103
+ export const tokenCallsOn = (run: HostRun<Tokens.Tokens>): TokenCalls => ({
104
+ create: (target, input) => run(Tokens.create(target, input)),
105
+ list: (target, input) => run(Tokens.list(target, input)),
106
+ get: (token, input) => run(Tokens.get(token, input)),
107
+ revoke: (token, input) => run(Tokens.revoke(token, input)),
108
+ revokeKey: (target, key, input) => run(Tokens.revokeKey(target, key, input)),
109
+ });
110
+
111
+ /** Git's repo list on `run`, as host code calls it. */
112
+ export const repoListOn =
113
+ (run: HostRun<Repos.Repos>): RepoCalls['list'] =>
114
+ (input) =>
115
+ run(Repos.list(input));
@@ -0,0 +1,28 @@
1
+ /** A handler's answer for a URL it owns, or `undefined` for one it leaves to the next. */
2
+ type Route = (request: Request) => Promise<Response | undefined>;
3
+
4
+ /** What `ingressOf` puts in front of the app, in its order. */
5
+ export interface Owners {
6
+ /** The device page's front door, `deviceAttemptGate`'s: an answer only for an attempt it refuses. */
7
+ readonly gate: Route;
8
+ /**
9
+ * Git's routes, the drop-in's, its REST's, its Smart HTTP's and its sign-in's among them, and
10
+ * Git's answer for a URL none owns: a JSON `404`.
11
+ */
12
+ readonly git: { readonly route: Route; readonly fetch: (request: Request) => Promise<Response> };
13
+ }
14
+
15
+ /**
16
+ * The server's two ways in, each through the front door first, so a code the page carries is
17
+ * read only once an attempt is spent: `owned`, for a request from outside, and `api`, for the
18
+ * app's own server calls, which never reach the app.
19
+ */
20
+ export const ingressOf = ({ gate, git }: Owners) => {
21
+ /** The front door, then every route of Git's runtime. */
22
+ const owned = async (request: Request) => (await gate(request)) ?? (await git.route(request));
23
+
24
+ /** Past the front door, Git's whole answer: a URL no route owns is its JSON `404`. */
25
+ const api = async (request: Request) => (await gate(request)) ?? git.fetch(request);
26
+
27
+ return { owned, api };
28
+ };