apps 1.0.0-beta.3 → 2.0.0-next.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 (90) hide show
  1. package/README.md +10 -48
  2. package/check-publish.mjs +7 -0
  3. package/package.json +27 -56
  4. package/src/Access.ts +37 -0
  5. package/src/Accounts.ts +468 -0
  6. package/src/App.ts +11 -0
  7. package/src/Ask.ts +156 -0
  8. package/src/Changes.ts +13 -0
  9. package/src/Http.ts +30 -0
  10. package/src/Provider.ts +146 -0
  11. package/src/Session.ts +52 -0
  12. package/src/Settings.ts +164 -0
  13. package/src/contract.ts +852 -0
  14. package/src/css-modules.d.ts +2 -0
  15. package/src/desktop/Desktop.ts +192 -0
  16. package/src/desktop/bridge.ts +62 -0
  17. package/src/desktop/errors.ts +88 -0
  18. package/src/desktop/index.ts +15 -0
  19. package/src/entry.ts +48 -0
  20. package/src/index.ts +16 -4
  21. package/src/internal/defects.ts +62 -0
  22. package/src/internal/files.ts +369 -0
  23. package/src/internal/host.ts +17 -0
  24. package/src/internal/query.ts +114 -0
  25. package/src/internal/records.ts +838 -0
  26. package/src/internal/retention.ts +87 -0
  27. package/src/internal/retries.ts +185 -0
  28. package/src/internal/telemetry.ts +167 -0
  29. package/src/migrations.ts +110 -0
  30. package/src/page/Accounts.ts +27 -0
  31. package/src/page/Changes.ts +126 -0
  32. package/src/page/Session.ts +46 -0
  33. package/src/page/client.ts +107 -0
  34. package/src/page/errors.ts +15 -0
  35. package/src/page/http.ts +21 -0
  36. package/src/page/index.ts +18 -0
  37. package/src/page/paths.ts +22 -0
  38. package/src/providers/anthropic.ts +26 -0
  39. package/src/providers/github.ts +49 -0
  40. package/src/providers/google.ts +67 -0
  41. package/src/providers/openai.ts +62 -0
  42. package/src/providers/slack.ts +81 -0
  43. package/src/runtime.ts +1540 -0
  44. package/src/testing.ts +660 -0
  45. package/src/text-modules.d.ts +5 -0
  46. package/src/theme.css +50 -0
  47. package/dist/authoring/index.d.ts +0 -393
  48. package/dist/authoring/index.js +0 -36
  49. package/dist/chunk-4OZFMCTT.js +0 -17
  50. package/dist/chunk-A3H32P2J.js +0 -143
  51. package/dist/chunk-B7NEUIJL.js +0 -14
  52. package/dist/chunk-F7GZYEAC.js +0 -41
  53. package/dist/chunk-MUFMJRXR.js +0 -308
  54. package/dist/chunk-S5KFP4JQ.js +0 -20
  55. package/dist/chunk-Y6LLTN7W.js +0 -99
  56. package/dist/chunk-YUZ4TXOY.js +0 -27
  57. package/dist/http/index.d.ts +0 -9
  58. package/dist/http/index.js +0 -6
  59. package/dist/index.d.ts +0 -4
  60. package/dist/index.js +0 -48
  61. package/dist/manifest/contract.d.ts +0 -63
  62. package/dist/manifest/contract.js +0 -8
  63. package/dist/manifest/index.d.ts +0 -20
  64. package/dist/manifest/index.js +0 -16
  65. package/dist/mcp/client.d.ts +0 -9
  66. package/dist/mcp/index.d.ts +0 -11
  67. package/dist/mcp/index.js +0 -7
  68. package/dist/openapi/index.d.ts +0 -14
  69. package/dist/openapi/index.js +0 -7
  70. package/dist/openapi/mapper.d.ts +0 -7
  71. package/dist/runner/index.d.ts +0 -4
  72. package/dist/runner/index.js +0 -66
  73. package/dist/runner/protocol.d.ts +0 -33
  74. package/dist/runner/protocol.js +0 -8
  75. package/dist/runtime/index.d.ts +0 -83
  76. package/dist/runtime/index.js +0 -12
  77. package/dist/workerd/index.d.ts +0 -7
  78. package/dist/workerd/index.js +0 -10
  79. package/src/authoring/index.ts +0 -658
  80. package/src/http/index.ts +0 -26
  81. package/src/manifest/contract.ts +0 -64
  82. package/src/manifest/index.ts +0 -156
  83. package/src/mcp/client.ts +0 -59
  84. package/src/mcp/index.ts +0 -42
  85. package/src/openapi/index.ts +0 -70
  86. package/src/openapi/mapper.ts +0 -25
  87. package/src/runner/index.ts +0 -80
  88. package/src/runner/protocol.ts +0 -54
  89. package/src/runtime/index.ts +0 -550
  90. package/src/workerd/index.ts +0 -17
