@process.co/sdk 0.0.0-stage → 0.1.0-next.2

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.
@@ -0,0 +1,10 @@
1
+ import type { ReactNode } from 'react';
2
+ import type { InstalledWorkflowConsent } from '../workflow';
3
+ import type { ConnectionStep, OperationRef } from '../methods';
4
+ interface Props {
5
+ step: ConnectionStep;
6
+ consent: (operation: OperationRef, signal?: AbortSignal) => Promise<InstalledWorkflowConsent>;
7
+ children?: ReactNode;
8
+ }
9
+ export declare function ProcessConnectionForm(props: Props): import("react/jsx-runtime").JSX.Element;
10
+ export {};
@@ -0,0 +1,47 @@
1
+ 'use client';
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.ProcessConnectionForm = ProcessConnectionForm;
5
+ const jsx_runtime_1 = require("react/jsx-runtime");
6
+ const react_1 = require("react");
7
+ function Form({ step, consent, children }) {
8
+ const [handoff, setHandoff] = (0, react_1.useState)(step.consent);
9
+ const [loading, setLoading] = (0, react_1.useState)(false);
10
+ const [error, setError] = (0, react_1.useState)(false);
11
+ const request = (0, react_1.useRef)(null);
12
+ (0, react_1.useEffect)(() => () => request.current?.abort(), []);
13
+ (0, react_1.useEffect)(() => {
14
+ if (!handoff)
15
+ return;
16
+ const timer = setTimeout(() => setHandoff(undefined), Math.max(0, Date.parse(handoff.expiresAt) - Date.now()));
17
+ return () => clearTimeout(timer);
18
+ }, [handoff]);
19
+ if (handoff && Date.parse(handoff.expiresAt) > Date.now())
20
+ return ((0, jsx_runtime_1.jsxs)("form", { action: handoff.installUrl, method: "post", target: "_blank", rel: "noopener noreferrer", children: [(0, jsx_runtime_1.jsx)("input", { type: "hidden", name: "confirmationCode", value: handoff.confirmationCode }), (0, jsx_runtime_1.jsx)("button", { type: "submit", children: children ?? 'Connect account' })] }));
21
+ async function renew() {
22
+ if (!step.operation || request.current)
23
+ return;
24
+ const controller = new AbortController();
25
+ request.current = controller;
26
+ setLoading(true);
27
+ setError(false);
28
+ try {
29
+ setHandoff(await consent(step.operation, controller.signal));
30
+ }
31
+ catch {
32
+ if (!controller.signal.aborted)
33
+ setError(true);
34
+ }
35
+ finally {
36
+ request.current = null;
37
+ if (!controller.signal.aborted)
38
+ setLoading(false);
39
+ }
40
+ }
41
+ if (!step.operation || step.operation.kind !== 'setup' || step.setupIssue)
42
+ return (0, jsx_runtime_1.jsx)("p", { role: "status", children: step.setupIssue ?? step.reason });
43
+ return (0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("button", { type: "button", disabled: loading, onClick: renew, children: "Get connection link" }), error && (0, jsx_runtime_1.jsx)("span", { role: "alert", children: "Could not get the connection link. Try again." })] });
44
+ }
45
+ function ProcessConnectionForm(props) {
46
+ return (0, jsx_runtime_1.jsx)(Form, { ...props }, JSON.stringify([props.step.operation?.id, props.step.step, props.step.consent?.installUrl]));
47
+ }
@@ -0,0 +1,99 @@
1
+ import type { ReactNode } from 'react';
2
+ import type { ProcessMethod } from '../methods';
3
+ export { useBoundMethod } from './use-method';
4
+ export type { MethodState } from './use-method';
5
+ export { ProcessConnectionForm } from './connection-form';
6
+ export { ProcessActionCard } from './action-card';
7
+ export type { ActionCard, CardControlProps, CardCommand } from './action-card';
8
+ /** Declare the host's method map once. Method names, arguments, and results then infer at every hook. */
9
+ export declare function createProcessReact<M extends Record<string, ProcessMethod<never, unknown>>>(): {
10
+ ProcessProvider: ({ methods, children }: {
11
+ methods: M;
12
+ children: ReactNode;
13
+ }) => import("react/jsx-runtime").JSX.Element;
14
+ useProcessMethod: <K extends keyof M & string>(name: K) => {
15
+ call: (input: Parameters<M[K]["start"]>[0], options?: import("../methods").CallOptions & import("../methods").WaitOptions) => Promise<Extract<Awaited<ReturnType<M[K]["start"]>>, {
16
+ state: "completed";
17
+ }>["data"]>;
18
+ resume: (op: import("../methods").OperationRef, options?: import("../methods").WaitOptions) => Promise<Extract<Awaited<ReturnType<M[K]["start"]>>, {
19
+ state: "completed";
20
+ }>["data"]>;
21
+ method: ProcessMethod<Parameters<M[K]["start"]>[0], Extract<Awaited<ReturnType<M[K]["start"]>>, {
22
+ state: "completed";
23
+ }>["data"]>;
24
+ state: "connection-required";
25
+ reason: string;
26
+ operation?: import("../methods").OperationRef;
27
+ consent?: import("..").InstalledWorkflowConsent;
28
+ step?: string;
29
+ setupIssue?: string;
30
+ } | {
31
+ call: (input: Parameters<M[K]["start"]>[0], options?: import("../methods").CallOptions & import("../methods").WaitOptions) => Promise<Extract<Awaited<ReturnType<M[K]["start"]>>, {
32
+ state: "completed";
33
+ }>["data"]>;
34
+ resume: (op: import("../methods").OperationRef, options?: import("../methods").WaitOptions) => Promise<Extract<Awaited<ReturnType<M[K]["start"]>>, {
35
+ state: "completed";
36
+ }>["data"]>;
37
+ method: ProcessMethod<Parameters<M[K]["start"]>[0], Extract<Awaited<ReturnType<M[K]["start"]>>, {
38
+ state: "completed";
39
+ }>["data"]>;
40
+ state: "idle" | "running";
41
+ } | {
42
+ call: (input: Parameters<M[K]["start"]>[0], options?: import("../methods").CallOptions & import("../methods").WaitOptions) => Promise<Extract<Awaited<ReturnType<M[K]["start"]>>, {
43
+ state: "completed";
44
+ }>["data"]>;
45
+ resume: (op: import("../methods").OperationRef, options?: import("../methods").WaitOptions) => Promise<Extract<Awaited<ReturnType<M[K]["start"]>>, {
46
+ state: "completed";
47
+ }>["data"]>;
48
+ method: ProcessMethod<Parameters<M[K]["start"]>[0], Extract<Awaited<ReturnType<M[K]["start"]>>, {
49
+ state: "completed";
50
+ }>["data"]>;
51
+ state: "error";
52
+ error: unknown;
53
+ } | {
54
+ call: (input: Parameters<M[K]["start"]>[0], options?: import("../methods").CallOptions & import("../methods").WaitOptions) => Promise<Extract<Awaited<ReturnType<M[K]["start"]>>, {
55
+ state: "completed";
56
+ }>["data"]>;
57
+ resume: (op: import("../methods").OperationRef, options?: import("../methods").WaitOptions) => Promise<Extract<Awaited<ReturnType<M[K]["start"]>>, {
58
+ state: "completed";
59
+ }>["data"]>;
60
+ method: ProcessMethod<Parameters<M[K]["start"]>[0], Extract<Awaited<ReturnType<M[K]["start"]>>, {
61
+ state: "completed";
62
+ }>["data"]>;
63
+ state: "completed";
64
+ data: Extract<Awaited<ReturnType<M[K]["start"]>>, {
65
+ state: "completed";
66
+ }>["data"];
67
+ };
68
+ };
69
+ export declare const ProcessProvider: ({ methods, children }: {
70
+ methods: Record<string, ProcessMethod<unknown, unknown>>;
71
+ children: ReactNode;
72
+ }) => import("react/jsx-runtime").JSX.Element, useProcessMethod: <K extends string>(name: K) => {
73
+ call: (input: unknown, options?: import("../methods").CallOptions & import("../methods").WaitOptions) => Promise<unknown>;
74
+ resume: (op: import("../methods").OperationRef, options?: import("../methods").WaitOptions) => Promise<unknown>;
75
+ method: ProcessMethod<unknown, unknown>;
76
+ state: "connection-required";
77
+ reason: string;
78
+ operation?: import("../methods").OperationRef;
79
+ consent?: import("..").InstalledWorkflowConsent;
80
+ step?: string;
81
+ setupIssue?: string;
82
+ } | {
83
+ call: (input: unknown, options?: import("../methods").CallOptions & import("../methods").WaitOptions) => Promise<unknown>;
84
+ resume: (op: import("../methods").OperationRef, options?: import("../methods").WaitOptions) => Promise<unknown>;
85
+ method: ProcessMethod<unknown, unknown>;
86
+ state: "idle" | "running";
87
+ } | {
88
+ call: (input: unknown, options?: import("../methods").CallOptions & import("../methods").WaitOptions) => Promise<unknown>;
89
+ resume: (op: import("../methods").OperationRef, options?: import("../methods").WaitOptions) => Promise<unknown>;
90
+ method: ProcessMethod<unknown, unknown>;
91
+ state: "error";
92
+ error: unknown;
93
+ } | {
94
+ call: (input: unknown, options?: import("../methods").CallOptions & import("../methods").WaitOptions) => Promise<unknown>;
95
+ resume: (op: import("../methods").OperationRef, options?: import("../methods").WaitOptions) => Promise<unknown>;
96
+ method: ProcessMethod<unknown, unknown>;
97
+ state: "completed";
98
+ data: unknown;
99
+ };
@@ -0,0 +1,33 @@
1
+ 'use client';
2
+ "use strict";
3
+ var _a;
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.useProcessMethod = exports.ProcessProvider = exports.ProcessActionCard = exports.ProcessConnectionForm = exports.useBoundMethod = void 0;
6
+ exports.createProcessReact = createProcessReact;
7
+ const jsx_runtime_1 = require("react/jsx-runtime");
8
+ const react_1 = require("react");
9
+ const use_method_1 = require("./use-method");
10
+ var use_method_2 = require("./use-method");
11
+ Object.defineProperty(exports, "useBoundMethod", { enumerable: true, get: function () { return use_method_2.useBoundMethod; } });
12
+ var connection_form_1 = require("./connection-form");
13
+ Object.defineProperty(exports, "ProcessConnectionForm", { enumerable: true, get: function () { return connection_form_1.ProcessConnectionForm; } });
14
+ var action_card_1 = require("./action-card");
15
+ Object.defineProperty(exports, "ProcessActionCard", { enumerable: true, get: function () { return action_card_1.ProcessActionCard; } });
16
+ /** Declare the host's method map once. Method names, arguments, and results then infer at every hook. */
17
+ function createProcessReact() {
18
+ const Context = (0, react_1.createContext)(null);
19
+ function ProcessProvider({ methods, children }) {
20
+ return (0, jsx_runtime_1.jsx)(Context.Provider, { value: methods, children: children });
21
+ }
22
+ function useProcessMethod(name) {
23
+ const methods = (0, react_1.useContext)(Context);
24
+ if (!methods)
25
+ throw new Error('useProcessMethod requires a ProcessProvider');
26
+ if (!Object.hasOwn(methods, name))
27
+ throw new Error('Unknown Process method: ' + name);
28
+ return (0, use_method_1.useBoundMethod)(methods[name]);
29
+ }
30
+ return { ProcessProvider, useProcessMethod };
31
+ }
32
+ // JavaScript apps can use the shared provider and hook directly. A typed method map also infers inputs and outputs.
33
+ _a = createProcessReact(), exports.ProcessProvider = _a.ProcessProvider, exports.useProcessMethod = _a.useProcessMethod;
@@ -0,0 +1,39 @@
1
+ import type { CallOptions, ConnectionStep, OperationRef, ProcessMethod, WaitOptions } from '../methods';
2
+ export type MethodState<T> = {
3
+ state: 'idle' | 'running';
4
+ } | ConnectionStep | {
5
+ state: 'completed';
6
+ data: T;
7
+ } | {
8
+ state: 'error';
9
+ error: unknown;
10
+ };
11
+ /** No calls on mount. The caller owns the event that starts an operation. */
12
+ export declare function useBoundMethod<I, O>(method: ProcessMethod<I, O>): {
13
+ call: (input: I, options?: CallOptions & WaitOptions) => Promise<O>;
14
+ resume: (op: OperationRef, options?: WaitOptions) => Promise<O>;
15
+ method: ProcessMethod<I, O>;
16
+ state: "connection-required";
17
+ reason: string;
18
+ operation?: OperationRef;
19
+ consent?: import("..").InstalledWorkflowConsent;
20
+ step?: string;
21
+ setupIssue?: string;
22
+ } | {
23
+ call: (input: I, options?: CallOptions & WaitOptions) => Promise<O>;
24
+ resume: (op: OperationRef, options?: WaitOptions) => Promise<O>;
25
+ method: ProcessMethod<I, O>;
26
+ state: "idle" | "running";
27
+ } | {
28
+ call: (input: I, options?: CallOptions & WaitOptions) => Promise<O>;
29
+ resume: (op: OperationRef, options?: WaitOptions) => Promise<O>;
30
+ method: ProcessMethod<I, O>;
31
+ state: "error";
32
+ error: unknown;
33
+ } | {
34
+ call: (input: I, options?: CallOptions & WaitOptions) => Promise<O>;
35
+ resume: (op: OperationRef, options?: WaitOptions) => Promise<O>;
36
+ method: ProcessMethod<I, O>;
37
+ state: "completed";
38
+ data: O;
39
+ };
@@ -0,0 +1,50 @@
1
+ 'use client';
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.useBoundMethod = useBoundMethod;
5
+ const react_1 = require("react");
6
+ const methods_1 = require("../methods");
7
+ /** No calls on mount. The caller owns the event that starts an operation. */
8
+ function useBoundMethod(method) {
9
+ const [view, setView] = (0, react_1.useState)();
10
+ const active = (0, react_1.useRef)(null);
11
+ (0, react_1.useEffect)(() => () => { active.current?.abort(); active.current = null; }, [method]);
12
+ const run = (0, react_1.useCallback)(async (execute, options) => {
13
+ if (active.current)
14
+ throw new Error('A call is already active in this hook');
15
+ const controller = new AbortController();
16
+ active.current = controller;
17
+ const abort = () => controller.abort(options.signal?.reason);
18
+ if (options.signal?.aborted)
19
+ abort();
20
+ options.signal?.addEventListener('abort', abort, { once: true });
21
+ const show = (result) => {
22
+ if (active.current === controller)
23
+ setView({ method, result });
24
+ };
25
+ show({ state: 'running' });
26
+ try {
27
+ const data = await execute({ ...options, signal: controller.signal, onConnectionRequired: async (step) => {
28
+ show(step);
29
+ await options.onConnectionRequired?.(step);
30
+ } });
31
+ show({ state: 'completed', data });
32
+ return data;
33
+ }
34
+ catch (error) {
35
+ if (error instanceof methods_1.ProcessMethodError && error.result.state === 'connection-required')
36
+ show(error.result);
37
+ else
38
+ show({ state: 'error', error });
39
+ throw error;
40
+ }
41
+ finally {
42
+ options.signal?.removeEventListener('abort', abort);
43
+ if (active.current === controller)
44
+ active.current = null;
45
+ }
46
+ }, [method]);
47
+ const call = (0, react_1.useCallback)((input, options = {}) => run(wait => (0, methods_1.callMethod)(method, input, { ...options, ...wait }), options), [method, run]);
48
+ const resume = (0, react_1.useCallback)((op, options = {}) => run(wait => (0, methods_1.resumeMethod)(method, op, wait), options), [method, run]);
49
+ return { ...(view?.method === method ? view.result : { state: 'idle' }), call, resume, method };
50
+ }
@@ -0,0 +1,5 @@
1
+ export * from './workflow';
2
+ export * from './methods';
3
+ export { installedMethod, handleMethodRequest } from './server';
4
+ export { createInstalledApp } from './app';
5
+ export type { InstalledAppOptions } from './app';
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.createInstalledApp = exports.handleMethodRequest = exports.installedMethod = void 0;
18
+ __exportStar(require("./workflow"), exports);
19
+ __exportStar(require("./methods"), exports);
20
+ var server_1 = require("./server");
21
+ Object.defineProperty(exports, "installedMethod", { enumerable: true, get: function () { return server_1.installedMethod; } });
22
+ Object.defineProperty(exports, "handleMethodRequest", { enumerable: true, get: function () { return server_1.handleMethodRequest; } });
23
+ var app_1 = require("./app");
24
+ Object.defineProperty(exports, "createInstalledApp", { enumerable: true, get: function () { return app_1.createInstalledApp; } });
@@ -0,0 +1,11 @@
1
+ import type { InstalledWorkflowOptions } from './workflow';
2
+ import type { MethodResult, OperationRef, ProcessMethod } from './methods';
3
+ export declare function installedMethod<I = unknown, O = unknown>(options: InstalledWorkflowOptions, responseMode?: 'direct' | 'async'): {
4
+ call: (input: I, options?: import("./methods").CallOptions & import("./methods").WaitOptions) => Promise<O>;
5
+ resume: (operation: OperationRef, options?: import("./methods").WaitOptions) => Promise<O>;
6
+ start(input: I, options?: import("./methods").CallOptions): Promise<MethodResult<O>>;
7
+ status(operation: OperationRef, signal?: AbortSignal): Promise<MethodResult<O>>;
8
+ consent(operation: OperationRef, signal?: AbortSignal): Promise<import("./workflow").InstalledWorkflowConsent>;
9
+ };
10
+ /** Invoke only after the host authenticates the request and binds one permitted method to that session. */
11
+ export declare function handleMethodRequest<I, O>(request: Request, method: ProcessMethod<I, O>): Promise<Response>;
package/dist/server.js ADDED
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.installedMethod = installedMethod;
4
+ exports.handleMethodRequest = handleMethodRequest;
5
+ const workflow_1 = require("./workflow");
6
+ const methods_1 = require("./methods");
7
+ function reference(op) {
8
+ return { kind: new URL(op.statusUrl).pathname.split('/').at(-2) === 'setup-operations' ? 'setup' : 'run', id: op.id };
9
+ }
10
+ function checkRef(value) {
11
+ const op = value;
12
+ if (!op || !['run', 'setup'].includes(String(op.kind)) || typeof op.id !== 'string' ||
13
+ !/^[\w-]{1,512}$/.test(op.id) || (op.kind === 'setup' && !/^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i.test(op.id))) {
14
+ throw new TypeError('Invalid operation reference');
15
+ }
16
+ }
17
+ function snapshot(body, operation) {
18
+ if (!body || typeof body !== 'object' || !('state' in body))
19
+ throw new Error('Invalid operation status');
20
+ const value = body;
21
+ switch (value.state) {
22
+ case 'succeeded': return { state: 'completed', data: value.settlement };
23
+ case 'waiting': {
24
+ const slot = value.slot;
25
+ return { state: 'connection-required', reason: 'waiting', operation,
26
+ ...(slot?.requirementId && { step: JSON.stringify([slot.requirementId, value.expectedRevision]) }) };
27
+ }
28
+ case 'interaction_required': return { state: 'interaction-required', operation, interaction: value.interaction };
29
+ case 'accepted':
30
+ case 'running':
31
+ case 'ready':
32
+ case 'dispatching':
33
+ case 'submitted': return { state: 'pending', operation };
34
+ case 'failed':
35
+ case 'canceled':
36
+ case 'cancelled':
37
+ case 'timed_out':
38
+ case 'expired':
39
+ return { state: 'failed', operation, reason: typeof value.reason === 'string' ? value.reason : value.state };
40
+ default: throw new Error('Unrecognized installed operation state');
41
+ }
42
+ }
43
+ function installedMethod(options, responseMode = 'direct') {
44
+ const workflow = (0, workflow_1.createInstalledWorkflow)(options);
45
+ return (0, methods_1.defineMethod)({
46
+ async start(input, call) {
47
+ const result = await workflow.invoke(input, { ...call, responseMode });
48
+ if (result.state === 'completed') {
49
+ const text = await result.response.text();
50
+ return { state: 'completed', data: text.length ? JSON.parse(text) : undefined };
51
+ }
52
+ if (result.state === 'accepted')
53
+ return { state: 'pending', operation: reference(result.operation) };
54
+ const { operation, ...step } = result;
55
+ return { ...step, ...(operation && { operation: reference(operation) }) };
56
+ },
57
+ async status(op, signal) {
58
+ checkRef(op);
59
+ const handle = op.kind === 'setup' ? workflow.setupOperation(op.id) : workflow.operation(op.id);
60
+ return snapshot(await handle.status(signal), op);
61
+ },
62
+ consent(op, signal) {
63
+ checkRef(op);
64
+ if (op.kind !== 'setup')
65
+ throw new TypeError('Consent requires a setup operation');
66
+ return workflow.setupOperation(op.id).consent(signal);
67
+ },
68
+ });
69
+ }
70
+ /** Invoke only after the host authenticates the request and binds one permitted method to that session. */
71
+ async function handleMethodRequest(request, method) {
72
+ const reply = (value, status = 200) => Response.json(value, { status, headers: { 'cache-control': 'no-store' } });
73
+ if (request.method !== 'POST')
74
+ return reply({ error: 'method-not-allowed' }, 405);
75
+ const origin = request.headers.get('origin');
76
+ if (origin && origin !== new URL(request.url).origin)
77
+ return reply({ error: 'invalid-origin' }, 403);
78
+ if (request.headers.get('content-type')?.split(';')[0]?.trim() !== 'application/json')
79
+ return reply({ error: 'expected-json' }, 415);
80
+ const body = await request.json().catch(() => null);
81
+ if (!body || typeof body !== 'object')
82
+ return reply({ error: 'invalid-request' }, 400);
83
+ try {
84
+ if (body.action === 'start') {
85
+ if (body.idempotencyKey !== undefined && (typeof body.idempotencyKey !== 'string' ||
86
+ !/^[\x21-\x7e]{1,256}$/.test(body.idempotencyKey)))
87
+ return reply({ error: 'invalid-idempotency-key' }, 400);
88
+ return reply(await method.start(body.input, { idempotencyKey: body.idempotencyKey, signal: request.signal }));
89
+ }
90
+ if (body.action !== 'status' && body.action !== 'consent')
91
+ return reply({ error: 'unknown-action' }, 400);
92
+ try {
93
+ checkRef(body.operation);
94
+ }
95
+ catch {
96
+ return reply({ error: 'invalid-operation' }, 400);
97
+ }
98
+ if (body.action === 'consent' && body.operation.kind !== 'setup')
99
+ return reply({ error: 'invalid-operation' }, 400);
100
+ return reply(await method[body.action](body.operation, request.signal));
101
+ }
102
+ catch (error) {
103
+ if (error instanceof workflow_1.InstalledWorkflowError)
104
+ return reply({ error: error.code ?? 'workflow-request-failed',
105
+ ...(error.settlement && { settlement: error.settlement }), ...(error.responseNotRetained && { responseNotRetained: true }) }, error.status);
106
+ if (request.signal.aborted)
107
+ throw error;
108
+ return reply({ error: 'workflow-unavailable' }, 502);
109
+ }
110
+ }
package/dist/url.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function trustedUrl(value: string): URL;
package/dist/url.js ADDED
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.trustedUrl = trustedUrl;
4
+ function trustedUrl(value) {
5
+ const url = new URL(value);
6
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
7
+ if ((url.protocol !== 'https:' && !(loopback && url.protocol === 'http:')) ||
8
+ url.username || url.password || url.href.includes('?') || url.href.includes('#')) {
9
+ throw new Error('Invalid installed workflow URL');
10
+ }
11
+ return url;
12
+ }
@@ -0,0 +1,103 @@
1
+ /** Server-side client for one published workflow in a consuming organization's app installation. */
2
+ export interface InstalledWorkflowOptions {
3
+ invokeUrl: string;
4
+ consentOrigin: string;
5
+ /** Defaults to the invocation origin. Set when Process serves operation URLs on a separate host. */
6
+ operationOrigin?: string;
7
+ getAccessToken: () => Promise<string> | string;
8
+ /** From the application's authenticated session. Omit for a signed-in Process member. */
9
+ externalUserId?: string;
10
+ }
11
+ export interface InstalledUserProfile {
12
+ displayName?: string;
13
+ email?: string;
14
+ metadata?: Record<string, string | number | boolean>;
15
+ }
16
+ export interface InstalledWorkflowCall {
17
+ idempotencyKey?: string;
18
+ responseMode?: 'direct' | 'async';
19
+ signal?: AbortSignal;
20
+ }
21
+ export interface InstalledWorkflowConsent {
22
+ installUrl: string;
23
+ confirmationCode: string;
24
+ expiresAt: string;
25
+ }
26
+ export type InstalledConnectionStatus = {
27
+ state: 'ready';
28
+ revision: number;
29
+ } | {
30
+ state: 'credential-required';
31
+ revision: number;
32
+ reasonCode: string;
33
+ };
34
+ export interface InstalledWorkflowOperation {
35
+ id: string;
36
+ statusUrl: string;
37
+ status(signal?: AbortSignal): Promise<unknown>;
38
+ /** Returns the authenticated SSE response. Supply the last event ID when reconnecting. */
39
+ events?: (options?: {
40
+ lastEventId?: string;
41
+ signal?: AbortSignal;
42
+ }) => Promise<Response>;
43
+ }
44
+ declare const setupIssues: readonly ["provider-not-oauth", "provider-not-personal", "workflow-scopes-missing", "provider-scopes-mismatch"];
45
+ export type InstalledWorkflowSetupIssue = typeof setupIssues[number];
46
+ export type InstalledWorkflowResult = {
47
+ state: 'completed';
48
+ response: Response;
49
+ } | {
50
+ state: 'accepted';
51
+ operation: InstalledWorkflowOperation;
52
+ } | {
53
+ state: 'connection-required';
54
+ reason: string;
55
+ setupIssue?: InstalledWorkflowSetupIssue;
56
+ operation?: InstalledWorkflowOperation;
57
+ consent?: InstalledWorkflowConsent;
58
+ };
59
+ declare const invocationErrorCodes: readonly ["AUTHENTICATION_REQUIRED", "NOT_FOUND", "SCOPE_DENIED", "APPROVAL_REQUIRED", "VERSION_UNAVAILABLE", "INVALID_ARGUMENTS", "LIMIT_EXCEEDED", "EXECUTION_REJECTED", "EXECUTION_FAILED", "TIMEOUT", "CANCELED", "CREDENTIAL_REQUIRED", "UNAVAILABLE"];
60
+ type InvocationErrorCode = typeof invocationErrorCodes[number];
61
+ export interface InstalledWorkflowSettlementError {
62
+ reason: 'invalid-success-settlement' | 'invalid-error-settlement';
63
+ upstreamStatus: number;
64
+ executionId?: string;
65
+ }
66
+ export declare class InstalledWorkflowError extends Error {
67
+ readonly status: number;
68
+ readonly code?: InvocationErrorCode | undefined;
69
+ readonly settlement?: InstalledWorkflowSettlementError | undefined;
70
+ readonly responseNotRetained: boolean;
71
+ constructor(status: number, code?: InvocationErrorCode | undefined, settlement?: InstalledWorkflowSettlementError | undefined, responseNotRetained?: boolean);
72
+ }
73
+ export declare function createInstalledWorkflow(options: InstalledWorkflowOptions): {
74
+ /** Provision the website user independently of provider consent or workflow execution.
75
+ * A supplied profile replaces this website's previous display profile. */
76
+ ensureUser(profile?: InstalledUserProfile, signal?: AbortSignal): Promise<{
77
+ instanceId: string;
78
+ }>;
79
+ /** Manage the signed-in user's account for one credential requirement in this publication. */
80
+ connection(requirementId: string): {
81
+ status: (signal?: AbortSignal) => Promise<InstalledConnectionStatus>;
82
+ consent: (expectedRevision: number, signal?: AbortSignal) => Promise<InstalledWorkflowConsent>;
83
+ disconnect: (expectedRevision: number, signal?: AbortSignal) => Promise<InstalledConnectionStatus>;
84
+ };
85
+ /** Read an existing execution using the current installation and caller. */
86
+ operation(id: string): InstalledWorkflowOperation;
87
+ /** Reattach from a server-side route after the browser returns from hosted consent. */
88
+ setupOperation(id: string, surface?: "rest" | "mcp"): {
89
+ consent(signal?: AbortSignal): Promise<InstalledWorkflowConsent>;
90
+ id: string;
91
+ statusUrl: string;
92
+ status(signal?: AbortSignal): Promise<unknown>;
93
+ /** Returns the authenticated SSE response. Supply the last event ID when reconnecting. */
94
+ events?: (options?: {
95
+ lastEventId?: string;
96
+ signal?: AbortSignal;
97
+ }) => Promise<Response>;
98
+ };
99
+ /** Decode an installed MCP tool result in the host. Only structuredContent is intended for the model. */
100
+ readMcpResult(reply: unknown): InstalledWorkflowResult;
101
+ invoke(args: unknown, call?: InstalledWorkflowCall): Promise<InstalledWorkflowResult>;
102
+ };
103
+ export {};