@palbase/backend 22.0.1 → 22.1.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.
Files changed (42) hide show
  1. package/dist/bin/palbase-backend.cjs +340 -22
  2. package/dist/bin/palbase-backend.cjs.map +1 -1
  3. package/dist/bin/palbase-backend.js +2 -2
  4. package/dist/{chunk-QYOHMVUW.js → chunk-74XDEF5J.js} +338 -22
  5. package/dist/chunk-74XDEF5J.js.map +1 -0
  6. package/dist/{chunk-SSGAMC26.js → chunk-I3ON7MYF.js} +57 -5
  7. package/dist/chunk-I3ON7MYF.js.map +1 -0
  8. package/dist/{chunk-POYAFBLF.js → chunk-SQC5EIWY.js} +5 -3
  9. package/dist/chunk-SQC5EIWY.js.map +1 -0
  10. package/dist/db/index.cjs +60 -6
  11. package/dist/db/index.cjs.map +1 -1
  12. package/dist/db/index.d.cts +2 -2
  13. package/dist/db/index.d.ts +2 -2
  14. package/dist/db/index.js +7 -3
  15. package/dist/{endpoint-B0LpZixz.d.cts → endpoint-BVT6jcVW.d.cts} +39 -7
  16. package/dist/{endpoint-B0LpZixz.d.ts → endpoint-BVT6jcVW.d.ts} +39 -7
  17. package/dist/engine/index.cjs +340 -22
  18. package/dist/engine/index.cjs.map +1 -1
  19. package/dist/engine/index.d.cts +4 -4
  20. package/dist/engine/index.d.ts +4 -4
  21. package/dist/engine/index.js +2 -2
  22. package/dist/{index-B4W6d2VJ.d.cts → index-BS1gW4nV.d.cts} +24 -25
  23. package/dist/{index-BGSCWlUa.d.cts → index-BqCiHao8.d.cts} +97 -7
  24. package/dist/{index-BCNtlG1w.d.ts → index-CCZqzych.d.ts} +24 -25
  25. package/dist/{index-g-EzitI-.d.ts → index-vwHoS0l2.d.ts} +97 -7
  26. package/dist/index.cjs +244 -6
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +124 -9
  29. package/dist/index.d.ts +124 -9
  30. package/dist/index.js +186 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/openapi/index.d.cts +2 -2
  33. package/dist/openapi/index.d.ts +2 -2
  34. package/dist/{registry-Cw0YEYCg.d.cts → registry-BWttGlaT.d.cts} +1 -1
  35. package/dist/{registry-3BLYv4si.d.ts → registry-Bsuf-orT.d.ts} +1 -1
  36. package/docs/endpoints.md +1 -1
  37. package/docs/errors.md +9 -0
  38. package/docs/llms-full.txt +10 -1
  39. package/package.json +2 -2
  40. package/dist/chunk-POYAFBLF.js.map +0 -1
  41. package/dist/chunk-QYOHMVUW.js.map +0 -1
  42. package/dist/chunk-SSGAMC26.js.map +0 -1
package/dist/index.d.cts CHANGED
@@ -1,13 +1,13 @@
1
- import { g as PalbaseResult, A as AuthSpec, H as HttpError } from './endpoint-B0LpZixz.cjs';
2
- export { h as AuthConfig, B as BadRequest, C as CacheClient, i as ClientInfo, j as Conflict, D as DBClient, k as DBOps, E as ErrorDef, l as ErrorMap, m as ErrorThrowers, F as FileContext, n as Forbidden, o as HttpMethod, L as Logger, M as Materialized, p as Middleware, q as MiddlewareContext, r as MiddlewareHandler, N as NotFound, s as PBRequest, t as PalError, u as PalbaseAnalyticsClient, v as PalbaseAnalyticsManagementNamespace, w as PalbaseAnalyticsProperties, x as PalbaseAnalyticsQueryNamespace, y as PalbaseAttestAndroidParams, z as PalbaseAttestAndroidResult, G as PalbaseAttestiOSParams, I as PalbaseAttestiOSResult, J as PalbaseAuthClient, K as PalbaseBatchOverrideOperation, O as PalbaseBatchSetOverridesResult, Q as PalbaseBindDeviceParams, e as PalbaseBucketClient, U as PalbaseClearAllOverridesResult, V as PalbaseClearOverrideResult, W as PalbaseCohortQueryInput, X as PalbaseCohortResult, Y as PalbaseCollectionRef, Z as PalbaseCountQueryInput, _ as PalbaseCountResult, $ as PalbaseCreateLinkParams, a0 as PalbaseDeviceInfo, a1 as PalbaseDeviceTokenView, P as PalbaseDocsClient, a2 as PalbaseDocumentRef, a3 as PalbaseDocumentSnapshot, a4 as PalbaseEmailClient, a5 as PalbaseEmailSendParams, a6 as PalbaseEmailSendResponse, a7 as PalbaseEventNamesResult, a8 as PalbaseEventsQueryInput, a9 as PalbaseEventsResult, aa as PalbaseFileObject, ab as PalbaseFlag, ac as PalbaseFlagContext, ad as PalbaseFlagSource, ae as PalbaseFlagValue, af as PalbaseFlagVariant, a as PalbaseFlagsClient, ag as PalbaseFlagsServiceClient, ah as PalbaseFunctionsClient, ai as PalbaseFunnelQueryInput, aj as PalbaseFunnelResult, ak as PalbaseIdentifyTraits, al as PalbaseInboxClient, am as PalbaseInboxListOptions, an as PalbaseInboxListResult, ao as PalbaseInboxMessage, ap as PalbaseInboxSendParams, aq as PalbaseInboxSendResponse, ar as PalbaseInitialLink, as as PalbaseInvokeOptions, at as PalbaseLink, au as PalbaseLinkAnalytics, av as PalbaseLinkDetails, aw as PalbaseLinksClient, ax as PalbaseListLinksOptions, ay as PalbaseListLinksResult, az as PalbaseListOptions, aA as PalbaseMatchParams, aB as PalbaseMultiChannelResponse, b as PalbaseNotificationsClient, aC as PalbaseOverviewResult, aD as PalbasePreferences, aE as PalbasePreferencesClient, aF as PalbasePushClient, aG as PalbasePushSendParams, aH as PalbasePushSendResponse, aI as PalbaseQrCodeOptions, aJ as PalbaseQuerySnapshot, c as PalbaseRealtimeClient, aK as PalbaseRegisterDeviceParams, aL as PalbaseRetentionQueryInput, aM as PalbaseRetentionResult, aN as PalbaseSession, aO as PalbaseSetOverrideResult, aP as PalbaseSetOverridesResult, aQ as PalbaseSignedUrlResponse, aR as PalbaseSmsClient, aS as PalbaseSmsSendParams, aT as PalbaseSmsSendResponse, d as PalbaseStorageClient, aU as PalbaseTransformOptions, aV as PalbaseUpdateLinkParams, aW as PalbaseUploadOptions, aX as PalbaseUser, aY as PalbaseUserDetailResult, aZ as PalbaseUsersQueryInput, a_ as PalbaseUsersResult, a$ as PalbaseVerifyRequestSignatureParams, b0 as PalbaseWhereOperator, R as RateLimitConfig, b1 as Ref, S as SecretsService, b2 as TooManyRequests, b3 as TxColumnExpr, b4 as TxInsertShape, b5 as TxInsertValue, b6 as TxNow, T as TxPlanBody, b7 as TxPlanError, b8 as TxPlanHandle, b9 as TxPlanOpResult, ba as TxPlanRejection, f as TxPlanResponse, bb as TxRefError, bc as TxRow, bd as TxRows, be as TxSelectOptions, bf as TxSetShape, bg as TxSetValue, bh as TxTable, bi as TxWhere, bj as TxWireExpr, bk as TxWireGuard, bl as TxWireOp, bm as TxWireRef, bn as TxWireValue, bo as Unauthorized, bp as UserT, bq as VerifiedDevice, br as dec, bs as defineMiddleware, bt as inc, bu as now } from './endpoint-B0LpZixz.cjs';
3
- import { M as ModuleClients } from './index-B4W6d2VJ.cjs';
4
- export { C as Cache, D as Database, a as Documents, F as Flags, L as LimitState, b as Log, N as Notifications, P as Purchases, c as PurchasesService, R as Realtime, d as RequestStore, e as RuntimeServices, S as Secrets, f as SpendOptions, g as Storage, h as StoreEnv, _ as __getRuntime, i as __requestALS, j as __runWithRuntime, k as __setRuntime } from './index-B4W6d2VJ.cjs';
1
+ import { g as PalbaseResult, A as AuthSpec, H as HttpError } from './endpoint-BVT6jcVW.cjs';
2
+ export { h as AuthConfig, B as BadRequest, C as CacheClient, i as ClientInfo, j as Conflict, D as DBClient, k as DBOps, E as ErrorDef, l as ErrorMap, m as ErrorThrowers, F as FileContext, n as Forbidden, o as HttpMethod, L as Logger, M as Materialized, p as Middleware, q as MiddlewareContext, r as MiddlewareHandler, N as NotFound, s as PBRequest, t as PalError, u as PalbaseAnalyticsClient, v as PalbaseAnalyticsManagementNamespace, w as PalbaseAnalyticsProperties, x as PalbaseAnalyticsQueryNamespace, y as PalbaseAttestAndroidParams, z as PalbaseAttestAndroidResult, G as PalbaseAttestiOSParams, I as PalbaseAttestiOSResult, J as PalbaseAuthClient, K as PalbaseBatchOverrideOperation, O as PalbaseBatchSetOverridesResult, Q as PalbaseBindDeviceParams, e as PalbaseBucketClient, U as PalbaseClearAllOverridesResult, V as PalbaseClearOverrideResult, W as PalbaseCohortQueryInput, X as PalbaseCohortResult, Y as PalbaseCollectionRef, Z as PalbaseCountQueryInput, _ as PalbaseCountResult, $ as PalbaseCreateLinkParams, a0 as PalbaseDeviceInfo, a1 as PalbaseDeviceTokenView, P as PalbaseDocsClient, a2 as PalbaseDocumentRef, a3 as PalbaseDocumentSnapshot, a4 as PalbaseEmailClient, a5 as PalbaseEmailSendParams, a6 as PalbaseEmailSendResponse, a7 as PalbaseEventNamesResult, a8 as PalbaseEventsQueryInput, a9 as PalbaseEventsResult, aa as PalbaseFileObject, ab as PalbaseFlag, ac as PalbaseFlagContext, ad as PalbaseFlagSource, ae as PalbaseFlagValue, af as PalbaseFlagVariant, a as PalbaseFlagsClient, ag as PalbaseFlagsServiceClient, ah as PalbaseFunctionsClient, ai as PalbaseFunnelQueryInput, aj as PalbaseFunnelResult, ak as PalbaseIdentifyTraits, al as PalbaseInboxClient, am as PalbaseInboxListOptions, an as PalbaseInboxListResult, ao as PalbaseInboxMessage, ap as PalbaseInboxSendParams, aq as PalbaseInboxSendResponse, ar as PalbaseInitialLink, as as PalbaseInvokeOptions, at as PalbaseLink, au as PalbaseLinkAnalytics, av as PalbaseLinkDetails, aw as PalbaseLinksClient, ax as PalbaseListLinksOptions, ay as PalbaseListLinksResult, az as PalbaseListOptions, aA as PalbaseMatchParams, aB as PalbaseMultiChannelResponse, b as PalbaseNotificationsClient, aC as PalbaseOverviewResult, aD as PalbasePreferences, aE as PalbasePreferencesClient, aF as PalbasePushClient, aG as PalbasePushSendParams, aH as PalbasePushSendResponse, aI as PalbaseQrCodeOptions, aJ as PalbaseQuerySnapshot, c as PalbaseRealtimeClient, aK as PalbaseRegisterDeviceParams, aL as PalbaseRetentionQueryInput, aM as PalbaseRetentionResult, aN as PalbaseSession, aO as PalbaseSetOverrideResult, aP as PalbaseSetOverridesResult, aQ as PalbaseSignedUrlResponse, aR as PalbaseSmsClient, aS as PalbaseSmsSendParams, aT as PalbaseSmsSendResponse, d as PalbaseStorageClient, aU as PalbaseTransformOptions, aV as PalbaseUpdateLinkParams, aW as PalbaseUploadOptions, aX as PalbaseUser, aY as PalbaseUserDetailResult, aZ as PalbaseUsersQueryInput, a_ as PalbaseUsersResult, a$ as PalbaseVerifyRequestSignatureParams, b0 as PalbaseWhereOperator, R as RateLimitConfig, b1 as Ref, S as SecretsService, b2 as TooManyRequests, b3 as TxColumnExpr, b4 as TxInsertShape, b5 as TxInsertValue, b6 as TxNow, T as TxPlanBody, b7 as TxPlanError, b8 as TxPlanHandle, b9 as TxPlanOpResult, ba as TxPlanRejection, f as TxPlanResponse, bb as TxRefError, bc as TxRow, bd as TxRows, be as TxSelectOptions, bf as TxSetShape, bg as TxSetValue, bh as TxTable, bi as TxWhere, bj as TxWireExpr, bk as TxWireGuard, bl as TxWireOp, bm as TxWireRef, bn as TxWireValue, bo as Unauthorized, bp as UserT, bq as VerifiedDevice, br as dec, bs as defineMiddleware, bt as inc, bu as now } from './endpoint-BVT6jcVW.cjs';
3
+ import { M as ModuleClients } from './index-BS1gW4nV.cjs';
4
+ export { C as Cache, D as Database, a as Documents, F as Flags, L as LimitState, b as Log, N as Notifications, P as Purchases, c as PurchasesService, R as Realtime, d as RequestStore, e as RuntimeServices, S as Secrets, f as SpendOptions, g as Storage, h as StoreEnv, _ as __getRuntime, i as __requestALS, j as __runWithRuntime, k as __setRuntime } from './index-BS1gW4nV.cjs';
5
5
  import { EntitlementKey, LimitKey } from './purchases/keys.cjs';