package/src/App.ts ADDED
@@ -0,0 +1,11 @@
1
+ /** The app's own identity on Executor. */
2
+ import { Effect } from "effect";
3
+ import { Host } from "./internal/host.ts";
4
+
5
+ /** The app's public address, e.g. `https://my-app.example.com`, with no trailing slash. */
6
+ export const url: Effect.Effect<string> = Effect.map(Effect.service(Host), (host) =>
7
+ host.appUrl.replace(/\/+$/u, ""),
8
+ );
9
+
10
+ /** The installed app's id. */
11
+ export const id: Effect.Effect<string> = Effect.map(Effect.service(Host), (host) => host.appId);
package/src/Ask.ts ADDED
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Asking the person a question from a `Toolkit` tool handler, on the
3
+ * request-scoped MCP server. Adapted from the independent design's
4
+ * `spikes/mcp/ask.ts`; built only on Effect's public MCP types.
5
+ *
6
+ * MCP 2026-07-28 asks by result: the server answers "input required" and the
7
+ * client calls again with the answers. Effect's `McpServer` carries that for
8
+ * tools registered by hand, but a `Toolkit` handler cannot return it. So:
9
+ *
10
+ * - `Ask.ask` looks for the answer in the request. With none, it records the
11
+ * question and stops the handler.
12
+ * - `Ask.layer`, a global MCP middleware, turns a stopped handler with recorded
13
+ * questions into `InputRequired`. Earlier answers ride in `requestState`,
14
+ * signed with a key kept in the app's own database, so a tool can ask several
15
+ * questions in turn and a question survives the app being stopped.
16
+ *
17
+ * The handler runs again from the top each round, so what it does before
18
+ * `ask` must be safe to repeat.
19
+ *
20
+ * ```ts
21
+ * clear_notes: () => Effect.gen(function*() {
22
+ * const { confirm } = yield* Ask.ask({ message: "Delete all your notes?", schema: Schema.Struct({ confirm: Schema.Boolean }) })
23
+ * if (!confirm) return "Kept your notes"
24
+ * ...
25
+ * })
26
+ *
27
+ * McpServer.toolkit(Tools).pipe(Layer.provide(Ask.layer), ...)
28
+ * ```
29
+ */
30
+ import { Context, Effect, Result, Schema } from "effect";
31
+ import { McpSchema, McpServer } from "effect/ai";
32
+ import { Base64Url } from "effect/encoding";
33
+ import { KeyValueStore } from "effect/persistence";
34
+
35
+ type Answers = Record<string, Record<string, unknown>>;
36
+
37
+ interface Round {
38
+ /** Answers from earlier rounds and this one. */
39
+ readonly answers: Answers;
40
+ /** Questions asked in this round that had no answer. */
41
+ readonly asked: Record<string, McpSchema.McpInputRequest>;
42
+ count: number;
43
+ }
44
+
45
+ const CurrentRound = Context.Reference<Round | undefined>("apps/Ask/CurrentRound", {
46
+ defaultValue: () => undefined,
47
+ });
48
+
49
+ const KEY_NAME = "apps/ask/state-key";
50
+
51
+ const hmac = (key: string, text: string) =>
52
+ Effect.promise(async () => {
53
+ const encoder = new TextEncoder();
54
+ const cryptoKey = await crypto.subtle.importKey(
55
+ "raw",
56
+ encoder.encode(key),
57
+ { name: "HMAC", hash: "SHA-256" },
58
+ false,
59
+ ["sign"],
60
+ );
61
+ return Base64Url.encode(
62
+ new Uint8Array(await crypto.subtle.sign("HMAC", cryptoKey, encoder.encode(text))),
63
+ );
64
+ });
65
+
66
+ /**
67
+ * Asks the person a question. The same arguments as `McpServer.elicit`.
68
+ * Fails with `ElicitationDeclined` when they decline; a cancel stops the call.
69
+ */
70
+ export const ask = <S extends Schema.ConstraintEncoder<Record<string, unknown>, unknown>>(options: {
71
+ readonly message: string;
72
+ readonly schema: S;
73
+ }): Effect.Effect<S["Type"], McpSchema.ElicitationDeclined, S["DecodingServices"]> =>
74
+ Effect.gen(function* () {
75
+ const round = yield* CurrentRound;
76
+ if (round === undefined)
77
+ return yield* Effect.die(new Error("Ask.ask: Ask.layer is not installed on this MCP server"));
78
+ const key = `q${round.count++}`;
79
+ const requestedSchema = Schema.toJsonSchemaDocument(options.schema).schema;
80
+ const request = { mode: "form", message: options.message, requestedSchema } as const;
81
+ const answer = round.answers[key];
82
+ if (answer === undefined) {
83
+ round.asked[key] = { method: "elicitation/create", params: request };
84
+ return yield* Effect.interrupt;
85
+ }
86
+ switch (answer["action"]) {
87
+ case "accept":
88
+ return yield* Effect.orDie(Schema.decodeUnknownEffect(options.schema)(answer["content"]));
89
+ case "cancel":
90
+ return yield* Effect.interrupt;
91
+ default:
92
+ return yield* new McpSchema.ElicitationDeclined({ request: request as never });
93
+ }
94
+ });
95
+
96
+ /** The global MCP middleware that makes `ask` work. Needs `KeyValueStore` (the app's database). */
97
+ export const layer = McpServer.middleware(
98
+ Effect.gen(function* () {
99
+ const store = yield* KeyValueStore.KeyValueStore;
100
+ const existing = yield* Effect.orDie(store.get(KEY_NAME));
101
+ const key = existing ?? Base64Url.encode(crypto.getRandomValues(new Uint8Array(32)));
102
+ if (existing === undefined) yield* Effect.orDie(store.set(KEY_NAME, key));
103
+
104
+ const seal = (scope: string, answers: Answers) => {
105
+ const body = Base64Url.encode(JSON.stringify({ scope, answers }));
106
+ return Effect.map(hmac(key, body), (signature) => `${body}.${signature}`);
107
+ };
108
+ const unseal = Effect.fnUntraced(function* (scope: string, state: string | undefined) {
109
+ if (state === undefined) return {} as Answers;
110
+ const [body, signature] = state.split(".");
111
+ if (body === undefined || signature !== (yield* hmac(key, body))) {
112
+ return yield* new McpSchema.InvalidParams({ message: "requestState failed verification" });
113
+ }
114
+ const decoded = Base64Url.decodeString(body);
115
+ if (Result.isFailure(decoded))
116
+ return yield* new McpSchema.InvalidParams({ message: "requestState is malformed" });
117
+ const parsed = JSON.parse(decoded.success) as { scope: string; answers: Answers };
118
+ if (parsed.scope !== scope) {
119
+ return yield* new McpSchema.InvalidParams({
120
+ message: "requestState belongs to another request",
121
+ });
122
+ }
123
+ return parsed.answers;
124
+ });
125
+
126
+ return (effect, { method, payload, requestContext, target }) => {
127
+ if (method !== "tools/call") return effect;
128
+ const scope = `${target}:${JSON.stringify((payload as { arguments?: unknown }).arguments ?? {})}`;
129
+ return Effect.gen(function* () {
130
+ const earlier = yield* unseal(scope, requestContext.requestState);
131
+ const round: Round = {
132
+ answers: { ...earlier, ...(requestContext.inputResponses as Answers | undefined) },
133
+ asked: {},
134
+ count: 0,
135
+ };
136
+ return yield* effect.pipe(
137
+ Effect.provideService(CurrentRound, round),
138
+ Effect.catchCause((cause) =>
139
+ Object.keys(round.asked).length === 0
140
+ ? Effect.failCause(cause)
141
+ : Effect.map(
142
+ seal(scope, round.answers),
143
+ // external: McpServer.middleware's result type is opaque; McpServer passes an InputRequired result through to the protocol.
144
+ (requestState) =>
145
+ new McpSchema.InputRequired({
146
+ inputRequests: round.asked,
147
+ requestState,
148
+ }) as never,
149
+ ),
150
+ ),
151
+ );
152
+ });
153
+ };
154
+ }),
155
+ { global: true },
156
+ );
package/src/Changes.ts ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Refresh on data change. A write to the app's own tables tells open pages by
3
+ * itself; `notify` is for a change the database cannot see, such as mail
4
+ * archived in Gmail, which the app learned about some other way.
5
+ */
6
+ import { Effect } from "effect";
7
+ import { Host } from "./internal/host.ts";
8
+
9
+ /** Tell the app's open pages that its data changed, so they fetch again. Does nothing outside Executor. */
10
+ export const notify: Effect.Effect<void> = Effect.gen(function* () {
11
+ const pages = (yield* Host).capabilities?.pages;
12
+ if (pages !== undefined) yield* Effect.promise(() => pages.changed());
13
+ });
package/src/Http.ts ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The app's limits on its HTTP side, as Executor applies them. The name `Http` is provisional.
3
+ *
4
+ * ```ts
5
+ * export const http = Http.declare({ firstResponse: "5 minutes" })
6
+ * ```
7
+ *
8
+ * `firstResponse`: how long a response may take to begin (its status and headers), per request.
9
+ * Executor cuts a request whose response has not begun by then. Undeclared, the host's default
10
+ * (60 seconds); a host also has a ceiling, and a longer value is held to it. Once a response
11
+ * has begun, its body streams with no such limit.
12
+ */
13
+ import { Duration } from "effect";
14
+
15
+ export interface HttpDeclaration {
16
+ readonly firstResponse?: Duration.Input;
17
+ }
18
+
19
+ /** What this bundle declared, for `describe()`. */
20
+ export const declarations: { firstResponseMs: number | null } = { firstResponseMs: null };
21
+
22
+ export const declare = (spec: HttpDeclaration): HttpDeclaration => {
23
+ if (spec.firstResponse !== undefined) {
24
+ const ms = Duration.toMillis(Duration.fromInputUnsafe(spec.firstResponse));
25
+ if (!Number.isFinite(ms) || ms <= 0)
26
+ throw new Error("Http.declare: firstResponse must be a positive, finite length of time");
27
+ declarations.firstResponseMs = ms;
28
+ }
29
+ return spec;
30
+ };
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Linkable services, as data. A provider says how a person signs in (OAuth or
3
+ * an API key), where its token is meant for, and how Executor reads who an
4
+ * account is. Executor does the signing in, keeps the grant and renews it; the
5
+ * app only ever asks for a token.
6
+ *
7
+ * ```ts
8
+ * export const GitHub = Provider.oauth2({
9
+ * name: "GitHub",
10
+ * authorizationUrl: "https://github.com/login/oauth/authorize",
11
+ * tokenUrl: "https://github.com/login/oauth/access_token",
12
+ * scopes: ["repo"],
13
+ * hosts: ["api.github.com"],
14
+ * profile: { url: "https://api.github.com/user", map: { externalId: "id", username: "login" } }
15
+ * })
16
+ *
17
+ * export const Linear = Provider.apiKey({ name: "Linear", label: "API key", hosts: ["api.linear.app"] })
18
+ * ```
19
+ */
20
+ import type {
21
+ OAuth2Method,
22
+ ProviderAuthMethod,
23
+ ProviderDescription,
24
+ ProviderProfile,
25
+ SecretsMethod,
26
+ } from "./contract.ts";
27
+
28
+ export interface Provider {
29
+ readonly description: ProviderDescription;
30
+ }
31
+
32
+ /** A provider with any number of sign-in methods, by name. `oauth2` and `apiKey` cover one method each. */
33
+ export const make = (options: {
34
+ readonly name: string;
35
+ readonly auth: Readonly<Record<string, ProviderAuthMethod>>;
36
+ readonly hosts?: ReadonlyArray<string>;
37
+ readonly profile?: ProviderProfile;
38
+ }): Provider => ({
39
+ description: {
40
+ name: options.name,
41
+ auth: options.auth,
42
+ ...(options.hosts === undefined ? {} : { hosts: [...new Set(options.hosts)].sort() }),
43
+ ...(options.profile === undefined ? {} : { profile: options.profile }),
44
+ },
45
+ });
46
+
47
+ /** The token response fields an app reads by default: the access token. */
48
+ const accessTokenResponse = {
49
+ type: "object",
50
+ properties: { access_token: { type: "string" } },
51
+ required: ["access_token"],
52
+ } as const;
53
+
54
+ export interface OAuth2Options {
55
+ readonly name: string;
56
+ /** An issuer whose endpoints Executor discovers (RFC 8414), registering its own client where the service allows. */
57
+ readonly discover?: string;
58
+ readonly authorizationUrl?: string;
59
+ readonly tokenUrl?: string;
60
+ readonly revocationUrl?: string;
61
+ readonly scopes?: ReadonlyArray<string>;
62
+ /** Service-defined parameters for the authorization request, e.g. Google's `{ access_type: "offline" }`. */
63
+ readonly authorizationParams?: Readonly<Record<string, string>>;
64
+ /** `false` for a service that refuses PKCE. */
65
+ readonly pkce?: false;
66
+ readonly hosts?: ReadonlyArray<string>;
67
+ readonly profile?: ProviderProfile;
68
+ /** The sign-in method's name. Default `oauth`. */
69
+ readonly method?: string;
70
+ }
71
+
72
+ /** A provider people link by signing in with OAuth 2. */
73
+ export const oauth2 = (options: OAuth2Options): Provider => {
74
+ const { name, hosts, profile, method, ...config } = options;
75
+ const auth: OAuth2Method = {
76
+ type: "oauth2",
77
+ ...Object.fromEntries(Object.entries(config).filter(([, value]) => value !== undefined)),
78
+ response: accessTokenResponse,
79
+ };
80
+ return make({
81
+ name,
82
+ auth: { [method ?? "oauth"]: auth },
83
+ ...(hosts === undefined ? {} : { hosts }),
84
+ ...(profile === undefined ? {} : { profile }),
85
+ });
86
+ };
87
+
88
+ export interface ApiKeyField {
89
+ /** Shown to people: "API key". */
90
+ readonly label: string;
91
+ readonly description?: string;
92
+ /** Not secret: forms show it. Default `false`. */
93
+ readonly plain?: boolean;
94
+ /** May be left empty. Default `false`. */
95
+ readonly optional?: boolean;
96
+ }
97
+
98
+ export interface ApiKeyOptions {
99
+ readonly name: string;
100
+ /** Shown to people: "API key". */
101
+ readonly label: string;
102
+ /** Markdown shown above the fields: where to create the key. */
103
+ readonly guide?: string;
104
+ /** The values a person enters. Default: one secret field, `api_key`. */
105
+ readonly fields?: Readonly<Record<string, ApiKeyField>>;
106
+ readonly hosts?: ReadonlyArray<string>;
107
+ readonly profile?: ProviderProfile;
108
+ /** The sign-in method's name. Default `key`. */
109
+ readonly method?: string;
110
+ }
111
+
112
+ /** A provider people link by pasting an API key (or several values). */
113
+ export const apiKey = (options: ApiKeyOptions): Provider => {
114
+ const fields = options.fields ?? { api_key: { label: options.label } };
115
+ const names = Object.keys(fields).sort();
116
+ const plain = names.filter((field) => fields[field]?.plain === true);
117
+ const auth: SecretsMethod = {
118
+ type: "secrets",
119
+ label: options.label,
120
+ ...(options.guide === undefined ? {} : { guide: options.guide }),
121
+ fields: {
122
+ type: "object",
123
+ properties: Object.fromEntries(
124
+ names.map((field) => {
125
+ const spec = fields[field]!;
126
+ return [
127
+ field,
128
+ {
129
+ type: "string",
130
+ title: spec.label,
131
+ ...(spec.description === undefined ? {} : { description: spec.description }),
132
+ },
133
+ ];
134
+ }),
135
+ ),
136
+ required: names.filter((field) => fields[field]?.optional !== true),
137
+ },
138
+ ...(plain.length === 0 ? {} : { plain }),
139
+ };
140
+ return make({
141
+ name: options.name,
142
+ auth: { [options.method ?? "key"]: auth },
143
+ ...(options.hosts === undefined ? {} : { hosts: options.hosts }),
144
+ ...(options.profile === undefined ? {} : { profile: options.profile }),
145
+ });
146
+ };
package/src/Session.ts ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Who is calling. The caller arrives with each request, in a header that
3
+ * Executor sets and strips from outside requests, so `current` works in a
4
+ * route, a tool call and anything else handling a request. Background work
5
+ * (a scheduled job, a workflow) has no caller: there `current` fails with
6
+ * `NoSession`.
7
+ */
8
+ import { Effect, Option, Schema } from "effect";
9
+ import { HttpServerRequest } from "effect/http";
10
+ import { IDENTITY_HEADER } from "./contract.ts";
11
+
12
+ export const User = Schema.Struct({
13
+ id: Schema.String,
14
+ name: Schema.optionalKey(Schema.String),
15
+ email: Schema.optionalKey(Schema.String),
16
+ });
17
+ export type User = typeof User.Type;
18
+
19
+ export const Organization = Schema.Struct({ id: Schema.String });
20
+ export type Organization = typeof Organization.Type;
21
+
22
+ /** The signed-in caller of the current request. */
23
+ export class Session extends Schema.Class<Session>("apps/Session")({
24
+ user: User,
25
+ organization: Organization,
26
+ /** The caller's role in the organization, where the host knows one. */
27
+ role: Schema.optionalKey(Schema.Literals(["owner", "admin", "member"])),
28
+ }) {}
29
+
30
+ /** Nobody is signed in: there is no request, or the request has no caller. */
31
+ export class NoSession extends Schema.TaggedError<NoSession>()("NoSession", {
32
+ message: Schema.String,
33
+ }) {}
34
+
35
+ const decodeIdentity = Schema.decodeUnknownOption(Schema.fromJsonString(Session));
36
+
37
+ /** The caller of the current request, from the request's identity header. */
38
+ export const current: Effect.Effect<Session, NoSession> = Effect.gen(function* () {
39
+ const request = yield* Effect.serviceOption(HttpServerRequest.HttpServerRequest);
40
+ if (Option.isNone(request)) {
41
+ return yield* new NoSession({ message: "No request: background work has no caller" });
42
+ }
43
+ const header = request.value.headers[IDENTITY_HEADER];
44
+ if (header === undefined) {
45
+ return yield* new NoSession({ message: "Nobody is signed in" });
46
+ }
47
+ const session = decodeIdentity(header);
48
+ if (Option.isNone(session)) {
49
+ return yield* new NoSession({ message: "The request's identity could not be read" });
50
+ }
51
+ return session.value;
52
+ });
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Settings and secrets. Declared here so Executor can ask a person for them on
3
+ * the app's page; read with Effect's own `Config`, as environment variables
4
+ * would be on a computer.
5
+ *
6
+ * ```ts
7
+ * export const settings = Settings.declare({
8
+ * GITHUB_HOOK_SECRET: Settings.generated(), // Executor makes it
9
+ * STRIPE_SIGNING_SECRET: Settings.secret("Stripe signing secret"), // a person pastes it on Executor's page
10
+ * TIME_ZONE: Settings.text("Time zone", { default: "UTC" }),
11
+ * })
12
+ *
13
+ * const zone = yield* Config.String("TIME_ZONE") // or: yield* settings.TIME_ZONE
14
+ * const secret = yield* settings.STRIPE_SIGNING_SECRET // Redacted
15
+ * ```
16
+ *
17
+ * Values are read when the app starts; Executor restarts the app when one
18
+ * changes.
19
+ */
20
+ import { Config, ConfigProvider, Effect, Redacted } from "effect";
21
+ import type { CheckResult, SettingDeclaration } from "./contract.ts";
22
+
23
+ /** A setting's own check, run when a person asks on the app's page. Fail with a message a person can act on. */
24
+ export type Check = Effect.Effect<void, { readonly message: string }>;
25
+
26
+ interface Spec<A> {
27
+ readonly declaration: Omit<SettingDeclaration, "name">;
28
+ readonly config: (name: string) => Config.Config<A>;
29
+ readonly check: Check | undefined;
30
+ }
31
+
32
+ export interface TextOptions {
33
+ readonly default?: string;
34
+ readonly description?: string;
35
+ readonly check?: Check;
36
+ }
37
+
38
+ export interface SecretOptions {
39
+ readonly description?: string;
40
+ readonly check?: Check;
41
+ }
42
+
43
+ /** A value a person types on the app's page. */
44
+ export const text = (label: string, options: TextOptions = {}): Spec<string> => ({
45
+ declaration: {
46
+ kind: "text",
47
+ label,
48
+ description: options.description ?? null,
49
+ default: options.default ?? null,
50
+ checked: options.check !== undefined,
51
+ },
52
+ config: (name) =>
53
+ options.default === undefined
54
+ ? Config.String(name)
55
+ : Config.withDefault(Config.String(name), options.default),
56
+ check: options.check,
57
+ });
58
+
59
+ /** A secret a person pastes on the app's page. It is never shown again. */
60
+ export const secret = (
61
+ label: string,
62
+ options: SecretOptions = {},
63
+ ): Spec<Redacted.Redacted<string>> => ({
64
+ declaration: {
65
+ kind: "secret",
66
+ label,
67
+ description: options.description ?? null,
68
+ default: null,
69
+ checked: options.check !== undefined,
70
+ },
71
+ config: (name) => Config.Redacted(name),
72
+ check: options.check,
73
+ });
74
+
75
+ /** A random secret Executor makes once, e.g. to sign webhooks. */
76
+ export const generated = (
77
+ options: { readonly description?: string } = {},
78
+ ): Spec<Redacted.Redacted<string>> => ({
79
+ declaration: {
80
+ kind: "generated",
81
+ label: null,
82
+ description: options.description ?? null,
83
+ default: null,
84
+ checked: false,
85
+ },
86
+ config: (name) => Config.Redacted(name),
87
+ check: undefined,
88
+ });
89
+
90
+ /** Every declaration in this bundle, for `describe()`. */
91
+ export const declarations: Array<SettingDeclaration> = [];
92
+ const checks = new Map<string, Check>();
93
+
94
+ export type Declared<S extends Record<string, Spec<unknown>>> = {
95
+ readonly [K in keyof S]: S[K] extends Spec<infer A> ? Config.Config<A> : never;
96
+ };
97
+
98
+ /** Declare the app's settings and secrets. Each entry is also a `Config` for reading it. */
99
+ export const declare = <const S extends Record<string, Spec<unknown>>>(spec: S): Declared<S> => {
100
+ const declared: Record<string, Config.Config<unknown>> = {};
101
+ for (const [name, entry] of Object.entries(spec)) {
102
+ declarations.push({ name, ...entry.declaration });
103
+ if (entry.check !== undefined) checks.set(name, entry.check);
104
+ declared[name] = entry.config(name);
105
+ }
106
+ return declared as Declared<S>;
107
+ };
108
+
109
+ /** Runs a setting's own check, in the app's own context. */
110
+ export const runCheck = (setting: string): Effect.Effect<CheckResult> => {
111
+ const check = checks.get(setting);
112
+ if (check === undefined)
113
+ return Effect.succeed({ status: "failed", message: `${setting} has no check` });
114
+ return check.pipe(
115
+ Effect.as<CheckResult>({ status: "ok", message: null }),
116
+ Effect.catch((error) =>
117
+ Effect.succeed<CheckResult>({ status: "failed", message: error.message }),
118
+ ),
119
+ );
120
+ };
121
+
122
+ /**
123
+ * The app's `Config` source: the values Executor holds, then each declared setting's default,
124
+ * so `Config.String("X")` and `settings.X` read the same. A declared
125
+ * setting nobody has filled in fails where it is read, with a `ConfigError` that
126
+ * names it and the page where a person sets it, so an app starts before its
127
+ * settings are filled in and only the work that needs the value fails.
128
+ */
129
+ export const configProvider = (
130
+ values: Readonly<Record<string, string>>,
131
+ url: string | null,
132
+ ): ConfigProvider.ConfigProvider =>
133
+ ConfigProvider.orElse(
134
+ ConfigProvider.fromEnvRecord(values),
135
+ ConfigProvider.make((path) => {
136
+ const name = path.length === 1 && typeof path[0] === "string" ? path[0] : undefined;
137
+ const declared = declarations.find((entry) => entry.name === name);
138
+ if (declared === undefined) return Effect.succeed(undefined);
139
+ if (declared.default !== null)
140
+ return Effect.succeed(ConfigProvider.makeValue(declared.default));
141
+ missingAsked.add(declared.name);
142
+ const where =
143
+ url === null
144
+ ? "on the app's settings page in Executor"
145
+ : `on the app's settings page: ${url}`;
146
+ return Effect.fail(
147
+ new ConfigProvider.SourceError({
148
+ message: `The setting ${declared.name} has no value yet. A person sets it ${where}`,
149
+ }),
150
+ );
151
+ }),
152
+ );
153
+
154
+ const missingAsked = new Set<string>();
155
+
156
+ /**
157
+ * The declared settings with no value that were read since the last call, for
158
+ * naming them when the app fails to start. Clears the record.
159
+ */
160
+ export const takeMissing = (): ReadonlyArray<string> => {
161
+ const names = [...missingAsked];
162
+ missingAsked.clear();
163
+ return names;
164
+ };