@ekanos/harness 0.1.5 → 0.3.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 (47) hide show
  1. package/README.md +243 -79
  2. package/dist/api.d.ts +42 -0
  3. package/dist/api.js +17 -0
  4. package/dist/internal/components/dev-toolbar.js +4 -2
  5. package/dist/internal/components/harness-providers.d.ts +8 -2
  6. package/dist/internal/components/harness-providers.js +4 -1
  7. package/dist/internal/components/local-oauth-panel.d.ts +29 -0
  8. package/dist/internal/components/local-oauth-panel.js +355 -0
  9. package/dist/internal/lib/actions-transport.d.ts +30 -0
  10. package/dist/internal/lib/actions-transport.js +6 -0
  11. package/dist/internal/lib/harness-fetch-interceptor.d.ts +53 -14
  12. package/dist/internal/lib/harness-fetch-interceptor.js +96 -0
  13. package/dist/internal/lib/oauth-setup-guide.d.ts +43 -0
  14. package/dist/internal/lib/oauth-setup-guide.js +28 -0
  15. package/dist/internal/lib/original-fetch.d.ts +36 -0
  16. package/dist/internal/lib/original-fetch.js +23 -0
  17. package/dist/internal/lib/run-activation-hook.d.ts +2 -8
  18. package/dist/internal/lib/toolbar-context.d.ts +7 -3
  19. package/dist/internal/lib/toolbar-context.js +10 -5
  20. package/dist/internal/lib/trigger-contract.d.ts +99 -0
  21. package/dist/internal/lib/trigger-contract.js +25 -0
  22. package/dist/internal/lib/trigger-runner.d.ts +55 -0
  23. package/dist/internal/lib/trigger-runner.js +153 -0
  24. package/dist/internal/routes/activation-page.js +42 -28
  25. package/dist/internal/routes/integration-layout.js +6 -1
  26. package/dist/internal/routes/triggers-page.js +121 -147
  27. package/dist/internal/server/actions-fixtures-context.d.ts +57 -0
  28. package/dist/internal/server/actions-fixtures-context.js +52 -0
  29. package/dist/internal/server/api-router.d.ts +54 -0
  30. package/dist/internal/server/api-router.js +575 -0
  31. package/dist/internal/server/live-context.d.ts +93 -0
  32. package/dist/internal/server/live-context.js +93 -0
  33. package/dist/internal/server/local-secrets.d.ts +84 -0
  34. package/dist/internal/server/local-secrets.js +144 -0
  35. package/dist/internal/server/loopback-guard.d.ts +33 -0
  36. package/dist/internal/server/loopback-guard.js +38 -0
  37. package/dist/internal/server/nonce-store.d.ts +38 -0
  38. package/dist/internal/server/nonce-store.js +40 -0
  39. package/dist/internal/server/oauth-loop.d.ts +114 -0
  40. package/dist/internal/server/oauth-loop.js +141 -0
  41. package/dist/internal/server/project-root.d.ts +29 -0
  42. package/dist/internal/server/project-root.js +31 -0
  43. package/dist/internal/server/storage-read.d.ts +34 -0
  44. package/dist/internal/server/storage-read.js +53 -0
  45. package/dist/registry.d.ts +73 -1
  46. package/dist/registry.js +21 -1
  47. package/package.json +13 -7
