@sylphx/sdk 0.4.0 → 0.5.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.
@@ -19559,6 +19559,129 @@ declare function createRestClient(config: RestClientConfig): openapi_fetch.Clien
19559
19559
  */
19560
19560
  type RestClient = ReturnType<typeof createRestClient>;
19561
19561
 
19562
+ declare class InvalidConnectionUrlError extends Error {
19563
+ readonly code: "INVALID_CONNECTION_URL";
19564
+ constructor(message: string);
19565
+ }
19566
+
19567
+ /**
19568
+ * SDK Configuration — ADR-055 Connection URL API
19569
+ *
19570
+ * v0.5.0: The primary entry point is `createClient(url)` which accepts
19571
+ * a `sylphx://` connection URL. The old `createConfig({ ref, publicKey })`
19572
+ * API is removed.
19573
+ *
19574
+ * @example
19575
+ * ```typescript
19576
+ * import { createClient } from '@sylphx/sdk'
19577
+ *
19578
+ * const sylphx = createClient(process.env.SYLPHX_URL!)
19579
+ * // Parses: sylphx://pk_prod_{hex}@bold-river-a1b2c3.sylphx.com
19580
+ * ```
19581
+ */
19582
+
19583
+ /**
19584
+ * SDK Configuration object — immutable, frozen.
19585
+ *
19586
+ * Created by `createClient()` or `createServerClient()`.
19587
+ * Passed to all pure SDK functions (`track()`, `signIn()`, etc.).
19588
+ */
19589
+ interface SylphxConfig {
19590
+ /** The credential string (pk_* or sk_*) */
19591
+ readonly credential: string;
19592
+ /** Credential type: 'pk' (publishable) or 'sk' (secret) */
19593
+ readonly credentialType: 'pk' | 'sk';
19594
+ /** Target environment: dev, stg, prod, or prev */
19595
+ readonly env: 'dev' | 'stg' | 'prod' | 'prev';
19596
+ /** Resource slug (first DNS label), e.g. 'bold-river-a1b2c3' */
19597
+ readonly slug: string;
19598
+ /** Pre-computed API base URL, e.g. 'https://bold-river-a1b2c3.sylphx.com/v1' */
19599
+ readonly baseUrl: string;
19600
+ /** Optional access token for authenticated requests */
19601
+ readonly accessToken?: string;
19602
+ /**
19603
+ * Secret key — populated when credentialType is 'sk'.
19604
+ * Backward-compatible alias for `credential` when credential is sk_*.
19605
+ */
19606
+ readonly secretKey?: string;
19607
+ /**
19608
+ * Publishable key — populated when credentialType is 'pk'.
19609
+ * Backward-compatible alias for `credential` when credential is pk_*.
19610
+ */
19611
+ readonly publicKey?: string;
19612
+ /**
19613
+ * @deprecated Use `slug`. Backward-compatible alias.
19614
+ */
19615
+ readonly ref: string;
19616
+ }
19617
+ /**
19618
+ * Explicit components input — alternative to connection URL string.
19619
+ *
19620
+ * For multi-tenant apps or cases where components are stored separately.
19621
+ */
19622
+ interface SylphxClientInput {
19623
+ /** Resource slug, e.g. 'bold-river-a1b2c3' */
19624
+ slug?: string;
19625
+ /** Publishable key (pk_*) — client-safe */
19626
+ publicKey?: string;
19627
+ /** Secret key (sk_*) — server-side only */
19628
+ secretKey?: string;
19629
+ /** Optional access token */
19630
+ accessToken?: string;
19631
+ /** API domain override (default: sylphx.com) */
19632
+ domain?: string;
19633
+ /**
19634
+ * @deprecated Use `slug`. Accepted for backward compatibility during migration.
19635
+ */
19636
+ ref?: string;
19637
+ /**
19638
+ * @deprecated Use `domain`. Accepted for backward compatibility during migration.
19639
+ */
19640
+ platformUrl?: string;
19641
+ }
19642
+ /**
19643
+ * Create a Sylphx client from a connection URL or explicit components.
19644
+ *
19645
+ * This is the primary SDK entry point for client-side (browser) usage.
19646
+ * Accepts a `sylphx://` connection URL or an explicit components object.
19647
+ *
19648
+ * @example Connection URL (recommended)
19649
+ * ```typescript
19650
+ * const sylphx = createClient(process.env.NEXT_PUBLIC_SYLPHX_URL!)
19651
+ * // Parses: sylphx://pk_prod_{hex}@bold-river-a1b2c3.sylphx.com
19652
+ * ```
19653
+ *
19654
+ * @example Explicit components
19655
+ * ```typescript
19656
+ * const sylphx = createClient({
19657
+ * slug: 'bold-river-a1b2c3',
19658
+ * publicKey: 'pk_prod_f19e...',
19659
+ * })
19660
+ * ```
19661
+ */
19662
+ declare function createClient(input: string | SylphxClientInput): SylphxConfig;
19663
+ /**
19664
+ * Create a Sylphx server client from a connection URL or explicit components.
19665
+ *
19666
+ * Equivalent to `createClient()` but validates that a secret key (sk_*) is provided.
19667
+ * Use this for server-side operations that require elevated permissions.
19668
+ *
19669
+ * @example Connection URL (recommended)
19670
+ * ```typescript
19671
+ * const sylphx = createServerClient(process.env.SYLPHX_SECRET_URL!)
19672
+ * // Parses: sylphx://sk_prod_{hex}@bold-river-a1b2c3.sylphx.com
19673
+ * ```
19674
+ *
19675
+ * @example Explicit components
19676
+ * ```typescript
19677
+ * const sylphx = createServerClient({
19678
+ * slug: 'bold-river-a1b2c3',
19679
+ * secretKey: 'sk_prod_5120...',
19680
+ * })
19681
+ * ```
19682
+ */
19683
+ declare function createServerClient(input: string | SylphxClientInput): SylphxConfig;
19684
+
19562
19685
  /**
19563
19686
  * Consent Functions
19564
19687
  *
@@ -19934,6 +20057,227 @@ declare function validateAndSanitizeKey(key: string | undefined | null): string;
19934
20057
  */