6
- import { S as SchemaDef } from './index-BGSCWlUa.cjs';
7
- export { C as ColumnBuilder, a as ColumnDef, b as ColumnMap, c as ColumnType, d as EXTENSION_DEPENDENCIES, e as EnvServiceDatabase, f as EnvTables, E as EnvTypedDatabase, g as EnvTypedTable, I as InsertShape, O as OnDeleteAction, P as PALBASE_EXTENSIONS, h as PalbaseExtension, i as PolicyBuilder, j as PolicyCommand, k as PolicyDef, l as PolicyMode, R as RawConstraintDef, m as RowShape, n as SchemaInput, T as TableDef, o as TableInput, p as TxPlan, q as TxTables, r as TypedDB, s as TypedTable, t as TypedTx, u as bigint, v as boolean, w as defineSchema, x as enumType, y as integer, z as isPalbaseExtension, A as jsonb, B as makeTypedDB, D as numeric, F as policy, G as raw, H as text, J as timestamp, K as uuid } from './index-BGSCWlUa.cjs';
6
+ import { S as SchemaDef } from './index-BqCiHao8.cjs';
7
+ export { C as ColumnBuilder, a as ColumnDef, b as ColumnMap, c as ColumnType, d as EXTENSION_DEPENDENCIES, e as EmbeddingModelRef, f as EnvServiceDatabase, g as EnvTables, E as EnvTypedDatabase, h as EnvTypedTable, I as InsertShape, O as OnDeleteAction, P as PALBASE_EXTENSIONS, i as PalbaseExtension, j as PolicyBuilder, k as PolicyCommand, l as PolicyDef, m as PolicyMode, R as RawConstraintDef, n as RowShape, o as SchemaInput, T as TableDef, p as TableInput, q as TxPlan, r as TxTables, s as TypedDB, t as TypedTable, u as TypedTx, v as bigint, w as boolean, x as defineSchema, y as enumType, z as integer, A as isPalbaseExtension, B as jsonb, D as makeTypedDB, F as numeric, G as openai, H as policy, J as raw, K as text, L as timestamp, M as uuid, N as vector } from './index-BqCiHao8.cjs';
8
8
  import { TableTypes, Tables } from './db/env.cjs';
9
- import { a as RouteOptions } from './registry-Cw0YEYCg.cjs';
10
- export { B as BucketDef, b as BucketOptions, H as HttpMethodUpper, I as ImageVariant, c as ParamKind, P as ParamMeta, R as RouteMeta, S as STORAGE_CONFIG_KIND, d as StorageConfig, e as StorageInput, T as ThrowDescriptor, f as Upload, U as UploadConfig, g as UploadedObject, h as bucket, i as defineStorage, j as getRoutes, p as parseFileSizeLimit, r as recordThrows, v as validateUploadAgainstStorage } from './registry-Cw0YEYCg.cjs';
9
+ import { a as RouteOptions } from './registry-BWttGlaT.cjs';
10
+ export { B as BucketDef, b as BucketOptions, H as HttpMethodUpper, I as ImageVariant, c as ParamKind, P as ParamMeta, R as RouteMeta, S as STORAGE_CONFIG_KIND, d as StorageConfig, e as StorageInput, T as ThrowDescriptor, f as Upload, U as UploadConfig, g as UploadedObject, h as bucket, i as defineStorage, j as getRoutes, p as parseFileSizeLimit, r as recordThrows, v as validateUploadAgainstStorage } from './registry-BWttGlaT.cjs';
11
11
  import { ZodTypeAny, z } from 'zod';