@@ -0,0 +1,43 @@
1
+ import type { IntegrationDefinition } from '@ekanos/sdk/integration';
2
+ import type { HarnessIntegration } from '../../registry.js';
3
+ /**
4
+ * ─────────────────────────────────────────────────────────────────────────────
5
+ * WHAT THE HUMAN HAS TO DO — derived from the declaration, plus notes
6
+ * ─────────────────────────────────────────────────────────────────────────────
7
+ *
8
+ * An OAuth loop needs things no code can do: someone signs in to the
9
+ * provider's developer console, creates an app, registers the redirect URI,
10
+ * enables the scopes, and copies two strings out. Most of that checklist is
11
+ * already IN the declaration — the provider is the authorize URL's host, the
12
+ * scopes are `provider.scopes`, PKCE is `provider.pkce`, the redirect URI is
13
+ * the shell's callback — so the harness derives it rather than asking the
14
+ * partner to write it twice. What it cannot derive is where that console
15
+ * lives and what the provider calls each credential, which is what the
16
+ * optional `oauth.setup` on the harness entry adds.
17
+ *
18
+ * Pure, so the checklist is testable without rendering.
19
+ */
20
+ export interface OAuthSetupGuide {
21
+ /** The provider, as the authorize URL's host — `account-d.docusign.com`. */
22
+ providerHost: string;
23
+ /** Where to create the app, when the entry says. */
24
+ console: {
25
+ url: string;
26
+ label: string;
27
+ } | null;
28
+ redirectUri: string;
29
+ scopes: readonly string[];
30
+ pkce: boolean;
31
+ /** The declared credential secret names, in the order the form shows them. */
32
+ credentials: {
33
+ clientId: string;
34
+ clientSecret: string;
35
+ };
36
+ /** Partner-authored, provider-specific steps. */
37
+ notes: readonly string[];
38
+ }
39
+ export declare function buildOAuthSetupGuide(args: {
40
+ definition: Pick<IntegrationDefinition, 'oauth'>;
41
+ entry: Pick<HarnessIntegration, 'oauth'>;
42
+ redirectUri: string;
43
+ }): OAuthSetupGuide | null;
@@ -0,0 +1,28 @@
1
+ function buildOAuthSetupGuide(args) {
2
+ const oauth = args.definition.oauth;
3
+ if (!oauth) return null;
4
+ const setup = args.entry.oauth?.setup;
5
+ const consoleUrl = setup?.consoleUrl;
6
+ return {
7
+ providerHost: hostOf(oauth.provider.authorizationUrl),
8
+ console: consoleUrl ? { url: consoleUrl, label: setup?.consoleLabel ?? hostOf(consoleUrl) } : null,
9
+ redirectUri: args.redirectUri,
10
+ scopes: oauth.provider.scopes,
11
+ pkce: oauth.provider.pkce === true,
12
+ credentials: {
13
+ clientId: oauth.credentials.clientIdSecretName,
14
+ clientSecret: oauth.credentials.clientSecretSecretName
15
+ },
16
+ notes: setup?.notes ?? []
17
+ };
18
+ }
19
+ function hostOf(url) {
20
+ try {
21
+ return new URL(url).host;
22
+ } catch {
23
+ return url;
24
+ }
25
+ }
26
+ export {
27
+ buildOAuthSetupGuide
28
+ };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * ─────────────────────────────────────────────────────────────────────────────
3
+ * FINDING THE REAL `fetch` FROM UNDER THE INTERCEPTOR
4
+ * ─────────────────────────────────────────────────────────────────────────────
5
+ *
6
+ * `harness-fetch-interceptor.ts` patches `globalThis.fetch` at module import,
7
+ * and `harness-providers.tsx` imports it — a `'use client'` module that Next
8
+ * ALSO evaluates during the server render, in the same Node process the API
9
+ * route handlers run in. So on the server, `globalThis.fetch` may be the
10
+ * interceptor, answering from whatever fixture table the last page render
11
+ * published: a route handler calling `globalThis.fetch(tokenUrl)` would then
12
+ * be refused as "no recorded response" in fixtures mode, or pass through in
13
+ * live mode, depending on which page happened to render last. Measured in
14
+ * review, not theorised.
15
+ *
16
+ * The interceptor therefore TAGS its wrapper with the function it wrapped,
17
+ * under a `Symbol.for` key so the tag survives duplicate module instances
18
+ * (dev HMR, two copies of this package). Server code that must reach the
19
+ * network unwraps here, at CALL time — the patch may land after this module
20
+ * was imported.
21
+ *
22
+ * Directive-free on purpose: imported by both the client interceptor and the
23
+ * server routes.
24
+ */
25
+ export declare const ORIGINAL_FETCH: unique symbol;
26
+ type Fetch = typeof globalThis.fetch;
27
+ /** Record on `wrapper` the fetch it delegates to. */
28
+ export declare function tagInterceptor(wrapper: Fetch, original: Fetch): void;
29
+ /**
30
+ * The fetch beneath every harness wrapper currently on `candidate` (default:
31
+ * the global). A function with no tag is taken to be the real one. Cycles
32
+ * cannot form through `tagInterceptor` alone, but the walk is bounded anyway
33
+ * so a hostile or buggy tag can never hang a request.
34
+ */
35
+ export declare function resolveOriginalFetch(candidate?: Fetch): Fetch;
36
+ export {};
@@ -0,0 +1,23 @@
1
+ const ORIGINAL_FETCH = /* @__PURE__ */ Symbol.for("ekanos.harness.original-fetch");
2
+ function tagInterceptor(wrapper, original) {
3
+ Object.defineProperty(wrapper, ORIGINAL_FETCH, {
4
+ value: original,
5
+ enumerable: false,
6
+ configurable: true,
7
+ writable: false
8
+ });
9
+ }
10
+ function resolveOriginalFetch(candidate = globalThis.fetch) {
11
+ let current = candidate;
12
+ const seen = /* @__PURE__ */ new Set();
13
+ while (current[ORIGINAL_FETCH] !== void 0 && !seen.has(current)) {
14
+ seen.add(current);
15
+ current = current[ORIGINAL_FETCH];
16
+ }
17
+ return current;
18
+ }
19
+ export {
20
+ ORIGINAL_FETCH,
21
+ resolveOriginalFetch,
22
+ tagInterceptor
23
+ };
@@ -1,5 +1,6 @@
1
1
  import type { IntegrationDefinition } from '@ekanos/sdk/integration';
