@dyrected/core 2.15.0 → 2.16.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.
@@ -1584,9 +1584,9 @@ type ActionConfig<TDoc extends Record<string, unknown> = Record<string, unknown>
1584
1584
  * Context passed to an action's server handler function.
1585
1585
  */
1586
1586
  interface ActionContext<TDoc extends Record<string, unknown> = Record<string, unknown>> {
1587
- /** The target document (for row actions). */
1588
- doc: TDoc;
1589
- /** All targeted documents (for bulk actions). */
1587
+ /** The target document (for row actions), or null for header actions. */
1588
+ doc: TDoc | null;
1589
+ /** All targeted documents (for bulk actions). Empty array for header actions. */
1590
1590
  docs: TDoc[];
1591
1591
  /** The authenticated acting user, if available. */
1592
1592
  user: Record<string, unknown> | null;
@@ -1835,6 +1835,30 @@ interface AuthConfig {
1835
1835
  */
1836
1836
  adminRole?: string;
1837
1837
  }
1838
+ /**
1839
+ * Physical database index specification for a collection.
1840
+ */
1841
+ interface CollectionIndex {
1842
+ /** Optional custom index name. If omitted, adapter auto-generates one. */
1843
+ name?: string;
1844
+ /** Field names participating in the index. */
1845
+ fields: string[];
1846
+ /** Whether the index enforces database-level uniqueness. Defaults to false. */
1847
+ unique?: boolean;
1848
+ /** Whether to only index non-null rows where supported. */
1849
+ sparse?: boolean;
1850
+ }
1851
+ /**
1852
+ * Atomic numeric update operators for database mutation payloads.
1853
+ */
1854
+ interface NumericUpdateOperator {
1855
+ increment?: number;
1856
+ decrement?: number;
1857
+ }
1858
+ /**
1859
+ * Strategy for generating document IDs.
1860
+ */
1861
+ type IdStrategy = "prefixed-nanoid" | "nanoid" | "ulid" | "uuid";
1838
1862
  /**
1839
1863
  * Use this contract when you want the exact shape of a collection config.
1840
1864
  *
@@ -1960,6 +1984,31 @@ interface CollectionConfig<TDoc extends object = Record<string, unknown>> {
1960
1984
  * @see {@link https://dyrected.com/docs/model-content/fields/blocks Blocks and page sections}
1961
1985
  */
1962
1986
  fields: Field[];
1987
+ /**
1988
+ * Database indexes to create on this collection.
1989
+ *
1990
+ * Fields participating in indexes are automatically promoted to physical columns.
1991
+ */
1992
+ indexes?: CollectionIndex[];
1993
+ /**
1994
+ * Optional custom prefix for auto-generated document IDs (e.g. `'usr'`, `'cob'`, `'sub'`).
1995
+ * When using the default prefixed ID generator, IDs will follow the format `${idPrefix}_${random}`.
1996
+ */
1997
+ idPrefix?: string;
1998
+ /**
1999
+ * Strategy for generating document IDs when not explicitly provided.
2000
+ * - `'prefixed-nanoid'`: Stripe-style prefixed NanoID (default), e.g. `cob_8xK2p9LmQwRt9a`
2001
+ * - `'nanoid'`: Compact URL-friendly random ID, e.g. `V1StGXR8_Z5jdHi6B-myT`
2002
+ * - `'ulid'`: 26-character Crockford Base32 time-sortable ID, e.g. `01J8K3R4Q7V9N2M1P6W0XYZA3C`
2003
+ * - `'uuid'`: 36-character RFC 4122 UUIDv4, e.g. `f47ac10b-58cc-4372-a567-0e02b2c3d479`
2004
+ *
2005
+ * Defaults to `'prefixed-nanoid'`.
2006
+ */
2007
+ idType?: IdStrategy;
2008
+ /**
2009
+ * Custom function to generate document IDs. Overrides `idType` and `idPrefix`.
2010
+ */
2011
+ idGenerator?: (slug: string) => string;
1963
2012
  /**
1964
2013
  * If `true`, Dyrected automatically adds the built-in system fields
1965
2014
  * `createdAt`, `updatedAt`, `createdBy`, and `updatedBy` to every document.
@@ -2424,21 +2473,26 @@ interface DatabaseAdapter {
2424
2473
  * ignore it; SQL adapters use it to sort numeric fields by magnitude.
2425
2474
  */
2426
2475
  fields?: Field[];
2476
+ /** Row-level locking strategy (e.g. SELECT ... FOR UPDATE in transactions). */
2477
+ lock?: "for-update";
2427
2478
  }): Promise<PaginatedResult>;
2428
2479
  /** Find a single document by its ID. Returns `null` if not found. */
2429
2480
  findOne(args: {
2430
2481
  collection: string;
2431
2482
  id: string;
2483
+ /** Row-level locking strategy (e.g. SELECT ... FOR UPDATE in transactions). */
2484
+ lock?: "for-update";
2432
2485
  }): Promise<BaseDocument | null>;
2433
2486
  /** Insert a new document and return it with its generated `id`. */
2434
2487
  create(args: {
2435
2488
  collection: string;
2436
2489
  data: Record<string, unknown>;
2437
2490
  }): Promise<BaseDocument>;
2438
- /** Update a document by ID and return the updated document. */
2491
+ /** Update a document by ID or conditional filter and return the updated document. */
2439
2492
  update(args: {
2440
2493
  collection: string;
2441
- id: string;
2494
+ id?: string;
2495
+ where?: Record<string, unknown>;
2442
2496
  data: Record<string, unknown>;
2443
2497
  }): Promise<BaseDocument>;
2444
2498
  /** Delete a document by ID. Return value is intentionally untyped — callers do not use it. */
