@palbase/backend 22.0.1 → 23.0.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 (73) hide show
  1. package/dist/bin/palbase-backend.cjs +764 -25
  2. package/dist/bin/palbase-backend.cjs.map +1 -1
  3. package/dist/bin/palbase-backend.js +4 -4
  4. package/dist/{chunk-POYAFBLF.js → chunk-FSGSB42K.js} +13 -6
  5. package/dist/chunk-FSGSB42K.js.map +1 -0
  6. package/dist/{chunk-SSGAMC26.js → chunk-HAF67F2H.js} +114 -5
  7. package/dist/chunk-HAF67F2H.js.map +1 -0
  8. package/dist/{chunk-QMVK4X3V.js → chunk-OMRTHM4X.js} +98 -98
  9. package/dist/chunk-OMRTHM4X.js.map +1 -0
  10. package/dist/{chunk-QYOHMVUW.js → chunk-REZU6UKT.js} +755 -24
  11. package/dist/chunk-REZU6UKT.js.map +1 -0
  12. package/dist/{chunk-YL4C5NRY.js → chunk-Y5HXVUMP.js} +2 -2
  13. package/dist/{chunk-N32VDWKH.js → chunk-ZC6Q2BRD.js} +4 -59
  14. package/dist/chunk-ZC6Q2BRD.js.map +1 -0
  15. package/dist/db/env.cjs.map +1 -1
  16. package/dist/db/env.d.cts +3 -21
  17. package/dist/db/env.d.ts +3 -21
  18. package/dist/db/index.cjs +117 -6
  19. package/dist/db/index.cjs.map +1 -1
  20. package/dist/db/index.d.cts +3 -2
  21. package/dist/db/index.d.ts +3 -2
  22. package/dist/db/index.js +7 -3
  23. package/dist/{endpoint-B0LpZixz.d.cts → endpoint-BavvbW4P.d.ts} +116 -14
  24. package/dist/{endpoint-B0LpZixz.d.ts → endpoint-i8TTCohk.d.cts} +116 -14
  25. package/dist/engine/index.cjs +764 -25
  26. package/dist/engine/index.cjs.map +1 -1
  27. package/dist/engine/index.d.cts +6 -5
  28. package/dist/engine/index.d.ts +6 -5
  29. package/dist/engine/index.js +3 -3
  30. package/dist/{index-g-EzitI-.d.ts → index-B3jmmItD.d.ts} +203 -7
  31. package/dist/{index-BCNtlG1w.d.ts → index-B7YBEG5w.d.ts} +117 -93
  32. package/dist/{index-BGSCWlUa.d.cts → index-Bmvx1EvJ.d.cts} +203 -7
  33. package/dist/{index-B4W6d2VJ.d.cts → index-E7OscPJT.d.cts} +117 -93
  34. package/dist/index.cjs +509 -1085
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +203 -1133
  37. package/dist/index.d.ts +203 -1133
  38. package/dist/index.js +288 -900
  39. package/dist/index.js.map +1 -1
  40. package/dist/openapi/index.cjs +3 -57
  41. package/dist/openapi/index.cjs.map +1 -1
  42. package/dist/openapi/index.d.cts +3 -2
  43. package/dist/openapi/index.d.ts +3 -2
  44. package/dist/openapi/index.js +5 -22
  45. package/dist/openapi/index.js.map +1 -1
  46. package/dist/{registry-3BLYv4si.d.ts → registry-C3H2uPeZ.d.cts} +13 -169
  47. package/dist/{registry-Cw0YEYCg.d.cts → registry-DY3d9l1k.d.ts} +13 -169
  48. package/dist/{purchases/keys.cjs → stack.cjs} +4 -4
  49. package/dist/stack.cjs.map +1 -0
  50. package/dist/stack.d.cts +76 -0
  51. package/dist/stack.d.ts +76 -0
  52. package/dist/stack.js +1 -0
  53. package/docs/README.md +7 -6
  54. package/docs/endpoints.md +1 -1
  55. package/docs/errors.md +9 -0
  56. package/docs/llms-full.txt +17 -261
  57. package/docs/llms.txt +0 -2
  58. package/package.json +7 -7
  59. package/template/package.json +1 -1
  60. package/dist/chunk-N32VDWKH.js.map +0 -1
  61. package/dist/chunk-POYAFBLF.js.map +0 -1
  62. package/dist/chunk-QMVK4X3V.js.map +0 -1
  63. package/dist/chunk-QYOHMVUW.js.map +0 -1
  64. package/dist/chunk-SSGAMC26.js.map +0 -1
  65. package/dist/purchases/keys.cjs.map +0 -1
  66. package/dist/purchases/keys.d.cts +0 -42
  67. package/dist/purchases/keys.d.ts +0 -42
  68. package/dist/purchases/keys.js +0 -1
  69. package/docs/config.md +0 -147
  70. package/docs/resources.md +0 -97
  71. package/template/config/secrets.ts +0 -24
  72. /package/dist/{chunk-YL4C5NRY.js.map → chunk-Y5HXVUMP.js.map} +0 -0
  73. /package/dist/{purchases/keys.js.map → stack.js.map} +0 -0
@@ -1,7 +1,8 @@
1
- export { A as App, l as AuthVerifier, B as BootRefused, m as CreateAppOptions, E as EgressPolicy, n as EngineConfig, M as ModuleClients, o as RateLimiter, p as RequestDatabase, q as RouteEntry, r as RuntimeHooks, s as ScrubResult, t as SqlDriver, u as SqlTx, v as buildRouteTable, w as createApp, x as createLazyTransaction, y as createOps, z as createRequestDatabase, G as effectiveAuth, H as hostAllowed, I as installEgressFence, J as loadConfig, K as makeMemoryCache, O as matchRoute, Q as quoteIdent, T as scrubSecrets, U as withTables } from '../index-B4W6d2VJ.cjs';
2
- import '../endpoint-B0LpZixz.cjs';
3
- import '../db/env.cjs';
1
+ export { A as App, h as AuthVerifier, B as BootRefused, i as CreateAppOptions, E as EgressPolicy, j as EngineConfig, M as ModuleClients, k as RateLimiter, l as RequestDatabase, m as RouteEntry, n as RuntimeHooks, o as ScrubResult, p as SqlDriver, q as SqlTx, r as buildRouteTable, s as createApp, t as createLazyTransaction, u as createOps, v as createRequestDatabase, w as effectiveAuth, x as hostAllowed, y as installEgressFence, z as loadConfig, G as makeMemoryCache, H as matchRoute, I as quoteIdent, J as scrubSecrets, K as withTables } from '../index-E7OscPJT.cjs';
2
+ import '../endpoint-i8TTCohk.cjs';
3
+ import '../stack.cjs';
4
4
  import 'node:async_hooks';
