@shivaedev/test-kits 0.4.0 → 0.6.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 (98) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +42 -0
  3. package/dist/contract/settledQueries.d.ts +13 -0
  4. package/dist/contract/settledQueries.d.ts.map +1 -0
  5. package/dist/contract/settledQueries.js +20 -0
  6. package/dist/contract/settledQueries.js.map +1 -0
  7. package/dist/github/adapters/appProvider.d.ts +31 -0
  8. package/dist/github/adapters/appProvider.d.ts.map +1 -0
  9. package/dist/github/adapters/appProvider.js +31 -0
  10. package/dist/github/adapters/appProvider.js.map +1 -0
  11. package/dist/github/adapters/credentials.d.ts +21 -0
  12. package/dist/github/adapters/credentials.d.ts.map +1 -0
  13. package/dist/github/adapters/credentials.js +48 -0
  14. package/dist/github/adapters/credentials.js.map +1 -0
  15. package/dist/github/adapters/webhookDelivery.d.ts +7 -0
  16. package/dist/github/adapters/webhookDelivery.d.ts.map +1 -0
  17. package/dist/github/adapters/webhookDelivery.js +15 -0
  18. package/dist/github/adapters/webhookDelivery.js.map +1 -0
  19. package/dist/github/fake.d.ts +52 -0
  20. package/dist/github/fake.d.ts.map +1 -0
  21. package/dist/github/fake.js +18 -0
  22. package/dist/github/fake.js.map +1 -0
  23. package/dist/host/ProcessError.d.ts +10 -0
  24. package/dist/host/ProcessError.d.ts.map +1 -0
  25. package/dist/host/ProcessError.js +4 -0
  26. package/dist/host/ProcessError.js.map +1 -0
  27. package/dist/host/adapters/process.d.ts +24 -0
  28. package/dist/host/adapters/process.d.ts.map +1 -0
  29. package/dist/host/adapters/process.js +111 -0
  30. package/dist/host/adapters/process.js.map +1 -0
  31. package/dist/host/adapters/processReadouts.d.ts +10 -0
  32. package/dist/host/adapters/processReadouts.d.ts.map +1 -0
  33. package/dist/host/adapters/processReadouts.js +26 -0
  34. package/dist/host/adapters/processReadouts.js.map +1 -0
  35. package/dist/host/process.d.ts +26 -0
  36. package/dist/host/process.d.ts.map +1 -0
  37. package/dist/host/process.js +56 -0
  38. package/dist/host/process.js.map +1 -0
  39. package/dist/host/processChild.d.ts +7 -0
  40. package/dist/host/processChild.d.ts.map +1 -0
  41. package/dist/host/processChild.js +19 -0
  42. package/dist/host/processChild.js.map +1 -0
  43. package/dist/host/processProtocol.d.ts +20 -0
  44. package/dist/host/processProtocol.d.ts.map +1 -0
  45. package/dist/host/processProtocol.js +11 -0
  46. package/dist/host/processProtocol.js.map +1 -0
  47. package/dist/host/processReadouts.d.ts +7 -0
  48. package/dist/host/processReadouts.d.ts.map +1 -0
  49. package/dist/host/processReadouts.js +37 -0
  50. package/dist/host/processReadouts.js.map +1 -0
  51. package/dist/host/time.d.ts +9 -0
  52. package/dist/host/time.d.ts.map +1 -0
  53. package/dist/host/time.js +27 -0
  54. package/dist/host/time.js.map +1 -0
  55. package/dist/identity/adapters/oauthAuthorization.d.ts +20 -0
  56. package/dist/identity/adapters/oauthAuthorization.d.ts.map +1 -0
  57. package/dist/identity/adapters/oauthAuthorization.js +39 -0
  58. package/dist/identity/adapters/oauthAuthorization.js.map +1 -0
  59. package/dist/identity/adapters/oauthProtocol.d.ts +9 -0
  60. package/dist/identity/adapters/oauthProtocol.d.ts.map +1 -0
  61. package/dist/identity/adapters/oauthProtocol.js +105 -0
  62. package/dist/identity/adapters/oauthProtocol.js.map +1 -0
  63. package/dist/identity/adapters/oidcTokens.d.ts +39 -0
  64. package/dist/identity/adapters/oidcTokens.d.ts.map +1 -0
  65. package/dist/identity/adapters/oidcTokens.js +39 -0
  66. package/dist/identity/adapters/oidcTokens.js.map +1 -0
  67. package/dist/identity/oauth.d.ts +43 -0
  68. package/dist/identity/oauth.d.ts.map +1 -0
  69. package/dist/identity/oauth.js +20 -0
  70. package/dist/identity/oauth.js.map +1 -0
  71. package/dist/webhooks/adapters/githubHeaders.d.ts +5 -0
  72. package/dist/webhooks/adapters/githubHeaders.d.ts.map +1 -0
  73. package/dist/webhooks/adapters/githubHeaders.js +6 -0
  74. package/dist/webhooks/adapters/githubHeaders.js.map +1 -0
  75. package/dist/webhooks/deliver.d.ts +13 -0
  76. package/dist/webhooks/deliver.d.ts.map +1 -0
  77. package/dist/webhooks/deliver.js +20 -0
  78. package/dist/webhooks/deliver.js.map +1 -0
  79. package/package.json +13 -11
  80. package/src/contract/settledQueries.ts +39 -0
  81. package/src/github/adapters/appProvider.ts +34 -0
  82. package/src/github/adapters/credentials.ts +62 -0
  83. package/src/github/adapters/webhookDelivery.ts +20 -0
  84. package/src/github/fake.ts +30 -0
  85. package/src/host/ProcessError.ts +6 -0
  86. package/src/host/adapters/process.ts +122 -0
  87. package/src/host/adapters/processReadouts.ts +29 -0
  88. package/src/host/process.ts +69 -0
  89. package/src/host/processChild.ts +25 -0
  90. package/src/host/processProtocol.ts +11 -0
  91. package/src/host/processReadouts.ts +46 -0
  92. package/src/host/time.ts +33 -0
  93. package/src/identity/adapters/oauthAuthorization.ts +54 -0
  94. package/src/identity/adapters/oauthProtocol.ts +111 -0
  95. package/src/identity/adapters/oidcTokens.ts +42 -0
  96. package/src/identity/oauth.ts +35 -0
  97. package/src/webhooks/adapters/githubHeaders.ts +6 -0
  98. package/src/webhooks/deliver.ts +33 -0