2
2
  import { type MockIntegrationContext } from '@ekanos/sdk/testing';
3
+ import type { OnActivateOutcome } from './trigger-contract.js';
3
4
  /**
4
5
  * The outcome of one local run of a definition's `onActivate` hook, for the
5
6
  * Activation surface's readout:
@@ -17,12 +18,5 @@ import { type MockIntegrationContext } from '@ekanos/sdk/testing';
17
18
  * rendering anything — the harness deliberately carries no component/DOM
18
19
  * tests (see vitest.config.ts), only the underlying logic.
19
20
  */
20
- export type OnActivateOutcome = {
21
- status: 'skipped';
22
- } | {
23
- status: 'ran';
24
- } | {
25
- status: 'threw';
26
- message: string;
27
- };
21
+ export type { OnActivateOutcome };
28
22
  export declare function runOnActivateHook(definition: IntegrationDefinition | undefined, ctx: MockIntegrationContext | null): Promise<OnActivateOutcome>;
@@ -27,11 +27,15 @@ export interface ToolbarState {
27
27
  * Where a widget's data comes from. `fixtures` seeds the react-query cache
28
28
  * and blocks every request; `live` lets the widget's own query functions run
29
29
  * against the real third-party API, through a fetch bound to the
30
- * integration's declared egress allowlist. Fusion stays mocked in both.
30
+ * integration's declared egress allowlist, and lets the shell's own API
31
+ * routes answer `/api/integrations/<slug>/…` over the live context.
31
32
  *
32
- * Only honoured for integrations that declare a `live` block in the registry.
33
+ * `null` means nobody has picked one yet, so the integration's own
34
+ * `live.default` decides (fixtures unless it says otherwise) — see
35
+ * `resolveEffectiveDataMode`. Only honoured for integrations that declare a
36
+ * `live` block in the registry.
33
37
  */
34
- dataMode: DataMode;
38
+ dataMode: DataMode | null;
35
39
  variant: FixtureVariant;
36
40
  viewport: ViewportKey;
37
41
  collapsed: boolean;
@@ -24,16 +24,18 @@ const VIEWPORTS = {
24
24
  };
25
25
  const DEFAULT_STATE = {
26
26
  renderState: "active",
27
- // Fixtures by default, always. Opening the harness must never fire a request
28
- // at somebody's API just because a previous session left a switch flipped for
29
- // a different integration.
30
- dataMode: "fixtures",
27
+ // Unset by default, which RESOLVES to fixtures unless the integration itself
28
+ // declares `live: { default: 'live' }`. Opening the harness must never fire a
29
+ // request at somebody's API just because a previous session left a switch
30
+ // flipped for a different integration — and an integration only declares a
31
+ // live default when its widgets never call the vendor from the browser.
32
+ dataMode: null,
31
33
  variant: "default",
32
34
  viewport: "full",
33
35
  collapsed: false,
34
36
  unhealthy: false
35
37
  };
36
- const STORAGE_KEY = "fusion-harness-toolbar";
38
+ const STORAGE_KEY = "fusion-harness-toolbar-v2";
37
39
  function isRenderState(value) {
38
40
  return RENDER_STATES.includes(value);
39
41
  }
@@ -55,6 +57,9 @@ function readStored() {
55
57
  const candidate = parsed;
56
58
  return {
57
59
  renderState: isRenderState(candidate.renderState) ? candidate.renderState : DEFAULT_STATE.renderState,
60
+ // A stored `'fixtures'` is an explicit choice from an earlier session and
61
+ // still wins over an integration's live default — that is what makes
62
+ // the default safe to declare.
58
63
  dataMode: isDataMode(candidate.dataMode) ? candidate.dataMode : DEFAULT_STATE.dataMode,
59
64
  variant: isVariant(candidate.variant) ? candidate.variant : DEFAULT_STATE.variant,
60
65
  viewport: isViewport(candidate.viewport) ? candidate.viewport : DEFAULT_STATE.viewport,
@@ -0,0 +1,99 @@
1
+ /**
2
+ * The wire and render contract shared by the Triggers/Activation surfaces and
3
+ * the harness's own `POST /api/integrations/[slug]/trigger` route.
4
+ *
5
+ * In FIXTURES mode the pages run handlers in the browser against a per-mount
6
+ * mock context and build these shapes locally. In LIVE mode they post to the
7
+ * route, which runs the same helpers against the server-held live context —
8
+ * the one `onTokens` stored real tokens in — and answers with the same shapes.
9
+ * One contract, so a panel cannot render one mode differently from the other.
10
+ *
11
+ * Directive-free: imported by client pages and by the server route.
12
+ */
13
+ export interface HandlerLog {
14
+ level: string;
15
+ message: string;
16
+ }
17
+ export interface StorageDump {
18
+ account: Record<string, unknown>;
19
+ user: Record<string, unknown>;
20
+ }
21
+ /** The outcome of one webhook delivery or schedule run. */
22
+ export interface InvocationOutcome {
23
+ ok: boolean;
24
+ summary: string;
25
+ detail?: string;
26
+ logs: readonly HandlerLog[];
27
+ /**
28
+ * BOTH scopes. `ctx.dumpStorage()` returns `{ account, user }`, and this
29
+ * panel used to render only `account` — so a handler writing to user scope
30
+ * looked like a handler that had written nothing.
31
+ */
32
+ storage: StorageDump;
33
+ }
34
+ /** The outcome of one `onActivate` run — see `run-activation-hook.ts`. */
35
+ export type OnActivateOutcome = {
36
+ status: 'skipped';
37
+ } | {
38
+ status: 'ran';
39
+ } | {
40
+ status: 'threw';
41
+ message: string;
42
+ };
43
+ export type TriggerRequest = {
44
+ kind: 'webhook';
45
+ id: string;
46
+ payload: unknown;
47
+ /** Delivery headers. Defaults to the local transport's unverified marker. */
48
+ headers?: Record<string, string>;
49
+ } | {
50
+ kind: 'schedule';
51
+ id: string;
52
+ } | {
53
+ kind: 'activate';
54
+ };
55
+ export type TriggerResponse = {
56
+ kind: 'webhook' | 'schedule';
57
+ outcome: InvocationOutcome;
58
+ /** Names only — never values. */
59
+ secretNames: string[];
60
+ } | {
61
+ kind: 'activate';
62
+ outcome: OnActivateOutcome;
63
+ logs: readonly HandlerLog[];
64
+ storage: StorageDump;
65
+ secretNames: string[];
66
+ };
67
+ /** The setup readout behind `GET /api/integrations/[slug]/local-setup`. */
68
+ export interface LocalSetupResponse {
69
+ slug: string;
70
+ /** The credentials file, relative to the project root. */
71
+ file: string;
72
+ /** Absolute, for copying into an editor. */
73
+ absolutePath: string;
74
+ /** `null` when the definition declares no `oauth`. */
75
+ redirectUri: string | null;
76
+ keys: {
77
+ name: string;
78
+ filled: boolean;
79
+ }[];
80
+ connected: boolean;
81
+ connection: {
82
+ obtainedAt: string;
83
+ expiresAt: string | null;
84
+ scope: string | null;
85
+ } | null;
86
+ /** Always true today: the connection lives in server memory only. */
87
+ volatile: true;
88
+ }
89
+ /**
90
+ * `PUT /api/integrations/[slug]/local-setup` — the Local OAuth panel's Save.
91
+ * Values travel browser → dev server over loopback ONCE, are written to
92
+ * `.ekanos/local-secrets.json`, and never come back: the response is the same
93
+ * `LocalSetupResponse` the GET returns, filled/missing only.
94
+ */
95
+ export interface LocalSetupWriteRequest {
96
+ values: Record<string, string>;
97
+ }
98
+ export declare function isLocalSetupWriteRequest(value: unknown): value is LocalSetupWriteRequest;
99
+ export declare function isTriggerRequest(value: unknown): value is TriggerRequest;
@@ -0,0 +1,25 @@
1
+ function isLocalSetupWriteRequest(value) {
2
+ if (typeof value !== "object" || value === null) return false;
3
+ const values = value.values;
4
+ return typeof values === "object" && values !== null && !Array.isArray(values) && Object.values(values).every(
5
+ (v) => typeof v === "string"
6
+ );
7
+ }
8
+ function isTriggerRequest(value) {
9
+ if (typeof value !== "object" || value === null) return false;
10
+ const record = value;
11
+ switch (record.kind) {
12
+ case "webhook":
13
+ return typeof record.id === "string" && (record.headers === void 0 || typeof record.headers === "object" && record.headers !== null);
14
+ case "schedule":
15
+ return typeof record.id === "string";
16
+ case "activate":
17
+ return true;
18
+ default:
19
+ return false;
20
+ }
21
+ }
22
+ export {
23
+ isLocalSetupWriteRequest,
24
+ isTriggerRequest
25
+ };
@@ -0,0 +1,55 @@
1
+ import type { IntegrationDefinition } from '@ekanos/sdk/integration';
2
+ import { type MockIntegrationContext } from '@ekanos/sdk/testing';
3
+ import type { InvocationOutcome, LocalSetupResponse, LocalSetupWriteRequest, OnActivateOutcome } from './trigger-contract.js';
4
+ /**
5
+ * ─────────────────────────────────────────────────────────────────────────────
6
+ * ONE WAY TO RUN A HANDLER, TWO PLACES IT CAN RUN
7
+ * ─────────────────────────────────────────────────────────────────────────────
8
+ *
9
+ * The Triggers and Activation surfaces used to hold a per-mount mock context
10
+ * and call `invokeWebhook`/`invokeSchedule`/`invokeActivate` on it directly.
11
+ * That is still exactly right for FIXTURES mode. It is wrong for LIVE mode,
12
+ * where the context that holds the real tokens lives on the SERVER
13
+ * (`internal/server/live-context.ts`) — a browser-side context would run the
14
+ * partner's schedule with no credentials and report a confident "skipped".
15
+ *
16
+ * So the pages ask a `TriggerRunner` and never touch a context themselves:
17
+ *
18
+ * createLocalTriggerRunner(definition, ctx) fixtures — in the browser
19
+ * createServerTriggerRunner(slug) live — POST …/trigger
20
+ *
21
+ * Both return the SAME outcome shapes (`trigger-contract.ts`), so the panels
22
+ * render identically whichever ran.
23
+ */
24
+ export interface TriggerRunner {
25
+ webhook(id: string, payload: unknown, headers?: Record<string, string>): Promise<InvocationOutcome>;
26
+ schedule(id: string): Promise<InvocationOutcome>;
27
+ activate(): Promise<OnActivateOutcome>;
28
+ }
29
+ /** Fixtures mode: run against the per-mount browser context. */
30
+ export declare function createLocalTriggerRunner(definition: IntegrationDefinition, ctx: MockIntegrationContext): TriggerRunner;
31
+ export declare function triggerUrl(slug: string): string;
32
+ export declare function localSetupUrl(slug: string): string;
33
+ /**
34
+ * A harness API error, with the server's own message when it sent one — the
35
+ * loopback refusal and the project-root failure both explain themselves, and
36
+ * that explanation must reach the panel rather than a bare status code.
37
+ */
38
+ export declare class HarnessApiError extends Error {
39
+ readonly status: number;
40
+ constructor(status: number, message: string);
41
+ }
42
+ /**
43
+ * Live mode: run on the server-held live context. The request goes through
44
+ * `globalThis.fetch`, which the interceptor passes through for the active
45
+ * integration's `/api/integrations/<slug>/` paths in live mode.
46
+ */
47
+ export declare function createServerTriggerRunner(slug: string, fetchImpl?: typeof globalThis.fetch): TriggerRunner;
48
+ /** The setup readout for the Local OAuth panel. Live mode only. */
49
+ export declare function fetchLocalSetup(slug: string, fetchImpl?: typeof globalThis.fetch): Promise<LocalSetupResponse>;
50
+ /**
51
+ * The Local OAuth panel's Save: write declared secret values into
52
+ * `.ekanos/local-secrets.json` through the dev server. The values leave the
53
+ * browser exactly once, to loopback; the response reports filled/missing.
54
+ */
55
+ export declare function saveLocalSetup(slug: string, request: LocalSetupWriteRequest, fetchImpl?: typeof globalThis.fetch): Promise<LocalSetupResponse>;
@@ -0,0 +1,153 @@
1
+ import {
2
+ invokeSchedule,
3
+ invokeWebhook
4
+ } from "@ekanos/sdk/testing";
5
+ import { runOnActivateHook } from "./run-activation-hook.js";
6
+ function describeError(error) {
7
+ return error instanceof Error ? error.message : String(error);
8
+ }
9
+ function createLocalTriggerRunner(definition, ctx) {
10
+ const run = async (invoke) => {
11
+ const logsBefore = ctx.logs.length;
12
+ try {
13
+ const result = await invoke();
14
+ return {
15
+ ok: true,
16
+ summary: result.status,
17
+ ...result.detail ? { detail: result.detail } : {},
18
+ logs: ctx.logs.slice(logsBefore),
19
+ storage: ctx.dumpStorage()
20
+ };
21
+ } catch (error) {
22
+ console.error("[harness] handler invocation failed:", error);
23
+ return {
24
+ ok: false,
25
+ summary: "failed",
26
+ detail: describeError(error),
27
+ logs: ctx.logs.slice(logsBefore),
28
+ storage: ctx.dumpStorage()
29
+ };
30
+ }
31
+ };
32
+ return {
33
+ webhook: (id, payload, headers) => run(async () => {
34
+ const webhook = definition.webhooks?.find((w) => w.id === id);
35
+ const { result } = await invokeWebhook(definition, id, payload, {
36
+ context: ctx,
37
+ headers: headers ?? (!webhook || webhook.signature === "none" ? {} : {
38
+ [webhook.signature.header]: "(unverified \u2014 local transport)"
39
+ })
40
+ });
41
+ return result;
42
+ }),
43
+ schedule: (id) => run(async () => {
44
+ const { result } = await invokeSchedule(definition, id, {
45
+ context: ctx
46
+ });
47
+ return result;
48
+ }),
49
+ activate: () => runOnActivateHook(definition, ctx)
50
+ };
51
+ }
52
+ function triggerUrl(slug) {
53
+ return `/api/integrations/${slug}/trigger`;
54
+ }
55
+ function localSetupUrl(slug) {
56
+ return `/api/integrations/${slug}/local-setup`;
57
+ }
58
+ class HarnessApiError extends Error {
59
+ constructor(status, message) {
60
+ super(message);
61
+ this.status = status;
62
+ this.name = "HarnessApiError";
63
+ }
64
+ }
65
+ async function readError(response) {
66
+ let message = `${response.status} ${response.statusText}`;
67
+ try {
68
+ const body = await response.json();
69
+ const detail = [body.message, body.hint].filter((part) => typeof part === "string").join(" ");
70
+ if (detail) message = `${message} \u2014 ${detail}`;
71
+ else if (typeof body.error === "string")
72
+ message = `${message} \u2014 ${body.error}`;
73
+ } catch {
74
+ }
75
+ return new HarnessApiError(response.status, message);
76
+ }
77
+ function createServerTriggerRunner(slug, fetchImpl = (input, init) => globalThis.fetch(input, init)) {
78
+ const post = async (request) => {
79
+ const response = await fetchImpl(triggerUrl(slug), {
80
+ method: "POST",
81
+ headers: {
82
+ "content-type": "application/json",
83
+ accept: "application/json"
84
+ },
85
+ body: JSON.stringify(request)
86
+ });
87
+ if (!response.ok) throw await readError(response);
88
+ return await response.json();
89
+ };
90
+ const invocation = async (request) => {
91
+ try {
92
+ const result = await post(request);
93
+ if (result.kind === "activate") {
94
+ throw new Error("trigger route answered the wrong kind");
95
+ }
96
+ return result.outcome;
97
+ } catch (error) {
98
+ console.error("[harness] server trigger failed:", error);
99
+ return {
100
+ ok: false,
101
+ summary: "failed",
102
+ detail: describeError(error),
103
+ logs: [],
104
+ storage: { account: {}, user: {} }
105
+ };
106
+ }
107
+ };
108
+ return {
109
+ webhook: (id, payload, headers) => invocation({
110
+ kind: "webhook",
111
+ id,
112
+ payload,
113
+ ...headers ? { headers } : {}
114
+ }),
115
+ schedule: (id) => invocation({ kind: "schedule", id }),
116
+ activate: async () => {
117
+ try {
118
+ const result = await post({ kind: "activate" });
119
+ return result.kind === "activate" ? result.outcome : {
120
+ status: "threw",
121
+ message: "trigger route answered the wrong kind"
122
+ };
123
+ } catch (error) {
124
+ return { status: "threw", message: describeError(error) };
125
+ }
126
+ }
127
+ };
128
+ }
129
+ async function fetchLocalSetup(slug, fetchImpl = (input, init) => globalThis.fetch(input, init)) {
130
+ const response = await fetchImpl(localSetupUrl(slug), {
131
+ headers: { accept: "application/json" }
132
+ });
133
+ if (!response.ok) throw await readError(response);
134
+ return await response.json();
135
+ }
136
+ async function saveLocalSetup(slug, request, fetchImpl = (input, init) => globalThis.fetch(input, init)) {
137
+ const response = await fetchImpl(localSetupUrl(slug), {
138
+ method: "PUT",
139
+ headers: { "content-type": "application/json", accept: "application/json" },
140
+ body: JSON.stringify(request)
141
+ });
142
+ if (!response.ok) throw await readError(response);
143
+ return await response.json();
144
+ }
145
+ export {
146
+ HarnessApiError,
147
+ createLocalTriggerRunner,
148
+ createServerTriggerRunner,
149
+ fetchLocalSetup,
150
+ localSetupUrl,
151
+ saveLocalSetup,
152
+ triggerUrl
153
+ };