12
12
  export { z } from 'zod';
13
13
  import 'node:async_hooks';
@@ -251,6 +251,7 @@ interface ColumnJSON {
251
251
  enumName?: string;
252
252
  enumValues?: string[];
253
253
  unique?: boolean;
254
+ dimensions?: number;
254
255
  }
255
256
  /** One RLS policy. Mirrors Go's `schema.PolicyJSON`. */
256
257
  interface PolicyJSON {
@@ -285,12 +286,32 @@ interface TableJSON {
285
286
  name: string;
286
287
  columns: string[];
287
288
  }[];
289
+ search?: SearchJSON;
288
290
  }
289
291
  /** A whole declaration. Mirrors Go's `schema.SchemaJSON`. */
290
292
  interface SchemaJSON {
291
293
  tables: Record<string, TableJSON>;
292
294
  extensions: string[];
293
295
  }
296
+ /** C-4 wire şekli — Go'nun SearchJSON'ıyla ALAN ADI sözleşmesi (C-5). */
297
+ interface SearchJSON {
298
+ text?: {
299
+ columns: string[];
300
+ };
301
+ vector?: {
302
+ column?: string;
303
+ metric: string;
304
+ embed?: {
305
+ provider: string;
306
+ model: string;
307
+ from: string[];
308
+ apiKeyName?: string;
309
+ dimensions?: number;
310
+ baseURL?: string;
311
+ };
312
+ staleness?: "null" | "keep";
313
+ }[];
314
+ }
294
315
  /**
295
316
  * Serialize a `defineSchema(...)` result into the JSON the deploy applies.
296
317
  *
@@ -300,6 +321,100 @@ interface SchemaJSON {
300
321
  */
301
322
  declare function toSchemaJSON(schema: SchemaDef): SchemaJSON;
302
323
 
324
+ /**
325
+ * channels.ts — the realtime channel authorization DSL (spec C-5).
326
+ *
327
+ * `defineChannels({...})` is evaluated at bundle load; the declaration is
328
+ * anchored on globalThis under Symbol.for (the error-registry.ts pattern) so
329
+ * the runtime — a separate module instance — reads the SAME object. The runtime
330
+ * empties that slot before each bundle import and puts it back afterwards, so
331
+ * the declaration belongs to the bundle that made it and not to the process.
332
+ * Entry ORDER is the object's key order and is semantic: first match wins.
333
+ *
334
+ * Undeclared channels are DENIED by the server (fail-closed). ownerOnly()
335
+ * patterns resolve with ZERO server hops; custom entries' authorize() runs
336
+ * in the customer's own runtime with the request scope a controller gets.
337
+ */
338
+ interface ChannelGrant {
339
+ subscribe: boolean;
340
+ publish?: boolean;
341
+ state?: {
342
+ read?: boolean;
343
+ write?: boolean;
344
+ };
345
+ }
346
+ interface ChannelAuthorizeCtx {
347
+ user: {
348
+ id: string;
349
+ };
350
+ params: Record<string, string>;
351
+ }
352
+ interface OwnerEntry {
353
+ kind: "owner";
354
+ }
355
+ interface PublicEntry {
356
+ kind: "public";
357
+ publish?: boolean;
358
+ state?: {
359
+ read?: boolean;
360
+ write?: boolean;
361
+ };
362
+ }
363
+ /** What a handler receives: who published, on which channel, and what. */
364
+ interface ChannelHandlerCtx {
365
+ user: {
366
+ id: string;
367
+ };
368
+ params: Record<string, string>;
369
+ channel: string;
370
+ event: string;
371
+ payload: Record<string, unknown>;
372
+ }
373
+ interface CustomEntry {
374
+ authorize: (ctx: ChannelAuthorizeCtx) => ChannelGrant | null | Promise<ChannelGrant | null>;
375
+ /**
376
+ * Take over publishes on this channel instead of fanning them out.
377
+ *
378
+ * Without it, `channel.send(...)` is relayed to the other subscribers
379
+ * verbatim — fine for a chat message, wrong for anything the client should
380
+ * not be trusted to assert. A bid, a vote, a game move is a REQUEST, and the
381
+ * result is whatever this function decides and then publishes (through
382
+ * `Realtime.broadcast` or `Realtime.state.set`).
383
+ *
384
+ * A function rather than the name of a route: `authorize` is already one and
385
+ * runs in this same scope, so naming an endpoint would mean inventing a
386
+ * resolution step for no gain.
387
+ */
388
+ handler?: (ctx: ChannelHandlerCtx) => void | Promise<void>;
389
+ }
390
+ type ChannelEntry = OwnerEntry | PublicEntry | CustomEntry;
391
+ type ChannelsInput = Record<string, ChannelEntry>;
392
+ interface ChannelsDef {
393
+ entries: Array<{
394
+ pattern: string;
395
+ kind: "owner" | "public" | "custom";
396
+ publish?: boolean;
397
+ state?: {
398
+ read?: boolean;
399
+ write?: boolean;
400
+ };
401
+ authorize?: CustomEntry["authorize"];
402
+ handler?: CustomEntry["handler"];
403
+ }>;
404
+ }
405
+ /** Full-access-to-the-owner pattern: the pattern must carry EXACTLY one {param};
406
+ * the server compares its value to the verified token subject with zero hops. */
407
+ declare function ownerOnly(): OwnerEntry;
408
+ /** Anyone with a valid token may subscribe; publish/state are explicit opt-ins. */
409
+ declare function publicChannel(opts?: {
410
+ publish?: boolean;
411
+ state?: {
412
+ read?: boolean;
413
+ write?: boolean;
414
+ };
415
+ }): PublicEntry;
416
+ declare function defineChannels(map: ChannelsInput): ChannelsDef;
417
+
303
418
  /**
304
419
  * env-gen.ts — generate the `palbase-env.d.ts` text from a `defineSchema()`
305
420
  * result.
@@ -1689,4 +1804,4 @@ declare function __runResourceBoot(envMap: Record<string, string>): Promise<void
1689
1804
  */
1690
1805
  declare function __shutdownResources(): Promise<void>;
1691
1806
 