@@ -0,0 +1,43 @@
1
+ import { Duration, Effect } from "effect";
2
+ import { type FakeHttpRequest, type FakeHttpRoute } from "@shivaedev/test-story/server/fakeHttpService.ts";
3
+ export interface OauthProfile {
4
+ readonly email: string;
5
+ readonly emailVerified?: boolean;
6
+ readonly name: string;
7
+ readonly sub: string;
8
+ }
9
+ export interface FakeOauthOptions {
10
+ readonly clientId?: string;
11
+ readonly clientSecret?: string;
12
+ readonly codeLifetime?: Duration.Input;
13
+ readonly profile?: OauthProfile | ((request: FakeHttpRequest) => OauthProfile);
14
+ readonly routes?: Readonly<Record<string, FakeHttpRoute>>;
15
+ }
16
+ export declare const fakeOauthProvider: (options?: FakeOauthOptions | undefined) => Effect.Effect<{
17
+ credentials: {
18
+ clientId: string;
19
+ clientSecret: string;
20
+ };
21
+ discoveryUrl: string;
22
+ refuseConsent: () => Effect.Effect<void, never, never>;
23
+ server: {
24
+ completed: import("effect/Stream").Stream<import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpRequestRecord, never, never>;
25
+ fault: (route: string, fault: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpFault, scope?: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpScope) => Effect.Effect<void, never, never>;
26
+ hold: (route: string, holdOptions?: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpHoldOptions) => Effect.Effect<{
27
+ release: Effect.Effect<void, never, never>;
28
+ waiting: Effect.Effect<void, never, never>;
29
+ }, never, never>;
30
+ narrate: (sink: (line: string) => void) => void;
31
+ received: import("effect/Stream").Stream<import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpRequestRecord, never, never>;
32
+ releaseOnArrival: (route: string, arrival: string, scope?: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpScope) => Effect.Effect<void, never, never>;
33
+ readonly requests: readonly import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpRequestRecord[];
34
+ scriptFault: (route: string, fault: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpFault, scriptOptions?: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpScriptOptions) => Effect.Effect<import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpScript, never, never>;
35
+ stall: (route: string, scope?: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpScope) => Effect.Effect<{
36
+ release: Effect.Effect<void, never, never>;
37
+ waiting: Effect.Effect<void, never, never>;
38
+ }, never, never>;
39
+ untilAbandoned: (matches: (request: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpRequestRecord) => boolean, wait: import("@shivaedev/test-story/server/until.ts").UntilOptions) => Effect.Effect<import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpRequestRecord, import("@shivaedev/test-story/server/until.ts").SignalNotReceived, never>;
40
+ url: string;
41
+ };
42
+ }, import("effect/Cause").UnknownError, import("effect/Scope").Scope>;
43
+ //# sourceMappingURL=oauth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth.d.ts","sourceRoot":"","sources":["../../src/identity/oauth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC1C,OAAO,EAAE,KAAK,eAAe,EAAE,KAAK,aAAa,EAAmB,MAAM,iDAAiD,CAAC;AAG5H,MAAM,WAAW,YAAY;IAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,aAAa,CAAC,EAAE,OAAO,CAAC;IACjC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,gBAAgB;IAChC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,YAAY,CAAC,EAAE,QAAQ,CAAC,KAAK,CAAC;IACvC,QAAQ,CAAC,OAAO,CAAC,EAAE,YAAY,GAAG,CAAC,CAAC,OAAO,EAAE,eAAe,KAAK,YAAY,CAAC,CAAC;IAC/E,QAAQ,CAAC,MAAM,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC;CAC1D;AAED,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;qEAe5B,CAAC"}
@@ -0,0 +1,20 @@
1
+ import { Duration, Effect } from "effect";
2
+ import { fakeHttpService } from "@shivaedev/test-story/server/fakeHttpService.ts";
3
+ import { oauthProtocol } from "#identity/adapters/oauthProtocol.ts";
4
+ export const fakeOauthProvider = Effect.fnUntraced(function* (options = {}) {
5
+ const credentials = { clientId: options.clientId ?? "story-client", clientSecret: options.clientSecret ?? "story-secret" };
6
+ const protocol = yield* oauthProtocol({
7
+ ...credentials,
8
+ codeLifetime: Duration.toMillis(options.codeLifetime ?? "1 minute"),
9
+ profile: options.profile ?? { email: "alice@social.test", name: "Alice", sub: "123" },
10
+ });
11
+ const server = yield* fakeHttpService({ routes: { ...protocol.routes, ...options.routes } });
12
+ protocol.issuer(server.url);
13
+ return {
14
+ credentials,
15
+ discoveryUrl: `${server.url}/.well-known/openid-configuration`,
16
+ refuseConsent: () => Effect.sync(() => protocol.consent(false)),
17
+ server,
18
+ };
19
+ });
20
+ //# sourceMappingURL=oauth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth.js","sourceRoot":"","sources":["../../src/identity/oauth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC1C,OAAO,EAA4C,eAAe,EAAE,MAAM,iDAAiD,CAAC;AAC5H,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAiBpE,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,OAAO,GAAqB,EAAE;IAC3F,MAAM,WAAW,GAAG,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,IAAI,cAAc,EAAE,YAAY,EAAE,OAAO,CAAC,YAAY,IAAI,cAAc,EAAE,CAAC;IAC3H,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,aAAa,CAAC;QACrC,GAAG,WAAW;QACd,YAAY,EAAE,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC,YAAY,IAAI,UAAU,CAAC;QACnE,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,EAAE,KAAK,EAAE,mBAAmB,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE;KACrF,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,eAAe,CAAC,EAAE,MAAM,EAAE,EAAE,GAAG,QAAQ,CAAC,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IAC7F,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAC5B,OAAO;QACN,WAAW;QACX,YAAY,EAAE,GAAG,MAAM,CAAC,GAAG,mCAAmC;QAC9D,aAAa,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QAC/D,MAAM;KACN,CAAC;AACH,CAAC,CAAC,CAAC"}
@@ -0,0 +1,5 @@
1
+ import { Effect, Redacted } from "effect";
2
+ export declare function githubHeaders(body: string, key: Redacted.Redacted<string>): Effect.Effect<{
3
+ "x-hub-signature-256": string;
4
+ }, never, never>;
5
+ //# sourceMappingURL=githubHeaders.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"githubHeaders.d.ts","sourceRoot":"","sources":["../../../src/webhooks/adapters/githubHeaders.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAE1C,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC;;iBAEzE"}
@@ -0,0 +1,6 @@
1
+ import { createHmac } from "node:crypto";
2
+ import { Effect, Redacted } from "effect";
3
+ export function githubHeaders(body, key) {
4
+ return Effect.sync(() => ({ "x-hub-signature-256": `sha256=${createHmac("sha256", Redacted.value(key)).update(body).digest("hex")}` }));
5
+ }
6
+ //# sourceMappingURL=githubHeaders.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"githubHeaders.js","sourceRoot":"","sources":["../../../src/webhooks/adapters/githubHeaders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAE1C,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,GAA8B;IACzE,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,qBAAqB,EAAE,UAAU,UAAU,CAAC,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AACzI,CAAC"}
@@ -0,0 +1,13 @@
1
+ import { Effect, type Redacted } from "effect";
2
+ import { HttpClient } from "effect/http";
3
+ import type { WebhookSource } from "@shivaedev/webhooks/server/registration.ts";
4
+ export type WebhookSigner<E = never, R = never> = (body: string, key: Redacted.Redacted<string>) => Effect.Effect<Readonly<Record<string, string>>, E, R>;
5
+ export interface WebhookDeliveryOptions<E = never, R = never> {
6
+ readonly body: string;
7
+ readonly headers?: Readonly<Record<string, string | null>>;
8
+ readonly sign?: WebhookSigner<E, R>;
9
+ readonly source: Pick<WebhookSource, "key">;
10
+ readonly url: string;
11
+ }
12
+ export declare const deliverWebhook: <E = never, R = never>(options: WebhookDeliveryOptions<E, R>) => Effect.Effect<import("effect/http/HttpClientResponse").HttpClientResponse, E | import("effect/Config").ConfigError | import("effect/http/HttpClientError").HttpClientError, R | HttpClient.HttpClient>;
13
+ //# sourceMappingURL=deliver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deliver.d.ts","sourceRoot":"","sources":["../../src/webhooks/deliver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAAY,UAAU,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4CAA4C,CAAC;AAGhF,MAAM,MAAM,aAAa,CAAC,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,KAAK,IAAI,CACjD,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,KAC1B,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;AAE3D,MAAM,WAAW,sBAAsB,CAAC,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,KAAK;IAC3D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC;IAC3D,QAAQ,CAAC,IAAI,CAAC,EAAE,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACpC,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;IAC5C,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACrB;AAED,eAAO,MAAM,cAAc,GAAgC,CAAC,UAAU,CAAC,0PAcrE,CAAC"}
@@ -0,0 +1,20 @@
1
+ import { Effect } from "effect";
2
+ import { HttpBody, HttpClient } from "effect/http";
3
+ import { githubHeaders } from "#webhooks/adapters/githubHeaders.ts";
4
+ export const deliverWebhook = Effect.fnUntraced(function* (options) {
5
+ const key = yield* options.source.key;
6
+ const signed = yield* (options.sign ?? githubHeaders)(options.body, key);
7
+ const headers = {};
8
+ for (const [name, value] of [...Object.entries(signed), ...Object.entries(options.headers ?? {})]) {
9
+ const lower = name.toLowerCase();
10
+ if (value === null) {
11
+ delete headers[lower];
12
+ }
13
+ else {
14
+ headers[lower] = value;
15
+ }
16
+ }
17
+ const client = yield* HttpClient.HttpClient;
18
+ return yield* client.post(options.url, { body: HttpBody.text(options.body, "application/json"), headers });
19
+ });
20
+ //# sourceMappingURL=deliver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deliver.js","sourceRoot":"","sources":["../../src/webhooks/deliver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAiB,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEnD,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAepE,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAwB,OAAqC;IACrH,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC;IACtC,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,IAAI,aAAa,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IACzE,MAAM,OAAO,GAA2B,EAAE,CAAC;IAC3C,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;QACnG,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QACjC,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YACpB,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC;QACvB,CAAC;aAAM,CAAC;YACP,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;QACxB,CAAC;IACF,CAAC;IACD,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,UAAU,CAAC,UAAU,CAAC;IAC5C,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,kBAAkB,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC;AAC5G,CAAC,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shivaedev/test-kits",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Reusable story building blocks for Platform applications",
5
5
  "keywords": [
6
6
  "effect"
@@ -43,11 +43,12 @@
43
43
  "README.md"
44
44
  ],
