@ekanos/sdk 0.22.0 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -30
- package/api-report.md +13 -3
- package/dist/components/base-activation-dialog.js +2 -2
- package/dist/components/base-activation-dialog.js.map +1 -1
- package/dist/components/base-activation-form.d.ts +55 -20
- package/dist/components/base-activation-form.js +41 -12
- package/dist/components/base-activation-form.js.map +1 -1
- package/dist/components/base-marketplace-tile.js +2 -2
- package/dist/components/base-marketplace-tile.js.map +1 -1
- package/dist/components/index.d.ts +4 -3
- package/dist/components/index.js +2 -1
- package/dist/components/index.js.map +1 -1
- package/dist/components/oauth-activation-form.d.ts +3 -3
- package/dist/components/oauth-activation-form.js +5 -5
- package/dist/components/oauth-activation-form.js.map +1 -1
- package/dist/components/widgets/ai-prompt-chip.js +2 -2
- package/dist/components/widgets/ai-prompt-chip.js.map +1 -1
- package/dist/components/widgets/widget-ask-bar.js +1 -1
- package/dist/components/widgets/widget-ask-bar.js.map +1 -1
- package/dist/components/widgets/widget-query-state.d.ts +57 -0
- package/dist/components/widgets/widget-query-state.js +44 -0
- package/dist/components/widgets/widget-query-state.js.map +1 -0
- package/dist/components/widgets/widget-state-components.js +4 -4
- package/dist/components/widgets/widget-state-components.js.map +1 -1
- package/dist/components/widgets/widget.d.ts +29 -25
- package/dist/components/widgets/widget.js +35 -36
- package/dist/components/widgets/widget.js.map +1 -1
- package/dist/experience/client.d.ts +7 -5
- package/dist/experience/client.js +10 -8
- package/dist/experience/client.js.map +1 -1
- package/dist/experience/define-experience.d.ts +13 -1
- package/dist/experience/define-experience.js +13 -1
- package/dist/experience/define-experience.js.map +1 -1
- package/dist/experience/runtime.d.ts +15 -8
- package/dist/experience/runtime.js.map +1 -1
- package/dist/experience/server.d.ts +3 -2
- package/dist/experience/server.js +3 -2
- package/dist/experience/server.js.map +1 -1
- package/dist/hooks/use-oauth-connection-status.js +3 -1
- package/dist/hooks/use-oauth-connection-status.js.map +1 -1
- package/dist/integration/index.d.ts +1 -1
- package/dist/integration/index.js.map +1 -1
- package/dist/integration/types.d.ts +1 -1
- package/dist/integration/types.js.map +1 -1
- package/dist/types/integration.d.ts +5 -2
- package/dist/types/integration.js.map +1 -1
- package/eslint.design-rules.mjs +35 -160
- package/package.json +10 -10
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
import { createContext, createElement,
|
|
2
|
+
import { createContext, createElement, use } from 'react';
|
|
3
3
|
/**
|
|
4
4
|
* `@ekanos/sdk/experience/client` — the hooks an experience widget uses to
|
|
5
5
|
* reach an integration.
|
|
@@ -16,11 +16,11 @@ import { createContext, createElement, useContext, } from 'react';
|
|
|
16
16
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
17
17
|
const RuntimeContext = createContext(null);
|
|
18
18
|
export function ExperienceRuntimeProvider(props) {
|
|
19
|
-
return createElement(RuntimeContext
|
|
19
|
+
return createElement(RuntimeContext, { value: props.runtime }, props.children);
|
|
20
20
|
}
|
|
21
21
|
/** The runtime from the nearest provider; throws a pointed error without one. */
|
|
22
22
|
export function useExperienceRuntime() {
|
|
23
|
-
const runtime =
|
|
23
|
+
const runtime = use(RuntimeContext);
|
|
24
24
|
if (!runtime) {
|
|
25
25
|
throw new Error('useOperation needs an <ExperienceRuntimeProvider>. Under `ekanos dev` and in the host one is mounted for you; in a unit test wrap the widget in one.');
|
|
26
26
|
}
|
|
@@ -92,10 +92,12 @@ function splitArgs(args) {
|
|
|
92
92
|
return [args[0], undefined];
|
|
93
93
|
}
|
|
94
94
|
/**
|
|
95
|
-
* Run a WRITE operation
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
95
|
+
* Run a WRITE operation, an `action/<name>` or a write `tool/<name>`, as the
|
|
96
|
+
* person's own click: it runs directly, with their authority, and is audited.
|
|
97
|
+
* To ask for a second click, make the operation's input require
|
|
98
|
+
* `confirmed: z.literal(true)`; the runtime asks the person and the promise
|
|
99
|
+
* resolves once they answer (`write_not_approved` when they cancel). Workflows
|
|
100
|
+
* and agents do not use this path; they go through their own approval gate.
|
|
99
101
|
*/
|
|
100
102
|
export function useOperationMutation(integration, op, options) {
|
|
101
103
|
var _a;
|
|
@@ -104,7 +106,7 @@ export function useOperationMutation(integration, op, options) {
|
|
|
104
106
|
const invalidate = (_a = options === null || options === void 0 ? void 0 : options.invalidate) !== null && _a !== void 0 ? _a : 'integration';
|
|
105
107
|
const mutation = useMutation({
|
|
106
108
|
mutationFn: async (variables) => runtime.call(Object.assign({ integration,
|
|
107
|
-
op, input: variables.input, channel: '
|
|
109
|
+
op, input: variables.input, channel: 'interactive' }, (variables.approval ? { approval: variables.approval } : {}))),
|
|
108
110
|
onSuccess: async (result) => {
|
|
109
111
|
if (!result.ok || invalidate === false)
|
|
110
112
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/experience/client.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAEL,aAAa,EACb,aAAa,EACb,UAAU,GACX,MAAM,OAAO,CAAC;AAEf;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAkB9E,MAAM,cAAc,GAAG,aAAa,CAA2B,IAAI,CAAC,CAAC;AAErE,MAAM,UAAU,yBAAyB,CAAC,KAGzC;IACC,OAAO,aAAa,CAClB,cAAc,CAAC,QAAQ,EACvB,EAAE,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,EACxB,KAAK,CAAC,QAAQ,CACf,CAAC;AACJ,CAAC;AAED,iFAAiF;AACjF,MAAM,UAAU,oBAAoB;IAClC,MAAM,OAAO,GAAG,UAAU,CAAC,cAAc,CAAC,CAAC;IAC3C,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACb,sJAAsJ,CACvJ,CAAC;I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,\n createElement,\n useContext,\n} from 'react';\n\n/**\n * `@ekanos/sdk/experience/client` — the hooks an experience widget uses to\n * reach an integration.\n *\n * ```tsx\n * const headlines = useOperation('news', 'tool/get_headlines', { limit: 10 });\n * const save = useOperationMutation('news', 'tool/save_idea');\n * ```\n *\n * Both go through the {@link ExperienceRuntime} the host or the harness\n * supplies via {@link ExperienceRuntimeProvider}. They need a React Query\n * `QueryClientProvider` above them, as every `@ekanos/sdk/hooks` hook does.\n */\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport type {\n ApprovalToken,\n ExperienceRuntime,\n IntegrationInfo,\n} from './runtime';\nimport type {\n InputArgs,\n OperationError,\n OperationInput,\n OperationOutput,\n OperationResult,\n ReadOperationKey,\n IntegrationName,\n WriteOperationKey,\n} from './types';\n\nconst RuntimeContext = createContext<ExperienceRuntime | null>(null);\n\nexport function ExperienceRuntimeProvider(props: {\n runtime: ExperienceRuntime;\n children?: ReactNode;\n}) {\n return createElement(\n RuntimeContext.Provider,\n { value: props.runtime },\n props.children,\n );\n}\n\n/** The runtime from the nearest provider; throws a pointed error without one. */\nexport function useExperienceRuntime(): ExperienceRuntime {\n const runtime = useContext(RuntimeContext);\n if (!runtime) {\n throw new Error(\n 'useOperation needs an <ExperienceRuntimeProvider>. Under `ekanos dev` and in the host one is mounted for you; in a unit test wrap the widget in one.',\n );\n }\n\n return runtime;\n}\n\n/** Integration metadata (provenance, run mode) for badges; never for branching logic. */\nexport function useIntegrationInfo(): IntegrationInfo[] {\n return useExperienceRuntime().integrations();\n}\n\n/** A refused call surfaced through React Query: carries the typed refusal. */\nclass OperationCallError extends Error {\n readonly reason: OperationError['reason'];\n\n constructor(error: OperationError) {\n super(error.message);\n this.name = 'OperationCallError';\n this.reason = error.reason;\n }\n}\n\nfunction toOperationError(error: unknown): OperationError {\n if (error instanceof OperationCallError) {\n return { reason: error.reason, message: error.message };\n }\n\n return {\n reason: 'execution_failed',\n message: error instanceof Error ? error.message : 'The operation failed.',\n };\n}\n\nconst QUERY_ROOT = 'ekanos-operation';\n\nexport interface UseOperationOptions {\n enabled?: boolean;\n /** Milliseconds a result stays fresh. Default 30s. */\n staleTime?: number;\n refetchInterval?: number;\n}\n\nexport interface UseOperationResult<T> {\n data: T | undefined;\n error: OperationError | undefined;\n isPending: boolean;\n isFetching: boolean;\n refetch: () => Promise<unknown>;\n}\n\n/**\n * Read an operation. Only READ operations type-check here; a write is a\n * compile error (use {@link useOperationMutation}) and, if forced through,\n * a runtime refusal.\n */\nexport function useOperation<\n S extends IntegrationName,\n K extends ReadOperationKey<S>,\n>(\n integration: S,\n op: K,\n ...args: [...InputArgs<OperationInput<S, K>>, options?: UseOperationOptions]\n): UseOperationResult<OperationOutput<S, K>> {\n const runtime = useExperienceRuntime();\n const [input, options] = splitArgs(args);\n\n const query = useQuery({\n queryKey: [QUERY_ROOT, integration, op, input ?? null],\n enabled: options?.enabled ?? true,\n staleTime: options?.staleTime ?? 30_000,\n refetchInterval: options?.refetchInterval,\n queryFn: async () => {\n const result = await runtime.call({\n integration,\n op,\n input: input ?? {},\n channel: 'http',\n });\n if (!result.ok) throw new OperationCallError(result);\n\n return result.data as OperationOutput<S, K>;\n },\n retry: false,\n });\n\n return {\n data: query.data,\n error: query.error ? toOperationError(query.error) : undefined,\n isPending: query.isPending,\n isFetching: query.isFetching,\n refetch: query.refetch,\n };\n}\n\nfunction splitArgs(\n args: readonly unknown[],\n): [unknown, UseOperationOptions | undefined] {\n // `(input?, options?)`: options is recognisable as the trailing object with\n // an option key only when two args are given; one arg is always the input.\n if (args.length >= 2) {\n return [args[0], args[1] as UseOperationOptions | undefined];\n }\n\n return [args[0], undefined];\n}\n\nexport interface UseOperationMutationOptions {\n /**\n * What a successful write refreshes: this integration's reads (default), every\n * operation query, or nothing.\n */\n invalidate?: 'integration' | 'all' | false;\n}\n\nexport interface MutateOptions {\n /** A token the runtime minted earlier; normally absent (the runtime asks). */\n approval?: ApprovalToken;\n}\n\nexport interface UseOperationMutationResult<I, O> {\n /** Resolves with the typed result; a refusal is `{ ok: false, reason }`, never a throw. */\n mutate: (input: I, options?: MutateOptions) => Promise<OperationResult<O>>;\n isPending: boolean;\n data: OperationResult<O> | undefined;\n reset: () => void;\n}\n\n/**\n * Run a WRITE operation. The runtime decides whether a person must approve it\n * (the harness shows its approvals tray; the host runs its approval gate), and\n * the promise resolves once that is settled: `write_not_approved` when it was\n * rejected.\n */\nexport function useOperationMutation<\n S extends IntegrationName,\n K extends WriteOperationKey<S>,\n>(\n integration: S,\n op: K,\n options?: UseOperationMutationOptions,\n): UseOperationMutationResult<OperationInput<S, K>, OperationOutput<S, K>> {\n const runtime = useExperienceRuntime();\n const queryClient = useQueryClient();\n const invalidate = options?.invalidate ?? 'integration';\n\n const mutation = useMutation({\n mutationFn: async (variables: {\n input: unknown;\n approval?: ApprovalToken;\n }) =>\n runtime.call({\n integration,\n op,\n input: variables.input,\n channel: 'http',\n ...(variables.approval ? { approval: variables.approval } : {}),\n }),\n onSuccess: async (result) => {\n if (!result.ok || invalidate === false) return;\n await queryClient.invalidateQueries({\n queryKey:\n invalidate === 'all' ? [QUERY_ROOT] : [QUERY_ROOT, integration],\n });\n },\n });\n\n return {\n mutate: async (input, mutateOptions) =>\n (await mutation.mutateAsync({\n input,\n ...(mutateOptions?.approval\n ? { approval: mutateOptions.approval }\n : {}),\n })) as OperationResult<OperationOutput<S, K>>,\n isPending: mutation.isPending,\n data: mutation.data as OperationResult<OperationOutput<S, K>> | undefined,\n reset: mutation.reset,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/experience/client.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAkB,aAAa,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAE1E;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAkB9E,MAAM,c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CAAC,MAAM,QAAQ,CAAC,WAAW,iBACzB,KAAK,IACF,CAAC,CAAA,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,QAAQ;YACzB,CAAC,CAAC,EAAE,QAAQ,EAAE,aAAa,CAAC,QAAQ,EAAE;YACtC,CAAC,CAAC,EAAE,CAAC,EACP,CAA2C;QAC/C,SAAS,EAAE,QAAQ,CAAC,SAAS;QAC7B,IAAI,EAAE,QAAQ,CAAC,IAA0D;QACzE,KAAK,EAAE,QAAQ,CAAC,KAAK;KACtB,CAAC;AACJ,CAAC","sourcesContent":["'use client';\n\nimport { type ReactNode, createContext, createElement, use } from 'react';\n\n/**\n * `@ekanos/sdk/experience/client` — the hooks an experience widget uses to\n * reach an integration.\n *\n * ```tsx\n * const headlines = useOperation('news', 'tool/get_headlines', { limit: 10 });\n * const save = useOperationMutation('news', 'tool/save_idea');\n * ```\n *\n * Both go through the {@link ExperienceRuntime} the host or the harness\n * supplies via {@link ExperienceRuntimeProvider}. They need a React Query\n * `QueryClientProvider` above them, as every `@ekanos/sdk/hooks` hook does.\n */\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport type {\n ApprovalToken,\n ExperienceRuntime,\n IntegrationInfo,\n} from './runtime';\nimport type {\n InputArgs,\n OperationError,\n OperationInput,\n OperationOutput,\n OperationResult,\n ReadOperationKey,\n IntegrationName,\n WriteOperationKey,\n} from './types';\n\nconst RuntimeContext = createContext<ExperienceRuntime | null>(null);\n\nexport function ExperienceRuntimeProvider(props: {\n runtime: ExperienceRuntime;\n children?: ReactNode;\n}) {\n return createElement(\n RuntimeContext,\n { value: props.runtime },\n props.children,\n );\n}\n\n/** The runtime from the nearest provider; throws a pointed error without one. */\nexport function useExperienceRuntime(): ExperienceRuntime {\n const runtime = use(RuntimeContext);\n if (!runtime) {\n throw new Error(\n 'useOperation needs an <ExperienceRuntimeProvider>. Under `ekanos dev` and in the host one is mounted for you; in a unit test wrap the widget in one.',\n );\n }\n\n return runtime;\n}\n\n/** Integration metadata (provenance, run mode) for badges; never for branching logic. */\nexport function useIntegrationInfo(): IntegrationInfo[] {\n return useExperienceRuntime().integrations();\n}\n\n/** A refused call surfaced through React Query: carries the typed refusal. */\nclass OperationCallError extends Error {\n readonly reason: OperationError['reason'];\n\n constructor(error: OperationError) {\n super(error.message);\n this.name = 'OperationCallError';\n this.reason = error.reason;\n }\n}\n\nfunction toOperationError(error: unknown): OperationError {\n if (error instanceof OperationCallError) {\n return { reason: error.reason, message: error.message };\n }\n\n return {\n reason: 'execution_failed',\n message: error instanceof Error ? error.message : 'The operation failed.',\n };\n}\n\nconst QUERY_ROOT = 'ekanos-operation';\n\nexport interface UseOperationOptions {\n enabled?: boolean;\n /** Milliseconds a result stays fresh. Default 30s. */\n staleTime?: number;\n refetchInterval?: number;\n}\n\nexport interface UseOperationResult<T> {\n data: T | undefined;\n error: OperationError | undefined;\n isPending: boolean;\n isFetching: boolean;\n refetch: () => Promise<unknown>;\n}\n\n/**\n * Read an operation. Only READ operations type-check here; a write is a\n * compile error (use {@link useOperationMutation}) and, if forced through,\n * a runtime refusal.\n */\nexport function useOperation<\n S extends IntegrationName,\n K extends ReadOperationKey<S>,\n>(\n integration: S,\n op: K,\n ...args: [...InputArgs<OperationInput<S, K>>, options?: UseOperationOptions]\n): UseOperationResult<OperationOutput<S, K>> {\n const runtime = useExperienceRuntime();\n const [input, options] = splitArgs(args);\n\n const query = useQuery({\n queryKey: [QUERY_ROOT, integration, op, input ?? null],\n enabled: options?.enabled ?? true,\n staleTime: options?.staleTime ?? 30_000,\n refetchInterval: options?.refetchInterval,\n queryFn: async () => {\n const result = await runtime.call({\n integration,\n op,\n input: input ?? {},\n channel: 'http',\n });\n if (!result.ok) throw new OperationCallError(result);\n\n return result.data as OperationOutput<S, K>;\n },\n retry: false,\n });\n\n return {\n data: query.data,\n error: query.error ? toOperationError(query.error) : undefined,\n isPending: query.isPending,\n isFetching: query.isFetching,\n refetch: query.refetch,\n };\n}\n\nfunction splitArgs(\n args: readonly unknown[],\n): [unknown, UseOperationOptions | undefined] {\n // `(input?, options?)`: options is recognisable as the trailing object with\n // an option key only when two args are given; one arg is always the input.\n if (args.length >= 2) {\n return [args[0], args[1] as UseOperationOptions | undefined];\n }\n\n return [args[0], undefined];\n}\n\nexport interface UseOperationMutationOptions {\n /**\n * What a successful write refreshes: this integration's reads (default), every\n * operation query, or nothing.\n */\n invalidate?: 'integration' | 'all' | false;\n}\n\nexport interface MutateOptions {\n /** A token a runtime minted earlier; normally absent, a person's click needs none. */\n approval?: ApprovalToken;\n}\n\nexport interface UseOperationMutationResult<I, O> {\n /** Resolves with the typed result; a refusal is `{ ok: false, reason }`, never a throw. */\n mutate: (input: I, options?: MutateOptions) => Promise<OperationResult<O>>;\n isPending: boolean;\n data: OperationResult<O> | undefined;\n reset: () => void;\n}\n\n/**\n * Run a WRITE operation, an `action/<name>` or a write `tool/<name>`, as the\n * person's own click: it runs directly, with their authority, and is audited.\n * To ask for a second click, make the operation's input require\n * `confirmed: z.literal(true)`; the runtime asks the person and the promise\n * resolves once they answer (`write_not_approved` when they cancel). Workflows\n * and agents do not use this path; they go through their own approval gate.\n */\nexport function useOperationMutation<\n S extends IntegrationName,\n K extends WriteOperationKey<S>,\n>(\n integration: S,\n op: K,\n options?: UseOperationMutationOptions,\n): UseOperationMutationResult<OperationInput<S, K>, OperationOutput<S, K>> {\n const runtime = useExperienceRuntime();\n const queryClient = useQueryClient();\n const invalidate = options?.invalidate ?? 'integration';\n\n const mutation = useMutation({\n mutationFn: async (variables: {\n input: unknown;\n approval?: ApprovalToken;\n }) =>\n runtime.call({\n integration,\n op,\n input: variables.input,\n channel: 'interactive',\n ...(variables.approval ? { approval: variables.approval } : {}),\n }),\n onSuccess: async (result) => {\n if (!result.ok || invalidate === false) return;\n await queryClient.invalidateQueries({\n queryKey:\n invalidate === 'all' ? [QUERY_ROOT] : [QUERY_ROOT, integration],\n });\n },\n });\n\n return {\n mutate: async (input, mutateOptions) =>\n (await mutation.mutateAsync({\n input,\n ...(mutateOptions?.approval\n ? { approval: mutateOptions.approval }\n : {}),\n })) as OperationResult<OperationOutput<S, K>>,\n isPending: mutation.isPending,\n data: mutation.data as OperationResult<OperationOutput<S, K>> | undefined,\n reset: mutation.reset,\n };\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ComponentType } from 'react';
|
|
2
|
-
import { type SuggestedLayout } from '@ekanos/integration-schema';
|
|
2
|
+
import { type WidgetLayouts, type SuggestedLayout } from '@ekanos/integration-schema';
|
|
3
3
|
import type { ReadOperationKey, IntegrationName } from './types.js';
|
|
4
4
|
import type { WorkflowTemplate } from './workflow-template.js';
|
|
5
5
|
/**
|
|
@@ -29,7 +29,19 @@ export interface ExperienceWidget {
|
|
|
29
29
|
title: string;
|
|
30
30
|
/** Integrations this widget calls. Checked against `ekanos.json` `integrations` by `ekanos check`. */
|
|
31
31
|
integrations: readonly IntegrationName[];
|
|
32
|
+
/**
|
|
33
|
+
* How wide the card is. The simple form. Precedence when more than one is
|
|
34
|
+
* declared: `size`, then `layouts.lg.w`, then `width`.
|
|
35
|
+
*/
|
|
32
36
|
width?: ExperienceWidgetWidth;
|
|
37
|
+
/** Same as an integration widget's `size`; wins over `layouts` and `width`. */
|
|
38
|
+
size?: ExperienceWidgetWidth;
|
|
39
|
+
/**
|
|
40
|
+
* Same as an integration widget's `layouts`. The grid reads `lg.w` (over 6 is
|
|
41
|
+
* full, 3 or under is compact, otherwise half) and `lg.maxHeight`; `x`, `y`,
|
|
42
|
+
* `h` and the `md` / `sm` boxes are accepted but not used today.
|
|
43
|
+
*/
|
|
44
|
+
layouts?: WidgetLayouts;
|
|
33
45
|
/**
|
|
34
46
|
* A plain React component. It receives no integration props: it calls
|
|
35
47
|
* `useOperation` / `useOperationMutation` and renders with `@ekanos/ui`,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { EXPERIENCE_PAGE_KINDS, SuggestedLayoutSchema, surfaceProblems, } from '@ekanos/integration-schema';
|
|
1
|
+
import { EXPERIENCE_PAGE_KINDS, SuggestedLayoutSchema, widgetLayoutsSchema, widgetSizeSchema, surfaceProblems, } from '@ekanos/integration-schema';
|
|
2
2
|
const INTEGRATION_ONLY_KEYS = [
|
|
3
3
|
'oauth',
|
|
4
4
|
'egress',
|
|
@@ -73,6 +73,18 @@ export function defineExperience(input) {
|
|
|
73
73
|
if (!KEBAB.test(widget.id)) {
|
|
74
74
|
throw new Error(`Invalid experience definition: widget id "${widget.id}" must be kebab-case.`);
|
|
75
75
|
}
|
|
76
|
+
for (const key of ['width', 'size']) {
|
|
77
|
+
const value = widget[key];
|
|
78
|
+
if (value !== undefined && !widgetSizeSchema.safeParse(value).success) {
|
|
79
|
+
throw new Error(`Invalid experience definition: widget "${widget.id}" ${key} "${String(value)}" must be compact, half or full.`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (widget.layouts !== undefined) {
|
|
83
|
+
const parsed = widgetLayoutsSchema.safeParse(widget.layouts);
|
|
84
|
+
if (!parsed.success) {
|
|
85
|
+
throw new Error(`Invalid experience definition: widget "${widget.id}" layouts is malformed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ')}.`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
76
88
|
if (typeof widget.component !== 'function' &&
|
|
77
89
|
typeof widget.component !== 'object') {
|
|
78
90
|
throw new Error(`Invalid experience definition: widget "${widget.id}" needs a component.`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define-experience.js","sourceRoot":"","sources":["../../src/experience/define-experience.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EAGrB,eAAe,GAChB,MAAM,4BAA4B,CAAC;AA0BpC,MAAM,qBAAqB,GAAsB;IAC/C,OAAO;IACP,QAAQ;IACR,SAAS;IACT,UAAU;IACV,OAAO;IACP,SAAS;IACT,YAAY;IACZ,YAAY;IACZ,QAAQ;IACR,aAAa;IACb,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E,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACnD,KAAK,MAAM,IAAI,IAAI,UAAU,CAAC,KAAK;QACjC,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,YAAY;YAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACjD,KAAK,MAAM,OAAO,UAAI,MAAA,UAAU,CAAC,WAAW,0CAAE,QAAQ,mCAAI,EAAE;QAC1D,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;IAChC,KAAK,MAAM,QAAQ,IAAI,UAAU,CAAC,SAAS,EAAE,CAAC;QAC5C,KAAK,MAAM,CAAC,IAAI,QAAQ,CAAC,KAAK,EAAE;YAC9B,IAAI,CAAC,CAAC,IAAI,KAAK,MAAM;gBAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;IACnD,CAAC;IAED,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;AAC1B,CAAC","sourcesContent":["import type { ComponentType } from 'react';\n\nimport {\n EXPERIENCE_PAGE_KINDS,\n SuggestedLayoutSchema,\n type ExperiencePageKind,\n type SuggestedLayout,\n surfaceProblems,\n} from '@ekanos/integration-schema';\n\nimport type { ReadOperationKey, IntegrationName } from './types';\nimport type { WorkflowTemplate } from './workflow-template';\n\n/**\n * Keys that belong to an INTEGRATION and have no meaning on an experience.\n * Typed `never` so passing one is a compile error that names the key; the\n * runtime check in {@link defineExperience} catches the same keys from\n * untyped code.\n */\nexport interface IntegrationOnlyKeys {\n oauth?: never;\n egress?: never;\n storage?: never;\n webhooks?: never;\n tools?: never;\n actions?: never;\n connection?: never;\n activation?: never;\n events?: never;\n agentEvents?: never;\n schedules?: never;\n secrets?: never;\n}\n\nconst INTEGRATION_ONLY_KEYS: readonly string[] = [\n 'oauth',\n 'egress',\n 'storage',\n 'webhooks',\n 'tools',\n 'actions',\n 'connection',\n 'activation',\n 'events',\n 'agentEvents',\n 'schedules',\n 'secrets',\n];\n\nexport type ExperienceWidgetWidth = 'compact' | 'half' | 'full';\n\nexport interface ExperienceWidget {\n /** kebab-case, unique within the experience. */\n id: string;\n title: string;\n /** Integrations this widget calls. Checked against `ekanos.json` `integrations` by `ekanos check`. */\n integrations: readonly IntegrationName[];\n width?: ExperienceWidgetWidth;\n /**\n * A plain React component. It receives no integration props: it calls\n * `useOperation` / `useOperationMutation` and renders with `@ekanos/ui`,\n * exactly as an integration widget does today.\n */\n component: ComponentType;\n isCollapsible?: boolean;\n isPinnable?: boolean;\n aiFooterEnabled?: boolean;\n}\n\n/** What a custom page's component receives. */\nexport interface ExperiencePageProps {\n /**\n * The route below the page's own path, as segments: `[]` at the page itself,\n * `['archive']` at `<page path>/archive`. Only the sub-routes a page declares\n * in `routes` are served.\n */\n path: string[];\n}\n\nexport interface ExperiencePageRoute {\n /** kebab-case segments joined by `/`, relative to the page: `archive`, `drafts/new`. */\n path: string;\n title: string;\n}\n\ninterface ExperiencePageBase {\n /** kebab-case, unique within the experience. */\n id: string;\n title: string;\n}\n\n/**\n * The experience's root, shown when someone opens it. Give it a `component`\n * for a hand-built landing page, or none for the host's default overview.\n * An experience has at most one.\n */\nexport interface ExperienceOverviewPageInput extends ExperiencePageBase {\n kind: 'overview';\n path?: never;\n integrations?: readonly IntegrationName[];\n component?: ComponentType<ExperiencePageProps>;\n}\n\n/**\n * A widget dashboard of the experience's own widgets, laid out by the host.\n * No component: `widgets` lists widget ids declared in this experience.\n */\nexport interface ExperienceCanvasPageInput extends ExperiencePageBase {\n kind: 'canvas';\n /** Route segment under the experience, e.g. `review`. */\n path: string;\n widgets: readonly string[];\n integrations?: readonly IntegrationName[];\n component?: never;\n}\n\n/** A page you build yourself. `kind` may be left out: this is the default. */\nexport interface ExperienceCustomPageInput extends ExperiencePageBase {\n kind?: 'custom';\n /** Route segment under the experience, e.g. `review`. */\n path: string;\n /** Sub-routes the component handles; it reads the remainder from its `path` prop. */\n routes?: readonly ExperiencePageRoute[];\n integrations: readonly IntegrationName[];\n component: ComponentType<ExperiencePageProps>;\n}\n\nexport type ExperiencePageInput =\n | ExperienceOverviewPageInput\n | ExperienceCanvasPageInput\n | ExperienceCustomPageInput;\n\n/** A page as `defineExperience` returns it: `kind` and `integrations` always set. */\nexport type ExperiencePage =\n | (Omit<ExperienceOverviewPageInput, 'integrations'> & {\n integrations: readonly IntegrationName[];\n })\n | (Omit<ExperienceCanvasPageInput, 'integrations'> & {\n integrations: readonly IntegrationName[];\n })\n | (Omit<ExperienceCustomPageInput, 'kind'> & { kind: 'custom' });\n\n/**\n * A layout the experience suggests: workspaces (named groups of widgets and\n * pages) a Source admin can apply. Audiences are free-form NAMES, not roles or\n * permissions: a package cannot know a Source's audiences, so the host maps a\n * name to the Source's business type (level-1 audience) of the same name and\n * leaves an item with no match for everyone.\n */\nexport type ExperienceSuggestedLayout = SuggestedLayout;\n\n/** One reads-only section of the review queue; `read` must be a READ op of the integration. */\nexport type ReviewQueueSection = {\n [S in IntegrationName]: {\n id: string;\n integration: S;\n read: ReadOperationKey<S>;\n };\n}[IntegrationName];\n\nexport interface ExperienceReviewQueue {\n readsOnly: true;\n sections: readonly ReviewQueueSection[];\n}\n\n/** A declaration only: the host decides how the sidebar draws it. */\nexport interface ExperienceSidebar {\n section: string;\n icon: string;\n label: string;\n}\n\nexport interface ExperienceInput extends IntegrationOnlyKeys {\n /** kebab-case; must equal `slug` in `ekanos.json`. */\n slug: string;\n name: string;\n description?: string;\n sidebar?: ExperienceSidebar;\n widgets?: readonly ExperienceWidget[];\n pages?: readonly ExperiencePageInput[];\n workflows?: readonly WorkflowTemplate[];\n reviewQueue?: ExperienceReviewQueue;\n suggestedLayout?: ExperienceSuggestedLayout;\n}\n\nexport interface ExperienceDefinition {\n readonly kind: 'experience';\n readonly slug: string;\n readonly name: string;\n readonly description?: string;\n readonly sidebar?: ExperienceSidebar;\n readonly widgets: readonly ExperienceWidget[];\n readonly pages: readonly ExperiencePage[];\n readonly workflows: readonly WorkflowTemplate[];\n readonly reviewQueue?: ExperienceReviewQueue;\n readonly suggestedLayout?: ExperienceSuggestedLayout;\n}\n\nfunction normalizePage(page: ExperiencePageInput): ExperiencePage {\n const kind: ExperiencePageKind = page.kind ?? 'custom';\n const rawPath = (page as { path?: unknown }).path;\n if (kind === 'overview') {\n if (rawPath !== undefined) {\n throw new Error(\n `Invalid experience definition: overview page \"${page.id}\" is the experience's root and takes no path.`,\n );\n }\n } else if (typeof rawPath !== 'string' || rawPath === '') {\n throw new Error(\n `Invalid experience definition: page \"${page.id}\" needs a path (a kebab-case string).`,\n );\n }\n\n return {\n ...page,\n kind,\n integrations: page.integrations ?? [],\n } as ExperiencePage;\n}\n\nconst KEBAB = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\n\nfunction assertUnique(kind: string, ids: readonly string[]): void {\n const seen = new Set<string>();\n for (const id of ids) {\n if (seen.has(id)) {\n throw new Error(\n `Invalid experience definition: ${kind} id \"${id}\" is declared twice.`,\n );\n }\n seen.add(id);\n }\n}\n\n/**\n * Declare an experience: widgets, pages, workflow templates and a reads-only\n * review queue that reach integrations only through their pinned contracts.\n *\n * Integrations are NOT declared here. They live in `ekanos.json` `integrations` (readable\n * without running code) and `ekanos codegen` types them; naming an integration that is\n * not there is a compile error, and `ekanos check` re-verifies it.\n *\n * @example\n * export default defineExperience({\n * slug: 'content-engine',\n * name: 'Content engine',\n * widgets: [{ id: 'queue', title: 'Queue', integrations: ['cms'], component: Queue }],\n * });\n */\nexport function defineExperience(input: ExperienceInput): ExperienceDefinition {\n const raw = input as unknown as Record<string, unknown>;\n for (const key of INTEGRATION_ONLY_KEYS) {\n if (raw[key] !== undefined) {\n throw new Error(\n `Invalid experience definition: \"${key}\" belongs to an integration. An experience reaches integrations only through the integrations it declares (ekanos.json \"integrations\").`,\n );\n }\n }\n if (!KEBAB.test(input.slug)) {\n throw new Error(\n `Invalid experience definition: slug \"${input.slug}\" must be kebab-case.`,\n );\n }\n if (input.name.trim() === '') {\n throw new Error('Invalid experience definition: name is required.');\n }\n\n const widgets = input.widgets ?? [];\n const pages = input.pages ?? [];\n const workflows = input.workflows ?? [];\n\n for (const widget of widgets) {\n if (!KEBAB.test(widget.id)) {\n throw new Error(\n `Invalid experience definition: widget id \"${widget.id}\" must be kebab-case.`,\n );\n }\n if (\n typeof widget.component !== 'function' &&\n typeof widget.component !== 'object'\n ) {\n throw new Error(\n `Invalid experience definition: widget \"${widget.id}\" needs a component.`,\n );\n }\n }\n const normalizedPages = pages.map(normalizePage);\n for (const page of normalizedPages) {\n if (!(EXPERIENCE_PAGE_KINDS as readonly string[]).includes(page.kind)) {\n throw new Error(\n `Invalid experience definition: page \"${page.id}\" has kind \"${String(page.kind)}\"; use overview, canvas or custom.`,\n );\n }\n if (\n !KEBAB.test(page.id) ||\n (page.kind !== 'overview' && !KEBAB.test(page.path))\n ) {\n throw new Error(\n `Invalid experience definition: page \"${page.id}\" id and path must be kebab-case.`,\n );\n }\n const component = (page as { component?: unknown }).component;\n if (page.kind === 'canvas' && component !== undefined) {\n throw new Error(\n `Invalid experience definition: canvas page \"${page.id}\" takes \"widgets\", not a component.`,\n );\n }\n if (\n page.kind === 'custom' &&\n typeof component !== 'function' &&\n typeof component !== 'object'\n ) {\n throw new Error(\n `Invalid experience definition: page \"${page.id}\" needs a component.`,\n );\n }\n }\n if (input.suggestedLayout !== undefined) {\n const parsed = SuggestedLayoutSchema.safeParse(input.suggestedLayout);\n if (!parsed.success) {\n throw new Error(\n `Invalid experience definition: suggestedLayout is malformed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ')}.`,\n );\n }\n }\n const problems = surfaceProblems({\n widgets,\n pages: normalizedPages.map((page) => ({\n id: page.id,\n kind: page.kind,\n ...(page.kind === 'overview' ? {} : { path: page.path }),\n ...(page.kind === 'canvas' ? { widgets: page.widgets } : {}),\n ...(page.kind === 'custom' && page.routes ? { routes: page.routes } : {}),\n })),\n ...(input.suggestedLayout\n ? { suggestedLayout: input.suggestedLayout }\n : {}),\n });\n if (problems[0] !== undefined) {\n throw new Error(`Invalid experience definition: ${problems[0]}.`);\n }\n assertUnique(\n 'workflow template',\n workflows.map((w) => w.id),\n );\n\n if (input.reviewQueue) {\n if (input.reviewQueue.readsOnly !== true) {\n throw new Error(\n 'Invalid experience definition: reviewQueue.readsOnly must be true.',\n );\n }\n assertUnique(\n 'review queue section',\n input.reviewQueue.sections.map((s) => s.id),\n );\n }\n\n return Object.freeze({\n kind: 'experience' as const,\n slug: input.slug,\n name: input.name,\n ...(input.description === undefined\n ? {}\n : { description: input.description }),\n ...(input.sidebar === undefined ? {} : { sidebar: input.sidebar }),\n widgets: Object.freeze([...widgets]),\n pages: Object.freeze(normalizedPages),\n workflows: Object.freeze([...workflows]),\n ...(input.reviewQueue === undefined\n ? {}\n : { reviewQueue: input.reviewQueue }),\n ...(input.suggestedLayout === undefined\n ? {}\n : { suggestedLayout: input.suggestedLayout }),\n });\n}\n\n/** Integrations an experience definition touches, deduplicated (for `check`/manifest). */\nexport function slotsUsedBy(definition: ExperienceDefinition): string[] {\n const used = new Set<string>();\n for (const widget of definition.widgets)\n for (const s of widget.integrations) used.add(s);\n for (const page of definition.pages)\n for (const s of page.integrations) used.add(s);\n for (const section of definition.reviewQueue?.sections ?? [])\n used.add(section.integration);\n for (const template of definition.workflows) {\n for (const s of template.build())\n if (s.type === 'tool') used.add(s.integration);\n }\n\n return [...used].sort();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"define-experience.js","sourceRoot":"","sources":["../../src/experience/define-experience.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,mBAAmB,EACnB,gBAAgB,EAIhB,eAAe,GAChB,MAAM,4BAA4B,CAAC;AA0BpC,MAAM,qBAAqB,GAAsB;IAC/C,OAAO;IACP,QAAQ;IACR,SAAS;IACT,UAAU;IACV,OAAO;IACP,SAAS;IACT,YAAY;IACZ,YAAY;IACZ,QAAQ;IACR,a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I,UAAU,CAAC,SAAS,EAAE,CAAC;QAC5C,KAAK,MAAM,CAAC,IAAI,QAAQ,CAAC,KAAK,EAAE;YAC9B,IAAI,CAAC,CAAC,IAAI,KAAK,MAAM;gBAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;IACnD,CAAC;IAED,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;AAC1B,CAAC","sourcesContent":["import type { ComponentType } from 'react';\n\nimport {\n EXPERIENCE_PAGE_KINDS,\n SuggestedLayoutSchema,\n widgetLayoutsSchema,\n widgetSizeSchema,\n type ExperiencePageKind,\n type WidgetLayouts,\n type SuggestedLayout,\n surfaceProblems,\n} from '@ekanos/integration-schema';\n\nimport type { ReadOperationKey, IntegrationName } from './types';\nimport type { WorkflowTemplate } from './workflow-template';\n\n/**\n * Keys that belong to an INTEGRATION and have no meaning on an experience.\n * Typed `never` so passing one is a compile error that names the key; the\n * runtime check in {@link defineExperience} catches the same keys from\n * untyped code.\n */\nexport interface IntegrationOnlyKeys {\n oauth?: never;\n egress?: never;\n storage?: never;\n webhooks?: never;\n tools?: never;\n actions?: never;\n connection?: never;\n activation?: never;\n events?: never;\n agentEvents?: never;\n schedules?: never;\n secrets?: never;\n}\n\nconst INTEGRATION_ONLY_KEYS: readonly string[] = [\n 'oauth',\n 'egress',\n 'storage',\n 'webhooks',\n 'tools',\n 'actions',\n 'connection',\n 'activation',\n 'events',\n 'agentEvents',\n 'schedules',\n 'secrets',\n];\n\nexport type ExperienceWidgetWidth = 'compact' | 'half' | 'full';\n\nexport interface ExperienceWidget {\n /** kebab-case, unique within the experience. */\n id: string;\n title: string;\n /** Integrations this widget calls. Checked against `ekanos.json` `integrations` by `ekanos check`. */\n integrations: readonly IntegrationName[];\n /**\n * How wide the card is. The simple form. Precedence when more than one is\n * declared: `size`, then `layouts.lg.w`, then `width`.\n */\n width?: ExperienceWidgetWidth;\n /** Same as an integration widget's `size`; wins over `layouts` and `width`. */\n size?: ExperienceWidgetWidth;\n /**\n * Same as an integration widget's `layouts`. The grid reads `lg.w` (over 6 is\n * full, 3 or under is compact, otherwise half) and `lg.maxHeight`; `x`, `y`,\n * `h` and the `md` / `sm` boxes are accepted but not used today.\n */\n layouts?: WidgetLayouts;\n /**\n * A plain React component. It receives no integration props: it calls\n * `useOperation` / `useOperationMutation` and renders with `@ekanos/ui`,\n * exactly as an integration widget does today.\n */\n component: ComponentType;\n isCollapsible?: boolean;\n isPinnable?: boolean;\n aiFooterEnabled?: boolean;\n}\n\n/** What a custom page's component receives. */\nexport interface ExperiencePageProps {\n /**\n * The route below the page's own path, as segments: `[]` at the page itself,\n * `['archive']` at `<page path>/archive`. Only the sub-routes a page declares\n * in `routes` are served.\n */\n path: string[];\n}\n\nexport interface ExperiencePageRoute {\n /** kebab-case segments joined by `/`, relative to the page: `archive`, `drafts/new`. */\n path: string;\n title: string;\n}\n\ninterface ExperiencePageBase {\n /** kebab-case, unique within the experience. */\n id: string;\n title: string;\n}\n\n/**\n * The experience's root, shown when someone opens it. Give it a `component`\n * for a hand-built landing page, or none for the host's default overview.\n * An experience has at most one.\n */\nexport interface ExperienceOverviewPageInput extends ExperiencePageBase {\n kind: 'overview';\n path?: never;\n integrations?: readonly IntegrationName[];\n component?: ComponentType<ExperiencePageProps>;\n}\n\n/**\n * A widget dashboard of the experience's own widgets, laid out by the host.\n * No component: `widgets` lists widget ids declared in this experience.\n */\nexport interface ExperienceCanvasPageInput extends ExperiencePageBase {\n kind: 'canvas';\n /** Route segment under the experience, e.g. `review`. */\n path: string;\n widgets: readonly string[];\n integrations?: readonly IntegrationName[];\n component?: never;\n}\n\n/** A page you build yourself. `kind` may be left out: this is the default. */\nexport interface ExperienceCustomPageInput extends ExperiencePageBase {\n kind?: 'custom';\n /** Route segment under the experience, e.g. `review`. */\n path: string;\n /** Sub-routes the component handles; it reads the remainder from its `path` prop. */\n routes?: readonly ExperiencePageRoute[];\n integrations: readonly IntegrationName[];\n component: ComponentType<ExperiencePageProps>;\n}\n\nexport type ExperiencePageInput =\n | ExperienceOverviewPageInput\n | ExperienceCanvasPageInput\n | ExperienceCustomPageInput;\n\n/** A page as `defineExperience` returns it: `kind` and `integrations` always set. */\nexport type ExperiencePage =\n | (Omit<ExperienceOverviewPageInput, 'integrations'> & {\n integrations: readonly IntegrationName[];\n })\n | (Omit<ExperienceCanvasPageInput, 'integrations'> & {\n integrations: readonly IntegrationName[];\n })\n | (Omit<ExperienceCustomPageInput, 'kind'> & { kind: 'custom' });\n\n/**\n * A layout the experience suggests: workspaces (named groups of widgets and\n * pages) a Source admin can apply. Audiences are free-form NAMES, not roles or\n * permissions: a package cannot know a Source's audiences, so the host maps a\n * name to the Source's business type (level-1 audience) of the same name and\n * leaves an item with no match for everyone.\n */\nexport type ExperienceSuggestedLayout = SuggestedLayout;\n\n/** One reads-only section of the review queue; `read` must be a READ op of the integration. */\nexport type ReviewQueueSection = {\n [S in IntegrationName]: {\n id: string;\n integration: S;\n read: ReadOperationKey<S>;\n };\n}[IntegrationName];\n\nexport interface ExperienceReviewQueue {\n readsOnly: true;\n sections: readonly ReviewQueueSection[];\n}\n\n/** A declaration only: the host decides how the sidebar draws it. */\nexport interface ExperienceSidebar {\n section: string;\n icon: string;\n label: string;\n}\n\nexport interface ExperienceInput extends IntegrationOnlyKeys {\n /** kebab-case; must equal `slug` in `ekanos.json`. */\n slug: string;\n name: string;\n description?: string;\n sidebar?: ExperienceSidebar;\n widgets?: readonly ExperienceWidget[];\n pages?: readonly ExperiencePageInput[];\n workflows?: readonly WorkflowTemplate[];\n reviewQueue?: ExperienceReviewQueue;\n suggestedLayout?: ExperienceSuggestedLayout;\n}\n\nexport interface ExperienceDefinition {\n readonly kind: 'experience';\n readonly slug: string;\n readonly name: string;\n readonly description?: string;\n readonly sidebar?: ExperienceSidebar;\n readonly widgets: readonly ExperienceWidget[];\n readonly pages: readonly ExperiencePage[];\n readonly workflows: readonly WorkflowTemplate[];\n readonly reviewQueue?: ExperienceReviewQueue;\n readonly suggestedLayout?: ExperienceSuggestedLayout;\n}\n\nfunction normalizePage(page: ExperiencePageInput): ExperiencePage {\n const kind: ExperiencePageKind = page.kind ?? 'custom';\n const rawPath = (page as { path?: unknown }).path;\n if (kind === 'overview') {\n if (rawPath !== undefined) {\n throw new Error(\n `Invalid experience definition: overview page \"${page.id}\" is the experience's root and takes no path.`,\n );\n }\n } else if (typeof rawPath !== 'string' || rawPath === '') {\n throw new Error(\n `Invalid experience definition: page \"${page.id}\" needs a path (a kebab-case string).`,\n );\n }\n\n return {\n ...page,\n kind,\n integrations: page.integrations ?? [],\n } as ExperiencePage;\n}\n\nconst KEBAB = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\n\nfunction assertUnique(kind: string, ids: readonly string[]): void {\n const seen = new Set<string>();\n for (const id of ids) {\n if (seen.has(id)) {\n throw new Error(\n `Invalid experience definition: ${kind} id \"${id}\" is declared twice.`,\n );\n }\n seen.add(id);\n }\n}\n\n/**\n * Declare an experience: widgets, pages, workflow templates and a reads-only\n * review queue that reach integrations only through their pinned contracts.\n *\n * Integrations are NOT declared here. They live in `ekanos.json` `integrations` (readable\n * without running code) and `ekanos codegen` types them; naming an integration that is\n * not there is a compile error, and `ekanos check` re-verifies it.\n *\n * @example\n * export default defineExperience({\n * slug: 'content-engine',\n * name: 'Content engine',\n * widgets: [{ id: 'queue', title: 'Queue', integrations: ['cms'], component: Queue }],\n * });\n */\nexport function defineExperience(input: ExperienceInput): ExperienceDefinition {\n const raw = input as unknown as Record<string, unknown>;\n for (const key of INTEGRATION_ONLY_KEYS) {\n if (raw[key] !== undefined) {\n throw new Error(\n `Invalid experience definition: \"${key}\" belongs to an integration. An experience reaches integrations only through the integrations it declares (ekanos.json \"integrations\").`,\n );\n }\n }\n if (!KEBAB.test(input.slug)) {\n throw new Error(\n `Invalid experience definition: slug \"${input.slug}\" must be kebab-case.`,\n );\n }\n if (input.name.trim() === '') {\n throw new Error('Invalid experience definition: name is required.');\n }\n\n const widgets = input.widgets ?? [];\n const pages = input.pages ?? [];\n const workflows = input.workflows ?? [];\n\n for (const widget of widgets) {\n if (!KEBAB.test(widget.id)) {\n throw new Error(\n `Invalid experience definition: widget id \"${widget.id}\" must be kebab-case.`,\n );\n }\n for (const key of ['width', 'size'] as const) {\n const value = widget[key];\n if (value !== undefined && !widgetSizeSchema.safeParse(value).success) {\n throw new Error(\n `Invalid experience definition: widget \"${widget.id}\" ${key} \"${String(value)}\" must be compact, half or full.`,\n );\n }\n }\n if (widget.layouts !== undefined) {\n const parsed = widgetLayoutsSchema.safeParse(widget.layouts);\n if (!parsed.success) {\n throw new Error(\n `Invalid experience definition: widget \"${widget.id}\" layouts is malformed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ')}.`,\n );\n }\n }\n if (\n typeof widget.component !== 'function' &&\n typeof widget.component !== 'object'\n ) {\n throw new Error(\n `Invalid experience definition: widget \"${widget.id}\" needs a component.`,\n );\n }\n }\n const normalizedPages = pages.map(normalizePage);\n for (const page of normalizedPages) {\n if (!(EXPERIENCE_PAGE_KINDS as readonly string[]).includes(page.kind)) {\n throw new Error(\n `Invalid experience definition: page \"${page.id}\" has kind \"${String(page.kind)}\"; use overview, canvas or custom.`,\n );\n }\n if (\n !KEBAB.test(page.id) ||\n (page.kind !== 'overview' && !KEBAB.test(page.path))\n ) {\n throw new Error(\n `Invalid experience definition: page \"${page.id}\" id and path must be kebab-case.`,\n );\n }\n const component = (page as { component?: unknown }).component;\n if (page.kind === 'canvas' && component !== undefined) {\n throw new Error(\n `Invalid experience definition: canvas page \"${page.id}\" takes \"widgets\", not a component.`,\n );\n }\n if (\n page.kind === 'custom' &&\n typeof component !== 'function' &&\n typeof component !== 'object'\n ) {\n throw new Error(\n `Invalid experience definition: page \"${page.id}\" needs a component.`,\n );\n }\n }\n if (input.suggestedLayout !== undefined) {\n const parsed = SuggestedLayoutSchema.safeParse(input.suggestedLayout);\n if (!parsed.success) {\n throw new Error(\n `Invalid experience definition: suggestedLayout is malformed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ')}.`,\n );\n }\n }\n const problems = surfaceProblems({\n widgets,\n pages: normalizedPages.map((page) => ({\n id: page.id,\n kind: page.kind,\n ...(page.kind === 'overview' ? {} : { path: page.path }),\n ...(page.kind === 'canvas' ? { widgets: page.widgets } : {}),\n ...(page.kind === 'custom' && page.routes ? { routes: page.routes } : {}),\n })),\n ...(input.suggestedLayout\n ? { suggestedLayout: input.suggestedLayout }\n : {}),\n });\n if (problems[0] !== undefined) {\n throw new Error(`Invalid experience definition: ${problems[0]}.`);\n }\n assertUnique(\n 'workflow template',\n workflows.map((w) => w.id),\n );\n\n if (input.reviewQueue) {\n if (input.reviewQueue.readsOnly !== true) {\n throw new Error(\n 'Invalid experience definition: reviewQueue.readsOnly must be true.',\n );\n }\n assertUnique(\n 'review queue section',\n input.reviewQueue.sections.map((s) => s.id),\n );\n }\n\n return Object.freeze({\n kind: 'experience' as const,\n slug: input.slug,\n name: input.name,\n ...(input.description === undefined\n ? {}\n : { description: input.description }),\n ...(input.sidebar === undefined ? {} : { sidebar: input.sidebar }),\n widgets: Object.freeze([...widgets]),\n pages: Object.freeze(normalizedPages),\n workflows: Object.freeze([...workflows]),\n ...(input.reviewQueue === undefined\n ? {}\n : { reviewQueue: input.reviewQueue }),\n ...(input.suggestedLayout === undefined\n ? {}\n : { suggestedLayout: input.suggestedLayout }),\n });\n}\n\n/** Integrations an experience definition touches, deduplicated (for `check`/manifest). */\nexport function slotsUsedBy(definition: ExperienceDefinition): string[] {\n const used = new Set<string>();\n for (const widget of definition.widgets)\n for (const s of widget.integrations) used.add(s);\n for (const page of definition.pages)\n for (const s of page.integrations) used.add(s);\n for (const section of definition.reviewQueue?.sections ?? [])\n used.add(section.integration);\n for (const template of definition.workflows) {\n for (const s of template.build())\n if (s.type === 'tool') used.add(s.integration);\n }\n\n return [...used].sort();\n}\n"]}
|
|
@@ -14,12 +14,18 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import type { OperationResult } from '@ekanos/integration-schema';
|
|
16
16
|
export { OPERATION_REFUSAL_REASONS, type OperationError, type OperationRefusalReason, type OperationResult, } from './types.js';
|
|
17
|
-
/** The channel a call arrives on; writes are judged by it (see `write_refused_on_channel`). */
|
|
18
|
-
export type OperationChannel = 'http' | 'rsc' | 'workflow';
|
|
19
17
|
/**
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
18
|
+
* The channel a call arrives on; writes are judged by it. `http` and `rsc` are
|
|
19
|
+
* reads (a write there is `write_refused_on_channel`). `interactive` is a
|
|
20
|
+
* person's own click in a widget or page: `useOperationMutation` uses it, and
|
|
21
|
+
* the write runs directly. `workflow` writes sit behind the workflow's
|
|
22
|
+
* approval step.
|
|
23
|
+
*/
|
|
24
|
+
export type OperationChannel = 'http' | 'rsc' | 'workflow' | 'interactive';
|
|
25
|
+
/**
|
|
26
|
+
* Proof that a person approved one write. Opaque to the experience. A widget
|
|
27
|
+
* or page write does not need one: the person's click is the authorization.
|
|
28
|
+
* Kept for runtimes that mint a token for a held write.
|
|
23
29
|
*/
|
|
24
30
|
export interface ApprovalToken {
|
|
25
31
|
readonly id: string;
|
|
@@ -44,9 +50,10 @@ export interface IntegrationInfo {
|
|
|
44
50
|
}
|
|
45
51
|
export interface ExperienceRuntime {
|
|
46
52
|
/**
|
|
47
|
-
* Run one operation.
|
|
48
|
-
*
|
|
49
|
-
*
|
|
53
|
+
* Run one operation. A write on `interactive` runs directly; if the
|
|
54
|
+
* operation requires `confirmed: z.literal(true)` in its input, the runtime
|
|
55
|
+
* asks the person first, so the call may take as long as they take to answer
|
|
56
|
+
* (`write_not_approved` when they cancel). Never throws for a
|
|
50
57
|
* refusal: those are `{ ok: false, reason }`. A rejected promise means the
|
|
51
58
|
* runtime itself is broken.
|
|
52
59
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/experience/runtime.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,yBAAyB,GAI1B,MAAM,SAAS,CAAC","sourcesContent":["/**\n * `@ekanos/sdk/experience/runtime` — the ONE seam between an experience and\n * an integration.\n *\n * An experience calls operations through an {@link ExperienceRuntime} and\n * through nothing else: no import of integration code, no `fetch` to an\n * integration route. The local harness implements it over its own\n * `/__ekanos/api/ops/run`; the host implements it over its experience route,\n * `/api/experiences/<experience>/slots/…?account=<team>`, with the team's own\n * connection to each integration (no install). Both answer with the same {@link OperationResult} and the same\n * refusal reasons, so an experience behaves identically in either.\n *\n * Isomorphic and dependency-free: types only (plus the re-exports below).\n */\nimport type { OperationResult } from '@ekanos/integration-schema';\n\nexport {\n OPERATION_REFUSAL_REASONS,\n type OperationError,\n type OperationRefusalReason,\n type OperationResult,\n} from './types';\n\n
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/experience/runtime.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,yBAAyB,GAI1B,MAAM,SAAS,CAAC","sourcesContent":["/**\n * `@ekanos/sdk/experience/runtime` — the ONE seam between an experience and\n * an integration.\n *\n * An experience calls operations through an {@link ExperienceRuntime} and\n * through nothing else: no import of integration code, no `fetch` to an\n * integration route. The local harness implements it over its own\n * `/__ekanos/api/ops/run`; the host implements it over its experience route,\n * `/api/experiences/<experience>/slots/…?account=<team>`, with the team's own\n * connection to each integration (no install). Both answer with the same {@link OperationResult} and the same\n * refusal reasons, so an experience behaves identically in either.\n *\n * Isomorphic and dependency-free: types only (plus the re-exports below).\n */\nimport type { OperationResult } from '@ekanos/integration-schema';\n\nexport {\n OPERATION_REFUSAL_REASONS,\n type OperationError,\n type OperationRefusalReason,\n type OperationResult,\n} from './types';\n\n/**\n * The channel a call arrives on; writes are judged by it. `http` and `rsc` are\n * reads (a write there is `write_refused_on_channel`). `interactive` is a\n * person's own click in a widget or page: `useOperationMutation` uses it, and\n * the write runs directly. `workflow` writes sit behind the workflow's\n * approval step.\n */\nexport type OperationChannel = 'http' | 'rsc' | 'workflow' | 'interactive';\n\n/**\n * Proof that a person approved one write. Opaque to the experience. A widget\n * or page write does not need one: the person's click is the authorization.\n * Kept for runtimes that mint a token for a held write.\n */\nexport interface ApprovalToken {\n readonly id: string;\n}\n\nexport interface OperationCallRequest {\n /** The integration name from `ekanos.json` `integrations` (its slug). */\n integration: string;\n /** `tool/<name>` or `action/<name>`. The version is the one `ekanos.json` pins. */\n op: string;\n input: unknown;\n channel: OperationChannel;\n approval?: ApprovalToken;\n}\n\nexport type IntegrationProvenance = 'registry' | 'local';\n\n/** What a runtime can say about an integration (for UI badges, never for widgets' logic). */\nexport interface IntegrationInfo {\n name: string;\n version: string;\n provenance: IntegrationProvenance;\n bindingMode?: string;\n runMode?: 'fixtures' | 'live';\n}\n\nexport interface ExperienceRuntime {\n /**\n * Run one operation. A write on `interactive` runs directly; if the\n * operation requires `confirmed: z.literal(true)` in its input, the runtime\n * asks the person first, so the call may take as long as they take to answer\n * (`write_not_approved` when they cancel). Never throws for a\n * refusal: those are `{ ok: false, reason }`. A rejected promise means the\n * runtime itself is broken.\n */\n call(request: OperationCallRequest): Promise<OperationResult<unknown>>;\n integrations(): IntegrationInfo[];\n}\n"]}
|
|
@@ -5,7 +5,8 @@ export declare function runWithExperienceRuntime<T>(runtime: ExperienceRuntime,
|
|
|
5
5
|
/** Register a process-wide runtime (the harness, which has no per-request wrapper). */
|
|
6
6
|
export declare function configureExperienceRuntime(runtime: ExperienceRuntime): void;
|
|
7
7
|
/**
|
|
8
|
-
* Call one operation on the server
|
|
9
|
-
*
|
|
8
|
+
* Call one operation on the server, to read. The `rsc` channel is read-only:
|
|
9
|
+
* a write is refused (`write_refused_on_channel`). Writes belong to a person's
|
|
10
|
+
* click in a widget or page (`useOperationMutation`) or to a workflow step.
|
|
10
11
|
*/
|
|
11
12
|
export declare function operation<S extends IntegrationName, K extends OperationKey<S>>(integration: S, op: K, ...args: InputArgs<OperationInput<S, K>>): Promise<OperationResult<OperationOutput<S, K>>>;
|
|
@@ -31,8 +31,9 @@ function currentRuntime() {
|
|
|
31
31
|
return runtime;
|
|
32
32
|
}
|
|
33
33
|
/**
|
|
34
|
-
* Call one operation on the server
|
|
35
|
-
*
|
|
34
|
+
* Call one operation on the server, to read. The `rsc` channel is read-only:
|
|
35
|
+
* a write is refused (`write_refused_on_channel`). Writes belong to a person's
|
|
36
|
+
* click in a widget or page (`useOperationMutation`) or to a workflow step.
|
|
36
37
|
*/
|
|
37
38
|
export async function operation(integration, op, ...args) {
|
|
38
39
|
var _a;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/experience/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAYrD,MAAM,OAAO,GAAG,IAAI,iBAAiB,EAAqB,CAAC;AAE3D,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;AAMhE,wEAAwE;AACxE,MAAM,UAAU,wBAAwB,CACtC,OAA0B,EAC1B,EAAW;IAEX,OAAO,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AAClC,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,0BAA0B,CAAC,OAA0B;IAClE,UAAgC,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC;AAC1D,CAAC;AAED,SAAS,cAAc;;IACrB,MAAM,OAAO,SACX,OAAO,CAAC,QAAQ,EAAE,mCAAK,UAAgC,CAAC,UAAU,CAAC,CAAC;IACtE,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACb,6IAA6I,CAC9I,CAAC;IACJ,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/experience/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAYrD,MAAM,OAAO,GAAG,IAAI,iBAAiB,EAAqB,CAAC;AAE3D,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;AAMhE,wEAAwE;AACxE,MAAM,UAAU,wBAAwB,CACtC,OAA0B,EAC1B,EAAW;IAEX,OAAO,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AAClC,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,0BAA0B,CAAC,OAA0B;IAClE,UAAgC,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC;AAC1D,CAAC;AAED,SAAS,cAAc;;IACrB,MAAM,OAAO,SACX,OAAO,CAAC,QAAQ,EAAE,mCAAK,UAAgC,CAAC,UAAU,CAAC,CAAC;IACtE,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACb,6IAA6I,CAC9I,CAAC;IACJ,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAI7B,WAAc,EACd,EAAK,EACL,GAAG,IAAqC;;IAExC,MAAM,MAAM,GAAG,MAAM,cAAc,EAAE,CAAC,IAAI,CAAC;QACzC,WAAW;QACX,EAAE;QACF,KAAK,QAAE,IAAI,CAAC,CAAC,CAAC,mCAAI,EAAE;QACpB,OAAO,EAAE,KAAK;KACf,CAAC,CAAC;IAEH,OAAO,MAAgD,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * `@ekanos/sdk/experience/server` — call an integration operation from a server\n * component, server action or route.\n *\n * ```ts\n * const res = await operation('cms', 'tool/list_posts', { limit: 20 });\n * if (res.ok) res.data; // typed from the pinned contract\n * ```\n *\n * The runtime comes from `AsyncLocalStorage` (set by the host or the harness\n * around the request with {@link runWithExperienceRuntime}), falling back to\n * one registered with {@link configureExperienceRuntime}.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nimport type { ExperienceRuntime } from './runtime';\nimport type {\n InputArgs,\n OperationInput,\n OperationKey,\n OperationOutput,\n OperationResult,\n IntegrationName,\n} from './types';\n\nconst storage = new AsyncLocalStorage<ExperienceRuntime>();\n\nconst GLOBAL_KEY = Symbol.for('@ekanos/sdk/experience/runtime');\n\ntype GlobalWithRuntime = typeof globalThis & {\n [GLOBAL_KEY]?: ExperienceRuntime;\n};\n\n/** Run `fn` with `runtime` as the one `operation()` calls inside it. */\nexport function runWithExperienceRuntime<T>(\n runtime: ExperienceRuntime,\n fn: () => T,\n): T {\n return storage.run(runtime, fn);\n}\n\n/** Register a process-wide runtime (the harness, which has no per-request wrapper). */\nexport function configureExperienceRuntime(runtime: ExperienceRuntime): void {\n (globalThis as GlobalWithRuntime)[GLOBAL_KEY] = runtime;\n}\n\nfunction currentRuntime(): ExperienceRuntime {\n const runtime =\n storage.getStore() ?? (globalThis as GlobalWithRuntime)[GLOBAL_KEY];\n if (!runtime) {\n throw new Error(\n 'operation() has no ExperienceRuntime. The host and `ekanos dev` set one per request; in a test call runWithExperienceRuntime(runtime, ...).',\n );\n }\n\n return runtime;\n}\n\n/**\n * Call one operation on the server, to read. The `rsc` channel is read-only:\n * a write is refused (`write_refused_on_channel`). Writes belong to a person's\n * click in a widget or page (`useOperationMutation`) or to a workflow step.\n */\nexport async function operation<\n S extends IntegrationName,\n K extends OperationKey<S>,\n>(\n integration: S,\n op: K,\n ...args: InputArgs<OperationInput<S, K>>\n): Promise<OperationResult<OperationOutput<S, K>>> {\n const result = await currentRuntime().call({\n integration,\n op,\n input: args[0] ?? {},\n channel: 'rsc',\n });\n\n return result as OperationResult<OperationOutput<S, K>>;\n}\n"]}
|
|
@@ -108,7 +108,9 @@ export function useOAuthWidgetGate(accountId, integrationActive, options) {
|
|
|
108
108
|
: options;
|
|
109
109
|
const query = useOAuthConnectionStatus(accountId !== null && accountId !== void 0 ? accountId : '', Object.assign(Object.assign({}, resolved), { enabled }));
|
|
110
110
|
const connectionPending = enabled && query.isPending;
|
|
111
|
-
|
|
111
|
+
// A failed RE-check keeps the last answer: only a check that never
|
|
112
|
+
// answered is an error. (TanStack keeps `data` after a failed refetch.)
|
|
113
|
+
const connectionError = enabled && query.isError && query.data === undefined;
|
|
112
114
|
const isConnected = ((_a = query.data) === null || _a === void 0 ? void 0 : _a.isConnected) === true;
|
|
113
115
|
const dataEnabled = enabled && isConnected;
|
|
114
116
|
// Only treat as "not connected" when the check resolved successfully with
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-oauth-connection-status.js","sourceRoot":"","sources":["../../src/hooks/use-oauth-connection-status.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAE5C,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEjE,OAAO,EAAE,4BAA4B,EAAE,MAAM,iBAAiB,CAAC;AAuC/D;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CACtC,SAAiB,EACjB,OAAwC;IAExC,MAAM,EACJ,aAAa,EACb,eAAe,EACf,OAAO,GAAG,IAAI,EACd,UAAU,GACX,GAAG,OAAO,CAAC;IACZ,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;IAErC,yEAAyE;IACzE,0EAA0E;IAC1E,MAAM,CAAC,kBAAkB,CAAC,GAAG,QAAQ,CAAC,GAAG,EAAE;QACzC,IAAI,OAAO,MAAM,KAAK,WAAW;YAAE,OAAO,KAAK,CAAC;QAChD,MAAM,MAAM,GAAG,IAAI,eAAe,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QAC3D,OAAO,MAAM,CAAC,GAAG,CAAC,eAAe,CAAC,KAAK,MAAM,CAAC;IAChD,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,UAAU,CAAC,GAAG,QAA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;AACnG,MAAM,UAAU,yBAAyB,CACvC,IAAY;IAEZ,OAAO;QACL,aAAa,EAAE,GAAG,IAAI,aAAa;QACnC,eAAe,EAAE,4BAA4B,CAAC,IAAI,CAAC;KACpD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,SAA6B,EAC7B,iBAA0B,EAC1B,OAA+B;;IAE/B,MAAM,OAAO,GAAG,iBAAiB,IAAI,CAAC,CAAC,SAAS,CAAC;IACjD,MAAM,QAAQ,GACZ,OAAO,CAAC,IAAI,KAAK,SAAS;QACxB,CAAC,CAAC,yBAAyB,CAAC,OAAO,CAAC,IAAI,CAAC;QACzC,CAAC,CAAC,OAAO,CAAC;IACd,MAAM,KAAK,GAAG,wBAAwB,CAAC,SAAS,aAAT,SAAS,cAAT,SAAS,GAAI,EAAE,kCACjD,QAAQ,KACX,OAAO,IACP,CAAC;IAEH,MAAM,iBAAiB,GAAG,OAAO,IAAI,KAAK,CAAC,SAAS,CAAC;IACrD,MAAM,eAAe,GAAG,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC;IACjD,MAAM,WAAW,GAAG,CAAA,MAAA,KAAK,CAAC,IAAI,0CAAE,WAAW,MAAK,IAAI,CAAC;IACrD,MAAM,WAAW,GAAG,OAAO,IAAI,WAAW,CAAC;IAC3C,0EAA0E;IAC1E,0EAA0E;IAC1E,MAAM,YAAY,GAChB,OAAO,IAAI,CAAC,iBAAiB,IAAI,CAAC,eAAe,IAAI,CAAC,WAAW,CAAC;IAEpE,OAAO;QACL,OAAO;QACP,WAAW;QACX,iBAAiB;QACjB,eAAe;QACf,WAAW;QACX,YAAY;KACb,CAAC;AACJ,CAAC","sourcesContent":["'use client';\n\nimport { useEffect, useState } from 'react';\n\nimport { useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport { createPartnerConnectionCheck } from './partner-oauth';\n\n/**\n * Result shape of an integration's check-connection server action\n * (the standard server-action envelope).\n */\nexport interface ConnectionCheckResult {\n success: boolean;\n data?: { obtainedAt?: string | null } | null;\n error?: string;\n}\n\nexport type ConnectionCheckAction = (input: {\n accountId: string;\n}) => Promise<ConnectionCheckResult>;\n\n/**\n * Optional OAuth failure query param an integration's connect route may\n * append on redirect (e.g. dropbox_error=credentials_not_configured).\n */\nexport interface OAuthErrorParam {\n name: string;\n /** Map the raw param value to a user-facing message; return null to ignore. */\n toMessage: (value: string) => string | null;\n}\n\nexport interface UseOAuthConnectionStatusOptions {\n /**\n * Cache key segment, by convention `<slug>-connection`. The full query key\n * is ['integration-data', accountId, connectionKey] so all widgets and the\n * activation form share one deduped request per dashboard load.\n */\n connectionKey: string;\n checkConnection: ConnectionCheckAction;\n /** Gate the query (e.g. on integration-active state). Defaults to true. */\n enabled?: boolean;\n errorParam?: OAuthErrorParam;\n}\n\n/**\n * Shared OAuth connection-status hook. Detects the `oauth_success=true`\n * return from an integration's connect route, strips the transient params\n * from the URL, and invalidates the cached status so dependent UI flips to\n * connected without a manual refresh.\n */\nexport function useOAuthConnectionStatus(\n accountId: string,\n options: UseOAuthConnectionStatusOptions,\n) {\n const {\n connectionKey,\n checkConnection,\n enabled = true,\n errorParam,\n } = options;\n const queryClient = useQueryClient();\n\n // Read the OAuth return params synchronously on mount (not in an effect)\n // so the first render already knows whether we just came back from OAuth.\n const [oauthJustCompleted] = useState(() => {\n if (typeof window === 'undefined') return false;\n const params = new URLSearchParams(window.location.search);\n return params.get('oauth_success') === 'true';\n });\n\n const [oauthError] = useState<string | null>(() => {\n if (!errorParam || typeof window === 'undefined') return null;\n const value = new URLSearchParams(window.location.search).get(\n errorParam.name,\n );\n return value ? errorParam.toMessage(value) : null;\n });\n\n const query = useQuery({\n queryKey: ['integration-data', accountId, connectionKey],\n queryFn: async () => {\n const result = await checkConnection({ accountId });\n\n if (!result.success) {\n return { isConnected: false, error: result.error };\n }\n\n return {\n isConnected: true,\n obtainedAt: result.data?.obtainedAt,\n };\n },\n enabled: enabled && !!accountId,\n staleTime: 5 * 60 * 1000,\n refetchOnWindowFocus: false,\n });\n\n const errorParamName = errorParam?.name;\n\n const returnedWithError = oauthError !== null;\n\n // Justified useEffect: after the OAuth redirect lands back on this page —\n // with `?oauth_success=true` OR with the integration's error param — we\n // must (1) strip the transient query params from the URL, so a reload does\n // not re-announce a stale success or re-show a stale error, and (2) on\n // success invalidate the cached connection status so widgets flip to\n // connected without a manual refresh. Both are post-render side effects\n // on external systems (history API + query cache), not derivable during\n // render. The error itself stays in state for this render, so the alert\n // still shows once.\n useEffect(() => {\n if (!oauthJustCompleted && !returnedWithError) return;\n\n const url = new URL(window.location.href);\n url.searchParams.delete('oauth_success');\n\n if (errorParamName) {\n url.searchParams.delete(errorParamName);\n }\n\n window.history.replaceState({}, '', url.pathname + url.search);\n\n if (oauthJustCompleted) {\n queryClient.invalidateQueries({\n queryKey: ['integration-data', accountId, connectionKey],\n });\n }\n }, [\n oauthJustCompleted,\n returnedWithError,\n accountId,\n connectionKey,\n errorParamName,\n queryClient,\n ]);\n\n // Named, not spread: spreading a query result reads every field, so\n // the component re-renders on all of them (TanStack render optimizations).\n return {\n data: query.data,\n error: query.error,\n status: query.status,\n isPending: query.isPending,\n isLoading: query.isLoading,\n isError: query.isError,\n isSuccess: query.isSuccess,\n isFetching: query.isFetching,\n isRefetching: query.isRefetching,\n dataUpdatedAt: query.dataUpdatedAt,\n refetch: query.refetch,\n oauthJustCompleted,\n oauthError,\n };\n}\n\n/**\n * Resolves the gating booleans every OAuth-backed dashboard widget needs:\n *\n * - `enabled` — the integration is active and an account id is present.\n * - `isConnected` — a live OAuth connection exists (access token).\n * - `dataEnabled` — safe to fire the widget's data query (active + connected).\n * - `connectionPending` — still resolving the connection status.\n * - `connectionError` — the connection check itself failed (network/5xx).\n * Distinct from `notConnected`: a transient failure should surface as an\n * error, not as a misleading \"connect X\" prompt.\n * - `notConnected` — activated, resolved without error, but no OAuth\n * connection. The widget should render its \"connect X\" inactive state.\n *\n * The underlying connection check shares one query key across all widgets,\n * so react-query dedupes it to a single request per dashboard load.\n */\nexport type OAuthWidgetGateOptions =\n | (Pick<\n UseOAuthConnectionStatusOptions,\n 'connectionKey' | 'checkConnection'\n > & {\n slug?: never;\n })\n /**\n * The hosted-transport shorthand: for an integration whose connection is\n * checked at `GET /api/integrations/<slug>/oauth/status`, the slug is the\n * only fact the gate needs — the key is `<slug>-connection` by convention\n * and the check is `createPartnerConnectionCheck(slug)`.\n */\n | { slug: string; connectionKey?: never; checkConnection?: never };\n\n/** Pure: the gate options a slug implies. Exported for tests and for widgets that need the key. */\nexport function oauthWidgetGateOptionsFor(\n slug: string,\n): Pick<UseOAuthConnectionStatusOptions, 'connectionKey' | 'checkConnection'> {\n return {\n connectionKey: `${slug}-connection`,\n checkConnection: createPartnerConnectionCheck(slug),\n };\n}\n\nexport function useOAuthWidgetGate(\n accountId: string | undefined,\n integrationActive: boolean,\n options: OAuthWidgetGateOptions,\n) {\n const enabled = integrationActive && !!accountId;\n const resolved =\n options.slug !== undefined\n ? oauthWidgetGateOptionsFor(options.slug)\n : options;\n const query = useOAuthConnectionStatus(accountId ?? '', {\n ...resolved,\n enabled,\n });\n\n const connectionPending = enabled && query.isPending;\n const connectionError = enabled && query.isError;\n const isConnected = query.data?.isConnected === true;\n const dataEnabled = enabled && isConnected;\n // Only treat as \"not connected\" when the check resolved successfully with\n // no token — a query error is an error state, not a disconnected account.\n const notConnected =\n enabled && !connectionPending && !connectionError && !isConnected;\n\n return {\n enabled,\n isConnected,\n connectionPending,\n connectionError,\n dataEnabled,\n notConnected,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"use-oauth-connection-status.js","sourceRoot":"","sources":["../../src/hooks/use-oauth-connection-status.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAE5C,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEjE,OAAO,EAAE,4BAA4B,EAAE,MAAM,iBAAiB,CAAC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,GAAG,OAAO,IAAI,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC;IAC7E,MAAM,WAAW,GAAG,CAAA,MAAA,KAAK,CAAC,IAAI,0CAAE,WAAW,MAAK,IAAI,CAAC;IACrD,MAAM,WAAW,GAAG,OAAO,IAAI,WAAW,CAAC;IAC3C,0EAA0E;IAC1E,0EAA0E;IAC1E,MAAM,YAAY,GAChB,OAAO,IAAI,CAAC,iBAAiB,IAAI,CAAC,eAAe,IAAI,CAAC,WAAW,CAAC;IAEpE,OAAO;QACL,OAAO;QACP,WAAW;QACX,iBAAiB;QACjB,eAAe;QACf,WAAW;QACX,YAAY;KACb,CAAC;AACJ,CAAC","sourcesContent":["'use client';\n\nimport { useEffect, useState } from 'react';\n\nimport { useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport { createPartnerConnectionCheck } from './partner-oauth';\n\n/**\n * Result shape of an integration's check-connection server action\n * (the standard server-action envelope).\n */\nexport interface ConnectionCheckResult {\n success: boolean;\n data?: { obtainedAt?: string | null } | null;\n error?: string;\n}\n\nexport type ConnectionCheckAction = (input: {\n accountId: string;\n}) => Promise<ConnectionCheckResult>;\n\n/**\n * Optional OAuth failure query param an integration's connect route may\n * append on redirect (e.g. dropbox_error=credentials_not_configured).\n */\nexport interface OAuthErrorParam {\n name: string;\n /** Map the raw param value to a user-facing message; return null to ignore. */\n toMessage: (value: string) => string | null;\n}\n\nexport interface UseOAuthConnectionStatusOptions {\n /**\n * Cache key segment, by convention `<slug>-connection`. The full query key\n * is ['integration-data', accountId, connectionKey] so all widgets and the\n * activation form share one deduped request per dashboard load.\n */\n connectionKey: string;\n checkConnection: ConnectionCheckAction;\n /** Gate the query (e.g. on integration-active state). Defaults to true. */\n enabled?: boolean;\n errorParam?: OAuthErrorParam;\n}\n\n/**\n * Shared OAuth connection-status hook. Detects the `oauth_success=true`\n * return from an integration's connect route, strips the transient params\n * from the URL, and invalidates the cached status so dependent UI flips to\n * connected without a manual refresh.\n */\nexport function useOAuthConnectionStatus(\n accountId: string,\n options: UseOAuthConnectionStatusOptions,\n) {\n const {\n connectionKey,\n checkConnection,\n enabled = true,\n errorParam,\n } = options;\n const queryClient = useQueryClient();\n\n // Read the OAuth return params synchronously on mount (not in an effect)\n // so the first render already knows whether we just came back from OAuth.\n const [oauthJustCompleted] = useState(() => {\n if (typeof window === 'undefined') return false;\n const params = new URLSearchParams(window.location.search);\n return params.get('oauth_success') === 'true';\n });\n\n const [oauthError] = useState<string | null>(() => {\n if (!errorParam || typeof window === 'undefined') return null;\n const value = new URLSearchParams(window.location.search).get(\n errorParam.name,\n );\n return value ? errorParam.toMessage(value) : null;\n });\n\n const query = useQuery({\n queryKey: ['integration-data', accountId, connectionKey],\n queryFn: async () => {\n const result = await checkConnection({ accountId });\n\n if (!result.success) {\n return { isConnected: false, error: result.error };\n }\n\n return {\n isConnected: true,\n obtainedAt: result.data?.obtainedAt,\n };\n },\n enabled: enabled && !!accountId,\n staleTime: 5 * 60 * 1000,\n refetchOnWindowFocus: false,\n });\n\n const errorParamName = errorParam?.name;\n\n const returnedWithError = oauthError !== null;\n\n // Justified useEffect: after the OAuth redirect lands back on this page —\n // with `?oauth_success=true` OR with the integration's error param — we\n // must (1) strip the transient query params from the URL, so a reload does\n // not re-announce a stale success or re-show a stale error, and (2) on\n // success invalidate the cached connection status so widgets flip to\n // connected without a manual refresh. Both are post-render side effects\n // on external systems (history API + query cache), not derivable during\n // render. The error itself stays in state for this render, so the alert\n // still shows once.\n useEffect(() => {\n if (!oauthJustCompleted && !returnedWithError) return;\n\n const url = new URL(window.location.href);\n url.searchParams.delete('oauth_success');\n\n if (errorParamName) {\n url.searchParams.delete(errorParamName);\n }\n\n window.history.replaceState({}, '', url.pathname + url.search);\n\n if (oauthJustCompleted) {\n queryClient.invalidateQueries({\n queryKey: ['integration-data', accountId, connectionKey],\n });\n }\n }, [\n oauthJustCompleted,\n returnedWithError,\n accountId,\n connectionKey,\n errorParamName,\n queryClient,\n ]);\n\n // Named, not spread: spreading a query result reads every field, so\n // the component re-renders on all of them (TanStack render optimizations).\n return {\n data: query.data,\n error: query.error,\n status: query.status,\n isPending: query.isPending,\n isLoading: query.isLoading,\n isError: query.isError,\n isSuccess: query.isSuccess,\n isFetching: query.isFetching,\n isRefetching: query.isRefetching,\n dataUpdatedAt: query.dataUpdatedAt,\n refetch: query.refetch,\n oauthJustCompleted,\n oauthError,\n };\n}\n\n/**\n * Resolves the gating booleans every OAuth-backed dashboard widget needs:\n *\n * - `enabled` — the integration is active and an account id is present.\n * - `isConnected` — a live OAuth connection exists (access token).\n * - `dataEnabled` — safe to fire the widget's data query (active + connected).\n * - `connectionPending` — still resolving the connection status.\n * - `connectionError` — the connection check itself failed (network/5xx).\n * Distinct from `notConnected`: a transient failure should surface as an\n * error, not as a misleading \"connect X\" prompt.\n * - `notConnected` — activated, resolved without error, but no OAuth\n * connection. The widget should render its \"connect X\" inactive state.\n *\n * The underlying connection check shares one query key across all widgets,\n * so react-query dedupes it to a single request per dashboard load.\n */\nexport type OAuthWidgetGateOptions =\n | (Pick<\n UseOAuthConnectionStatusOptions,\n 'connectionKey' | 'checkConnection'\n > & {\n slug?: never;\n })\n /**\n * The hosted-transport shorthand: for an integration whose connection is\n * checked at `GET /api/integrations/<slug>/oauth/status`, the slug is the\n * only fact the gate needs — the key is `<slug>-connection` by convention\n * and the check is `createPartnerConnectionCheck(slug)`.\n */\n | { slug: string; connectionKey?: never; checkConnection?: never };\n\n/** Pure: the gate options a slug implies. Exported for tests and for widgets that need the key. */\nexport function oauthWidgetGateOptionsFor(\n slug: string,\n): Pick<UseOAuthConnectionStatusOptions, 'connectionKey' | 'checkConnection'> {\n return {\n connectionKey: `${slug}-connection`,\n checkConnection: createPartnerConnectionCheck(slug),\n };\n}\n\nexport function useOAuthWidgetGate(\n accountId: string | undefined,\n integrationActive: boolean,\n options: OAuthWidgetGateOptions,\n) {\n const enabled = integrationActive && !!accountId;\n const resolved =\n options.slug !== undefined\n ? oauthWidgetGateOptionsFor(options.slug)\n : options;\n const query = useOAuthConnectionStatus(accountId ?? '', {\n ...resolved,\n enabled,\n });\n\n const connectionPending = enabled && query.isPending;\n // A failed RE-check keeps the last answer: only a check that never\n // answered is an error. (TanStack keeps `data` after a failed refetch.)\n const connectionError = enabled && query.isError && query.data === undefined;\n const isConnected = query.data?.isConnected === true;\n const dataEnabled = enabled && isConnected;\n // Only treat as \"not connected\" when the check resolved successfully with\n // no token — a query error is an error state, not a disconnected account.\n const notConnected =\n enabled && !connectionPending && !connectionError && !isConnected;\n\n return {\n enabled,\n isConnected,\n connectionPending,\n connectionError,\n dataEnabled,\n notConnected,\n };\n}\n"]}
|
|
@@ -23,4 +23,4 @@ export { DEFAULT_UNTRUSTED_TEXT_MAX_CHARS, untrustedText, untrustedTextNote, } f
|
|
|
23
23
|
export { DEFAULT_OAUTH_CONNECTION_ID, DEFAULT_SIGNATURE_TOLERANCE_SECONDS, IntegrationDefinitionSchema, MAX_AGENT_EVENT_DEDUPE_KEY_LENGTH, MAX_RAISED_AGENT_EVENTS, MAX_ROUTE_VALUE_LENGTH, MAX_ROUTING_KEYS, PARTNER_STORAGE_LIMITS, RESERVED_OAUTH_AUTHORIZATION_PARAMS, validateIntegrationDefinitions, } from '@ekanos/integration-schema';
|
|
24
24
|
export { normalizeOAuthUrlValue, oauthProviderPlaceholders, resolveOAuthProvider, resolveOAuthUrl, } from '@ekanos/integration-schema';
|
|
25
25
|
export type { ResolveOAuthProviderResult, ResolveOAuthUrlResult, } from '@ekanos/integration-schema';
|
|
26
|
-
export type { IntegrationDefinition, IntegrationComponentDeclarations, IntegrationProposals, IntegrationCapabilityDeclaration, IntegrationPermissionDeclaration, PartnerWidgetDeclaration, PartnerToolModule, PartnerToolParameters, PartnerActionDeclaration, ToolClassificationProposal, DefinitionCollisionInput, FirstPartyInventory, PartnerWebhookDeclaration, WebhookSignatureDeclaration, WebhookSignatureScheme, WebhookEvent, WebhookResult, RaisedAgentEvent, PartnerAgentChannelDeclaration, AgentChannelRun, AgentEventDeclaration, AgentConversation, AgentTriggerFilter, AgentTriggerFilterField, AgentChannelReply, AgentChannelDeliveryResult, AgentChannelRunOutcome, AgentChannelHandoff, AgentRouteValue, AgentUnroutedEvent, RoutingDeclaration, RoutingKeyDeclaration, RouteKeyOption, SourceConnectionDeclaration, PartnerScheduleDeclaration, ScheduleInvocation, ScheduleResult, PartnerOAuthDeclaration, PartnerOAuthConnectionDeclaration, TeamAppDeclaration, OAuthProviderDeclaration, OAuthSetupDeclaration, OAuthTokens, OnActivateHandler, AttentionHandler, AttentionSignal, WidgetVerdict, WidgetVerdictTone, } from '@ekanos/integration-schema';
|
|
26
|
+
export type { IntegrationDefinition, IntegrationComponentDeclarations, ActivationDeclaration, ActivationFieldDeclaration, IntegrationProposals, IntegrationCapabilityDeclaration, IntegrationPermissionDeclaration, PartnerWidgetDeclaration, PartnerToolModule, PartnerToolParameters, PartnerActionDeclaration, ToolClassificationProposal, DefinitionCollisionInput, FirstPartyInventory, PartnerWebhookDeclaration, WebhookSignatureDeclaration, WebhookSignatureScheme, WebhookEvent, WebhookResult, RaisedAgentEvent, PartnerAgentChannelDeclaration, AgentChannelRun, AgentEventDeclaration, AgentConversation, AgentTriggerFilter, AgentTriggerFilterField, AgentChannelReply, AgentChannelDeliveryResult, AgentChannelRunOutcome, AgentChannelHandoff, AgentRouteValue, AgentUnroutedEvent, RoutingDeclaration, RoutingKeyDeclaration, RouteKeyOption, SourceConnectionDeclaration, PartnerScheduleDeclaration, ScheduleInvocation, ScheduleResult, PartnerOAuthDeclaration, PartnerOAuthConnectionDeclaration, TeamAppDeclaration, OAuthProviderDeclaration, OAuthSetupDeclaration, OAuthTokens, OnActivateHandler, AttentionHandler, AttentionSignal, WidgetVerdict, WidgetVerdictTone, } from '@ekanos/integration-schema';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/integration/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,6EAA6E;AAC7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAExD,mEAAmE;AACnE,0EAA0E;AAC1E,0EAA0E;AAC1E,OAAO,EAAE,mBAAmB,EAAE,MAAM,QAAQ,CAAC;AAE7C,oEAAoE;AACpE,+CAA+C;AAC/C,8CAA8C;AAC9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAElE,8EAA8E;AAC9E,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,cAAc,GACf,MAAM,cAAc,CAAC;AAEtB,+EAA+E;AAC/E,OAAO,EACL,gCAAgC,EAChC,aAAa,EACb,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,2BAA2B,EAC3B,mCAAmC,EACnC,2BAA2B,EAC3B,iCAAiC,EACjC,uBAAuB,EACvB,sBAAsB,EACtB,gBAAgB,EAChB,sBAAsB,EACtB,mCAAmC,EACnC,8BAA8B,GAC/B,MAAM,4BAA4B,CAAC;AAEpC,sEAAsE;AACtE,4EAA4E;AAC5E,4EAA4E;AAC5E,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,oBAAoB,EACpB,eAAe,GAChB,MAAM,4BAA4B,CAAC","sourcesContent":["/**\n * @ekanos/sdk/integration — the partner authoring contract.\n *\n * `defineIntegration()` is THE way a partner declares an integration\n * Partners never extend a base class.\n * The host adapts the returned definition internally via\n * `registerPartnerIntegration` in `@kit/integrations-core`, which re-parses\n * against the SAME canonical schema (`@ekanos/integration-schema`) at the\n * trust boundary — one contract, no structural twin (F3/F9).\n *\n * Dependency-pure and isomorphic: zod plus the schema package, no `@kit/*`,\n * no `server-only`.\n *\n * Surface discipline: additions require an entry in\n * api-report.md, regenerated by `pnpm --filter @ekanos/sdk api-report`.\n */\n\nexport { defineIntegration } from './define-integration';\n\n// Agent events (plan 222): types an event's functions by its payload schema.\nexport { defineAgentEvent } from './define-agent-event';\n\n// Event-surface validation values: the 5-field cron parser backing\n// `defineIntegration()`'s schedule validation, exported so validators and\n// the harness can check/describe an expression the same way the SDK does.\nexport { parseCronExpression } from './cron';\n\n// The one escape hatch from the actions host route's opaque-failure\n// discipline — see the class's own doc comment\n// (the widget-actions opaque-failure ruling).\nexport { PublicActionError } from '../errors/public-action-error';\n\n// Gate a write action on the caller's role (the host fills `ctx.actor.role`).\nexport {\n ADMIN_HIERARCHY_LEVEL,\n OWNER_HIERARCHY_LEVEL,\n actorIsAtLeast,\n} from './actor-role';\n\n// Vendor/user-authored text in tool output: one name (`untrusted*`), one clip.\nexport {\n DEFAULT_UNTRUSTED_TEXT_MAX_CHARS,\n untrustedText,\n untrustedTextNote,\n} from './untrusted-text';\n\nexport {\n DEFAULT_OAUTH_CONNECTION_ID,\n DEFAULT_SIGNATURE_TOLERANCE_SECONDS,\n IntegrationDefinitionSchema,\n MAX_AGENT_EVENT_DEDUPE_KEY_LENGTH,\n MAX_RAISED_AGENT_EVENTS,\n MAX_ROUTE_VALUE_LENGTH,\n MAX_ROUTING_KEYS,\n PARTNER_STORAGE_LIMITS,\n RESERVED_OAUTH_AUTHORIZATION_PARAMS,\n validateIntegrationDefinitions,\n} from '@ekanos/integration-schema';\n\n// OAuth endpoint templates (`https://{subdomain}.zendesk.com/…`): the\n// resolver the host transport and the harness fill them with, exported so a\n// partner refreshing its own tokens builds the token URL by the same rules.\nexport {\n normalizeOAuthUrlValue,\n oauthProviderPlaceholders,\n resolveOAuthProvider,\n resolveOAuthUrl,\n} from '@ekanos/integration-schema';\nexport type {\n ResolveOAuthProviderResult,\n ResolveOAuthUrlResult,\n} from '@ekanos/integration-schema';\n\nexport type {\n IntegrationDefinition,\n IntegrationComponentDeclarations,\n IntegrationProposals,\n IntegrationCapabilityDeclaration,\n IntegrationPermissionDeclaration,\n PartnerWidgetDeclaration,\n PartnerToolModule,\n PartnerToolParameters,\n // Widget-invoked server handlers (`actions`): the declaration type a\n // partner needs to export a handler shared between an action and a tool.\n PartnerActionDeclaration,\n ToolClassificationProposal,\n DefinitionCollisionInput,\n FirstPartyInventory,\n // Event surfaces (webhooks, schedules, OAuth): declared in the definition,\n // executed locally by the harness/testing helpers today; the host's real\n // transports (public ingress, scheduler, hosted OAuth callback) bind to\n // these exact declarations later with no partner code change.\n PartnerWebhookDeclaration,\n WebhookSignatureDeclaration,\n WebhookSignatureScheme,\n WebhookEvent,\n WebhookResult,\n // Agent events and channel (plan 222): events a webhook raises to start\n // agents, and the channel a run answers in.\n RaisedAgentEvent,\n PartnerAgentChannelDeclaration,\n AgentChannelRun,\n AgentEventDeclaration,\n AgentConversation,\n AgentTriggerFilter,\n AgentTriggerFilterField,\n AgentChannelReply,\n AgentChannelDeliveryResult,\n AgentChannelRunOutcome,\n AgentChannelHandoff,\n // Routing and Source connections (plan 241): one connection for a whole\n // Source, its events routed to teams by a key such as the organization.\n AgentRouteValue,\n AgentUnroutedEvent,\n RoutingDeclaration,\n RoutingKeyDeclaration,\n RouteKeyOption,\n SourceConnectionDeclaration,\n PartnerScheduleDeclaration,\n ScheduleInvocation,\n ScheduleResult,\n PartnerOAuthDeclaration,\n PartnerOAuthConnectionDeclaration,\n TeamAppDeclaration,\n OAuthProviderDeclaration,\n OAuthSetupDeclaration,\n OAuthTokens,\n // Activation lifecycle hook: cache seeding / eager validation at connect\n // time. Runs after first persist and after every activationData update;\n // v1 errors are non-fatal (logged as a warning, activation stays active).\n OnActivateHandler,\n // Each widget's verdict, computed on the server for home's Needs you.\n AttentionHandler,\n AttentionSignal,\n WidgetVerdict,\n WidgetVerdictTone,\n} from '@ekanos/integration-schema';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/integration/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,6EAA6E;AAC7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAExD,mEAAmE;AACnE,0EAA0E;AAC1E,0EAA0E;AAC1E,OAAO,EAAE,mBAAmB,EAAE,MAAM,QAAQ,CAAC;AAE7C,oEAAoE;AACpE,+CAA+C;AAC/C,8CAA8C;AAC9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAElE,8EAA8E;AAC9E,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,cAAc,GACf,MAAM,cAAc,CAAC;AAEtB,+EAA+E;AAC/E,OAAO,EACL,gCAAgC,EAChC,aAAa,EACb,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,2BAA2B,EAC3B,mCAAmC,EACnC,2BAA2B,EAC3B,iCAAiC,EACjC,uBAAuB,EACvB,sBAAsB,EACtB,gBAAgB,EAChB,sBAAsB,EACtB,mCAAmC,EACnC,8BAA8B,GAC/B,MAAM,4BAA4B,CAAC;AAEpC,sEAAsE;AACtE,4EAA4E;AAC5E,4EAA4E;AAC5E,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,oBAAoB,EACpB,eAAe,GAChB,MAAM,4BAA4B,CAAC","sourcesContent":["/**\n * @ekanos/sdk/integration — the partner authoring contract.\n *\n * `defineIntegration()` is THE way a partner declares an integration\n * Partners never extend a base class.\n * The host adapts the returned definition internally via\n * `registerPartnerIntegration` in `@kit/integrations-core`, which re-parses\n * against the SAME canonical schema (`@ekanos/integration-schema`) at the\n * trust boundary — one contract, no structural twin (F3/F9).\n *\n * Dependency-pure and isomorphic: zod plus the schema package, no `@kit/*`,\n * no `server-only`.\n *\n * Surface discipline: additions require an entry in\n * api-report.md, regenerated by `pnpm --filter @ekanos/sdk api-report`.\n */\n\nexport { defineIntegration } from './define-integration';\n\n// Agent events (plan 222): types an event's functions by its payload schema.\nexport { defineAgentEvent } from './define-agent-event';\n\n// Event-surface validation values: the 5-field cron parser backing\n// `defineIntegration()`'s schedule validation, exported so validators and\n// the harness can check/describe an expression the same way the SDK does.\nexport { parseCronExpression } from './cron';\n\n// The one escape hatch from the actions host route's opaque-failure\n// discipline — see the class's own doc comment\n// (the widget-actions opaque-failure ruling).\nexport { PublicActionError } from '../errors/public-action-error';\n\n// Gate a write action on the caller's role (the host fills `ctx.actor.role`).\nexport {\n ADMIN_HIERARCHY_LEVEL,\n OWNER_HIERARCHY_LEVEL,\n actorIsAtLeast,\n} from './actor-role';\n\n// Vendor/user-authored text in tool output: one name (`untrusted*`), one clip.\nexport {\n DEFAULT_UNTRUSTED_TEXT_MAX_CHARS,\n untrustedText,\n untrustedTextNote,\n} from './untrusted-text';\n\nexport {\n DEFAULT_OAUTH_CONNECTION_ID,\n DEFAULT_SIGNATURE_TOLERANCE_SECONDS,\n IntegrationDefinitionSchema,\n MAX_AGENT_EVENT_DEDUPE_KEY_LENGTH,\n MAX_RAISED_AGENT_EVENTS,\n MAX_ROUTE_VALUE_LENGTH,\n MAX_ROUTING_KEYS,\n PARTNER_STORAGE_LIMITS,\n RESERVED_OAUTH_AUTHORIZATION_PARAMS,\n validateIntegrationDefinitions,\n} from '@ekanos/integration-schema';\n\n// OAuth endpoint templates (`https://{subdomain}.zendesk.com/…`): the\n// resolver the host transport and the harness fill them with, exported so a\n// partner refreshing its own tokens builds the token URL by the same rules.\nexport {\n normalizeOAuthUrlValue,\n oauthProviderPlaceholders,\n resolveOAuthProvider,\n resolveOAuthUrl,\n} from '@ekanos/integration-schema';\nexport type {\n ResolveOAuthProviderResult,\n ResolveOAuthUrlResult,\n} from '@ekanos/integration-schema';\n\nexport type {\n IntegrationDefinition,\n IntegrationComponentDeclarations,\n ActivationDeclaration,\n ActivationFieldDeclaration,\n IntegrationProposals,\n IntegrationCapabilityDeclaration,\n IntegrationPermissionDeclaration,\n PartnerWidgetDeclaration,\n PartnerToolModule,\n PartnerToolParameters,\n // Widget-invoked server handlers (`actions`): the declaration type a\n // partner needs to export a handler shared between an action and a tool.\n PartnerActionDeclaration,\n ToolClassificationProposal,\n DefinitionCollisionInput,\n FirstPartyInventory,\n // Event surfaces (webhooks, schedules, OAuth): declared in the definition,\n // executed locally by the harness/testing helpers today; the host's real\n // transports (public ingress, scheduler, hosted OAuth callback) bind to\n // these exact declarations later with no partner code change.\n PartnerWebhookDeclaration,\n WebhookSignatureDeclaration,\n WebhookSignatureScheme,\n WebhookEvent,\n WebhookResult,\n // Agent events and channel (plan 222): events a webhook raises to start\n // agents, and the channel a run answers in.\n RaisedAgentEvent,\n PartnerAgentChannelDeclaration,\n AgentChannelRun,\n AgentEventDeclaration,\n AgentConversation,\n AgentTriggerFilter,\n AgentTriggerFilterField,\n AgentChannelReply,\n AgentChannelDeliveryResult,\n AgentChannelRunOutcome,\n AgentChannelHandoff,\n // Routing and Source connections (plan 241): one connection for a whole\n // Source, its events routed to teams by a key such as the organization.\n AgentRouteValue,\n AgentUnroutedEvent,\n RoutingDeclaration,\n RoutingKeyDeclaration,\n RouteKeyOption,\n SourceConnectionDeclaration,\n PartnerScheduleDeclaration,\n ScheduleInvocation,\n ScheduleResult,\n PartnerOAuthDeclaration,\n PartnerOAuthConnectionDeclaration,\n TeamAppDeclaration,\n OAuthProviderDeclaration,\n OAuthSetupDeclaration,\n OAuthTokens,\n // Activation lifecycle hook: cache seeding / eager validation at connect\n // time. Runs after first persist and after every activationData update;\n // v1 errors are non-fatal (logged as a warning, activation stays active).\n OnActivateHandler,\n // Each widget's verdict, computed on the server for home's Needs you.\n AttentionHandler,\n AttentionSignal,\n WidgetVerdict,\n WidgetVerdictTone,\n} from '@ekanos/integration-schema';\n"]}
|
|
@@ -4,4 +4,4 @@
|
|
|
4
4
|
* one contract and no structural twin — F9). This file re-exports them under
|
|
5
5
|
* `@ekanos/sdk/integration`.
|
|
6
6
|
*/
|
|
7
|
-
export type { IntegrationDefinition, IntegrationComponentDeclarations, IntegrationProposals, IntegrationCapabilityDeclaration, IntegrationPermissionDeclaration, PartnerWidgetDeclaration, PartnerToolModule, PartnerToolParameters, ToolClassificationProposal, PartnerWebhookDeclaration, WebhookSignatureDeclaration, WebhookEvent, WebhookResult, PartnerScheduleDeclaration, ScheduleInvocation, ScheduleResult, PartnerOAuthDeclaration, OAuthProviderDeclaration, OAuthTokens, OnActivateHandler, AttentionHandler, } from '@ekanos/integration-schema';
|
|
7
|
+
export type { IntegrationDefinition, IntegrationComponentDeclarations, ActivationDeclaration, ActivationFieldDeclaration, IntegrationProposals, IntegrationCapabilityDeclaration, IntegrationPermissionDeclaration, PartnerWidgetDeclaration, PartnerToolModule, PartnerToolParameters, ToolClassificationProposal, PartnerWebhookDeclaration, WebhookSignatureDeclaration, WebhookEvent, WebhookResult, PartnerScheduleDeclaration, ScheduleInvocation, ScheduleResult, PartnerOAuthDeclaration, OAuthProviderDeclaration, OAuthTokens, OnActivateHandler, AttentionHandler, } from '@ekanos/integration-schema';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/integration/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The partner authoring types are owned by `@ekanos/integration-schema` (the\n * dependency-pure package `@kit/integrations-core` also imports, so there is\n * one contract and no structural twin — F9). This file re-exports them under\n * `@ekanos/sdk/integration`.\n */\nexport type {\n IntegrationDefinition,\n IntegrationComponentDeclarations,\n IntegrationProposals,\n IntegrationCapabilityDeclaration,\n IntegrationPermissionDeclaration,\n PartnerWidgetDeclaration,\n PartnerToolModule,\n PartnerToolParameters,\n ToolClassificationProposal,\n PartnerWebhookDeclaration,\n WebhookSignatureDeclaration,\n WebhookEvent,\n WebhookResult,\n PartnerScheduleDeclaration,\n ScheduleInvocation,\n ScheduleResult,\n PartnerOAuthDeclaration,\n OAuthProviderDeclaration,\n OAuthTokens,\n OnActivateHandler,\n AttentionHandler,\n} from '@ekanos/integration-schema';\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/integration/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * The partner authoring types are owned by `@ekanos/integration-schema` (the\n * dependency-pure package `@kit/integrations-core` also imports, so there is\n * one contract and no structural twin — F9). This file re-exports them under\n * `@ekanos/sdk/integration`.\n */\nexport type {\n IntegrationDefinition,\n IntegrationComponentDeclarations,\n ActivationDeclaration,\n ActivationFieldDeclaration,\n IntegrationProposals,\n IntegrationCapabilityDeclaration,\n IntegrationPermissionDeclaration,\n PartnerWidgetDeclaration,\n PartnerToolModule,\n PartnerToolParameters,\n ToolClassificationProposal,\n PartnerWebhookDeclaration,\n WebhookSignatureDeclaration,\n WebhookEvent,\n WebhookResult,\n PartnerScheduleDeclaration,\n ScheduleInvocation,\n ScheduleResult,\n PartnerOAuthDeclaration,\n OAuthProviderDeclaration,\n OAuthTokens,\n OnActivateHandler,\n AttentionHandler,\n} from '@ekanos/integration-schema';\n"]}
|
|
@@ -61,7 +61,10 @@ export type ActivationFormProps = IntegrationComponentProps & {
|
|
|
61
61
|
onSuccess?: (result: ActivationResult) => void;
|
|
62
62
|
onCancel?: () => void;
|
|
63
63
|
isLoading?: boolean;
|
|
64
|
-
/**
|
|
64
|
+
/**
|
|
65
|
+
* @deprecated Every host renders a connect form inline in its own frame,
|
|
66
|
+
* and `ActivationForm` is always inline; a form can ignore this.
|
|
67
|
+
*/
|
|
65
68
|
inline?: boolean;
|
|
66
69
|
/**
|
|
67
70
|
* The integration is already connected and the person chose to connect it
|
|
@@ -140,7 +143,7 @@ export interface IntegrationMetadata {
|
|
|
140
143
|
* marketplace tile. Always declares its own top-level sidebar Section
|
|
141
144
|
* via `getSidebarNav()` and NEVER declares `getWorkspaceTargets()` —
|
|
142
145
|
* its widgets have no Workspace of their own, so an admin places them
|
|
143
|
-
* on one in the composer (`/admin/sources/[id]/
|
|
146
|
+
* on one in the composer (`/admin/sources/[id]/workspaces`).
|
|
144
147
|
* 'integration' — a connection to an outside system. Made available to a
|
|
145
148
|
* Source by a super-admin, then connected by a team or user (usually
|
|
146
149
|
* OAuth/SSO); has credentials, an activation flow and a marketplace
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.js","sourceRoot":"","sources":["../../src/types/integration.ts"],"names":[],"mappings":"","sourcesContent":["import type { ComponentType } from 'react';\n\nimport type { IconRenderer } from './icon';\n\n// Capability shown on the integration detail page (numbered grid)\nexport interface IntegrationCapability {\n label: string;\n description: string;\n icon?: IconRenderer;\n}\n\n// Permission scope shown on the integration detail page\nexport interface IntegrationPermission {\n label: string;\n detail: string;\n type: 'read' | 'write';\n}\n\n// ---- Integration Health Monitoring (issue #474) -----------------------------\n\n// Higher = healthier. Used internally for \"least healthy wins\" merging.\nexport type HealthStatus = 'healthy' | 'degraded' | 'unhealthy' | 'unknown';\n\n/**\n * Result returned by `BaseIntegration.healthCheck(accountId)`. Routed through\n * `classifyHealth()` (server-side) before writing to\n * `integration_health_status`.\n */\nexport interface HealthCheckResult {\n status: HealthStatus;\n errorCode?: string;\n errorMessage?: string;\n /** Rolling 24h error rate from `account_product_usage_events`, 0..100. */\n errorRatePct?: number;\n /** Sample size used to compute errorRatePct; if below threshold, treated as unknown. */\n sampleSize?: number;\n /** Whether the most recent observed call succeeded. */\n lastObservationSucceeded?: boolean;\n /** Token/credential expiry, if known. Drives token-expiry warnings. */\n tokenExpiresAt?: string;\n /** Free-form per-integration data carried to the dashboard. */\n metadata?: Record<string, unknown>;\n}\n\n// Activation result from integration\nexport interface ActivationResult {\n success: boolean;\n configData?: Record<string, unknown>;\n externalId?: string;\n errorMessage?: string;\n metadata?: Record<string, unknown>;\n}\n\n// Base props that all integration components need\ninterface BaseIntegrationComponentProps {\n accountId: string;\n sourceId?: string;\n integrationConfig?: Record<string, unknown>;\n}\n\n// Discriminated union for product reference - only one allowed\ntype ProductReference =\n | { productId: string; productSlug?: never }\n | { productSlug: string; productId?: never };\n\n// New base type using discriminated union\nexport type IntegrationComponentProps = BaseIntegrationComponentProps &\n ProductReference;\n\n// Marketplace tile props\nexport type MarketplaceTileProps = IntegrationComponentProps & {\n onActivate?: () => void;\n isActivated?: boolean;\n /** Navigation URL for the integration detail page */\n href?: string;\n};\n\n// Activation form props\nexport type ActivationFormProps = IntegrationComponentProps & {\n onSuccess?: (result: ActivationResult) => void;\n onCancel?: () => void;\n isLoading?: boolean;\n /** Render inline instead of in a dialog */\n inline?: boolean;\n /**\n * The integration is already connected and the person chose to connect it\n * again — after a token expired, a password changed, or a health check\n * failed. An OAuth form sends them through sign-in even when a token is\n * stored; a credential form simply accepts new values. Activating again\n * resets the integration's health to unknown until the next check.\n */\n reconnect?: boolean;\n /**\n * The TEAM account context the user is activating within — separate from\n * `accountId`, which for `scope: 'user'` integrations is collapsed to the\n * personal account for activation storage/token purposes. Only consumed by\n * workspace materialization (`materializeWorkspaceOnActivation`), never for\n * activation/token storage itself (plan 009 Part A2). Optional: undefined\n * for team-scoped integrations (their `accountId` already IS the team) and\n * for any caller that hasn't threaded it yet — the server action falls back\n * to `accountId` when absent.\n */\n teamAccountId?: string;\n};\n\n// Integration metadata\nexport interface IntegrationMetadata {\n productId: string;\n productSlug: string;\n integrationName: string;\n description: string;\n category: string;\n version: string;\n icon?: string;\n /** Bundled logo URL — overrides product.logo_path on the marketplace */\n logoPath?: string;\n /** When 'user', activation data is stored under the user's personal account (user.id) instead of the team account */\n scope?: 'user' | 'team';\n /**\n * Set FALSE to assert this integration has NO self-serve activation surface —\n * the marketplace detail page then renders no activation form at all.\n *\n * This is deliberately distinct from \"has no CUSTOM activation form\": an\n * integration that omits `getActivationForm()` still gets the generic one, and\n * six integrations depend on that. Use this flag only when submitting ANY\n * activation form would be a dead end — where `activate()` cannot succeed, so\n * showing a form hands the user a button that cannot work.\n * Undefined/true = normal self-serve activation.\n */\n selfServeActivation?: boolean;\n /**\n * How this integration's MCP tools resolve credentials — the integration's\n * SELF-DECLARATION of machine-executability, consumed dynamically by the\n * workflow engine's fail-closed tool allowlist (isGatewayExposableTool).\n *\n * 'account' — credentials/identity resolve from team- or source-level\n * config via the ToolContext (`getAccountId(ctx)` + `ctx.supabase`).\n * Safe for durable machine-principal execution (workflows): eligible\n * tools (read + public/internal sensitivity) become workflow-callable.\n * 'user' — credentials or identity are personal (ctx.user.id, personal\n * OAuth, session reads like getSupabaseServerClient()/requireUser()).\n * NEVER machine-executable: a workflow would silently ride one\n * employee's personal grant.\n * 'source' — platform-level credentials (diagnostics-class integrations).\n * Not exposed to account workflows.\n *\n * UNDECLARED = fail closed (treated as not machine-executable). Declaring\n * 'account' is a security assertion: the integration's MCP run() handlers\n * must use ctx-based resolution ONLY — no session clients, no personal\n * grants. A guard test in @kit/integrations-workflows enforces the obvious\n * violations (session-client reads in mcp/ code of 'account' declarers).\n */\n credentialModel?: 'account' | 'user' | 'source';\n /**\n * Which KIND of integration this is. **Required** — nothing is inferred from\n * omission. An Integration is any package extending `BaseIntegration`; its\n * kind says who turns it on and whether it needs credentials:\n *\n * 'feature' — an Ekanos-native capability. Enabled for a Source by a\n * super-admin; no third-party credentials, no activation flow, no\n * marketplace tile. Always declares its own top-level sidebar Section\n * via `getSidebarNav()` and NEVER declares `getWorkspaceTargets()` —\n * its widgets have no Workspace of their own, so an admin places them\n * on one in the composer (`/admin/sources/[id]/layout`).\n * 'integration' — a connection to an outside system. Made available to a\n * Source by a super-admin, then connected by a team or user (usually\n * OAuth/SSO); has credentials, an activation flow and a marketplace\n * tile. Declares a Workspace via `getWorkspaceTargets()`, a top-level\n * Section via `getSidebarNav()`, or both (Centrex does both).\n *\n * The asymmetry is one-directional and enforced by the host's CI:\n * a Feature MUST declare a Section and MUST NOT declare a Workspace; a\n * connector MAY declare either or both.\n */\n kind: 'feature' | 'integration';\n /**\n * Product slugs that MUST be attached to the same Source for this product to\n * function — a hard dependency, not a suggestion.\n *\n * The host REFUSES to attach this product to a Source missing any of them,\n * and refuses a detach that would strand a dependent. Admin surfaces render\n * the dependency in both directions (\"Requires X\" / \"Enables Y\").\n *\n * Host CI enforces: every slug is registered, nothing requires itself, no\n * cycles, and a `kind: 'feature'` may require a `'integration'` but never\n * the reverse.\n */\n requires?: string[];\n}\n\n// Widget configuration\nexport interface WidgetConfig {\n id: string;\n name: string;\n component: ComponentType<IntegrationComponentProps>;\n gridSize?: { cols: number; rows: number } | { cols: number; rows: number }[];\n gridPosition?: { col: number; row: number };\n widgetState: 'active' | 'inactive' | 'disabled';\n /**\n * `compact` (a figure tile, 1 → 2 → 4 across its row), `half` or `full`\n * (the design system's widget rules). Unset, it is derived from `layouts.lg.w`.\n */\n size?: 'compact' | 'half' | 'full';\n // React-grid-layout format\n layouts?: {\n lg?: { x: number; y: number; w: number; h: number; maxHeight?: number };\n md?: { x: number; y: number; w: number; h: number; maxHeight?: number };\n sm?: { x: number; y: number; w: number; h: number; maxHeight?: number };\n };\n // Integration metadata for widgets\n integrationMetadata?: IntegrationMetadata;\n category?: { id: string; name: string; slug: string; icon: string | null };\n // Database product ID (UUID) from widget_config table\n productId?: string;\n isCollapsible?: boolean;\n // For collapsed state persistence\n collapsed?: boolean;\n widgetConfigId?: string;\n // Resolved workspace placement (explicit widget_config.workspace_id\n // override, else the product's inheriting attachment). Populated by the\n // dashboard widgets loader; null = no workspace (unscoped dashboard).\n workspaceId?: string | null;\n isPinnable?: boolean;\n isPinned?: boolean;\n // When true, the dashboard renders the \"Ask about this\" AI footer bar for\n // this widget. The widget may still pass `askContext` to the wrapper for a\n // rich snapshot; otherwise a minimal default is used.\n aiFooterEnabled?: boolean;\n // Integration health for this widget's product. `unhealthy` downgrades the\n // widget to `disabled`; `degraded` surfaces a stale-data footer.\n health?: {\n status: HealthStatus;\n lastSuccessAt?: string | null;\n errorMessage?: string | null;\n };\n}\n\n// Database types for integration tables.\n//\n// PARTNER-VISIBLE SUBSET: these row types deliberately OMIT `vault_secret_id`.\n// A vault id is a host handle to a decryptable secret; the partner surface\n// never exposes one — `ctx.secrets` fences it off. Host code keeps the full\n// row because it needs the handle; a parity test pins the SDK type as the\n// host's row minus exactly the host-only fields, so a new column cannot drift\n// in here unnoticed.\nexport interface IntegrationConfig {\n id: string;\n account_id: string | null;\n product_id: string;\n config_type: 'api_credentials' | 'activation_data' | 'settings';\n config_data: Record<string, unknown>;\n status: 'active' | 'inactive' | 'pending' | 'error' | 'suspended';\n is_active: boolean;\n created_at: string;\n updated_at: string;\n created_by: string | null;\n updated_by: string | null;\n}\n\n/**\n * The PARTNER-VISIBLE `data_type` values on `account_product_data` — a strict\n * SUBSET of `@kit/integrations-core`'s union.\n *\n * `'secret'` is deliberately absent. Secret rows are host-managed (one row per\n * secret name, value in Vault, `vault_secret_id` on the row), written only by\n * the capability context's `persistSecret` and read only through\n * `ctx.secrets`. Naming the kind here would advertise a row shape partner code\n * must never address: `ctx.storage` rejects it, and core's generic accessors\n * reject it too (`config-utils.ts`, `assertNotHostOnlyDataType`) precisely\n * because a write there would land the plaintext in the `data` column.\n *\n * When you add an integration-specific kind, add it in BOTH places (core owns\n * the full union) and keep this one partner-appropriate. Prefer `dataSubtype`\n * for orthogonal slicing within a kind (e.g. `data_type='cache'`,\n * `data_subtype='profile'`); reserve a new top-level kind for data that has a\n * distinct lifecycle or is queried independently.\n */\nexport type AccountProductDataType =\n | 'activation'\n | 'settings'\n | 'metrics_summary'\n | 'sync_state'\n | 'cache'\n // Integration-specific kinds — extend here when needed.\n | 'cash_forecast' // quickbooks — user-supplied manual cash-forecast estimates\n | 'tax_config'; // quickbooks — per-user federal/state tax rate config\n\nexport interface AccountProductData {\n id: string;\n account_id: string;\n product_id: string;\n data_type: AccountProductDataType;\n data_subtype?: string;\n data: Record<string, unknown>;\n expires_at?: string;\n integration_config_id?: string;\n external_id?: string;\n created_at: string;\n updated_at: string;\n created_by: string | null;\n updated_by: string | null;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"integration.js","sourceRoot":"","sources":["../../src/types/integration.ts"],"names":[],"mappings":"","sourcesContent":["import type { ComponentType } from 'react';\n\nimport type { IconRenderer } from './icon';\n\n// Capability shown on the integration detail page (numbered grid)\nexport interface IntegrationCapability {\n label: string;\n description: string;\n icon?: IconRenderer;\n}\n\n// Permission scope shown on the integration detail page\nexport interface IntegrationPermission {\n label: string;\n detail: string;\n type: 'read' | 'write';\n}\n\n// ---- Integration Health Monitoring (issue #474) -----------------------------\n\n// Higher = healthier. Used internally for \"least healthy wins\" merging.\nexport type HealthStatus = 'healthy' | 'degraded' | 'unhealthy' | 'unknown';\n\n/**\n * Result returned by `BaseIntegration.healthCheck(accountId)`. Routed through\n * `classifyHealth()` (server-side) before writing to\n * `integration_health_status`.\n */\nexport interface HealthCheckResult {\n status: HealthStatus;\n errorCode?: string;\n errorMessage?: string;\n /** Rolling 24h error rate from `account_product_usage_events`, 0..100. */\n errorRatePct?: number;\n /** Sample size used to compute errorRatePct; if below threshold, treated as unknown. */\n sampleSize?: number;\n /** Whether the most recent observed call succeeded. */\n lastObservationSucceeded?: boolean;\n /** Token/credential expiry, if known. Drives token-expiry warnings. */\n tokenExpiresAt?: string;\n /** Free-form per-integration data carried to the dashboard. */\n metadata?: Record<string, unknown>;\n}\n\n// Activation result from integration\nexport interface ActivationResult {\n success: boolean;\n configData?: Record<string, unknown>;\n externalId?: string;\n errorMessage?: string;\n metadata?: Record<string, unknown>;\n}\n\n// Base props that all integration components need\ninterface BaseIntegrationComponentProps {\n accountId: string;\n sourceId?: string;\n integrationConfig?: Record<string, unknown>;\n}\n\n// Discriminated union for product reference - only one allowed\ntype ProductReference =\n | { productId: string; productSlug?: never }\n | { productSlug: string; productId?: never };\n\n// New base type using discriminated union\nexport type IntegrationComponentProps = BaseIntegrationComponentProps &\n ProductReference;\n\n// Marketplace tile props\nexport type MarketplaceTileProps = IntegrationComponentProps & {\n onActivate?: () => void;\n isActivated?: boolean;\n /** Navigation URL for the integration detail page */\n href?: string;\n};\n\n// Activation form props\nexport type ActivationFormProps = IntegrationComponentProps & {\n onSuccess?: (result: ActivationResult) => void;\n onCancel?: () => void;\n isLoading?: boolean;\n /**\n * @deprecated Every host renders a connect form inline in its own frame,\n * and `ActivationForm` is always inline; a form can ignore this.\n */\n inline?: boolean;\n /**\n * The integration is already connected and the person chose to connect it\n * again — after a token expired, a password changed, or a health check\n * failed. An OAuth form sends them through sign-in even when a token is\n * stored; a credential form simply accepts new values. Activating again\n * resets the integration's health to unknown until the next check.\n */\n reconnect?: boolean;\n /**\n * The TEAM account context the user is activating within — separate from\n * `accountId`, which for `scope: 'user'` integrations is collapsed to the\n * personal account for activation storage/token purposes. Only consumed by\n * workspace materialization (`materializeWorkspaceOnActivation`), never for\n * activation/token storage itself (plan 009 Part A2). Optional: undefined\n * for team-scoped integrations (their `accountId` already IS the team) and\n * for any caller that hasn't threaded it yet — the server action falls back\n * to `accountId` when absent.\n */\n teamAccountId?: string;\n};\n\n// Integration metadata\nexport interface IntegrationMetadata {\n productId: string;\n productSlug: string;\n integrationName: string;\n description: string;\n category: string;\n version: string;\n icon?: string;\n /** Bundled logo URL — overrides product.logo_path on the marketplace */\n logoPath?: string;\n /** When 'user', activation data is stored under the user's personal account (user.id) instead of the team account */\n scope?: 'user' | 'team';\n /**\n * Set FALSE to assert this integration has NO self-serve activation surface —\n * the marketplace detail page then renders no activation form at all.\n *\n * This is deliberately distinct from \"has no CUSTOM activation form\": an\n * integration that omits `getActivationForm()` still gets the generic one, and\n * six integrations depend on that. Use this flag only when submitting ANY\n * activation form would be a dead end — where `activate()` cannot succeed, so\n * showing a form hands the user a button that cannot work.\n * Undefined/true = normal self-serve activation.\n */\n selfServeActivation?: boolean;\n /**\n * How this integration's MCP tools resolve credentials — the integration's\n * SELF-DECLARATION of machine-executability, consumed dynamically by the\n * workflow engine's fail-closed tool allowlist (isGatewayExposableTool).\n *\n * 'account' — credentials/identity resolve from team- or source-level\n * config via the ToolContext (`getAccountId(ctx)` + `ctx.supabase`).\n * Safe for durable machine-principal execution (workflows): eligible\n * tools (read + public/internal sensitivity) become workflow-callable.\n * 'user' — credentials or identity are personal (ctx.user.id, personal\n * OAuth, session reads like getSupabaseServerClient()/requireUser()).\n * NEVER machine-executable: a workflow would silently ride one\n * employee's personal grant.\n * 'source' — platform-level credentials (diagnostics-class integrations).\n * Not exposed to account workflows.\n *\n * UNDECLARED = fail closed (treated as not machine-executable). Declaring\n * 'account' is a security assertion: the integration's MCP run() handlers\n * must use ctx-based resolution ONLY — no session clients, no personal\n * grants. A guard test in @kit/integrations-workflows enforces the obvious\n * violations (session-client reads in mcp/ code of 'account' declarers).\n */\n credentialModel?: 'account' | 'user' | 'source';\n /**\n * Which KIND of integration this is. **Required** — nothing is inferred from\n * omission. An Integration is any package extending `BaseIntegration`; its\n * kind says who turns it on and whether it needs credentials:\n *\n * 'feature' — an Ekanos-native capability. Enabled for a Source by a\n * super-admin; no third-party credentials, no activation flow, no\n * marketplace tile. Always declares its own top-level sidebar Section\n * via `getSidebarNav()` and NEVER declares `getWorkspaceTargets()` —\n * its widgets have no Workspace of their own, so an admin places them\n * on one in the composer (`/admin/sources/[id]/workspaces`).\n * 'integration' — a connection to an outside system. Made available to a\n * Source by a super-admin, then connected by a team or user (usually\n * OAuth/SSO); has credentials, an activation flow and a marketplace\n * tile. Declares a Workspace via `getWorkspaceTargets()`, a top-level\n * Section via `getSidebarNav()`, or both (Centrex does both).\n *\n * The asymmetry is one-directional and enforced by the host's CI:\n * a Feature MUST declare a Section and MUST NOT declare a Workspace; a\n * connector MAY declare either or both.\n */\n kind: 'feature' | 'integration';\n /**\n * Product slugs that MUST be attached to the same Source for this product to\n * function — a hard dependency, not a suggestion.\n *\n * The host REFUSES to attach this product to a Source missing any of them,\n * and refuses a detach that would strand a dependent. Admin surfaces render\n * the dependency in both directions (\"Requires X\" / \"Enables Y\").\n *\n * Host CI enforces: every slug is registered, nothing requires itself, no\n * cycles, and a `kind: 'feature'` may require a `'integration'` but never\n * the reverse.\n */\n requires?: string[];\n}\n\n// Widget configuration\nexport interface WidgetConfig {\n id: string;\n name: string;\n component: ComponentType<IntegrationComponentProps>;\n gridSize?: { cols: number; rows: number } | { cols: number; rows: number }[];\n gridPosition?: { col: number; row: number };\n widgetState: 'active' | 'inactive' | 'disabled';\n /**\n * `compact` (a figure tile, 1 → 2 → 4 across its row), `half` or `full`\n * (the design system's widget rules). Unset, it is derived from `layouts.lg.w`.\n */\n size?: 'compact' | 'half' | 'full';\n // React-grid-layout format\n layouts?: {\n lg?: { x: number; y: number; w: number; h: number; maxHeight?: number };\n md?: { x: number; y: number; w: number; h: number; maxHeight?: number };\n sm?: { x: number; y: number; w: number; h: number; maxHeight?: number };\n };\n // Integration metadata for widgets\n integrationMetadata?: IntegrationMetadata;\n category?: { id: string; name: string; slug: string; icon: string | null };\n // Database product ID (UUID) from widget_config table\n productId?: string;\n isCollapsible?: boolean;\n // For collapsed state persistence\n collapsed?: boolean;\n widgetConfigId?: string;\n // Resolved workspace placement (explicit widget_config.workspace_id\n // override, else the product's inheriting attachment). Populated by the\n // dashboard widgets loader; null = no workspace (unscoped dashboard).\n workspaceId?: string | null;\n isPinnable?: boolean;\n isPinned?: boolean;\n // When true, the dashboard renders the \"Ask about this\" AI footer bar for\n // this widget. The widget may still pass `askContext` to the wrapper for a\n // rich snapshot; otherwise a minimal default is used.\n aiFooterEnabled?: boolean;\n // Integration health for this widget's product. `unhealthy` downgrades the\n // widget to `disabled`; `degraded` surfaces a stale-data footer.\n health?: {\n status: HealthStatus;\n lastSuccessAt?: string | null;\n errorMessage?: string | null;\n };\n}\n\n// Database types for integration tables.\n//\n// PARTNER-VISIBLE SUBSET: these row types deliberately OMIT `vault_secret_id`.\n// A vault id is a host handle to a decryptable secret; the partner surface\n// never exposes one — `ctx.secrets` fences it off. Host code keeps the full\n// row because it needs the handle; a parity test pins the SDK type as the\n// host's row minus exactly the host-only fields, so a new column cannot drift\n// in here unnoticed.\nexport interface IntegrationConfig {\n id: string;\n account_id: string | null;\n product_id: string;\n config_type: 'api_credentials' | 'activation_data' | 'settings';\n config_data: Record<string, unknown>;\n status: 'active' | 'inactive' | 'pending' | 'error' | 'suspended';\n is_active: boolean;\n created_at: string;\n updated_at: string;\n created_by: string | null;\n updated_by: string | null;\n}\n\n/**\n * The PARTNER-VISIBLE `data_type` values on `account_product_data` — a strict\n * SUBSET of `@kit/integrations-core`'s union.\n *\n * `'secret'` is deliberately absent. Secret rows are host-managed (one row per\n * secret name, value in Vault, `vault_secret_id` on the row), written only by\n * the capability context's `persistSecret` and read only through\n * `ctx.secrets`. Naming the kind here would advertise a row shape partner code\n * must never address: `ctx.storage` rejects it, and core's generic accessors\n * reject it too (`config-utils.ts`, `assertNotHostOnlyDataType`) precisely\n * because a write there would land the plaintext in the `data` column.\n *\n * When you add an integration-specific kind, add it in BOTH places (core owns\n * the full union) and keep this one partner-appropriate. Prefer `dataSubtype`\n * for orthogonal slicing within a kind (e.g. `data_type='cache'`,\n * `data_subtype='profile'`); reserve a new top-level kind for data that has a\n * distinct lifecycle or is queried independently.\n */\nexport type AccountProductDataType =\n | 'activation'\n | 'settings'\n | 'metrics_summary'\n | 'sync_state'\n | 'cache'\n // Integration-specific kinds — extend here when needed.\n | 'cash_forecast' // quickbooks — user-supplied manual cash-forecast estimates\n | 'tax_config'; // quickbooks — per-user federal/state tax rate config\n\nexport interface AccountProductData {\n id: string;\n account_id: string;\n product_id: string;\n data_type: AccountProductDataType;\n data_subtype?: string;\n data: Record<string, unknown>;\n expires_at?: string;\n integration_config_id?: string;\n external_id?: string;\n created_at: string;\n updated_at: string;\n created_by: string | null;\n updated_by: string | null;\n}\n"]}
|