1692
- export { type AcsOptions, type ApnsOptions, type AuthHookEvent, Body, Client, type ColumnJSON, Controller, type ControllerOptions, DEFAULT_TEMPLATE_LOCALE, type DefinedError, type DefinedErrorWithData, Delete, Deny, type DocumentHookEvent, EGRESS_CONFIG_KIND, EGRESS_TIMEOUT_DEFAULT_MS, EGRESS_TIMEOUT_MAX_MS, EGRESS_TIMEOUT_MIN_MS, type EgressConfig, type EgressInput, type EmailTemplateContent, type EmailTemplateDef, type EmailTemplateOptions, EntitlementKey, FLAGS_CONFIG_KIND, type FcmOptions, type FileDeletedEvent, type FileUploadedEvent, type FlagDef, type FlagJsonObject, type FlagJsonValue, type FlagOptions, type FlagType, type FlagValue, type FlagsConfig, type FlagsInput, Get, Headers, Hook, type HookFn, type HookMeta, HttpError, Job, type JobMeta, type JobOptions, LimitKey, type ModuleClientsConfig, type ModuleTransport, NOTIFICATIONS_CONFIG_KIND, type NotificationsConfig, type NotificationsInput, On, OptionalUser, type OwnedTablesOf, PROVIDER_CATALOG, PalbaseModuleError, PalbaseResult, Param, Patch, type PolicyJSON, Post, type ProviderCatalogEntry, type ProviderDef, type ProviderName, type ProviderOptions, type PurchasesManifest, Put, Query, QueryParams, RESERVED_SECRET_PREFIX, type RegisteredError, Req, RequestId, type RequestOptions, RequireEntitlement, type ResolvedHookClass, type ResolvedJob, type ResolvedWebhook, Resource, type ResourceEnv, RouteOptions, SECRETS_CONFIG_KIND, SchemaDef, type SchemaJSON, type SecretDef, type SecretOptions, type SecretsConfig, type SecretsInput, type Seed, type SeedFor, type SeedJson, type SeedRowFor, type SendgridOptions, type SesOptions, type SignatureSpec, type SmsTemplateContent, type SmsTemplateDef, type SmsTemplateOptions, type SmtpOptions, Spend, type SpendMeta, TEST_USERS_CONFIG_KIND, type TableGraph, type TableJSON, TableTypes, Tables, type TemplatesConfig, type TemplatesInput, type TestUserDef, type TestUserOptions, type TestUsersConfig, type TestUsersInput, TraceId, type TransportConfig, type TwilioOptions, User, Webhook, type WebhookEventHandler, type WebhookMeta, type WebhookOptions, type WebhookProvider, type WebhookRequest, __registerResource, __resetRegisteredControllers, __runResourceBoot, __shutdownResources, buildModuleClients, buildProvider, defineEgress, defineError, defineFlags, defineNotifications, defineSecrets, defineTestUsers, entitlementFor, extractVariables, flag, getErrorRegistry, getHookConfig, getJobConfig, getRegisteredControllers, getWebhookConfig, makeEnvDts, makeHttpClient, makePurchasesDts, reservedSecretKey, secret, spendFor, testUser, toSchemaJSON };
1807
+ export { type AcsOptions, type ApnsOptions, type AuthHookEvent, Body, type ChannelAuthorizeCtx, type ChannelEntry, type ChannelGrant, type ChannelsDef, type ChannelsInput, Client, type ColumnJSON, Controller, type ControllerOptions, DEFAULT_TEMPLATE_LOCALE, type DefinedError, type DefinedErrorWithData, Delete, Deny, type DocumentHookEvent, EGRESS_CONFIG_KIND, EGRESS_TIMEOUT_DEFAULT_MS, EGRESS_TIMEOUT_MAX_MS, EGRESS_TIMEOUT_MIN_MS, type EgressConfig, type EgressInput, type EmailTemplateContent, type EmailTemplateDef, type EmailTemplateOptions, EntitlementKey, FLAGS_CONFIG_KIND, type FcmOptions, type FileDeletedEvent, type FileUploadedEvent, type FlagDef, type FlagJsonObject, type FlagJsonValue, type FlagOptions, type FlagType, type FlagValue, type FlagsConfig, type FlagsInput, Get, Headers, Hook, type HookFn, type HookMeta, HttpError, Job, type JobMeta, type JobOptions, LimitKey, type ModuleClientsConfig, type ModuleTransport, NOTIFICATIONS_CONFIG_KIND, type NotificationsConfig, type NotificationsInput, On, OptionalUser, type OwnedTablesOf, PROVIDER_CATALOG, PalbaseModuleError, PalbaseResult, Param, Patch, type PolicyJSON, Post, type ProviderCatalogEntry, type ProviderDef, type ProviderName, type ProviderOptions, type PurchasesManifest, Put, Query, QueryParams, RESERVED_SECRET_PREFIX, type RegisteredError, Req, RequestId, type RequestOptions, RequireEntitlement, type ResolvedHookClass, type ResolvedJob, type ResolvedWebhook, Resource, type ResourceEnv, RouteOptions, SECRETS_CONFIG_KIND, SchemaDef, type SchemaJSON, type SecretDef, type SecretOptions, type SecretsConfig, type SecretsInput, type Seed, type SeedFor, type SeedJson, type SeedRowFor, type SendgridOptions, type SesOptions, type SignatureSpec, type SmsTemplateContent, type SmsTemplateDef, type SmsTemplateOptions, type SmtpOptions, Spend, type SpendMeta, TEST_USERS_CONFIG_KIND, type TableGraph, type TableJSON, TableTypes, Tables, type TemplatesConfig, type TemplatesInput, type TestUserDef, type TestUserOptions, type TestUsersConfig, type TestUsersInput, TraceId, type TransportConfig, type TwilioOptions, User, Webhook, type WebhookEventHandler, type WebhookMeta, type WebhookOptions, type WebhookProvider, type WebhookRequest, __registerResource, __resetRegisteredControllers, __runResourceBoot, __shutdownResources, buildModuleClients, buildProvider, defineChannels, defineEgress, defineError, defineFlags, defineNotifications, defineSecrets, defineTestUsers, entitlementFor, extractVariables, flag, getErrorRegistry, getHookConfig, getJobConfig, getRegisteredControllers, getWebhookConfig, makeEnvDts, makeHttpClient, makePurchasesDts, ownerOnly, publicChannel, reservedSecretKey, secret, spendFor, testUser, toSchemaJSON };
package/dist/index.d.ts CHANGED
@@ -1,13 +1,13 @@
1
- import { g as PalbaseResult, A as AuthSpec, H as HttpError } from './endpoint-B0LpZixz.js';
2
- export { h as AuthConfig, B as BadRequest, C as CacheClient, i as ClientInfo, j as Conflict, D as DBClient, k as DBOps, E as ErrorDef, l as ErrorMap, m as ErrorThrowers, F as FileContext, n as Forbidden, o as HttpMethod, L as Logger, M as Materialized, p as Middleware, q as MiddlewareContext, r as MiddlewareHandler, N as NotFound, s as PBRequest, t as PalError, u as PalbaseAnalyticsClient, v as PalbaseAnalyticsManagementNamespace, w as PalbaseAnalyticsProperties, x as PalbaseAnalyticsQueryNamespace, y as PalbaseAttestAndroidParams, z as PalbaseAttestAndroidResult, G as PalbaseAttestiOSParams, I as PalbaseAttestiOSResult, J as PalbaseAuthClient, K as PalbaseBatchOverrideOperation, O as PalbaseBatchSetOverridesResult, Q as PalbaseBindDeviceParams, e as PalbaseBucketClient, U as PalbaseClearAllOverridesResult, V as PalbaseClearOverrideResult, W as PalbaseCohortQueryInput, X as PalbaseCohortResult, Y as PalbaseCollectionRef, Z as PalbaseCountQueryInput, _ as PalbaseCountResult, $ as PalbaseCreateLinkParams, a0 as PalbaseDeviceInfo, a1 as PalbaseDeviceTokenView, P as PalbaseDocsClient, a2 as PalbaseDocumentRef, a3 as PalbaseDocumentSnapshot, a4 as PalbaseEmailClient, a5 as PalbaseEmailSendParams, a6 as PalbaseEmailSendResponse, a7 as PalbaseEventNamesResult, a8 as PalbaseEventsQueryInput, a9 as PalbaseEventsResult, aa as PalbaseFileObject, ab as PalbaseFlag, ac as PalbaseFlagContext, ad as PalbaseFlagSource, ae as PalbaseFlagValue, af as PalbaseFlagVariant, a as PalbaseFlagsClient, ag as PalbaseFlagsServiceClient, ah as PalbaseFunctionsClient, ai as PalbaseFunnelQueryInput, aj as PalbaseFunnelResult, ak as PalbaseIdentifyTraits, al as PalbaseInboxClient, am as PalbaseInboxListOptions, an as PalbaseInboxListResult, ao as PalbaseInboxMessage, ap as PalbaseInboxSendParams, aq as PalbaseInboxSendResponse, ar as PalbaseInitialLink, as as PalbaseInvokeOptions, at as PalbaseLink, au as PalbaseLinkAnalytics, av as PalbaseLinkDetails, aw as PalbaseLinksClient, ax as PalbaseListLinksOptions, ay as PalbaseListLinksResult, az as PalbaseListOptions, aA as PalbaseMatchParams, aB as PalbaseMultiChannelResponse, b as PalbaseNotificationsClient, aC as PalbaseOverviewResult, aD as PalbasePreferences, aE as PalbasePreferencesClient, aF as PalbasePushClient, aG as PalbasePushSendParams, aH as PalbasePushSendResponse, aI as PalbaseQrCodeOptions, aJ as PalbaseQuerySnapshot, c as PalbaseRealtimeClient, aK as PalbaseRegisterDeviceParams, aL as PalbaseRetentionQueryInput, aM as PalbaseRetentionResult, aN as PalbaseSession, aO as PalbaseSetOverrideResult, aP as PalbaseSetOverridesResult, aQ as PalbaseSignedUrlResponse, aR as PalbaseSmsClient, aS as PalbaseSmsSendParams, aT as PalbaseSmsSendResponse, d as PalbaseStorageClient, aU as PalbaseTransformOptions, aV as PalbaseUpdateLinkParams, aW as PalbaseUploadOptions, aX as PalbaseUser, aY as PalbaseUserDetailResult, aZ as PalbaseUsersQueryInput, a_ as PalbaseUsersResult, a$ as PalbaseVerifyRequestSignatureParams, b0 as PalbaseWhereOperator, R as RateLimitConfig, b1 as Ref, S as SecretsService, b2 as TooManyRequests, b3 as TxColumnExpr, b4 as TxInsertShape, b5 as TxInsertValue, b6 as TxNow, T as TxPlanBody, b7 as TxPlanError, b8 as TxPlanHandle, b9 as TxPlanOpResult, ba as TxPlanRejection, f as TxPlanResponse, bb as TxRefError, bc as TxRow, bd as TxRows, be as TxSelectOptions, bf as TxSetShape, bg as TxSetValue, bh as TxTable, bi as TxWhere, bj as TxWireExpr, bk as TxWireGuard, bl as TxWireOp, bm as TxWireRef, bn as TxWireValue, bo as Unauthorized, bp as UserT, bq as VerifiedDevice, br as dec, bs as defineMiddleware, bt as inc, bu as now } from './endpoint-B0LpZixz.js';
3
- import { M as ModuleClients } from './index-BCNtlG1w.js';
4
- export { C as Cache, D as Database, a as Documents, F as Flags, L as LimitState, b as Log, N as Notifications, P as Purchases, c as PurchasesService, R as Realtime, d as RequestStore, e as RuntimeServices, S as Secrets, f as SpendOptions, g as Storage, h as StoreEnv, _ as __getRuntime, i as __requestALS, j as __runWithRuntime, k as __setRuntime } from './index-BCNtlG1w.js';
1
+ import { g as PalbaseResult, A as AuthSpec, H as HttpError } from './endpoint-BVT6jcVW.js';
2
+ export { h as AuthConfig, B as BadRequest, C as CacheClient, i as ClientInfo, j as Conflict, D as DBClient, k as DBOps, E as ErrorDef, l as ErrorMap, m as ErrorThrowers, F as FileContext, n as Forbidden, o as HttpMethod, L as Logger, M as Materialized, p as Middleware, q as MiddlewareContext, r as MiddlewareHandler, N as NotFound, s as PBRequest, t as PalError, u as PalbaseAnalyticsClient, v as PalbaseAnalyticsManagementNamespace, w as PalbaseAnalyticsProperties, x as PalbaseAnalyticsQueryNamespace, y as PalbaseAttestAndroidParams, z as PalbaseAttestAndroidResult, G as PalbaseAttestiOSParams, I as PalbaseAttestiOSResult, J as PalbaseAuthClient, K as PalbaseBatchOverrideOperation, O as PalbaseBatchSetOverridesResult, Q as PalbaseBindDeviceParams, e as PalbaseBucketClient, U as PalbaseClearAllOverridesResult, V as PalbaseClearOverrideResult, W as PalbaseCohortQueryInput, X as PalbaseCohortResult, Y as PalbaseCollectionRef, Z as PalbaseCountQueryInput, _ as PalbaseCountResult, $ as PalbaseCreateLinkParams, a0 as PalbaseDeviceInfo, a1 as PalbaseDeviceTokenView, P as PalbaseDocsClient, a2 as PalbaseDocumentRef, a3 as PalbaseDocumentSnapshot, a4 as PalbaseEmailClient, a5 as PalbaseEmailSendParams, a6 as PalbaseEmailSendResponse, a7 as PalbaseEventNamesResult, a8 as PalbaseEventsQueryInput, a9 as PalbaseEventsResult, aa as PalbaseFileObject, ab as PalbaseFlag, ac as PalbaseFlagContext, ad as PalbaseFlagSource, ae as PalbaseFlagValue, af as PalbaseFlagVariant, a as PalbaseFlagsClient, ag as PalbaseFlagsServiceClient, ah as PalbaseFunctionsClient, ai as PalbaseFunnelQueryInput, aj as PalbaseFunnelResult, ak as PalbaseIdentifyTraits, al as PalbaseInboxClient, am as PalbaseInboxListOptions, an as PalbaseInboxListResult, ao as PalbaseInboxMessage, ap as PalbaseInboxSendParams, aq as PalbaseInboxSendResponse, ar as PalbaseInitialLink, as as PalbaseInvokeOptions, at as PalbaseLink, au as PalbaseLinkAnalytics, av as PalbaseLinkDetails, aw as PalbaseLinksClient, ax as PalbaseListLinksOptions, ay as PalbaseListLinksResult, az as PalbaseListOptions, aA as PalbaseMatchParams, aB as PalbaseMultiChannelResponse, b as PalbaseNotificationsClient, aC as PalbaseOverviewResult, aD as PalbasePreferences, aE as PalbasePreferencesClient, aF as PalbasePushClient, aG as PalbasePushSendParams, aH as PalbasePushSendResponse, aI as PalbaseQrCodeOptions, aJ as PalbaseQuerySnapshot, c as PalbaseRealtimeClient, aK as PalbaseRegisterDeviceParams, aL as PalbaseRetentionQueryInput, aM as PalbaseRetentionResult, aN as PalbaseSession, aO as PalbaseSetOverrideResult, aP as PalbaseSetOverridesResult, aQ as PalbaseSignedUrlResponse, aR as PalbaseSmsClient, aS as PalbaseSmsSendParams, aT as PalbaseSmsSendResponse, d as PalbaseStorageClient, aU as PalbaseTransformOptions, aV as PalbaseUpdateLinkParams, aW as PalbaseUploadOptions, aX as PalbaseUser, aY as PalbaseUserDetailResult, aZ as PalbaseUsersQueryInput, a_ as PalbaseUsersResult, a$ as PalbaseVerifyRequestSignatureParams, b0 as PalbaseWhereOperator, R as RateLimitConfig, b1 as Ref, S as SecretsService, b2 as TooManyRequests, b3 as TxColumnExpr, b4 as TxInsertShape, b5 as TxInsertValue, b6 as TxNow, T as TxPlanBody, b7 as TxPlanError, b8 as TxPlanHandle, b9 as TxPlanOpResult, ba as TxPlanRejection, f as TxPlanResponse, bb as TxRefError, bc as TxRow, bd as TxRows, be as TxSelectOptions, bf as TxSetShape, bg as TxSetValue, bh as TxTable, bi as TxWhere, bj as TxWireExpr, bk as TxWireGuard, bl as TxWireOp, bm as TxWireRef, bn as TxWireValue, bo as Unauthorized, bp as UserT, bq as VerifiedDevice, br as dec, bs as defineMiddleware, bt as inc, bu as now } from './endpoint-BVT6jcVW.js';
3
+ import { M as ModuleClients } from './index-CCZqzych.js';
4
+ export { C as Cache, D as Database, a as Documents, F as Flags, L as LimitState, b as Log, N as Notifications, P as Purchases, c as PurchasesService, R as Realtime, d as RequestStore, e as RuntimeServices, S as Secrets, f as SpendOptions, g as Storage, h as StoreEnv, _ as __getRuntime, i as __requestALS, j as __runWithRuntime, k as __setRuntime } from './index-CCZqzych.js';
5
5
  import { EntitlementKey, LimitKey } from './purchases/keys.js';