5
- import '../index-BGSCWlUa.cjs';
6
- import '../registry-Cw0YEYCg.cjs';
5
+ import '../index-Bmvx1EvJ.cjs';
6
+ import '../db/env.cjs';
7
+ import '../registry-C3H2uPeZ.cjs';
7
8
  import 'zod';
@@ -1,7 +1,8 @@
1
- export { A as App, l as AuthVerifier, B as BootRefused, m as CreateAppOptions, E as EgressPolicy, n as EngineConfig, M as ModuleClients, o as RateLimiter, p as RequestDatabase, q as RouteEntry, r as RuntimeHooks, s as ScrubResult, t as SqlDriver, u as SqlTx, v as buildRouteTable, w as createApp, x as createLazyTransaction, y as createOps, z as createRequestDatabase, G as effectiveAuth, H as hostAllowed, I as installEgressFence, J as loadConfig, K as makeMemoryCache, O as matchRoute, Q as quoteIdent, T as scrubSecrets, U as withTables } from '../index-BCNtlG1w.js';
2
- import '../endpoint-B0LpZixz.js';
3
- import '../db/env.js';
1
+ export { A as App, h as AuthVerifier, B as BootRefused, i as CreateAppOptions, E as EgressPolicy, j as EngineConfig, M as ModuleClients, k as RateLimiter, l as RequestDatabase, m as RouteEntry, n as RuntimeHooks, o as ScrubResult, p as SqlDriver, q as SqlTx, r as buildRouteTable, s as createApp, t as createLazyTransaction, u as createOps, v as createRequestDatabase, w as effectiveAuth, x as hostAllowed, y as installEgressFence, z as loadConfig, G as makeMemoryCache, H as matchRoute, I as quoteIdent, J as scrubSecrets, K as withTables } from '../index-B7YBEG5w.js';
2
+ import '../endpoint-BavvbW4P.js';
3
+ import '../stack.js';
4
4
  import 'node:async_hooks';
5
- import '../index-g-EzitI-.js';
6
- import '../registry-3BLYv4si.js';
5
+ import '../index-B3jmmItD.js';
6
+ import '../db/env.js';
7
+ import '../registry-DY3d9l1k.js';
7
8
  import 'zod';
@@ -16,10 +16,10 @@ import {
16
16
  quoteIdent,
17
17
  scrubSecrets,
18
18
  withTables
19
- } from "../chunk-QYOHMVUW.js";
20
- import "../chunk-POYAFBLF.js";
19
+ } from "../chunk-REZU6UKT.js";
20
+ import "../chunk-FSGSB42K.js";
21
21
  import "../chunk-W5ODXPY3.js";
22
- import "../chunk-QMVK4X3V.js";
22
+ import "../chunk-OMRTHM4X.js";
23
23
  import "../chunk-7D4SUZUM.js";