19935
20058
  declare function isDevelopmentRuntime(): boolean;
19936
20059
 
20060
+ /**
20061
+ * Functions Client — Serverless V8 Isolate Functions (ADR-043)
20062
+ *
20063
+ * Deploy and manage serverless functions powered by Supabase Edge Runtime.
20064
+ * Functions run in isolated V8 contexts with < 5ms cold starts.
20065
+ *
20066
+ * ## Key Concepts
20067
+ *
20068
+ * - Functions are TypeScript/JavaScript handlers deployed to the Sylphx edge runtime
20069
+ * - Invoked via HTTP: GET/POST https://{project}.sylphx.app/functions/{name}
20070
+ * - Can access all Sylphx BaaS services via the SDK inside the handler
20071
+ * - Isolated per project — no shared state between projects
20072
+ *
20073
+ * ## Quick Start
20074
+ *
20075
+ * ```typescript
20076
+ * // functions/hello-world/index.ts — your function code
20077
+ * import { createServerClient } from '@sylphx/sdk/server'
20078
+ *
20079
+ * export default async function handler(req: Request): Promise<Response> {
20080
+ * const { name } = await req.json()
20081
+ * return Response.json({ message: `Hello, ${name}!` })
20082
+ * }
20083
+ * ```
20084
+ *
20085
+ * ```bash
20086
+ * # Deploy via CLI
20087
+ * sylphx functions deploy hello-world
20088
+ * # → https://my-project.sylphx.app/functions/hello-world
20089
+ * ```
20090
+ *
20091
+ * ```typescript
20092
+ * // Or deploy programmatically via SDK
20093
+ * import { createConfig, FunctionsClient } from '@sylphx/sdk'
20094
+ *
20095
+ * const config = createConfig({ secretKey: process.env.SYLPHX_SECRET_KEY! })
20096
+ *
20097
+ * await FunctionsClient.deploy(config, {
20098
+ * name: 'hello-world',
20099
+ * code: `export default async (req) => Response.json({ ok: true })`,
20100
+ * })
20101
+ *
20102
+ * // Invoke the function
20103
+ * const result = await FunctionsClient.invoke(config, 'hello-world', { name: 'world' })
20104
+ * ```
20105
+ *
20106
+ * ## Available in handler
20107
+ *
20108
+ * All Web Standard APIs are available inside function handlers:
20109
+ * - `fetch()` — HTTP requests
20110
+ * - `Request`, `Response`, `Headers`, `URL`
20111
+ * - `crypto` — Web Crypto API
20112
+ * - `TextEncoder`, `TextDecoder`
20113
+ * - `Deno.env.get('KEY')` — access injected env vars
20114
+ *
20115
+ * ## Constraints
20116
+ *
20117
+ * - Memory: 150 MB default (max 512 MB)
20118
+ * - Timeout: 30s default (max 120s)
20119
+ * - No filesystem access (`fs` module unavailable)
20120
+ * - No raw socket access (`net` module unavailable)
20121
+ * - npm packages via CDN URL: `import { z } from 'https://esm.sh/zod'`
20122
+ */
20123
+
20124
+ type FunctionStatus = 'active' | 'deploying' | 'failed' | 'disabled';
20125
+ type FunctionRuntime = 'deno';
20126
+ interface FunctionDeployOptions {
20127
+ /**
20128
+ * Function slug — URL-safe name (lowercase kebab-case).
20129
+ * Used in the invocation URL: /functions/{name}
20130
+ */
20131
+ name: string;
20132
+ /**
20133
+ * TypeScript/JavaScript source code.
20134
+ * Must export a default handler function:
20135
+ * export default async function(req: Request): Promise<Response> { ... }
20136
+ *
20137
+ * For functions > 100KB, use the CLI: sylphx functions deploy
20138
+ */
20139
+ code: string;
20140
+ /** Human-readable display name */
20141
+ displayName?: string;
20142
+ /** Short description shown in console */
20143
+ description?: string;
20144
+ /** Memory limit in MB (default: 150, max: 512) */
20145
+ memoryMb?: number;
20146
+ /** Execution timeout in seconds (default: 30, max: 120) */
20147
+ timeoutSeconds?: number;
20148
+ /** Per-function env var overrides (merged with project env vars) */
20149
+ envVars?: Record<string, string>;
20150
+ /** Whether invocations require Sylphx platform auth (default: false) */
20151
+ requireAuth?: boolean;
20152
+ /** Target environment slug (default: 'production') */
20153
+ environment?: string;
20154
+ }
20155
+ interface FunctionRecord {
20156
+ id: string;
20157
+ name: string;
20158
+ displayName: string | null;
20159
+ description: string | null;
20160
+ status: FunctionStatus;
20161
+ version: number;
20162
+ runtime: FunctionRuntime;
20163
+ memoryMb: number;
20164
+ timeoutSeconds: number;
20165
+ requireAuth: boolean;
20166
+ invocationCount: number;
20167
+ errorCount: number;
20168
+ lastInvokedAt: string | null;
20169
+ /** Invocation URL */
20170
+ url: string;
20171
+ createdAt: string;
20172
+ updatedAt: string;
20173
+ }
20174
+ interface FunctionDeployResult {
20175
+ id: string;
20176
+ name: string;
20177
+ version: number;
20178
+ status: FunctionStatus;
20179
+ /** The live invocation URL */
20180
+ url: string;
20181
+ }
20182
+ interface FunctionInvokeOptions {
20183
+ /** HTTP method (default: POST) */
20184
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
20185
+ /** Request headers */
20186
+ headers?: Record<string, string>;
20187
+ /** Request body (JSON-serialized automatically) */
20188
+ body?: unknown;
20189
+ /** Query parameters appended to the URL */
20190
+ query?: Record<string, string>;
20191
+ }
20192
+ interface FunctionListOptions {
20193
+ /** Filter by status */
20194
+ status?: FunctionStatus;
20195
+ /** Environment slug (default: 'production') */
20196
+ environment?: string;
20197
+ /** Max results (default: 50) */
20198
+ limit?: number;
20199
+ }
20200
+ interface FunctionLogsOptions {
20201
+ /** Maximum log entries to return (default: 100) */
20202
+ limit?: number;
20203
+ /** Only return errors */
20204
+ errorsOnly?: boolean;
20205
+ /** ISO timestamp — only logs after this time */
20206
+ since?: string;
20207
+ }
20208
+ interface FunctionLogEntry {
20209
+ id: string;
20210
+ status: 'success' | 'error' | 'timeout';
20211
+ statusCode: number | null;
20212
+ durationMs: number | null;
20213
+ method: string;
20214
+ path: string | null;
20215
+ errorMessage: string | null;
20216
+ createdAt: string;
20217
+ }
20218
+ declare const FunctionsClient: {
20219
+ /**
20220
+ * Deploy (create or update) a function.
20221
+ *
20222
+ * If a function with the same name already exists, it is updated
20223
+ * (version number incremented, code replaced atomically).
20224
+ *
20225
+ * @example
20226
+ * ```typescript
20227
+ * const fn = await FunctionsClient.deploy(config, {
20228
+ * name: 'send-webhook',
20229
+ * code: `
20230
+ * export default async (req: Request) => {
20231
+ * const body = await req.json()
20232
+ * await fetch(body.url, { method: 'POST', body: JSON.stringify(body.payload) })
20233
+ * return Response.json({ ok: true })
20234
+ * }
20235
+ * `,
20236
+ * timeoutSeconds: 10,
20237
+ * })
20238
+ * console.log('Deployed:', fn.url)
20239
+ * ```
20240
+ */
20241
+ readonly deploy: (config: SylphxConfig, options: FunctionDeployOptions) => Promise<FunctionDeployResult>;
20242
+ /**
20243
+ * Get a function by name.
20244
+ */
20245
+ readonly get: (config: SylphxConfig, name: string) => Promise<FunctionRecord>;
20246
+ /**
20247
+ * List all functions for this project.
20248
+ */
20249
+ readonly list: (config: SylphxConfig, options?: FunctionListOptions) => Promise<FunctionRecord[]>;
20250
+ /**
20251
+ * Delete a function permanently.
20252
+ */
20253
+ readonly delete: (config: SylphxConfig, name: string) => Promise<void>;
20254
+ /**
20255
+ * Invoke a function from server-side code.
20256
+ *
20257
+ * For client-side invocations, call the function URL directly via fetch().
20258
+ *
20259
+ * @example
20260
+ * ```typescript
20261
+ * const result = await FunctionsClient.invoke(config, 'process-order', {
20262
+ * body: { orderId: '123', userId: 'user_abc' },
20263
+ * })
20264
+ * ```
20265
+ */
20266
+ readonly invoke: <T = unknown>(config: SylphxConfig, name: string, body?: unknown, options?: FunctionInvokeOptions) => Promise<T>;
20267
+ /**
20268
+ * Retrieve recent invocation logs for a function.
20269
+ *
20270
+ * @example
20271
+ * ```typescript
20272
+ * const logs = await FunctionsClient.logs(config, 'send-webhook', { errorsOnly: true })
20273
+ * for (const entry of logs) {
20274
+ * console.log(`${entry.status} ${entry.durationMs}ms`, entry.errorMessage)
20275
+ * }
20276
+ * ```
20277
+ */
20278
+ readonly logs: (config: SylphxConfig, name: string, options?: FunctionLogsOptions) => Promise<FunctionLogEntry[]>;
20279
+ };
20280
+
19937
20281
  /**
19938
20282
  * Platform ID utilities for the Sylphx SDK
19939
20283
  *
@@ -20483,14 +20827,14 @@ declare function getStreams(): StreamsClient;
20483
20827
  * Sylphx Server SDK
20484
20828
  *
20485
20829
  * Server-side operations using REST API for type safety.
20486
- * Uses Secret Key for authentication - NEVER expose this to client-side.
20830
+ * Uses connection URL (sylphx://sk_*@slug.sylphx.com) for authentication.
20487
20831
  *
20488
20832
  * @example
20489
20833
  * ```typescript
20490
20834
  * import { createServerClient, verifyWebhook } from '@sylphx/sdk/server'
20491
20835
  *
20492
- * const client = createServerClient({
20493
- * secretKey: process.env.SYLPHX_SECRET_KEY!,
20836
+ * const client = createServerRestClient({
20837
+ * secretKey: process.env.SYLPHX_SECRET_URL!,
20494
20838
  * })
20495
20839
  *
20496
20840
  * // REST API calls
@@ -20516,30 +20860,23 @@ interface ServerConfig {
20516
20860
  revalidate?: number;
20517
20861
  }
20518
20862
  /**
20519
- * Create a Server Client for platform operations.
20863
+ * Create a Server REST Client for type-safe API calls.
20520
20864
  *
20521
- * Uses REST API for type-safe API calls.
20522
- * The secret key identifies the app no separate app ID needed.
20865
+ * For the new connection URL API, use `createServerClient()` from '@sylphx/sdk'.
20866
+ * This function creates an openapi-fetch REST client from a raw secret key.
20523
20867
  *
20524
20868
  * @example
20525
20869
  * ```typescript
20526
- * const client = createServerClient({
20527
- * secretKey: process.env.SYLPHX_SECRET_KEY!,
20870
+ * const client = createServerRestClient({
20871
+ * secretKey: 'sk_prod_...',
20528
20872
  * })
20529
20873
  *
20530
- * // Billing
20531
20874
  * const { data: plans } = await client.GET('/billing/plans')
20532
- * const { data: subscription } = await client.GET('/billing/subscription')
20533
- *
20534
- * // Analytics
20535
- * await client.POST('/analytics/track', {
20536
- * body: { events: [{ event: 'purchase', properties: { amount: 99 } }] }
20537
- * })
20538
20875
  * ```
20539
20876
  */