6
- import { S as SchemaDef } from './index-g-EzitI-.js';
7
- export { C as ColumnBuilder, a as ColumnDef, b as ColumnMap, c as ColumnType, d as EXTENSION_DEPENDENCIES, e as EnvServiceDatabase, f as EnvTables, E as EnvTypedDatabase, g as EnvTypedTable, I as InsertShape, O as OnDeleteAction, P as PALBASE_EXTENSIONS, h as PalbaseExtension, i as PolicyBuilder, j as PolicyCommand, k as PolicyDef, l as PolicyMode, R as RawConstraintDef, m as RowShape, n as SchemaInput, T as TableDef, o as TableInput, p as TxPlan, q as TxTables, r as TypedDB, s as TypedTable, t as TypedTx, u as bigint, v as boolean, w as defineSchema, x as enumType, y as integer, z as isPalbaseExtension, A as jsonb, B as makeTypedDB, D as numeric, F as policy, G as raw, H as text, J as timestamp, K as uuid } from './index-g-EzitI-.js';
6
+ import { S as SchemaDef } from './index-vwHoS0l2.js';
7
+ export { C as ColumnBuilder, a as ColumnDef, b as ColumnMap, c as ColumnType, d as EXTENSION_DEPENDENCIES, e as EmbeddingModelRef, f as EnvServiceDatabase, g as EnvTables, E as EnvTypedDatabase, h as EnvTypedTable, I as InsertShape, O as OnDeleteAction, P as PALBASE_EXTENSIONS, i as PalbaseExtension, j as PolicyBuilder, k as PolicyCommand, l as PolicyDef, m as PolicyMode, R as RawConstraintDef, n as RowShape, o as SchemaInput, T as TableDef, p as TableInput, q as TxPlan, r as TxTables, s as TypedDB, t as TypedTable, u as TypedTx, v as bigint, w as boolean, x as defineSchema, y as enumType, z as integer, A as isPalbaseExtension, B as jsonb, D as makeTypedDB, F as numeric, G as openai, H as policy, J as raw, K as text, L as timestamp, M as uuid, N as vector } from './index-vwHoS0l2.js';
8
8
  import { TableTypes, Tables } from './db/env.js';
