@notation/factory 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Notation Labs Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,43 @@
1
+ import type { ResourceGroup } from "@notation/resource";
2
+ import * as v from "valibot";
3
+ import type { ConnectionRef } from "./connection.ts";
4
+
5
+ /**
6
+ * In an outpost's config: deliveries from `connection`, in `scope`, are this
7
+ * channel's. Without `scope`, the hub uses the provider's default, such as
8
+ * the outpost's repo for GitHub.
9
+ */
10
+ export type ChannelEntry = {
11
+ provider: string;
12
+ connection: string;
13
+ scope?: string;
14
+ };
15
+
16
+ /** A channel's config: `scope` is what it covers. Where a provider has a sensible default (GitHub: the outpost's repo), it's optional. */
17
+ export const channelConfig = v.object({ scope: v.optional(v.string()) });
18
+ export type ChannelConfig = v.InferInput<typeof channelConfig>;
19
+
20
+ /** What every connection's `channel()` takes: the channel's `id` and its config. The connection is its dependency, so it isn't passed. */
21
+ export type ChannelOptions = { id: string } & ChannelConfig;
22
+
23
+ /**
24
+ * Made by a connection in an outpost. Selectors are made by a provider's
25
+ * channel. Its `id` keys it in the outpost's config.
26
+ */
27
+ export interface Channel extends ResourceGroup {
28
+ readonly scope: string | undefined;
29
+ readonly connection: ConnectionRef;
30
+ }
31
+
32
+ /**
33
+ * Events on a channel, as data the router matches without running the repo's
34
+ * code. `E` is the type of the events it matches, which types worktree
35
+ * functions; `match` is the provider's, including its `from`.
36
+ */
37
+ export type Selector<E> = {
38
+ readonly channel: Channel;
39
+ readonly event: string;
40
+ readonly match: unknown;
41
+ /** Phantom: the matched events' type. */
42
+ readonly __event?: E;
43
+ };
@@ -0,0 +1,15 @@
1
+ import type { ResourceGroup } from "@notation/resource";
2
+ import type { Channel, ChannelOptions } from "./channel.ts";
3
+ import type { Router } from "./router.ts";
4
+
5
+ /** In the infra: Notation Factory's presence on a platform, which sends its deliveries to `router`. Outposts look it up by `name`. */
6
+ export interface Connection extends ResourceGroup {
7
+ readonly name: string;
8
+ readonly router: Router;
9
+ }
10
+
11
+ /** In an outpost: a connection the infra declares, found by `name`. Each provider's makes its own kind of channel. */
12
+ export interface ConnectionRef extends ResourceGroup {
13
+ readonly name: string;
14
+ channel(opts: ChannelOptions): Channel;
15
+ }
@@ -0,0 +1,33 @@
1
+ import type { ResourceGroup } from "@notation/resource";
2
+ import type { Connection } from "./connection.ts";
3
+ import type { Runtime } from "./outpost.ts";
4
+ import type { RepoPattern, Router } from "./router.ts";
5
+ import type { Vault, VaultSecret } from "./vault.ts";
6
+
7
+ /** Where the repos live, which of them get outposts (`allow`), and what mints containers' code credentials. An infra has one. */
8
+ export interface CodeHost extends ResourceGroup {
9
+ readonly connection: Connection;
10
+ readonly allow: RepoPattern[];
11
+ }
12
+
13
+ /** Who may run the CLI against the running hub. Declared, not managed: it contributes to the router's config. */
14
+ export interface OperatorAuth extends ResourceGroup {
15
+ readonly provider: string;
16
+ }
17
+
18
+ /**
19
+ * Credentials an agent runtime runs on. The deployer binds each of `secrets`
20
+ * and injects it into containers that list `runtime`.
21
+ */
22
+ export interface Account extends ResourceGroup {
23
+ readonly runtime: Runtime;
24
+ /** Keyed by the env var name that containers read the secret as, such as `CLAUDE_CODE_OAUTH_TOKEN`. */
25
+ readonly secrets: Record<string, VaultSecret>;
26
+ }
27
+
28
+ /** Checks and builds outposts' containers, and gives them `accounts`' credentials. */
29
+ export interface Deployer extends ResourceGroup {
30
+ readonly router: Router;
31
+ readonly vault: Vault;
32
+ readonly accounts: Account[];
33
+ }
@@ -0,0 +1,36 @@
1
+ export {
2
+ type Channel,
3
+ type ChannelConfig,
4
+ channelConfig,
5
+ type ChannelEntry,
6
+ type ChannelOptions,
7
+ type Selector,
8
+ } from "./channel.ts";
9
+ export type { Connection, ConnectionRef } from "./connection.ts";
10
+ export type { Account, CodeHost, Deployer, OperatorAuth } from "./hub.ts";
11
+ export type {
12
+ Agent,
13
+ AgentEntry,
14
+ ContainerEntry,
15
+ OutpostConfig,
16
+ PolicyContract,
17
+ PolicyEntry,
18
+ Runtime,
19
+ TriggerEntry,
20
+ } from "./outpost.ts";
21
+ export type {
22
+ CodeHostEntry,
23
+ ConnectionEntry,
24
+ OperatorsEntry,
25
+ RepoPattern,
26
+ Router,
27
+ RouterChannelOptions,
28
+ RouterConfig,
29
+ RouterConfigContribution,
30
+ RouterConfigStore,
31
+ } from "./router.ts";
32
+ export type {
33
+ Vault,
34
+ VaultSecret,
35
+ VaultSecretOptions,
36
+ } from "./vault.ts";
@@ -0,0 +1,54 @@
1
+ import type { ResourceGroup } from "@notation/resource";
2
+ import type { ChannelEntry } from "./channel.ts";
3
+
4
+ /** A kind of agent, which a container's image installs the CLI of. `setup` is a root shell script that installs the CLI system-wide; the deployer adds it to the container's build context. */
5
+ export type Runtime = { id: string; setup?: string };
6
+
7
+ /** An agent persona for a runtime. Its provider decides its settings. */
8
+ export interface Agent extends ResourceGroup {
9
+ readonly runtime: Runtime;
10
+ }
11
+
12
+ /** Credentials a container may ask the router for. `provider` names what mints them (e.g. "github": the code host). */
13
+ export interface PolicyContract extends ResourceGroup {
14
+ readonly provider: string;
15
+ }
16
+
17
+ /** In an outpost's config: a container, with its runtimes' and policies' ids. */
18
+ export type ContainerEntry = {
19
+ /** The Dockerfile, relative to `.factory/`. Without it, the container gets Factory's default image. */
20
+ image?: string;
21
+ runtimes: string[];
22
+ policies: string[];
23
+ files: Record<string, string | Record<string, unknown>>;
24
+ };
25
+
26
+ /** In an outpost's config: a policy. The rest is its provider's. */
27
+ export type PolicyEntry = { provider: string } & Record<string, unknown>;
28
+
29
+ /** In an outpost's config: an agent. The rest is its runtime's settings. */
30
+ export type AgentEntry = { runtime: string } & Record<string, unknown>;
31
+
32
+ /**
33
+ * In an outpost's config: the whole dispatch rule. A delivery of `event` on
34
+ * `channel` that `match` accepts runs `agent` in `container`. With `worktree`,
35
+ * the run's branch is named from the event, cut from `base`: the function
36
+ * isn't data, so the deployer runs the config to call it.
37
+ */
38
+ export type TriggerEntry = {
39
+ channel: string;
40
+ event: string;
41
+ match: unknown;
42
+ agent: string;
43
+ container: string;
44
+ worktree?: { base?: string };
45
+ };
46
+
47
+ /** An outpost's config, keyed by each resource's id. */
48
+ export type OutpostConfig = {
49
+ channels: Record<string, ChannelEntry>;
50
+ containers: Record<string, ContainerEntry>;
51
+ policies: Record<string, PolicyEntry>;
52
+ agents: Record<string, AgentEntry>;
53
+ triggers: Record<string, TriggerEntry>;
54
+ };
@@ -0,0 +1,104 @@
1
+ import type {
2
+ DeepInput,
3
+ Input,
4
+ OutputRef,
5
+ ResourceGroup,
6
+ } from "@notation/resource";
7
+ import type { Vault, VaultSecret } from "./vault.ts";
8
+
9
+ /**
10
+ * In the router's config: where a connection's deliveries come from
11
+ * (`source`, e.g. a GitHub App's id), the binding names of the vault secrets
12
+ * that the router reads for it, and the name the router reaches its channel
13
+ * by.
14
+ * Keyed by `<provider>/<name>`: outposts look a connection up by name, from
15
+ * its provider's package, so a GitHub App and a Slack app may share a name.
16
+ */
17
+ export type ConnectionEntry = {
18
+ provider: string;
19
+ source: string;
20
+ credentials: Record<string, string>;
21
+ channel?: string;
22
+ };
23
+
24
+ /** Repos a code host serves: all of `owner`'s, or just `owner/repo`. */
25
+ export type RepoPattern = { owner: string; repo?: string };
26
+
27
+ /** In the router's config: which repos get outposts, and the connection their tokens are minted through. */
28
+ export type CodeHostEntry = {
29
+ provider: string;
30
+ connection: string;
31
+ allow: RepoPattern[];
32
+ };
33
+
34
+ /** In the router's config: how it checks who an operator is. The rest is the provider's. */
35
+ export type OperatorsEntry = { provider: string } & Record<string, unknown>;
36
+
37
+ /** The router's config. Connections are keyed by provider and name. An infra has one code host and one operator auth. */
38
+ export type RouterConfig = {
39
+ connections: Record<string, ConnectionEntry>;
40
+ codeHost: CodeHostEntry;
41
+ operators: OperatorsEntry;
42
+ };
43
+
44
+ type ConfigPartial<T> = T extends readonly unknown[]
45
+ ? T
46
+ : T extends object
47
+ ? { [K in keyof T]?: ConfigPartial<T[K]> }
48
+ : T;
49
+
50
+ /**
51
+ * A contribution to the router's config: any object key can be left out, and
52
+ * an array is given whole. Any value can be a ref.
53
+ */
54
+ export type RouterConfigContribution = {
55
+ [K in keyof RouterConfig]?: DeepInput<ConfigPartial<RouterConfig[K]>>;
56
+ };
57
+
58
+ /**
59
+ * Where the router's config is kept: anything that takes contributions to
60
+ * it, such as a resource or a `kvJson()` document.
61
+ */
62
+ export type RouterConfigStore = {
63
+ contribute(values: RouterConfigContribution): void;
64
+ };
65
+
66
+ /** A connection's channel, which the router runs and calls for each delivery to the connection. */
67
+ export type RouterChannelOptions = {
68
+ /** The connection's key in the router's config, such as `github/gh`. */
69
+ connection: string;
70
+ /** The absolute path of the module that exports the provider's `channel`, a `ChannelModule`. */
71
+ module: string;
72
+ /** The vault secrets that the channel reads with `ctx.secret(name)`. */
73
+ secrets?: Record<string, VaultSecret>;
74
+ /** The values that the channel reads with `ctx.value(name)`. */
75
+ values?: Record<string, Input<string>>;
76
+ };
77
+
78
+ /**
79
+ * Receives every connection's deliveries, matches outposts' triggers, relays
80
+ * channel replies and mints code host tokens. A provider decides where each
81
+ * part lives (a Worker and a KV entry, …). The config is `store`, not
82
+ * `config`, which ResourceGroup already uses for the group's own options.
83
+ * `vault` is on the router's own provider. `rootKey` is the secret that the
84
+ * router and the deployer derive every other key from.
85
+ */
86
+ export interface Router extends ResourceGroup {
87
+ /** The router's URL, which deploy fills in. Join a path to it with `text`. */
88
+ readonly url: OutputRef<string>;
89
+ readonly store: RouterConfigStore;
90
+ readonly vault: Vault;
91
+ readonly rootKey: VaultSecret;
92
+ /**
93
+ * Binds a secret from the router's vault to the router, and returns the
94
+ * name the router reads it as. The name is made from the secret's id,
95
+ * unless `name` is given. A connection binds its credentials this way, and
96
+ * records the names in its entry.
97
+ */
98
+ bind(secret: VaultSecret, name?: string): string;
99
+ /**
100
+ * Runs a connection's channel, and records in the connection's entry the
101
+ * name the router reaches it by.
102
+ */
103
+ channel(options: RouterChannelOptions): void;
104
+ }
@@ -0,0 +1,22 @@
1
+ import type { CredentialRef, ResourceGroup } from "@notation/resource";
2
+
3
+ export type VaultSecretOptions = {
4
+ /** Keys the secret in state. The name in the store is generated by the vault's provider. */
5
+ id: string;
6
+ /**
7
+ * A credential of another resource, such as `source.credentials.value` for
8
+ * a source, or `token.credentials.Value` for an API token. Deploy writes
9
+ * it to the store, and state holds a marker in its place.
10
+ */
11
+ value: CredentialRef<string>;
12
+ };
13
+
14
+ /** A secret that a vault declares. The router or the deployer binds it. */
15
+ export type VaultSecret = ResourceGroup;
16
+
17
+ /** The hub's write-only secret store. `secret()` declares a secret that the vault owns. */
18
+ export interface Vault<S extends VaultSecret = VaultSecret>
19
+ extends ResourceGroup {
20
+ readonly provider: string;
21
+ secret(opts: VaultSecretOptions): S;
22
+ }
@@ -0,0 +1,31 @@
1
+ import { collectResourceGraph } from "@notation/resource";
2
+ import type { OutpostConfig } from "../contracts/outpost.ts";
3
+
4
+ /** Runs an outpost's config with `load`, and returns the outpost config that its resources contribute. */
5
+ export const collectOutpost = async (
6
+ load: () => Promise<unknown>,
7
+ ): Promise<OutpostConfig> => {
8
+ const graph = await collectResourceGraph(async () => {
9
+ await load();
10
+ });
11
+ const store = graph.resources.find(
12
+ (resource) => resource.type === "factory/deployer/OutpostConfig",
13
+ );
14
+ if (!store) throw new Error(".factory/config.ts declares no outpost resources");
15
+ return (await store.getParams()) as OutpostConfig;
16
+ };
17
+
18
+ /** Runs an outpost's config with `load`, and calls the worktree function of the trigger `id` with `event`. */
19
+ export const collectWorktree = async (
20
+ load: () => Promise<unknown>,
21
+ id: string,
22
+ event: unknown,
23
+ ): Promise<string | undefined> => {
24
+ const graph = await collectResourceGraph(async () => {
25
+ await load();
26
+ });
27
+ const trigger = graph.resourceGroups.find((group) => group.type === "factory/Trigger" && group.id === id);
28
+ if (!trigger) throw new Error(`.factory/config.ts declares no trigger ${id}`);
29
+ const worktree = trigger.config.worktree as ((event: unknown) => string | undefined) | undefined;
30
+ return worktree?.(event);
31
+ };
@@ -0,0 +1,50 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import type { OutpostConfig } from "../contracts/outpost.ts";
4
+ import { type DeployerContext, deploy } from "./index.ts";
5
+
6
+ const previous: OutpostConfig = { channels: {}, containers: {}, policies: {}, agents: {}, triggers: {} };
7
+
8
+ const context = (evaluate: DeployerContext["evaluate"]) => {
9
+ const stored: Record<string, OutpostConfig | undefined> = { "acme/api": previous };
10
+ const ctx: DeployerContext = {
11
+ evaluate,
12
+ putOutpost: async (repo, outpost) => {
13
+ stored[repo] = outpost;
14
+ return [];
15
+ },
16
+ getFiles: async () => undefined,
17
+ deleteOutpost: async (repo) => void delete stored[repo],
18
+ };
19
+ return { ctx, stored };
20
+ };
21
+
22
+ test("deploy stores the evaluated outpost, with the repo as the scope of unscoped channels", async () => {
23
+ const { ctx, stored } = context(async () => ({
24
+ channels: { issues: { provider: "github", connection: "gh" } },
25
+ }));
26
+ const status = await deploy("acme/api", { ref: "abc", files: { "config.ts": "" } }, ctx);
27
+ assert.equal(status.state, "deployed");
28
+ assert.equal(status.ref, "abc");
29
+ assert.deepEqual(stored["acme/api"], {
30
+ channels: { issues: { provider: "github", connection: "gh", scope: "acme/api" } },
31
+ });
32
+ });
33
+
34
+ test("a config that fails leaves the outpost as it was", async () => {
35
+ const { ctx, stored } = context(async () => {
36
+ throw new Error("bad config");
37
+ });
38
+ const status = await deploy("acme/api", { ref: "abc", files: { "config.ts": "" } }, ctx);
39
+ assert.equal(status.state, "failed");
40
+ assert.equal(status.error, "bad config");
41
+ assert.equal(stored["acme/api"], previous);
42
+ });
43
+
44
+ test("a repo with no config.ts loses its outpost", async () => {
45
+ const { ctx, stored } = context(async () => ({}));
46
+ const status = await deploy("acme/api", { ref: "abc", files: { Dockerfile: "" } }, ctx);
47
+ assert.equal(status.state, "failed");
48
+ assert.match(status.error!, /no \.factory\/config\.ts/);
49
+ assert.equal("acme/api" in stored, false);
50
+ });
@@ -0,0 +1,152 @@
1
+ import { transform } from "sucrase";
2
+ import type { OutpostConfig } from "../contracts/outpost.ts";
3
+ import type { FactoryStatus, SourceFiles } from "../router/channel.ts";
4
+ import { FACTORY_DIR } from "../router/handle.ts";
5
+ import sdk from "./sdk.gen.ts";
6
+ import { SDK_COLLECT, SDK_DIR, SDK_PACKAGES } from "./sdk.ts";
7
+
8
+ /**
9
+ * ES modules by name, all JavaScript. `main` default-exports a function
10
+ * that takes `input` and returns the result. `input` is JSON.
11
+ */
12
+ export type Program = { main: string; modules: Record<string, string>; input?: unknown };
13
+
14
+ /** What the deployer needs from the platform it runs on. */
15
+ export interface DeployerContext {
16
+ /**
17
+ * Runs `program` in an isolate with no network access and no bindings,
18
+ * calls its main function with `program.input`, and returns what it
19
+ * returns. Throws the program's error.
20
+ */
21
+ evaluate(program: Program): Promise<unknown>;
22
+ /**
23
+ * Stores the repo's outpost config, where the router reads it, and the
24
+ * `.factory/` files it was evaluated from. `ref` is the commit they were
25
+ * read at. Resolves to the containers whose images started building.
26
+ */
27
+ putOutpost(repo: string, outpost: OutpostConfig, files: Record<string, string>, ref: string): Promise<string[]>;
28
+ /** The `.factory/` files of the repo's outpost. */
29
+ getFiles(repo: string): Promise<Record<string, string> | undefined>;
30
+ deleteOutpost(repo: string): Promise<void>;
31
+ }
32
+
33
+ const MAIN = "main.js";
34
+
35
+ /**
36
+ * The modules of an outpost's config:
37
+ * 1. Each `.ts` file in `.factory/` loses its types. Its name stays, so that
38
+ * the files' imports of each other still resolve.
39
+ * 2. Each package that a config can import is a module of its own name, which
40
+ * re-exports the SDK's build of it. The SDK's modules are under `sdk/`.
41
+ */
42
+ const configModules = (files: Record<string, string>) => {
43
+ if (!(`config.ts` in files)) throw new Error(`There's no ${FACTORY_DIR}/config.ts.`);
44
+ const modules: Record<string, string> = {};
45
+ for (const [path, code] of Object.entries(files)) {
46
+ if (/\.(m?js)$/.test(path)) modules[`${FACTORY_DIR}/${path}`] = code;
47
+ if (/\.(m?ts)$/.test(path)) {
48
+ modules[`${FACTORY_DIR}/${path}`] = transform(code, {
49
+ transforms: ["typescript"],
50
+ disableESTransforms: true,
51
+ filePath: path,
52
+ }).code;
53
+ }
54
+ }
55
+ for (const [file, code] of Object.entries(sdk)) modules[`${SDK_DIR}/${file}`] = code;
56
+ // The runtime resolves a package's name relative to the importing module,
57
+ // like a relative path, so each directory of files gets its own aliases.
58
+ const dirs = new Set(
59
+ Object.keys(modules)
60
+ .filter((name) => name.startsWith(`${FACTORY_DIR}/`))
61
+ .map((name) => name.slice(0, name.lastIndexOf("/"))),
62
+ );
63
+ for (const dir of dirs) {
64
+ for (const [name, module] of Object.entries(SDK_PACKAGES)) {
65
+ const alias = `${dir}/${name}`;
66
+ const up = "../".repeat(alias.split("/").length - 1);
67
+ modules[alias] = `export * from "${up}${SDK_DIR}/${module}.js";`;
68
+ }
69
+ }
70
+ return modules;
71
+ };
72
+
73
+ /** The program that runs an outpost's config through the SDK's collector, and returns the outpost config. */
74
+ export const outpostProgram = (files: Record<string, string>): Program => {
75
+ const modules = configModules(files);
76
+ modules[MAIN] = [
77
+ `import { collectOutpost } from "./${SDK_DIR}/${SDK_COLLECT}.js";`,
78
+ `export default () => collectOutpost(() => import("./${FACTORY_DIR}/config.ts"));`,
79
+ ].join("\n");
80
+ return { main: MAIN, modules };
81
+ };
82
+
83
+ /** The program that runs an outpost's config, and calls the worktree function of `trigger` with its input. */
84
+ export const worktreeProgram = (files: Record<string, string>, trigger: string, payload: unknown): Program => {
85
+ const modules = configModules(files);
86
+ modules[MAIN] = [
87
+ `import { collectWorktree } from "./${SDK_DIR}/${SDK_COLLECT}.js";`,
88
+ `export default (payload) => collectWorktree(() => import("./${FACTORY_DIR}/config.ts"), ${JSON.stringify(trigger)}, payload);`,
89
+ ].join("\n");
90
+ return { main: MAIN, modules, input: payload };
91
+ };
92
+
93
+ /**
94
+ * Calls the worktree function of the repo's trigger with `payload`, and
95
+ * returns the branch it names. The config is the one the outpost was last
96
+ * deployed from.
97
+ */
98
+ export const worktree = async (
99
+ repo: string,
100
+ trigger: string,
101
+ payload: unknown,
102
+ context: Pick<DeployerContext, "evaluate" | "getFiles">,
103
+ ): Promise<string | undefined> => {
104
+ const files = await context.getFiles(repo);
105
+ if (!files) throw new Error(`${repo} has no deployed outpost.`);
106
+ const branch = await context.evaluate(worktreeProgram(files, trigger, payload));
107
+ if (branch === undefined || branch === null) return undefined;
108
+ if (typeof branch !== "string") {
109
+ throw new Error(`The worktree function of ${trigger} returned ${typeof branch}, not a string.`);
110
+ }
111
+ return branch;
112
+ };
113
+
114
+ /**
115
+ * Evaluates a repo's `.factory/` files, and returns the repo's outpost
116
+ * config. A channel with no scope gets the repo's.
117
+ */
118
+ export const evaluateOutpost = async (
119
+ repo: string,
120
+ files: Record<string, string>,
121
+ context: Pick<DeployerContext, "evaluate">,
122
+ ): Promise<OutpostConfig> => {
123
+ const outpost = (await context.evaluate(outpostProgram(files))) as OutpostConfig;
124
+ for (const channel of Object.values(outpost.channels ?? {})) {
125
+ channel.scope ??= repo;
126
+ }
127
+ return outpost;
128
+ };
129
+
130
+ const message = (error: unknown) => (error instanceof Error ? error.message : String(error));
131
+
132
+ /**
133
+ * Deploys a repo's outpost from its `.factory/` files. A repo with no
134
+ * `.factory/config.ts` loses its outpost. A config that fails leaves the
135
+ * outpost as it was.
136
+ */
137
+ export const deploy = async (
138
+ repo: string,
139
+ { ref, files }: SourceFiles,
140
+ context: DeployerContext,
141
+ ): Promise<FactoryStatus> => {
142
+ if (!("config.ts" in files)) {
143
+ await context.deleteOutpost(repo);
144
+ return { state: "failed", ref, error: `There's no ${FACTORY_DIR}/config.ts.`, at: new Date().toISOString() };
145
+ }
146
+ try {
147
+ const building = await context.putOutpost(repo, await evaluateOutpost(repo, files, context), files, ref);
148
+ return { state: "deployed", ref, at: new Date().toISOString(), ...(building.length && { building }) };
149
+ } catch (error) {
150
+ return { state: "failed", ref, error: message(error), at: new Date().toISOString() };
151
+ }
152
+ };