@@ -3900,4 +3954,4 @@ interface DyrectedContext {
3900
3954
  */
3901
3955
  declare function createDyrectedApp(rawConfig: DyrectedConfig | any): Promise<Hono<DyrectedContext, hono_types.BlankSchema, "/">>;
3902
3956
 
3903
- export { type JoinField as $, type AdminAuthConfig as A, type Block as B, type CollectionConfig as C, type DyrectedConfig as D, type DetailTabs as E, type Field as F, type GlobalConfig as G, type HookRequestContext as H, type DetailTextOptions as I, type DetailText as J, type DetailSchema as K, type LifecycleEventName as L, type DyrectedContext as M, type AIConfig as N, type AIPIIConfig as O, type PublicAdminAuthConfig as P, type ArrayField as Q, type FieldType as R, type BooleanField as S, type AuthConfig as T, type AccessPolicyResolver as U, type DateField as V, type WorkflowConfig as W, type DateTimeField as X, type EmailField as Y, type IconField as Z, type ImageField as _, type DeclarativeHookExpression as a, type BooleanFieldAdmin as a$, type JsonField as a0, type MultiSelectField as a1, type NumberField as a2, type ObjectField as a3, type RadioField as a4, type RelationshipField as a5, type RichTextField as a6, type RowField as a7, type SelectField as a8, type TextField as a9, type ActionConfig as aA, type ActionConfigBase as aB, type ActionConfigWithHandler as aC, type ActionConfigWithMutation as aD, type ActionContext as aE, type ActionType as aF, type AdminAuthAccessResolution as aG, type AdminAuthClaimMapping as aH, type AdminAuthMember as aI, type AdminAuthProvider as aJ, type AdminAuthProviderMembersConfig as aK, type AdminAuthProvisioningMode as aL, type AdminAuthResolveAccessArgs as aM, type AdminAuthResolvedIdentity as aN, type AdminConfig as aO, type AdminDashboardComponentSlots as aP, type AdminIconName as aQ, type AggregateArgs as aR, type AggregateCastType as aS, type AggregateCollectionResult as aT, type AggregateInput as aU, type AggregateOperation as aV, type AggregateResult as aW, type BaseAdminAuthProvider as aX, type BaseFieldAdmin as aY, type BlockVariant as aZ, type BlocksField as a_, type TextareaField as aa, type TimeField as ab, type UrlField as ac, type AIAction as ad, type AIActionStatus as ae, type AIActionType as af, type AIAuditActionType as ag, type AIAuditRecord as ah, type AIChunk as ai, type AIMessage as aj, type AIPIIPattern as ak, type AIRateLimitResult as al, type AIRateLimitStore as am, type AIThread as an, type AIToolContext as ao, type AIToolDefinition as ap, AI_ACTIONS_COLLECTION as aq, AI_AUDIT_COLLECTION as ar, AI_CHUNKS_COLLECTION as as, AI_MESSAGES_COLLECTION as at, AI_THREADS_COLLECTION as au, type AccessConfig as av, type AccessFunction as aw, type AccessFunctionArgs as ax, type AccessResult as ay, type AccessRule as az, type AuthenticatedUser as b, type GlobalAfterReadHookEntry as b$, type BooleanFormat as b0, type CharacterLimitFieldAdmin as b1, type CharacterLimitFieldConfig as b2, type CollectionAfterChangeHook as b3, type CollectionAfterDeleteHook as b4, type CollectionAfterReadHook as b5, type CollectionAfterReadHookEntry as b6, type CollectionAfterTransitionHook as b7, type CollectionBeforeChangeHook as b8, type CollectionBeforeChangeHookEntry as b9, type DistinctCountOperation as bA, type DistinctValuesOperation as bB, type DynamicOptionItem as bC, type DynamicOptionsConfig as bD, type DynamicOptionsResolver as bE, type DynamicOptionsResolverArgs as bF, type DyrectedAIContext as bG, type DyrectedLoggerConfig as bH, type DyrectedObservabilityConfig as bI, type EmailFieldAdmin as bJ, type FieldAdminHooks as bK, type FieldAdminOnChangeHook as bL, type FieldAdminOnChangeHookArgs as bM, type FieldAdminOptionsHook as bN, type FieldAdminOptionsHookArgs as bO, type FieldAdminOptionsHookResult as bP, type FieldAfterReadHook as bQ, type FieldAfterReadHookArgs as bR, type FieldBase as bS, type FieldBeforeChangeHook as bT, type FieldBeforeChangeHookArgs as bU, type FieldHook as bV, type FieldHooks as bW, type FileData as bX, type GetDocumentResult as bY, type GlobalAfterChangeHook as bZ, type GlobalAfterReadHook as b_, type CollectionBeforeDeleteHook as ba, type CollectionBeforeReadHook as bb, type CollectionBeforeReadHookEntry as bc, type CollectionBeforeTransitionHook as bd, type CollectionListComponentSlots as be, type CollectionRAGConfig as bf, type CollectionSchemaResult as bg, type CollectionSummaryResult as bh, type CollectionViewComponentSlots as bi, type CountOperation as bj, type CustomAdminAuthProvider as bk, type DatabaseAdapter as bl, type DateFieldAdmin as bm, type DateFormat as bn, type DefaultValueContext as bo, type DefineActionOptions as bp, type DefineCalendarViewOptions as bq, type DefineCardsViewOptions as br, type DefineGanttViewOptions as bs, type DefineKanbanViewOptions as bt, type DefineTableViewOptions as bu, type DefineViewBaseOptions as bv, type DefineViewOptions as bw, type DetailSpan as bx, type DisplayTone as by, type DisplayVariant as bz, type WorkflowTransition as c, type WorkflowTransitionContext as c$, type GlobalBeforeChangeHook as c0, type GlobalBeforeChangeHookEntry as c1, type GlobalBeforeReadHook as c2, type GlobalBeforeReadHookEntry as c3, type GlobalRAGConfig as c4, type GlobalSchemaResult as c5, type GlobalSummaryResult as c6, type HeadingLevel as c7, type HookFunction as c8, type IconFieldAdmin as c9, type RichTextFeature as cA, type RichTextFieldConfig as cB, type SelectFieldAdmin as cC, type SqlWhereResult as cD, type StorageAdapter as cE, type TextFieldAdmin as cF, type TextFormat as cG, type TextareaFieldAdmin as cH, type TrustProxyConfig as cI, type TypedField as cJ, type UploadConfig as cK, type UrlFieldAdmin as cL, type UrlLinkValue as cM, type ViewActionFeatures as cN, type ViewComponentSlots as cO, type ViewConfig as cP, type ViewLayout as cQ, type ViewMetric as cR, type ViewSubMetric as cS, type WhereClause as cT, type WhereOperator as cU, type WhereOperatorName as cV, type WordLimitFieldAdmin as cW, type WordLimitFieldConfig as cX, type WorkflowMetadata as cY, type WorkflowRole as cZ, type WorkflowState as c_, type ImageService as ca, type ImageTransformOptions as cb, type InferAggregateResult as cc, type JoinFieldAdmin as cd, type JsonFieldAdmin as ce, type JsonFormat as cf, LIFECYCLE_EVENT_NAMES as cg, type LifecycleEventHandler as ch, type LinkFormat as ci, type MetricColor as cj, type MultiSelectFieldAdmin as ck, type NamedAccessPolicy as cl, type NumberFieldAdmin as cm, type NumberFormat as cn, type NumberLimitFieldAdmin as co, type NumberLimitFieldConfig as cp, type NumericOperation as cq, type OIDCAdminAuthProvider as cr, type OptionFormat as cs, type PaginatedResult as ct, type PublicAdminAuthProvider as cu, type QueryCollectionResult as cv, type RAGSearchResult as cw, type RadioFieldAdmin as cx, type RateLimitConfig as cy, type ReadonlyDatabaseAdapter as cz, type LifecycleEvent as d, defineAction as d0, defineCalendarView as d1, defineCardsView as d2, defineGanttView as d3, defineKanbanView as d4, defineTableView as d5, defineView as d6, isAICollection as d7, parseMongoWhere as d8, parseSqlWhere as d9, verifyCollectionToken as dA, type CollectionTokenPayload as da, DEFAULT_SESSION_EXPIRY as db, type DyrectedObservabilityRuntime as dc, type RequestBodyCapture as dd, type RequestTraceContext as de, type ResolvedObservabilityConfig as df, attachRequestMetrics as dg, bindObservabilityRuntime as dh, buildRequestLogger as di, captureRequestBody as dj, createDyrectedApp as dk, createObservabilityRuntime as dl, createRequestSpan as dm, decodeCollectionToken as dn, endRequestSpan as dp, getConfigLogger as dq, getObservabilityRuntime as dr, getRequestLogger as ds, redactBody as dt, redactHeaders as du, renderPrometheusMetrics as dv, resolveObservabilityConfig as dw, resolveSessionTokenExpiry as dx, shouldSampleRequest as dy, signCollectionToken as dz, type BaseDocument as e, type DetailActionOptions as f, type DetailAction as g, type DetailComputedOptions as h, type ComputedHandler as i, type DetailComputed as j, type DetailCustomOptions as k, type DetailCustom as l, type DetailDividerOptions as m, type DetailDivider as n, type DisplayFieldOptions as o, type DetailField as p, type DetailItem as q, type DetailGridOptions as r, type DetailGrid as s, type DetailRepeatOptions as t, type DetailRepeat as u, type DetailSectionOptions as v, type DetailSection as w, type DetailTabOptions as x, type DetailTab as y, type DetailTabsOptions as z };
3957
+ export { type ImageField as $, type AdminAuthConfig as A, type Block as B, type CollectionConfig as C, type DyrectedConfig as D, type DetailTabs as E, type Field as F, type GlobalConfig as G, type HookRequestContext as H, type DetailTextOptions as I, type DetailText as J, type DetailSchema as K, type LifecycleEventName as L, type DyrectedContext as M, type AIConfig as N, type AIPIIConfig as O, type PublicAdminAuthConfig as P, type IdStrategy as Q, type ArrayField as R, type FieldType as S, type BooleanField as T, type AuthConfig as U, type AccessPolicyResolver as V, type WorkflowConfig as W, type DateField as X, type DateTimeField as Y, type EmailField as Z, type IconField as _, type DeclarativeHookExpression as a, type BlocksField as a$, type JoinField as a0, type JsonField as a1, type MultiSelectField as a2, type NumberField as a3, type ObjectField as a4, type RadioField as a5, type RelationshipField as a6, type RichTextField as a7, type RowField as a8, type SelectField as a9, type AccessRule as aA, type ActionConfig as aB, type ActionConfigBase as aC, type ActionConfigWithHandler as aD, type ActionConfigWithMutation as aE, type ActionContext as aF, type ActionType as aG, type AdminAuthAccessResolution as aH, type AdminAuthClaimMapping as aI, type AdminAuthMember as aJ, type AdminAuthProvider as aK, type AdminAuthProviderMembersConfig as aL, type AdminAuthProvisioningMode as aM, type AdminAuthResolveAccessArgs as aN, type AdminAuthResolvedIdentity as aO, type AdminConfig as aP, type AdminDashboardComponentSlots as aQ, type AdminIconName as aR, type AggregateArgs as aS, type AggregateCastType as aT, type AggregateCollectionResult as aU, type AggregateInput as aV, type AggregateOperation as aW, type AggregateResult as aX, type BaseAdminAuthProvider as aY, type BaseFieldAdmin as aZ, type BlockVariant as a_, type TextField as aa, type TextareaField as ab, type TimeField as ac, type UrlField as ad, type AIAction as ae, type AIActionStatus as af, type AIActionType as ag, type AIAuditActionType as ah, type AIAuditRecord as ai, type AIChunk as aj, type AIMessage as ak, type AIPIIPattern as al, type AIRateLimitResult as am, type AIRateLimitStore as an, type AIThread as ao, type AIToolContext as ap, type AIToolDefinition as aq, AI_ACTIONS_COLLECTION as ar, AI_AUDIT_COLLECTION as as, AI_CHUNKS_COLLECTION as at, AI_MESSAGES_COLLECTION as au, AI_THREADS_COLLECTION as av, type AccessConfig as aw, type AccessFunction as ax, type AccessFunctionArgs as ay, type AccessResult as az, type AuthenticatedUser as b, type GlobalAfterChangeHook as b$, type BooleanFieldAdmin as b0, type BooleanFormat as b1, type CharacterLimitFieldAdmin as b2, type CharacterLimitFieldConfig as b3, type CollectionAfterChangeHook as b4, type CollectionAfterDeleteHook as b5, type CollectionAfterReadHook as b6, type CollectionAfterReadHookEntry as b7, type CollectionAfterTransitionHook as b8, type CollectionBeforeChangeHook as b9, type DisplayTone as bA, type DisplayVariant as bB, type DistinctCountOperation as bC, type DistinctValuesOperation as bD, type DynamicOptionItem as bE, type DynamicOptionsConfig as bF, type DynamicOptionsResolver as bG, type DynamicOptionsResolverArgs as bH, type DyrectedAIContext as bI, type DyrectedLoggerConfig as bJ, type DyrectedObservabilityConfig as bK, type EmailFieldAdmin as bL, type FieldAdminHooks as bM, type FieldAdminOnChangeHook as bN, type FieldAdminOnChangeHookArgs as bO, type FieldAdminOptionsHook as bP, type FieldAdminOptionsHookArgs as bQ, type FieldAdminOptionsHookResult as bR, type FieldAfterReadHook as bS, type FieldAfterReadHookArgs as bT, type FieldBase as bU, type FieldBeforeChangeHook as bV, type FieldBeforeChangeHookArgs as bW, type FieldHook as bX, type FieldHooks as bY, type FileData as bZ, type GetDocumentResult as b_, type CollectionBeforeChangeHookEntry as ba, type CollectionBeforeDeleteHook as bb, type CollectionBeforeReadHook as bc, type CollectionBeforeReadHookEntry as bd, type CollectionBeforeTransitionHook as be, type CollectionIndex as bf, type CollectionListComponentSlots as bg, type CollectionRAGConfig as bh, type CollectionSchemaResult as bi, type CollectionSummaryResult as bj, type CollectionViewComponentSlots as bk, type CountOperation as bl, type CustomAdminAuthProvider as bm, type DatabaseAdapter as bn, type DateFieldAdmin as bo, type DateFormat as bp, type DefaultValueContext as bq, type DefineActionOptions as br, type DefineCalendarViewOptions as bs, type DefineCardsViewOptions as bt, type DefineGanttViewOptions as bu, type DefineKanbanViewOptions as bv, type DefineTableViewOptions as bw, type DefineViewBaseOptions as bx, type DefineViewOptions as by, type DetailSpan as bz, type WorkflowTransition as c, type WorkflowMetadata as c$, type GlobalAfterReadHook as c0, type GlobalAfterReadHookEntry as c1, type GlobalBeforeChangeHook as c2, type GlobalBeforeChangeHookEntry as c3, type GlobalBeforeReadHook as c4, type GlobalBeforeReadHookEntry as c5, type GlobalRAGConfig as c6, type GlobalSchemaResult as c7, type GlobalSummaryResult as c8, type HeadingLevel as c9, type RadioFieldAdmin as cA, type RateLimitConfig as cB, type ReadonlyDatabaseAdapter as cC, type RichTextFeature as cD, type RichTextFieldConfig as cE, type SelectFieldAdmin as cF, type SqlWhereResult as cG, type StorageAdapter as cH, type TextFieldAdmin as cI, type TextFormat as cJ, type TextareaFieldAdmin as cK, type TrustProxyConfig as cL, type TypedField as cM, type UploadConfig as cN, type UrlFieldAdmin as cO, type UrlLinkValue as cP, type ViewActionFeatures as cQ, type ViewComponentSlots as cR, type ViewConfig as cS, type ViewLayout as cT, type ViewMetric as cU, type ViewSubMetric as cV, type WhereClause as cW, type WhereOperator as cX, type WhereOperatorName as cY, type WordLimitFieldAdmin as cZ, type WordLimitFieldConfig as c_, type HookFunction as ca, type IconFieldAdmin as cb, type ImageService as cc, type ImageTransformOptions as cd, type InferAggregateResult as ce, type JoinFieldAdmin as cf, type JsonFieldAdmin as cg, type JsonFormat as ch, LIFECYCLE_EVENT_NAMES as ci, type LifecycleEventHandler as cj, type LinkFormat as ck, type MetricColor as cl, type MultiSelectFieldAdmin as cm, type NamedAccessPolicy as cn, type NumberFieldAdmin as co, type NumberFormat as cp, type NumberLimitFieldAdmin as cq, type NumberLimitFieldConfig as cr, type NumericOperation as cs, type NumericUpdateOperator as ct, type OIDCAdminAuthProvider as cu, type OptionFormat as cv, type PaginatedResult as cw, type PublicAdminAuthProvider as cx, type QueryCollectionResult as cy, type RAGSearchResult as cz, type LifecycleEvent as d, type WorkflowRole as d0, type WorkflowState as d1, type WorkflowTransitionContext as d2, defineAction as d3, defineCalendarView as d4, defineCardsView as d5, defineGanttView as d6, defineKanbanView as d7, defineTableView as d8, defineView as d9, resolveSessionTokenExpiry as dA, shouldSampleRequest as dB, signCollectionToken as dC, verifyCollectionToken as dD, isAICollection as da, parseMongoWhere as db, parseSqlWhere as dc, type CollectionTokenPayload as dd, DEFAULT_SESSION_EXPIRY as de, type DyrectedObservabilityRuntime as df, type RequestBodyCapture as dg, type RequestTraceContext as dh, type ResolvedObservabilityConfig as di, attachRequestMetrics as dj, bindObservabilityRuntime as dk, buildRequestLogger as dl, captureRequestBody as dm, createDyrectedApp as dn, createObservabilityRuntime as dp, createRequestSpan as dq, decodeCollectionToken as dr, endRequestSpan as ds, getConfigLogger as dt, getObservabilityRuntime as du, getRequestLogger as dv, redactBody as dw, redactHeaders as dx, renderPrometheusMetrics as dy, resolveObservabilityConfig as dz, type BaseDocument as e, type DetailActionOptions as f, type DetailAction as g, type DetailComputedOptions as h, type ComputedHandler as i, type DetailComputed as j, type DetailCustomOptions as k, type DetailCustom as l, type DetailDividerOptions as m, type DetailDivider as n, type DisplayFieldOptions as o, type DetailField as p, type DetailItem as q, type DetailGridOptions as r, type DetailGrid as s, type DetailRepeatOptions as t, type DetailRepeat as u, type DetailSectionOptions as v, type DetailSection as w, type DetailTabOptions as x, type DetailTab as y, type DetailTabsOptions as z };
@@ -1584,9 +1584,9 @@ type ActionConfig<TDoc extends Record<string, unknown> = Record<string, unknown>
1584
1584
  * Context passed to an action's server handler function.
1585
1585
  */
1586
1586
  interface ActionContext<TDoc extends Record<string, unknown> = Record<string, unknown>> {
1587
- /** The target document (for row actions). */
1588
- doc: TDoc;
1589
- /** All targeted documents (for bulk actions). */
1587
+ /** The target document (for row actions), or null for header actions. */
1588
+ doc: TDoc | null;
1589
+ /** All targeted documents (for bulk actions). Empty array for header actions. */
1590
1590
  docs: TDoc[];
1591
1591
  /** The authenticated acting user, if available. */
1592
1592
  user: Record<string, unknown> | null;
@@ -1835,6 +1835,30 @@ interface AuthConfig {
1835
1835
  */
1836
1836
  adminRole?: string;
1837
1837
  }
1838
+ /**
1839
+ * Physical database index specification for a collection.
1840
+ */
1841
+ interface CollectionIndex {
1842
+ /** Optional custom index name. If omitted, adapter auto-generates one. */
1843
+ name?: string;
1844
+ /** Field names participating in the index. */
1845
+ fields: string[];
1846
+ /** Whether the index enforces database-level uniqueness. Defaults to false. */
1847
+ unique?: boolean;
1848
+ /** Whether to only index non-null rows where supported. */
1849
+ sparse?: boolean;
1850
+ }
1851
+ /**
1852
+ * Atomic numeric update operators for database mutation payloads.
1853
+ */
1854
+ interface NumericUpdateOperator {
1855
+ increment?: number;
1856
+ decrement?: number;
1857
+ }
1858
+ /**
1859
+ * Strategy for generating document IDs.
1860
+ */
1861
+ type IdStrategy = "prefixed-nanoid" | "nanoid" | "ulid" | "uuid";
1838
1862
  /**
1839
1863
  * Use this contract when you want the exact shape of a collection config.
1840
1864
  *
@@ -1960,6 +1984,31 @@ interface CollectionConfig<TDoc extends object = Record<string, unknown>> {
1960
1984
  * @see {@link https://dyrected.com/docs/model-content/fields/blocks Blocks and page sections}
1961
1985
  */
1962
1986
  fields: Field[];
1987
+ /**
1988
+ * Database indexes to create on this collection.
1989
+ *
1990
+ * Fields participating in indexes are automatically promoted to physical columns.
1991
+ */
1992
+ indexes?: CollectionIndex[];
1993
+ /**
1994
+ * Optional custom prefix for auto-generated document IDs (e.g. `'usr'`, `'cob'`, `'sub'`).
1995
+ * When using the default prefixed ID generator, IDs will follow the format `${idPrefix}_${random}`.
1996
+ */
1997
+ idPrefix?: string;
1998
+ /**
1999
+ * Strategy for generating document IDs when not explicitly provided.
2000
+ * - `'prefixed-nanoid'`: Stripe-style prefixed NanoID (default), e.g. `cob_8xK2p9LmQwRt9a`
2001
+ * - `'nanoid'`: Compact URL-friendly random ID, e.g. `V1StGXR8_Z5jdHi6B-myT`
2002
+ * - `'ulid'`: 26-character Crockford Base32 time-sortable ID, e.g. `01J8K3R4Q7V9N2M1P6W0XYZA3C`
2003
+ * - `'uuid'`: 36-character RFC 4122 UUIDv4, e.g. `f47ac10b-58cc-4372-a567-0e02b2c3d479`
2004
+ *
2005
+ * Defaults to `'prefixed-nanoid'`.
2006
+ */
2007
+ idType?: IdStrategy;
2008
+ /**
2009
+ * Custom function to generate document IDs. Overrides `idType` and `idPrefix`.
2010
+ */
2011
+ idGenerator?: (slug: string) => string;
1963
2012
  /**
1964
2013
  * If `true`, Dyrected automatically adds the built-in system fields
1965
2014
  * `createdAt`, `updatedAt`, `createdBy`, and `updatedBy` to every document.
@@ -2424,21 +2473,26 @@ interface DatabaseAdapter {
2424
2473
  * ignore it; SQL adapters use it to sort numeric fields by magnitude.
2425
2474
  */
2426
2475
  fields?: Field[];
2476
+ /** Row-level locking strategy (e.g. SELECT ... FOR UPDATE in transactions). */
2477
+ lock?: "for-update";
2427
2478
  }): Promise<PaginatedResult>;