9
- import { a as RouteOptions } from './registry-3BLYv4si.js';
10
- export { B as BucketDef, b as BucketOptions, H as HttpMethodUpper, I as ImageVariant, c as ParamKind, P as ParamMeta, R as RouteMeta, S as STORAGE_CONFIG_KIND, d as StorageConfig, e as StorageInput, T as ThrowDescriptor, f as Upload, U as UploadConfig, g as UploadedObject, h as bucket, i as defineStorage, j as getRoutes, p as parseFileSizeLimit, r as recordThrows, v as validateUploadAgainstStorage } from './registry-3BLYv4si.js';
9
+ import { a as RouteOptions } from './registry-Bsuf-orT.js';
10
+ export { B as BucketDef, b as BucketOptions, H as HttpMethodUpper, I as ImageVariant, c as ParamKind, P as ParamMeta, R as RouteMeta, S as STORAGE_CONFIG_KIND, d as StorageConfig, e as StorageInput, T as ThrowDescriptor, f as Upload, U as UploadConfig, g as UploadedObject, h as bucket, i as defineStorage, j as getRoutes, p as parseFileSizeLimit, r as recordThrows, v as validateUploadAgainstStorage } from './registry-Bsuf-orT.js';
11
11
  import { ZodTypeAny, z } from 'zod';
12
12
  export { z } from 'zod';
13
13
  import 'node:async_hooks';
@@ -251,6 +251,7 @@ interface ColumnJSON {
251
251
  enumName?: string;
252
252
  enumValues?: string[];
253
253
  unique?: boolean;
254
+ dimensions?: number;
254
255
  }
255
256
  /** One RLS policy. Mirrors Go's `schema.PolicyJSON`. */
256
257
  interface PolicyJSON {
@@ -285,12 +286,32 @@ interface TableJSON {
285
286
  name: string;
286
287
  columns: string[];
287
288
  }[];
289
+ search?: SearchJSON;
288
290
  }
289
291
  /** A whole declaration. Mirrors Go's `schema.SchemaJSON`. */
290
292
  interface SchemaJSON {
291
293
  tables: Record<string, TableJSON>;
292
294
  extensions: string[];
293
295
  }
296
+ /** C-4 wire şekli — Go'nun SearchJSON'ıyla ALAN ADI sözleşmesi (C-5). */
297
+ interface SearchJSON {
298
+ text?: {
299
+ columns: string[];
300
+ };
301
+ vector?: {
302
+ column?: string;
303
+ metric: string;
304
+ embed?: {
305
+ provider: string;
306
+ model: string;
307
+ from: string[];
308
+ apiKeyName?: string;
309
+ dimensions?: number;
310
+ baseURL?: string;
311
+ };
312
+ staleness?: "null" | "keep";
313
+ }[];
314
+ }
294
315
  /**
295
316
  * Serialize a `defineSchema(...)` result into the JSON the deploy applies.
296
317
  *
@@ -300,6 +321,100 @@ interface SchemaJSON {
300
321
  */
301
322
  declare function toSchemaJSON(schema: SchemaDef): SchemaJSON;
302
323
 
324
+ /**
325
+ * channels.ts — the realtime channel authorization DSL (spec C-5).
326
+ *
327
+ * `defineChannels({...})` is evaluated at bundle load; the declaration is
328
+ * anchored on globalThis under Symbol.for (the error-registry.ts pattern) so
329
+ * the runtime — a separate module instance — reads the SAME object. The runtime
330
+ * empties that slot before each bundle import and puts it back afterwards, so
331
+ * the declaration belongs to the bundle that made it and not to the process.
332
+ * Entry ORDER is the object's key order and is semantic: first match wins.
333
+ *
334
+ * Undeclared channels are DENIED by the server (fail-closed). ownerOnly()
335
+ * patterns resolve with ZERO server hops; custom entries' authorize() runs
336
+ * in the customer's own runtime with the request scope a controller gets.
337
+ */
338
+ interface ChannelGrant {
339
+ subscribe: boolean;
340
+ publish?: boolean;
341
+ state?: {
342
+ read?: boolean;
343
+ write?: boolean;
344
+ };
345
+ }
346
+ interface ChannelAuthorizeCtx {
347
+ user: {
348
+ id: string;
349
+ };
350
+ params: Record<string, string>;
351
+ }
352
+ interface OwnerEntry {
353
+ kind: "owner";
354
+ }
355
+ interface PublicEntry {
356
+ kind: "public";
357
+ publish?: boolean;
358
+ state?: {
359
+ read?: boolean;
360
+ write?: boolean;
361
+ };
362
+ }
363
+ /** What a handler receives: who published, on which channel, and what. */
364
+ interface ChannelHandlerCtx {
365
+ user: {
366
+ id: string;
367
+ };
368
+ params: Record<string, string>;
369
+ channel: string;
370
+ event: string;
371
+ payload: Record<string, unknown>;
372
+ }
373
+ interface CustomEntry {
374
+ authorize: (ctx: ChannelAuthorizeCtx) => ChannelGrant | null | Promise<ChannelGrant | null>;
375
+ /**
376
+ * Take over publishes on this channel instead of fanning them out.
377
+ *
378
+ * Without it, `channel.send(...)` is relayed to the other subscribers
379
+ * verbatim — fine for a chat message, wrong for anything the client should
380
+ * not be trusted to assert. A bid, a vote, a game move is a REQUEST, and the
381
+ * result is whatever this function decides and then publishes (through
382
+ * `Realtime.broadcast` or `Realtime.state.set`).
383
+ *
384
+ * A function rather than the name of a route: `authorize` is already one and
385
+ * runs in this same scope, so naming an endpoint would mean inventing a
386
+ * resolution step for no gain.
387
+ */
388
+ handler?: (ctx: ChannelHandlerCtx) => void | Promise<void>;
389
+ }
390
+ type ChannelEntry = OwnerEntry | PublicEntry | CustomEntry;
391
+ type ChannelsInput = Record<string, ChannelEntry>;
392
+ interface ChannelsDef {
393
+ entries: Array<{
394
+ pattern: string;
395
+ kind: "owner" | "public" | "custom";
396
+ publish?: boolean;
397
+ state?: {
398
+ read?: boolean;
399
+ write?: boolean;
400
+ };
401
+ authorize?: CustomEntry["authorize"];
402
+ handler?: CustomEntry["handler"];
403
+ }>;
404
+ }
405
+ /** Full-access-to-the-owner pattern: the pattern must carry EXACTLY one {param};
406
+ * the server compares its value to the verified token subject with zero hops. */
407
+ declare function ownerOnly(): OwnerEntry;
408
+ /** Anyone with a valid token may subscribe; publish/state are explicit opt-ins. */
409
+ declare function publicChannel(opts?: {
410
+ publish?: boolean;
411
+ state?: {
412
+ read?: boolean;
413
+ write?: boolean;
414
+ };
415
+ }): PublicEntry;
416
+ declare function defineChannels(map: ChannelsInput): ChannelsDef;
417
+
303
418
  /**
304
419
  * env-gen.ts — generate the `palbase-env.d.ts` text from a `defineSchema()`
305
420
  * result.
@@ -1689,4 +1804,4 @@ declare function __runResourceBoot(envMap: Record<string, string>): Promise<void
1689
1804
  */
1690
1805
  declare function __shutdownResources(): Promise<void>;
1691
1806
 
