@duct-sdk/sdk 0.1.6
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/README.md +92 -0
- package/dist/adapters/next/index.d.ts +4 -0
- package/dist/adapters/next/index.js +5 -0
- package/dist/adapters/next/receiver.d.ts +44 -0
- package/dist/adapters/next/receiver.js +162 -0
- package/dist/adapters/next/shell.d.ts +88 -0
- package/dist/adapters/next/shell.js +255 -0
- package/dist/adapters/react/index.d.ts +2 -0
- package/dist/adapters/react/index.js +4 -0
- package/dist/adapters/react/shell.d.ts +88 -0
- package/dist/adapters/react/shell.js +255 -0
- package/dist/adapters/remix/index.d.ts +2 -0
- package/dist/adapters/remix/index.js +4 -0
- package/dist/adapters/remix/receiver.d.ts +44 -0
- package/dist/adapters/remix/receiver.js +153 -0
- package/dist/adapters/sveltekit/index.d.ts +2 -0
- package/dist/adapters/sveltekit/index.js +4 -0
- package/dist/adapters/sveltekit/receiver.d.ts +56 -0
- package/dist/adapters/sveltekit/receiver.js +154 -0
- package/dist/adapters/vite/index.d.ts +2 -0
- package/dist/adapters/vite/index.js +4 -0
- package/dist/adapters/vite/receiver.d.ts +82 -0
- package/dist/adapters/vite/receiver.js +164 -0
- package/dist/assets/logo.d.ts +1 -0
- package/dist/assets/logo.js +1 -0
- package/dist/cli/agents/api-agent.d.ts +14 -0
- package/dist/cli/agents/api-agent.js +656 -0
- package/dist/cli/agents/auth-agent.d.ts +6 -0
- package/dist/cli/agents/auth-agent.js +198 -0
- package/dist/cli/agents/deeplink-agent.d.ts +6 -0
- package/dist/cli/agents/deeplink-agent.js +263 -0
- package/dist/cli/agents/llm.d.ts +33 -0
- package/dist/cli/agents/llm.js +276 -0
- package/dist/cli/agents/pipeline.d.ts +51 -0
- package/dist/cli/agents/pipeline.js +236 -0
- package/dist/cli/agents/reviewer-agent.d.ts +11 -0
- package/dist/cli/agents/reviewer-agent.js +442 -0
- package/dist/cli/agents/route-agent.d.ts +13 -0
- package/dist/cli/agents/route-agent.js +346 -0
- package/dist/cli/detectors/auth.d.ts +18 -0
- package/dist/cli/detectors/auth.js +273 -0
- package/dist/cli/detectors/framework.d.ts +22 -0
- package/dist/cli/detectors/framework.js +242 -0
- package/dist/cli/drift.d.ts +39 -0
- package/dist/cli/drift.js +247 -0
- package/dist/cli/fs/sandbox.d.ts +77 -0
- package/dist/cli/fs/sandbox.js +295 -0
- package/dist/cli/generators/config.d.ts +7 -0
- package/dist/cli/generators/config.js +255 -0
- package/dist/cli/generators/receiver.d.ts +12 -0
- package/dist/cli/generators/receiver.js +683 -0
- package/dist/cli/generators/shell.d.ts +18 -0
- package/dist/cli/generators/shell.js +672 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +603 -0
- package/dist/cli/init.d.ts +26 -0
- package/dist/cli/init.js +835 -0
- package/dist/core/action.d.ts +37 -0
- package/dist/core/action.js +140 -0
- package/dist/core/config.d.ts +514 -0
- package/dist/core/config.js +221 -0
- package/dist/core/endpoints.d.ts +17 -0
- package/dist/core/endpoints.js +128 -0
- package/dist/core/token.d.ts +70 -0
- package/dist/core/token.js +174 -0
- package/dist/core/types.d.ts +450 -0
- package/dist/core/types.js +11 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +9 -0
- package/package.json +84 -0
package/README.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# @duct-sdk/sdk
|
|
2
|
+
|
|
3
|
+
An intelligent execution shell for your product — lets humans and agents act on your backend without touching your UI.
|
|
4
|
+
|
|
5
|
+
> A shell (like terminal) that knows when to talk, when to show, and when to hand off.
|
|
6
|
+
|
|
7
|
+
- **Humans** type what they want, Duct executes it, navigates, or surfaces structured data inline.
|
|
8
|
+
- **Agents** get a permissioned, structured API surface — no scraping, no computer use.
|
|
9
|
+
|
|
10
|
+
Credentials and shell provisioning are managed by **duct**.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## Quickstart
|
|
15
|
+
|
|
16
|
+
**1. Create your account and get your API key**
|
|
17
|
+
|
|
18
|
+
**2. Authenticate:**
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npx @duct-sdk/sdk login
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
**3. Run setup in the root of your project:**
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npx @duct-sdk/sdk init
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
This scans your codebase, detects your API surface, and generates:
|
|
31
|
+
- `duct.config.ts` — your shell manifest
|
|
32
|
+
- A receiver route (`/duct/receive`) — handles deeplink handoffs
|
|
33
|
+
- A shell widget component — drop into your layout
|
|
34
|
+
|
|
35
|
+
**4. Push your manifest to Duct cloud:**
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npx @duct-sdk/sdk push
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
**5. Add the shell to your layout** (Next.js example):
|
|
42
|
+
|
|
43
|
+
```tsx
|
|
44
|
+
import { DuctShell } from '@duct-sdk/sdk/next';
|
|
45
|
+
|
|
46
|
+
export default function Layout({ children }) {
|
|
47
|
+
return (
|
|
48
|
+
<>
|
|
49
|
+
{children}
|
|
50
|
+
<DuctShell shellId={process.env.NEXT_PUBLIC_DUCT_SHELL_ID} />
|
|
51
|
+
</>
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## CLI Reference
|
|
59
|
+
|
|
60
|
+
| Command | Description |
|
|
61
|
+
|---|---|
|
|
62
|
+
| `npx @duct-sdk/sdk login` | Authenticate with your Duct API key |
|
|
63
|
+
| `npx @duct-sdk/sdk init` | Scan codebase and generate config + shell files |
|
|
64
|
+
| `npx @duct-sdk/sdk init --no-agents` | Skip AI scan and start from a blank template |
|
|
65
|
+
| `npx @duct-sdk/sdk push` | Push `duct.config.ts` manifest to Duct cloud |
|
|
66
|
+
| `npx @duct-sdk/sdk init --update` | Incremental re-scan against git diff |
|
|
67
|
+
| `npx @duct-sdk/sdk init --manual` | Generate a config template without LLM (instant) |
|
|
68
|
+
| `npx @duct-sdk/sdk scan` | Detect drift between live API and manifest |
|
|
69
|
+
|
|
70
|
+
Once installed globally (`npm i -g @duct-sdk/sdk`), all commands shorten to `duct login`, `duct init`, etc.
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
## Framework Support
|
|
75
|
+
|
|
76
|
+
| Framework | Import |
|
|
77
|
+
|---|---|
|
|
78
|
+
| Next.js (App Router) | `@duct-sdk/sdk/next` |
|
|
79
|
+
| Remix | `@duct-sdk/sdk/remix` |
|
|
80
|
+
| Vite | `@duct-sdk/sdk/vite` |
|
|
81
|
+
| SvelteKit | `@duct-sdk/sdk/sveltekit` |
|
|
82
|
+
| React Embed | `@duct-sdk/sdk/react` |
|
|
83
|
+
|
|
84
|
+
> Your API endpoints stay yours. Duct reads your manifest, routes intent, and calls your existing endpoints — nothing is proxied or stored.
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## Security
|
|
89
|
+
|
|
90
|
+
- Keep secrets server-side and never expose them in client code
|
|
91
|
+
- Use least privilege when marking actions as agent-accessible
|
|
92
|
+
- Store credentials in environment variables and rotate them in the Duct dashboard when needed
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @duct/sdk/next — Next.js adapter exports
|
|
3
|
+
// ============================================================
|
|
4
|
+
export { DuctReceiver } from "./receiver.js";
|
|
5
|
+
export { DuctShell, DuctShellButton } from "./shell.js";
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type NextRequest, NextResponse } from "next/server";
|
|
2
|
+
import type { DuctConfig, SessionContext } from "../../core/types.js";
|
|
3
|
+
export interface DuctReceiverOptions {
|
|
4
|
+
/** Your Duct config (import from duct.config.ts) */
|
|
5
|
+
config: DuctConfig;
|
|
6
|
+
/** HMAC secret key — use process.env.DUCT_SECRET_KEY */
|
|
7
|
+
secretKey: string;
|
|
8
|
+
/**
|
|
9
|
+
* Called when a valid deeplink token is received.
|
|
10
|
+
* Use this to pre-load data, set cookies, etc.
|
|
11
|
+
*/
|
|
12
|
+
onReceive: (deeplinkId: string, state: Record<string, unknown>, session: SessionContext) => Promise<ReceiverResult | void>;
|
|
13
|
+
/**
|
|
14
|
+
* Called when token verification fails.
|
|
15
|
+
* Optional — default behavior logs the error and returns 401.
|
|
16
|
+
*/
|
|
17
|
+
onError?: (error: Error, req: NextRequest) => NextResponse | Promise<NextResponse>;
|
|
18
|
+
}
|
|
19
|
+
export interface ReceiverResult {
|
|
20
|
+
/** Override the redirect URL (default: derived from config) */
|
|
21
|
+
redirectUrl?: string;
|
|
22
|
+
/** Additional data to include in the response */
|
|
23
|
+
data?: Record<string, unknown>;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Create a Next.js App Router POST handler for the Duct deeplink receiver.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```ts
|
|
30
|
+
* // app/api/duct/receive/route.ts
|
|
31
|
+
* import { DuctReceiver } from "@duct/sdk/next";
|
|
32
|
+
* import ductConfig from "../../../../duct.config";
|
|
33
|
+
*
|
|
34
|
+
* export const POST = DuctReceiver({
|
|
35
|
+
* config: ductConfig,
|
|
36
|
+
* secretKey: process.env.DUCT_SECRET_KEY!,
|
|
37
|
+
* async onReceive(deeplinkId, state, session) {
|
|
38
|
+
* // Pre-load data, set session cookies, etc.
|
|
39
|
+
* console.log("Deeplink received:", deeplinkId, state);
|
|
40
|
+
* },
|
|
41
|
+
* });
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export declare function DuctReceiver(options: DuctReceiverOptions): (request: NextRequest) => Promise<NextResponse>;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @duct/sdk — Next.js Deeplink Receiver
|
|
3
|
+
// Verifies Duct deeplink tokens for Next.js App Router
|
|
4
|
+
// ============================================================
|
|
5
|
+
import { NextResponse } from "next/server";
|
|
6
|
+
import { verifyDeeplinkToken } from "../../core/token.js";
|
|
7
|
+
import { getActiveApiBase } from "../../core/endpoints.js";
|
|
8
|
+
// ----------------------------------------------------------------
|
|
9
|
+
// Helpers
|
|
10
|
+
// ----------------------------------------------------------------
|
|
11
|
+
function buildDefaultRedirectUrl(targetRoute, state, baseUrl) {
|
|
12
|
+
let path = targetRoute;
|
|
13
|
+
// Replace path params [id] with state values
|
|
14
|
+
const paramMatches = [...targetRoute.matchAll(/\[([^\]]+)\]/g)];
|
|
15
|
+
const usedKeys = new Set();
|
|
16
|
+
for (const match of paramMatches) {
|
|
17
|
+
const paramName = match[1];
|
|
18
|
+
const value = state[paramName] ??
|
|
19
|
+
state[`${paramName}Id`] ??
|
|
20
|
+
state[`${paramName}_id`];
|
|
21
|
+
if (value !== undefined) {
|
|
22
|
+
path = path.replace(match[0], String(value));
|
|
23
|
+
usedKeys.add(paramName);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
// Append remaining state as query params
|
|
27
|
+
const queryEntries = Object.entries(state).filter(([key]) => !usedKeys.has(key) && state[key] !== undefined && state[key] !== null);
|
|
28
|
+
if (queryEntries.length > 0) {
|
|
29
|
+
const qs = new URLSearchParams(queryEntries.map(([k, v]) => [k, String(v)])).toString();
|
|
30
|
+
path += `?${qs}`;
|
|
31
|
+
}
|
|
32
|
+
// Normalize base URL
|
|
33
|
+
const base = baseUrl.replace(/\/$/, "");
|
|
34
|
+
return `${base}${path}`;
|
|
35
|
+
}
|
|
36
|
+
function buildSessionContext(sub, shellId) {
|
|
37
|
+
return {
|
|
38
|
+
sessionId: `dl_${Date.now()}_${Math.random().toString(36).slice(2)}`,
|
|
39
|
+
shellId,
|
|
40
|
+
user: { id: sub },
|
|
41
|
+
isAgent: false,
|
|
42
|
+
messages: [],
|
|
43
|
+
createdAt: new Date().toISOString(),
|
|
44
|
+
updatedAt: new Date().toISOString(),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
// ----------------------------------------------------------------
|
|
48
|
+
// DuctReceiver
|
|
49
|
+
// ----------------------------------------------------------------
|
|
50
|
+
/**
|
|
51
|
+
* Create a Next.js App Router POST handler for the Duct deeplink receiver.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```ts
|
|
55
|
+
* // app/api/duct/receive/route.ts
|
|
56
|
+
* import { DuctReceiver } from "@duct/sdk/next";
|
|
57
|
+
* import ductConfig from "../../../../duct.config";
|
|
58
|
+
*
|
|
59
|
+
* export const POST = DuctReceiver({
|
|
60
|
+
* config: ductConfig,
|
|
61
|
+
* secretKey: process.env.DUCT_SECRET_KEY!,
|
|
62
|
+
* async onReceive(deeplinkId, state, session) {
|
|
63
|
+
* // Pre-load data, set session cookies, etc.
|
|
64
|
+
* console.log("Deeplink received:", deeplinkId, state);
|
|
65
|
+
* },
|
|
66
|
+
* });
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
export function DuctReceiver(options) {
|
|
70
|
+
const { config, secretKey, onReceive, onError } = options;
|
|
71
|
+
return async function POST(request) {
|
|
72
|
+
// Validate secret key is configured
|
|
73
|
+
if (!secretKey) {
|
|
74
|
+
console.error("[Duct] DUCT_SECRET_KEY is not set");
|
|
75
|
+
return NextResponse.json({ error: "Server configuration error" }, { status: 500 });
|
|
76
|
+
}
|
|
77
|
+
// Extract token from Authorization header or request body
|
|
78
|
+
const authHeader = request.headers.get("authorization");
|
|
79
|
+
let token = null;
|
|
80
|
+
if (authHeader?.startsWith("Bearer ")) {
|
|
81
|
+
token = authHeader.slice(7);
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
try {
|
|
85
|
+
const body = await request.json();
|
|
86
|
+
token = body.token ?? null;
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return NextResponse.json({ error: "Invalid request body — expected JSON with token field" }, { status: 400 });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (!token) {
|
|
93
|
+
return NextResponse.json({ error: "No token provided. Include as Authorization: Bearer <token> or { token: '...' }" }, { status: 401 });
|
|
94
|
+
}
|
|
95
|
+
// Verify the deeplink token
|
|
96
|
+
const verifyResult = await verifyDeeplinkToken(token, {
|
|
97
|
+
secretKey,
|
|
98
|
+
expectedShellId: config.shellId,
|
|
99
|
+
});
|
|
100
|
+
if (!verifyResult.valid || !verifyResult.payload) {
|
|
101
|
+
const error = new Error(verifyResult.error ?? "Token verification failed");
|
|
102
|
+
console.warn("[Duct] Token verification failed:", verifyResult.error);
|
|
103
|
+
if (onError) {
|
|
104
|
+
return await onError(error, request);
|
|
105
|
+
}
|
|
106
|
+
return NextResponse.json({ error: "Invalid or expired token", detail: verifyResult.error }, { status: 401 });
|
|
107
|
+
}
|
|
108
|
+
const { deeplink_id, state, sub } = verifyResult.payload;
|
|
109
|
+
// Validate deeplink ID against our config
|
|
110
|
+
const deeplinkDef = config.deeplinks.find((d) => d.id === deeplink_id);
|
|
111
|
+
if (!deeplinkDef) {
|
|
112
|
+
console.warn("[Duct] Unknown deeplink ID:", deeplink_id);
|
|
113
|
+
return NextResponse.json({ error: `Unknown deeplink: "${deeplink_id}"` }, { status: 400 });
|
|
114
|
+
}
|
|
115
|
+
// Build session context
|
|
116
|
+
const session = buildSessionContext(sub, config.shellId);
|
|
117
|
+
session.user = { id: sub };
|
|
118
|
+
// Call user's onReceive handler
|
|
119
|
+
let customResult;
|
|
120
|
+
try {
|
|
121
|
+
customResult = await onReceive(deeplink_id, state, session);
|
|
122
|
+
}
|
|
123
|
+
catch (err) {
|
|
124
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
125
|
+
console.error("[Duct] onReceive handler threw:", error.message);
|
|
126
|
+
if (onError) {
|
|
127
|
+
return await onError(error, request);
|
|
128
|
+
}
|
|
129
|
+
return NextResponse.json({ error: "Internal server error in onReceive handler" }, { status: 500 });
|
|
130
|
+
}
|
|
131
|
+
// Determine redirect URL
|
|
132
|
+
const redirectUrl = customResult?.redirectUrl ??
|
|
133
|
+
buildDefaultRedirectUrl(deeplinkDef.targetRoute, state, config.product.baseUrl);
|
|
134
|
+
// Call Duct callback to confirm receipt
|
|
135
|
+
const ductApiBase = getActiveApiBase();
|
|
136
|
+
const ductApiKey = process.env["DUCT_API_KEY"];
|
|
137
|
+
if (ductApiKey) {
|
|
138
|
+
// Fire-and-forget — don't block the response on this
|
|
139
|
+
fetch(`${ductApiBase}/v1/deeplinks/${deeplink_id}/confirm`, {
|
|
140
|
+
method: "POST",
|
|
141
|
+
headers: {
|
|
142
|
+
"Content-Type": "application/json",
|
|
143
|
+
Authorization: `Bearer ${ductApiKey}`,
|
|
144
|
+
},
|
|
145
|
+
body: JSON.stringify({
|
|
146
|
+
shellId: config.shellId,
|
|
147
|
+
userId: sub,
|
|
148
|
+
redirectUrl,
|
|
149
|
+
}),
|
|
150
|
+
}).catch((err) => {
|
|
151
|
+
console.warn("[Duct] Could not confirm receipt:", err.message);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
return NextResponse.json({
|
|
155
|
+
success: true,
|
|
156
|
+
redirect: redirectUrl,
|
|
157
|
+
deeplinkId: deeplink_id,
|
|
158
|
+
userId: sub,
|
|
159
|
+
...(customResult?.data ?? {}),
|
|
160
|
+
});
|
|
161
|
+
};
|
|
162
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import React, { type CSSProperties } from "react";
|
|
2
|
+
export interface DuctShellProps {
|
|
3
|
+
/** Your Duct shell ID (e.g., "shell_acme_prod") */
|
|
4
|
+
shellId: string;
|
|
5
|
+
/**
|
|
6
|
+
* User context to pass to the shell as public metadata.
|
|
7
|
+
* Do NOT include sensitive data — this is not authenticated.
|
|
8
|
+
*/
|
|
9
|
+
userContext?: Record<string, string | number | boolean | null>;
|
|
10
|
+
/**
|
|
11
|
+
* Called when the Duct shell requests an auth token.
|
|
12
|
+
* Should call your /api/duct/token endpoint and return the JWT string.
|
|
13
|
+
* Return empty string for unauthenticated/guest users.
|
|
14
|
+
*/
|
|
15
|
+
onTokenRequest?: (shellId: string) => Promise<string>;
|
|
16
|
+
/** Called when the shell requests navigation to a URL (deeplink handoff) */
|
|
17
|
+
onNavigate?: (url: string) => void;
|
|
18
|
+
/** Controlled open state */
|
|
19
|
+
open?: boolean;
|
|
20
|
+
/** Called whenever shell open state changes */
|
|
21
|
+
onOpenChange?: (open: boolean) => void;
|
|
22
|
+
/** Whether the shell is initially open (default: false) */
|
|
23
|
+
defaultOpen?: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Duct shell host URL.
|
|
26
|
+
* For local dev: http://localhost:3000
|
|
27
|
+
* For production: https://shell.duct.sh
|
|
28
|
+
*/
|
|
29
|
+
shellHost?: string;
|
|
30
|
+
/**
|
|
31
|
+
* Position of the floating launcher.
|
|
32
|
+
* @default "bottom-right"
|
|
33
|
+
*/
|
|
34
|
+
position?: "bottom-right" | "bottom-left";
|
|
35
|
+
/**
|
|
36
|
+
* Panel width in pixels.
|
|
37
|
+
* @default 420
|
|
38
|
+
*/
|
|
39
|
+
panelWidth?: number;
|
|
40
|
+
/**
|
|
41
|
+
* Panel height in pixels.
|
|
42
|
+
* @default 640
|
|
43
|
+
*/
|
|
44
|
+
panelHeight?: number;
|
|
45
|
+
/** Override container styles (wrapper div). */
|
|
46
|
+
style?: CSSProperties;
|
|
47
|
+
className?: string;
|
|
48
|
+
/**
|
|
49
|
+
* Optional launcher icon source.
|
|
50
|
+
* When omitted, the SDK tries cloud-hosted icon first, then local /assets/logo.png.
|
|
51
|
+
*/
|
|
52
|
+
launcherIconSrc?: string;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* DuctShell — a self-contained floating launcher button + chat panel.
|
|
56
|
+
*
|
|
57
|
+
* Drop this anywhere in your layout. It renders:
|
|
58
|
+
* - A fixed bubble button (bottom-right by default)
|
|
59
|
+
* - A full-height chat panel that opens when clicked
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```tsx
|
|
63
|
+
* // app/layout.tsx
|
|
64
|
+
* <DuctShell
|
|
65
|
+
* shellId={process.env.DUCT_SHELL_ID!}
|
|
66
|
+
* shellHost={process.env.DUCT_SHELL_HOST}
|
|
67
|
+
* onTokenRequest={async () => {
|
|
68
|
+
* const res = await fetch("/api/duct/token", { method: "POST" });
|
|
69
|
+
* const { token } = await res.json();
|
|
70
|
+
* return token;
|
|
71
|
+
* }}
|
|
72
|
+
* />
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
export declare function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, open, onOpenChange, defaultOpen, shellHost, position, panelWidth, panelHeight, style, className, launcherIconSrc, }: DuctShellProps): React.ReactElement | null;
|
|
76
|
+
export interface DuctShellButtonProps {
|
|
77
|
+
shellId: string;
|
|
78
|
+
children?: React.ReactNode;
|
|
79
|
+
onToggle?: (open: boolean) => void;
|
|
80
|
+
className?: string;
|
|
81
|
+
style?: CSSProperties;
|
|
82
|
+
open?: boolean;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Headless launch button — use when you want a custom trigger.
|
|
86
|
+
* Pair with DuctShell in controlled mode.
|
|
87
|
+
*/
|
|
88
|
+
export declare function DuctShellButton({ children, onToggle, className, style, open: controlledOpen, }: DuctShellButtonProps): React.ReactElement | null;
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @shoryasethia/duct-sdk — DuctShell React Component
|
|
3
|
+
// Floating launcher + iframe panel with postMessage bridge
|
|
4
|
+
// ============================================================
|
|
5
|
+
"use client";
|
|
6
|
+
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
7
|
+
import { useEffect, useRef, useCallback, useState, } from "react";
|
|
8
|
+
// ----------------------------------------------------------------
|
|
9
|
+
// DuctShell — floating launcher + panel
|
|
10
|
+
// ----------------------------------------------------------------
|
|
11
|
+
const DUCT_SHELL_HOST_DEFAULT = (typeof process !== "undefined" && process.env?.["DUCT_SHELL_HOST"]) ||
|
|
12
|
+
"http://localhost:3000";
|
|
13
|
+
const DUCT_LAUNCHER_ICON_LOCAL_FALLBACK = "/assets/logo.png";
|
|
14
|
+
/**
|
|
15
|
+
* DuctShell — a self-contained floating launcher button + chat panel.
|
|
16
|
+
*
|
|
17
|
+
* Drop this anywhere in your layout. It renders:
|
|
18
|
+
* - A fixed bubble button (bottom-right by default)
|
|
19
|
+
* - A full-height chat panel that opens when clicked
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```tsx
|
|
23
|
+
* // app/layout.tsx
|
|
24
|
+
* <DuctShell
|
|
25
|
+
* shellId={process.env.DUCT_SHELL_ID!}
|
|
26
|
+
* shellHost={process.env.DUCT_SHELL_HOST}
|
|
27
|
+
* onTokenRequest={async () => {
|
|
28
|
+
* const res = await fetch("/api/duct/token", { method: "POST" });
|
|
29
|
+
* const { token } = await res.json();
|
|
30
|
+
* return token;
|
|
31
|
+
* }}
|
|
32
|
+
* />
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, open, onOpenChange, defaultOpen = false, shellHost = DUCT_SHELL_HOST_DEFAULT, position = "bottom-right", panelWidth = 420, panelHeight = 640, style, className, launcherIconSrc, }) {
|
|
36
|
+
const iframeRef = useRef(null);
|
|
37
|
+
const [isReady, setIsReady] = useState(false);
|
|
38
|
+
const [isOpen, setIsOpen] = useState(defaultOpen);
|
|
39
|
+
const [isAnimating, setIsAnimating] = useState(false);
|
|
40
|
+
const [iconCandidateIndex, setIconCandidateIndex] = useState(0);
|
|
41
|
+
const [iconLoadFailed, setIconLoadFailed] = useState(false);
|
|
42
|
+
const pendingTokenRequests = useRef(new Map());
|
|
43
|
+
const controlled = open !== undefined;
|
|
44
|
+
const panelOpen = controlled ? open : isOpen;
|
|
45
|
+
const shellUrl = buildShellUrl(shellHost, shellId, userContext);
|
|
46
|
+
const shellOrigin = (() => {
|
|
47
|
+
try {
|
|
48
|
+
return new URL(shellHost).origin;
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return shellHost;
|
|
52
|
+
}
|
|
53
|
+
})();
|
|
54
|
+
const iconCandidates = launcherIconSrc
|
|
55
|
+
? [launcherIconSrc]
|
|
56
|
+
: [`${shellOrigin}/duct-logo.png`, DUCT_LAUNCHER_ICON_LOCAL_FALLBACK];
|
|
57
|
+
const currentIconSrc = iconCandidates[Math.min(iconCandidateIndex, iconCandidates.length - 1)];
|
|
58
|
+
// Send a message to the iframe
|
|
59
|
+
const postToShell = useCallback((message) => {
|
|
60
|
+
iframeRef.current?.contentWindow?.postMessage(message, shellOrigin);
|
|
61
|
+
}, [shellOrigin]);
|
|
62
|
+
// Toggle open state
|
|
63
|
+
const setOpen = useCallback((next) => {
|
|
64
|
+
if (!controlled)
|
|
65
|
+
setIsOpen(next);
|
|
66
|
+
onOpenChange?.(next);
|
|
67
|
+
}, [controlled, onOpenChange]);
|
|
68
|
+
// Animate open
|
|
69
|
+
const openPanel = useCallback(() => {
|
|
70
|
+
setIsAnimating(true);
|
|
71
|
+
setOpen(true);
|
|
72
|
+
requestAnimationFrame(() => requestAnimationFrame(() => setIsAnimating(false)));
|
|
73
|
+
}, [setOpen]);
|
|
74
|
+
// Animate close
|
|
75
|
+
const closePanel = useCallback(() => {
|
|
76
|
+
setIsAnimating(true);
|
|
77
|
+
setTimeout(() => {
|
|
78
|
+
setOpen(false);
|
|
79
|
+
setIsAnimating(false);
|
|
80
|
+
}, 220);
|
|
81
|
+
}, [setOpen]);
|
|
82
|
+
// Handle inbound messages from the iframe
|
|
83
|
+
const handleMessage = useCallback(async (event) => {
|
|
84
|
+
if (event.origin !== shellOrigin)
|
|
85
|
+
return;
|
|
86
|
+
if (typeof event.data !== "object" || !event.data?.type)
|
|
87
|
+
return;
|
|
88
|
+
const msg = event.data;
|
|
89
|
+
switch (msg.type) {
|
|
90
|
+
case "DUCT_READY": {
|
|
91
|
+
setIsReady(true);
|
|
92
|
+
if (userContext && Object.keys(userContext).length > 0) {
|
|
93
|
+
postToShell({ type: "DUCT_USER_CONTEXT", context: userContext });
|
|
94
|
+
}
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
case "DUCT_REQUEST_TOKEN": {
|
|
98
|
+
const { requestId, shellId: reqShellId } = msg;
|
|
99
|
+
if (!onTokenRequest) {
|
|
100
|
+
postToShell({ type: "DUCT_TOKEN_RESPONSE", requestId, token: "" });
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
const token = await onTokenRequest(reqShellId);
|
|
105
|
+
postToShell({ type: "DUCT_TOKEN_RESPONSE", requestId, token: token ?? "" });
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
postToShell({ type: "DUCT_TOKEN_RESPONSE", requestId, token: "" });
|
|
109
|
+
}
|
|
110
|
+
pendingTokenRequests.current.delete(requestId);
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
case "DUCT_DEEPLINK_NAVIGATE": {
|
|
114
|
+
const { url } = msg;
|
|
115
|
+
if (onNavigate) {
|
|
116
|
+
onNavigate(url);
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
window.location.href = url;
|
|
120
|
+
}
|
|
121
|
+
postToShell({ type: "DUCT_NAVIGATE_CONFIRMED", url });
|
|
122
|
+
closePanel();
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
case "DUCT_OPEN": {
|
|
126
|
+
openPanel();
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
case "DUCT_CLOSE": {
|
|
130
|
+
closePanel();
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}, [shellOrigin, userContext, onTokenRequest, postToShell, onNavigate, openPanel, closePanel]);
|
|
135
|
+
useEffect(() => {
|
|
136
|
+
window.addEventListener("message", handleMessage);
|
|
137
|
+
return () => window.removeEventListener("message", handleMessage);
|
|
138
|
+
}, [handleMessage]);
|
|
139
|
+
useEffect(() => {
|
|
140
|
+
if (!isReady || !userContext)
|
|
141
|
+
return;
|
|
142
|
+
postToShell({ type: "DUCT_USER_CONTEXT", context: userContext });
|
|
143
|
+
}, [isReady, userContext, postToShell]);
|
|
144
|
+
// Sync controlled open
|
|
145
|
+
useEffect(() => {
|
|
146
|
+
if (open === undefined)
|
|
147
|
+
return;
|
|
148
|
+
if (open)
|
|
149
|
+
openPanel();
|
|
150
|
+
else
|
|
151
|
+
closePanel();
|
|
152
|
+
}, [open]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
153
|
+
useEffect(() => {
|
|
154
|
+
setIconCandidateIndex(0);
|
|
155
|
+
setIconLoadFailed(false);
|
|
156
|
+
}, [launcherIconSrc, shellOrigin]);
|
|
157
|
+
const handleIconError = useCallback(() => {
|
|
158
|
+
if (iconCandidateIndex < iconCandidates.length - 1) {
|
|
159
|
+
setIconCandidateIndex((prev) => prev + 1);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
setIconLoadFailed(true);
|
|
163
|
+
}, [iconCandidateIndex, iconCandidates.length]);
|
|
164
|
+
if (!shellId) {
|
|
165
|
+
console.error("[DuctShell] shellId prop is required");
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
const isRight = position === "bottom-right";
|
|
169
|
+
const panelVisible = panelOpen || isAnimating;
|
|
170
|
+
// Responsive: full-screen on small viewports
|
|
171
|
+
const panelStyle = {
|
|
172
|
+
position: "fixed",
|
|
173
|
+
bottom: "80px",
|
|
174
|
+
[isRight ? "right" : "left"]: "16px",
|
|
175
|
+
width: `min(${panelWidth}px, calc(100vw - 32px))`,
|
|
176
|
+
height: `min(${panelHeight}px, calc(100dvh - 96px))`,
|
|
177
|
+
zIndex: 9998,
|
|
178
|
+
borderRadius: "16px",
|
|
179
|
+
overflow: "hidden",
|
|
180
|
+
boxShadow: "0 24px 64px rgba(0,0,0,0.18), 0 8px 24px rgba(0,0,0,0.10)",
|
|
181
|
+
// Slide-in / slide-out animation
|
|
182
|
+
// Opens: slides up from below (translateY(100%) → translateY(0))
|
|
183
|
+
// Closes: slides back down
|
|
184
|
+
opacity: panelOpen && !isAnimating ? 1 : 0,
|
|
185
|
+
transform: panelOpen && !isAnimating
|
|
186
|
+
? "translateY(0)"
|
|
187
|
+
: "translateY(100%)",
|
|
188
|
+
transition: "opacity 220ms cubic-bezier(0.16,1,0.3,1), transform 0.25s cubic-bezier(0.16, 1, 0.3, 1)",
|
|
189
|
+
pointerEvents: panelOpen ? "auto" : "none",
|
|
190
|
+
visibility: panelVisible ? "visible" : "hidden",
|
|
191
|
+
...style,
|
|
192
|
+
};
|
|
193
|
+
const buttonStyle = {
|
|
194
|
+
position: "fixed",
|
|
195
|
+
bottom: "16px",
|
|
196
|
+
[isRight ? "right" : "left"]: "16px",
|
|
197
|
+
zIndex: 9999,
|
|
198
|
+
width: "56px",
|
|
199
|
+
height: "56px",
|
|
200
|
+
borderRadius: "50%",
|
|
201
|
+
border: "none",
|
|
202
|
+
cursor: "pointer",
|
|
203
|
+
display: "flex",
|
|
204
|
+
alignItems: "center",
|
|
205
|
+
justifyContent: "center",
|
|
206
|
+
backgroundColor: "#E8622A",
|
|
207
|
+
boxShadow: "0 4px 16px rgba(232,98,42,0.40), 0 2px 8px rgba(0,0,0,0.12)",
|
|
208
|
+
padding: 0,
|
|
209
|
+
transition: "transform 150ms ease, box-shadow 150ms ease",
|
|
210
|
+
};
|
|
211
|
+
return (_jsxs(_Fragment, { children: [!panelOpen && (_jsx("button", { type: "button", style: buttonStyle, onClick: openPanel, "aria-label": "Open Duct Shell", className: className, onMouseEnter: (e) => {
|
|
212
|
+
e.currentTarget.style.transform = "scale(1.07)";
|
|
213
|
+
e.currentTarget.style.boxShadow =
|
|
214
|
+
"0 6px 20px rgba(232,98,42,0.50), 0 2px 8px rgba(0,0,0,0.14)";
|
|
215
|
+
}, onMouseLeave: (e) => {
|
|
216
|
+
e.currentTarget.style.transform = "scale(1)";
|
|
217
|
+
e.currentTarget.style.boxShadow =
|
|
218
|
+
"0 4px 16px rgba(232,98,42,0.40), 0 2px 8px rgba(0,0,0,0.12)";
|
|
219
|
+
}, children: !iconLoadFailed ? (_jsx("img", { src: currentIconSrc, alt: "Duct", width: 28, height: 28, onError: handleIconError, style: { width: "28px", height: "28px", objectFit: "contain" } })) : (_jsx("svg", { width: "28", height: "28", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: _jsx("path", { d: "M18 12c0-3.3-2.2-5.5-5.5-5.5C9 6.5 7 8.7 7 12s2 5.5 5.5 5.5c2 0 3.6-.8 4.6-2.2l-2.2-1.6c-.6.8-1.4 1.3-2.4 1.3-1.6 0-2.8-1.2-2.8-3s1.2-3 2.8-3c1 0 1.8.5 2.3 1.3L18 12z", fill: "white" }) })) })), _jsx("div", { style: panelStyle, "data-duct-shell": shellId, children: _jsx("iframe", { ref: iframeRef, src: shellUrl, title: "Duct Shell", sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", allow: "clipboard-write", referrerPolicy: "no-referrer-when-downgrade", style: {
|
|
220
|
+
width: "100%",
|
|
221
|
+
height: "100%",
|
|
222
|
+
border: "none",
|
|
223
|
+
display: "block",
|
|
224
|
+
}, loading: "lazy" }) })] }));
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Headless launch button — use when you want a custom trigger.
|
|
228
|
+
* Pair with DuctShell in controlled mode.
|
|
229
|
+
*/
|
|
230
|
+
export function DuctShellButton({ children, onToggle, className, style, open: controlledOpen, }) {
|
|
231
|
+
const [internalOpen, setInternalOpen] = useState(false);
|
|
232
|
+
const isOpen = controlledOpen !== undefined ? controlledOpen : internalOpen;
|
|
233
|
+
const handleClick = useCallback(() => {
|
|
234
|
+
const next = !isOpen;
|
|
235
|
+
if (controlledOpen === undefined)
|
|
236
|
+
setInternalOpen(next);
|
|
237
|
+
onToggle?.(next);
|
|
238
|
+
}, [isOpen, controlledOpen, onToggle]);
|
|
239
|
+
return (_jsx("button", { type: "button", onClick: handleClick, className: className, style: style, "aria-label": isOpen ? "Close Duct Shell" : "Open Duct Shell", children: children ?? (isOpen ? "✕" : "Ask AI") }));
|
|
240
|
+
}
|
|
241
|
+
// ----------------------------------------------------------------
|
|
242
|
+
// Helpers
|
|
243
|
+
// ----------------------------------------------------------------
|
|
244
|
+
function buildShellUrl(shellHost, shellId, userContext) {
|
|
245
|
+
const base = shellHost.replace(/\/$/, "");
|
|
246
|
+
const url = new URL(`${base}/${shellId}`);
|
|
247
|
+
if (userContext) {
|
|
248
|
+
for (const [key, value] of Object.entries(userContext)) {
|
|
249
|
+
if (value !== null && value !== undefined) {
|
|
250
|
+
url.searchParams.set(`ctx_${key}`, String(value));
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return url.toString();
|
|
255
|
+
}
|