45
45
  "dependencies": {
46
- "@shivaedev/test-sql": "0.21.1",
47
- "@shivaedev/test-story": "0.39.1"
46
+ "@shivaedev/test-sql": "0.22.0",
47
+ "@shivaedev/test-story": "0.40.0"
48
48
  },
49
49
  "devDependencies": {
50
- "@shivaedev/quality": "0.61.1",
50
+ "@shivaedev/github": "0.13.1",
51
+ "@shivaedev/quality": "0.63.0",
51
52
  "@types/node": "24.19.2",
52
53
  "better-auth": "1.7.14",
53
54
  "effect": "4.0.7",
@@ -56,12 +57,13 @@
56
57
  },
57
58
  "peerDependencies": {
58
59
  "@shivaedev/changes": "0.10.1",
59
- "@shivaedev/contract": "0.36.1",
60
- "@shivaedev/discord": "0.2.1",
61
- "@shivaedev/email": "0.4.2",
62
- "@shivaedev/identity": "0.26.0",
63
- "@shivaedev/jobs": "0.36.0",
64
- "@shivaedev/sql": "0.39.0",
60
+ "@shivaedev/contract": "0.37.0",
61
+ "@shivaedev/discord": "0.2.2",
62
+ "@shivaedev/email": "0.4.4",
63
+ "@shivaedev/identity": "0.26.2",
64
+ "@shivaedev/jobs": "0.37.1",
65
+ "@shivaedev/sql": "0.41.0",
66
+ "@shivaedev/webhooks": "0.9.0",
65
67
  "better-auth": "1.7.14",
66
68
  "effect": "4.0.7",
67
69
  "pg-boss": "12.38.0"
@@ -76,7 +78,7 @@
76
78
  "scripts": {
77
79
  "build": "node --eval \"import('node:fs').then(({ rmSync }) => rmSync('dist', { force: true, recursive: true }))\" && tsc --project tsconfig.build.json",
78
80
  "ready": "pnpm typecheck && pnpm test && pnpm build",
79
- "test": "vitest run",
81
+ "test": "vitest run --configLoader native",
80
82
  "typecheck": "tsc --noEmit"
81
83
  }
82
84
  }