1692
- export { type AcsOptions, type ApnsOptions, type AuthHookEvent, Body, Client, type ColumnJSON, Controller, type ControllerOptions, DEFAULT_TEMPLATE_LOCALE, type DefinedError, type DefinedErrorWithData, Delete, Deny, type DocumentHookEvent, EGRESS_CONFIG_KIND, EGRESS_TIMEOUT_DEFAULT_MS, EGRESS_TIMEOUT_MAX_MS, EGRESS_TIMEOUT_MIN_MS, type EgressConfig, type EgressInput, type EmailTemplateContent, type EmailTemplateDef, type EmailTemplateOptions, EntitlementKey, FLAGS_CONFIG_KIND, type FcmOptions, type FileDeletedEvent, type FileUploadedEvent, type FlagDef, type FlagJsonObject, type FlagJsonValue, type FlagOptions, type FlagType, type FlagValue, type FlagsConfig, type FlagsInput, Get, Headers, Hook, type HookFn, type HookMeta, HttpError, Job, type JobMeta, type JobOptions, LimitKey, type ModuleClientsConfig, type ModuleTransport, NOTIFICATIONS_CONFIG_KIND, type NotificationsConfig, type NotificationsInput, On, OptionalUser, type OwnedTablesOf, PROVIDER_CATALOG, PalbaseModuleError, PalbaseResult, Param, Patch, type PolicyJSON, Post, type ProviderCatalogEntry, type ProviderDef, type ProviderName, type ProviderOptions, type PurchasesManifest, Put, Query, QueryParams, RESERVED_SECRET_PREFIX, type RegisteredError, Req, RequestId, type RequestOptions, RequireEntitlement, type ResolvedHookClass, type ResolvedJob, type ResolvedWebhook, Resource, type ResourceEnv, RouteOptions, SECRETS_CONFIG_KIND, SchemaDef, type SchemaJSON, type SecretDef, type SecretOptions, type SecretsConfig, type SecretsInput, type Seed, type SeedFor, type SeedJson, type SeedRowFor, type SendgridOptions, type SesOptions, type SignatureSpec, type SmsTemplateContent, type SmsTemplateDef, type SmsTemplateOptions, type SmtpOptions, Spend, type SpendMeta, TEST_USERS_CONFIG_KIND, type TableGraph, type TableJSON, TableTypes, Tables, type TemplatesConfig, type TemplatesInput, type TestUserDef, type TestUserOptions, type TestUsersConfig, type TestUsersInput, TraceId, type TransportConfig, type TwilioOptions, User, Webhook, type WebhookEventHandler, type WebhookMeta, type WebhookOptions, type WebhookProvider, type WebhookRequest, __registerResource, __resetRegisteredControllers, __runResourceBoot, __shutdownResources, buildModuleClients, buildProvider, defineEgress, defineError, defineFlags, defineNotifications, defineSecrets, defineTestUsers, entitlementFor, extractVariables, flag, getErrorRegistry, getHookConfig, getJobConfig, getRegisteredControllers, getWebhookConfig, makeEnvDts, makeHttpClient, makePurchasesDts, reservedSecretKey, secret, spendFor, testUser, toSchemaJSON };
1807
+ export { type AcsOptions, type ApnsOptions, type AuthHookEvent, Body, type ChannelAuthorizeCtx, type ChannelEntry, type ChannelGrant, type ChannelsDef, type ChannelsInput, Client, type ColumnJSON, Controller, type ControllerOptions, DEFAULT_TEMPLATE_LOCALE, type DefinedError, type DefinedErrorWithData, Delete, Deny, type DocumentHookEvent, EGRESS_CONFIG_KIND, EGRESS_TIMEOUT_DEFAULT_MS, EGRESS_TIMEOUT_MAX_MS, EGRESS_TIMEOUT_MIN_MS, type EgressConfig, type EgressInput, type EmailTemplateContent, type EmailTemplateDef, type EmailTemplateOptions, EntitlementKey, FLAGS_CONFIG_KIND, type FcmOptions, type FileDeletedEvent, type FileUploadedEvent, type FlagDef, type FlagJsonObject, type FlagJsonValue, type FlagOptions, type FlagType, type FlagValue, type FlagsConfig, type FlagsInput, Get, Headers, Hook, type HookFn, type HookMeta, HttpError, Job, type JobMeta, type JobOptions, LimitKey, type ModuleClientsConfig, type ModuleTransport, NOTIFICATIONS_CONFIG_KIND, type NotificationsConfig, type NotificationsInput, On, OptionalUser, type OwnedTablesOf, PROVIDER_CATALOG, PalbaseModuleError, PalbaseResult, Param, Patch, type PolicyJSON, Post, type ProviderCatalogEntry, type ProviderDef, type ProviderName, type ProviderOptions, type PurchasesManifest, Put, Query, QueryParams, RESERVED_SECRET_PREFIX, type RegisteredError, Req, RequestId, type RequestOptions, RequireEntitlement, type ResolvedHookClass, type ResolvedJob, type ResolvedWebhook, Resource, type ResourceEnv, RouteOptions, SECRETS_CONFIG_KIND, SchemaDef, type SchemaJSON, type SecretDef, type SecretOptions, type SecretsConfig, type SecretsInput, type Seed, type SeedFor, type SeedJson, type SeedRowFor, type SendgridOptions, type SesOptions, type SignatureSpec, type SmsTemplateContent, type SmsTemplateDef, type SmsTemplateOptions, type SmtpOptions, Spend, type SpendMeta, TEST_USERS_CONFIG_KIND, type TableGraph, type TableJSON, TableTypes, Tables, type TemplatesConfig, type TemplatesInput, type TestUserDef, type TestUserOptions, type TestUsersConfig, type TestUsersInput, TraceId, type TransportConfig, type TwilioOptions, User, Webhook, type WebhookEventHandler, type WebhookMeta, type WebhookOptions, type WebhookProvider, type WebhookRequest, __registerResource, __resetRegisteredControllers, __runResourceBoot, __shutdownResources, buildModuleClients, buildProvider, defineChannels, defineEgress, defineError, defineFlags, defineNotifications, defineSecrets, defineTestUsers, entitlementFor, extractVariables, flag, getErrorRegistry, getHookConfig, getJobConfig, getRegisteredControllers, getWebhookConfig, makeEnvDts, makeHttpClient, makePurchasesDts, ownerOnly, publicChannel, reservedSecretKey, secret, spendFor, testUser, toSchemaJSON };
package/dist/index.js CHANGED
@@ -11,12 +11,14 @@ import {
11
11
  jsonb,
12
12
  makeTypedDB,
13
13
  numeric,
14
+ openai,
14
15
  policy,
15
16
  raw,
16
17
  text,
17
18
  timestamp,
18
- uuid
19
- } from "./chunk-SSGAMC26.js";
19
+ uuid,
20
+ vector
21
+ } from "./chunk-I3ON7MYF.js";
20
22
  import {
21
23
  defineError,
22
24
  entitlementFor,
@@ -40,7 +42,7 @@ import {
40
42
  __requestALS,
41
43
  __runWithRuntime,
42
44
  __setRuntime
43
- } from "./chunk-POYAFBLF.js";
45
+ } from "./chunk-SQC5EIWY.js";
44
46
  import {
45
47
  TxPlanError,
46
48
  TxRefError,
@@ -790,7 +792,88 @@ function mintToken(secret2) {
790
792
  }
791
793
  function buildRealtimeClient(cfg) {
792
794
  const url = `${cfg.baseUrl}/realtime/api/broadcast`;
795
+ const stateUrl = `${cfg.baseUrl}/realtime/api/state`;
796
+ async function writeState(topic, key, value, del) {
797
+ if (typeof topic !== "string" || topic.length === 0) {
798
+ return {
799
+ data: null,
800
+ error: new PalbaseModuleError("invalid_argument", "topic must be a non-empty string", 400)
801
+ };
802
+ }
803
+ if (typeof key !== "string" || key.length === 0) {
804
+ return {
805
+ data: null,
806
+ error: new PalbaseModuleError("invalid_argument", "key must be a non-empty string", 400)
807
+ };
808
+ }
809
+ if (!cfg.apiJwtSecret) {
810
+ return {
811
+ data: null,
812
+ error: new PalbaseModuleError(
813
+ "realtime_unconfigured",
814
+ "Realtime.state is unavailable: realtime is not provisioned for this Environment (PALBASE_REALTIME_API_JWT_SECRET unset).",
815
+ 503
816
+ )
817
+ };
818
+ }
819
+ let token;
820
+ try {
821
+ token = mintToken(cfg.apiJwtSecret);
822
+ } catch (err) {
823
+ return {
824
+ data: null,
825
+ error: new PalbaseModuleError(
826
+ "realtime_token_error",
827
+ err instanceof Error ? err.message : "token mint failed",
828
+ 500
829
+ )
830
+ };
831
+ }
832
+ const op = del ? { topic, key, del: true } : { topic, key, value: value ?? {} };
833
+ const doFetch = cfg.fetchImpl ?? globalThis.fetch;
834
+ let response;
835
+ try {
836
+ response = await doFetch(stateUrl, {
837
+ method: "POST",
838
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
839
+ body: JSON.stringify({ ops: [op] })
840
+ });
841
+ } catch (err) {
842
+ return {
843
+ data: null,
844
+ error: new PalbaseModuleError(
845
+ "network_error",
846
+ err instanceof Error ? err.message : "state request failed",
847
+ 0
848
+ )
849
+ };
850
+ }
851
+ if (response.status === 202 || response.status === 200) {
852
+ return { data: void 0, error: null };
853
+ }
854
+ const detail = await response.text().catch(() => "");
855
+ return {
856
+ data: null,
857
+ error: new PalbaseModuleError(
858
+ "realtime_state_failed",
859
+ `realtime state write returned ${response.status}${detail ? `: ${detail}` : ""}`,
860
+ response.status
861
+ )
862
+ };
863
+ }
793
864
  return {
865
+ state: {
866
+ /** Write one DURABLE entry on a channel's shared state.
867
+ *
868
+ * The difference from broadcast is WHO it reaches: a broadcast reaches
869
+ * whoever is listening at that instant, while state is also handed to
870
+ * whoever joins afterwards. "This value is now X" wants the second — a
871
+ * client connecting a second later should not have to wait for the next
872
+ * change to learn X. */
873
+ set: (topic, key, value) => writeState(topic, key, value, false),
874
+ /** Remove one entry. */
875
+ clear: (topic, key) => writeState(topic, key, void 0, true)
876
+ },
794
877
  async broadcast(channel, event, payload) {
795
878
  if (typeof channel !== "string" || channel.length === 0) {
796
879
  return {
@@ -1046,6 +1129,7 @@ function columnToJSON(column) {
1046
1129
  if (def.enumName !== void 0) out.enumName = def.enumName;
1047
1130
  if (def.enumValues !== void 0) out.enumValues = [...def.enumValues];
1048
1131
  if (def.unique === true) out.unique = true;
1132
+ if (def.dimensions !== void 0) out.dimensions = def.dimensions;
1049
1133
  return out;
1050
1134
  }
1051
1135
  function policyToJSON(policy2) {
@@ -1061,6 +1145,30 @@ function policyToJSON(policy2) {
1061
1145
  permissive: policy2.permissive !== false
1062
1146
  };
1063
1147
  }
1148
+ function searchToJSON(search) {
1149
+ const out = {};
1150
+ if (search.text !== void 0 && search.text.length > 0) out.text = { columns: [...search.text] };
1151
+ const legs = search.vector === void 0 ? [] : Array.isArray(search.vector) ? search.vector : [search.vector];
1152
+ if (legs.length > 0) {
1153
+ out.vector = legs.map((leg) => {
1154
+ const v = { metric: leg.metric ?? "cosine" };
1155
+ if (leg.column !== void 0) v.column = leg.column;
1156
+ if (leg.staleness !== void 0) v.staleness = leg.staleness;
1157
+ if (leg.model !== void 0) {
1158
+ v.embed = {
1159
+ provider: leg.model.provider,
1160
+ model: leg.model.model,
1161
+ from: [...leg.from ?? []],
1162
+ ...leg.model.apiKeyName !== void 0 ? { apiKeyName: leg.model.apiKeyName } : {},
1163
+ ...leg.model.dimensions !== void 0 ? { dimensions: leg.model.dimensions } : {},
1164
+ ...leg.model.baseURL !== void 0 ? { baseURL: leg.model.baseURL } : {}
1165
+ };
1166
+ }
1167
+ return v;
1168
+ });
1169
+ }
1170
+ return out;
1171
+ }
1064
1172
  function tableToJSON(table) {
1065
1173
  const columns = {};
1066
1174
  for (const [name, column] of Object.entries(table.columns)) {
@@ -1096,6 +1204,10 @@ function tableToJSON(table) {
1096
1204
  if (table.indexes !== void 0 && table.indexes.length > 0) {
1097
1205
  out.indexes = table.indexes.map((i) => ({ name: i.name, columns: [...i.columns] }));
1098
1206
  }
1207
+ if (table.search !== void 0) {
1208
+ const sj = searchToJSON(table.search);
1209
+ if (sj.text !== void 0 || sj.vector !== void 0) out.search = sj;
1210
+ }
1099
1211
  return out;
1100
1212
  }
1101
1213
  function toSchemaJSON(schema) {
@@ -1107,6 +1219,63 @@ function toSchemaJSON(schema) {
1107
1219
  return { tables, extensions: [...new Set(schema.extensions ?? [])] };
1108
1220
  }
1109
1221
 
1222
+ // src/channels.ts
1223
+ var CHANNELS = /* @__PURE__ */ Symbol.for("palbase.backend.channels");
1224
+ function ownerOnly() {
1225
+ return { kind: "owner" };
1226
+ }
1227
+ function publicChannel(opts = {}) {
1228
+ return { kind: "public", publish: opts.publish ?? false, state: opts.state };
1229
+ }
1230
+ function paramCount(pattern) {
1231
+ return pattern.split(":").filter((s) => s.startsWith("{") && s.endsWith("}")).length;
1232
+ }
1233
+ function defineChannels(map) {
1234
+ const entries = [];
1235
+ for (const [pattern, entry] of Object.entries(map)) {
1236
+ if ("kind" in entry && entry.kind === "owner") {
1237
+ if (paramCount(pattern) !== 1) {
1238
+ throw new Error(
1239
+ `defineChannels: ownerOnly() pattern "${pattern}" must carry exactly one {param} (its value is compared to the token subject)`
1240
+ );
1241
+ }
1242
+ entries.push({ pattern, kind: "owner" });
1243
+ } else if ("kind" in entry && entry.kind === "public") {
1244
+ entries.push({ pattern, kind: "public", publish: entry.publish, state: entry.state });
1245
+ } else {
1246
+ const c = entry;
1247
+ entries.push({ pattern, kind: "custom", authorize: c.authorize, handler: c.handler });
1248
+ }
1249
+ }
1250
+ const def = { entries };
1251
+ const carrier = globalThis;
1252
+ const existing = carrier[CHANNELS];
1253
+ if (existing && !sameDeclaration(existing, def)) {
1254
+ throw new Error(
1255
+ `defineChannels: channels were already declared (${existing.entries.length} pattern(s): ${existing.entries.map((e) => e.pattern).join(", ")}). A project declares its channels ONCE \u2014 a second call would overwrite the first, and channels nobody declared are refused.`
1256
+ );
1257
+ }
1258
+ carrier[CHANNELS] = def;
1259
+ return def;
1260
+ }
1261
+ function wireRow(e) {
1262
+ return JSON.stringify([
1263
+ e.pattern,
1264
+ e.kind,
1265
+ e.publish ?? false,
1266
+ e.state?.read ?? false,
1267
+ e.state?.write ?? false,
1268
+ // The handler is compared by SOURCE, like authorize: two evaluations of one
1269
+ // module give the same text, while different logic gives different text.
1270
+ e.handler ? e.handler.toString() : "",
1271
+ e.authorize ? e.authorize.toString() : ""
1272
+ ]);
1273
+ }
1274
+ function sameDeclaration(a, b) {
1275
+ if (a.entries.length !== b.entries.length) return false;
1276
+ return a.entries.every((x, i) => wireRow(x) === wireRow(b.entries[i]));
1277
+ }
1278
+
1110
1279
  // src/db/env-gen.ts
1111
1280
  function baseTsType(def) {
1112
1281
  switch (def.type) {
@@ -1128,6 +1297,11 @@ function baseTsType(def) {
1128
1297
  return "boolean";
1129
1298
  case "jsonb":
1130
1299
  return "unknown";
1300
+ // FR-008: the authoring type of a pgvector column. The default `unknown`
1301
+ // branch below STAYS — an unknown wire type is refused on the Go side
1302
+ // (FR-005), never papered over here.
1303
+ case "vector":
1304
+ return "number[]";
1131
1305
  case "enum": {
1132
1306
  const values = def.enumValues ?? [];
1133
1307
  if (values.length === 0) return "string";
@@ -1209,6 +1383,10 @@ function tableBlock(table, children, indent) {
1209
1383
  `${indent} };`,
1210
1384
  `${indent} owner: ${owner === null ? "null" : JSON.stringify(owner)};`,
1211
1385
  `${indent} children: {${childEntries === "" ? "" : ` ${childEntries} `}};`,
1386
+ // searchable: vector kolonu YA DA search beyanı → EnvTypedTable'da search()
1387
+ // üyesini açan yapısal bayrak (FR-013). Yokken satır hiç üretilmez ki
1388
+ // mevcut şemaların d.ts'i bayt-aynı kalsın.
1389
+ ...cols.some(([, b]) => b._def.type === "vector") || table.search !== void 0 ? [`${indent} searchable: true;`] : [],
1212
1390
  `${indent}};`
1213
1391
  ].join("\n");
1214
1392
  }
@@ -2379,6 +2557,7 @@ export {
2379
2557
  buildModuleClients,
2380
2558
  buildProvider,
2381
2559
  dec,
2560
+ defineChannels,
2382
2561
  defineEgress,
2383
2562
  defineError,
2384
2563
  defineFlags,
@@ -2408,8 +2587,11 @@ export {
2408
2587
  makeTypedDB,
2409
2588
  now,
2410
2589
  numeric,
2590
+ openai,
2591
+ ownerOnly,
2411
2592
  parseFileSizeLimit,
2412
2593
  policy,
2594
+ publicChannel,
2413
2595
  raw,
2414
2596
  recordThrows,
2415
2597
  reservedSecretKey,
@@ -2421,6 +2603,7 @@ export {
2421
2603
  toSchemaJSON,
2422
2604
  uuid,
2423
2605
  validateUploadAgainstStorage,
2606
+ vector,
2424
2607
  z
2425
2608
  };
2426
2609
  //# sourceMappingURL=index.js.map