20540
- declare function createServerClient(config: ServerConfig): RestClient;
20877
+ declare function createServerRestClient(config: ServerConfig): RestClient;
20541
20878
  /**
20542
- * Create a Server Client with user context (access token)
20879
+ * Create a Server REST Client with user context (access token)
20543
20880
  */
20544
20881
  declare function createAuthenticatedServerClient(config: ServerConfig, accessToken: string): RestClient;
20545
20882
  /**
@@ -20937,4 +21274,4 @@ declare function getDatabaseConnection(options: AuthenticatedFetchOptions): Prom
20937
21274
  */
20938
21275
  declare function getDatabaseStatus(options: AuthenticatedFetchOptions): Promise<DatabaseStatusInfo>;
20939
21276
 
20940
- export { type AIClient, type AIClientOptions, type AppConfig, type AppMetadata, type ChannelHelper, type ChatCompletionChunk, type ChatCompletionOptions, type ChatCompletionResponse, type ChatCompletionStreamOptions, type ChatMessage, type ConsentType, type DatabaseConnectionInfo, type DatabaseStatusInfo, type EmbeddingOptions, type EmbeddingResponse, type EngagementLeaderboardEntry, type EngagementLeaderboardResult, type EnvironmentType, type FeatureFlagDefinition, type GetAppConfigOptions, type KeyType, type KeyValidationResult, type KvClient, type KvClientOptions, type KvRateLimitResult, type KvSetOptions, type KvZMember, type ModelInfo, type ModelsResponse, type OAuthProviderInfo, type Plan, type ReferralLeaderboardEntry, type ReferralLeaderboardResult, type RestClient, type RestClientConfig as ServerClientConfig, type ServerConfig, type StreamHistoryOptions, type StreamMessage, type StreamsClient, type StreamsClientOptions, type WebhookPayload, type WebhookVerifyOptions, type WebhookVerifyResult, createAI, createAuthenticatedServerClient, createKv, createServerClient, createStreams, createWebhookHandler, decodeUserId, detectEnvironment, detectKeyType, encodeUserId, getAI, getAppConfig, getAppMetadata, getConsentTypes, getCookieNamespace, getDatabaseConnection, getDatabaseStatus, getEngagementLeaderboard, getFeatureFlags, getJwks, getKv, getOAuthProviders, getOAuthProvidersWithInfo, getPlans, getReferralLeaderboard, getStreams, isAppId, isDevelopmentKey, isDevelopmentRuntime, isProductionKey, isSecretKey, resetJwksCache, validateAndSanitizeAppId, validateAndSanitizeKey, validateAndSanitizeSecretKey, validateAppId, validateKey, validateSecretKey, verifyAccessToken, verifyWebhook };
21277
+ export { type AIClient, type AIClientOptions, type AppConfig, type AppMetadata, type ChannelHelper, type ChatCompletionChunk, type ChatCompletionOptions, type ChatCompletionResponse, type ChatCompletionStreamOptions, type ChatMessage, type ConsentType, type DatabaseConnectionInfo, type DatabaseStatusInfo, type EmbeddingOptions, type EmbeddingResponse, type EngagementLeaderboardEntry, type EngagementLeaderboardResult, type EnvironmentType, type FeatureFlagDefinition, type FunctionDeployOptions, type FunctionDeployResult, type FunctionInvokeOptions, type FunctionListOptions, type FunctionLogEntry, type FunctionLogsOptions, type FunctionRecord, type FunctionRuntime, type FunctionStatus, FunctionsClient, type GetAppConfigOptions, InvalidConnectionUrlError, type KeyType, type KeyValidationResult, type KvClient, type KvClientOptions, type KvRateLimitResult, type KvSetOptions, type KvZMember, type ModelInfo, type ModelsResponse, type OAuthProviderInfo, type Plan, type ReferralLeaderboardEntry, type ReferralLeaderboardResult, type RestClient, type RestClientConfig as ServerClientConfig, type ServerConfig, type StreamHistoryOptions, type StreamMessage, type StreamsClient, type StreamsClientOptions, type SylphxClientInput, type SylphxConfig, type WebhookPayload, type WebhookVerifyOptions, type WebhookVerifyResult, createAI, createAuthenticatedServerClient, createClient, createKv, createServerClient, createServerRestClient, createStreams, createWebhookHandler, decodeUserId, detectEnvironment, detectKeyType, encodeUserId, getAI, getAppConfig, getAppMetadata, getConsentTypes, getCookieNamespace, getDatabaseConnection, getDatabaseStatus, getEngagementLeaderboard, getFeatureFlags, getJwks, getKv, getOAuthProviders, getOAuthProvidersWithInfo, getPlans, getReferralLeaderboard, getStreams, isAppId, isDevelopmentKey, isDevelopmentRuntime, isProductionKey, isSecretKey, resetJwksCache, validateAndSanitizeAppId, validateAndSanitizeKey, validateAndSanitizeSecretKey, validateAppId, validateKey, validateSecretKey, verifyAccessToken, verifyWebhook };