@@ -0,0 +1,39 @@
1
+ import { Effect, Queue } from "effect";
2
+ import type * as AsyncResult from "effect/reactivity/AsyncResult";
3
+ import type * as Atom from "effect/reactivity/Atom";
4
+ import * as AtomRegistry from "effect/reactivity/AtomRegistry";
5
+ import { querySignals } from "@shivaedev/contract/querySignals.ts";
6
+
7
+ export interface SettledQueries<A, E> {
8
+ readonly latest: Effect.Effect<AsyncResult.AsyncResult<A, E>>;
9
+ readonly next: Effect.Effect<AsyncResult.AsyncResult<A, E>>;
10
+ }
11
+
12
+ export const settledQueries = Effect.fn("Contract.settledQueries")(function* <A, E>(query: Atom.Atom<AsyncResult.AsyncResult<A, E>>) {
13
+ const registry = yield* AtomRegistry.AtomRegistry;
14
+ const results = yield* Queue.unbounded<AsyncResult.AsyncResult<A, E>>();
15
+ let completed = 0;
16
+ yield* Effect.acquireRelease(
17
+ Effect.sync(() => registry.mount(query)),
18
+ (stop) => Effect.sync(stop),
19
+ );
20
+ yield* Effect.acquireRelease(
21
+ Effect.sync(() =>
22
+ registry.subscribe(
23
+ querySignals(query),
24
+ (state) => {
25
+ if (!state.pending && state.completed > completed) {
26
+ completed = state.completed;
27
+ Queue.offerUnsafe(results, registry.get(query));
28
+ }
29
+ },
30
+ { immediate: true },
31
+ ),
32
+ ),
33
+ (stop) => Effect.sync(stop),
34
+ );
35
+ return {
36
+ latest: Effect.sync(() => registry.get(query)),
37
+ next: Queue.take(results),
38
+ } satisfies SettledQueries<A, E>;
39
+ });
@@ -0,0 +1,34 @@
1
+ import { Clock, Effect } from "effect";
2
+ import type { FakeHttpRequest } from "@shivaedev/test-story/server/fakeHttpService.ts";
3
+ import type { GitHubAppAccess } from "#github/fake.ts";
4
+ import type { AppJwt, githubAppCredentials } from "./credentials.ts";
5
+
6
+ export const appProvider = Effect.fnUntraced(function* (credentials: ReturnType<typeof githubAppCredentials>, prefix: string) {
7
+ const clock = yield* Clock.Clock;
8
+ const state: { exchanges: number; jwts: (AppJwt | undefined)[] } = { exchanges: 0, jwts: [] };
9
+ const tokens = new Map<string, number>();
10
+ const access: GitHubAppAccess = {
11
+ appRequest: (request) => {
12
+ const jwt = credentials.appJwtOf(request.headers.authorization, clock.currentTimeMillisUnsafe());
13
+ state.jwts.push(jwt);
14
+ return credentials.signedByApp(jwt);
15
+ },
16
+ installationOf: (request) => tokens.get(request.headers.authorization ?? ""),
17
+ installationToken: (request) => tokens.has(request.headers.authorization ?? ""),
18
+ };
19
+ return {
20
+ access,
21
+ state,
22
+ token: {
23
+ guard: access.appRequest,
24
+ method: "POST",
25
+ path: `${prefix}/app/installations/:installationId/access_tokens`,
26
+ reply: (request: FakeHttpRequest) => {
27
+ state.exchanges += 1;
28
+ const token = `${credentials.tokenPrefix}-${state.exchanges}`;
29
+ tokens.set(`Bearer ${token}`, Number(request.params.installationId));
30
+ return { body: { "expires_at": new Date(clock.currentTimeMillisUnsafe() + 3_600_000).toISOString(), token } };
31
+ },
32
+ },
33
+ };
34
+ });
@@ -0,0 +1,62 @@
1
+ import { createHmac, generateKeyPairSync, type KeyObject, verify } from "node:crypto";
2
+ import { Option, Schema } from "effect";
3
+
4
+ export function githubAppCredentials() {
5
+ const keys = generateKeyPairSync("rsa", { modulusLength: 2048 });
6
+ const appId = "123456";
7
+ const webhookSecret = "webhook-secret";
8
+ return {
9
+ appId,
10
+ appJwtOf: (authorization: string | undefined, nowMillis: number) => appJwtOf(keys.publicKey, authorization, nowMillis),
11
+ privateKey: keys.privateKey.export({ format: "pem", type: "pkcs8" }).toString(),
12
+ signedByApp: (jwt: AppJwt | undefined) => signedByApp(appId, jwt),
13
+ tokenPrefix: "installation-token-secret",
14
+ webhookSecret,
15
+ webhookSignature: (body: Uint8Array) => `sha256=${createHmac("sha256", webhookSecret).update(body).digest("hex")}`,
16
+ };
17
+ }
18
+
19
+ const Claims = Schema.fromJsonString(Schema.Struct({ exp: Schema.Number, iat: Schema.Number, iss: Schema.String }));
20
+ const Header = Schema.fromJsonString(Schema.Struct({ alg: Schema.String, typ: Schema.String }));
21
+
22
+ export interface AppJwt {
23
+ readonly algorithm: string;
24
+ readonly expiresIn: number;
25
+ readonly issuedAgo: number;
26
+ readonly issuer: string;
27
+ readonly signedBy: "the App's key" | "another key";
28
+ readonly type: string;
29
+ }
30
+
31
+ export function appJwtOf(publicKey: KeyObject, authorization: string | undefined, nowMillis: number): AppJwt | undefined {
32
+ const [header = "", payload = "", signature = ""] = (authorization?.replace(/^Bearer /u, "") ?? "").split(".");
33
+ const claims = Schema.decodeUnknownOption(Claims)(Buffer.from(payload, "base64url").toString());
34
+ const fields = Schema.decodeUnknownOption(Header)(Buffer.from(header, "base64url").toString());
35
+ if (Option.isNone(claims) || Option.isNone(fields)) {
36
+ return undefined;
37
+ }
38
+ const now = nowMillis / 1000;
39
+ return {
40
+ algorithm: fields.value.alg,
41
+ expiresIn: claims.value.exp - now,
42
+ issuedAgo: now - claims.value.iat,
43
+ issuer: claims.value.iss,
44
+ signedBy: verify("RSA-SHA256", Buffer.from(`${header}.${payload}`), publicKey, Buffer.from(signature, "base64url"))
45
+ ? "the App's key"
46
+ : "another key",
47
+ type: fields.value.typ,
48
+ };
49
+ }
50
+
51
+ export function signedByApp(appId: string, jwt: AppJwt | undefined) {
52
+ return (
53
+ jwt !== undefined
54
+ && jwt.signedBy === "the App's key"
55
+ && jwt.algorithm === "RS256"
56
+ && jwt.issuer === appId
57
+ && jwt.issuedAgo >= 0
58
+ && jwt.issuedAgo <= 600
59
+ && jwt.expiresIn > 0
60
+ && jwt.expiresIn <= 600
61
+ );
62
+ }
@@ -0,0 +1,20 @@
1
+ import { Effect } from "effect";
2
+ import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
3
+
4
+ export function webhookDelivery(sign: (body: Uint8Array) => string) {
5
+ return Effect.fnUntraced(function* (url: string, delivery: { readonly body: Uint8Array; readonly event: string; readonly deliveryId: string }) {
6
+ const client = yield* HttpClient.HttpClient;
7
+ const response = yield* client.execute(
8
+ HttpClientRequest.post(url).pipe(
9
+ HttpClientRequest.setHeaders({
10
+ "x-github-delivery": delivery.deliveryId,
11
+ "x-github-event": delivery.event,
12
+ "x-hub-signature-256": sign(delivery.body),
13
+ }),
14
+ HttpClientRequest.bodyUint8Array(delivery.body, "application/json"),
15
+ ),
16
+ );
17
+ yield* response.text;
18
+ return response.status;
19
+ }, Effect.provide(FetchHttpClient.layer));
20
+ }
@@ -0,0 +1,30 @@
1
+ import { Effect } from "effect";
2
+ import { type FakeHttpRequest, type FakeHttpRoute, fakeHttpService } from "@shivaedev/test-story/server/fakeHttpService.ts";
3
+ import { appProvider } from "#github/adapters/appProvider.ts";
4
+ import { githubAppCredentials } from "#github/adapters/credentials.ts";
5
+ import { webhookDelivery } from "#github/adapters/webhookDelivery.ts";
6
+
7
+ export interface GitHubAppAccess {
8
+ readonly appRequest: (request: FakeHttpRequest) => boolean;
9
+ readonly installationOf: (request: FakeHttpRequest) => number | undefined;
10
+ readonly installationToken: (request: FakeHttpRequest) => boolean;
11
+ }
12
+
13
+ export const fakeGitHubApp = Effect.fnUntraced(function* (
14
+ options: {
15
+ readonly credentials?: ReturnType<typeof githubAppCredentials>;
16
+ readonly prefix?: string;
17
+ readonly routes?: (access: GitHubAppAccess) => Readonly<Record<string, FakeHttpRoute>>;
18
+ } = {},
19
+ ) {
20
+ const credentials = options.credentials ?? githubAppCredentials();
21
+ const prefix = options.prefix ?? "";
22
+ const { access, state, token } = yield* appProvider(credentials, prefix);
23
+ const server = yield* fakeHttpService({
24
+ routes: {
25
+ token,
26
+ ...options.routes?.(access),
27
+ },
28
+ });
29
+ return { credentials, deliverWebhook: webhookDelivery(credentials.webhookSignature), server, state };
30
+ });
@@ -0,0 +1,6 @@
1
+ import { Data } from "effect";
2
+
3
+ export class HostProcessError extends Data.TaggedError("HostProcessError")<{
4
+ readonly operation: "launch" | "signal" | "request" | "readout";
5
+ readonly cause: unknown;
6
+ }> {}
@@ -0,0 +1,122 @@
1
+ import { type ChildProcess, type ForkOptions, fork } from "node:child_process";
2
+ import process from "node:process";
3
+ import { fileURLToPath } from "node:url";
4
+ import { Option, type Redacted, Schema } from "effect";
5
+
6
+ export interface HostProcessOptions {
7
+ readonly args?: readonly string[];
8
+ readonly cwd?: string;
9
+ readonly databaseUrl?: Redacted.Redacted<string>;
10
+ readonly env?: NodeJS.ProcessEnv;
11
+ readonly execArgv?: readonly string[];
12
+ readonly module: string | URL;
13
+ }
14
+
15
+ export function forkHost(options: HostProcessOptions, databaseUrl?: string) {
16
+ const settings: ForkOptions = {
17
+ cwd: options.cwd,
18
+ env: databaseUrl === undefined ? options.env : { ...options.env, "DATABASE_URL": databaseUrl },
19
+ execArgv: [...(options.execArgv ?? [])],
20
+ stdio: ["ignore", "ignore", "inherit", "ipc"],
21
+ };
22
+ return fork(typeof options.module === "string" ? options.module : fileURLToPath(options.module), [...(options.args ?? [])], settings);
23
+ }
24
+
25
+ export function receiveHostMessage<A>(child: ChildProcess, schema: Schema.Codec<A>, signal: AbortSignal, action?: () => void) {
26
+ return new Promise<A>((resolve, reject) => {
27
+ function cleanup() {
28
+ child.off("message", message);
29
+ child.off("exit", exited);
30
+ child.off("error", failed);
31
+ signal.removeEventListener("abort", aborted);
32
+ }
33
+ function failed(cause: unknown) {
34
+ cleanup();
35
+ reject(cause);
36
+ }
37
+ function exited(code: number | null, delivered: NodeJS.Signals | null) {
38
+ failed(new Error(`Host exited (${delivered ?? code}) before IPC acknowledgement`));
39
+ }
40
+ function aborted() {
41
+ failed(signal.reason);
42
+ }
43
+ function message(value: unknown) {
44
+ const decoded = Schema.decodeUnknownOption(schema)(value);
45
+ if (Option.isSome(decoded)) {
46
+ cleanup();
47
+ resolve(decoded.value);
48
+ }
49
+ }
50
+ child.on("message", message);
51
+ child.once("exit", exited);
52
+ child.once("error", failed);
53
+ signal.addEventListener("abort", aborted, { once: true });
54
+ if (signal.aborted) {
55
+ aborted();
56
+ } else if (child.exitCode !== null || child.signalCode !== null) {
57
+ exited(child.exitCode, child.signalCode);
58
+ } else {
59
+ try {
60
+ action?.();
61
+ } catch (cause) {
62
+ failed(cause);
63
+ }
64
+ }
65
+ });
66
+ }
67
+
68
+ export function stopHost(child: ChildProcess) {
69
+ if (child.pid === undefined || child.exitCode !== null || child.signalCode !== null) {
70
+ return Promise.resolve();
71
+ }
72
+ return new Promise<void>((resolve) => {
73
+ child.once("exit", () => resolve());
74
+ child.kill("SIGKILL");
75
+ });
76
+ }
77
+
78
+ export function sendHostMessage(message: unknown) {
79
+ return new Promise<void>((resolve, reject) => {
80
+ if (process.send === undefined) {
81
+ reject(new Error("Host process needs a parent IPC channel"));
82
+ return;
83
+ }
84
+ process.send(message, (error) => (error === null ? resolve() : reject(error)));
85
+ });
86
+ }
87
+
88
+ export function sendHostReady(url: string) {
89
+ return sendHostMessage({ pid: process.pid, type: "host-ready", url });
90
+ }
91
+
92
+ export function waitForHostStart(signal: AbortSignal) {
93
+ return new Promise<void>((resolve, reject) => {
94
+ function cleanup() {
95
+ process.off("SIGUSR2", start);
96
+ signal.removeEventListener("abort", aborted);
97
+ }
98
+ function failed(cause: unknown) {
99
+ cleanup();
100
+ reject(cause);
101
+ }
102
+ function start() {
103
+ cleanup();
104
+ resolve();
105
+ }
106
+ function aborted() {
107
+ failed(signal.reason);
108
+ }
109
+ process.once("SIGUSR2", start);
110
+ signal.addEventListener("abort", aborted, { once: true });
111
+ if (signal.aborted) {
112
+ aborted();
113
+ } else {
114
+ void sendHostMessage({ type: "host-prepared" }).catch(failed);
115
+ }
116
+ });
117
+ }
118
+
119
+ export async function hostResponse(url: string, path: string, signal: AbortSignal) {
120
+ const response = await fetch(new URL(path, url), { redirect: "manual", signal });
121
+ return { body: await response.text(), headers: Object.fromEntries(response.headers), status: response.status };
122
+ }
@@ -0,0 +1,29 @@
1
+ import type { ChildProcess } from "node:child_process";
2
+ import process from "node:process";
3
+ import { Option, Predicate, Schema } from "effect";
4
+ import { HostReadouts } from "#host/processProtocol.ts";
5
+ import { receiveHostMessage } from "./process.ts";
6
+
7
+ export function listenHostReadouts(read: () => typeof HostReadouts.Type) {
8
+ function requested(message: unknown) {
9
+ if (Predicate.hasProperty(message, "type") && message.type === "host-readouts") {
10
+ process.send?.(read());
11
+ }
12
+ }
13
+ process.on("message", requested);
14
+ return () => process.off("message", requested);
15
+ }
16
+
17
+ export function collectHostReadouts(child: ChildProcess) {
18
+ let completed: typeof HostReadouts.Type | undefined;
19
+ child.on("message", (message: unknown) => {
20
+ const decoded = Schema.decodeUnknownOption(HostReadouts)(message);
21
+ if (Option.isSome(decoded) && decoded.value.shutdownDuration !== null) {
22
+ completed = decoded.value;
23
+ }
24
+ });
25
+ return (signal: AbortSignal) =>
26
+ completed === undefined
27
+ ? receiveHostMessage(child, HostReadouts, signal, () => child.send({ type: "host-readouts" }))
28
+ : Promise.resolve(completed);
29
+ }
@@ -0,0 +1,69 @@
1
+ import { Effect, Redacted, Schema } from "effect";
2
+ import { forkHost, type HostProcessOptions, hostResponse, receiveHostMessage, stopHost } from "#host/adapters/process.ts";
3
+ import { collectHostReadouts } from "#host/adapters/processReadouts.ts";
4
+ import { HostProcessError } from "./ProcessError.ts";
5
+ import { HostPrepared, HostReady, HostSignal } from "./processProtocol.ts";
6
+
7
+ export const hostProcess = Effect.fn("HostProcess.hostProcess")(function* <E = never, R = never>(
8
+ options: HostProcessOptions & { readonly beforeStart?: Effect.Effect<void, E, R> },
9
+ ) {
10
+ const databaseUrl = options.databaseUrl;
11
+ const database =
12
+ databaseUrl === undefined
13
+ ? undefined
14
+ : yield* Effect.promise(() => import("@shivaedev/test-sql/server/disconnectProxy.ts")).pipe(
15
+ Effect.flatMap(({ disconnectProxy }) => disconnectProxy(Redacted.value(databaseUrl))),
16
+ );
17
+ const child = yield* Effect.acquireRelease(
18
+ Effect.try({ catch: (cause) => new HostProcessError({ cause, operation: "launch" }), try: () => forkHost(options, database?.url) }),
19
+ (acquired) => Effect.promise(() => stopHost(acquired)),
20
+ );
21
+ const read = collectHostReadouts(child);
22
+ if (options.beforeStart !== undefined) {
23
+ yield* Effect.tryPromise({
24
+ catch: (cause) => new HostProcessError({ cause, operation: "launch" }),
25
+ try: (signal) => receiveHostMessage(child, HostPrepared, signal),
26
+ });
27
+ yield* options.beforeStart;
28
+ }
29
+ const { pid, url } = yield* Effect.tryPromise({
30
+ catch: (cause) => new HostProcessError({ cause, operation: "launch" }),
31
+ try: (signal) => receiveHostMessage(child, HostReady, signal, options.beforeStart === undefined ? undefined : () => child.kill("SIGUSR2")),
32
+ });
33
+ function response(path: string) {
34
+ return Effect.tryPromise({
35
+ catch: (cause) => new HostProcessError({ cause, operation: "request" }),
36
+ try: (signal) => hostResponse(url, path, signal),
37
+ });
38
+ }
39
+ function readouts() {
40
+ return Effect.tryPromise({
41
+ catch: (cause) => new HostProcessError({ cause, operation: "readout" }),
42
+ try: read,
43
+ });
44
+ }
45
+ return {
46
+ activeWork: () => readouts().pipe(Effect.map((state) => state.activeWork)),
47
+ disconnectIdlePostgres: () =>
48
+ Effect.suspend(() =>
49
+ database === undefined
50
+ ? Effect.die(new Error("Launch the host with databaseUrl before disconnecting PostgreSQL"))
51
+ : Effect.sync(database.disconnect),
52
+ ),
53
+ finalizers: () => readouts().pipe(Effect.map((state) => state.finalizers)),
54
+ headers: (path: string) => response(path).pipe(Effect.map((answer) => answer.headers)),
55
+ health: () => response("/health"),
56
+ pid,
57
+ shutdownDuration: () => readouts().pipe(Effect.map((state) => state.shutdownDuration)),
58
+ signal: (delivered: NodeJS.Signals) =>
59
+ Effect.tryPromise({
60
+ catch: (cause) => new HostProcessError({ cause, operation: "signal" }),
61
+ try: (signal) =>
62
+ receiveHostMessage(child, HostSignal.pipe(Schema.check(Schema.makeFilter((ack) => ack.signal === delivered))), signal, () => {
63
+ child.kill(delivered);
64
+ }),
65
+ }).pipe(Effect.asVoid),
66
+ stop: () => Effect.promise(() => stopHost(child)),
67
+ url,
68
+ };
69
+ });
@@ -0,0 +1,25 @@
1
+ import { Effect } from "effect";
2
+ import { HttpServer } from "effect/http";
3
+ import { sendHostMessage, sendHostReady, waitForHostStart } from "#host/adapters/process.ts";
4
+ import { HostProcessError } from "#host/ProcessError.ts";
5
+
6
+ export const awaitHostStart = Effect.tryPromise({
7
+ catch: (cause) => new HostProcessError({ cause, operation: "launch" }),
8
+ try: waitForHostStart,
9
+ });
10
+
11
+ export const reportHostReady = HttpServer.HttpServer.pipe(
12
+ Effect.flatMap((server) =>
13
+ Effect.tryPromise({
14
+ catch: (cause) => new HostProcessError({ cause, operation: "launch" }),
15
+ try: () => sendHostReady(HttpServer.formatAddress(server.address)),
16
+ }),
17
+ ),
18
+ );
19
+
20
+ export function acknowledgeHostSignal(signal: NodeJS.Signals) {
21
+ return Effect.tryPromise({
22
+ catch: (cause) => new HostProcessError({ cause, operation: "signal" }),
23
+ try: () => sendHostMessage({ signal, type: "host-signal" }),
24
+ });
25
+ }