24
24
  export {
25
25
  AuthVerifier,
@@ -1,5 +1,5 @@
1
1
  import { Tables, TableTypes } from './db/env.js';
2
- import { D as DBClient, b8 as TxPlanHandle, bh as TxTable, M as Materialized } from './endpoint-B0LpZixz.js';
2
+ import { D as DBClient, b8 as TxPlanHandle, bh as TxTable, M as Materialized } from './endpoint-BavvbW4P.js';
3
3
 
4
4
  /** On delete action for foreign key references. */
5
5
  type OnDeleteAction = 'cascade' | 'set null' | 'restrict' | 'no action';
@@ -13,7 +13,7 @@ type OnDeleteAction = 'cascade' | 'set null' | 'restrict' | 'no action';
13
13
  */
14
14
  type AuthUserOnDelete = Extract<OnDeleteAction, 'cascade' | 'set null'>;
15
15
  /** Column type identifiers. */
16
- type ColumnType = 'uuid' | 'text' | 'integer' | 'bigint' | 'numeric' | 'boolean' | 'timestamp' | 'jsonb' | 'enum';
16
+ type ColumnType = 'uuid' | 'text' | 'integer' | 'bigint' | 'numeric' | 'boolean' | 'timestamp' | 'jsonb' | 'enum' | 'vector';
17
17
  /** Base column definition shared by all column types. */
18
18
  interface ColumnDef {
19
19
  type: ColumnType;
@@ -36,6 +36,9 @@ interface ColumnDef {
36
36
  enumName?: string;
37
37
  enumValues?: string[];
38
38
  unique?: boolean;
39
+ /** vector(n): the declared dimension count — part of the TYPE (typmod), read
40
+ * by the wire serializer and the deploy's auto-index (FR-001). */
41
+ dimensions?: number;
39
42
  }
40
43
  declare const __colKind: unique symbol;
41
44
  declare const __colNullable: unique symbol;
@@ -147,7 +150,7 @@ declare class ColumnBuilder<K extends ColumnType = ColumnType, N extends boolean
147
150
  * - "jsonb" → P (the dev-supplied payload shape from jsonb<T>(), else unknown)
148
151
  * - "enum" → E (the union of literal values)
149
152
  */
150
- type ColValue<C> = C extends ColumnBuilder<'uuid' | 'text' | 'timestamp' | 'bigint' | 'numeric', infer N, infer _D, infer _E, infer _P> ? N extends true ? string | null : string : C extends ColumnBuilder<'integer', infer N, infer _D, infer _E, infer _P> ? N extends true ? number | null : number : C extends ColumnBuilder<'boolean', infer N, infer _D, infer _E, infer _P> ? N extends true ? boolean | null : boolean : C extends ColumnBuilder<'jsonb', infer N, infer _D, infer _E, infer P> ? N extends true ? P | null : P : C extends ColumnBuilder<'enum', infer N, infer _D, infer E, infer _P> ? N extends true ? E | null : E : never;
153
+ type ColValue<C> = C extends ColumnBuilder<'uuid' | 'text' | 'timestamp' | 'bigint' | 'numeric', infer N, infer _D, infer _E, infer _P> ? N extends true ? string | null : string : C extends ColumnBuilder<'integer', infer N, infer _D, infer _E, infer _P> ? N extends true ? number | null : number : C extends ColumnBuilder<'boolean', infer N, infer _D, infer _E, infer _P> ? N extends true ? boolean | null : boolean : C extends ColumnBuilder<'jsonb', infer N, infer _D, infer _E, infer P> ? N extends true ? P | null : P : C extends ColumnBuilder<'vector', infer N, infer _D, infer _E, infer _P> ? N extends true ? number[] | null : number[] : C extends ColumnBuilder<'enum', infer N, infer _D, infer E, infer _P> ? N extends true ? E | null : E : never;
151
154
  /**
152
155
  * True when a column is optional on INSERT:
153
156
  * - nullable columns (N = true) — the DB allows NULL so the field may be omitted
@@ -198,6 +201,10 @@ declare function jsonb<T = unknown>(): ColumnBuilder<'jsonb', false, false, neve
198
201
  * union `V[number]` is as narrow as possible.
199
202
  */
200
203
  declare function enumType<const V extends readonly string[]>(name: string, values: V): ColumnBuilder<'enum', false, false, V[number]>;
204
+ /** vector(n) — pgvector kolonu. n TİPİN parçasıdır (typmod) ve [1, 2000] —
205
+ * 2000 = pgvector'ün HNSW-indekslenebilir tavanı; auto-index bu beyanla bağlı
206
+ * (spec FR-001, D-3). */
207
+ declare function vector(dimensions: number): ColumnBuilder<'vector', false, false, unknown, number[]>;
201
208
 
202
209
  /**
203
210
  * policy.ts — the RLS policy authoring DSL.
@@ -301,7 +308,7 @@ declare function policy(name: string): PolicyBuilder;
301
308
  * supported names and a typo fails typecheck. It is intentionally extensible:
302
309
  * add a name here (+ confirm the base image ships it) to support more.
303
310
  */
304
- declare const PALBASE_EXTENSIONS: readonly ["vector", "pg_trgm", "unaccent", "citext", "postgis", "cube", "earthdistance", "hstore", "ltree", "btree_gist", "pg_cron", "pgcrypto", "uuid-ossp"];
311
+ declare const PALBASE_EXTENSIONS: readonly ["vector", "pg_trgm", "unaccent", "citext", "cube", "earthdistance", "hstore", "ltree", "btree_gist", "pgcrypto", "uuid-ossp"];
305
312
  /** A Postgres extension supported by Palbase (allowlist union). */
306
313
  type PalbaseExtension = (typeof PALBASE_EXTENSIONS)[number];
307
314
  /**
@@ -329,6 +336,33 @@ declare function raw(name: string, up: string, opts?: {
329
336
  down?: string;
330
337
  }): RawConstraintDef;
331
338
 
339
+ /** Embedding sağlayıcı DESKRIPTORU — canlı istemci değil, düz veri: şemayla
340
+ * birlikte serileşir, çağrıyı Go worker (yazma) ve engine (sorgu) yapar.
341
+ * Adlandırma Vercel AI SDK'nın aynasıdır (openai.embedding("...")) ama paket
342
+ * bağımlılığı bilinçli olarak YOKTUR (spec C-3, UD-016). v1 sağlayıcı: openai (D-10). */
343
+ interface EmbeddingModelRef {
344
+ provider: "openai";
345
+ model: string;
346
+ dimensions?: number;
347
+ apiKeyName?: string;
348
+ baseURL?: string;
349
+ }
350
+ /** Chat/damıtma modeli DESKRIPTORU (C-11, D-019) — memory beyanının extract'i.
351
+ * Embedding gibi düz veridir; çağrıyı worker yapar, anahtar vault'taki
352
+ * OPENAI_API_KEY'dir (D-017: aynı sağlayıcı, yeni dış sistem yok). */
353
+ interface ChatModelRef {
354
+ provider: "openai";
355
+ model: string;
356
+ }
357
+ declare const openai: {
358
+ embedding(model: string, opts?: {
359
+ dimensions?: number;
360
+ apiKeyName?: string;
361
+ baseURL?: string;
362
+ }): EmbeddingModelRef;
363
+ chat(model: string): ChatModelRef;
364
+ };
365
+
332
366
  /**
333
367
  * A map of column builders keyed by column name — the value you write under
334
368
  * the `columns` key of `defineSchema({ tables: { <name>: { columns } } })`.
@@ -355,6 +389,64 @@ type ColumnMap = Record<string, ColumnBuilder>;
355
389
  * The `C` type parameter preserves the precise per-column phantom types so the
356
390
  * typed `Database.tables.*` surface keeps inferring insert/row shapes.
357
391
  */
392
+ /** Arama metriği — tek kelime; opclass ve operatör bundan türetilir, asla yüzeye çıkmaz (D-5/D-6). */
393
+ type SearchMetric = "cosine" | "euclidean" | "inner_product";
394
+ /** Bir vektör arama kolu. `model` varsa auto-embed: platform yazma+sorgu embedding'ini üstlenir (D-9). */
395
+ interface VectorSearchDecl {
396
+ /** Hedef vector kolonu; tabloda TEK vector kolonu varsa atlanabilir (Go apply çözer, FR-010). */
397
+ column?: string;
398
+ /** Varsa auto-embed. Deskriptor düz veridir — şemayla serileşir (C-3). */
399
+ model?: EmbeddingModelRef;
400
+ /** model varsa ZORUNLU: embed kaynak kolonları = trigger'ın UPDATE OF listesi (C-2). */
401
+ from?: string[];
402
+ metric?: SearchMetric;
403
+ /** Kaynak metin değişince ara-dönem davranışı (yalnız auto-embed'de):
404
+ * "null" (vars.) — embedding anında NULL'lanır; satır yeni vektör yazılana
405
+ * dek anlamsal aramada aday değildir. Bayat eşleşme asla servis edilmez.
406
+ * "keep" — eski vektör aramada kalır, platform yenisini yazınca sessizce
407
+ * değişir. Görünürlük penceresi sıfır; bedeli saniyeler süren bayat
408
+ * eşleşme riski (Confluence-tipi sync yükleri için). */
409
+ staleness?: "null" | "keep";
410
+ }
411
+ /** Tablonun arama beyanı — İKİ biçim (D-007, tek yüzey):
412
+ *
413
+ * YENİ (önerilen): `{ from, model, ... }` — `from` kolonları hem FTS'e hem
414
+ * embed'e girer. Tabloda vector kolonu declare edilmişse SATIR-modu; yoksa
415
+ * CHUNK-modu otomatiktir (D-010): vektörler türev `__palbase_chunks`
416
+ * tablosunda yaşar, içerik otomatik bölünür. `text: false` FTS'i kapatır,
417
+ * `text: [..]` FTS kolonlarını from'dan ayırır. `chunks` yalnız ince ayar.
418
+ *
419
+ * ESKİ: `text: string[]` + `vector: {...}` — aynen çalışır, wire çıktısı
420
+ * bayt-aynı kalır (NFR-B1). İki biçim KARIŞTIRILAMAZ. */
421
+ interface SearchDecl {
422
+ text?: string[] | boolean;
423
+ vector?: VectorSearchDecl | VectorSearchDecl[];
424
+ /** Yeni biçim: arama kaynağı kolonlar (FTS + embed). Varlığı yeni biçimi seçer. */
425
+ from?: string[];
426
+ /** Yeni biçim: auto-embed modeli (zorunlu — BYO için eski biçimi kullanın). */
427
+ model?: EmbeddingModelRef;
428
+ metric?: SearchMetric;
429
+ staleness?: "null" | "keep";
430
+ /** Chunk-modu ince ayarı (yalnız vector kolonsuz tabloda anlamlı). */
431
+ chunks?: {
432
+ size?: number;
433
+ overlap?: number;
434
+ };
435
+ /** Sorgu-yeniden-yazımı: tek yönlü eş anlamlı haritası (FR-026). */
436
+ synonyms?: Record<string, string[]>;
437
+ /** Geçerlilik kolonları türetilir; arama varsayılan yalnız günceli tarar (FR-029). */
438
+ validity?: boolean;
439
+ }
440
+ /** Hafıza beyanı (FR-032, D-019): kaynak tablonun yazımlarından platform
441
+ * fact damıtır ve `into` tablosuna yazar. Hedef NORMAL declared tablodur —
442
+ * kendi search/unique/validity beyanlarıyla. Okuma = Database.search(into).
443
+ * subject default "owner": fact'in kime ait olduğu kolonu (iki tabloda da). */
444
+ interface MemoryDecl {
445
+ from: string[];
446
+ into: string;
447
+ extract: ChatModelRef;
448
+ subject?: string;
449
+ }
358
450
  interface TableInput<C extends ColumnMap = ColumnMap> {
359
451
  columns: C;
360
452
  rls?: boolean;
@@ -394,6 +486,10 @@ interface TableInput<C extends ColumnMap = ColumnMap> {
394
486
  name: string;
395
487
  columns: string[];
396
488
  }[];
489
+ /** Arama beyanı — bkz. SearchDecl. */
490
+ search?: SearchDecl;
491
+ /** Hafıza beyanı — bkz. MemoryDecl (FR-032). */
492
+ memory?: MemoryDecl;
397
493
  }
398
494
  /**
399
495
  * A table definition — the runtime value the Go runtime's `schema_extract.js`
@@ -429,6 +525,10 @@ interface TableDef<C extends ColumnMap = ColumnMap> {
429
525
  name: string;
430
526
  columns: string[];
431
527
  }[];
528
+ /** Arama beyanı, doğrulanmış ve taşınmış hali. */
529
+ search?: SearchDecl;
530
+ /** Hafıza beyanı, doğrulanmış ve taşınmış hali (FR-032). */
531
+ memory?: MemoryDecl;
432
532
  }
433
533
  /**
434
534
  * A schema definition containing multiple tables, keyed by table name.
@@ -583,8 +683,77 @@ type TypedTx<S extends SchemaDef> = TxPlanHandle<{
583
683
  * through `Object.keys` iteration) — see the module-level doc comment.
584
684
  */
585
685
  declare function makeTypedDB<S extends SchemaDef>(schema: S, raw: DBClient): TypedDB<S>;
586
- /** A typed table accessor derived from one env `Tables` entry's flat shapes. */
587
- interface EnvTypedTable<T extends TableTypes> {
686
+ /** Bir where değeri: düz eşitlik YA DA operatör nesnesi (FR-016). */
687
+ type WhereOp<V> = V | {
688
+ gt?: V;
689
+ gte?: V;
690
+ lt?: V;
691
+ lte?: V;
692
+ neq?: V;
693
+ in?: V[];
694
+ };
695
+ /** search() parametreleri, satır tipiyle koşullanmış (FR-013). `offset` BİLEREK yok (UD-013). */
696
+ interface SearchParamsTyped<T extends TableTypes> {
697
+ /** Metin sorgusu: FTS kolunu besler; embed beyanlıysa sorgu vektörü de bundan üretilir. */
698
+ query?: string;
699
+ /** Hazır sorgu vektörü — verilirse embed çağrısı olmaz (FR-025). */
700
+ vector?: number[];
701
+ where?: {
702
+ [K in keyof T["row"]]?: WhereOp<T["row"][K]>;
703
+ };
704
+ /** default 20, tavan 100 (engine uygular). */
705
+ limit?: number;
706
+ /** Birden çok vektör kolonunda hedef seçimi (model geçişi, FR-013/using). */
707
+ using?: string;
708
+ mode?: "hybrid" | "text" | "vector";
709
+ /** Nihai (RRF-sonrası) skor alt eşiği — süzme LIMIT'ten önce uygulanır (FR-001). */
710
+ minScore?: number;
711
+ /** Chunk-modunda satır başına en iyi blok sayısı (1..10, vars. 3; FR-015). */
712
+ blocksPerRow?: number;
713
+ /** Tazelik çürümesi: nihai skor RRF-sonrası exp(-ln(2)*yaş/halfLife) ile çarpılır;
714
+ * field bir timestamp kolonu, halfLife "90s" | "15m" | "12h" | "30d" biçiminde (FR-004). */
715
+ recency?: {
716
+ field: Extract<keyof T["row"], string>;
717
+ halfLife: string;
718
+ };
719
+ /** Filtrelenmiş küme üzerinde kolon başına top-20 değer sayacı — dönüş
720
+ * dizisinin `_facets` özelliği (FR-027). */
721
+ facets?: Extract<keyof T["row"], string>[];
722
+ /** Satır-modunda FTS eşleşme vurgusu: sonuç satırına `_highlight` ekler;
723
+ * chunk-modda no-op — bloklar zaten eşleşen kesittir (FR-025). */
724
+ highlight?: boolean;
725
+ /** Validity'li tabloda zaman penceresi: varsayılan yalnız güncel versiyon;
726
+ * "all" tüm versiyonlar; {asOf} o anda geçerli olan (FR-029). */
727
+ validity?: "all" | {
728
+ asOf: string;
729
+ };
730
+ /** Alan-boost (FR-030): skor * (1 + w·x/(1+x)) — sayısal kolonla sınırlı
731
+ * çarpan, dış servissiz; bileşim RRF → boost → recency → minScore. */
732
+ boost?: {
733
+ field: Extract<keyof T["row"], string>;
734
+ weight: number;
735
+ };
736
+ }
737
+ /** search() dönüş dizisinin sorgu-düzeyi ekleri (FR-027): `_facets` dizinin
738
+ * ÖZELLİĞİDİR, satırlara kopyalanmaz (JSON'a satır başına şişme olmasın). */
739
+ type SearchFacets = Record<string, {
740
+ value: string | null;
741
+ count: number;
742
+ }[]>;
743
+ /** similar()/recommend() taşıyıcı opsiyonları (T018, FR-022): search'ün
744
+ * paramlarından query/vector/mode düşer — hedef vektörü metodun kendisi
745
+ * DB'den kurar; facets/highlight de düşer (T020) — engine bu ikisini
746
+ * similar/recommend'e geçirmez, tip vaadi gerçekle aynı kalır. */
747
+ type SimilarParamsTyped<T extends TableTypes> = Omit<SearchParamsTyped<T>, "query" | "vector" | "mode" | "facets" | "highlight">;
748
+ /** recommend() parametreleri (T018, FR-023). */
749
+ type RecommendParamsTyped<T extends TableTypes> = SimilarParamsTyped<T> & {
750
+ /** Kaynak beğeniler — hedef vektör bunların DB-içi avg'ı; boş olamaz. */
751
+ positive: string[];
752
+ /** İtilen örnekler — hedef pos.v + (pos.v - neg.v) ile yönlenir. */
753
+ negative?: string[];
754
+ };
755
+ /** Temel tablo erişimcisi — search'süz beş op. */
756
+ interface EnvTypedTableBase<T extends TableTypes> {
588
757
  insert(data: T["insert"]): Promise<T["row"]>;
589
758
  /** Update the row by id; resolves to the updated row, or `null` if no row
590
759
  * matched (absent or RLS-hidden) — an idempotent outcome, mirroring
@@ -593,7 +762,34 @@ interface EnvTypedTable<T extends TableTypes> {
593
762
  delete(id: string): Promise<void>;
594
763
  findById(id: string): Promise<T["row"] | null>;
595
764
  findMany(query?: Partial<T["row"]>): Promise<T["row"][]>;
765
+ /** Validity'li tabloda satırın yeni versiyonu (FR-029, C-9): eski satır
766
+ * kapanır (valid_to/superseded_by), yenisi TEK savepoint'te eklenir; dönüş
767
+ * yeni satır. Validity beyanı olmayan tabloda adlandırılmış çalışma-zamanı
768
+ * hatası — tip düzeyinde ayrım env `Tables` bayrağı taşımadığından yapılamaz. */
769
+ supersede(id: string, row: T["insert"]): Promise<T["row"]>;
596
770
  }
771
+ /** Tablo erişimcisi: env girdisi `searchable: true` taşıyorsa (vector kolonu ya da
772
+ * search beyanı — env-gen üretir) `search()` üyesi VARDIR; yoksa üye hiç yoktur ve
773
+ * çağrı derleme hatasıdır (FR-013). Yapısal koşul TableTypes'ı genişletmeden çalışır. */
774
+ type EnvTypedTable<T extends TableTypes> = EnvTypedTableBase<T> & (T extends {
775
+ searchable: true;
776
+ } ? {
777
+ search(params: SearchParamsTyped<T>): Promise<Array<T["row"] & {
778
+ _score: number;
779
+ }> & {
780
+ _facets?: SearchFacets;
781
+ }>;
782
+ /** "Bu satıra benzeyenler" (FR-022): hedef vektör DB'den okunur,
783
+ * kaynak satır sonuçta yoktur; id yoksa adlandırılmış hata. */
784
+ similar(id: string, params?: SimilarParamsTyped<T>): Promise<Array<T["row"] & {
785
+ _score: number;
786
+ }>>;
787
+ /** positive/negative beğenilerden öneri (FR-023): hedef vektör DB-içi
788
+ * avg CTE'leriyle; kaynak id'ler sonuçta yoktur. */
789
+ recommend(params: RecommendParamsTyped<T>): Promise<Array<T["row"] & {
790
+ _score: number;
791
+ }>>;
792
+ } : Record<never, never>);
597
793
  /** The `tables` map exposed on `Database`/`tx`, keyed by the env `Tables`
598
794
  * interface. When no schema is declared `Tables` is empty, so `tables` is an
599
795
  * empty object — accessing `.tables.foo` is then a compile error (no member). */
@@ -671,4 +867,4 @@ interface EnvTypedDatabase extends Omit<DBClient, "txPlan" | "asService"> {
671
867
  asService(): EnvServiceDatabase;
672
868
  }
673
869
 
674
- export { jsonb as A, makeTypedDB as B, ColumnBuilder as C, numeric as D, type EnvTypedDatabase as E, policy as F, raw as G, text as H, type InsertShape as I, timestamp as J, uuid as K, type OnDeleteAction as O, PALBASE_EXTENSIONS as P, type RawConstraintDef as R, type SchemaDef as S, type TableDef as T, type ColumnDef as a, type ColumnMap as b, type ColumnType as c, EXTENSION_DEPENDENCIES as d, type EnvServiceDatabase as e, type EnvTables as f, type EnvTypedTable as g, type PalbaseExtension as h, PolicyBuilder as i, type PolicyCommand as j, type PolicyDef as k, type PolicyMode as l, type RowShape as m, type SchemaInput as n, type TableInput as o, type TxPlan as p, type TxTables as q, type TypedDB as r, type TypedTable as s, type TypedTx as t, bigint as u, boolean as v, defineSchema as w, enumType as x, integer as y, isPalbaseExtension as z };
870
+ export { isPalbaseExtension as A, jsonb as B, ColumnBuilder as C, makeTypedDB as D, type EnvTypedDatabase as E, numeric as F, openai as G, policy as H, type InsertShape as I, raw as J, text as K, timestamp as L, uuid as M, vector as N, type OnDeleteAction as O, PALBASE_EXTENSIONS as P, type RawConstraintDef as R, type SchemaDef as S, type TableDef as T, type ColumnDef as a, type ColumnMap as b, type ColumnType as c, EXTENSION_DEPENDENCIES as d, type EmbeddingModelRef as e, type EnvServiceDatabase as f, type EnvTables as g, type EnvTypedTable as h, type PalbaseExtension as i, PolicyBuilder as j, type PolicyCommand as k, type PolicyDef as l, type PolicyMode as m, type RowShape as n, type SchemaInput as o, type TableInput as p, type TxPlan as q, type TxTables as r, type TypedDB as s, type TypedTable as t, type TypedTx as u, bigint as v, boolean as w, defineSchema as x, enumType as y, integer as z };
@@ -1,63 +1,8 @@
1
- import { Buckets, BucketTypes } from './db/env.js';
1
+ import { Buckets, BucketTypes } from './stack.js';
2
2
  import { AsyncLocalStorage } from 'node:async_hooks';
3
- import { C as CacheClient, P as PalbaseDocsClient, a as PalbaseFlagsClient, L as Logger, b as PalbaseNotificationsClient, c as PalbaseRealtimeClient, D as DBClient, S as SecretsService, d as PalbaseStorageClient, e as PalbaseBucketClient, T as TxPlanBody, f as TxPlanResponse } from './endpoint-B0LpZixz.js';
4
- import { E as EnvTypedDatabase } from './index-g-EzitI-.js';
5
- import { R as RouteMeta } from './registry-3BLYv4si.js';
6
-
7
- /**
8
- * The purchases surface the decorators need, declared as a NARROW STRUCTURAL
9
- * interface rather than an import of `@palstore/purchases`.
10
- *
11
- * `PurchasesClient` (palstore's `sk_` backend SDK) satisfies this shape as-is,
12
- * so the runtime injects the real client with no adapter — but `@palbase/backend`
13
- * itself gains no dependency on it. That matters: this package is published
14
- * public and baked into the br-pod image from a tarball, so a dependency on an
15
- * unpublished sibling would break `npm install palbase-backend.tgz`. It is also
16
- * the pattern `withSpend` already uses for the same reason (`SpendCapableClient`
17
- * in palstore's own spend.ts: "a narrow structural interface … so this file has
18
- * no dependency on client.ts").
19
- *
20
- * The methods here are a SUBSET of `PurchasesClient` — only what the two
21
- * decorators call. Grants, refunds, credits and customer-info reads stay off
22
- * this interface: a tenant that wants them imports the palstore SDK directly.
23
- */
24
- /** Store environment a subject is fixed to. Mirrors `StoreEnv` in `@palstore/purchases`. */
25
- type StoreEnv = "production" | "sandbox";
26
- /** Quota/credit state carried by a 429. Mirrors `LimitState` in `@palstore/purchases`
27
- * (SPEC-purchases-v1 §11) — re-declared, not imported, for the reason above. */
28
- interface LimitState {
29
- key: string;
30
- scope: string;
31
- window: string;
32
- used: number;
33
- reserved: number;
34
- max: number;
35
- remaining: number;
36
- resetAt: string;
37
- }
38
- /** Options for one spend. `idempotencyKey` is required by the server (§9). */
39
- interface SpendOptions {
40
- /** Defaults to 1. */
41
- count?: number;
42
- idempotencyKey: string;
43
- }
44
- interface PurchasesService {
45
- /** Map a tenant-side user reference to its palstore subject, creating one on
46
- * first sight. Server-authoritative — the caller never names a subject. */
47
- resolveSubject(input: {
48
- userRef: string;
49
- storeEnv: StoreEnv;
50
- }): Promise<{
51
- subjectId: string;
52
- }>;
53
- /** Resolve silently when `entitlementKey` is active for `subjectId`; throw
54
- * `EntitlementRequiredError` otherwise. Consumes nothing. */
55
- require(subjectId: string, entitlementKey: string): Promise<void>;
56
- /** Reserve → run `handler` → commit on success, cancel on throw, always
57
- * rethrowing the handler's own error. The whole reason the decorators are a
58
- * thin layer: this lifecycle is already written and tested in palstore's SDK. */
59
- withSpend<T>(subjectId: string, key: string, opts: SpendOptions, handler: () => Promise<T>): Promise<T>;
60
- }
3
+ import { C as CacheClient, P as PalbaseDocsClient, a as PalbaseFlagsClient, L as Logger, b as PalbaseNotificationsClient, c as PalbaseRealtimeClient, D as DBClient, S as SecretsService, d as PalbaseStorageClient, e as PalbaseBucketClient, T as TxPlanBody, f as TxPlanResponse } from './endpoint-BavvbW4P.js';
4
+ import { E as EnvTypedDatabase } from './index-B3jmmItD.js';
5
+ import { R as RouteMeta } from './registry-DY3d9l1k.js';
61
6
 
62
7
  /**
63
8
  * runtime.ts — request-scoped service singletons.
@@ -118,7 +63,6 @@ interface RuntimeServices {
118
63
  Notifications: PalbaseNotificationsClient;
119
64
  Flags: PalbaseFlagsClient;
120
65
  Realtime: PalbaseRealtimeClient;
121
- Purchases: PurchasesService;
122
66
  }
123
67
  /**
124
68
  * The per-request ALS box.
@@ -239,15 +183,6 @@ declare const Secrets: SecretsService;
239
183
  declare const Log: Logger;
240
184
  /** Push / email / SMS / in-app notifications. */
241
185
  declare const Notifications: PalbaseNotificationsClient;
242
- /**
243
- * Palstore purchases (entitlements + quota/credit spend).
244
- *
245
- * Reached by handlers through the `@RequireEntitlement` / `@Spend` decorators
246
- * rather than called directly in the common case; exposed as a singleton for
247
- * the cases the decorators deliberately do not cover (a dynamic spend count,
248
- * which must run BEFORE the billable side-effect).
249
- */
250
- declare const Purchases: PurchasesService;
251
186
  /**
252
187
  * Feature flags.
253
188
  *
@@ -434,6 +369,111 @@ declare function createOps(tx: TxLike): {
434
369
  delete(table: string, id: string): Promise<void>;
435
370
  findById(table: string, id: string): Promise<Row | null>;
436
371
  findMany(table: string, query?: Row): Promise<Row[]>;
372
+ /**
373
+ * Tek-SQL hibrit arama (FR-014): iki kol CTE + FULL OUTER JOIN + RRF
374
+ * (1/(50+rank), CLAIM-N4). Operatör şema-nitelikli (C-10, M-1); GUC
375
+ * hnsw.iterative_scan=relaxed_order aynı tx'te set_config ile (CLAIM-N3 —
376
+ * RLS/filtre altında LIMIT-altı dönüş açığını kapatır). Sorgu-anı embed
377
+ * T024'te gelir; o zamana dek vector kolu yalnız params.vector ile koşar.
378
+ */
379
+ search(table: string, params?: {
380
+ query?: string;
381
+ vector?: number[];
382
+ where?: Record<string, unknown>;
383
+ limit?: number;
384
+ using?: string;
385
+ mode?: "hybrid" | "text" | "vector";
386
+ /** Nihai (RRF-sonrası) skor alt eşiği — süzme LIMIT'ten ÖNCE (FR-001). */
387
+ minScore?: number;
388
+ /** RRF-sonrası üstel tazelik çürümesi: _score * exp(-ln(2)*yaş/halfLife) (FR-004). */
389
+ recency?: {
390
+ field: string;
391
+ halfLife: string;
392
+ };
393
+ /** Chunk-modunda satır başına dönen en iyi blok sayısı (1..10, vars. 3; FR-015). */
394
+ blocksPerRow?: number;
395
+ /** Filtrelenmiş küme üzerinde kolon başına top-20 değer sayacı —
396
+ * dönüş dizisinin `_facets` özelliği (FR-027). */
397
+ facets?: string[];
398
+ /** Satır-modunda FTS eşleşme vurgusu: ts_headline ile `_highlight`
399
+ * alanı; chunk-modda no-op — bloklar zaten eşleşen kesittir (FR-025). */
400
+ highlight?: boolean;
401
+ /** Validity'li tabloda zaman penceresi: varsayılan yalnız güncel;
402
+ * "all" tüm versiyonlar; {asOf} o andaki geçerli versiyon (FR-029). */
403
+ validity?: "all" | {
404
+ asOf: string;
405
+ };
406
+ /** Alan-boost (FR-030): skor * (1 + w·x/(1+x)) — sınırlı, dış servissiz. */
407
+ boost?: {
408
+ field: string;
409
+ weight: number;
410
+ };
411
+ }): Promise<Row[]>;
412
+ /**
413
+ * similar (T018, FR-022): "bu satıra benzeyenler". Hedef vektör DB'den
414
+ * okunur — satır-modu satırın kendi kolonu, chunk-modu parent chunk'larının
415
+ * şema-nitelikli avg'ı — ve ana arama search'ün vector yoluyla koşar;
416
+ * kaynak satır sonuçtan düşer. İKİ tur BİLİNÇLİ (plan T018): target-CTE'li
417
+ * tek SQL'de "id yok" ile "0 komşu" ayrılamazdı; +1 küçük turla id-yokluğu
418
+ * adlandırılmış hataya çevrilir. Sonuç şekli search ile aynı (FR-015).
419
+ */
420
+ similar(table: string, id: string, opts?: {
421
+ where?: Record<string, unknown>;
422
+ limit?: number;
423
+ using?: string;
424
+ minScore?: number;
425
+ recency?: {
426
+ field: string;
427
+ halfLife: string;
428
+ };
429
+ blocksPerRow?: number;
430
+ validity?: "all" | {
431
+ asOf: string;
432
+ };
433
+ boost?: {
434
+ field: string;
435
+ weight: number;
436
+ };
437
+ }): Promise<Row[]>;
438
+ /**
439
+ * recommend (T018, FR-023): positive/negative id kümelerinden öneri.
440
+ * Hedef vektör DB-İÇİ CTE'lerle türer: pos = avg(embedding of positives),
441
+ * negative varsa hedef = pos.v + (pos.v - neg.v) — pgvector avg agregası
442
+ * ve +/- operatörleri ŞEMA-NİTELİKLİ (M-1: search_path'e güvenilmez).
443
+ * Vektör matematiği istemciye inmez; bulunamayan positive/negative
444
+ * adlandırılmış hatadır ve kaynak id'ler sonuçtan düşer.
445
+ */
446
+ recommend(table: string, opts: {
447
+ positive: unknown[];
448
+ negative?: unknown[];
449
+ where?: Record<string, unknown>;
450
+ limit?: number;
451
+ using?: string;
452
+ minScore?: number;
453
+ recency?: {
454
+ field: string;
455
+ halfLife: string;
456
+ };
457
+ blocksPerRow?: number;
458
+ validity?: "all" | {
459
+ asOf: string;
460
+ };
461
+ boost?: {
462
+ field: string;
463
+ weight: number;
464
+ };
465
+ }): Promise<Row[]>;
466
+ /**
467
+ * supersede (T021, FR-029, C-9): validity'li tabloda satırın YENİ
468
+ * versiyonunu TEK savepoint'te yazar — eski satır kapatılır
469
+ * (valid_to = now(), superseded_by = yeni pk), yeni satır eklenir, dönüş
470
+ * yeni satırdır. Yeni pk CLIENT'ta üretilir (row'da verilmemişse
471
+ * randomUUID — declared şemaların uuid().defaultRandom() standardı) ki
472
+ * kapatma UPDATE'i INSERT'ten ÖNCE koşabilsin: 0 satır = zaten superseded
473
+ * ya da yok → INSERT hiç denenmez; INSERT hatası ise savepoint'le
474
+ * kapatmayı da geri sarar — yarım supersede diye bir durum yoktur.
475
+ */
476
+ supersede(table: string, id: string, row: Row): Promise<Row>;
437
477
  /** A real SAVEPOINT inside the request's transaction. */
438
478
  transaction<T>(cb: (t: unknown) => Promise<T>): Promise<T>;
439
479
  /**
@@ -779,36 +819,20 @@ declare function hostAllowed(host: string, allow: readonly string[]): boolean;
779
819
  */
780
820
  declare function installEgressFence(policy: EgressPolicy): typeof fetch;
781
821
 
782
- /**
783
- * engine/index.ts — the engine: a backend that boots itself.
784
- *
785
- * `createApp` turns a set of `@Controller` classes into a `fetch(Request)`
786
- * handler. No V8 isolate, no capability hop: this process owns its database
787
- * pool, verifies its own tokens, applies its own rate limits, and calls the
788
- * modules directly.
789
- *
790
- * import { createApp, loadConfig } from "@palbase/backend/engine";
791
- *
792
- * const app = await createApp({
793
- * config: loadConfig(process.env),
794
- * controllers: [TodosController],
795
- * schema,
796
- * });
797
- * Bun.serve({ port: app.config.port, fetch: app.handle });
798
- *
799
- * The Web-standard `fetch` signature is the point: the same handler runs under
800
- * Bun, Deno and any host that speaks Request/Response, so "works locally" and
801
- * "works in the cloud" are the same code path rather than two.
802
- */
803
-
804
822
  /** The `__`-prefixed request-scope seam, as re-exported by a deployed bundle. */
805
823
  interface RuntimeHooks {
806
824
  __runWithRuntime: typeof __runWithRuntime;
807
825
  __requestALS: typeof __requestALS;
808
826
  }
809
827
  /** The module singletons the engine injects, minus the two it owns itself. */
810
- type ModuleClients = Partial<Pick<RuntimeServices, "Documents" | "Storage" | "Notifications" | "Flags" | "Realtime" | "Purchases" | "Secrets">>;
828
+ type ModuleClients = Partial<Pick<RuntimeServices, "Documents" | "Storage" | "Notifications" | "Flags" | "Realtime" | "Secrets">>;
811
829
  interface CreateAppOptions {
830
+ /**
831
+ * Vault'tan TEK secret okuma (FR-025): sorgu-anı embedding'in anahtarı
832
+ * buradan akar. Verilmezse auto-embed'li search({query}) adlandırılmış
833
+ * hatayla düşer — sessiz boş sonuç asla (FR-015).
834
+ */
835
+ secretReader?: (name: string) => Promise<string | null>;
812
836
  config: EngineConfig;
813
837
  /** `@Controller` classes. A class that collected zero routes is fatal. */
814
838
  controllers: readonly unknown[];
@@ -855,4 +879,4 @@ interface App {
855
879
  */
856
880
  declare function createApp(opts: CreateAppOptions): Promise<App>;
857
881
 
858
- export { type App as A, BootRefused as B, Cache as C, Database as D, type EgressPolicy as E, Flags as F, effectiveAuth as G, hostAllowed as H, installEgressFence as I, loadConfig as J, makeMemoryCache as K, type LimitState as L, type ModuleClients as M, Notifications as N, matchRoute as O, Purchases as P, quoteIdent as Q, Realtime as R, Secrets as S, scrubSecrets as T, withTables as U, __getRuntime as _, Documents as a, Log as b, type PurchasesService as c, type RequestStore as d, type RuntimeServices as e, type SpendOptions as f, Storage as g, type StoreEnv as h, __requestALS as i, __runWithRuntime as j, __setRuntime as k, AuthVerifier as l, type CreateAppOptions as m, type EngineConfig as n, RateLimiter as o, type RequestDatabase as p, type RouteEntry as q, type RuntimeHooks as r, type ScrubResult as s, type SqlDriver as t, type SqlTx as u, buildRouteTable as v, createApp as w, createLazyTransaction as x, createOps as y, createRequestDatabase as z };
882
+ export { type App as A, BootRefused as B, Cache as C, Database as D, type EgressPolicy as E, Flags as F, makeMemoryCache as G, matchRoute as H, quoteIdent as I, scrubSecrets as J, withTables as K, Log as L, type ModuleClients as M, Notifications as N, Realtime as R, Secrets as S, __getRuntime as _, Documents as a, type RequestStore as b, type RuntimeServices as c, Storage as d, __requestALS as e, __runWithRuntime as f, __setRuntime as g, AuthVerifier as h, type CreateAppOptions as i, type EngineConfig as j, RateLimiter as k, type RequestDatabase as l, type RouteEntry as m, type RuntimeHooks as n, type ScrubResult as o, type SqlDriver as p, type SqlTx as q, buildRouteTable as r, createApp as s, createLazyTransaction as t, createOps as u, createRequestDatabase as v, effectiveAuth as w, hostAllowed as x, installEgressFence as y, loadConfig as z };