2428
2479
  /** Find a single document by its ID. Returns `null` if not found. */
2429
2480
  findOne(args: {
2430
2481
  collection: string;
2431
2482
  id: string;
2483
+ /** Row-level locking strategy (e.g. SELECT ... FOR UPDATE in transactions). */
2484
+ lock?: "for-update";
2432
2485
  }): Promise<BaseDocument | null>;
2433
2486
  /** Insert a new document and return it with its generated `id`. */
2434
2487
  create(args: {
2435
2488
  collection: string;
2436
2489
  data: Record<string, unknown>;
2437
2490
  }): Promise<BaseDocument>;
2438
- /** Update a document by ID and return the updated document. */
2491
+ /** Update a document by ID or conditional filter and return the updated document. */
2439
2492
  update(args: {
2440
2493
  collection: string;
2441
- id: string;
2494
+ id?: string;
2495
+ where?: Record<string, unknown>;
2442
2496
  data: Record<string, unknown>;
2443
2497
  }): Promise<BaseDocument>;
2444
2498
  /** Delete a document by ID. Return value is intentionally untyped — callers do not use it. */
@@ -3900,4 +3954,4 @@ interface DyrectedContext {
3900
3954
  */
3901
3955
  declare function createDyrectedApp(rawConfig: DyrectedConfig | any): Promise<Hono<DyrectedContext, hono_types.BlankSchema, "/">>;
3902
3956
 
3903
- export { type JoinField as $, type AdminAuthConfig as A, type Block as B, type CollectionConfig as C, type DyrectedConfig as D, type DetailTabs as E, type Field as F, type GlobalConfig as G, type HookRequestContext as H, type DetailTextOptions as I, type DetailText as J, type DetailSchema as K, type LifecycleEventName as L, type DyrectedContext as M, type AIConfig as N, type AIPIIConfig as O, type PublicAdminAuthConfig as P, type ArrayField as Q, type FieldType as R, type BooleanField as S, type AuthConfig as T, type AccessPolicyResolver as U, type DateField as V, type WorkflowConfig as W, type DateTimeField as X, type EmailField as Y, type IconField as Z, type ImageField as _, type DeclarativeHookExpression as a, type BooleanFieldAdmin as a$, type JsonField as a0, type MultiSelectField as a1, type NumberField as a2, type ObjectField as a3, type RadioField as a4, type RelationshipField as a5, type RichTextField as a6, type RowField as a7, type SelectField as a8, type TextField as a9, type ActionConfig as aA, type ActionConfigBase as aB, type ActionConfigWithHandler as aC, type ActionConfigWithMutation as aD, type ActionContext as aE, type ActionType as aF, type AdminAuthAccessResolution as aG, type AdminAuthClaimMapping as aH, type AdminAuthMember as aI, type AdminAuthProvider as aJ, type AdminAuthProviderMembersConfig as aK, type AdminAuthProvisioningMode as aL, type AdminAuthResolveAccessArgs as aM, type AdminAuthResolvedIdentity as aN, type AdminConfig as aO, type AdminDashboardComponentSlots as aP, type AdminIconName as aQ, type AggregateArgs as aR, type AggregateCastType as aS, type AggregateCollectionResult as aT, type AggregateInput as aU, type AggregateOperation as aV, type AggregateResult as aW, type BaseAdminAuthProvider as aX, type BaseFieldAdmin as aY, type BlockVariant as aZ, type BlocksField as a_, type TextareaField as aa, type TimeField as ab, type UrlField as ac, type AIAction as ad, type AIActionStatus as ae, type AIActionType as af, type AIAuditActionType as ag, type AIAuditRecord as ah, type AIChunk as ai, type AIMessage as aj, type AIPIIPattern as ak, type AIRateLimitResult as al, type AIRateLimitStore as am, type AIThread as an, type AIToolContext as ao, type AIToolDefinition as ap, AI_ACTIONS_COLLECTION as aq, AI_AUDIT_COLLECTION as ar, AI_CHUNKS_COLLECTION as as, AI_MESSAGES_COLLECTION as at, AI_THREADS_COLLECTION as au, type AccessConfig as av, type AccessFunction as aw, type AccessFunctionArgs as ax, type AccessResult as ay, type AccessRule as az, type AuthenticatedUser as b, type GlobalAfterReadHookEntry as b$, type BooleanFormat as b0, type CharacterLimitFieldAdmin as b1, type CharacterLimitFieldConfig as b2, type CollectionAfterChangeHook as b3, type CollectionAfterDeleteHook as b4, type CollectionAfterReadHook as b5, type CollectionAfterReadHookEntry as b6, type CollectionAfterTransitionHook as b7, type CollectionBeforeChangeHook as b8, type CollectionBeforeChangeHookEntry as b9, type DistinctCountOperation as bA, type DistinctValuesOperation as bB, type DynamicOptionItem as bC, type DynamicOptionsConfig as bD, type DynamicOptionsResolver as bE, type DynamicOptionsResolverArgs as bF, type DyrectedAIContext as bG, type DyrectedLoggerConfig as bH, type DyrectedObservabilityConfig as bI, type EmailFieldAdmin as bJ, type FieldAdminHooks as bK, type FieldAdminOnChangeHook as bL, type FieldAdminOnChangeHookArgs as bM, type FieldAdminOptionsHook as bN, type FieldAdminOptionsHookArgs as bO, type FieldAdminOptionsHookResult as bP, type FieldAfterReadHook as bQ, type FieldAfterReadHookArgs as bR, type FieldBase as bS, type FieldBeforeChangeHook as bT, type FieldBeforeChangeHookArgs as bU, type FieldHook as bV, type FieldHooks as bW, type FileData as bX, type GetDocumentResult as bY, type GlobalAfterChangeHook as bZ, type GlobalAfterReadHook as b_, type CollectionBeforeDeleteHook as ba, type CollectionBeforeReadHook as bb, type CollectionBeforeReadHookEntry as bc, type CollectionBeforeTransitionHook as bd, type CollectionListComponentSlots as be, type CollectionRAGConfig as bf, type CollectionSchemaResult as bg, type CollectionSummaryResult as bh, type CollectionViewComponentSlots as bi, type CountOperation as bj, type CustomAdminAuthProvider as bk, type DatabaseAdapter as bl, type DateFieldAdmin as bm, type DateFormat as bn, type DefaultValueContext as bo, type DefineActionOptions as bp, type DefineCalendarViewOptions as bq, type DefineCardsViewOptions as br, type DefineGanttViewOptions as bs, type DefineKanbanViewOptions as bt, type DefineTableViewOptions as bu, type DefineViewBaseOptions as bv, type DefineViewOptions as bw, type DetailSpan as bx, type DisplayTone as by, type DisplayVariant as bz, type WorkflowTransition as c, type WorkflowTransitionContext as c$, type GlobalBeforeChangeHook as c0, type GlobalBeforeChangeHookEntry as c1, type GlobalBeforeReadHook as c2, type GlobalBeforeReadHookEntry as c3, type GlobalRAGConfig as c4, type GlobalSchemaResult as c5, type GlobalSummaryResult as c6, type HeadingLevel as c7, type HookFunction as c8, type IconFieldAdmin as c9, type RichTextFeature as cA, type RichTextFieldConfig as cB, type SelectFieldAdmin as cC, type SqlWhereResult as cD, type StorageAdapter as cE, type TextFieldAdmin as cF, type TextFormat as cG, type TextareaFieldAdmin as cH, type TrustProxyConfig as cI, type TypedField as cJ, type UploadConfig as cK, type UrlFieldAdmin as cL, type UrlLinkValue as cM, type ViewActionFeatures as cN, type ViewComponentSlots as cO, type ViewConfig as cP, type ViewLayout as cQ, type ViewMetric as cR, type ViewSubMetric as cS, type WhereClause as cT, type WhereOperator as cU, type WhereOperatorName as cV, type WordLimitFieldAdmin as cW, type WordLimitFieldConfig as cX, type WorkflowMetadata as cY, type WorkflowRole as cZ, type WorkflowState as c_, type ImageService as ca, type ImageTransformOptions as cb, type InferAggregateResult as cc, type JoinFieldAdmin as cd, type JsonFieldAdmin as ce, type JsonFormat as cf, LIFECYCLE_EVENT_NAMES as cg, type LifecycleEventHandler as ch, type LinkFormat as ci, type MetricColor as cj, type MultiSelectFieldAdmin as ck, type NamedAccessPolicy as cl, type NumberFieldAdmin as cm, type NumberFormat as cn, type NumberLimitFieldAdmin as co, type NumberLimitFieldConfig as cp, type NumericOperation as cq, type OIDCAdminAuthProvider as cr, type OptionFormat as cs, type PaginatedResult as ct, type PublicAdminAuthProvider as cu, type QueryCollectionResult as cv, type RAGSearchResult as cw, type RadioFieldAdmin as cx, type RateLimitConfig as cy, type ReadonlyDatabaseAdapter as cz, type LifecycleEvent as d, defineAction as d0, defineCalendarView as d1, defineCardsView as d2, defineGanttView as d3, defineKanbanView as d4, defineTableView as d5, defineView as d6, isAICollection as d7, parseMongoWhere as d8, parseSqlWhere as d9, verifyCollectionToken as dA, type CollectionTokenPayload as da, DEFAULT_SESSION_EXPIRY as db, type DyrectedObservabilityRuntime as dc, type RequestBodyCapture as dd, type RequestTraceContext as de, type ResolvedObservabilityConfig as df, attachRequestMetrics as dg, bindObservabilityRuntime as dh, buildRequestLogger as di, captureRequestBody as dj, createDyrectedApp as dk, createObservabilityRuntime as dl, createRequestSpan as dm, decodeCollectionToken as dn, endRequestSpan as dp, getConfigLogger as dq, getObservabilityRuntime as dr, getRequestLogger as ds, redactBody as dt, redactHeaders as du, renderPrometheusMetrics as dv, resolveObservabilityConfig as dw, resolveSessionTokenExpiry as dx, shouldSampleRequest as dy, signCollectionToken as dz, type BaseDocument as e, type DetailActionOptions as f, type DetailAction as g, type DetailComputedOptions as h, type ComputedHandler as i, type DetailComputed as j, type DetailCustomOptions as k, type DetailCustom as l, type DetailDividerOptions as m, type DetailDivider as n, type DisplayFieldOptions as o, type DetailField as p, type DetailItem as q, type DetailGridOptions as r, type DetailGrid as s, type DetailRepeatOptions as t, type DetailRepeat as u, type DetailSectionOptions as v, type DetailSection as w, type DetailTabOptions as x, type DetailTab as y, type DetailTabsOptions as z };
3957
+ export { type ImageField as $, type AdminAuthConfig as A, type Block as B, type CollectionConfig as C, type DyrectedConfig as D, type DetailTabs as E, type Field as F, type GlobalConfig as G, type HookRequestContext as H, type DetailTextOptions as I, type DetailText as J, type DetailSchema as K, type LifecycleEventName as L, type DyrectedContext as M, type AIConfig as N, type AIPIIConfig as O, type PublicAdminAuthConfig as P, type IdStrategy as Q, type ArrayField as R, type FieldType as S, type BooleanField as T, type AuthConfig as U, type AccessPolicyResolver as V, type WorkflowConfig as W, type DateField as X, type DateTimeField as Y, type EmailField as Z, type IconField as _, type DeclarativeHookExpression as a, type BlocksField as a$, type JoinField as a0, type JsonField as a1, type MultiSelectField as a2, type NumberField as a3, type ObjectField as a4, type RadioField as a5, type RelationshipField as a6, type RichTextField as a7, type RowField as a8, type SelectField as a9, type AccessRule as aA, type ActionConfig as aB, type ActionConfigBase as aC, type ActionConfigWithHandler as aD, type ActionConfigWithMutation as aE, type ActionContext as aF, type ActionType as aG, type AdminAuthAccessResolution as aH, type AdminAuthClaimMapping as aI, type AdminAuthMember as aJ, type AdminAuthProvider as aK, type AdminAuthProviderMembersConfig as aL, type AdminAuthProvisioningMode as aM, type AdminAuthResolveAccessArgs as aN, type AdminAuthResolvedIdentity as aO, type AdminConfig as aP, type AdminDashboardComponentSlots as aQ, type AdminIconName as aR, type AggregateArgs as aS, type AggregateCastType as aT, type AggregateCollectionResult as aU, type AggregateInput as aV, type AggregateOperation as aW, type AggregateResult as aX, type BaseAdminAuthProvider as aY, type BaseFieldAdmin as aZ, type BlockVariant as a_, type TextField as aa, type TextareaField as ab, type TimeField as ac, type UrlField as ad, type AIAction as ae, type AIActionStatus as af, type AIActionType as ag, type AIAuditActionType as ah, type AIAuditRecord as ai, type AIChunk as aj, type AIMessage as ak, type AIPIIPattern as al, type AIRateLimitResult as am, type AIRateLimitStore as an, type AIThread as ao, type AIToolContext as ap, type AIToolDefinition as aq, AI_ACTIONS_COLLECTION as ar, AI_AUDIT_COLLECTION as as, AI_CHUNKS_COLLECTION as at, AI_MESSAGES_COLLECTION as au, AI_THREADS_COLLECTION as av, type AccessConfig as aw, type AccessFunction as ax, type AccessFunctionArgs as ay, type AccessResult as az, type AuthenticatedUser as b, type GlobalAfterChangeHook as b$, type BooleanFieldAdmin as b0, type BooleanFormat as b1, type CharacterLimitFieldAdmin as b2, type CharacterLimitFieldConfig as b3, type CollectionAfterChangeHook as b4, type CollectionAfterDeleteHook as b5, type CollectionAfterReadHook as b6, type CollectionAfterReadHookEntry as b7, type CollectionAfterTransitionHook as b8, type CollectionBeforeChangeHook as b9, type DisplayTone as bA, type DisplayVariant as bB, type DistinctCountOperation as bC, type DistinctValuesOperation as bD, type DynamicOptionItem as bE, type DynamicOptionsConfig as bF, type DynamicOptionsResolver as bG, type DynamicOptionsResolverArgs as bH, type DyrectedAIContext as bI, type DyrectedLoggerConfig as bJ, type DyrectedObservabilityConfig as bK, type EmailFieldAdmin as bL, type FieldAdminHooks as bM, type FieldAdminOnChangeHook as bN, type FieldAdminOnChangeHookArgs as bO, type FieldAdminOptionsHook as bP, type FieldAdminOptionsHookArgs as bQ, type FieldAdminOptionsHookResult as bR, type FieldAfterReadHook as bS, type FieldAfterReadHookArgs as bT, type FieldBase as bU, type FieldBeforeChangeHook as bV, type FieldBeforeChangeHookArgs as bW, type FieldHook as bX, type FieldHooks as bY, type FileData as bZ, type GetDocumentResult as b_, type CollectionBeforeChangeHookEntry as ba, type CollectionBeforeDeleteHook as bb, type CollectionBeforeReadHook as bc, type CollectionBeforeReadHookEntry as bd, type CollectionBeforeTransitionHook as be, type CollectionIndex as bf, type CollectionListComponentSlots as bg, type CollectionRAGConfig as bh, type CollectionSchemaResult as bi, type CollectionSummaryResult as bj, type CollectionViewComponentSlots as bk, type CountOperation as bl, type CustomAdminAuthProvider as bm, type DatabaseAdapter as bn, type DateFieldAdmin as bo, type DateFormat as bp, type DefaultValueContext as bq, type DefineActionOptions as br, type DefineCalendarViewOptions as bs, type DefineCardsViewOptions as bt, type DefineGanttViewOptions as bu, type DefineKanbanViewOptions as bv, type DefineTableViewOptions as bw, type DefineViewBaseOptions as bx, type DefineViewOptions as by, type DetailSpan as bz, type WorkflowTransition as c, type WorkflowMetadata as c$, type GlobalAfterReadHook as c0, type GlobalAfterReadHookEntry as c1, type GlobalBeforeChangeHook as c2, type GlobalBeforeChangeHookEntry as c3, type GlobalBeforeReadHook as c4, type GlobalBeforeReadHookEntry as c5, type GlobalRAGConfig as c6, type GlobalSchemaResult as c7, type GlobalSummaryResult as c8, type HeadingLevel as c9, type RadioFieldAdmin as cA, type RateLimitConfig as cB, type ReadonlyDatabaseAdapter as cC, type RichTextFeature as cD, type RichTextFieldConfig as cE, type SelectFieldAdmin as cF, type SqlWhereResult as cG, type StorageAdapter as cH, type TextFieldAdmin as cI, type TextFormat as cJ, type TextareaFieldAdmin as cK, type TrustProxyConfig as cL, type TypedField as cM, type UploadConfig as cN, type UrlFieldAdmin as cO, type UrlLinkValue as cP, type ViewActionFeatures as cQ, type ViewComponentSlots as cR, type ViewConfig as cS, type ViewLayout as cT, type ViewMetric as cU, type ViewSubMetric as cV, type WhereClause as cW, type WhereOperator as cX, type WhereOperatorName as cY, type WordLimitFieldAdmin as cZ, type WordLimitFieldConfig as c_, type HookFunction as ca, type IconFieldAdmin as cb, type ImageService as cc, type ImageTransformOptions as cd, type InferAggregateResult as ce, type JoinFieldAdmin as cf, type JsonFieldAdmin as cg, type JsonFormat as ch, LIFECYCLE_EVENT_NAMES as ci, type LifecycleEventHandler as cj, type LinkFormat as ck, type MetricColor as cl, type MultiSelectFieldAdmin as cm, type NamedAccessPolicy as cn, type NumberFieldAdmin as co, type NumberFormat as cp, type NumberLimitFieldAdmin as cq, type NumberLimitFieldConfig as cr, type NumericOperation as cs, type NumericUpdateOperator as ct, type OIDCAdminAuthProvider as cu, type OptionFormat as cv, type PaginatedResult as cw, type PublicAdminAuthProvider as cx, type QueryCollectionResult as cy, type RAGSearchResult as cz, type LifecycleEvent as d, type WorkflowRole as d0, type WorkflowState as d1, type WorkflowTransitionContext as d2, defineAction as d3, defineCalendarView as d4, defineCardsView as d5, defineGanttView as d6, defineKanbanView as d7, defineTableView as d8, defineView as d9, resolveSessionTokenExpiry as dA, shouldSampleRequest as dB, signCollectionToken as dC, verifyCollectionToken as dD, isAICollection as da, parseMongoWhere as db, parseSqlWhere as dc, type CollectionTokenPayload as dd, DEFAULT_SESSION_EXPIRY as de, type DyrectedObservabilityRuntime as df, type RequestBodyCapture as dg, type RequestTraceContext as dh, type ResolvedObservabilityConfig as di, attachRequestMetrics as dj, bindObservabilityRuntime as dk, buildRequestLogger as dl, captureRequestBody as dm, createDyrectedApp as dn, createObservabilityRuntime as dp, createRequestSpan as dq, decodeCollectionToken as dr, endRequestSpan as ds, getConfigLogger as dt, getObservabilityRuntime as du, getRequestLogger as dv, redactBody as dw, redactHeaders as dx, renderPrometheusMetrics as dy, resolveObservabilityConfig as dz, type BaseDocument as e, type DetailActionOptions as f, type DetailAction as g, type DetailComputedOptions as h, type ComputedHandler as i, type DetailComputed as j, type DetailCustomOptions as k, type DetailCustom as l, type DetailDividerOptions as m, type DetailDivider as n, type DisplayFieldOptions as o, type DetailField as p, type DetailItem as q, type DetailGridOptions as r, type DetailGrid as s, type DetailRepeatOptions as t, type DetailRepeat as u, type DetailSectionOptions as v, type DetailSection as w, type DetailTabOptions as x, type DetailTab as y, type DetailTabsOptions as z };
package/dist/index.cjs CHANGED
@@ -1789,9 +1789,12 @@ __export(index_exports, {
1789
1789
  AI_CHUNKS_COLLECTION: () => AI_CHUNKS_COLLECTION,
1790
1790
  AI_MESSAGES_COLLECTION: () => AI_MESSAGES_COLLECTION,
1791
1791
  AI_THREADS_COLLECTION: () => AI_THREADS_COLLECTION,
1792
+ BASE62_ALPHABET: () => BASE62_ALPHABET,
1792
1793
  BUILTIN_JEXL_HELPERS: () => BUILTIN_JEXL_HELPERS,
1794
+ CROCKFORD_BASE32: () => CROCKFORD_BASE32,
1793
1795
  ConfigValidationError: () => ConfigValidationError,
1794
1796
  ConflictError: () => ConflictError,
1797
+ DuplicateKeyError: () => DuplicateKeyError,
1795
1798
  DyrectedAIError: () => DyrectedAIError,
1796
1799
  DyrectedError: () => DyrectedError,
1797
1800
  FieldConditionBuilder: () => FieldConditionBuilder,
@@ -1799,6 +1802,7 @@ __export(index_exports, {
1799
1802
  LIFECYCLE_EVENTS_COLLECTION: () => LIFECYCLE_EVENTS_COLLECTION,
1800
1803
  LIFECYCLE_EVENT_NAMES: () => LIFECYCLE_EVENT_NAMES,
1801
1804
  MatchBuilder: () => MatchBuilder,
1805
+ NANOID_ALPHABET: () => NANOID_ALPHABET,
1802
1806
  NON_NEGOTIABLE_CREDENTIAL_FIELDS: () => NON_NEGOTIABLE_CREDENTIAL_FIELDS,
1803
1807
  NotFoundError: () => NotFoundError,
1804
1808
  PII_REGEX_PATTERNS: () => PII_REGEX_PATTERNS,
@@ -1894,6 +1898,8 @@ __export(index_exports, {
1894
1898
  formatDate: () => formatDate,
1895
1899
  formatJexlValue: () => formatJexlValue,
1896
1900
  generateDefaultDetailSchema: () => generateDefaultDetailSchema,
1901
+ generateDocumentId: () => generateDocumentId,
1902
+ generateId: () => generateId,
1897
1903
  generateOpenApi: () => generateOpenApi,
1898
1904
  get: () => get,
1899
1905
  getAdminAuthCollection: () => getAdminAuthCollection,
@@ -1920,6 +1926,7 @@ __export(index_exports, {
1920
1926
  materializeWorkflowDocument: () => materializeWorkflowDocument,
1921
1927
  max: () => max,
1922
1928
  min: () => min,
1929
+ nanoid: () => nanoid,
1923
1930
  normalizeConfig: () => normalizeConfig,
1924
1931
  normalizeDetailItem: () => normalizeDetailItem,
1925
1932
  now: () => now,
@@ -1928,6 +1935,7 @@ __export(index_exports, {
1928
1935
  parseSort: () => parseSort,
1929
1936
  parseSqlWhere: () => parseSqlWhere,
1930
1937
  pow: () => pow,
1938
+ prefixedId: () => prefixedId,
1931
1939
  publishedStateName: () => publishedStateName,
1932
1940
  publishingWorkflow: () => publishingWorkflow,
1933
1941
  readingTime: () => readingTime,
@@ -1935,6 +1943,7 @@ __export(index_exports, {
1935
1943
  replace: () => replace,
1936
1944
  resolveAdminAuthCollection: () => resolveAdminAuthCollection,
1937
1945
  resolveAuthorizedSiteId: () => resolveAuthorizedSiteId,
1946
+ resolvePrefix: () => resolvePrefix,
1938
1947
  round: () => round,
1939
1948
  runCollectionHooks: () => runCollectionHooks,
1940
1949
  sanitizeDocForAI: () => sanitizeDocForAI,
@@ -1948,8 +1957,10 @@ __export(index_exports, {
1948
1957
  transitionWorkflow: () => transitionWorkflow,
1949
1958
  trim: () => trim,
1950
1959
  truncate: () => truncate,
1960
+ ulid: () => ulid,
1951
1961
  unique: () => unique,
1952
1962
  upper: () => upper,
1963
+ uuid: () => uuid,
1953
1964
  validateAdminConditionExpression: () => validateAdminConditionExpression,
1954
1965
  validateDeclarativeAccessExpression: () => validateDeclarativeAccessExpression,
1955
1966
  validateDeclarativeHookExpression: () => validateDeclarativeHookExpression,
@@ -3549,6 +3560,134 @@ function assertValidDeclarativeAccessInConfig(config, source = "config") {
3549
3560
  throw new ConfigValidationError(source, diagnostics);
3550
3561
  }
3551
3562
 
3563
+ // src/utils/id.ts
3564
+ var import_node_crypto = require("crypto");
3565
+ var NANOID_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";
3566
+ var BASE62_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
3567
+ var CROCKFORD_BASE32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
3568
+ var COMMON_SLUG_PREFIXES = {
3569
+ users: "usr",
3570
+ members: "mem",
3571
+ accounts: "acc",
3572
+ applications: "app",
3573
+ customers: "cus",
3574
+ products: "prd",
3575
+ orders: "ord",
3576
+ reports: "rpt",
3577
+ sessions: "ses",
3578
+ transactions: "txn",
3579
+ wallets: "wal",
3580
+ media: "med",
3581
+ files: "fil",
3582
+ posts: "post",
3583
+ pages: "page",
3584
+ tags: "tag",
3585
+ categories: "cat",
3586
+ comments: "com"
3587
+ };
3588
+ function nanoid(size = 21, alphabet = NANOID_ALPHABET) {
3589
+ const mask = (2 << 31 - Math.clz32(alphabet.length - 1 | 1)) - 1;
3590
+ const step = Math.ceil(1.6 * mask * size / alphabet.length);
3591
+ let id = "";
3592
+ while (true) {
3593
+ const bytes = (0, import_node_crypto.randomBytes)(step);
3594
+ for (let i = 0; i < step; i++) {
3595
+ const byte = bytes[i] & mask;
3596
+ if (alphabet[byte]) {
3597
+ id += alphabet[byte];
3598
+ if (id.length === size) return id;
3599
+ }
3600
+ }
3601
+ }
3602
+ }
3603
+ function encodeUlidTime(now2, len = 10) {
3604
+ let str = "";
3605
+ let time = Math.floor(now2);
3606
+ for (let i = len - 1; i >= 0; i--) {
3607
+ const mod = time % 32;
3608
+ str = CROCKFORD_BASE32[mod] + str;
3609
+ time = (time - mod) / 32;
3610
+ }
3611
+ return str;
3612
+ }
3613
+ function encodeUlidRandom(bytes) {
3614
+ let str = "";
3615
+ let bitBuffer = 0;
3616
+ let bitsInBuffer = 0;
3617
+ for (let i = 0; i < bytes.length; i++) {
3618
+ bitBuffer = bitBuffer << 8 | bytes[i];
3619
+ bitsInBuffer += 8;
3620
+ while (bitsInBuffer >= 5) {
3621
+ bitsInBuffer -= 5;
3622
+ const index = bitBuffer >> bitsInBuffer & 31;
3623
+ str += CROCKFORD_BASE32[index];
3624
+ }
3625
+ }
3626
+ return str;
3627
+ }
3628
+ function ulid(seedTime = Date.now()) {
3629
+ const timePart = encodeUlidTime(seedTime);
3630
+ const randPart = encodeUlidRandom((0, import_node_crypto.randomBytes)(10));
3631
+ return timePart + randPart;
3632
+ }
3633
+ function uuid() {
3634
+ return (0, import_node_crypto.randomUUID)();
3635
+ }
3636
+ function resolvePrefix(slug, explicitPrefix) {
3637
+ if (explicitPrefix && typeof explicitPrefix === "string" && explicitPrefix.trim().length > 0) {
3638
+ const cleaned = explicitPrefix.trim().toLowerCase().replace(/[^a-z0-9_]/g, "");
3639
+ if (cleaned.length > 0) return cleaned;
3640
+ }
3641
+ if (!slug || typeof slug !== "string") return "col";
3642
+ const s = slug.trim().toLowerCase();
3643
+ if (COMMON_SLUG_PREFIXES[s]) return COMMON_SLUG_PREFIXES[s];
3644
+ const pieces = s.split(/[-_]/).filter(Boolean);
3645
+ if (pieces.length > 1 && pieces[0].length >= 2) {
3646
+ const first2 = pieces[0].replace(/[^a-z0-9]/g, "");
3647
+ if (first2.length >= 2) return first2.slice(0, 4);
3648
+ }
3649
+ const cleanWord = s.replace(/[^a-z0-9]/g, "");
3650
+ if (cleanWord.length <= 4) return cleanWord || "col";
3651
+ return cleanWord.slice(0, 3) || "col";
3652
+ }
3653
+ function prefixedId(prefix = "col", size = 16) {
3654
+ const cleanPrefix = (prefix || "col").toLowerCase().replace(/[^a-z0-9_]/g, "") || "col";
3655
+ return `${cleanPrefix}_${nanoid(size, BASE62_ALPHABET)}`;
3656
+ }
3657
+ function generateId(options) {
3658
+ if (typeof options === "string") {
3659
+ return prefixedId(resolvePrefix(options));
3660
+ }
3661
+ const opts = options || {};
3662
+ const type = opts.type || "prefixed-nanoid";
3663
+ switch (type) {
3664
+ case "uuid":
3665
+ return uuid();
3666
+ case "ulid":
3667
+ return ulid();
3668
+ case "nanoid":
3669
+ return nanoid(opts.size || 21);
3670
+ case "prefixed-nanoid":
3671
+ default:
3672
+ return prefixedId(opts.prefix || "col", opts.size || 16);
3673
+ }
3674
+ }
3675
+ function generateDocumentId(collectionOrSlug) {
3676
+ if (!collectionOrSlug) {
3677
+ return prefixedId("col");
3678
+ }
3679
+ if (typeof collectionOrSlug === "string") {
3680
+ const prefix2 = resolvePrefix(collectionOrSlug);
3681
+ return prefixedId(prefix2);
3682
+ }
3683
+ if (typeof collectionOrSlug.idGenerator === "function") {
3684
+ return collectionOrSlug.idGenerator(collectionOrSlug.slug);
3685
+ }
3686
+ const type = collectionOrSlug.idType || "prefixed-nanoid";
3687
+ const prefix = resolvePrefix(collectionOrSlug.slug, collectionOrSlug.idPrefix);
3688
+ return generateId({ prefix, type });
3689
+ }
3690
+
3552
3691
  // src/utils/config.ts
3553
3692
  var AUDIT_COLLECTION_SLUG = "__audit";
3554
3693
  var SYSTEM_FIELDS = [
@@ -3870,11 +4009,31 @@ function normalizeConfig(config) {
3870
4009
  }
3871
4010
  const updatedFieldNames = new Set(fields.map((f) => f.name));
3872
4011
  const fieldsToInject = SYSTEM_FIELDS.filter((f) => !updatedFieldNames.has(f.name));
4012
+ const indexedFieldNames = /* @__PURE__ */ new Set();
4013
+ if (col.indexes) {
4014
+ for (const idx of col.indexes) {
4015
+ if (Array.isArray(idx.fields)) {
4016
+ for (const f of idx.fields) {
4017
+ indexedFieldNames.add(f);
4018
+ }
4019
+ }
4020
+ }
4021
+ }
4022
+ const allFields = [...fields, ...fieldsToInject].map((field) => {
4023
+ if (field.unique || field.name && indexedFieldNames.has(field.name)) {
4024
+ return { ...field, promoted: true };
4025
+ }
4026
+ return field;
4027
+ });
3873
4028
  const workflow = col.workflow || (col.drafts ? simplePublishingWorkflow() : void 0);
4029
+ const idPrefix = col.idPrefix || resolvePrefix(col.slug);
4030
+ const idType = col.idType || "prefixed-nanoid";
3874
4031
  return {
3875
4032
  ...col,
4033
+ idPrefix,
4034
+ idType,
3876
4035
  workflow,
3877
- fields: [...fields, ...fieldsToInject]
4036
+ fields: allFields
3878
4037
  };
3879
4038
  });
3880
4039
  const hasAuditCollection = normalizedCollections.some((col) => col.slug === AUDIT_COLLECTION_SLUG);
@@ -3934,6 +4093,17 @@ var ConflictError = class _ConflictError extends DyrectedError {
3934
4093
  Object.setPrototypeOf(this, _ConflictError.prototype);
3935
4094
  }
3936
4095
  };
4096
+ var DuplicateKeyError = class _DuplicateKeyError extends ConflictError {
4097
+ field;
4098
+ value;
4099
+ constructor(message, options) {
4100
+ super(message);
4101
+ this.name = "DuplicateKeyError";
4102
+ this.field = options?.field;
4103
+ this.value = options?.value;
4104
+ Object.setPrototypeOf(this, _DuplicateKeyError.prototype);
4105
+ }
4106
+ };
3937
4107
 
3938
4108
  // src/utils/parse-where.ts
3939
4109
  function assertNever(op, context) {
@@ -6619,9 +6789,12 @@ function defineTab(args) {
6619
6789
  AI_CHUNKS_COLLECTION,
6620
6790
  AI_MESSAGES_COLLECTION,
6621
6791
  AI_THREADS_COLLECTION,
6792
+ BASE62_ALPHABET,
6622
6793
  BUILTIN_JEXL_HELPERS,
6794
+ CROCKFORD_BASE32,
6623
6795
  ConfigValidationError,
6624
6796
  ConflictError,
6797
+ DuplicateKeyError,
6625
6798
  DyrectedAIError,
6626
6799
  DyrectedError,
6627
6800
  FieldConditionBuilder,
@@ -6629,6 +6802,7 @@ function defineTab(args) {
6629
6802
  LIFECYCLE_EVENTS_COLLECTION,
6630
6803
  LIFECYCLE_EVENT_NAMES,
6631
6804
  MatchBuilder,
6805
+ NANOID_ALPHABET,
6632
6806
  NON_NEGOTIABLE_CREDENTIAL_FIELDS,
6633
6807
  NotFoundError,
6634
6808
  PII_REGEX_PATTERNS,
@@ -6724,6 +6898,8 @@ function defineTab(args) {
6724
6898
  formatDate,
6725
6899
  formatJexlValue,
6726
6900
  generateDefaultDetailSchema,
6901
+ generateDocumentId,
6902
+ generateId,
6727
6903
  generateOpenApi,
6728
6904
  get,
6729
6905
  getAdminAuthCollection,
@@ -6750,6 +6926,7 @@ function defineTab(args) {
6750
6926
  materializeWorkflowDocument,
6751
6927
  max,
6752
6928
  min,
6929
+ nanoid,
6753
6930
  normalizeConfig,
6754
6931
  normalizeDetailItem,
6755
6932
  now,
@@ -6758,6 +6935,7 @@ function defineTab(args) {
6758
6935
  parseSort,
6759
6936
  parseSqlWhere,
6760
6937
  pow,
6938
+ prefixedId,
6761
6939
  publishedStateName,
6762
6940
  publishingWorkflow,
6763
6941
  readingTime,
@@ -6765,6 +6943,7 @@ function defineTab(args) {
6765
6943
  replace,
6766
6944
  resolveAdminAuthCollection,
6767
6945
  resolveAuthorizedSiteId,
6946
+ resolvePrefix,
6768
6947
  round,
6769
6948
  runCollectionHooks,
6770
6949
  sanitizeDocForAI,
@@ -6778,8 +6957,10 @@ function defineTab(args) {
6778
6957
  transitionWorkflow,
6779
6958
  trim,
6780
6959
  truncate,
6960
+ ulid,
6781
6961
  unique,
6782
6962
  upper,
6963
+ uuid,
6783
6964
  validateAdminConditionExpression,
6784
6965
  validateDeclarativeAccessExpression,
6785
6966
  validateDeclarativeHookExpression,