@adaptive-ai/sdk 0.1.28 → 0.1.31
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/dist/server/index.d.ts +227 -19
- package/dist/server/index.js +26 -2
- package/package.json +6 -1
package/dist/server/index.d.ts
CHANGED
|
@@ -3,7 +3,10 @@
|
|
|
3
3
|
import * as _trpc_client from '@trpc/client';
|
|
4
4
|
import * as _trpc_server from '@trpc/server';
|
|
5
5
|
import * as _trpc_server_rpc from '@trpc/server/rpc';
|
|
6
|
+
import * as plainjob from 'plainjob';
|
|
7
|
+
import { Job, JobStatus } from 'plainjob';
|
|
6
8
|
import superjson from 'superjson';
|
|
9
|
+
import { handleRpc } from 'typed-rpc/server';
|
|
7
10
|
|
|
8
11
|
declare const ProductKind: {
|
|
9
12
|
readonly SUBSCRIPTION: "SUBSCRIPTION";
|
|
@@ -1641,6 +1644,63 @@ export declare const appConfigSchema: z.ZodObject<{
|
|
|
1641
1644
|
stopAt?: string | undefined;
|
|
1642
1645
|
maxExecutions?: number | undefined;
|
|
1643
1646
|
}>, "many">;
|
|
1647
|
+
events: z.ZodDefault<z.ZodArray<z.ZodObject<{
|
|
1648
|
+
provider: z.ZodNativeEnum<{
|
|
1649
|
+
readonly AC1: "AC1";
|
|
1650
|
+
readonly GITHUB_USER: "GITHUB_USER";
|
|
1651
|
+
readonly GITHUB_BOT: "GITHUB_BOT";
|
|
1652
|
+
readonly GOOGLE: "GOOGLE";
|
|
1653
|
+
readonly SLACK: "SLACK";
|
|
1654
|
+
readonly SLACK_BOT: "SLACK_BOT";
|
|
1655
|
+
readonly DISCORD: "DISCORD";
|
|
1656
|
+
readonly NOTION: "NOTION";
|
|
1657
|
+
readonly TWITTER: "TWITTER";
|
|
1658
|
+
readonly LINKEDIN: "LINKEDIN";
|
|
1659
|
+
readonly YAHOO: "YAHOO";
|
|
1660
|
+
readonly FIGMA: "FIGMA";
|
|
1661
|
+
readonly PLAID: "PLAID";
|
|
1662
|
+
readonly SQUARE: "SQUARE";
|
|
1663
|
+
readonly SHOPIFY: "SHOPIFY";
|
|
1664
|
+
readonly WHOOP: "WHOOP";
|
|
1665
|
+
}>;
|
|
1666
|
+
event: z.ZodString;
|
|
1667
|
+
handler: z.ZodEffects<z.ZodString, string, string>;
|
|
1668
|
+
}, "strip", z.ZodTypeAny, {
|
|
1669
|
+
event: string;
|
|
1670
|
+
provider: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1";
|
|
1671
|
+
handler: string;
|
|
1672
|
+
}, {
|
|
1673
|
+
event: string;
|
|
1674
|
+
provider: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1";
|
|
1675
|
+
handler: string;
|
|
1676
|
+
}>, "many">>;
|
|
1677
|
+
webhooks: z.ZodDefault<z.ZodArray<z.ZodObject<{
|
|
1678
|
+
handler: z.ZodEffects<z.ZodString, string, string>;
|
|
1679
|
+
provider: z.ZodOptional<z.ZodNullable<z.ZodNativeEnum<{
|
|
1680
|
+
readonly AC1: "AC1";
|
|
1681
|
+
readonly GITHUB_USER: "GITHUB_USER";
|
|
1682
|
+
readonly GITHUB_BOT: "GITHUB_BOT";
|
|
1683
|
+
readonly GOOGLE: "GOOGLE";
|
|
1684
|
+
readonly SLACK: "SLACK";
|
|
1685
|
+
readonly SLACK_BOT: "SLACK_BOT";
|
|
1686
|
+
readonly DISCORD: "DISCORD";
|
|
1687
|
+
readonly NOTION: "NOTION";
|
|
1688
|
+
readonly TWITTER: "TWITTER";
|
|
1689
|
+
readonly LINKEDIN: "LINKEDIN";
|
|
1690
|
+
readonly YAHOO: "YAHOO";
|
|
1691
|
+
readonly FIGMA: "FIGMA";
|
|
1692
|
+
readonly PLAID: "PLAID";
|
|
1693
|
+
readonly SQUARE: "SQUARE";
|
|
1694
|
+
readonly SHOPIFY: "SHOPIFY";
|
|
1695
|
+
readonly WHOOP: "WHOOP";
|
|
1696
|
+
}>>>;
|
|
1697
|
+
}, "strip", z.ZodTypeAny, {
|
|
1698
|
+
handler: string;
|
|
1699
|
+
provider?: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1" | null | undefined;
|
|
1700
|
+
}, {
|
|
1701
|
+
handler: string;
|
|
1702
|
+
provider?: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1" | null | undefined;
|
|
1703
|
+
}>, "many">>;
|
|
1644
1704
|
}, "strip", z.ZodTypeAny, {
|
|
1645
1705
|
crons: {
|
|
1646
1706
|
slug: string;
|
|
@@ -1653,6 +1713,15 @@ export declare const appConfigSchema: z.ZodObject<{
|
|
|
1653
1713
|
stopAt?: string | undefined;
|
|
1654
1714
|
maxExecutions?: number | undefined;
|
|
1655
1715
|
}[];
|
|
1716
|
+
events: {
|
|
1717
|
+
event: string;
|
|
1718
|
+
provider: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1";
|
|
1719
|
+
handler: string;
|
|
1720
|
+
}[];
|
|
1721
|
+
webhooks: {
|
|
1722
|
+
handler: string;
|
|
1723
|
+
provider?: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1" | null | undefined;
|
|
1724
|
+
}[];
|
|
1656
1725
|
}, {
|
|
1657
1726
|
crons: {
|
|
1658
1727
|
slug: string;
|
|
@@ -1665,6 +1734,15 @@ export declare const appConfigSchema: z.ZodObject<{
|
|
|
1665
1734
|
stopAt?: string | undefined;
|
|
1666
1735
|
maxExecutions?: number | undefined;
|
|
1667
1736
|
}[];
|
|
1737
|
+
events?: {
|
|
1738
|
+
event: string;
|
|
1739
|
+
provider: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1";
|
|
1740
|
+
handler: string;
|
|
1741
|
+
}[] | undefined;
|
|
1742
|
+
webhooks?: {
|
|
1743
|
+
handler: string;
|
|
1744
|
+
provider?: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1" | null | undefined;
|
|
1745
|
+
}[] | undefined;
|
|
1668
1746
|
}>;
|
|
1669
1747
|
export type AppConfig = z.infer<typeof appConfigSchema>;
|
|
1670
1748
|
declare const AuthProvider: {
|
|
@@ -1686,6 +1764,86 @@ declare const AuthProvider: {
|
|
|
1686
1764
|
readonly WHOOP: "WHOOP";
|
|
1687
1765
|
};
|
|
1688
1766
|
export type AuthProvider = (typeof AuthProvider)[keyof typeof AuthProvider];
|
|
1767
|
+
export type ErrorLogSource = "server" | "client" | "worker";
|
|
1768
|
+
export type ErrorLogEntry = {
|
|
1769
|
+
source: ErrorLogSource;
|
|
1770
|
+
message: string;
|
|
1771
|
+
stack?: string;
|
|
1772
|
+
metadata?: object;
|
|
1773
|
+
requestId?: string;
|
|
1774
|
+
};
|
|
1775
|
+
export type ErrorTracker = ReturnType<typeof createErrorTracker>;
|
|
1776
|
+
declare function createErrorTracker({ environment, dbPath, }: {
|
|
1777
|
+
environment: string;
|
|
1778
|
+
dbPath?: string;
|
|
1779
|
+
}): {
|
|
1780
|
+
captureClientLog: ({ body, requestId, }: {
|
|
1781
|
+
body: string;
|
|
1782
|
+
requestId?: string;
|
|
1783
|
+
}) => {
|
|
1784
|
+
message: string;
|
|
1785
|
+
persisted: boolean;
|
|
1786
|
+
};
|
|
1787
|
+
captureRpcError: ({ result, requestId, }: {
|
|
1788
|
+
result: unknown;
|
|
1789
|
+
requestId?: string;
|
|
1790
|
+
}) => boolean;
|
|
1791
|
+
getRecentErrors: (limit?: number) => unknown[];
|
|
1792
|
+
hasErrors: (sinceMinutes?: number) => boolean;
|
|
1793
|
+
logError: (entry: ErrorLogEntry) => void;
|
|
1794
|
+
registerProcessHandlers: ({ logger, }?: {
|
|
1795
|
+
logger?: Pick<Console, "error">;
|
|
1796
|
+
}) => void;
|
|
1797
|
+
};
|
|
1798
|
+
export type RequestContext = {
|
|
1799
|
+
requestId: string;
|
|
1800
|
+
channelId?: string;
|
|
1801
|
+
hasTasks?: boolean;
|
|
1802
|
+
};
|
|
1803
|
+
export declare function runWithContext<T>(context: RequestContext, fn: () => Promise<T>): Promise<T>;
|
|
1804
|
+
export type QueueLogger = {
|
|
1805
|
+
error: (...args: unknown[]) => void;
|
|
1806
|
+
warn: (...args: unknown[]) => void;
|
|
1807
|
+
info: (...args: unknown[]) => void;
|
|
1808
|
+
debug: (...args: unknown[]) => void;
|
|
1809
|
+
};
|
|
1810
|
+
export type QueueHandlers = Record<string, (payload: any, job: Job) => Promise<void>> & {
|
|
1811
|
+
getJob?: never;
|
|
1812
|
+
};
|
|
1813
|
+
export type QueueApi<THandlers extends QueueHandlers> = {
|
|
1814
|
+
[K in keyof THandlers]: (payload: Parameters<THandlers[K]>[0]) => {
|
|
1815
|
+
id: number;
|
|
1816
|
+
};
|
|
1817
|
+
};
|
|
1818
|
+
declare function createQueue<THandlers extends QueueHandlers>({ dbPath, handlers, errorTracker, queueName, logger, }: {
|
|
1819
|
+
dbPath: string;
|
|
1820
|
+
handlers: THandlers;
|
|
1821
|
+
errorTracker?: Pick<ErrorTracker, "logError">;
|
|
1822
|
+
queueName?: string;
|
|
1823
|
+
logger?: QueueLogger;
|
|
1824
|
+
}): {
|
|
1825
|
+
getActiveJobCount: () => number;
|
|
1826
|
+
getJob: (id: number) => {
|
|
1827
|
+
id: number;
|
|
1828
|
+
type: string;
|
|
1829
|
+
data: string;
|
|
1830
|
+
status: JobStatus;
|
|
1831
|
+
createdAt: number;
|
|
1832
|
+
nextRunAt?: number;
|
|
1833
|
+
failedAt?: number;
|
|
1834
|
+
error?: string;
|
|
1835
|
+
} | undefined;
|
|
1836
|
+
getJobCounts: () => {
|
|
1837
|
+
pending: number;
|
|
1838
|
+
processing: number;
|
|
1839
|
+
done: number;
|
|
1840
|
+
failed: number;
|
|
1841
|
+
};
|
|
1842
|
+
getPendingJobCount: () => number;
|
|
1843
|
+
queue: QueueApi<THandlers>;
|
|
1844
|
+
startWorker: () => plainjob.Worker;
|
|
1845
|
+
};
|
|
1846
|
+
export type QueueController<THandlers extends QueueHandlers> = ReturnType<typeof createQueue<THandlers>>;
|
|
1689
1847
|
export type SignInInput = {
|
|
1690
1848
|
email: string;
|
|
1691
1849
|
phoneNumber?: null | undefined;
|
|
@@ -1697,11 +1855,6 @@ export type SignInInput = {
|
|
|
1697
1855
|
} | {
|
|
1698
1856
|
redirectUri?: string;
|
|
1699
1857
|
};
|
|
1700
|
-
export type RequestContext = {
|
|
1701
|
-
requestId: string;
|
|
1702
|
-
channelId?: string;
|
|
1703
|
-
hasTasks?: boolean;
|
|
1704
|
-
};
|
|
1705
1858
|
export interface EmailHandlerInput {
|
|
1706
1859
|
subject: string;
|
|
1707
1860
|
body: string;
|
|
@@ -2248,15 +2401,15 @@ declare let client: {
|
|
|
2248
2401
|
};
|
|
2249
2402
|
_input_in: {
|
|
2250
2403
|
name: string;
|
|
2251
|
-
kind: "IN_APP_PURCHASE" | "SUBSCRIPTION";
|
|
2252
2404
|
description: string;
|
|
2405
|
+
kind: "IN_APP_PURCHASE" | "SUBSCRIPTION";
|
|
2253
2406
|
price: number;
|
|
2254
2407
|
appId?: string | undefined;
|
|
2255
2408
|
};
|
|
2256
2409
|
_input_out: {
|
|
2257
2410
|
name: string;
|
|
2258
|
-
kind: "IN_APP_PURCHASE" | "SUBSCRIPTION";
|
|
2259
2411
|
description: string;
|
|
2412
|
+
kind: "IN_APP_PURCHASE" | "SUBSCRIPTION";
|
|
2260
2413
|
price: number;
|
|
2261
2414
|
appId?: string | undefined;
|
|
2262
2415
|
};
|
|
@@ -2266,8 +2419,8 @@ declare let client: {
|
|
|
2266
2419
|
purchaseLink: string;
|
|
2267
2420
|
id: string;
|
|
2268
2421
|
name: string;
|
|
2269
|
-
kind: ProductKind;
|
|
2270
2422
|
description: string;
|
|
2423
|
+
kind: ProductKind;
|
|
2271
2424
|
price: number;
|
|
2272
2425
|
}>>;
|
|
2273
2426
|
};
|
|
@@ -2357,8 +2510,8 @@ declare let client: {
|
|
|
2357
2510
|
purchaseLink: string;
|
|
2358
2511
|
id: string;
|
|
2359
2512
|
name: string;
|
|
2360
|
-
kind: ProductKind;
|
|
2361
2513
|
description: string;
|
|
2514
|
+
kind: ProductKind;
|
|
2362
2515
|
price: number;
|
|
2363
2516
|
}[]>>;
|
|
2364
2517
|
};
|
|
@@ -2449,8 +2602,8 @@ declare let client: {
|
|
|
2449
2602
|
}, {
|
|
2450
2603
|
id: string;
|
|
2451
2604
|
name: string;
|
|
2452
|
-
kind: ProductKind;
|
|
2453
2605
|
description: string;
|
|
2606
|
+
kind: ProductKind;
|
|
2454
2607
|
price: number;
|
|
2455
2608
|
}[]>>;
|
|
2456
2609
|
};
|
|
@@ -2729,14 +2882,14 @@ declare let client: {
|
|
|
2729
2882
|
pushToken: string | null | undefined;
|
|
2730
2883
|
};
|
|
2731
2884
|
_input_in: {
|
|
2732
|
-
userId: string;
|
|
2733
2885
|
provider: string;
|
|
2886
|
+
userId: string;
|
|
2734
2887
|
scope: string;
|
|
2735
2888
|
appId?: string | undefined;
|
|
2736
2889
|
};
|
|
2737
2890
|
_input_out: {
|
|
2738
|
-
userId: string;
|
|
2739
2891
|
provider: string;
|
|
2892
|
+
userId: string;
|
|
2740
2893
|
scope: string;
|
|
2741
2894
|
appId?: string | undefined;
|
|
2742
2895
|
};
|
|
@@ -3005,15 +3158,15 @@ declare let client: {
|
|
|
3005
3158
|
pushToken: string | null | undefined;
|
|
3006
3159
|
};
|
|
3007
3160
|
_input_in: {
|
|
3008
|
-
connectionToken: string;
|
|
3009
3161
|
url: string;
|
|
3162
|
+
connectionToken: string;
|
|
3010
3163
|
method: string;
|
|
3011
3164
|
body?: any;
|
|
3012
3165
|
headers?: Record<string, string> | undefined;
|
|
3013
3166
|
};
|
|
3014
3167
|
_input_out: {
|
|
3015
|
-
connectionToken: string;
|
|
3016
3168
|
url: string;
|
|
3169
|
+
connectionToken: string;
|
|
3017
3170
|
method: string;
|
|
3018
3171
|
body?: any;
|
|
3019
3172
|
headers?: Record<string, string> | undefined;
|
|
@@ -3298,11 +3451,65 @@ declare let client: {
|
|
|
3298
3451
|
}, string>>;
|
|
3299
3452
|
};
|
|
3300
3453
|
};
|
|
3301
|
-
export
|
|
3454
|
+
export type InitializeServerEnvironmentInput = {
|
|
3302
3455
|
baseUrl: string;
|
|
3303
3456
|
realtimeDomain: string;
|
|
3304
3457
|
guestServicesUrl: string;
|
|
3305
|
-
|
|
3458
|
+
environment: string;
|
|
3459
|
+
apiKey?: string;
|
|
3460
|
+
queueDbPath?: string;
|
|
3461
|
+
errorsDbPath?: string;
|
|
3462
|
+
};
|
|
3463
|
+
export type InitializedServerEnvironment<THandlers extends QueueHandlers = QueueHandlers> = {
|
|
3464
|
+
environment: string;
|
|
3465
|
+
queueDbPath?: string;
|
|
3466
|
+
errorsDbPath?: string;
|
|
3467
|
+
errorTracker?: ErrorTracker;
|
|
3468
|
+
queue?: QueueController<THandlers>;
|
|
3469
|
+
queueWorkerStarted?: boolean;
|
|
3470
|
+
};
|
|
3471
|
+
export type HonoLikeContext<TRequestBody = unknown, TJsonResponse extends Response = Response> = {
|
|
3472
|
+
req: {
|
|
3473
|
+
json(): Promise<TRequestBody>;
|
|
3474
|
+
text(): Promise<string>;
|
|
3475
|
+
header(name: string): string | undefined;
|
|
3476
|
+
method: string;
|
|
3477
|
+
url: string;
|
|
3478
|
+
};
|
|
3479
|
+
json(data: unknown): TJsonResponse;
|
|
3480
|
+
};
|
|
3481
|
+
export type HonoRpcOptions = NonNullable<Parameters<typeof handleRpc>[2]>;
|
|
3482
|
+
export type HonoMiddlewareNext = () => Promise<void>;
|
|
3483
|
+
export type HonoMiddlewareHandler<TContext extends HonoLikeContext = HonoLikeContext> = (context: TContext, next: HonoMiddlewareNext) => Promise<Response | void>;
|
|
3484
|
+
export declare function initializeServerEnvironment<THandlers extends QueueHandlers>({ baseUrl, realtimeDomain, guestServicesUrl, environment, queueDbPath, errorsDbPath, apiKey, }: InitializeServerEnvironmentInput): InitializedServerEnvironment<THandlers>;
|
|
3485
|
+
export declare function getErrorTracker(): {
|
|
3486
|
+
captureClientLog: ({ body, requestId, }: {
|
|
3487
|
+
body: string;
|
|
3488
|
+
requestId?: string;
|
|
3489
|
+
}) => {
|
|
3490
|
+
message: string;
|
|
3491
|
+
persisted: boolean;
|
|
3492
|
+
};
|
|
3493
|
+
captureRpcError: ({ result, requestId, }: {
|
|
3494
|
+
result: unknown;
|
|
3495
|
+
requestId?: string;
|
|
3496
|
+
}) => boolean;
|
|
3497
|
+
getRecentErrors: (limit?: number) => unknown[];
|
|
3498
|
+
hasErrors: (sinceMinutes?: number) => boolean;
|
|
3499
|
+
logError: (entry: ErrorLogEntry) => void;
|
|
3500
|
+
registerProcessHandlers: ({ logger, }?: {
|
|
3501
|
+
logger?: Pick<Console, "error">;
|
|
3502
|
+
}) => void;
|
|
3503
|
+
};
|
|
3504
|
+
export declare function getQueue<THandlers extends QueueHandlers = QueueHandlers>(): NonNullable<InitializedServerEnvironment<THandlers>["queue"]>["queue"] & Pick<QueueController<THandlers>, "getJob">;
|
|
3505
|
+
export declare function honoMiddleware<THandlers extends QueueHandlers, TProcedures extends Parameters<typeof handleRpc>[1], TContext extends HonoLikeContext = HonoLikeContext>({ procedures, jobs, transcoder, rpcPath, loggerPath, queueStatusPath, }: {
|
|
3506
|
+
procedures: TProcedures;
|
|
3507
|
+
jobs?: THandlers;
|
|
3508
|
+
transcoder?: HonoRpcOptions["transcoder"];
|
|
3509
|
+
rpcPath?: string;
|
|
3510
|
+
loggerPath?: string | false;
|
|
3511
|
+
queueStatusPath?: string | false;
|
|
3512
|
+
}): HonoMiddlewareHandler<TContext>;
|
|
3306
3513
|
export type MutationProxy<TClient> = {
|
|
3307
3514
|
[K in keyof TClient as TClient[K] extends {
|
|
3308
3515
|
mutate: (...args: any) => any;
|
|
@@ -3318,9 +3525,6 @@ export type MCP = Omit<MCPBase, "promptAgent"> & {
|
|
|
3318
3525
|
promptAgent: (args: PromptAgentStrictInput) => ReturnType<MCPBase["promptAgent"]>;
|
|
3319
3526
|
};
|
|
3320
3527
|
export declare const mcp: MCP;
|
|
3321
|
-
export declare function getRequestContext(): RequestContext | undefined;
|
|
3322
|
-
export declare function setRequestContext(context: Partial<RequestContext>): void;
|
|
3323
|
-
export declare function runWithContext<T>(context: RequestContext, fn: () => Promise<T>): Promise<T>;
|
|
3324
3528
|
export declare function getBaseUrl(): string;
|
|
3325
3529
|
export declare function getLastStreamTime(): number | null;
|
|
3326
3530
|
export declare function getRealtimeStore<T extends object>({ channelId, onUpdate, }: {
|
|
@@ -3361,4 +3565,8 @@ declare namespace z {
|
|
|
3361
3565
|
export { AnyZodObject, AnyZodTuple, ArrayCardinality, ArrayKeys, AssertArray, AsyncParseReturnType, BRAND, CatchallInput, CatchallOutput, CustomErrorParams, DIRTY, DenormalizedError, EMPTY_PATH, Effect, EnumLike, EnumValues, ErrorMapCtx, FilterEnum, INVALID, Indices, InnerTypeOfFunction, InputTypeOfTuple, InputTypeOfTupleWithRest, IpVersion, IssueData, KeySchema, NEVER, OK, ObjectPair, OuterTypeOfFunction, OutputTypeOfTuple, OutputTypeOfTupleWithRest, ParseContext, ParseInput, ParseParams, ParsePath, ParsePathComponent, ParseResult, ParseReturnType, ParseStatus, PassthroughType, PreprocessEffect, Primitive, ProcessedCreateParams, RawCreateParams, RecordType, Refinement, RefinementCtx, RefinementEffect, SafeParseError, SafeParseReturnType, SafeParseSuccess, Scalars, SomeZodObject, StringValidation, SuperRefinement, SyncParseReturnType, TransformEffect, TypeOf, TypeOf as infer, UnknownKeysParam, Values, Writeable, ZodAny, ZodAnyDef, ZodArray, ZodArrayDef, ZodBigInt, ZodBigIntCheck, ZodBigIntDef, ZodBoolean, ZodBooleanDef, ZodBranded, ZodBrandedDef, ZodCatch, ZodCatchDef, ZodCustomIssue, ZodDate, ZodDateCheck, ZodDateDef, ZodDefault, ZodDefaultDef, ZodDiscriminatedUnion, ZodDiscriminatedUnionDef, ZodDiscriminatedUnionOption, ZodEffects, ZodEffects as ZodTransformer, ZodEffectsDef, ZodEnum, ZodEnumDef, ZodError, ZodErrorMap, ZodFirstPartySchemaTypes, ZodFirstPartyTypeKind, ZodFormattedError, ZodFunction, ZodFunctionDef, ZodIntersection, ZodIntersectionDef, ZodInvalidArgumentsIssue, ZodInvalidDateIssue, ZodInvalidEnumValueIssue, ZodInvalidIntersectionTypesIssue, ZodInvalidLiteralIssue, ZodInvalidReturnTypeIssue, ZodInvalidStringIssue, ZodInvalidTypeIssue, ZodInvalidUnionDiscriminatorIssue, ZodInvalidUnionIssue, ZodIssue, ZodIssueBase, ZodIssueCode, ZodIssueOptionalMessage, ZodLazy, ZodLazyDef, ZodLiteral, ZodLiteralDef, ZodMap, ZodMapDef, ZodNaN, ZodNaNDef, ZodNativeEnum, ZodNativeEnumDef, ZodNever, ZodNeverDef, ZodNonEmptyArray, ZodNotFiniteIssue, ZodNotMultipleOfIssue, ZodNull, ZodNullDef, ZodNullable, ZodNullableDef, ZodNullableType, ZodNumber, ZodNumberCheck, ZodNumberDef, ZodObject, ZodObjectDef, ZodOptional, ZodOptionalDef, ZodOptionalType, ZodParsedType, ZodPipeline, ZodPipelineDef, ZodPromise, ZodPromiseDef, ZodRawShape, ZodReadonly, ZodReadonlyDef, ZodRecord, ZodRecordDef, ZodSet, ZodSetDef, ZodString, ZodStringCheck, ZodStringDef, ZodSymbol, ZodSymbolDef, ZodTooBigIssue, ZodTooSmallIssue, ZodTuple, ZodTupleDef, ZodTupleItems, ZodType, ZodType as Schema, ZodType as ZodSchema, ZodTypeAny, ZodTypeDef, ZodUndefined, ZodUndefinedDef, ZodUnion, ZodUnionDef, ZodUnionOptions, ZodUnknown, ZodUnknownDef, ZodUnrecognizedKeysIssue, ZodVoid, ZodVoidDef, addIssueToContext, anyType as any, arrayOutputType, arrayType as array, baseObjectInputType, baseObjectOutputType, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, datetimeRegex, deoptional, discriminatedUnionType as discriminatedUnion, effectsType as effect, effectsType as transformer, enumType as enum, errorMap as defaultErrorMap, functionType as function, getErrorMap, getParsedType, inferFlattenedErrors, inferFormattedError, input, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, mergeTypes, nanType as nan, nativeEnumType as nativeEnum, neverType as never, noUnrecognized, nullType as null, nullableType as nullable, numberType as number, objectInputType, objectOutputType, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, output, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setErrorMap, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, tupleType as tuple, typeToFlattenedError, typecast, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void };
|
|
3362
3566
|
}
|
|
3363
3567
|
|
|
3568
|
+
export {
|
|
3569
|
+
Job,
|
|
3570
|
+
};
|
|
3571
|
+
|
|
3364
3572
|
export {};
|
package/dist/server/index.js
CHANGED
|
@@ -1,2 +1,26 @@
|
|
|
1
|
-
import {z
|
|
2
|
-
|
|
1
|
+
import {z}from'zod';import {createTRPCProxyClient,httpLink}from'@trpc/client';import P from'superjson';import {handleRpc}from'typed-rpc/server';import {inspect}from'util';import {AsyncLocalStorage}from'async_hooks';import ke from'better-sqlite3';import {better,defineQueue,defineWorker,JobStatus}from'plainjob';var le={GITHUB_USER:"GITHUB_USER",GITHUB_BOT:"GITHUB_BOT",GOOGLE:"GOOGLE",SLACK:"SLACK",SLACK_BOT:"SLACK_BOT",DISCORD:"DISCORD",NOTION:"NOTION",TWITTER:"TWITTER",LINKEDIN:"LINKEDIN",YAHOO:"YAHOO",FIGMA:"FIGMA",PLAID:"PLAID",SQUARE:"SQUARE",SHOPIFY:"SHOPIFY",WHOOP:"WHOOP"},C={...le,AC1:"AC1"};var fe=z.object({slug:z.string(),name:z.string().optional(),schedule:z.string(),description:z.string().optional(),rpcEndpoint:z.string(),isEnabled:z.boolean().default(true),stopAt:z.string().datetime().optional(),maxExecutions:z.number().optional(),timezone:z.string().optional()}),$=z.string().refine(e=>/^[a-zA-Z0-9_]+$/.test(e),"Must be a valid identifier (letters, numbers, and underscores only)."),me=z.object({handler:$,provider:z.nativeEnum(C).nullish()}),ge=z.object({provider:z.nativeEnum(C),event:z.string().min(1),handler:$}),Ee=z.object({crons:z.array(fe),events:z.array(ge).default([]),webhooks:z.array(me).default([])});function N(e){let r=Object.create(null);for(let t in e){let o=e[t];r[o]=t;}return r}var _={PARSE_ERROR:-32700,BAD_REQUEST:-32600,INTERNAL_SERVER_ERROR:-32603,NOT_IMPLEMENTED:-32603,UNAUTHORIZED:-32001,FORBIDDEN:-32003,NOT_FOUND:-32004,METHOD_NOT_SUPPORTED:-32005,TIMEOUT:-32008,CONFLICT:-32009,PRECONDITION_FAILED:-32012,PAYLOAD_TOO_LARGE:-32013,UNPROCESSABLE_CONTENT:-32022,TOO_MANY_REQUESTS:-32029,CLIENT_CLOSED_REQUEST:-32099};N(_);N(_);typeof window>"u"||"Deno"in window||globalThis.process?.env?.NODE_ENV==="test"||!!globalThis.process?.env?.JEST_WORKER_ID||!!globalThis.process?.env?.VITEST_WORKER_ID;var x=class e extends Error{static prefix="__MISSING AUTH FOR SCOPE";static jsonRpcCode=-32001;constructor({provider:r,scope:t,accountId:o,popup:n=false}){let s=btoa(JSON.stringify({provider:r,scope:t,accountId:o}));super(`${e.prefix}: ${s}${n?" --popup":" end"}`);}jsonRpcError(){return {code:e.jsonRpcCode,message:this.message}}static check(r){return r?.message?.startsWith(e.prefix)}};var ne=new AsyncLocalStorage;function F(){return ne.getStore()}async function oe(e,r){return ne.run(e,r)}function se({environment:e,dbPath:r="errors.db"}){let t=new ke(r,{fileMustExist:false});t.pragma("journal_mode = WAL"),t.exec(`
|
|
2
|
+
CREATE TABLE IF NOT EXISTS error_logs (
|
|
3
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
4
|
+
environment TEXT NOT NULL,
|
|
5
|
+
source TEXT NOT NULL,
|
|
6
|
+
message TEXT NOT NULL,
|
|
7
|
+
stack TEXT,
|
|
8
|
+
metadata TEXT,
|
|
9
|
+
request_id TEXT,
|
|
10
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch())
|
|
11
|
+
)
|
|
12
|
+
`),t.exec(`
|
|
13
|
+
CREATE INDEX IF NOT EXISTS idx_error_logs_env_created
|
|
14
|
+
ON error_logs (environment, created_at)
|
|
15
|
+
`);let o=t.prepare(`
|
|
16
|
+
INSERT INTO error_logs (environment, source, message, stack, metadata, request_id)
|
|
17
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
18
|
+
`),n=false;function s(d){o.run(e,d.source,d.message,d.stack??null,d.metadata?JSON.stringify(d.metadata):null,d.requestId??null);}function i(d=5){return t.prepare(`
|
|
19
|
+
SELECT COUNT(*) as count FROM error_logs
|
|
20
|
+
WHERE created_at > unixepoch() - ?
|
|
21
|
+
`).get(d*60).count>0}function c(d=50){return t.prepare(`
|
|
22
|
+
SELECT * FROM error_logs
|
|
23
|
+
ORDER BY created_at DESC
|
|
24
|
+
LIMIT ?
|
|
25
|
+
`).all(d)}function a({body:d,requestId:p}){let E=d,m,h;try{let y=JSON.parse(d);E=y.message??d,m=y.stack,h=y.metadata;}catch{}let f=E.startsWith("[console.warn]")||E.startsWith("[console.error]");return f&&s({source:"client",message:E,stack:m,metadata:h,requestId:p}),{message:E,persisted:f}}function u({result:d,requestId:p}){let m=d.json?.error;return m?(s({source:"server",message:m.message??"Unknown RPC error",stack:m.stack,requestId:p,metadata:m.data?{errorData:m.data}:void 0}),true):false}function l({logger:d=console}={}){n||(process.on("uncaughtException",p=>{s({source:"server",message:p.message,stack:p.stack,metadata:{type:"uncaughtException"}}),d.error("Uncaught exception:",p);}),process.on("unhandledRejection",p=>{s({source:"server",message:p instanceof Error?p.message:String(p),stack:p instanceof Error?p.stack:void 0,metadata:{type:"unhandledRejection"}}),d.error("Unhandled rejection:",p);}),n=true);}return {captureClientLog:a,captureRpcError:u,getRecentErrors:c,hasErrors:i,logError:s,registerProcessHandlers:l}}var Le={error:console.error.bind(console),warn:console.warn.bind(console),info:()=>{},debug:()=>{}};function j(e){try{return JSON.parse(e.data)}catch{return null}}function ie({dbPath:e,handlers:r,errorTracker:t,queueName:o="default",logger:n=Le}){let s=new ke(e,{fileMustExist:false});s.pragma("journal_mode = WAL");let i=better(s),c=defineQueue({connection:i}),a=new Proxy({},{get(m,h){return f=>c.add(o,{action:h,payload:f})}});function u(m){return c.getJobById(m)}function l(){return c.countJobs({status:JobStatus.Processing})}function d(){return c.countJobs({status:JobStatus.Pending})}function p(){return {pending:c.countJobs({status:JobStatus.Pending}),processing:c.countJobs({status:JobStatus.Processing}),done:c.countJobs({status:JobStatus.Done}),failed:c.countJobs({status:JobStatus.Failed})}}function E(){let m=defineWorker(o,async h=>{let f=j(h);if(!f)throw new Error(`Failed to parse queue payload for job ${h.id}`);let y=r[f.action];if(!y)throw new Error(`No handler registered for action: ${f.action}`);console.log(`Processing job ${h.id} with action: ${f.action}`),await y(f.payload,h);},{queue:c,logger:n,onCompleted:h=>{let y=j(h)?.action??"unknown";console.log(`Job ${h.id} completed: ${y}`);},onFailed:(h,f)=>{let y=j(h);t?.logError({source:"worker",message:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0,metadata:{jobId:h.id,action:y?.action}}),console.error(`Job ${h.id} failed: ${y?.action??"unknown"}`,f);}});return m.start(),m}return {getActiveJobCount:l,getJob:u,getJobCounts:p,getPendingJobCount:d,queue:a,startWorker:E}}var de=createTRPCProxyClient({transformer:P,links:[]}),w;function Dr({baseUrl:e,realtimeDomain:r,guestServicesUrl:t,environment:o,queueDbPath:n,errorsDbPath:s,apiKey:i}){return globalThis.env||(globalThis.env={},globalThis.env.BASE_URL=e,globalThis.env.REALTIME_DOMAIN=r,globalThis.env.GUEST_SERVICES_URL=t,de=createTRPCProxyClient({transformer:P,links:[httpLink({url:t,transformer:P,headers:()=>{let c=F();return {...c?.requestId?{"x-request-id":c.requestId}:{},...i?{"x-boxman-api-key":i}:{},"x-boxman-app-base-url":e}}})]}),console.log("Adaptive SDK server environment initialized")),w?(w.environment=o,w.queueDbPath=n,w.errorsDbPath=s):w={environment:o,queueDbPath:n,errorsDbPath:s},w}function I(){if(!w)throw new Error("Adaptive SDK server environment is not initialized. Please call initializeServerEnvironment first.");return w}function pe(){let e=I();!e.errorTracker&&e.errorsDbPath&&(e.errorTracker=se({environment:e.environment,dbPath:e.errorsDbPath}),e.errorTracker.registerProcessHandlers());let{errorTracker:r}=e;if(!r)throw new Error("Adaptive SDK error tracking is not initialized. Pass `errorsDbPath` to initializeServerEnvironment first.");return r}function je({handlers:e,queueName:r,logger:t,autoStartWorker:o=true}){let n=I();if(!n.queue){if(!n.queueDbPath)throw new Error("Adaptive SDK queue is not initialized. Pass `queueDbPath` to initializeServerEnvironment first.");n.queue=ie({dbPath:n.queueDbPath,handlers:e,queueName:r,logger:t,errorTracker:n.errorsDbPath?pe():void 0});}o&&!n.queueWorkerStarted&&(n.queue.startWorker(),n.queueWorkerStarted=true);let{queue:s}=n;if(!s)throw new Error("Adaptive SDK queue is not initialized. Pass `queueDbPath` to initializeServerEnvironment first.");return s}function qr(){return new Proxy({},{get(e,r){let t=I();if(!t.queue)throw new Error("Adaptive SDK queue is not initialized. Pass `queueDbPath` to initializeServerEnvironment first.");return r==="getJob"?t.queue.getJob:t.queue.queue[r]}})}function Q(e,r){return r.endsWith("*")?e.startsWith(r.slice(0,-1)):e===r}function Hr({procedures:e,jobs:r,transcoder:t,rpcPath:o="/api/*",loggerPath:n="/_logger",queueStatusPath:s="/_queue/status"}){let i=I(),c=i.errorsDbPath?pe():void 0,a=r&&i.queueDbPath?je({handlers:r}):void 0;return async(u,l)=>{let d=new URL(u.req.url).pathname;if(n&&c&&u.req.method==="POST"&&Q(d,n)){let p=await u.req.text(),E=u.req.header("x-request-id"),{message:m}=c.captureClientLog({body:p,requestId:E??void 0});return console.log("[browser]",m),u.json({status:"ok"})}if(s&&a&&u.req.method==="GET"&&Q(d,s))return u.json({activeJobs:a.getActiveJobCount(),pendingJobs:a.getPendingJobCount()});if(u.req.method==="POST"&&Q(d,o)){let p=await u.req.json(),E=u.req.header("x-request-id"),m=u.req.header("x-channel-id");E||console.warn("Request is missing x-request-id header. Adaptive AI SDK relies on this for request context."),console.log(`[${E}] Starting request ${u.req.method} ${u.req.url}`),m&&console.log(`[${E}] Channel ID: ${m}`);let f=await oe({requestId:E??"unknown-request-id",channelId:m,hasTasks:false},async()=>await handleRpc(p,e,{transcoder:t}));return console.log(`[${E}] Response:`,inspect(f,{depth:3,colors:true})),c?.captureRpcError({result:f,requestId:E??void 0}),u.json(f)}await l();}}var Qe=new Proxy({},{get(e,r){return async t=>{if(globalThis.env===void 0)throw new Error("Adaptive SDK server environment is not initialized. Please call initializeServerEnvironment first.");let n=de[r];if(!n||typeof n.mutate!="function")throw new Error(`Property "${String(r)}" is not a mutation procedure`);return n.mutate(t)}}});function Lr(){return globalThis.env.BASE_URL}var J=null;function Mr(){return J}function Ur({channelId:e,onUpdate:r}){let t=new WebSocket(`wss://${globalThis.env.REALTIME_DOMAIN}/${e}`),o=-1;function n(s){r&&(J=Date.now());try{let i=JSON.parse(s.data.toString());if(i?.id&&i.id>o){let c=P.parse(i.payload);r?.(c),o=i.id;}}catch{}}return t.addEventListener("message",n),{destroy(){t.close(),t.removeEventListener("message",n);}}}async function ae({channelId:e,data:r}){J=Date.now(),await fetch(`https://${globalThis.env.REALTIME_DOMAIN}/${e}`,{method:"POST",body:P.stringify(r)}).catch(console.error);}async function Fr(){let e,r=F()?.channelId;if(!r)throw new Error("API's using `startRealtimeResponse` must be called via `useRealtimeMutation`.");return {next(t){e=t,ae({channelId:r,data:t});},end(){return ae({channelId:r,data:e}),e}}}function ue(e){throw new x({provider:"AC1",popup:true})}async function jr(e){let r=await Qe.getCurrentUser();if(r?.error==="SEED")throw new Error('Call to "getAuth" in seed function is not allowed. Seed functions should not depend on user data.');if(r.userId)return {userId:r.userId,status:"authenticated",signIn:ue,providers:r.providers};if(e?.required)throw new x({provider:"AC1"});return {userId:null,status:"unauthenticated",signIn:ue,providers:[]}}
|
|
26
|
+
export{Ee as appConfigSchema,jr as getAuth,Lr as getBaseUrl,pe as getErrorTracker,Mr as getLastStreamTime,qr as getQueue,Ur as getRealtimeStore,Hr as honoMiddleware,Dr as initializeServerEnvironment,Qe as mcp,oe as runWithContext,ae as setRealtimeStore,Fr as startRealtimeResponse};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adaptive-ai/sdk",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.31",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -18,6 +18,10 @@
|
|
|
18
18
|
"README.md",
|
|
19
19
|
"LICENSE"
|
|
20
20
|
],
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"better-sqlite3": "^12.5.0",
|
|
23
|
+
"plainjob": "^0.0.14"
|
|
24
|
+
},
|
|
21
25
|
"scripts": {
|
|
22
26
|
"build:dev": "pnpm run build && ./distribute-local.sh",
|
|
23
27
|
"lint": "NODE_OPTIONS='--max-old-space-size=8192' eslint --cache .",
|
|
@@ -58,6 +62,7 @@
|
|
|
58
62
|
"@ac1/core": "workspace:*",
|
|
59
63
|
"@ac1/iso": "workspace:*",
|
|
60
64
|
"@types/eslint": "^8.44.2",
|
|
65
|
+
"@types/better-sqlite3": "^7.6.13",
|
|
61
66
|
"@types/lodash": "^4.14.200",
|
|
62
67
|
"@types/node": "^20.14.8",
|
|
63
68
|
"@types/object-inspect": "^1.13.0",
|