@process.co/sdk 0.0.0-bootstrap.0 → 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.
package/REACT.md ADDED
@@ -0,0 +1,97 @@
1
+ # Process for React
2
+
3
+ Use your application's signed-in session to call installed workflows. A method returns ordinary data and exposes React state for the parts of the page that care about progress, connection setup or failure. React 18.2 and 19 are supported.
4
+
5
+ ## JavaScript with React
6
+
7
+ Register the methods once around your app. Import the hook directly inside a component.
8
+
9
+ ```jsx
10
+ import { browserMethod } from '@process.co/sdk';
11
+ import { ProcessProvider, useProcessMethod } from '@process.co/sdk/react';
12
+
13
+ const methods = { inbox: browserMethod('/api/outlook/inbox') };
14
+
15
+ function InboxButton({ onMessages, onError }) {
16
+ const inbox = useProcessMethod('inbox');
17
+ async function load() {
18
+ try {
19
+ const { messages } = await inbox.call({ limit: 20 });
20
+ onMessages(messages);
21
+ } catch (error) { onError(error); }
22
+ }
23
+ return <button onClick={load} disabled={inbox.state === 'running'}>Load inbox</button>;
24
+ }
25
+
26
+ // Inside your signed-in app:
27
+ <ProcessProvider key={userId} methods={methods}>
28
+ <InboxButton onMessages={setMessages} onError={setError} />
29
+ </ProcessProvider>
30
+ ```
31
+
32
+ ## Typed methods and connection setup
33
+
34
+ The example uses one same-origin route per installed method. See the JavaScript package's `handleMethodRequest` example for the server half. The route authenticates the website user and binds the installation and workflow.
35
+
36
+ ```tsx
37
+ 'use client';
38
+ import { browserMethod } from '@process.co/sdk';
39
+ import { createProcessReact, ProcessConnectionForm } from '@process.co/sdk/react';
40
+
41
+ type Message = { id: string; subject: string };
42
+ const methods = {
43
+ 'outlook.inbox.list': browserMethod<{ limit: number }, { messages: Message[] }>('/api/outlook/inbox')
44
+ };
45
+ const { ProcessProvider, useProcessMethod } = createProcessReact<typeof methods>();
46
+
47
+ export function App({ userId }: { userId: string }) {
48
+ return <ProcessProvider key={userId} methods={methods}><Inbox /></ProcessProvider>;
49
+ }
50
+ function Inbox() {
51
+ const inbox = useProcessMethod('outlook.inbox.list');
52
+ async function load() {
53
+ try {
54
+ const { messages } = await inbox.call({ limit: 20 });
55
+ // messages can also feed another component, cache or search index.
56
+ } catch { /* The hook exposes the failure for rendering. */ }
57
+ }
58
+ if (inbox.state === 'connection-required')
59
+ return <ProcessConnectionForm step={inbox} consent={inbox.method.consent}>Connect Outlook</ProcessConnectionForm>;
60
+ if (inbox.state === 'error') return <p role="alert">Could not load your inbox.</p>;
61
+ return <>
62
+ <button disabled={inbox.state === 'running'} onClick={load}>Load inbox</button>
63
+ {inbox.state === 'completed' && inbox.data.messages.map(m => <p key={m.id}>{m.subject}</p>)}
64
+ </>;
65
+ }
66
+ ```
67
+
68
+ Here `outlook.inbox.list` is the host's key for a callable entry in the installed project's manifest. A project can expose several entries, each with its own input schema. The server binds each host route to a published capability ID. Short aliases such as `inbox` work as well. The component initiates a call from a user event. Use a stable method map and key the provider by signed-in user. Unmounting cancels the local wait. Pass `onOperation` to persist a receipt with its user, installation and method. After a navigation, `inbox.resume(receipt)` reads the original call. The connection form posts to the Process-hosted checklist in a separate tab and the original page continues observing. If Process cannot retain a call, the hook exposes the connection step and the promise rejects. The host can offer an explicit new call after setup.
69
+
70
+ ## Render a Process review card
71
+
72
+ Pass each server-issued card revision to `ProcessActionCard`. The host resolves the registered element and version to its trusted React control. For Outlook, use the declared draft or reply-draft control that wraps the shared Outlook compose surface. The SDK forwards the card's data, mode, execution state and allowed actions.
73
+
74
+ ```tsx
75
+ <ProcessActionCard
76
+ card={card}
77
+ resolveControl={p => controls.get(JSON.stringify([p.fern, p.elementVersion, p.uiKey]))}
78
+ onCommand={command => submitCardAction(command)}
79
+ fallback={<p>This item can be reviewed in Process.</p>}
80
+ />
81
+ ```
82
+
83
+ Here `controls` is the app's trusted registry and `submitCardAction` calls its authenticated backend. A command carries the card ID, reviewed revision, action ID and edited input. The server authorizes the user, revision and policy before executing a command. A receipt is read-only. The card component accepts updates from any host transport, including a stream that delivers complete card snapshots. The package does not provision an Outlook workflow, event subscription or agent.
84
+
85
+ ## Migrating from the development package
86
+
87
+ Replace the global Zustand initializer and `useAPI()` with a named method map and a provider per signed-in application tree. Plain JavaScript callers share those same methods. The previous development package's globals and environment helpers have no counterpart in this client. Pass application configuration through your own server and React context.
88
+
89
+ ## Outlook example routes
90
+
91
+ | Application entry point | Purpose |
92
+ | --- | --- |
93
+ | `/api/outlook/inbox` | Call the installed inbox method and return message data to any component. |
94
+ | `/api/outlook/draft-proposals` | Call the published proposal method and return a review card. |
95
+ | `/api/outlook/card-actions` | Submit the user's chosen action and reviewed revision to the server for a policy decision. |
96
+
97
+ These are URLs the example app defines. Bind the first two to their own published Process methods and signed-in session. Put card action handling behind its own authenticated route. Reconnecting and observing a receipt use the originating method route. Inbound provider events use the installation's event subscription and a separate delivery handler.
package/README.md CHANGED
@@ -1 +1,100 @@
1
- Install @process.co/sdk@next for the public developer preview.
1
+ # Process JavaScript SDK
2
+
3
+ Install the developer preview with `npm install @process.co/sdk@next`. Use the package root for plain JavaScript, `@process.co/sdk/react` for React components and hooks, and `@process.co/sdk/server` on the application server. [React example](./REACT.md)
4
+
5
+ ## Calling a method
6
+
7
+ Use `createInstalledApp` on your server. Select the published trigger by its capability key with `app.method(key)`. Bind one method to the installation selected by the backend and the user authenticated on this request. Process manages the provider's credential and refresh. The application supplies its Process caller token. These examples use the inbox method's published JSON shape.
8
+
9
+ ```js
10
+ import { createInstalledApp, handleMethodRequest } from '@process.co/sdk/server';
11
+
12
+ export async function POST(request) {
13
+ const session = await requireSession(request);
14
+ const app = createInstalledApp({
15
+ installationUrl: config.installedAppUrl,
16
+ consentOrigin: config.processConsentOrigin,
17
+ externalUserId: session.user.id,
18
+ getAccessToken: getProcessCallerToken
19
+ });
20
+ return handleMethodRequest(request, app.method(config.inboxCapabilityKey));
21
+ }
22
+ ```
23
+
24
+ To get data directly on the server, call `await app.method(config.inboxCapabilityKey).call({ limit: 20 })`. The input object follows that entry point’s published trigger schema. The host chooses the exposed keys. For an integration configured with a complete invocation URL, `installedMethod(options)` provides the same interface. To call that same bound method in a browser, use the same-origin application route. The browser sends the website session automatically.
25
+
26
+ ```js
27
+ import { browserMethod, createConnectionForm } from '@process.co/sdk';
28
+ const inbox = browserMethod('/api/outlook/inbox');
29
+ const { messages } = await inbox.call({ limit: 20 }, {
30
+ signal: AbortSignal.timeout(120_000),
31
+ onOperation: receipt => saveReceiptForSignedInUser('inbox', receipt),
32
+ onConnectionRequired: async step => {
33
+ const form = await createConnectionForm(inbox, step, { label: 'Connect Outlook' });
34
+ document.querySelector('#connection').replaceChildren(form);
35
+ }
36
+ });
37
+ document.querySelector('#connection').replaceChildren();
38
+ renderInbox(messages);
39
+ ```
40
+
41
+ The form posts a short-lived confirmation code to the Process-hosted checklist in a separate tab. It can obtain a fresh handoff for a retained setup step. Display handoffs only to the signed-in user. Process hosts the consent and checklist. After a reload call `await inbox.resume(receipt, options)` for the original request. Scope stored receipts to the signed-in user, method and installation. Aborting stops the caller's wait. For retryable network failures on submission, use the same `idempotencyKey` for the same logical request.
42
+
43
+ Without a connection handler, `call` rejects with `ProcessMethodError` and the recoverable step in `error.result`. A connection step without a receipt needs an explicit new call after setup. An approval or other workflow interaction is available as `interaction-required` with its receipt. For fully event-driven control, use `start`, `status` and `consent` directly. Pass `'async'` as the second argument of `installedMethod` for a workflow with published asynchronous execution. Use the lower-level client below for raw HTTP responses and SSE.
44
+
45
+ ## Python SDK contract
46
+
47
+ The package ships `conformance/v1.json` with JSON examples exercised by the JavaScript tests. A Python client can expose `await method.call(inputs)` and `await method.resume(receipt)`. Map a JSON response to Python values and an empty body to `None`. For a 428, retain the setup receipt and return the hosted handoff to the app. After consent, read that receipt under the same installation and subject until the original result settles. A missing receipt requires an explicit caller decision before resubmission. Keep execution failures, consent, and policy interactions distinct. The application bridge accepts `start`, `status` and `consent`; provider tokens stay server-side.
48
+
49
+ ## Low-level workflow client
50
+
51
+ Use this Node.js client on the application server that signs the user in. Configure the installed workflow invocation URL and the Process origin that hosts provider consent. Both come from the customer's installation.
52
+
53
+ ```ts
54
+ import { createInstalledWorkflow } from '@process.co/sdk/server';
55
+
56
+ const workflow = createInstalledWorkflow({
57
+ invokeUrl: config.installedWorkflowUrl,
58
+ consentOrigin: config.processConsentOrigin,
59
+ getAccessToken: () => getWebsiteCallerToken(),
60
+ externalUserId: session.user.id,
61
+ });
62
+
63
+ // In the website's sign-in handler, create or refresh the directory entry.
64
+ await workflow.ensureUser({
65
+ displayName: session.user.name,
66
+ email: session.user.email,
67
+ metadata: { storeId: merchant.storeId },
68
+ });
69
+ ```
70
+
71
+ The installation directory uses these fields for display and search. Repeated calls for the same website user return the same `instanceId`. Supply the full display profile when you update it. Calling `ensureUser()` preserves any previously supplied fields. Outlook consent can happen later, when the user chooses an action that needs their account.
72
+
73
+ ```ts
74
+ const result = await workflow.invoke({ invoiceId }, { idempotencyKey: requestId });
75
+ if (result.state === 'completed') return result.response.json();
76
+ if (result.state === 'connection-required' && result.consent) {
77
+ // Render a form to this signed-in user. POST confirmationCode to installUrl
78
+ // in a new browser tab so the user can review and authorize the account.
79
+ return renderConnectForm(result.consent);
80
+ }
81
+ ```
82
+
83
+ For a Process member acting directly, supply their Process session token through `getAccessToken` and omit `externalUserId`. A website backend supplies its own authorized token and takes the external ID from its authenticated session. A member can explicitly link a website identity to their installation user to use the same saved account through either entry point.
84
+
85
+ Use the same client to let that user manage a saved account from your website. Pass the `requirementId` from the installed workflow’s published credential requirements.
86
+
87
+ ```ts
88
+ const connection = workflow.connection(requirementId);
89
+ const status = await connection.status();
90
+ ```
91
+
92
+ When the user chooses to connect, call `connection.consent(status.revision)` and present its hosted form to that user. This sets up the account without starting a workflow. When they confirm disconnection, call `connection.disconnect(status.revision)` using the revision they reviewed. An HTTP 409 means the selection changed. Reload its status and let the user review the new selection. Disconnect applies to an account connected through the installation. The owner manages a separately selected personal account from their Process personal connections.
93
+
94
+ A connection response carries the platform's reason, such as `missing`, `disconnected`, or `scope-insufficient`. Send the confirmation code only to the user's form. If no hosted handoff is available, show the account action corresponding to the reason. Follow the returned operation to observe the original request.
95
+
96
+ For a workflow that publishes asynchronous execution, pass `responseMode: 'async'`. An accepted call returns `operation.status()` and, when the workflow publishes events, `operation.events({ signal, lastEventId })`. The latter returns the streaming HTTP response. Both methods get a fresh access token from the original caller's callback. When the installation serves operation URLs from a separate host, configure that Process host with `operationOrigin`.
97
+
98
+ From a Process monorepo checkout, run `pnpm --filter @process.co/sdk test`. The package builds with TypeScript and has no runtime dependencies.
99
+
100
+ A first-use consent response can include an `operation`. Keep its ID with the application request. After consent, Process dispatches the original invocation. Call `workflow.setupOperation(id).status()` or subscribe with `.events()` using the same authorized caller. If the user closes consent or another slot requires setup, call `workflow.setupOperation(id).consent()` on their next setup click. It issues a fresh handoff for the current slot while the request is waiting.
@@ -0,0 +1,33 @@
1
+ {
2
+ "version": 1,
3
+ "start": {
4
+ "status": 428,
5
+ "body": {
6
+ "error": {
7
+ "code": "CREDENTIAL_REQUIRED",
8
+ "details": {
9
+ "reasonCode": "disconnected",
10
+ "operation": {
11
+ "kind": "operation",
12
+ "operationId": "05eefbcf-f863-4611-94a9-4b55807c673e",
13
+ "statusUrl": "https://api.example.test/api/v1/organizations/shop/app-installations/merchant/rest/capabilities/inbox/setup-operations/05eefbcf-f863-4611-94a9-4b55807c673e"
14
+ }
15
+ }
16
+ }
17
+ }
18
+ },
19
+ "cases": [
20
+ { "status": { "state": "waiting", "slot": { "requirementId": "outlook" }, "expectedRevision": 1 }, "expected": "connection-required" },
21
+ { "status": { "state": "ready" }, "expected": "pending" },
22
+ { "status": { "state": "dispatching" }, "expected": "pending" },
23
+ { "status": { "state": "submitted" }, "expected": "pending" },
24
+ { "status": { "state": "running" }, "expected": "pending" },
25
+ { "status": { "state": "interaction_required", "interaction": { "kind": "approval" } }, "expected": "interaction-required" },
26
+ { "status": { "state": "succeeded", "settlement": { "messages": ["one"] } }, "expected": "completed" },
27
+ { "status": { "state": "failed", "reason": "VERSION_UNAVAILABLE" }, "expected": "failed" },
28
+ { "status": { "state": "expired" }, "expected": "failed" },
29
+ { "status": { "state": "timed_out" }, "expected": "failed" },
30
+ { "status": { "state": "canceled" }, "expected": "failed" },
31
+ { "status": { "state": "cancelled" }, "expected": "failed" }
32
+ ]
33
+ }
package/dist/app.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { InstalledWorkflowOptions } from './workflow';
2
+ export type InstalledAppOptions = Omit<InstalledWorkflowOptions, 'invokeUrl'> & {
3
+ installationUrl: string;
4
+ };
5
+ /** Bind the authenticated app user once per request, then select a published workflow entry by its capability ID. */
6
+ export declare function createInstalledApp({ installationUrl, ...caller }: InstalledAppOptions): {
7
+ method<Input = unknown, Output = unknown>(key: string, responseMode?: "direct" | "async"): {
8
+ call: (input: Input, options?: import("./methods").CallOptions & import("./methods").WaitOptions) => Promise<Output>;
9
+ resume: (operation: import("./methods").OperationRef, options?: import("./methods").WaitOptions) => Promise<Output>;
10
+ start(input: Input, options?: import("./methods").CallOptions): Promise<import("./methods").MethodResult<Output>>;
11
+ status(operation: import("./methods").OperationRef, signal?: AbortSignal): Promise<import("./methods").MethodResult<Output>>;
12
+ consent(operation: import("./methods").OperationRef, signal?: AbortSignal): Promise<import("./workflow").InstalledWorkflowConsent>;
13
+ };
14
+ };
package/dist/app.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createInstalledApp = createInstalledApp;
4
+ const server_1 = require("./server");
5
+ const url_1 = require("./url");
6
+ /** Bind the authenticated app user once per request, then select a published workflow entry by its capability ID. */
7
+ function createInstalledApp({ installationUrl, ...caller }) {
8
+ const base = (0, url_1.trustedUrl)(installationUrl);
9
+ if (!/^\/(?:api\/)?v1\/organizations\/[^/]+\/app-installations\/[^/]+\/?$/.test(base.pathname)) {
10
+ throw new TypeError('Expected an installed app URL');
11
+ }
12
+ const root = base.href.replace(/\/$/, '');
13
+ return {
14
+ method(key, responseMode = 'direct') {
15
+ if (typeof key !== 'string' || key.length === 0 || key.length > 256 || key.trim() !== key ||
16
+ key === '.' || key === '..' || /[\x00-\x1f\x7f]/u.test(key))
17
+ throw new TypeError('Invalid published method key');
18
+ return (0, server_1.installedMethod)({ ...caller, invokeUrl: root + '/capabilities/' + encodeURIComponent(key) + '/invoke' }, responseMode);
19
+ },
20
+ };
21
+ }
@@ -0,0 +1,16 @@
1
+ export { callMethod, resumeMethod, ProcessMethodError } from './methods';
2
+ export type { ProcessMethod, MethodResult, OperationRef, ConnectionStep } from './methods';
3
+ export declare class MethodRequestError extends Error {
4
+ readonly status: number;
5
+ readonly code: string;
6
+ constructor(status: number, code: string);
7
+ }
8
+ /** Use a same-origin application route backed by handleMethodRequest. Session cookies stay on that origin. */
9
+ export declare function browserMethod<I = unknown, O = unknown>(path: string): {
10
+ call: (input: I, options?: import("./methods").CallOptions & import("./methods").WaitOptions) => Promise<O>;
11
+ resume: (operation: import("./methods").OperationRef, options?: import("./methods").WaitOptions) => Promise<O>;
12
+ start(input: I, options?: import("./methods").CallOptions): Promise<import("./methods").MethodResult<O>>;
13
+ status(operation: import("./methods").OperationRef, signal?: AbortSignal): Promise<import("./methods").MethodResult<O>>;
14
+ consent(operation: import("./methods").OperationRef, signal?: AbortSignal): Promise<import("./workflow").InstalledWorkflowConsent>;
15
+ };
16
+ export { createConnectionForm } from './connection-form';
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createConnectionForm = exports.MethodRequestError = exports.ProcessMethodError = exports.resumeMethod = exports.callMethod = void 0;
4
+ exports.browserMethod = browserMethod;
5
+ const methods_1 = require("./methods");
6
+ var methods_2 = require("./methods");
7
+ Object.defineProperty(exports, "callMethod", { enumerable: true, get: function () { return methods_2.callMethod; } });
8
+ Object.defineProperty(exports, "resumeMethod", { enumerable: true, get: function () { return methods_2.resumeMethod; } });
9
+ Object.defineProperty(exports, "ProcessMethodError", { enumerable: true, get: function () { return methods_2.ProcessMethodError; } });
10
+ class MethodRequestError extends Error {
11
+ status;
12
+ code;
13
+ constructor(status, code) {
14
+ super(code);
15
+ this.status = status;
16
+ this.code = code;
17
+ this.name = 'MethodRequestError';
18
+ }
19
+ }
20
+ exports.MethodRequestError = MethodRequestError;
21
+ /** Use a same-origin application route backed by handleMethodRequest. Session cookies stay on that origin. */
22
+ function browserMethod(path) {
23
+ if (!path.startsWith('/') || path.startsWith('//') || /[\\?#\s]/.test(path))
24
+ throw new TypeError('Expected a same-origin route path');
25
+ async function post(body, signal) {
26
+ const response = await fetch(path, { method: 'POST', credentials: 'same-origin', redirect: 'error', cache: 'no-store',
27
+ headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal });
28
+ if (!response.ok) {
29
+ const details = await response.json().catch(() => null);
30
+ throw new MethodRequestError(response.status, typeof details?.error === 'string' ? details.error : 'method-request-failed');
31
+ }
32
+ return response.json();
33
+ }
34
+ return (0, methods_1.defineMethod)({
35
+ start: (input, options = {}) => post({ action: 'start', input, idempotencyKey: options.idempotencyKey }, options.signal),
36
+ status: (operation, signal) => post({ action: 'status', operation }, signal),
37
+ consent: (operation, signal) => post({ action: 'consent', operation }, signal),
38
+ });
39
+ }
40
+ var connection_form_1 = require("./connection-form");
41
+ Object.defineProperty(exports, "createConnectionForm", { enumerable: true, get: function () { return connection_form_1.createConnectionForm; } });
@@ -0,0 +1,7 @@
1
+ import type { ConnectionStep, ProcessMethod } from './methods';
2
+ /** Create a native HTML form for the Process-hosted account checklist. Mount it where the user should connect. */
3
+ export declare function createConnectionForm<I, O>(method: ProcessMethod<I, O>, step: ConnectionStep, options?: {
4
+ label?: string;
5
+ signal?: AbortSignal;
6
+ document?: Document;
7
+ }): Promise<HTMLFormElement>;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createConnectionForm = createConnectionForm;
4
+ /** Create a native HTML form for the Process-hosted account checklist. Mount it where the user should connect. */
5
+ async function createConnectionForm(method, step, options = {}) {
6
+ let handoff = step.consent;
7
+ if (!handoff || Date.parse(handoff.expiresAt) <= Date.now()) {
8
+ if (step.operation?.kind !== 'setup' || step.setupIssue)
9
+ throw new Error(step.setupIssue ?? step.reason);
10
+ handoff = await method.consent(step.operation, options.signal);
11
+ }
12
+ options.signal?.throwIfAborted();
13
+ const doc = options.document ?? document;
14
+ const form = doc.createElement('form');
15
+ form.method = 'post';
16
+ form.action = handoff.installUrl;
17
+ form.target = '_blank';
18
+ form.rel = 'noopener noreferrer';
19
+ const proof = doc.createElement('input');
20
+ proof.type = 'hidden';
21
+ proof.name = 'confirmationCode';
22
+ proof.value = handoff.confirmationCode;
23
+ const button = doc.createElement('button');
24
+ button.type = 'submit';
25
+ button.textContent = options.label ?? 'Connect account';
26
+ form.append(proof, button);
27
+ return form;
28
+ }
@@ -0,0 +1,3 @@
1
+ export { browserMethod, createConnectionForm, MethodRequestError } from './browser';
2
+ export * from './methods';
3
+ export type { InstalledWorkflowConsent } from './workflow';
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
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.MethodRequestError = exports.createConnectionForm = exports.browserMethod = void 0;
18
+ var browser_1 = require("./browser");
19
+ Object.defineProperty(exports, "browserMethod", { enumerable: true, get: function () { return browser_1.browserMethod; } });
20
+ Object.defineProperty(exports, "createConnectionForm", { enumerable: true, get: function () { return browser_1.createConnectionForm; } });
21
+ Object.defineProperty(exports, "MethodRequestError", { enumerable: true, get: function () { return browser_1.MethodRequestError; } });
22
+ __exportStar(require("./methods"), exports);
@@ -0,0 +1,63 @@
1
+ import type { InstalledWorkflowConsent } from './workflow';
2
+ export interface OperationRef {
3
+ kind: 'setup' | 'run';
4
+ id: string;
5
+ }
6
+ export interface CallOptions {
7
+ idempotencyKey?: string;
8
+ signal?: AbortSignal;
9
+ }
10
+ export type ConnectionStep = {
11
+ state: 'connection-required';
12
+ reason: string;
13
+ operation?: OperationRef;
14
+ consent?: InstalledWorkflowConsent;
15
+ step?: string;
16
+ setupIssue?: string;
17
+ };
18
+ export type MethodResult<T> = {
19
+ state: 'completed';
20
+ data: T;
21
+ } | {
22
+ state: 'pending';
23
+ operation: OperationRef;
24
+ } | ConnectionStep | {
25
+ state: 'interaction-required';
26
+ operation: OperationRef;
27
+ interaction: unknown;
28
+ } | {
29
+ state: 'failed';
30
+ operation: OperationRef;
31
+ reason: string;
32
+ };
33
+ /** Implemented by the server binding and by the same-origin browser transport. */
34
+ export interface ProcessMethod<Input, Output> {
35
+ start(input: Input, options?: CallOptions): Promise<MethodResult<Output>>;
36
+ status(operation: OperationRef, signal?: AbortSignal): Promise<MethodResult<Output>>;
37
+ consent(operation: OperationRef, signal?: AbortSignal): Promise<InstalledWorkflowConsent>;
38
+ }
39
+ export declare class ProcessMethodError extends Error {
40
+ readonly result: ConnectionStep | Extract<MethodResult<never>, {
41
+ state: 'interaction-required' | 'failed';
42
+ }>;
43
+ constructor(result: ConnectionStep | Extract<MethodResult<never>, {
44
+ state: 'interaction-required' | 'failed';
45
+ }>);
46
+ }
47
+ export interface WaitOptions {
48
+ signal?: AbortSignal;
49
+ pollIntervalMs?: number;
50
+ onOperation?: (operation: OperationRef) => void;
51
+ onConnectionRequired?: (step: ConnectionStep) => void | Promise<void>;
52
+ }
53
+ /** Invoke once. A connection callback can present hosted consent while this promise follows the receipt. */
54
+ export declare function callMethod<I, O>(method: ProcessMethod<I, O>, input: I, options?: CallOptions & WaitOptions): Promise<O>;
55
+ /** Observe an existing call after a reload, consent redirect, or interrupted wait. */
56
+ export declare function resumeMethod<I, O>(method: ProcessMethod<I, O>, operation: OperationRef, options?: WaitOptions): Promise<O>;
57
+ export declare function defineMethod<I, O>(transport: ProcessMethod<I, O>): {
58
+ call: (input: I, options?: CallOptions & WaitOptions) => Promise<O>;
59
+ resume: (operation: OperationRef, options?: WaitOptions) => Promise<O>;
60
+ start(input: I, options?: CallOptions): Promise<MethodResult<O>>;
61
+ status(operation: OperationRef, signal?: AbortSignal): Promise<MethodResult<O>>;
62
+ consent(operation: OperationRef, signal?: AbortSignal): Promise<InstalledWorkflowConsent>;
63
+ };
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProcessMethodError = void 0;
4
+ exports.callMethod = callMethod;
5
+ exports.resumeMethod = resumeMethod;
6
+ exports.defineMethod = defineMethod;
7
+ class ProcessMethodError extends Error {
8
+ result;
9
+ constructor(result) {
10
+ super(result.state === 'interaction-required' ? 'This operation needs interaction' : result.reason);
11
+ this.result = result;
12
+ this.name = 'ProcessMethodError';
13
+ }
14
+ }
15
+ exports.ProcessMethodError = ProcessMethodError;
16
+ function delay(ms, signal) {
17
+ return new Promise((resolve, reject) => {
18
+ signal?.throwIfAborted();
19
+ const stop = () => { clearTimeout(timer); reject(signal?.reason); };
20
+ const timer = setTimeout(() => { signal?.removeEventListener('abort', stop); resolve(); }, ms);
21
+ signal?.addEventListener('abort', stop, { once: true });
22
+ });
23
+ }
24
+ function interval(options) {
25
+ const ms = options.pollIntervalMs ?? 1000;
26
+ if (!Number.isSafeInteger(ms) || ms < 1 || ms > 2_147_483_647)
27
+ throw new RangeError('Invalid poll interval');
28
+ return ms;
29
+ }
30
+ async function settle(method, result, options) {
31
+ const ms = interval(options);
32
+ if (result.state !== 'completed' && result.operation)
33
+ options.onOperation?.(result.operation);
34
+ let lastStep;
35
+ let reportedConnection = false;
36
+ for (;;) {
37
+ options.signal?.throwIfAborted();
38
+ if (result.state === 'completed')
39
+ return result.data;
40
+ if (result.state === 'failed' || result.state === 'interaction-required')
41
+ throw new ProcessMethodError(result);
42
+ if (result.state === 'connection-required') {
43
+ if (!options.onConnectionRequired || !result.operation)
44
+ throw new ProcessMethodError(result);
45
+ // Initial handoffs have no slot identifier. The first status names that same slot.
46
+ if (!reportedConnection || (lastStep && result.step && result.step !== lastStep)) {
47
+ await options.onConnectionRequired(result);
48
+ }
49
+ reportedConnection = true;
50
+ lastStep = result.step ?? lastStep;
51
+ }
52
+ await delay(ms, options.signal);
53
+ result = await method.status(result.operation, options.signal);
54
+ }
55
+ }
56
+ /** Invoke once. A connection callback can present hosted consent while this promise follows the receipt. */
57
+ async function callMethod(method, input, options = {}) {
58
+ interval(options);
59
+ options.signal?.throwIfAborted();
60
+ return settle(method, await method.start(input, options), options);
61
+ }
62
+ /** Observe an existing call after a reload, consent redirect, or interrupted wait. */
63
+ async function resumeMethod(method, operation, options = {}) {
64
+ interval(options);
65
+ options.signal?.throwIfAborted();
66
+ return settle(method, await method.status(operation, options.signal), options);
67
+ }
68
+ function defineMethod(transport) {
69
+ return {
70
+ ...transport,
71
+ call: (input, options) => callMethod(transport, input, options),
72
+ resume: (operation, options) => resumeMethod(transport, operation, options),
73
+ };
74
+ }
@@ -0,0 +1,54 @@
1
+ import type { ComponentType, ReactNode } from 'react';
2
+ type ExecutionStatus = 'proposed' | 'awaiting-approval' | 'executing' | 'settlement-unknown' | 'succeeded' | 'failed' | 'denied' | 'cancelled';
3
+ interface Action {
4
+ id: string;
5
+ label: string;
6
+ }
7
+ export interface ActionCard<T> {
8
+ id: string;
9
+ revision?: number;
10
+ status: string;
11
+ title?: string;
12
+ data: T;
13
+ presentation: {
14
+ kind: string;
15
+ fern?: string;
16
+ elementVersion?: string;
17
+ uiKey?: string;
18
+ mode?: 'proposal' | 'receipt';
19
+ };
20
+ execution?: {
21
+ status: ExecutionStatus;
22
+ };
23
+ providerLifecycle?: {
24
+ state: string;
25
+ };
26
+ actions: readonly Action[];
27
+ }
28
+ export interface CardCommand<T> {
29
+ cardId: string;
30
+ revision: number;
31
+ actionId: string;
32
+ input: T;
33
+ }
34
+ export interface CardControlProps<T> {
35
+ value: T;
36
+ data: T;
37
+ title?: string;
38
+ mode: 'proposal' | 'receipt';
39
+ actions: readonly Action[];
40
+ execution?: ActionCard<T>['execution'];
41
+ readonly: boolean;
42
+ pending: boolean;
43
+ onChange(value: T): void;
44
+ onCommand(id: string): Promise<void>;
45
+ }
46
+ interface Props<T> {
47
+ card: ActionCard<T>;
48
+ resolveControl(presentation: ActionCard<T>['presentation']): ComponentType<CardControlProps<T>> | undefined;
49
+ onCommand(command: CardCommand<T>): Promise<void>;
50
+ fallback?: ReactNode;
51
+ }
52
+ /** A new server revision replaces local edits. The host resolves trusted, versioned renderers. */
53
+ export declare function ProcessActionCard<T>(props: Props<T>): import("react/jsx-runtime").JSX.Element;
54
+ export {};
@@ -0,0 +1,42 @@
1
+ 'use client';
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.ProcessActionCard = ProcessActionCard;
5
+ const jsx_runtime_1 = require("react/jsx-runtime");
6
+ const react_1 = require("react");
7
+ function Surface({ card, resolveControl, onCommand, fallback }) {
8
+ const [value, setValue] = (0, react_1.useState)(() => card.data);
9
+ const [busy, setBusy] = (0, react_1.useState)(false);
10
+ const [failed, setFailed] = (0, react_1.useState)(false);
11
+ const sending = (0, react_1.useRef)(false);
12
+ const Control = card.presentation.kind === 'element-control' ? resolveControl(card.presentation) : undefined;
13
+ if (!Control)
14
+ return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: fallback ?? (0, jsx_runtime_1.jsx)("p", { children: "Review unavailable for this card." }) });
15
+ const mode = card.presentation.mode ?? 'proposal';
16
+ const pending = busy || card.status === 'streaming' || card.execution?.status === 'executing';
17
+ const readonly = pending || card.status !== 'ready' || mode === 'receipt' || card.revision === undefined ||
18
+ card.providerLifecycle?.state === 'sent' || ['succeeded', 'denied', 'settlement-unknown', 'cancelled'].includes(card.execution?.status ?? '');
19
+ async function dispatch(actionId) {
20
+ if (readonly || sending.current || card.revision === undefined || !card.actions.some(action => action.id === actionId))
21
+ return;
22
+ sending.current = true;
23
+ setBusy(true);
24
+ setFailed(false);
25
+ try {
26
+ await onCommand({ cardId: card.id, revision: card.revision, actionId, input: value });
27
+ }
28
+ catch {
29
+ setFailed(true);
30
+ }
31
+ finally {
32
+ sending.current = false;
33
+ setBusy(false);
34
+ }
35
+ }
36
+ return (0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(Control, { value: value, data: value, title: card.title, mode: mode, actions: card.actions, execution: card.execution, pending: pending, readonly: readonly, onChange: next => { if (!readonly)
37
+ setValue(() => next); }, onCommand: dispatch }), failed && (0, jsx_runtime_1.jsx)("p", { role: "alert", children: "The action could not be completed." })] });
38
+ }
39
+ /** A new server revision replaces local edits. The host resolves trusted, versioned renderers. */
40
+ function ProcessActionCard(props) {
41
+ return (0, jsx_runtime_1.jsx)(Surface, { ...props }, JSON.stringify([props.card.id, props.card.revision, props.card.data]));
42
+ }
@@ -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 {};