@xnetjs/data 0.0.2 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +112 -0
  2. package/dist/account-MWNCH4GJ.js +12 -0
  3. package/dist/account-ledger-R2GAFJL6.js +38 -0
  4. package/dist/auth/index.d.ts +420 -0
  5. package/dist/auth/index.js +102 -0
  6. package/dist/budget-NN7P35XP.js +12 -0
  7. package/dist/canvas-6WYBNH53.js +10 -0
  8. package/dist/channel-AT3LQF4A.js +12 -0
  9. package/dist/chat-message-DSVO72B3.js +10 -0
  10. package/dist/chunk-2ZNJWIQG.js +84 -0
  11. package/dist/chunk-3J3HILXO.js +46 -0
  12. package/dist/chunk-3RUDVTMH.js +5543 -0
  13. package/dist/chunk-4EYKGTSQ.js +49 -0
  14. package/dist/chunk-53F4PRNC.js +32 -0
  15. package/dist/chunk-5EXHNXPL.js +48 -0
  16. package/dist/{chunk-BQBPA5HS.js → chunk-5HC5NO57.js} +16 -2
  17. package/dist/chunk-6KLGA6IR.js +47 -0
  18. package/dist/chunk-6OMG4I7M.js +41 -0
  19. package/dist/chunk-7PDRDSFH.js +69 -0
  20. package/dist/chunk-BQLQSWKZ.js +232 -0
  21. package/dist/chunk-BY5O6LNC.js +380 -0
  22. package/dist/chunk-DCTRX6II.js +40 -0
  23. package/dist/{chunk-VYR5GPJP.js → chunk-DWEXKD6E.js} +9 -3
  24. package/dist/chunk-EBNMV2VO.js +896 -0
  25. package/dist/chunk-FVEACSKE.js +102 -0
  26. package/dist/chunk-GU6THOAB.js +45 -0
  27. package/dist/chunk-H4GA4BBK.js +75 -0
  28. package/dist/chunk-IJ44LR7N.js +76 -0
  29. package/dist/chunk-J4ANIXIV.js +402 -0
  30. package/dist/chunk-JDFNMFOZ.js +45 -0
  31. package/dist/chunk-K7DOZWWT.js +1811 -0
  32. package/dist/chunk-KQAT4XBL.js +49 -0
  33. package/dist/chunk-KQUALW4O.js +183 -0
  34. package/dist/chunk-LYSWLCOI.js +47 -0
  35. package/dist/chunk-MBTUO3ZL.js +65 -0
  36. package/dist/chunk-NI4FHG2K.js +52 -0
  37. package/dist/chunk-OCMSAKWV.js +78 -0
  38. package/dist/chunk-OGJCRNGE.js +57 -0
  39. package/dist/chunk-OPPHF3TF.js +143 -0
  40. package/dist/{chunk-IDMBCRUC.js → chunk-OSAWNZVM.js} +1 -1
  41. package/dist/chunk-PMUQACPY.js +33 -0
  42. package/dist/chunk-PNESGUH5.js +63 -0
  43. package/dist/chunk-Q3IEGH4B.js +51 -0
  44. package/dist/chunk-QJW5LDP4.js +52 -0
  45. package/dist/chunk-QWFTRZQT.js +142 -0
  46. package/dist/{chunk-SZC345Z2.js → chunk-RL64OJJ5.js} +1025 -1110
  47. package/dist/chunk-S5RP5RKY.js +416 -0
  48. package/dist/chunk-S6U6TCMN.js +722 -0
  49. package/dist/chunk-SVNGSZZA.js +69 -0
  50. package/dist/chunk-T5AZAOG5.js +54 -0
  51. package/dist/chunk-TCTZW4A6.js +42 -0
  52. package/dist/chunk-U64CW73O.js +109 -0
  53. package/dist/chunk-UDWKWTAX.js +6526 -0
  54. package/dist/chunk-UQM3G5A2.js +148 -0
  55. package/dist/chunk-VQ7JHB67.js +57 -0
  56. package/dist/chunk-W7EBL7ZU.js +73 -0
  57. package/dist/chunk-WEPK7SZF.js +65 -0
  58. package/dist/chunk-XHEA5UER.js +75 -0
  59. package/dist/chunk-XMSKJ5PV.js +66 -0
  60. package/dist/chunk-XROI44ZP.js +64 -0
  61. package/dist/chunk-Y3S5SRVM.js +45 -0
  62. package/dist/chunk-YEFKQYKA.js +43 -0
  63. package/dist/chunk-YSUIXD2Y.js +105 -0
  64. package/dist/chunk-ZCOFZY5M.js +70 -0
  65. package/dist/chunk-ZLU4Y3O2.js +50 -0
  66. package/dist/chunk-ZPZ7XDA6.js +54 -0
  67. package/dist/chunk-ZZ6TWKGS.js +40 -0
  68. package/dist/clone-C0Jhk2UN.d.ts +2205 -0
  69. package/dist/comment-QSWYAQVS.js +10 -0
  70. package/dist/crm-L5RYAAF3.js +68 -0
  71. package/dist/dashboard-JMKTTRA7.js +10 -0
  72. package/dist/database/index.d.ts +882 -0
  73. package/dist/database/index.js +523 -0
  74. package/dist/database-GIXSPZJW.js +10 -0
  75. package/dist/database-field-3EPAMZUR.js +10 -0
  76. package/dist/database-row-6Q6TRVE4.js +10 -0
  77. package/dist/database-select-option-BBBJFLLH.js +10 -0
  78. package/dist/database-view-5PLSOBI2.js +10 -0
  79. package/dist/experiment-DOVOZ34Y.js +10 -0
  80. package/dist/external-item-P2E5X7BZ.js +14 -0
  81. package/dist/external-reference-7BSFF6SA.js +8 -0
  82. package/dist/feed-2IXHHP6O.js +12 -0
  83. package/dist/feed-item-DPE6LN7I.js +12 -0
  84. package/dist/folder-6KM3KYD5.js +21 -0
  85. package/dist/game-5AK5XWBR.js +50 -0
  86. package/dist/grant-WTQSNT5A.js +8 -0
  87. package/dist/grant-expiration-cleaner-CY6BcmlR.d.ts +249 -0
  88. package/dist/import-batch-IXBJLQPJ.js +12 -0
  89. package/dist/inbox-state-E5NSVOGP.js +12 -0
  90. package/dist/index.d.ts +224 -4548
  91. package/dist/index.js +2252 -4754
  92. package/dist/map-RG5Y3CPC.js +10 -0
  93. package/dist/media-asset-QTCGLIZA.js +8 -0
  94. package/dist/memory-PNRTMBZO.js +12 -0
  95. package/dist/metric-65SVOX5C.js +10 -0
  96. package/dist/milestone-XEO6ZGDG.js +12 -0
  97. package/dist/moderation-FFHETMRB.js +30 -0
  98. package/dist/observation-2Y3QKUXM.js +10 -0
  99. package/dist/page-2V27JGKJ.js +10 -0
  100. package/dist/posting-GBOSZCMZ.js +12 -0
  101. package/dist/profile-BLLDWIDK.js +8 -0
  102. package/dist/project-CQL5LN26.js +10 -0
  103. package/dist/query-ast-C3m6kZYv.d.ts +226 -0
  104. package/dist/reaction-T2DTJBBV.js +10 -0
  105. package/dist/registry-DunPv__d.d.ts +99 -0
  106. package/dist/saved-view-4R2DBCL3.js +10 -0
  107. package/dist/schema/index.d.ts +6489 -0
  108. package/dist/schema/index.js +677 -0
  109. package/dist/schema-extension-LNRF2YRD.js +18 -0
  110. package/dist/space-IJU24PBH.js +42 -0
  111. package/dist/space-membership-DEUMM7NV.js +14 -0
  112. package/dist/store/index.d.ts +518 -0
  113. package/dist/store/index.js +135 -0
  114. package/dist/store-DtIDjk7c.d.ts +355 -0
  115. package/dist/sync/awareness.d.ts +69 -0
  116. package/dist/sync/awareness.js +20 -0
  117. package/dist/system-ILHCZOVO.js +38 -0
  118. package/dist/tag-SKCHM3U5.js +16 -0
  119. package/dist/task-7AOBP7WC.js +16 -0
  120. package/dist/task-view-NUGKELJP.js +10 -0
  121. package/dist/transaction-ZDSEGDIR.js +12 -0
  122. package/dist/transcription-PSCLDAGX.js +12 -0
  123. package/dist/types-S-BJAKyK.d.ts +1576 -0
  124. package/dist/updates.d.ts +44 -0
  125. package/dist/updates.js +16 -0
  126. package/dist/user-widget-RLY2N46A.js +8 -0
  127. package/dist/view-types-DSde-uT_.d.ts +316 -0
  128. package/package.json +32 -9
  129. package/dist/canvas-HSIKIQFK.js +0 -7
  130. package/dist/chunk-2L5ZUGG5.js +0 -53
  131. package/dist/chunk-4MTS5KAQ.js +0 -22
  132. package/dist/chunk-GZHARFKC.js +0 -25
  133. package/dist/chunk-WKIKJTI2.js +0 -45
  134. package/dist/comment-277JD7DV.js +0 -7
  135. package/dist/database-W3KEHLI3.js +0 -7
  136. package/dist/database-row-3O2QSNZN.js +0 -7
  137. package/dist/grant-QVZ454YC.js +0 -7
  138. package/dist/page-O4WTOIEO.js +0 -7
  139. package/dist/task-SEKAYJH7.js +0 -7
package/dist/index.d.ts CHANGED
@@ -1,4598 +1,274 @@
1
- import { DID as DID$1, AuthAction, AuthDecision, AuthTrace, PolicyEvaluator, ContentId, AuthDenyReason, RoleResolver, AuthCheckInput, SerializedAuthorization, AuthorizationDefinition, VectorClock, SignedUpdate } from '@xnetjs/core';
1
+ export { a5 as ApplyNodeBatchInput, a6 as ApplyNodeBatchResult, b1 as AuthGrant, av as ConflictResult, ay as ContentKeyCache, ae as CountNodesOptions, H as CreateNodeOptions, C as CreateNodeStoreOptions, aX as DEFAULT_OFFLINE_POLICY, y as DID, D as DefinedSchema, ab as DeterministicNodeBatchWriteInput, m as DeterministicNodeImportDraft, aV as GRANT_SCHEMA_IRI, G as GetWithMigrationOptions, w as GrantIndex, b0 as GrantInput, aU as GrantRateLimiter, n as ImportDeterministicNodesOptions, o as ImportDeterministicNodesResult, a3 as ImportNodesOptions, I as InferCreateProps, Q as InferNode, K as InferProperties, J as InferPropertyType, W as LensOperation, Z as LensRegistry, L as ListNodesOptions, s as MergeConflict, M as MigratedNodeState, Y as MigrationError, az as MigrationInfo, X as MigrationResult, x as Node, aw as NodeBatchChangeEvent, u as NodeBatchChangeListener, a7 as NodeBatchIndexMode, a8 as NodeBatchNotificationMode, aa as NodeBatchPreflightResult, a9 as NodeBatchSyncMode, p as NodeBatchWriteInput, ac as NodeBatchWritePolicy, q as NodeBatchWriteResult, ad as NodeBatchWriteTimings, r as NodeChange, v as NodeChangeEvent, t as NodeChangeListener, ax as NodeContentCipher, i as NodeId, a0 as NodePayload, ar as NodeQueryCursor, aq as NodeQueryCursorOrderEntry, j as NodeQueryDescriptor, ao as NodeQueryMaterializedViewOptions, as as NodeQueryOptions, N as NodeQueryPageCountMode, ap as NodeQueryPageOptions, au as NodeQueryParityCheckMetadata, at as NodeQueryPlanMetadata, k as NodeQueryResult, am as NodeQuerySearchField, an as NodeQuerySearchFilter, al as NodeQuerySpatialFilter, af as NodeQuerySpatialPoint, ah as NodeQuerySpatialPointFields, ak as NodeQuerySpatialRadius, ag as NodeQuerySpatialRect, ai as NodeQuerySpatialRectFields, aj as NodeQuerySpatialWindow, h as NodeState, g as NodeStorageAdapter, f as NodeStoreOptions, O as OfflineAuthPolicy, P as PropertyBuilder, E as PropertyDefinition, $ as PropertyKey, a1 as PropertyTimestamp, B as PropertyType, a4 as RebuildNodeIndexesOptions, a as Schema, S as SchemaIRI, R as SchemaLens, aR as SchemaLookup, a2 as SetNodeOptions, c as SortDirection, aT as StoreAuth, e as StoreAuthAPI, b2 as StoreAuthError, b3 as StoreAuthErrorCode, a$ as StoreAuthKeyManager, aZ as StoreAuthOptions, a_ as StoreAuthStore, d as SystemOrderField, aO as TEMP_ID_PREFIX, aS as TempIdResolution, T as TransactionOperation, l as TransactionResult, U as UpdateNodeOptions, F as ValidationError, V as ValidationResult, aI as applyNodeQueryDescriptor, A as createNodeId, aA as createNodeQueryDescriptor, aQ as createSchemaLookup, aC as decodeNodeQueryCursor, aB as encodeNodeQueryCursor, aG as filterNodeQueryResults, aJ as getNodeQuerySearchTokens, aW as isGrantActive, z as isNode, aN as isTempId, _ as lensRegistry, aF as matchesNodeQueryDescriptor, aY as mergeOfflinePolicy, aK as nodeQueryDescriptorNeedsBoundedReload, aD as nodeQueryDescriptorToOptions, aP as resolveTempIds, aE as serializeNodeQueryDescriptor, aH as sortNodeQueryResults, aM as withoutNodeQueryMaterializedView, aL as withoutNodeQueryPagination } from './types-S-BJAKyK.js';
2
+ import { FileRef } from './schema/index.js';
3
+ export { ACCOUNT_RECORD_SCHEMA_IRI, ACCOUNT_SCHEMA_IRI, ACHIEVEMENT_SCHEMA_IRI, ACTIVITY_KINDS, ACTIVITY_SCHEMA_IRI, AbuseReport, AbuseReportSchema, Account, AccountClassId, AccountRecord, AccountRecordSchema, AccountSchema, Achievement, AchievementSchema, Activity, ActivityKind, ActivitySchema, AnchorData, AnchorType, Appeal, AppealSchema, BUDGET_SCHEMA_IRI, Budget, BudgetPeriod, BudgetSchema, BuiltInSchemaIRI, CHANNEL_KINDS, CONTACT_LIFECYCLE, CONTACT_SCHEMA_IRI, CRM_NAMESPACE, Canvas, CanvasObjectAnchor, CanvasObjectAnchorPlacement, CanvasPositionAnchor, CanvasSchema, CellAnchor, Channel, ChannelKind, ChannelNotifyTier, ChannelSchema, ChatMessage, ChatMessageSchema, CheckboxOptions, ColumnAnchor, Comment, CommentSchema, CommunityNote, CommunityNoteSchema, Contact, ContactLifecycle, ContactSchema, ContentProvenance, ContentProvenanceSchema, CoreSchemaResolver, CreatedByOptions, CreatedOptions, CrmVisibility, DEAL_CONTACT_ROLES, DEAL_CONTACT_ROLE_SCHEMA_IRI, DEAL_SCHEMA_IRI, DEAL_SOURCES, DEFAULT_CHANNEL_TIER, DEVICE_RECORD_SCHEMA_IRI, Dashboard, DashboardBreakpointId, DashboardLayoutItem, DashboardLayouts, DashboardSchema, DashboardTimeRange, DashboardVariablesState, DashboardWidgetInstance, DashboardWidgetRefresh, Database, DatabaseField, DatabaseFieldSchema, DatabaseRow, DatabaseRowSchema, DatabaseSchema, DatabaseSelectOption, DatabaseSelectOptionSchema, DatabaseView, DatabaseViewSchema, DateOptions, DateRange, DateRangeOptions, Deal, DealContactRole, DealContactRoleKind, DealContactRoleSchema, DealSchema, DealSource, DefineSchemaOptions, DeviceLike, DeviceRecord, DeviceRecordSchema, EXTENSION_FIELD_SCHEMA_IRI, EXTERNAL_ITEM_SCHEMA_IRI, EXTERNAL_ITEM_SOURCES, EXT_PREFIX, EffectiveExtensionField, EmailOptions, Experiment, ExperimentDesign, ExperimentPhase, ExperimentSchema, ExperimentStatus, ExtensionField, ExtensionFieldRecord, ExtensionFieldSchema, ExtensionRecord, ExternalItem, ExternalItemSchema, ExternalReference, ExternalReferenceSchema, FEED_ITEM_SCHEMA_IRI, FEED_SCHEMA_IRI, FOLDER_SCHEMA_IRI, FORECAST_CATEGORIES, Feed, FeedItem, FeedItemSchema, FeedSchema, FileOptions, Folder, FolderLike, FolderSchema, FolderTreeNode, ForecastCategory, GAME_ASSET_FORMATS, GAME_ASSET_MIME_TYPES, GAME_ASSET_SCHEMA_IRI, GAME_ECONOMY_ENTRY_SCHEMA_IRI, GAME_ITEM_SCHEMA_IRI, GAME_NAMESPACE, GAME_SCHEMA_IRIS, GameAsset, GameAssetFormat, GameAssetSchema, GameEconomyEntry, GameEconomyEntrySchema, GameItem, GameItemSchema, GameVisibility, GeoFeature, GeoFeatureCollection, GeoGeometry, GeoPosition, Grant, GrantSchema, IMPORT_BATCH_SCHEMA_IRI, INVENTORY_SCHEMA_IRI, ITEM_RARITIES, ImportBatch, ImportBatchSchema, ImportSource, InboxItemTriage, InboxState, InboxStateSchema, InboxWatermark, Inventory, InventorySchema, ItemRarity, JsonOptions, LINE_ITEM_SCHEMA_IRI, LedgerNodeIntent, LineItem, LineItemSchema, MATCH_RESULTS, MATCH_SESSION_SCHEMA_IRI, MAX_MENTION_DIDS, MAX_TAG_NAME_LENGTH, MEMORY_ITEM_SCHEMA_IRI, MEMORY_KINDS, MILESTONE_SCHEMA_IRI, Map, MapBasemapId, MapLayerGeometry, MapLayerSource, MapLayerSpec, MapLayerStyle, MapSchema, MapViewport, MatchResult, MatchSession, MatchSessionSchema, MediaAsset, MediaAssetSchema, MemoryItem, MemoryItemSchema, MemoryKind, Mention, MessageMentions, MessageRequest, MessageRequestSchema, Metric, MetricKind, MetricPolarity, MetricScheduleId, MetricSchema, Milestone, MilestoneSchema, ModerationLabel, ModerationLabelSchema, MoneyOptions, MoneyValue, MultiSelectOptions, NODE_VISIBILITY, NodeAnchor, NodeVisibility, NoteRating, NoteRatingSchema, NotificationPrefs, NumberOptions, ORGANIZATION_SCHEMA_IRI, ORGANIZATION_SIZES, Observation, ObservationPhase, ObservationSchema, Organization, OrganizationSchema, OrganizationSize, OrphanReason, OrphanResolvers, OrphanStatus, PIPELINE_SCHEMA_IRI, PLAYER_IDENTITY_SCHEMA_IRI, POSTING_SCHEMA_IRI, PRODUCT_KINDS, PRODUCT_SCHEMA_IRI, Page, PageSchema, ParsedSystemNamespaceResource, ParsedTaskShortId, PersonOptions, PhoneOptions, Pipeline, PipelineSchema, PlayerIdentity, PlayerIdentitySchema, PolicyList, PolicyListSchema, PolicySubscription, PolicySubscriptionSchema, Posting, PostingSchema, PresenceAggregator, PresenceAggregatorOptions, PresenceAggregatorStore, PresenceCountBucket, PresenceSummary, PresenceSummaryDescriptor, PresenceSummarySchema, PresenceVisibility, PresenceVisibilityResolver, Product, ProductKind, ProductSchema, Profile, ProfileSchema, Project, ProjectSchema, PublicInteractionPolicy, PublicInteractionPolicySchema, QualitySignal, QualitySignalSchema, RECOVERY_RECORD_SCHEMA_IRI, RELATIONSHIP_KINDS, RELATIONSHIP_SCHEMA_IRI, REVOCATION_RECORD_SCHEMA_IRI, Reaction, ReactionSchema, RecoveryRecord, RecoveryRecordSchema, RelationOptions, Relationship, RelationshipKind, RelationshipSchema, ReviewTask, ReviewTaskSchema, RevocationLike, RevocationRecord, RevocationRecordSchema, RowAnchor, SCHEMA_EXTENSION_SCHEMA_IRI, SIDECAR_PREFIX, SPACE_KINDS, SPACE_MEMBERSHIP_SCHEMA_IRI, SPACE_ROLES, SPACE_SCHEMA_IRI, SPACE_VISIBILITY, STAGE_SCHEMA_IRI, SYSTEM_NAMESPACE_KINDS, SYSTEM_SCHEMA_BASE_IRIS, SYSTEM_SCHEMA_IRIS, SavedView, SavedViewSchema, SchemaAuthorityResolution, SchemaAuthorityResolutionKind, SchemaAuthorityResolutionOptions, SchemaCompatibility, SchemaCompatibilityMode, SchemaCompatibilitySchema, SchemaDefinition, SchemaDefinitionSchema, SchemaDefinitionSigningInput, SchemaDefinitionStatus, SchemaExtension, SchemaExtensionSchema, SelectOption, SelectOptions, SidecarOverlay, Space, SpaceKind, SpaceLike, SpaceMembership, SpaceMembershipSchema, SpaceRole, SpaceSchema, SpaceTreeNode, SpaceVisibility, Stage, StageSchema, SyncPolicy, SyncPolicySchema, SyncPolicyStatus, SystemFederationErrorCode, SystemNamespaceKind, SystemSchemaDefinitionRecord, SystemSchemaIndex, SystemSchemaIndexDiagnostic, SystemSchemaIndexOptions, SystemSchemaIndexStore, TAG_SCHEMA_IRI, TASK_SHORT_ID_PATTERN, TASK_STATUS_CATEGORIES, TRANSACTION_SCHEMA_IRI, TRANSCRIPTION_SCHEMA_IRI, Tag, TagSchema, Task, TaskSchema, TaskShortIdBlock, TaskStatusCategory, TaskStatusId, TaskView, TaskViewSchema, TextAnchor, TextOptions, Transaction, TransactionSchema, TransactionStatus, Transcription, TranscriptionSchema, TranscriptionSourceId, UpdatedOptions, UrlOptions, UserWidget, UserWidgetConfigField, UserWidgetSchema, UserWidgetSize, ValidateSchemaDefinitionNodeOptions, accountRecordId, accountState, addDefault, admitDeviceRecord, bucketPresenceCount, buildEffectiveSchema, buildFolderTree, buildSpaceTree, buildSystemNamespace, buildSystemNodeId, builtInSchemas, canManageSpace, canModifyColumn, checkOrphanStatus, checkbox, compareSpaceRoles, composeLens, computeSchemaDefinitionContentHash, convert, copy, createAccountRecord, createNodeGraphSchemaResolver, createOperations, createSchemaDefinitionSigningPayload, created, createdBy, crmSchemas, date, dateRange, decodeAnchor, defineSchema, deviceRecipientExpander, deviceRecordId, effectiveSpaceRole, email, encodeAnchor, extKey, extractMentions, file, filterOrphanedComments, findLockedColumns, flattenFolderTree, flattenSpaceTree, folderAncestorIds, folderPathIds, formatTaskShortId, gameSchemas, getMentionedUsers, getPresenceNoisePolicy, getTaskStatusCategory, identity, inboxStateNodeId, isCanvasObjectAnchor, isCanvasPositionAnchor, isCellAnchor, isColumnAnchor, isCompletedTaskStatus, isDeviceAuthorized, isExtKey, isMoneyValue, isNodeAnchor, isRowAnchor, isSchemaDefinitionNode, isSpaceRole, isSystemNamespaceResource, isSystemSchemaIri, isTextAnchor, isValidMentions, isValidTagName, json, loadExtensionFields, lockedPropertyKeys, mentionsInclude, merge, mergeSidecarsIntoRow, money, multiSelect, nextEpoch, normalizeMentions, normalizeTagName, number, parseExtKey, parseSystemNamespaceResource, parseTaskShortId, person, phone, promoteOverlay, recoveryRecordId, relation, remove, rename, resolveActiveDevices, resolveEffectiveSchema, resolveSchemaAuthority, revocationRecordId, revokeDeviceRecord, revokeSubjectRecord, revokedSubjects, schemaExtensionId, select, selectExtensionFields, shortIdsFromBlock, sidecarId, sidecarOverlayKeys, spaceAncestorIds, spaceMembershipId, spacePathIds, spaceRoleGrantActions, spaceRoleToShareRole, summarizePresenceNodes, taskBranchName, text, transform, updated, url, validateSchemaDefinitionNode, when, wouldCreateFolderCycle, wouldCreateSpaceCycle } from './schema/index.js';
4
+ export { S as SchemaRegistry, s as schemaRegistry } from './registry-DunPv__d.js';
5
+ export { SignUpdateOptions, applySignedUpdate, captureUpdate, getMissingUpdates, mergeDocuments, signUpdate, verifyUpdate } from './updates.js';
2
6
  import * as Y from 'yjs';
3
- import { Doc } from 'yjs';
4
- export { Array as YArray, Doc as YDoc, Map as YMap, Text as YText, XmlFragment as YXmlFragment } from 'yjs';
5
- import { Awareness } from 'y-protocols/awareness';
6
- import { PublicKeyResolver } from '@xnetjs/crypto';
7
- import { Change, LamportTimestamp } from '@xnetjs/sync';
8
- import { SQLiteAdapter } from '@xnetjs/sqlite';
7
+ export { Array as YArray, Doc as YDoc, Map as YMap, Text as YText, XmlElement as YXmlElement, XmlFragment as YXmlFragment, XmlText as YXmlText } from 'yjs';
8
+ export { CursorPosition, SelectionRange, UserPresence, clearLocalPresence, createAwareness, generateUserColor, getAllPresences, getLocalClientId, getRemotePresences, onPresenceChange, setLocalPresence } from './sync/awareness.js';
9
+ export { G as QUERY_AST_VERSION, r as QueryAST, n as QueryASTAggregate, A as QueryASTAggregateExecution, m as QueryASTAggregateFunction, y as QueryASTAggregateGroup, x as QueryASTAggregatePlan, z as QueryASTAggregateResult, d as QueryASTComparisonPredicate, e as QueryASTCompoundPredicate, a as QueryASTField, l as QueryASTIncludes, p as QueryASTNodeQuery, s as QueryASTNodeQueryOptions, f as QueryASTNotPredicate, c as QueryASTOperator, h as QueryASTOrderBy, i as QueryASTPage, B as QueryASTPlannerGate, g as QueryASTPredicate, q as QueryASTQuerySet, o as QueryASTQuerySetAggregate, j as QueryASTRelationDirection, k as QueryASTRelationInclude, t as QueryASTRelationIncludeOptions, w as QueryASTRelationIndexRequirement, b as QueryASTSchemaInput, u as QueryASTValidationError, v as QueryASTValidationResult, Q as QueryASTVersion, S as SavedViewDescriptor, F as SavedViewFeedDensity, E as SavedViewFeedLayout, C as SavedViewPresentationHint, D as SavedViewPresentationHintMode, V as and, a3 as avg, N as between, P as contains, a0 as count, a1 as countDistinct, a9 as dashboardQuerySet, Z as defineNodeQueryAST, a8 as defineQuerySetAST, ab as defineSavedViewDescriptor, H as eq, aj as evaluateQueryASTPlannerGate, af as executeQueryASTLoadedAggregates, ag as filterQueryASTLoadedRows, _ as follow, $ as from, ah as getQueryASTRelationIndexRequirements, a6 as groupBy, J as gt, K as gte, a7 as having, O as includesAny, U as isNotNull, T as isNull, L as lt, M as lte, ai as matchesQueryASTLoadedRow, a5 as max, a4 as min, I as neq, X as not, W as or, ae as planQueryASTAggregates, Y as queryOperators, aa as querySetCount, R as startsWith, a2 as sum, ac as validateQueryAST, ad as validateSavedViewDescriptor } from './query-ast-C3m6kZYv.js';
10
+ export { N as NodeStore } from './store-DtIDjk7c.js';
11
+ export { MemoryNodeStorageAdapter, PermissionError, SQLiteAdaptiveIndexingOptions, SQLiteNodeStorageAdapter, SQLiteNodeStorageAdapterOptions, SQLiteQueryVerificationOptions, createNodeStorageAdapter } from './store/index.js';
12
+ export { A as ActionPermission, b as DecisionCache, D as DefaultPolicyEvaluator, a as DefaultRoleResolver, G as GrantExpirationCleaner, H as HubPolicy, P as PermissionMatrix, R as RoleSummary, c as buildPermissionMatrix, d as describeRoleResolver, h as hubActionsForSpaceRole, s as schemaToHubPolicy } from './grant-expiration-cleaner-CY6BcmlR.js';
13
+ import { ContentId } from '@xnetjs/core';
9
14
  import { ChunkManager } from '@xnetjs/storage';
10
-
11
- /**
12
- * Node - The universal container type for all data in xNet.
13
- *
14
- * A Node has only 4 universal fields. Everything else is defined by its schema.
15
- */
16
- /**
17
- * Schema IRI - globally unique identifier for a schema.
18
- * Format: xnet://<authority>/<name> or xnet://<authority>/<name>@<version>
19
- *
20
- * Examples:
21
- * - xnet://xnet.fyi/Page (unversioned, treated as @1.0.0)
22
- * - xnet://xnet.fyi/Task@1.0.0 (explicit version)
23
- * - xnet://xnet.fyi/Task@2.0.0 (newer version)
24
- * - xnet://acme-corp.com/Project@1.0.0 (organization schema)
25
- * - xnet://did:key:z6Mk.../Recipe@1.0.0 (personal schema)
26
- */
27
- type SchemaIRI = `xnet://${string}/${string}`;
28
- /**
29
- * Parsed schema IRI components.
30
- */
31
- interface ParsedSchemaIRI {
32
- /** Full IRI including version */
33
- iri: SchemaIRI;
34
- /** Base IRI without version (e.g., xnet://xnet.fyi/Task) */
35
- baseIRI: SchemaIRI;
36
- /** Namespace (e.g., xnet://xnet.fyi/) */
37
- namespace: string;
38
- /** Schema name (e.g., Task) */
39
- name: string;
40
- /** Version (e.g., 1.0.0) - defaults to 1.0.0 if not present */
41
- version: string;
42
- /** Whether version was explicitly specified */
43
- hasExplicitVersion: boolean;
44
- }
45
- /**
46
- * DID - Decentralized Identifier for user identity.
47
- */
48
- type DID = `did:key:${string}`;
49
- /**
50
- * The minimal universal Node interface.
51
- *
52
- * Only 4 fields are universal - everything else is schema-defined:
53
- * - id: Unique identifier
54
- * - schemaId: What type of node (IRI)
55
- * - createdAt: When created (for sync/attribution)
56
- * - createdBy: Who created it (for sync/attribution)
57
- */
58
- interface Node {
59
- /** Unique identifier for this node */
15
+ export { a as CELL_PREFIX, D as CellDateRange, F as CellFileRef, C as CellValue, d2 as CloneSchemaOptions, d3 as CloneSchemaResult, d4 as CloneSourceData, aY as ConvertContext, aZ as ConvertedCell, cY as CreateDatabaseSchemaResolverOptions, ag as CreateExtensionFieldOptions, a0 as CreateFieldOptions, h as CreateRowOptions, a2 as CreateSelectOptionOptions, ao as CreateViewOptions, bz as CsvExportOptions, bk as CsvParseOptions, cN as DATABASE_SCHEMA_NAMESPACE, cO as DATABASE_SCHEMA_PREFIX, aH as DEFAULT_DATABASE_SCHEMA_VERSION, aV as DatabaseDocumentModel, k as DatabaseRowNode, cQ as DatabaseSchemaMetadata, cX as DocFetcher, af as EnsureExtensionOptions, by as ExportRow, bC as ExportedColumn, bB as ExportedJSON, O as FIELD_TYPES, L as FieldConfig, N as FieldNode, K as FieldType, cf as FilterableRow, b6 as FormulaRow, b4 as FormulaService, b7 as FormulaValidationResult, ct as GroupAggregates, cr as GroupConfig, cq as GroupableRow, bm as InferredColumn, bA as JsonExportOptions, bn as JsonParseOptions, M as MAX_KEY_LENGTH, cP as MAX_VERSION_HISTORY, c4 as OPERATORS_BY_TYPE, c5 as OPERATOR_LABELS, bj as ParsedCSV, bl as ParsedJSON, cB as QueryOptions, cC as QueryResult, Q as QueryRowsOptions, j as QueryRowsResult, cA as QueryableRow, R as RICHTEXT_PREFIX, b3 as RollupContext, b2 as RollupRow, cs as RowGroup, P as SELECT_COLORS, cS as SchemaVersionEntry, S as SelectOptionNode, aG as SetupDatabaseResult, cl as SortableRow, cR as StoredColumn, a1 as UpdateFieldOptions, ap as UpdateViewOptions, cT as VersionBumpType, an as ViewNode, aP as addDefaultTableView, aO as addDefaultTitleColumn, cj as addOrToggleSort, bW as addViewSort, a_ as aggregate, V as autoColor, b0 as batchComputeRollups, cJ as buildDatabaseSchema, aJ as buildSchemaFromFields, cD as buildSchemaIRI, cH as bumpSchemaVersion, c as cellKey, aX as cellValueToText, s as checkNeedsRebalancing, bU as clearViewFilters, bY as clearViewSorts, c_ as cloneColumns, c$ as cloneSampleRows, cZ as cloneSchema, cp as collapseAllGroups, b as columnIdFromKey, cd as combineFiltersAnd, ce as combineFiltersOr, y as compareSortKeys, a$ as computeRollup, aW as convertCellValue, cc as createAnyOfFilter, bH as createColumn, br as createCsvBlob, cU as createDatabaseSchemaResolver, cb as createEqualsFilter, ac as createExtensionField, a6 as createField, cv as createFilterQuery, b5 as createFormulaService, cI as createInitialSchemaMetadata, bw as createJsonBlob, aL as createNodeDatabaseSchemaResolver, cx as createPaginatedQuery, l as createRow, aj as createSelectOption, ch as createSort, cw as createSortQuery, cK as createVersionEntry, bP as createView, as as createViewNode, bJ as deleteColumn, ae as deleteExtensionField, a8 as deleteField, aT as deleteMeta, I as deleteRichTextCell, n as deleteRow, al as deleteSelectOption, bR as deleteView, au as deleteViewNode, bs as downloadCsv, bx as downloadJson, bL as duplicateColumn, aa as duplicateField, bS as duplicateView, av as duplicateViewNode, aE as effectiveFieldSortKey, ab as ensureSchemaExtension, bp as escapeCSV, cu as executeQuery, co as expandAllGroups, bo as exportToCsv, bt as exportToJson, bu as exportToJsonArray, bv as exportToNdjson, cV as extractSchemaFromDoc, aI as fieldsToStoredColumns, ca as filterRows, cy as flattenGroups, bq as formatValue, f as fromCellProperties, d0 as generateColumnIdMap, v as generateSortKey, w as generateSortKeyWithJitter, bE as getColumn, bF as getColumnIndex, bD as getColumns, aU as getDatabaseDocumentModel, aK as getDatabaseSchemaIRI, ai as getDatabaseSelectOptions, a4 as getField, a3 as getFields, aR as getMeta, c8 as getOperatorLabel, c6 as getOperatorsForType, B as getRichTextCell, H as getRichTextColumnIds, J as getRichTextPlainText, o as getRow, cW as getSchemaIRIFromDoc, ah as getSelectOptions, bG as getTitleColumn, a5 as getTitleField, cz as getTotalFromGroups, cM as getVersionBumpType, bN as getView, bO as getViewByType, ar as getViewNode, aq as getViewNodes, bM as getViews, cm as groupRows, ba as guessColumnType, G as hasRichTextColumns, E as hasRichTextContent, c1 as hideColumn, bd as inferColumnTypes, bf as inferColumnsFromRows, bg as inferTypeFromValues, aM as initializeDatabaseDoc, Y as isAutoFieldType, d as isCellDateRange, e as isCellFileRef, i as isCellKey, g as isCellValue, X as isComputedFieldType, aN as isDatabaseDocInitialized, cF as isDatabaseSchemaIRI, T as isFieldType, W as isNodeStoreFieldType, U as isSelectColor, c7 as isValidOperator, x as isValidSortKey, Z as isYDocFieldType, a9 as moveField, p as moveRow, am as moveSelectOption, aw as moveView, A as needsRebalancing, c9 as operatorRequiresValue, b8 as parseCSV, b9 as parseCSVLine, cE as parseDatabaseSchemaIRI, be as parseJSON, bc as parseRow, bb as parseValue, cG as parseVersion, cL as pruneVersionHistory, q as queryRows, r as rebalanceDatabase, z as rebalanceSortKeys, d1 as remapViewColumnIds, ck as removeSort, bX as removeViewSort, ad as renameExtensionField, bK as reorderColumn, c2 as reorderViewColumns, c3 as setColumnWidth, aB as setFieldHidden, aS as setMeta, aD as setViewFieldOrder, aC as setViewFieldWidth, bT as setViewFilters, bZ as setViewGroupBy, ax as setViewNodeFilters, az as setViewNodeGroupBy, ay as setViewNodeSorts, bV as setViewSorts, b$ as setVisibleColumns, aF as setupDatabase, aQ as setupNewDatabase, c0 as showColumn, cg as sortRows, t as toCellProperties, bh as toColumnDefinitions, _ as toFieldNode, $ as toSelectOptionNode, b_ as toggleGroupCollapsed, cn as toggleGroupCollapsedState, ci as toggleSortDirection, aA as toggleViewGroupCollapsed, u as updateCell, m as updateCells, bI as updateColumn, a7 as updateField, ak as updateSelectOption, bQ as updateView, at as updateViewNode, bi as validateJsonData, b1 as validateRollupConfig } from './clone-C0Jhk2UN.js';
16
+ export { d as ColumnConfig, c as ColumnDefinition, e as ColumnSelectOption, B as ColumnSummaryResult, C as ColumnType, I as DEFAULT_ROW_HEIGHT, D as DateColumnConfig, D as DateFieldConfig, E as EmptyConfig, b as FileColumnConfig, b as FileFieldConfig, n as FilterCondition, m as FilterGroup, o as FilterOperator, F as FormulaColumnConfig, F as FormulaFieldConfig, N as NumberColumnConfig, N as NumberFieldConfig, H as ROW_HEIGHTS, G as ROW_HEIGHT_PX, R as RelationColumnConfig, R as RelationFieldConfig, g as RollupAggregation, a as RollupColumnConfig, a as RollupFieldConfig, M as RowHeight, u as SUMMARY_FUNCTIONS_BY_TYPE, f as SelectColor, S as SelectColumnConfig, p as SortConfig, A as SummaryColumnLike, y as SummaryFunction, z as SummaryRow, T as TextColumnConfig, T as TextFieldConfig, l as ViewConfig, V as ViewType, L as asRowHeight, x as computeColumnSummary, j as isAutoColumnType, h as isComputedColumnType, w as isFilledValue, r as isFilterCondition, q as isFilterGroup, i as isNodeStoreColumnType, k as isYDocColumnType, t as requiresDateColumn, K as resolveRowHeightPx, J as rowHeightLabel, v as summaryFunctionLabel, s as supportsGrouping } from './view-types-DSde-uT_.js';
17
+ import '@xnetjs/crypto';
18
+ import '@xnetjs/sqlite';
19
+ import '@xnetjs/sync';
20
+ import 'y-protocols/awareness';
21
+
22
+ /**
23
+ * Shared external-reference and embed parsing utilities.
24
+ *
25
+ * These helpers normalize URLs into source-backed external references so
26
+ * editor surfaces, task chips, and canvas drops all resolve the same
27
+ * provider, kind, metadata, and embed targets.
28
+ */
29
+ type ExternalReferenceProvider = 'github' | 'figma' | 'youtube' | 'loom' | 'vimeo' | 'codesandbox' | 'spotify' | 'twitter' | 'instagram' | 'tiktok' | 'generic';
30
+ type ExternalReferenceKind = 'issue' | 'pull-request' | 'design' | 'video' | 'sandbox' | 'social' | 'audio' | 'link';
31
+ interface EmbedProvider {
32
+ name: ExternalReferenceProvider;
33
+ displayName: string;
34
+ icon: string;
35
+ patterns: RegExp[];
36
+ extractId: (url: string) => string | null;
37
+ getEmbedUrl: (id: string) => string;
38
+ aspectRatio?: number;
39
+ }
40
+ type ExternalReferenceDescriptor = {
41
+ normalizedUrl: string;
42
+ provider: ExternalReferenceProvider;
43
+ kind: ExternalReferenceKind;
44
+ refId?: string;
45
+ title: string;
46
+ subtitle?: string;
47
+ icon?: string;
48
+ embedUrl?: string;
49
+ metadata: Record<string, string>;
50
+ };
51
+ declare const EMBED_PROVIDERS: EmbedProvider[];
52
+ declare function normalizeExternalReferenceUrl(input: string): string | null;
53
+ declare function detectEmbedProvider(url: string): EmbedProvider | null;
54
+ declare function parseEmbedUrl(url: string): {
55
+ provider: EmbedProvider;
60
56
  id: string;
61
- /** Schema IRI defining what type this node is */
62
- schemaId: SchemaIRI;
63
- /** Unix timestamp (ms) when this node was created */
64
- createdAt: number;
65
- /** DID of the user who created this node */
66
- createdBy: DID;
67
- /** All other fields are schema-defined */
68
- [key: string]: unknown;
69
- }
70
- /**
71
- * Type guard to check if a value is a valid Node.
72
- */
73
- declare function isNode(value: unknown): value is Node;
74
- /**
75
- * Create a new node ID using nanoid.
76
- *
77
- * Node IDs are just unique identifiers - they don't need to be sortable
78
- * (sorting is done by Lamport timestamps in the Change log).
79
- *
80
- * Default length is 21 characters, providing ~126 bits of randomness.
81
- * URL-safe characters: A-Za-z0-9_-
82
- *
83
- * @param length - Optional length (default 21)
84
- * @returns A unique node ID
85
- */
86
- declare function createNodeId(length?: number): string;
57
+ embedUrl: string;
58
+ } | null;
59
+ declare function parseExternalReferenceUrl(input: string): ExternalReferenceDescriptor | null;
60
+
61
+ /**
62
+ * External-reference metadata resolution pipeline.
63
+ */
64
+ type ExternalReferenceMetadataSource = 'oembed' | 'open-graph';
65
+ type ExternalReferenceMetadataStatus = 'resolved' | 'unavailable' | 'blocked' | 'error';
66
+ type ExternalReferenceResolvedMetadata = {
67
+ title: string | null;
68
+ subtitle: string | null;
69
+ description: string | null;
70
+ imageUrl: string | null;
71
+ providerName: string | null;
72
+ authorName: string | null;
73
+ source: ExternalReferenceMetadataSource;
74
+ sourceUrl: string;
75
+ };
76
+ type ExternalReferenceMetadataResult = {
77
+ status: 'resolved';
78
+ metadata: ExternalReferenceResolvedMetadata;
79
+ } | {
80
+ status: Exclude<ExternalReferenceMetadataStatus, 'resolved'>;
81
+ metadata: null;
82
+ reason: string;
83
+ source?: ExternalReferenceMetadataSource;
84
+ sourceUrl?: string;
85
+ error?: string;
86
+ };
87
+ type ExternalReferenceMetadataFetcher = (url: string, init?: RequestInit) => Promise<Response>;
88
+ type ResolveExternalReferenceMetadataInput = {
89
+ url: string;
90
+ provider?: string | null;
91
+ fallbackTitle?: string | null;
92
+ fallbackSubtitle?: string | null;
93
+ fetcher?: ExternalReferenceMetadataFetcher;
94
+ signal?: AbortSignal;
95
+ allowOEmbed?: boolean;
96
+ allowOpenGraph?: boolean;
97
+ openGraphProxyUrl?: string | ((url: string) => string | null);
98
+ };
99
+ type OpenGraphMetadata = {
100
+ title: string | null;
101
+ description: string | null;
102
+ imageUrl: string | null;
103
+ siteName: string | null;
104
+ };
105
+ declare function getExternalReferenceOEmbedEndpoint(input: {
106
+ url: string;
107
+ provider?: string | null;
108
+ }): string | null;
109
+ declare function parseOpenGraphMetadata(html: string): OpenGraphMetadata;
110
+ declare function resolveExternalReferenceMetadata(input: ResolveExternalReferenceMetadataInput): Promise<ExternalReferenceMetadataResult>;
87
111
 
88
112
  /**
89
- * Temp ID resolution for transactional node creation.
90
- *
91
- * Temp IDs are `~`-prefixed strings (e.g., `~parent`, `~comment`) that act as
92
- * placeholders for node IDs in a transaction. The same temp ID used in multiple
93
- * places within a transaction resolves to the same real nanoid.
94
- *
95
- * Resolution happens in two places:
96
- * 1. **Operation IDs** — `create.options.id` and `update/delete/restore.nodeId`
97
- * 2. **Relation properties** — any property with `definition.type === 'relation'`
98
- * in the schema (requires SchemaRegistry access)
99
- *
100
- * @example
101
- * ```typescript
102
- * await store.transaction([
103
- * { type: 'create', options: { id: '~parent', schemaId: 'Task', properties: { title: 'P' } } },
104
- * { type: 'create', options: { id: '~child', schemaId: 'Task', properties: { title: 'C', parent: '~parent' } } },
105
- * ])
106
- * // Returns: { tempIds: { '~parent': 'xK9mQ2...', '~child': 'pL3nR7...' }, ... }
107
- * ```
113
+ * Workspace policy helpers for external-reference iframe embeds.
108
114
  */
109
115
 
110
- /** Prefix that identifies a temp ID. nanoid never produces `~`. */
111
- declare const TEMP_ID_PREFIX = "~";
112
- /**
113
- * Check whether a string is a temp ID (starts with `~`).
114
- */
115
- declare function isTempId(value: unknown): value is string;
116
- /**
117
- * Callback to look up a schema's relation property names by schema IRI.
118
- * Returns the set of property keys that have `type === 'relation'`,
119
- * or undefined if the schema is not available.
120
- */
121
- type SchemaLookup = (schemaId: SchemaIRI) => Set<string> | undefined;
122
- /**
123
- * Build a SchemaLookup from a map of DefinedSchema objects.
124
- * Caches the relation property sets for each schema IRI.
125
- */
126
- declare function createSchemaLookup(getSchema: (iri: SchemaIRI) => DefinedSchema<Record<string, PropertyBuilder>> | undefined): SchemaLookup;
127
- /**
128
- * Result of resolving temp IDs in a list of transaction operations.
129
- */
130
- interface TempIdResolution {
131
- /** The operations with all temp IDs replaced by real IDs */
132
- operations: TransactionOperation[];
133
- /** Map from temp ID → generated real ID (empty if no temp IDs were found) */
134
- tempIds: Record<string, NodeId>;
135
- }
116
+ type ExternalReferenceIframeSandboxToken = 'allow-downloads' | 'allow-forms' | 'allow-modals' | 'allow-orientation-lock' | 'allow-pointer-lock' | 'allow-popups' | 'allow-popups-to-escape-sandbox' | 'allow-presentation' | 'allow-same-origin' | 'allow-scripts' | 'allow-storage-access-by-user-activation' | 'allow-top-navigation-by-user-activation';
117
+ type ExternalReferenceEmbedBlockReason = 'missing-embed-url' | 'invalid-embed-url' | 'provider-blocked' | 'origin-blocked' | 'arbitrary-iframe-blocked';
118
+ type ExternalReferenceEmbedPolicy = {
119
+ allowedProviders?: readonly ExternalReferenceProvider[];
120
+ allowedOrigins?: readonly string[];
121
+ allowArbitraryIframes?: boolean;
122
+ sandbox?: readonly ExternalReferenceIframeSandboxToken[];
123
+ allow?: string;
124
+ referrerPolicy?: ReferrerPolicy;
125
+ };
126
+ type ExternalReferenceEmbedPolicyDecision = {
127
+ allowed: true;
128
+ provider: ExternalReferenceProvider;
129
+ embedUrl: string;
130
+ origin: string;
131
+ sandbox: string;
132
+ allow: string;
133
+ referrerPolicy: ReferrerPolicy;
134
+ } | {
135
+ allowed: false;
136
+ provider: ExternalReferenceProvider;
137
+ embedUrl: string | null;
138
+ origin: string | null;
139
+ reason: ExternalReferenceEmbedBlockReason;
140
+ };
141
+ type EvaluateExternalReferenceEmbedPolicyInput = {
142
+ sourceUrl: string;
143
+ embedUrl?: string | null;
144
+ provider?: string | null;
145
+ policy?: ExternalReferenceEmbedPolicy | null;
146
+ };
147
+ declare const DEFAULT_EXTERNAL_REFERENCE_IFRAME_ALLOW = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share";
148
+ declare function evaluateExternalReferenceEmbedPolicy(input: EvaluateExternalReferenceEmbedPolicyInput): ExternalReferenceEmbedPolicyDecision;
149
+
136
150
  /**
137
- * Resolve all `~`-prefixed temp IDs in a list of transaction operations.
138
- *
139
- * Resolution order:
140
- * 1. Scan all operations to collect temp IDs and generate real IDs
141
- * 2. Replace temp IDs in operation `id` fields (create) and `nodeId` fields (update/delete/restore)
142
- * 3. If a SchemaLookup is provided, replace temp IDs in `relation`-typed property values
143
- *
144
- * @param operations - The original transaction operations (not mutated)
145
- * @param schemaLookup - Optional callback to get relation property names for a schema
146
- * @returns Resolved operations and the temp ID → real ID mapping
151
+ * Shared embed provider registry and iframe policy facade.
147
152
  */
148
- declare function resolveTempIds(operations: TransactionOperation[], schemaLookup?: SchemaLookup): TempIdResolution;
153
+ type EmbedRegistryProvider = 'youtube' | 'spotify' | 'vimeo' | 'loom' | 'figma' | 'codesandbox' | 'generic';
154
+ type EmbedRegistryIframeSecurityAttributes = {
155
+ sandbox: string;
156
+ allow: string;
157
+ referrerPolicy: 'no-referrer' | 'strict-origin-when-cross-origin';
158
+ loading: 'lazy';
159
+ };
160
+ type EmbedRegistryProviderPolicy = {
161
+ provider: EmbedRegistryProvider;
162
+ allowedHostnames: readonly string[];
163
+ iframeAttributes: EmbedRegistryIframeSecurityAttributes;
164
+ metadataFetchingDefault: boolean;
165
+ };
166
+ type EmbedRegistryPolicyDecision = {
167
+ allowed: boolean;
168
+ provider: EmbedRegistryProvider;
169
+ reason?: string;
170
+ policy: EmbedRegistryProviderPolicy;
171
+ iframeAttributes: EmbedRegistryIframeSecurityAttributes;
172
+ };
173
+ type EvaluateEmbedRegistryPolicyInput = {
174
+ provider?: string | null;
175
+ embedUrl?: string | null;
176
+ allowArbitraryEmbeds?: boolean;
177
+ };
178
+ declare function getEmbedRegistryProviderPolicies(): EmbedRegistryProviderPolicy[];
179
+ declare function getEmbedRegistryProviderPolicy(provider: string | null | undefined): EmbedRegistryProviderPolicy;
180
+ declare function evaluateEmbedRegistryPolicy(input: EvaluateEmbedRegistryPolicyInput): EmbedRegistryPolicyDecision;
149
181
 
150
- interface GrantRateLimiterOptions {
151
- limitPerMinute?: number;
152
- windowMs?: number;
153
- now?: () => number;
154
- }
155
182
  /**
156
- * Per-peer rate limiter for grant operations.
157
- *
158
- * Default policy: max 10 grant attempts per peer per minute.
183
+ * Block type registry for document content
159
184
  */
160
- declare class GrantRateLimiter {
161
- private readonly limitPerMinute;
162
- private readonly windowMs;
163
- private readonly now;
164
- private readonly attemptsByPeer;
165
- constructor(options?: GrantRateLimiterOptions);
166
- allow(peerDid: DID$1): boolean;
167
- reset(peerDid?: DID$1): void;
168
- }
169
185
 
170
- declare const GRANT_SCHEMA_IRI: "xnet://xnet.fyi/Grant";
171
- interface GrantNode {
186
+ type BlockType = 'paragraph' | 'heading' | 'list' | 'todo' | 'code' | 'quote' | 'divider' | 'image' | 'embed' | 'table' | 'callout' | 'toggle';
187
+ type Block = {
172
188
  id: string;
189
+ type: BlockType;
190
+ parent: string;
191
+ content: Y.XmlFragment | Y.Map<unknown>;
192
+ children: string[];
173
193
  properties: Record<string, unknown>;
174
- deleted: boolean;
175
- }
176
- interface GrantIndexStore {
177
- list(options?: {
178
- schemaId?: string;
179
- includeDeleted?: boolean;
180
- }): Promise<NodeState[]>;
181
- subscribe(listener: (event: NodeChangeEvent) => void): () => void;
182
- }
183
- interface GrantIndexOptions {
184
- schemaId?: string;
185
- clock?: () => number;
186
- }
187
- declare function isGrantActive(grant: GrantNode, now?: number): boolean;
188
- declare class GrantIndex {
189
- private readonly store;
190
- private byResourceAndGrantee;
191
- private byResource;
192
- private grantsById;
193
- private unsubscribe;
194
- private readonly schemaId;
195
- private readonly clock;
196
- constructor(store: GrantIndexStore, options?: GrantIndexOptions);
197
- initialize(): Promise<void>;
198
- findGrants(resource: string, grantee: DID$1): GrantNode[];
199
- findGrantsForResource(resource: string): GrantNode[];
200
- findAllGrantsForResource(resource: string): GrantNode[];
201
- findGrantsForGrantee(grantee: DID$1): GrantNode[];
202
- dispose(): void;
203
- private loadGrantNodes;
204
- private isGrantSchema;
205
- private indexGrant;
206
- private removeGrant;
207
- }
208
-
209
- interface OfflineAuthPolicy {
210
- /** Cache TTL for can() decisions in eventual mode. Default: 5 minutes. */
211
- decisionCacheTTL: number;
212
- /** Max staleness before operations must revalidate. Default: 1 hour. */
213
- maxStaleness: number;
214
- /** Re-validation strategy used on reconnect. */
215
- revalidation: 'eager' | 'lazy' | 'hybrid';
216
- /** Allow grant/revoke writes while offline. */
217
- allowOfflineGrants: boolean;
218
- }
219
- declare const DEFAULT_OFFLINE_POLICY: OfflineAuthPolicy;
220
- declare function mergeOfflinePolicy(current: OfflineAuthPolicy, patch: Partial<OfflineAuthPolicy>): OfflineAuthPolicy;
221
-
222
- type GrantStatus = 'active' | 'expired' | 'revoked' | 'all';
223
- interface StoreAuthAPI {
224
- can(input: {
225
- action: AuthAction;
226
- nodeId: string;
227
- patch?: Record<string, unknown>;
228
- }): Promise<AuthDecision>;
229
- explain(input: {
230
- action: AuthAction;
231
- nodeId: string;
232
- }): Promise<AuthTrace>;
233
- grant(input: GrantInput): Promise<Grant$1>;
234
- revoke(input: {
235
- grantId: string;
236
- }): Promise<void>;
237
- listGrants(input: {
238
- nodeId: string;
239
- status?: GrantStatus;
240
- }): Promise<Grant$1[]>;
241
- listIssuedGrants(): Promise<Grant$1[]>;
242
- listReceivedGrants(): Promise<Grant$1[]>;
243
- getOfflinePolicy(): OfflineAuthPolicy;
244
- setOfflinePolicy(policy: Partial<OfflineAuthPolicy>): void;
245
- }
246
- interface GrantInput {
247
- to: DID$1;
248
- actions: AuthAction[];
249
- resource: string;
250
- expiresIn?: string | number;
251
- parentGrantId?: string;
252
- }
253
- interface Grant$1 {
254
- id: string;
255
- issuer: DID$1;
256
- grantee: DID$1;
257
- resource: string;
258
- resourceSchema: string;
259
- actions: AuthAction[];
260
- expiresAt: number;
261
- revokedAt: number;
262
- revokedBy?: DID$1;
263
- ucanToken?: string;
264
- proofDepth: number;
265
- parentGrantId?: string;
266
- }
267
- interface StoreAuthStore {
268
- create(options: {
269
- schemaId: string;
270
- properties: Record<string, unknown>;
271
- }): Promise<{
272
- id: string;
273
- }>;
274
- update(nodeId: string, options: {
275
- properties: Record<string, unknown>;
276
- }): Promise<unknown>;
277
- get(nodeId: string): Promise<{
278
- id: string;
279
- createdBy: DID$1;
280
- schemaId: string;
281
- properties: Record<string, unknown>;
282
- } | null>;
283
- list(options?: {
284
- schemaId?: string;
285
- includeDeleted?: boolean;
286
- }): Promise<Array<{
287
- id: string;
288
- schemaId: string;
289
- properties: Record<string, unknown>;
290
- }>>;
291
- }
292
- interface StoreAuthKeyManager {
293
- getContentKey(resourceId: string): Promise<Uint8Array>;
294
- addRecipient(input: {
295
- resourceId: string;
296
- recipient: DID$1;
297
- contentKey: Uint8Array;
298
- recipientPublicKey: Uint8Array;
299
- }): Promise<void>;
300
- rotateContentKey(resourceId: string, revokedRecipient: DID$1): Promise<void>;
301
- }
302
- interface StoreAuthOptions {
303
- store: StoreAuthStore;
304
- actorDid: DID$1;
305
- signingKey: Uint8Array;
306
- evaluator: PolicyEvaluator;
307
- grantIndex?: GrantIndex;
308
- publicKeyResolver?: PublicKeyResolver;
309
- keyManager?: StoreAuthKeyManager;
310
- rateLimiter?: GrantRateLimiter;
311
- now?: () => number;
312
- maxProofDepth?: number;
313
- }
314
- type StoreAuthErrorCode = 'AUTH_PERMISSION_DENIED' | 'AUTH_RATE_LIMIT_EXCEEDED' | 'AUTH_DELEGATION_DEPTH_EXCEEDED' | 'AUTH_DELEGATION_ESCALATION';
315
- declare class StoreAuthError extends Error {
316
- readonly code: StoreAuthErrorCode;
317
- constructor(code: StoreAuthErrorCode, message: string);
318
- }
319
- declare class StoreAuth implements StoreAuthAPI {
320
- private readonly options;
321
- private readonly rateLimiter;
322
- private readonly now;
323
- private readonly maxProofDepth;
324
- private offlinePolicy;
325
- constructor(options: StoreAuthOptions);
326
- can(input: {
327
- action: AuthAction;
328
- nodeId: string;
329
- patch?: Record<string, unknown>;
330
- }): Promise<AuthDecision>;
331
- explain(input: {
332
- action: AuthAction;
333
- nodeId: string;
334
- }): Promise<AuthTrace>;
335
- grant(input: GrantInput): Promise<Grant$1>;
336
- revoke(input: {
337
- grantId: string;
338
- }): Promise<void>;
339
- listGrants(input: {
340
- nodeId: string;
341
- status?: GrantStatus;
342
- }): Promise<Grant$1[]>;
343
- listIssuedGrants(): Promise<Grant$1[]>;
344
- listReceivedGrants(): Promise<Grant$1[]>;
345
- getOfflinePolicy(): OfflineAuthPolicy;
346
- setOfflinePolicy(policy: Partial<OfflineAuthPolicy>): void;
347
- private matchesStatus;
348
- private validateRevocation;
349
- private assertDelegationAttenuation;
350
- private computeProofDepth;
351
- private cascadeRevocation;
352
- private getGrantNodeOrThrow;
353
- private loadGrantNodes;
354
- private createDelegationUCAN;
355
- private computeExpiration;
356
- }
357
-
358
- /**
359
- * Schema Lens System - Bidirectional transformations between schema versions.
360
- *
361
- * A lens defines how to transform data from one schema version to another,
362
- * enabling automatic migrations during read operations.
363
- *
364
- * @example
365
- * ```typescript
366
- * const taskV1toV2: SchemaLens = {
367
- * source: 'xnet://xnet.fyi/Task@1.0.0',
368
- * target: 'xnet://xnet.fyi/Task@2.0.0',
369
- * forward: (data) => ({
370
- * ...data,
371
- * status: data.complete ? 'done' : 'todo',
372
- * priority: data.priority ?? 'medium'
373
- * }),
374
- * backward: (data) => ({
375
- * ...data,
376
- * complete: data.status === 'done'
377
- * }),
378
- * lossless: false // priority is lost in backward transform
379
- * }
380
- *
381
- * registry.register(taskV1toV2)
382
- * const migrated = registry.transform(oldData, 'Task@1.0.0', 'Task@2.0.0')
383
- * ```
384
- */
385
-
386
- /**
387
- * A bidirectional transformation between two schema versions.
388
- */
389
- interface SchemaLens {
390
- /** Source schema IRI (versioned) */
391
- source: SchemaIRI;
392
- /** Target schema IRI (versioned) */
393
- target: SchemaIRI;
394
- /** Transform data from source to target schema */
395
- forward: (data: Record<string, unknown>) => Record<string, unknown>;
396
- /** Transform data from target back to source schema */
397
- backward: (data: Record<string, unknown>) => Record<string, unknown>;
398
- /** Whether the transformation preserves all data (can round-trip without loss) */
399
- lossless: boolean;
400
- }
194
+ };
401
195
  /**
402
- * A single lens operation (used by lens builders).
403
- * Can be composed into a full SchemaLens.
196
+ * Block definition for registering new block types
404
197
  */
405
- interface LensOperation {
406
- /** Transform data forward */
407
- forward: (data: Record<string, unknown>) => Record<string, unknown>;
408
- /** Transform data backward */
409
- backward: (data: Record<string, unknown>) => Record<string, unknown>;
410
- /** Whether this operation is lossless (defaults to true) */
411
- lossless?: boolean;
198
+ interface BlockDefinition {
199
+ type: BlockType;
200
+ create: (id: string, parent: string) => Block;
201
+ validate: (block: Block) => boolean;
412
202
  }
413
203
  /**
414
- * Result of a migration transformation.
204
+ * Register a new block type
415
205
  */
416
- interface MigrationResult {
417
- /** The transformed data */
418
- data: Record<string, unknown>;
419
- /** The path of lenses applied */
420
- path: SchemaLens[];
421
- /** Whether all transformations were lossless */
422
- lossless: boolean;
423
- /** Warnings about potential data loss */
424
- warnings: string[];
425
- }
206
+ declare function registerBlockType(definition: BlockDefinition): void;
426
207
  /**
427
- * Error thrown when migration fails.
208
+ * Create a block of a specific type
428
209
  */
429
- declare class MigrationError extends Error {
430
- readonly source?: SchemaIRI | undefined;
431
- readonly target?: SchemaIRI | undefined;
432
- constructor(message: string, source?: SchemaIRI | undefined, target?: SchemaIRI | undefined);
433
- }
210
+ declare function createBlock(type: BlockType, id: string, parent: string): Block;
434
211
  /**
435
- * Registry for schema lenses with pathfinding for multi-step migrations.
436
- *
437
- * The registry finds the shortest path between schema versions using BFS,
438
- * allowing automatic migrations through intermediate versions.
439
- *
440
- * @example
441
- * ```typescript
442
- * const registry = new LensRegistry()
443
- *
444
- * // Register direct migrations
445
- * registry.register(taskV1toV2)
446
- * registry.register(taskV2toV3)
447
- *
448
- * // Can now migrate from v1 to v3 through v2
449
- * const migrated = registry.transform(v1Data, 'Task@1.0.0', 'Task@3.0.0')
450
- * ```
212
+ * Validate a block
451
213
  */
452
- declare class LensRegistry {
453
- private lenses;
454
- private pathCache;
455
- /**
456
- * Register a lens for transforming between two schema versions.
457
- * Also registers the reverse transformation automatically.
458
- */
459
- register(lens: SchemaLens): void;
460
- /**
461
- * Unregister a lens (and its reverse).
462
- */
463
- unregister(source: SchemaIRI, target: SchemaIRI): boolean;
464
- /**
465
- * Get a direct lens between two schemas (if registered).
466
- */
467
- get(source: SchemaIRI, target: SchemaIRI): SchemaLens | undefined;
468
- /**
469
- * Check if a direct lens exists between two schemas.
470
- */
471
- has(source: SchemaIRI, target: SchemaIRI): boolean;
472
- /**
473
- * Find the shortest path of lenses between two schema versions.
474
- * Uses BFS to find the optimal path through intermediate versions.
475
- *
476
- * @returns Array of lenses to apply in order, or null if no path exists
477
- */
478
- findPath(from: SchemaIRI, to: SchemaIRI): SchemaLens[] | null;
479
- /**
480
- * Transform data from one schema version to another.
481
- *
482
- * @throws MigrationError if no path exists between schemas
483
- */
484
- transform(data: Record<string, unknown>, from: SchemaIRI, to: SchemaIRI): Record<string, unknown>;
485
- /**
486
- * Transform data with detailed migration result.
487
- */
488
- transformWithDetails(data: Record<string, unknown>, from: SchemaIRI, to: SchemaIRI): MigrationResult;
489
- /**
490
- * Check if a migration path exists between two schemas.
491
- */
492
- canMigrate(from: SchemaIRI, to: SchemaIRI): boolean;
493
- /**
494
- * Check if a migration path is lossless (all transformations preserve data).
495
- */
496
- isLossless(from: SchemaIRI, to: SchemaIRI): boolean;
497
- /**
498
- * Get all registered schema IRIs.
499
- */
500
- getSchemas(): SchemaIRI[];
501
- /**
502
- * Clear all registered lenses and cached paths.
503
- */
504
- clear(): void;
505
- /**
506
- * BFS pathfinding to find shortest lens path between schemas.
507
- */
508
- private bfsPath;
509
- }
214
+ declare function validateBlock(block: Block): boolean;
510
215
  /**
511
- * Default global lens registry instance.
216
+ * Get all registered block types
512
217
  */
513
- declare const lensRegistry: LensRegistry;
218
+ declare function getRegisteredBlockTypes(): BlockType[];
514
219
 
515
220
  /**
516
- * NodeStore types - Event-sourced storage for Nodes
517
- *
518
- * The NodeStore manages Nodes using Change<T> from @xnetjs/sync.
519
- * Each Node change is a Change with a NodePayload.
221
+ * BlobService - High-level file upload and retrieval.
520
222
  *
521
- * Key design decisions:
522
- * - No operation types (create-item, update-item, etc.) - just Changes
523
- * - LWW conflict resolution using Lamport timestamps
524
- * - Changes store sparse updates (only changed properties)
525
- * - Materialized state computed by replaying Changes
223
+ * Provides a simple API for storing and retrieving files,
224
+ * handling chunking, URL generation, and cleanup.
526
225
  */
527
226
 
528
- /** Unique identifier for a Node */
529
- type NodeId = string;
530
- /** Identifier for a property within a Node */
531
- type PropertyKey = string;
532
- /**
533
- * Payload for a Node change.
534
- *
535
- * Contains the sparse set of properties that changed.
536
- * First change for a nodeId implicitly creates the Node.
537
- * Setting a property to `undefined` deletes it.
538
- */
539
- interface NodePayload {
540
- /** The Node being changed */
541
- nodeId: NodeId;
542
- /** Schema IRI (required on first change, optional on updates) */
543
- schemaId?: SchemaIRI;
544
- /** Changed properties (sparse - only what changed) */
545
- properties: Record<PropertyKey, unknown>;
546
- /** Soft delete flag (optional) */
547
- deleted?: boolean;
548
- }
549
- /** A Change containing a NodePayload */
550
- type NodeChange = Change<NodePayload>;
551
- /**
552
- * Timestamp metadata for a property value (for LWW resolution).
553
- */
554
- interface PropertyTimestamp {
555
- /** The Lamport timestamp when this value was set */
556
- lamport: LamportTimestamp;
557
- /** Wall clock time (for display) */
558
- wallTime: number;
559
- }
560
- /**
561
- * Materialized Node state with LWW metadata.
562
- *
563
- * This is computed by replaying all Changes for a nodeId.
564
- */
565
- interface NodeState {
566
- /** Node ID */
567
- id: NodeId;
568
- /** Schema IRI */
569
- schemaId: SchemaIRI;
570
- /** Current property values (after LWW resolution) */
571
- properties: Record<PropertyKey, unknown>;
572
- /** LWW timestamps per property (for conflict resolution) */
573
- timestamps: Record<PropertyKey, PropertyTimestamp>;
574
- /** Soft delete flag */
575
- deleted: boolean;
576
- /** When deleted (if deleted) */
577
- deletedAt?: PropertyTimestamp;
578
- /** Creation metadata */
579
- createdAt: number;
580
- createdBy: DID$1;
581
- /** Last update metadata */
582
- updatedAt: number;
583
- updatedBy: DID$1;
584
- /**
585
- * Serialized CRDT document content (for nodes with document type).
586
- * For Yjs: Uint8Array from Y.encodeStateAsUpdate()
587
- * Use Y.applyUpdate(ydoc, documentContent) to hydrate.
588
- */
589
- documentContent?: Uint8Array;
590
- /**
591
- * Unknown properties from future schema versions.
592
- * Preserved on read and passed through on write for forward compatibility.
593
- * These properties exist in the change log but aren't known to the current schema.
594
- */
595
- _unknown?: Record<PropertyKey, unknown>;
596
- /**
597
- * The schema version that last wrote to this node.
598
- * Used to detect when migrations might be needed.
599
- */
600
- _schemaVersion?: string;
601
- }
602
- /**
603
- * Storage adapter interface for NodeStore.
604
- *
605
- * Implementations can use SQLite or memory.
606
- * The adapter stores Changes and materialized NodeState.
607
- */
608
- interface NodeStorageAdapter {
609
- /** Open/initialize the storage connection */
610
- open?(): Promise<void>;
611
- /** Close the storage connection */
612
- close?(): Promise<void>;
613
- appendChange(change: NodeChange): Promise<void>;
614
- getChanges(nodeId: NodeId): Promise<NodeChange[]>;
615
- getAllChanges(): Promise<NodeChange[]>;
616
- /** Get changes with Lamport time greater than `since` */
617
- getChangesSince(sinceLamport: number): Promise<NodeChange[]>;
618
- getChangeByHash(hash: ContentId): Promise<NodeChange | null>;
619
- getLastChange(nodeId: NodeId): Promise<NodeChange | null>;
620
- getNode(id: NodeId): Promise<NodeState | null>;
621
- setNode(node: NodeState): Promise<void>;
622
- deleteNode(id: NodeId): Promise<void>;
623
- listNodes(options?: ListNodesOptions): Promise<NodeState[]>;
624
- countNodes(options?: CountNodesOptions): Promise<number>;
625
- getLastLamportTime(): Promise<number>;
626
- setLastLamportTime(time: number): Promise<void>;
627
- getDocumentContent(nodeId: NodeId): Promise<Uint8Array | null>;
628
- setDocumentContent(nodeId: NodeId, content: Uint8Array): Promise<void>;
629
- }
630
- interface ListNodesOptions {
631
- /** Filter by schema IRI */
632
- schemaId?: SchemaIRI;
633
- /** Include soft-deleted nodes */
634
- includeDeleted?: boolean;
635
- /** Limit results */
636
- limit?: number;
637
- /** Offset for pagination */
638
- offset?: number;
639
- }
640
- interface CountNodesOptions {
641
- /** Filter by schema IRI */
642
- schemaId?: SchemaIRI;
643
- /** Include soft-deleted nodes */
644
- includeDeleted?: boolean;
645
- }
646
- /**
647
- * Result of LWW conflict resolution for a property.
648
- */
649
- interface ConflictResult {
650
- /** Which value won */
651
- winner: 'local' | 'remote';
652
- /** The property key */
653
- key: PropertyKey;
654
- /** The winning value */
655
- value: unknown;
656
- /** The winning timestamp */
657
- timestamp: PropertyTimestamp;
658
- }
659
- /**
660
- * Conflict detected during merge (for debugging/UI).
661
- */
662
- interface MergeConflict {
663
- nodeId: NodeId;
664
- key: PropertyKey;
665
- localValue: unknown;
666
- localTimestamp: PropertyTimestamp;
667
- remoteValue: unknown;
668
- remoteTimestamp: PropertyTimestamp;
669
- resolved: 'local' | 'remote';
227
+ interface BlobServiceOptions {
228
+ /** Maximum file size in bytes (default: 100MB) */
229
+ maxSize?: number;
670
230
  }
671
- /**
672
- * Callback to get the known property names for a schema.
673
- * Used for unknown property preservation during version compatibility.
674
- * Returns the set of property names defined in the schema,
675
- * or undefined if the schema is not available (all properties treated as known).
676
- */
677
- type PropertyLookup = (schemaId: SchemaIRI) => Set<string> | undefined;
678
- /**
679
- * Options for creating a NodeStore.
680
- */
681
- interface NodeStoreOptions {
682
- /** Storage adapter */
683
- storage: NodeStorageAdapter;
684
- /** Author's DID */
685
- authorDID: DID$1;
686
- /** Ed25519 signing key */
687
- signingKey: Uint8Array;
688
- /**
689
- * Optional schema lookup for temp ID resolution in relation properties.
690
- * When provided, `transaction()` will resolve `~`-prefixed temp IDs in
691
- * properties whose schema type is `'relation'`.
692
- * Without this, temp IDs are only resolved in operation ID fields.
693
- */
694
- schemaLookup?: SchemaLookup;
695
- /**
696
- * Optional property lookup for unknown property preservation.
697
- * When provided, properties not in the schema are stored in `_unknown`.
698
- * Without this, all properties are stored as known properties.
699
- */
700
- propertyLookup?: PropertyLookup;
231
+ declare class BlobService {
232
+ private chunkManager;
233
+ private options;
234
+ private urlCache;
235
+ constructor(chunkManager: ChunkManager, options?: BlobServiceOptions);
701
236
  /**
702
- * Optional lens registry for automatic schema migrations.
703
- * When provided, nodes are automatically migrated to the target schema
704
- * version on read (getWithMigration). Without this, nodes are returned as-is.
237
+ * Upload a File and return a FileRef for storage in node properties.
705
238
  */
706
- lensRegistry?: LensRegistry;
707
- /** Optional authorization evaluator used for mutation gating. */
708
- authEvaluator?: PolicyEvaluator;
239
+ upload(file: File): Promise<FileRef>;
709
240
  /**
710
- * Optional transparent node content cipher.
711
- *
712
- * When provided, NodeStore writes encrypted node payload snapshots via
713
- * `setDocumentContent()` and decrypts them on read paths.
241
+ * Upload from Uint8Array (for programmatic use).
714
242
  */
715
- nodeContentCipher?: NodeContentCipher;
243
+ uploadData(data: Uint8Array, metadata: {
244
+ filename: string;
245
+ mimeType: string;
246
+ }): Promise<FileRef>;
716
247
  /**
717
- * Optional cache for per-node content keys used by `nodeContentCipher`.
718
- *
719
- * This avoids expensive key unwraps on repeated reads.
248
+ * Get a URL for displaying/downloading a file.
249
+ * Creates a blob URL that should be revoked when no longer needed.
720
250
  */
721
- contentKeyCache?: ContentKeyCache;
251
+ getUrl(ref: FileRef): Promise<string>;
722
252
  /**
723
- * Optional lookup for properties that can change node recipients.
724
- * When provided, update paths only trigger recipient recomputation hooks
725
- * if one of these properties is changed.
253
+ * Get raw data for a file.
726
254
  */
727
- authRelevantPropertyLookup?: (schemaId: SchemaIRI) => Set<string> | undefined;
255
+ getData(ref: FileRef): Promise<Uint8Array | null>;
728
256
  /**
729
- * Optional callback triggered when an update touches auth-relevant properties.
730
- * Integrators can use this to recompute recipients and rotate keys.
257
+ * Check if a file exists locally.
731
258
  */
732
- onRecipientsMayNeedRecompute?: (context: {
733
- nodeId: NodeId;
734
- schemaId: SchemaIRI;
735
- changedProperties: string[];
736
- }) => Promise<void> | void;
259
+ has(ref: FileRef): Promise<boolean>;
737
260
  /**
738
- * Optional callback for rejected unauthorized remote changes.
739
- * Remote unauthorized changes are rejected silently and never applied.
261
+ * Get list of missing chunk CIDs (for sync).
740
262
  */
741
- onUnauthorizedRemoteChange?: (context: {
742
- change: NodeChange;
743
- action: AuthAction;
744
- decision: AuthDecision;
745
- }) => void;
746
- /** Optional high-level authorization API attached as `store.auth`. */
747
- auth?: StoreAuthAPI;
263
+ getMissingChunks(ref: FileRef): Promise<ContentId[]>;
748
264
  /**
749
- * Optional telemetry collector for tracking CRUD operations, errors, and performance.
750
- * When provided, NodeStore will report:
751
- * - Performance metrics for create/update/delete/list operations
752
- * - Usage metrics for operation counts
753
- * - Crash reports for errors
754
- *
755
- * Compatible with @xnetjs/telemetry TelemetryCollector.
265
+ * Revoke a blob URL to free memory.
756
266
  */
757
- telemetry?: {
758
- reportPerformance(metricName: string, durationMs: number, codeNamespace?: string): void;
759
- reportUsage(metricName: string, value: number): void;
760
- reportCrash(error: Error, context?: {
761
- codeNamespace?: string;
762
- }): void;
763
- reportSecurityEvent(eventName: string, severity: 'low' | 'medium' | 'high' | 'critical'): void;
764
- };
765
- }
766
- /**
767
- * Cache for per-node content keys used during transparent decrypt/encrypt flows.
768
- */
769
- interface ContentKeyCache {
770
- get(nodeId: NodeId): Uint8Array | undefined;
771
- set(nodeId: NodeId, key: Uint8Array): void;
772
- delete(nodeId: NodeId): void;
773
- clear?(): void;
774
- }
775
- /**
776
- * Pluggable cipher for transparent node payload encryption.
777
- */
778
- interface NodeContentCipher {
779
- encrypt(input: {
780
- nodeId: NodeId;
781
- schemaId: SchemaIRI;
782
- content: Uint8Array;
783
- cachedContentKey?: Uint8Array;
784
- }): Promise<{
785
- encryptedContent: Uint8Array;
786
- contentKey?: Uint8Array;
787
- }>;
788
- decrypt(input: {
789
- nodeId: NodeId;
790
- schemaId: SchemaIRI;
791
- encryptedContent: Uint8Array;
792
- cachedContentKey?: Uint8Array;
793
- }): Promise<{
794
- content: Uint8Array;
795
- contentKey?: Uint8Array;
796
- }>;
797
- }
798
- /**
799
- * Options for creating a Node.
800
- */
801
- interface CreateNodeOptions$1 {
802
- /** Optional ID (generated if not provided) */
803
- id?: NodeId;
804
- /** Schema IRI */
805
- schemaId: SchemaIRI;
806
- /** Initial property values */
807
- properties: Record<PropertyKey, unknown>;
808
- }
809
- /**
810
- * Options for updating a Node.
811
- */
812
- interface UpdateNodeOptions {
813
- /** Changed properties (sparse) */
814
- properties: Record<PropertyKey, unknown>;
815
- }
816
- /**
817
- * A single operation within a transaction.
818
- */
819
- type TransactionOperation = {
820
- type: 'create';
821
- options: CreateNodeOptions$1;
822
- } | {
823
- type: 'update';
824
- nodeId: NodeId;
825
- options: UpdateNodeOptions;
826
- } | {
827
- type: 'delete';
828
- nodeId: NodeId;
829
- } | {
830
- type: 'restore';
831
- nodeId: NodeId;
832
- };
833
- /**
834
- * Result of a transaction execution.
835
- * Returns the affected nodes in the same order as operations.
836
- */
837
- interface TransactionResult {
838
- /** The batch ID shared by all changes */
839
- batchId: string;
840
- /** Results for each operation (NodeState or null for delete) */
841
- results: (NodeState | null)[];
842
- /** All changes created in this transaction */
843
- changes: NodeChange[];
844
- /** Map from temp ID → generated real ID (empty if no temp IDs were used) */
845
- tempIds: Record<string, NodeId>;
846
- }
847
- /**
848
- * Event emitted when a Node changes.
849
- */
850
- interface NodeChangeEvent {
851
- /** The change that was applied */
852
- change: NodeChange;
853
- /** The resulting Node state */
854
- node: NodeState | null;
855
- /** Whether this was a remote change (from sync) */
856
- isRemote: boolean;
857
- }
858
- /**
859
- * Listener for Node change events.
860
- */
861
- type NodeChangeListener = (event: NodeChangeEvent) => void;
862
- /**
863
- * Options for getWithMigration.
864
- */
865
- interface GetWithMigrationOptions {
866
- /** Target schema IRI to migrate to (required) */
867
- targetSchemaId: SchemaIRI;
868
- }
869
- /**
870
- * Information about a migration that was applied.
871
- */
872
- interface MigrationInfo {
873
- /** The original schema IRI of the stored data */
874
- from: SchemaIRI;
875
- /** The target schema IRI */
876
- to: SchemaIRI;
877
- /** Whether the migration preserved all data (no data loss) */
878
- lossless: boolean;
879
- /** Warnings about potential data loss */
880
- warnings: string[];
881
- }
882
- /**
883
- * Result of getWithMigration.
884
- */
885
- interface MigratedNodeState extends NodeState {
267
+ revokeUrl(ref: FileRef): void;
886
268
  /**
887
- * Migration info if the node was migrated from a different schema version.
888
- * Undefined if no migration was needed.
269
+ * Revoke all cached blob URLs.
889
270
  */
890
- _migrationInfo?: MigrationInfo;
271
+ revokeAllUrls(): void;
891
272
  }
892
273
 
893
- /**
894
- * NodeStore - Event-sourced storage for Nodes
895
- *
896
- * Manages Nodes using Change<T> from @xnetjs/sync with LWW conflict resolution.
897
- *
898
- * Key features:
899
- * - Simple CRUD API that creates Changes under the hood
900
- * - LWW conflict resolution using Lamport timestamps
901
- * - Sparse updates (only store changed properties)
902
- * - Materialized state for fast reads
903
- */
904
-
905
- /**
906
- * NodeStore manages event-sourced Nodes with LWW conflict resolution.
907
- */
908
- declare class NodeStore {
909
- private storage;
910
- private authorDID;
911
- private signingKey;
912
- private clock;
913
- private conflicts;
914
- private listeners;
915
- private schemaLookup?;
916
- private propertyLookup?;
917
- private lensRegistry?;
918
- private authEvaluator?;
919
- private nodeContentCipher?;
920
- private contentKeyCache?;
921
- private authRelevantPropertyLookup?;
922
- private onRecipientsMayNeedRecompute?;
923
- private onUnauthorizedRemoteChange?;
924
- readonly auth?: StoreAuthAPI;
925
- private telemetry?;
926
- constructor(options: NodeStoreOptions);
927
- /**
928
- * Initialize the store by loading the last Lamport time from storage.
929
- * Call this before using the store.
930
- */
931
- initialize(): Promise<void>;
932
- /**
933
- * Get the underlying storage adapter.
934
- *
935
- * Use this to access low-level storage operations like change history,
936
- * document content, and Lamport timestamps. Useful for building history,
937
- * audit, and verification features.
938
- *
939
- * @returns The NodeStorageAdapter instance
940
- */
941
- getStorageAdapter(): NodeStorageAdapter;
942
- /**
943
- * Create a new Node.
944
- */
945
- create(options: CreateNodeOptions$1): Promise<NodeState>;
946
- /**
947
- * Get a Node by ID.
948
- */
949
- get(id: NodeId): Promise<NodeState | null>;
950
- /**
951
- * Get a Node by ID with automatic schema migration.
952
- *
953
- * If the stored node's schema version differs from the target schema,
954
- * and a migration path exists in the lens registry, the node's properties
955
- * will be automatically transformed.
956
- *
957
- * @param id - The node ID to fetch
958
- * @param options - Options including the target schema IRI
959
- * @returns The node with migrated properties, or null if not found
960
- *
961
- * @example
962
- * ```typescript
963
- * // Get node and migrate to TaskSchema v2.0.0
964
- * const node = await store.getWithMigration('node-123', {
965
- * targetSchemaId: TaskSchemaV2['@id']
966
- * })
967
- *
968
- * if (node?._migrationInfo) {
969
- * console.log('Migrated from:', node._migrationInfo.from)
970
- * if (!node._migrationInfo.lossless) {
971
- * console.warn('Migration warnings:', node._migrationInfo.warnings)
972
- * }
973
- * }
974
- * ```
975
- */
976
- getWithMigration(id: NodeId, options: GetWithMigrationOptions): Promise<MigratedNodeState | null>;
977
- /**
978
- * Update a Node's properties.
979
- */
980
- update(id: NodeId, options: UpdateNodeOptions): Promise<NodeState>;
981
- /**
982
- * Delete a Node (soft delete).
983
- */
984
- delete(id: NodeId): Promise<void>;
985
- /**
986
- * Restore a deleted Node.
987
- */
988
- restore(id: NodeId): Promise<NodeState>;
989
- /**
990
- * List Nodes with optional filtering.
991
- */
992
- list(options?: ListNodesOptions): Promise<NodeState[]>;
993
- /**
994
- * Execute multiple operations as a single atomic transaction.
995
- *
996
- * All changes created in the transaction share the same batchId and Lamport
997
- * timestamp, making them logically atomic. This is useful for:
998
- * - Multi-node operations (move task between projects)
999
- * - Undo/redo grouping
1000
- * - Audit trails ("user did X" as a single action)
1001
- * - Future blockchain integration (batch = transaction)
1002
- *
1003
- * @example
1004
- * ```typescript
1005
- * const result = await store.transaction([
1006
- * { type: 'update', nodeId: task.id, options: { properties: { projectId: newProject.id } } },
1007
- * { type: 'update', nodeId: oldProject.id, options: { properties: { taskIds: [...] } } },
1008
- * { type: 'update', nodeId: newProject.id, options: { properties: { taskIds: [...] } } },
1009
- * ])
1010
- * console.log(`Batch ${result.batchId} applied ${result.changes.length} changes`)
1011
- * ```
1012
- */
1013
- transaction(operations: TransactionOperation[]): Promise<TransactionResult>;
1014
- /**
1015
- * Apply a remote change (from sync).
1016
- * Verifies the change signature before applying.
1017
- *
1018
- * @throws Error if signature verification fails
1019
- */
1020
- applyRemoteChange(change: NodeChange): Promise<void>;
1021
- /**
1022
- * Apply multiple remote changes (from sync).
1023
- */
1024
- applyRemoteChanges(changes: NodeChange[]): Promise<void>;
1025
- /**
1026
- * Get all changes for a Node (for sync).
1027
- */
1028
- getChanges(nodeId: NodeId): Promise<NodeChange[]>;
1029
- /**
1030
- * Get all changes (for full sync).
1031
- */
1032
- getAllChanges(): Promise<NodeChange[]>;
1033
- /**
1034
- * Get changes since a Lamport time (for delta sync).
1035
- */
1036
- getChangesSince(sinceLamport: number): Promise<NodeChange[]>;
1037
- /**
1038
- * Get the current Lamport time (for sync protocol).
1039
- */
1040
- getCurrentLamportTime(): number;
1041
- /**
1042
- * Get recent merge conflicts (for debugging/UI).
1043
- */
1044
- getRecentConflicts(): MergeConflict[];
1045
- /**
1046
- * Clear conflict history.
1047
- */
1048
- clearConflicts(): void;
1049
- /**
1050
- * Get CRDT document content for a node.
1051
- * Returns null if no document content exists.
1052
- */
1053
- getDocumentContent(nodeId: NodeId): Promise<Uint8Array | null>;
1054
- /**
1055
- * Set CRDT document content for a node.
1056
- * Used to persist serialized Y.Doc or other CRDT state.
1057
- */
1058
- setDocumentContent(nodeId: NodeId, content: Uint8Array): Promise<void>;
1059
- /**
1060
- * Subscribe to node changes.
1061
- *
1062
- * @param listener - Callback invoked when nodes change
1063
- * @returns Unsubscribe function
1064
- *
1065
- * @example
1066
- * ```ts
1067
- * const unsubscribe = store.subscribe((event) => {
1068
- * console.log('Node changed:', event.node?.id, event.isRemote)
1069
- * })
1070
- * // Later: unsubscribe()
1071
- * ```
1072
- */
1073
- subscribe(listener: NodeChangeListener): () => void;
1074
- /**
1075
- * Emit a change event to all listeners.
1076
- */
1077
- private emit;
1078
- /**
1079
- * Create a signed change.
1080
- */
1081
- private createChange;
1082
- /**
1083
- * Create a signed change with batch metadata.
1084
- * Used for transaction support - all changes in a batch share the same
1085
- * batchId, Lamport timestamp, and wallTime.
1086
- */
1087
- private createBatchedChange;
1088
- /**
1089
- * Apply a change to storage and update materialized state.
1090
- */
1091
- private applyChange;
1092
- /**
1093
- * Determine if newTs should replace existingTs (LWW).
1094
- */
1095
- private shouldReplace;
1096
- /**
1097
- * Trim conflicts array to prevent unbounded memory growth.
1098
- * Keeps only the most recent MAX_CONFLICTS entries.
1099
- */
1100
- private trimConflicts;
1101
- private assertAuthorized;
1102
- private assertAuthorizedBatch;
1103
- private inferActionFromChange;
1104
- private shouldRecomputeRecipients;
1105
- private persistEncryptedNodeSnapshot;
1106
- private decryptNodeSnapshotIfPresent;
1107
- private serializeNodeSnapshot;
1108
- private deserializeNodeSnapshot;
1109
- private parseEncryptedNodeSnapshot;
1110
- }
1111
-
1112
- /**
1113
- * Error thrown when a local mutation fails authorization checks.
1114
- */
1115
- declare class PermissionError extends Error {
1116
- readonly code = "PERMISSION_DENIED";
1117
- readonly action: AuthAction;
1118
- readonly nodeId: string;
1119
- readonly subject: DID$1;
1120
- readonly reasons: AuthDenyReason[];
1121
- readonly roles: string[];
1122
- readonly decision: AuthDecision;
1123
- constructor(decision: AuthDecision);
1124
- }
1125
-
1126
- /**
1127
- * In-memory storage adapter for NodeStore.
1128
- *
1129
- * Useful for testing and ephemeral data.
1130
- */
1131
-
1132
- /**
1133
- * In-memory implementation of NodeStorageAdapter.
1134
- */
1135
- declare class MemoryNodeStorageAdapter implements NodeStorageAdapter {
1136
- private changes;
1137
- private changesByHash;
1138
- private nodes;
1139
- private documentContentStore;
1140
- private yjsSnapshotStore;
1141
- private lastLamportTime;
1142
- appendChange(change: NodeChange): Promise<void>;
1143
- getChanges(nodeId: NodeId): Promise<NodeChange[]>;
1144
- getAllChanges(): Promise<NodeChange[]>;
1145
- getChangesSince(sinceLamport: number): Promise<NodeChange[]>;
1146
- getChangeByHash(hash: ContentId): Promise<NodeChange | null>;
1147
- getLastChange(nodeId: NodeId): Promise<NodeChange | null>;
1148
- getNode(id: NodeId): Promise<NodeState | null>;
1149
- setNode(node: NodeState): Promise<void>;
1150
- deleteNode(id: NodeId): Promise<void>;
1151
- listNodes(options?: ListNodesOptions): Promise<NodeState[]>;
1152
- countNodes(options?: CountNodesOptions): Promise<number>;
1153
- getLastLamportTime(): Promise<number>;
1154
- setLastLamportTime(time: number): Promise<void>;
1155
- getDocumentContent(nodeId: NodeId): Promise<Uint8Array | null>;
1156
- setDocumentContent(nodeId: NodeId, content: Uint8Array): Promise<void>;
1157
- saveYjsSnapshot(snapshot: {
1158
- nodeId: NodeId;
1159
- timestamp: number;
1160
- snapshot: Uint8Array;
1161
- docState: Uint8Array;
1162
- byteSize: number;
1163
- }): Promise<void>;
1164
- getYjsSnapshots(nodeId: NodeId): Promise<{
1165
- nodeId: NodeId;
1166
- timestamp: number;
1167
- snapshot: Uint8Array;
1168
- docState: Uint8Array;
1169
- byteSize: number;
1170
- }[]>;
1171
- deleteYjsSnapshots(nodeId: NodeId): Promise<void>;
1172
- /**
1173
- * Clear all data (for testing).
1174
- */
1175
- clear(): void;
1176
- /**
1177
- * Get total change count (for testing).
1178
- */
1179
- getChangeCount(): number;
1180
- /**
1181
- * Get total node count (for testing).
1182
- */
1183
- getNodeCount(): number;
1184
- }
1185
-
1186
- /**
1187
- * SQLite storage adapter for NodeStore.
1188
- *
1189
- * Provides high-performance storage for nodes and changes using SQLite.
1190
- * Works with any SQLiteAdapter implementation (Electron, Web, Expo).
1191
- */
1192
-
1193
- /**
1194
- * SQLite-backed storage adapter for NodeStore.
1195
- *
1196
- * This adapter provides high-performance storage for nodes and changes
1197
- * using the platform-appropriate SQLite implementation.
1198
- *
1199
- * @example
1200
- * ```typescript
1201
- * import { createMemorySQLiteAdapter } from '@xnetjs/sqlite/memory'
1202
- *
1203
- * const sqliteAdapter = await createMemorySQLiteAdapter()
1204
- * const nodeStorage = new SQLiteNodeStorageAdapter(sqliteAdapter)
1205
- *
1206
- * const store = new NodeStore({
1207
- * storage: nodeStorage,
1208
- * authorDID: identity.did,
1209
- * signingKey: identity.signingKey
1210
- * })
1211
- * ```
1212
- */
1213
- declare class SQLiteNodeStorageAdapter implements NodeStorageAdapter {
1214
- private db;
1215
- private stmtCache;
1216
- constructor(db: SQLiteAdapter);
1217
- getSQLiteAdapter(): SQLiteAdapter;
1218
- open(): Promise<void>;
1219
- close(): Promise<void>;
1220
- /**
1221
- * Get or create a prepared statement.
1222
- * Cached statements are reused for better performance.
1223
- */
1224
- private getStatement;
1225
- appendChange(change: NodeChange): Promise<void>;
1226
- getChanges(nodeId: NodeId): Promise<NodeChange[]>;
1227
- getAllChanges(): Promise<NodeChange[]>;
1228
- getChangesSince(sinceLamport: number): Promise<NodeChange[]>;
1229
- getChangeByHash(hash: ContentId): Promise<NodeChange | null>;
1230
- getLastChange(nodeId: NodeId): Promise<NodeChange | null>;
1231
- getNode(id: NodeId): Promise<NodeState | null>;
1232
- setNode(node: NodeState): Promise<void>;
1233
- /**
1234
- * Internal method for setting a node without starting a new transaction.
1235
- * Used by importNodes to avoid nested transactions.
1236
- */
1237
- private _setNodeInternal;
1238
- deleteNode(id: NodeId): Promise<void>;
1239
- listNodes(options?: ListNodesOptions): Promise<NodeState[]>;
1240
- /**
1241
- * Optimized listNodes using a single JOIN query.
1242
- * Fetches nodes and properties in one query for better performance with large datasets.
1243
- */
1244
- listNodesOptimized(options?: ListNodesOptions): Promise<NodeState[]>;
1245
- countNodes(options?: CountNodesOptions): Promise<number>;
1246
- getLastLamportTime(): Promise<number>;
1247
- setLastLamportTime(time: number): Promise<void>;
1248
- getDocumentContent(nodeId: NodeId): Promise<Uint8Array | null>;
1249
- setDocumentContent(nodeId: NodeId, content: Uint8Array): Promise<void>;
1250
- /**
1251
- * Save a Yjs snapshot for time travel.
1252
- */
1253
- saveYjsSnapshot(snapshot: {
1254
- nodeId: NodeId;
1255
- timestamp: number;
1256
- snapshot: Uint8Array;
1257
- docState: Uint8Array;
1258
- byteSize: number;
1259
- }): Promise<void>;
1260
- /**
1261
- * Get Yjs snapshots for a node.
1262
- */
1263
- getYjsSnapshots(nodeId: NodeId): Promise<Array<{
1264
- nodeId: NodeId;
1265
- timestamp: number;
1266
- snapshot: Uint8Array;
1267
- docState: Uint8Array;
1268
- byteSize: number;
1269
- }>>;
1270
- /**
1271
- * Delete Yjs snapshots for a node.
1272
- */
1273
- deleteYjsSnapshots(nodeId: NodeId): Promise<void>;
1274
- /**
1275
- * Import multiple nodes in a single transaction.
1276
- * Used for sync and restore operations.
1277
- */
1278
- importNodes(nodes: NodeState[]): Promise<void>;
1279
- /**
1280
- * Import multiple changes in a single transaction.
1281
- */
1282
- importChanges(changes: NodeChange[]): Promise<void>;
1283
- /**
1284
- * Clear all data (for testing or reset).
1285
- */
1286
- clear(): Promise<void>;
1287
- private serializePayload;
1288
- private deserializePayload;
1289
- private serializeValue;
1290
- private deserializeValue;
1291
- private deserializeChange;
1292
- }
1293
-
1294
- interface NodeStoreReader {
1295
- get(id: string): Promise<NodeState | null>;
1296
- list(options?: {
1297
- schemaId?: string;
1298
- includeDeleted?: boolean;
1299
- }): Promise<NodeState[]>;
1300
- subscribe(listener: (event: NodeChangeEvent) => void): () => void;
1301
- }
1302
- interface DecisionCacheOptions {
1303
- ttlMs?: number;
1304
- maxSize?: number;
1305
- now?: () => number;
1306
- }
1307
- declare class DecisionCache {
1308
- private cache;
1309
- private ttlMs;
1310
- private readonly maxSize;
1311
- private readonly now;
1312
- constructor(options?: DecisionCacheOptions);
1313
- get(subject: DID$1, action: string, nodeId: string): AuthDecision | null;
1314
- set(subject: DID$1, action: string, nodeId: string, decision: AuthDecision): void;
1315
- invalidateNode(nodeId: string): void;
1316
- invalidateSubject(did: DID$1): void;
1317
- clear(): void;
1318
- setTTL(ttlMs: number): void;
1319
- private key;
1320
- }
1321
- interface DefaultRoleResolverOptions {
1322
- maxDepth?: number;
1323
- maxNodes?: number;
1324
- }
1325
- declare class DefaultRoleResolver {
1326
- private readonly store;
1327
- private readonly schemaRegistry;
1328
- private readonly maxDepth;
1329
- private readonly maxNodes;
1330
- constructor(store: NodeStoreReader, schemaRegistry: SchemaRegistry, options?: DefaultRoleResolverOptions);
1331
- resolveRoles(did: DID$1, node: NodeState, schema: Schema): Promise<Set<string>>;
1332
- resolveRoleMembers(resolver: RoleResolver, node: NodeState): Promise<DID$1[]>;
1333
- private resolveRoleMembersInner;
1334
- private checkRole;
1335
- private loadRelatedNodes;
1336
- }
1337
- interface DefaultPolicyEvaluatorOptions {
1338
- store: NodeStoreReader;
1339
- schemaRegistry: SchemaRegistry;
1340
- grantIndex?: GrantIndex;
1341
- cache?: DecisionCache;
1342
- roleResolver?: DefaultRoleResolver;
1343
- maxDepth?: number;
1344
- maxNodes?: number;
1345
- now?: () => number;
1346
- offlinePolicy?: Partial<OfflineAuthPolicy>;
1347
- getLastSyncedAt?: () => number;
1348
- isOnline?: () => boolean;
1349
- onRevalidation?: (event: RevalidationEvent) => void;
1350
- onDecision?: (event: AuthDecisionEvent) => void;
1351
- }
1352
- interface RevalidationEvent {
1353
- type: 'hybrid-revalidation';
1354
- at: number;
1355
- invalidated: 'all';
1356
- }
1357
- interface AuthDecisionEvent {
1358
- type: 'auth:decision';
1359
- timestamp: number;
1360
- subject: DID$1;
1361
- action: AuthDecision['action'];
1362
- resource: string;
1363
- allowed: boolean;
1364
- cached: boolean;
1365
- roles: string[];
1366
- reasons: AuthDenyReason[];
1367
- duration: number;
1368
- }
1369
- declare class DefaultPolicyEvaluator implements PolicyEvaluator {
1370
- private readonly options;
1371
- private readonly grantIndex?;
1372
- private readonly cache;
1373
- private readonly roleResolver;
1374
- private readonly now;
1375
- private offlinePolicy;
1376
- private readonly getLastSyncedAt?;
1377
- private readonly isOnline;
1378
- private readonly onRevalidation?;
1379
- private readonly onDecision?;
1380
- private lastConnectivityOnline;
1381
- constructor(options: DefaultPolicyEvaluatorOptions);
1382
- can(input: AuthCheckInput): Promise<AuthDecision>;
1383
- explain(input: AuthCheckInput): Promise<AuthTrace>;
1384
- invalidate(nodeId: string): void;
1385
- invalidateSubject(did: DID$1): void;
1386
- getOfflinePolicy(): OfflineAuthPolicy;
1387
- setOfflinePolicy(patch: Partial<OfflineAuthPolicy>): void;
1388
- handleConnectivityChange(isOnline: boolean): void;
1389
- private findMatchingGrant;
1390
- private checkFieldRules;
1391
- private decision;
1392
- private deny;
1393
- private loadNodeFromInput;
1394
- private isAuthStateStale;
1395
- private emitDecision;
1396
- }
1397
-
1398
- interface GrantExpirationStore {
1399
- list(options?: {
1400
- schemaId?: string;
1401
- includeDeleted?: boolean;
1402
- }): Promise<Array<{
1403
- id: string;
1404
- properties: Record<string, unknown>;
1405
- }>>;
1406
- update(nodeId: string, options: {
1407
- properties: Record<string, unknown>;
1408
- }): Promise<unknown>;
1409
- }
1410
- interface GrantExpirationCleanerOptions {
1411
- clock?: () => number;
1412
- cleanupIntervalMs?: number;
1413
- clockSkewToleranceMs?: number;
1414
- systemRevoker?: string;
1415
- }
1416
- declare class GrantExpirationCleaner {
1417
- private readonly store;
1418
- static readonly DEFAULT_CLOCK_SKEW_TOLERANCE_MS = 60000;
1419
- static readonly DEFAULT_CLEANUP_INTERVAL_MS: number;
1420
- private readonly clock;
1421
- private readonly cleanupIntervalMs;
1422
- private readonly clockSkewToleranceMs;
1423
- private readonly systemRevoker;
1424
- private timer;
1425
- constructor(store: GrantExpirationStore, options?: GrantExpirationCleanerOptions);
1426
- start(): void;
1427
- stop(): void;
1428
- cleanup(): Promise<{
1429
- pruned: number;
1430
- }>;
1431
- }
1432
-
1433
- /**
1434
- * Schema types for xNet's code-first schema system.
1435
- */
1436
-
1437
- /**
1438
- * Property type identifiers.
1439
- */
1440
- type PropertyType = 'text' | 'number' | 'checkbox' | 'date' | 'dateRange' | 'select' | 'multiSelect' | 'person' | 'relation' | 'rollup' | 'formula' | 'url' | 'email' | 'phone' | 'file' | 'created' | 'updated' | 'createdBy';
1441
- /**
1442
- * Base property definition stored in a schema.
1443
- */
1444
- interface PropertyDefinition {
1445
- /** Property IRI (e.g., 'xnet://xnet.fyi/Task#title') */
1446
- '@id': string;
1447
- /** Property name */
1448
- name: string;
1449
- /** Property type */
1450
- type: PropertyType;
1451
- /** Whether this property is required */
1452
- required: boolean;
1453
- /** Type-specific configuration */
1454
- config?: Record<string, unknown>;
1455
- }
1456
- /**
1457
- * A property builder returned by property helper functions.
1458
- * Contains both the definition and runtime validation/coercion.
1459
- */
1460
- interface PropertyBuilder<T = unknown> {
1461
- /** The property definition for schema storage */
1462
- definition: Omit<PropertyDefinition, '@id' | 'name'>;
1463
- /** Validate a value against this property type */
1464
- validate(value: unknown): value is T;
1465
- /** Coerce a value to this property type (returns null if invalid) */
1466
- coerce(value: unknown): T | null;
1467
- /** TypeScript type marker (never used at runtime) */
1468
- _type: T;
1469
- }
1470
- /**
1471
- * CRDT document type for collaborative content.
1472
- *
1473
- * When a schema specifies a document type, nodes of that schema
1474
- * have an associated CRDT document that syncs via the CRDT's
1475
- * native protocol (e.g., y-webrtc for Yjs).
1476
- *
1477
- * - 'yjs': Yjs Y.Doc for collaborative rich text, canvas, etc.
1478
- * - 'automerge': Automerge document (future support)
1479
- */
1480
- type DocumentType = 'yjs' | 'automerge';
1481
- /**
1482
- * Schema definition stored as JSON-LD.
1483
- */
1484
- interface Schema {
1485
- /** Schema IRI */
1486
- '@id': SchemaIRI;
1487
- /** Type marker for JSON-LD */
1488
- '@type': 'xnet://xnet.fyi/Schema';
1489
- /** Human-readable name */
1490
- name: string;
1491
- /** Namespace for this schema */
1492
- namespace: string;
1493
- /**
1494
- * Schema version in semver format.
1495
- * Included in IRI as `@version` suffix.
1496
- */
1497
- version: string;
1498
- /**
1499
- * Previous schema IRI to migrate from.
1500
- * Used for automatic migration path discovery.
1501
- */
1502
- migrateFrom?: SchemaIRI;
1503
- /** Property definitions */
1504
- properties: PropertyDefinition[];
1505
- /** Parent schema IRI (for inheritance) */
1506
- extends?: SchemaIRI;
1507
- /**
1508
- * CRDT document type for collaborative content.
1509
- * When set, nodes of this schema have an associated CRDT document
1510
- * that syncs separately from properties (which use LWW).
1511
- */
1512
- document?: DocumentType;
1513
- /**
1514
- * Authorization rules for this schema.
1515
- * Defines roles, action permissions, and access control policies.
1516
- * When present, nodes of this schema are encrypted and access is controlled.
1517
- */
1518
- authorization?: SerializedAuthorization;
1519
- }
1520
- /**
1521
- * Validation result from schema validation.
1522
- */
1523
- interface ValidationResult {
1524
- valid: boolean;
1525
- errors: ValidationError[];
1526
- }
1527
- /**
1528
- * A single validation error.
1529
- */
1530
- interface ValidationError {
1531
- path: string;
1532
- message: string;
1533
- value?: unknown;
1534
- }
1535
- /**
1536
- * Options for creating a node from a schema.
1537
- */
1538
- interface CreateNodeOptions {
1539
- /** Override the generated ID */
1540
- id?: string;
1541
- /** The creator's DID */
1542
- createdBy: DID;
1543
- /** Override the creation timestamp */
1544
- createdAt?: number;
1545
- }
1546
- /**
1547
- * A defined schema with runtime methods.
1548
- */
1549
- interface DefinedSchema<TProperties extends Record<string, PropertyBuilder> = Record<string, PropertyBuilder>> {
1550
- /** The schema definition (JSON-LD compatible) */
1551
- schema: Schema;
1552
- /** Validate a node against this schema */
1553
- validate(node: unknown): ValidationResult;
1554
- /** Create a new node of this schema type */
1555
- create(properties: InferCreateProps<TProperties>, options: CreateNodeOptions): InferNode<TProperties>;
1556
- /** Type guard - check if a node matches this schema */
1557
- is(node: Node): node is InferNode<TProperties>;
1558
- /** Schema IRI for type inference */
1559
- readonly _schemaId: SchemaIRI;
1560
- /** Property builders for type inference */
1561
- readonly _properties: TProperties;
1562
- }
1563
- /**
1564
- * Infer the TypeScript type from a property builder.
1565
- */
1566
- type InferPropertyType<B> = B extends PropertyBuilder<infer T> ? T : never;
1567
- /**
1568
- * Infer required properties from a record of property builders.
1569
- */
1570
- type RequiredKeys<P extends Record<string, PropertyBuilder>> = {
1571
- [K in keyof P]: P[K]['definition']['required'] extends true ? K : never;
1572
- }[keyof P];
1573
- /**
1574
- * Infer optional properties from a record of property builders.
1575
- */
1576
- type OptionalKeys<P extends Record<string, PropertyBuilder>> = {
1577
- [K in keyof P]: P[K]['definition']['required'] extends true ? never : K;
1578
- }[keyof P];
1579
- /**
1580
- * Infer the properties type from property builders.
1581
- */
1582
- type InferProperties<P extends Record<string, PropertyBuilder>> = {
1583
- [K in RequiredKeys<P>]: InferPropertyType<P[K]>;
1584
- } & {
1585
- [K in OptionalKeys<P>]?: InferPropertyType<P[K]>;
1586
- };
1587
- /**
1588
- * Infer the create props (what you pass to create()).
1589
- * Same as InferProperties but allows undefined for optional fields.
1590
- */
1591
- type InferCreateProps<P extends Record<string, PropertyBuilder>> = {
1592
- [K in RequiredKeys<P>]: InferPropertyType<P[K]>;
1593
- } & {
1594
- [K in OptionalKeys<P>]?: InferPropertyType<P[K]> | undefined;
1595
- };
1596
- /**
1597
- * Infer the full Node type from property builders.
1598
- */
1599
- type InferNode<P extends Record<string, PropertyBuilder>> = {
1600
- id: string;
1601
- schemaId: SchemaIRI;
1602
- createdAt: number;
1603
- createdBy: DID;
1604
- } & InferProperties<P>;
1605
-
1606
- /**
1607
- * defineSchema - Create a schema definition with TypeScript inference.
1608
- */
1609
-
1610
- /**
1611
- * Options for defining a schema.
1612
- */
1613
- interface DefineSchemaOptions<P extends Record<string, PropertyBuilder>, A extends AuthorizationDefinition = AuthorizationDefinition> {
1614
- /** Schema name (e.g., 'Task', 'Page') */
1615
- name: string;
1616
- /** Namespace (e.g., 'xnet://xnet.fyi/') */
1617
- namespace: `xnet://${string}/`;
1618
- /**
1619
- * Schema version in semver format (e.g., '1.0.0', '2.1.0').
1620
- * Used for schema evolution and migration paths.
1621
- *
1622
- * Defaults to '1.0.0' if not specified.
1623
- *
1624
- * The version is included in the SchemaIRI:
1625
- * - Without version: `xnet://xnet.fyi/Task` (treated as @1.0.0)
1626
- * - With version: `xnet://xnet.fyi/Task@2.0.0`
1627
- */
1628
- version?: string;
1629
- /**
1630
- * Previous schema version to migrate from.
1631
- * Used to define automatic migration paths.
1632
- *
1633
- * Example: `xnet://xnet.fyi/Task@1.0.0`
1634
- */
1635
- migrateFrom?: SchemaIRI;
1636
- /** Property definitions */
1637
- properties: P;
1638
- /** Parent schema to extend */
1639
- extends?: DefinedSchema<Record<string, PropertyBuilder>>;
1640
- /**
1641
- * CRDT document type for collaborative content.
1642
- * - 'yjs': Yjs Y.Doc for rich text, canvas, etc.
1643
- * - 'automerge': Automerge document (future)
1644
- * - undefined: No document, properties only
1645
- */
1646
- document?: DocumentType;
1647
- /**
1648
- * Authorization rules for this schema.
1649
- * When present, nodes are subject to encrypted access control.
1650
- */
1651
- authorization?: A;
1652
- }
1653
- /**
1654
- * Define a schema with full TypeScript inference.
1655
- *
1656
- * @example
1657
- * ```typescript
1658
- * const TaskSchema = defineSchema({
1659
- * name: 'Task',
1660
- * namespace: 'xnet://xnet.fyi/',
1661
- * properties: {
1662
- * title: text({ required: true }),
1663
- * status: select({ options: ['todo', 'done'] as const }),
1664
- * dueDate: date({})
1665
- * },
1666
- * document: 'yjs' // Enable collaborative Y.Doc
1667
- * })
1668
- *
1669
- * type Task = InferNode<typeof TaskSchema['_properties']>
1670
- * ```
1671
- */
1672
- declare function defineSchema<P extends Record<string, PropertyBuilder>>(options: DefineSchemaOptions<P>): DefinedSchema<P>;
1673
-
1674
- /**
1675
- * Text property helper.
1676
- */
1677
-
1678
- interface TextOptions {
1679
- required?: boolean;
1680
- minLength?: number;
1681
- maxLength?: number;
1682
- pattern?: RegExp;
1683
- placeholder?: string;
1684
- }
1685
- /**
1686
- * Define a text property.
1687
- *
1688
- * @example
1689
- * ```typescript
1690
- * const schema = defineSchema({
1691
- * properties: {
1692
- * title: text({ required: true, maxLength: 500 }),
1693
- * description: text({})
1694
- * }
1695
- * })
1696
- * ```
1697
- */
1698
- declare function text(options?: TextOptions): PropertyBuilder<string>;
1699
-
1700
- /**
1701
- * Number property helper.
1702
- */
1703
-
1704
- interface NumberOptions {
1705
- required?: boolean;
1706
- min?: number;
1707
- max?: number;
1708
- integer?: boolean;
1709
- }
1710
- /**
1711
- * Define a number property.
1712
- *
1713
- * @example
1714
- * ```typescript
1715
- * const schema = defineSchema({
1716
- * properties: {
1717
- * price: number({ required: true, min: 0 }),
1718
- * quantity: number({ integer: true, min: 1 })
1719
- * }
1720
- * })
1721
- * ```
1722
- */
1723
- declare function number(options?: NumberOptions): PropertyBuilder<number>;
1724
-
1725
- /**
1726
- * Checkbox (boolean) property helper.
1727
- */
1728
-
1729
- interface CheckboxOptions {
1730
- required?: boolean;
1731
- default?: boolean;
1732
- }
1733
- /**
1734
- * Define a checkbox (boolean) property.
1735
- *
1736
- * @example
1737
- * ```typescript
1738
- * const schema = defineSchema({
1739
- * properties: {
1740
- * completed: checkbox({ default: false }),
1741
- * archived: checkbox({})
1742
- * }
1743
- * })
1744
- * ```
1745
- */
1746
- declare function checkbox(options?: CheckboxOptions): PropertyBuilder<boolean>;
1747
-
1748
- /**
1749
- * Date property helper.
1750
- * Stores dates as Unix timestamps (milliseconds).
1751
- */
1752
-
1753
- interface DateOptions {
1754
- required?: boolean;
1755
- includeTime?: boolean;
1756
- }
1757
- /**
1758
- * Define a date property.
1759
- * Dates are stored as Unix timestamps (milliseconds).
1760
- *
1761
- * @example
1762
- * ```typescript
1763
- * const schema = defineSchema({
1764
- * properties: {
1765
- * dueDate: date({ required: true }),
1766
- * reminder: date({ includeTime: true })
1767
- * }
1768
- * })
1769
- * ```
1770
- */
1771
- declare function date(options?: DateOptions): PropertyBuilder<number>;
1772
-
1773
- /**
1774
- * Date range property helper.
1775
- */
1776
-
1777
- /**
1778
- * A date range with start and optional end.
1779
- */
1780
- interface DateRange$1 {
1781
- /** Start date as ISO 8601 string */
1782
- start: string;
1783
- /** End date as ISO 8601 string (optional for ongoing ranges) */
1784
- end?: string;
1785
- }
1786
- interface DateRangeOptions {
1787
- required?: boolean;
1788
- /** Include time, not just date */
1789
- includeTime?: boolean;
1790
- }
1791
- /**
1792
- * Define a date range property.
1793
- *
1794
- * @example
1795
- * ```typescript
1796
- * const schema = defineSchema({
1797
- * properties: {
1798
- * duration: dateRange({ includeTime: true }),
1799
- * vacationPeriod: dateRange({ required: true })
1800
- * }
1801
- * })
1802
- * ```
1803
- */
1804
- declare function dateRange(options?: DateRangeOptions): PropertyBuilder<DateRange$1>;
1805
-
1806
- /**
1807
- * Select property helper with literal type inference.
1808
- */
1809
-
1810
- interface SelectOption$1 {
1811
- id: string;
1812
- name: string;
1813
- color?: string;
1814
- }
1815
- interface SelectOptions<T extends readonly SelectOption$1[]> {
1816
- options: T;
1817
- required?: boolean;
1818
- default?: T[number]['id'];
1819
- }
1820
- /**
1821
- * Define a select (single choice) property.
1822
- * Use `as const` on the options array for literal type inference.
1823
- *
1824
- * @example
1825
- * ```typescript
1826
- * const schema = defineSchema({
1827
- * properties: {
1828
- * status: select({
1829
- * options: [
1830
- * { id: 'todo', name: 'To Do', color: 'gray' },
1831
- * { id: 'done', name: 'Done', color: 'green' }
1832
- * ] as const,
1833
- * default: 'todo'
1834
- * }),
1835
- * }
1836
- * })
1837
- * // status type is 'todo' | 'done'
1838
- * ```
1839
- */
1840
- declare function select<T extends readonly SelectOption$1[]>(options: SelectOptions<T>): PropertyBuilder<T[number]['id']>;
1841
-
1842
- /**
1843
- * Multi-select property helper with literal type inference.
1844
- */
1845
-
1846
- interface MultiSelectOptions<T extends readonly SelectOption$1[]> {
1847
- options: T;
1848
- required?: boolean;
1849
- default?: T[number]['id'][];
1850
- }
1851
- /**
1852
- * Define a multi-select (multiple choice) property.
1853
- * Use `as const` on the options array for literal type inference.
1854
- *
1855
- * @example
1856
- * ```typescript
1857
- * const schema = defineSchema({
1858
- * properties: {
1859
- * tags: multiSelect({
1860
- * options: [
1861
- * { id: 'bug', name: 'Bug', color: 'red' },
1862
- * { id: 'feature', name: 'Feature', color: 'blue' },
1863
- * { id: 'docs', name: 'Documentation', color: 'green' }
1864
- * ] as const
1865
- * }),
1866
- * }
1867
- * })
1868
- * // tags type is ('bug' | 'feature' | 'docs')[]
1869
- * ```
1870
- */
1871
- declare function multiSelect<T extends readonly SelectOption$1[]>(options: MultiSelectOptions<T>): PropertyBuilder<T[number]['id'][]>;
1872
-
1873
- /**
1874
- * Person (DID reference) property helper.
1875
- */
1876
-
1877
- interface PersonOptions {
1878
- required?: boolean;
1879
- /** Allow multiple people */
1880
- multiple?: boolean;
1881
- }
1882
- /**
1883
- * Define a person reference property.
1884
- * Stores DIDs (decentralized identifiers) that reference users.
1885
- *
1886
- * @example
1887
- * ```typescript
1888
- * const schema = defineSchema({
1889
- * properties: {
1890
- * assignee: person({}),
1891
- * watchers: person({ multiple: true })
1892
- * }
1893
- * })
1894
- * ```
1895
- */
1896
- declare function person(options: PersonOptions & {
1897
- multiple: true;
1898
- }): PropertyBuilder<DID[]>;
1899
- declare function person(options?: PersonOptions): PropertyBuilder<DID>;
1900
-
1901
- /**
1902
- * Relation (node reference) property helper.
1903
- *
1904
- * Stores a reference to another node by ID. Can optionally constrain the
1905
- * target to a specific schema (typed relation) or leave it unconstrained
1906
- * (untyped relation that can reference any node).
1907
- *
1908
- * This is the xNet equivalent of Datomic's `:db.type/ref` — it tells the
1909
- * system that a property value is a node ID, enabling:
1910
- * - Temp ID resolution in transactions
1911
- * - Reverse lookups and cascade operations (future)
1912
- * - Graph traversal through relation edges (future)
1913
- */
1914
-
1915
- interface RelationOptions {
1916
- /**
1917
- * Target schema IRI to constrain this relation to a specific node type.
1918
- * When omitted, the relation can reference any node regardless of schema.
1919
- *
1920
- * @example
1921
- * // Typed: only references Task nodes
1922
- * parent: relation({ target: 'xnet://xnet.fyi/Task' })
1923
- *
1924
- * // Untyped: references any node
1925
- * target: relation({ required: true })
1926
- */
1927
- target?: SchemaIRI;
1928
- required?: boolean;
1929
- /** Allow multiple relations */
1930
- multiple?: boolean;
1931
- }
1932
- /**
1933
- * Define a relation property that references other nodes.
1934
- *
1935
- * When `target` is specified, the relation is typed — it declares that
1936
- * values should be node IDs of the given schema. When omitted, the
1937
- * relation is untyped and can reference any node.
1938
- *
1939
- * @example
1940
- * ```typescript
1941
- * const schema = defineSchema({
1942
- * properties: {
1943
- * // Typed relation (references Task nodes only)
1944
- * parent: relation({ target: 'xnet://xnet.fyi/Task' }),
1945
- * subtasks: relation({ target: 'xnet://xnet.fyi/Task', multiple: true }),
1946
- *
1947
- * // Untyped relation (references any node)
1948
- * target: relation({ required: true }),
1949
- * inReplyTo: relation({})
1950
- * }
1951
- * })
1952
- * ```
1953
- */
1954
- declare function relation(options: RelationOptions & {
1955
- multiple: true;
1956
- }): PropertyBuilder<string[]>;
1957
- declare function relation(options: RelationOptions): PropertyBuilder<string>;
1958
-
1959
- /**
1960
- * URL property helper.
1961
- */
1962
-
1963
- interface UrlOptions {
1964
- required?: boolean;
1965
- placeholder?: string;
1966
- }
1967
- /**
1968
- * Define a URL property.
1969
- *
1970
- * @example
1971
- * ```typescript
1972
- * const schema = defineSchema({
1973
- * properties: {
1974
- * website: url({ placeholder: 'https://example.com' }),
1975
- * sourceRepo: url({ required: true })
1976
- * }
1977
- * })
1978
- * ```
1979
- */
1980
- declare function url(options?: UrlOptions): PropertyBuilder<string>;
1981
-
1982
- /**
1983
- * Email property helper.
1984
- */
1985
-
1986
- interface EmailOptions {
1987
- required?: boolean;
1988
- placeholder?: string;
1989
- }
1990
- /**
1991
- * Define an email property.
1992
- *
1993
- * @example
1994
- * ```typescript
1995
- * const schema = defineSchema({
1996
- * properties: {
1997
- * email: email({ required: true, placeholder: 'user@example.com' })
1998
- * }
1999
- * })
2000
- * ```
2001
- */
2002
- declare function email(options?: EmailOptions): PropertyBuilder<string>;
2003
-
2004
- /**
2005
- * Phone property helper.
2006
- */
2007
-
2008
- interface PhoneOptions {
2009
- required?: boolean;
2010
- placeholder?: string;
2011
- }
2012
- /**
2013
- * Define a phone number property.
2014
- *
2015
- * @example
2016
- * ```typescript
2017
- * const schema = defineSchema({
2018
- * properties: {
2019
- * phone: phone({ placeholder: '+1 (555) 123-4567' })
2020
- * }
2021
- * })
2022
- * ```
2023
- */
2024
- declare function phone(options?: PhoneOptions): PropertyBuilder<string>;
2025
-
2026
- /**
2027
- * File reference property helper.
2028
- */
2029
-
2030
- /**
2031
- * File reference stored in a file property.
2032
- */
2033
- interface FileRef$1 {
2034
- /** Content-addressed ID (CID) of the file */
2035
- cid: string;
2036
- /** Original filename */
2037
- name: string;
2038
- /** MIME type */
2039
- mimeType: string;
2040
- /** File size in bytes */
2041
- size: number;
2042
- }
2043
- interface FileOptions {
2044
- required?: boolean;
2045
- /** Allow multiple files */
2046
- multiple?: boolean;
2047
- /** Accepted MIME types (e.g., ['image/*', 'application/pdf']) */
2048
- accept?: string[];
2049
- /** Maximum file size in bytes */
2050
- maxSize?: number;
2051
- }
2052
- /**
2053
- * Define a file reference property.
2054
- *
2055
- * @example
2056
- * ```typescript
2057
- * const schema = defineSchema({
2058
- * properties: {
2059
- * avatar: file({ accept: ['image/*'], maxSize: 5_000_000 }),
2060
- * attachments: file({ multiple: true })
2061
- * }
2062
- * })
2063
- * ```
2064
- */
2065
- declare function file(options: FileOptions & {
2066
- multiple: true;
2067
- }): PropertyBuilder<FileRef$1[]>;
2068
- declare function file(options?: FileOptions): PropertyBuilder<FileRef$1>;
2069
-
2070
- /**
2071
- * Created timestamp property helper.
2072
- *
2073
- * This is an auto-populated property that stores when a node was created.
2074
- * The value is set automatically at node creation time and cannot be modified.
2075
- */
2076
-
2077
- interface CreatedOptions {
2078
- /** Custom label for UI display */
2079
- label?: string;
2080
- }
2081
- /**
2082
- * Define a created timestamp property (auto-populated).
2083
- *
2084
- * The value is automatically set to Date.now() when the node is created
2085
- * and cannot be modified afterward.
2086
- *
2087
- * @example
2088
- * ```typescript
2089
- * const schema = defineSchema({
2090
- * properties: {
2091
- * createdAt: created({ label: 'Created' })
2092
- * }
2093
- * })
2094
- * // createdAt is automatically set to creation timestamp
2095
- * ```
2096
- */
2097
- declare function created(options?: CreatedOptions): PropertyBuilder<number>;
2098
-
2099
- /**
2100
- * Updated timestamp property helper.
2101
- *
2102
- * This is an auto-populated property that stores when a node was last modified.
2103
- * The value is automatically updated on each change.
2104
- */
2105
-
2106
- interface UpdatedOptions {
2107
- /** Custom label for UI display */
2108
- label?: string;
2109
- }
2110
- /**
2111
- * Define an updated timestamp property (auto-populated).
2112
- *
2113
- * The value is automatically updated to Date.now() whenever the node is modified.
2114
- *
2115
- * @example
2116
- * ```typescript
2117
- * const schema = defineSchema({
2118
- * properties: {
2119
- * updatedAt: updated({ label: 'Last Modified' })
2120
- * }
2121
- * })
2122
- * // updatedAt is automatically updated on each change
2123
- * ```
2124
- */
2125
- declare function updated(options?: UpdatedOptions): PropertyBuilder<number>;
2126
-
2127
- /**
2128
- * CreatedBy (author DID) property helper.
2129
- *
2130
- * This is an auto-populated property that stores who created a node.
2131
- * The value is set automatically at node creation time and cannot be modified.
2132
- */
2133
-
2134
- interface CreatedByOptions {
2135
- /** Custom label for UI display */
2136
- label?: string;
2137
- }
2138
- /**
2139
- * Define a createdBy (author) property (auto-populated).
2140
- *
2141
- * The value is automatically set to the creator's DID when the node is created
2142
- * and cannot be modified afterward.
2143
- *
2144
- * @example
2145
- * ```typescript
2146
- * const schema = defineSchema({
2147
- * properties: {
2148
- * author: createdBy({ label: 'Author' })
2149
- * }
2150
- * })
2151
- * // author is automatically set to the creator's DID
2152
- * ```
2153
- */
2154
- declare function createdBy(options?: CreatedByOptions): PropertyBuilder<DID>;
2155
-
2156
- declare const PageSchema: DefinedSchema<{
2157
- /** Page title */
2158
- title: PropertyBuilder<string>;
2159
- /** Emoji or icon URL */
2160
- icon: PropertyBuilder<string>;
2161
- /** Cover image */
2162
- cover: PropertyBuilder<FileRef$1>;
2163
- }>;
2164
- /**
2165
- * A Page node type (inferred from schema).
2166
- */
2167
- type Page = InferNode<(typeof PageSchema)['_properties']>;
2168
-
2169
- declare const DatabaseSchema: DefinedSchema<{
2170
- /** Database title */
2171
- title: PropertyBuilder<string>;
2172
- /** Emoji or icon URL */
2173
- icon: PropertyBuilder<string>;
2174
- /** Cover image */
2175
- cover: PropertyBuilder<FileRef$1>;
2176
- /** Default view type for this database */
2177
- defaultView: PropertyBuilder<"table" | "board" | "list" | "gallery" | "calendar" | "timeline">;
2178
- /**
2179
- * Cached row count for this database.
2180
- * Updated on row add/delete operations.
2181
- * Used for query routing decisions (local vs hub).
2182
- */
2183
- rowCount: PropertyBuilder<number>;
2184
- }>;
2185
- /**
2186
- * A Database node type (inferred from schema).
2187
- */
2188
- type Database = InferNode<(typeof DatabaseSchema)['_properties']>;
2189
-
2190
- declare const DatabaseRowSchema: DefinedSchema<{
2191
- /**
2192
- * Reference to the parent database.
2193
- * This is a typed relation that only accepts Database node IDs.
2194
- */
2195
- database: PropertyBuilder<string>;
2196
- /**
2197
- * Fractional index for row ordering.
2198
- * Uses a string-based fractional indexing scheme (like Figma/Linear)
2199
- * that allows inserting between any two rows without reindexing.
2200
- *
2201
- * @see packages/data/src/database/fractional-index.ts
2202
- */
2203
- sortKey: PropertyBuilder<string>;
2204
- }>;
2205
- /**
2206
- * A DatabaseRow node type (inferred from schema).
2207
- *
2208
- * Note: Cell values are stored as dynamic properties with `cell_` prefix,
2209
- * so they won't appear in this type. Use `fromCellProperties()` to extract
2210
- * cell values from a row's properties.
2211
- */
2212
- type DatabaseRow = InferNode<(typeof DatabaseRowSchema)['_properties']>;
2213
-
2214
- declare const TaskSchema: DefinedSchema<{
2215
- /** Task title */
2216
- title: PropertyBuilder<string>;
2217
- /** Whether the task is completed */
2218
- completed: PropertyBuilder<boolean>;
2219
- /** Task status */
2220
- status: PropertyBuilder<"done" | "todo" | "in-progress" | "cancelled">;
2221
- /** Task priority */
2222
- priority: PropertyBuilder<"low" | "medium" | "high" | "urgent">;
2223
- /** Due date */
2224
- dueDate: PropertyBuilder<number>;
2225
- /** Assigned person */
2226
- assignee: PropertyBuilder<`did:key:${string}`>;
2227
- /** Parent task (for subtasks) */
2228
- parent: PropertyBuilder<string>;
2229
- }>;
2230
- /**
2231
- * A Task node type (inferred from schema).
2232
- */
2233
- type Task = InferNode<(typeof TaskSchema)['_properties']>;
2234
-
2235
- declare const CanvasSchema: DefinedSchema<{
2236
- /** Canvas title */
2237
- title: PropertyBuilder<string>;
2238
- /** Emoji or icon URL */
2239
- icon: PropertyBuilder<string>;
2240
- }>;
2241
- /**
2242
- * A Canvas node type (inferred from schema).
2243
- */
2244
- type Canvas = InferNode<(typeof CanvasSchema)['_properties']>;
2245
-
2246
- declare const CommentSchema: DefinedSchema<{
2247
- /** The Node this comment is on (any schema - Page, Task, Database, Canvas, etc.) */
2248
- target: PropertyBuilder<string>;
2249
- /** Schema IRI of the target Node (optimization hint, not enforced) */
2250
- targetSchema: PropertyBuilder<string>;
2251
- /** Root comment ID for threading (null = this IS the root) */
2252
- inReplyTo: PropertyBuilder<string>;
2253
- /** Type of anchor point */
2254
- anchorType: PropertyBuilder<"text" | "node" | "cell" | "row" | "column" | "canvas-position" | "canvas-object">;
2255
- /** JSON-encoded anchor position data */
2256
- anchorData: PropertyBuilder<string>;
2257
- /** Comment body in GitHub-flavored markdown (stored as plain text) */
2258
- content: PropertyBuilder<string>;
2259
- /** Optional file attachments */
2260
- attachments: PropertyBuilder<FileRef$1[]>;
2261
- /** DID of user being replied to (UI hint) */
2262
- replyToUser: PropertyBuilder<`did:key:${string}`>;
2263
- /** Comment ID being referenced (for "in reply to" display) */
2264
- replyToCommentId: PropertyBuilder<string>;
2265
- /** Whether the thread has been resolved */
2266
- resolved: PropertyBuilder<boolean>;
2267
- /** Who resolved the thread */
2268
- resolvedBy: PropertyBuilder<`did:key:${string}`>;
2269
- /** When the thread was resolved */
2270
- resolvedAt: PropertyBuilder<number>;
2271
- /** Whether the comment has been edited */
2272
- edited: PropertyBuilder<boolean>;
2273
- /** When the comment was last edited */
2274
- editedAt: PropertyBuilder<number>;
2275
- createdAt: PropertyBuilder<number>;
2276
- createdBy: PropertyBuilder<`did:key:${string}`>;
2277
- }>;
2278
- /**
2279
- * A Comment node type (inferred from schema).
2280
- */
2281
- type Comment = InferNode<(typeof CommentSchema)['_properties']>;
2282
-
2283
- declare const GrantSchema: DefinedSchema<{
2284
- issuer: PropertyBuilder<`did:key:${string}`>;
2285
- grantee: PropertyBuilder<`did:key:${string}`>;
2286
- resource: PropertyBuilder<string>;
2287
- resourceSchema: PropertyBuilder<string>;
2288
- actions: PropertyBuilder<string>;
2289
- expiresAt: PropertyBuilder<number>;
2290
- revokedAt: PropertyBuilder<number>;
2291
- revokedBy: PropertyBuilder<`did:key:${string}`>;
2292
- ucanToken: PropertyBuilder<string>;
2293
- proofDepth: PropertyBuilder<number>;
2294
- parentGrantId: PropertyBuilder<string>;
2295
- }>;
2296
- type Grant = InferNode<(typeof GrantSchema)['_properties']>;
2297
-
2298
- /**
2299
- * Comment anchor types and utilities.
2300
- *
2301
- * Anchors define where a comment attaches to content. The anchorData field
2302
- * on Comment is JSON-encoded using these types.
2303
- */
2304
- type AnchorType = 'text' | 'cell' | 'row' | 'column' | 'canvas-position' | 'canvas-object' | 'node';
2305
- /**
2306
- * Text selection in the rich text editor.
2307
- * Uses Yjs RelativePosition to survive concurrent edits.
2308
- */
2309
- interface TextAnchor {
2310
- /** Yjs relative position for selection start (Base64-encoded Uint8Array) */
2311
- startRelative: string;
2312
- /** Yjs relative position for selection end */
2313
- endRelative: string;
2314
- /** The quoted text at time of comment (fallback for orphaned anchors) */
2315
- quotedText: string;
2316
- }
2317
- /** Database cell anchor */
2318
- interface CellAnchor {
2319
- /** Node ID of the database row */
2320
- rowId: string;
2321
- /** Schema property key of the column */
2322
- propertyKey: string;
2323
- }
2324
- /** Database row anchor */
2325
- interface RowAnchor {
2326
- /** Node ID of the database row */
2327
- rowId: string;
2328
- }
2329
- /** Database column anchor */
2330
- interface ColumnAnchor {
2331
- /** Schema property key of the column */
2332
- propertyKey: string;
2333
- }
2334
- /**
2335
- * Fixed canvas position (Figma-style pin).
2336
- * Does not move when canvas objects move.
2337
- */
2338
- interface CanvasPositionAnchor {
2339
- /** Canvas-space X coordinate */
2340
- x: number;
2341
- /** Canvas-space Y coordinate */
2342
- y: number;
2343
- }
2344
- /**
2345
- * Canvas object attachment (follows object movement).
2346
- */
2347
- interface CanvasObjectAnchor {
2348
- /** ID of the canvas object */
2349
- objectId: string;
2350
- /** Optional offset from object origin */
2351
- offsetX?: number;
2352
- offsetY?: number;
2353
- }
2354
- /**
2355
- * Whole-node comment (no additional positioning needed).
2356
- * The target on Comment is sufficient.
2357
- */
2358
- interface NodeAnchor {
2359
- }
2360
- /** Union type for all anchor data */
2361
- type AnchorData = TextAnchor | CellAnchor | RowAnchor | ColumnAnchor | CanvasPositionAnchor | CanvasObjectAnchor | NodeAnchor;
2362
- /**
2363
- * Encode anchor data for storage.
2364
- */
2365
- declare function encodeAnchor(data: AnchorData): string;
2366
- /**
2367
- * Decode anchor data from storage.
2368
- */
2369
- declare function decodeAnchor<T extends AnchorData>(json: string): T;
2370
- /**
2371
- * Type guard for text anchors.
2372
- */
2373
- declare function isTextAnchor(data: AnchorData): data is TextAnchor;
2374
- /**
2375
- * Type guard for cell anchors.
2376
- */
2377
- declare function isCellAnchor(data: AnchorData): data is CellAnchor;
2378
- /**
2379
- * Type guard for row anchors.
2380
- */
2381
- declare function isRowAnchor(data: AnchorData): data is RowAnchor;
2382
- /**
2383
- * Type guard for column anchors.
2384
- */
2385
- declare function isColumnAnchor(data: AnchorData): data is ColumnAnchor;
2386
- /**
2387
- * Type guard for canvas position anchors.
2388
- */
2389
- declare function isCanvasPositionAnchor(data: AnchorData): data is CanvasPositionAnchor;
2390
- /**
2391
- * Type guard for canvas object anchors.
2392
- */
2393
- declare function isCanvasObjectAnchor(data: AnchorData): data is CanvasObjectAnchor;
2394
- /**
2395
- * Type guard for node anchors (empty object).
2396
- */
2397
- declare function isNodeAnchor(data: AnchorData): data is NodeAnchor;
2398
-
2399
- /**
2400
- * Comment orphan detection utilities.
2401
- *
2402
- * An anchor is "orphaned" when its target no longer exists:
2403
- * - Text anchor: The relative positions can't be resolved (text was deleted)
2404
- * - Cell anchor: The row or column was deleted
2405
- * - Row anchor: The row was deleted
2406
- * - Column anchor: The column was deleted
2407
- * - Canvas position: Never orphans (coordinates are absolute)
2408
- * - Canvas object: The object was deleted
2409
- * - Node anchor: Never orphans (points to the target node itself)
2410
- */
2411
-
2412
- /** Why an anchor is orphaned */
2413
- type OrphanReason = 'text-deleted' | 'row-deleted' | 'column-deleted' | 'object-deleted' | 'invalid-anchor';
2414
- /** Result of orphan detection */
2415
- interface OrphanStatus {
2416
- /** Whether the anchor is orphaned */
2417
- orphaned: boolean;
2418
- /** If orphaned, the reason */
2419
- reason?: OrphanReason;
2420
- /** Human-readable context (quoted text, row title, etc.) */
2421
- context?: string;
2422
- }
2423
- /** Functions to check if entities exist */
2424
- interface OrphanResolvers {
2425
- /** Check if text anchor positions are still valid */
2426
- resolveTextAnchor?: (anchor: TextAnchor) => {
2427
- from: number;
2428
- to: number;
2429
- } | null;
2430
- /** Check if a row exists in a database */
2431
- rowExists?: (rowId: string) => boolean;
2432
- /** Check if a column/property exists in a database */
2433
- columnExists?: (propertyKey: string) => boolean;
2434
- /** Check if a canvas object exists */
2435
- objectExists?: (objectId: string) => boolean;
2436
- /** Check if a node exists */
2437
- nodeExists?: (nodeId: string) => boolean;
2438
- }
2439
- /**
2440
- * Check if a comment anchor is orphaned.
2441
- *
2442
- * @param anchorType - Type of anchor
2443
- * @param anchorData - JSON-encoded anchor data
2444
- * @param resolvers - Functions to check entity existence
2445
- * @returns OrphanStatus with orphaned flag and reason
2446
- *
2447
- * @example
2448
- * ```ts
2449
- * const status = checkOrphanStatus('text', anchorData, {
2450
- * resolveTextAnchor: (anchor) => resolveTextAnchor(editor, anchor)
2451
- * })
2452
- *
2453
- * if (status.orphaned) {
2454
- * console.log(`Comment orphaned: ${status.reason}`)
2455
- * }
2456
- * ```
2457
- */
2458
- declare function checkOrphanStatus(anchorType: AnchorType | string, anchorData: string, resolvers: OrphanResolvers): OrphanStatus;
2459
- /**
2460
- * Filter orphaned comments from a list.
2461
- *
2462
- * @param comments - Array of comments to check
2463
- * @param resolvers - Functions to check entity existence
2464
- * @returns Object with active and orphaned comments
2465
- */
2466
- declare function filterOrphanedComments<T extends {
2467
- properties: {
2468
- anchorType: string;
2469
- anchorData: string;
2470
- };
2471
- }>(comments: T[], resolvers: OrphanResolvers): {
2472
- active: T[];
2473
- orphaned: {
2474
- comment: T;
2475
- status: OrphanStatus;
2476
- }[];
2477
- };
2478
-
2479
- /**
2480
- * All built-in schemas, keyed by their IRI.
2481
- *
2482
- * Both unversioned (legacy) and versioned (@1.0.0) IRIs are supported.
2483
- * The unversioned IRIs are aliases for @1.0.0 versions.
2484
- */
2485
- declare const builtInSchemas: {
2486
- readonly 'xnet://xnet.fyi/Page@1.0.0': () => Promise<DefinedSchema<{
2487
- title: PropertyBuilder<string>;
2488
- icon: PropertyBuilder<string>;
2489
- cover: PropertyBuilder<FileRef$1>;
2490
- }>>;
2491
- readonly 'xnet://xnet.fyi/Database@1.0.0': () => Promise<DefinedSchema<{
2492
- title: PropertyBuilder<string>;
2493
- icon: PropertyBuilder<string>;
2494
- cover: PropertyBuilder<FileRef$1>;
2495
- defaultView: PropertyBuilder<"table" | "board" | "list" | "gallery" | "calendar" | "timeline">;
2496
- rowCount: PropertyBuilder<number>;
2497
- }>>;
2498
- readonly 'xnet://xnet.fyi/DatabaseRow@1.0.0': () => Promise<DefinedSchema<{
2499
- database: PropertyBuilder<string>;
2500
- sortKey: PropertyBuilder<string>;
2501
- }>>;
2502
- readonly 'xnet://xnet.fyi/Task@1.0.0': () => Promise<DefinedSchema<{
2503
- title: PropertyBuilder<string>;
2504
- completed: PropertyBuilder<boolean>;
2505
- status: PropertyBuilder<"done" | "todo" | "in-progress" | "cancelled">;
2506
- priority: PropertyBuilder<"low" | "medium" | "high" | "urgent">;
2507
- dueDate: PropertyBuilder<number>;
2508
- assignee: PropertyBuilder<`did:key:${string}`>;
2509
- parent: PropertyBuilder<string>;
2510
- }>>;
2511
- readonly 'xnet://xnet.fyi/Canvas@1.0.0': () => Promise<DefinedSchema<{
2512
- title: PropertyBuilder<string>;
2513
- icon: PropertyBuilder<string>;
2514
- }>>;
2515
- readonly 'xnet://xnet.fyi/Comment@1.0.0': () => Promise<DefinedSchema<{
2516
- target: PropertyBuilder<string>;
2517
- targetSchema: PropertyBuilder<string>;
2518
- inReplyTo: PropertyBuilder<string>;
2519
- anchorType: PropertyBuilder<"text" | "node" | "cell" | "row" | "column" | "canvas-position" | "canvas-object">;
2520
- anchorData: PropertyBuilder<string>;
2521
- content: PropertyBuilder<string>;
2522
- attachments: PropertyBuilder<FileRef$1[]>;
2523
- replyToUser: PropertyBuilder<`did:key:${string}`>;
2524
- replyToCommentId: PropertyBuilder<string>;
2525
- resolved: PropertyBuilder<boolean>;
2526
- resolvedBy: PropertyBuilder<`did:key:${string}`>;
2527
- resolvedAt: PropertyBuilder<number>;
2528
- edited: PropertyBuilder<boolean>;
2529
- editedAt: PropertyBuilder<number>;
2530
- createdAt: PropertyBuilder<number>;
2531
- createdBy: PropertyBuilder<`did:key:${string}`>;
2532
- }>>;
2533
- readonly 'xnet://xnet.fyi/Grant@1.0.0': () => Promise<DefinedSchema<{
2534
- issuer: PropertyBuilder<`did:key:${string}`>;
2535
- grantee: PropertyBuilder<`did:key:${string}`>;
2536
- resource: PropertyBuilder<string>;
2537
- resourceSchema: PropertyBuilder<string>;
2538
- actions: PropertyBuilder<string>;
2539
- expiresAt: PropertyBuilder<number>;
2540
- revokedAt: PropertyBuilder<number>;
2541
- revokedBy: PropertyBuilder<`did:key:${string}`>;
2542
- ucanToken: PropertyBuilder<string>;
2543
- proofDepth: PropertyBuilder<number>;
2544
- parentGrantId: PropertyBuilder<string>;
2545
- }>>;
2546
- readonly 'xnet://xnet.fyi/Page': () => Promise<DefinedSchema<{
2547
- title: PropertyBuilder<string>;
2548
- icon: PropertyBuilder<string>;
2549
- cover: PropertyBuilder<FileRef$1>;
2550
- }>>;
2551
- readonly 'xnet://xnet.fyi/Database': () => Promise<DefinedSchema<{
2552
- title: PropertyBuilder<string>;
2553
- icon: PropertyBuilder<string>;
2554
- cover: PropertyBuilder<FileRef$1>;
2555
- defaultView: PropertyBuilder<"table" | "board" | "list" | "gallery" | "calendar" | "timeline">;
2556
- rowCount: PropertyBuilder<number>;
2557
- }>>;
2558
- readonly 'xnet://xnet.fyi/DatabaseRow': () => Promise<DefinedSchema<{
2559
- database: PropertyBuilder<string>;
2560
- sortKey: PropertyBuilder<string>;
2561
- }>>;
2562
- readonly 'xnet://xnet.fyi/Task': () => Promise<DefinedSchema<{
2563
- title: PropertyBuilder<string>;
2564
- completed: PropertyBuilder<boolean>;
2565
- status: PropertyBuilder<"done" | "todo" | "in-progress" | "cancelled">;
2566
- priority: PropertyBuilder<"low" | "medium" | "high" | "urgent">;
2567
- dueDate: PropertyBuilder<number>;
2568
- assignee: PropertyBuilder<`did:key:${string}`>;
2569
- parent: PropertyBuilder<string>;
2570
- }>>;
2571
- readonly 'xnet://xnet.fyi/Canvas': () => Promise<DefinedSchema<{
2572
- title: PropertyBuilder<string>;
2573
- icon: PropertyBuilder<string>;
2574
- }>>;
2575
- readonly 'xnet://xnet.fyi/Comment': () => Promise<DefinedSchema<{
2576
- target: PropertyBuilder<string>;
2577
- targetSchema: PropertyBuilder<string>;
2578
- inReplyTo: PropertyBuilder<string>;
2579
- anchorType: PropertyBuilder<"text" | "node" | "cell" | "row" | "column" | "canvas-position" | "canvas-object">;
2580
- anchorData: PropertyBuilder<string>;
2581
- content: PropertyBuilder<string>;
2582
- attachments: PropertyBuilder<FileRef$1[]>;
2583
- replyToUser: PropertyBuilder<`did:key:${string}`>;
2584
- replyToCommentId: PropertyBuilder<string>;
2585
- resolved: PropertyBuilder<boolean>;
2586
- resolvedBy: PropertyBuilder<`did:key:${string}`>;
2587
- resolvedAt: PropertyBuilder<number>;
2588
- edited: PropertyBuilder<boolean>;
2589
- editedAt: PropertyBuilder<number>;
2590
- createdAt: PropertyBuilder<number>;
2591
- createdBy: PropertyBuilder<`did:key:${string}`>;
2592
- }>>;
2593
- readonly 'xnet://xnet.fyi/Grant': () => Promise<DefinedSchema<{
2594
- issuer: PropertyBuilder<`did:key:${string}`>;
2595
- grantee: PropertyBuilder<`did:key:${string}`>;
2596
- resource: PropertyBuilder<string>;
2597
- resourceSchema: PropertyBuilder<string>;
2598
- actions: PropertyBuilder<string>;
2599
- expiresAt: PropertyBuilder<number>;
2600
- revokedAt: PropertyBuilder<number>;
2601
- revokedBy: PropertyBuilder<`did:key:${string}`>;
2602
- ucanToken: PropertyBuilder<string>;
2603
- proofDepth: PropertyBuilder<number>;
2604
- parentGrantId: PropertyBuilder<string>;
2605
- }>>;
2606
- };
2607
- /**
2608
- * Built-in schema IRIs.
2609
- */
2610
- type BuiltInSchemaIRI = keyof typeof builtInSchemas;
2611
-
2612
- /**
2613
- * Schema Registry - Runtime lookup for schema definitions.
2614
- *
2615
- * The registry provides:
2616
- * - Registration of custom schemas
2617
- * - Lookup by schema IRI
2618
- * - Lazy loading of built-in schemas
2619
- * - Validation that a node matches its schema
2620
- */
2621
-
2622
- /**
2623
- * Schema Registry for runtime schema lookup.
2624
- */
2625
- declare class SchemaRegistry {
2626
- private schemas;
2627
- private loadingPromises;
2628
- private remoteResolver;
2629
- /**
2630
- * Register a custom schema.
2631
- *
2632
- * @param schema - The defined schema to register
2633
- * @throws If a schema with this IRI is already registered
2634
- */
2635
- register<P extends Record<string, PropertyBuilder>>(schema: DefinedSchema<P>): void;
2636
- /**
2637
- * Get a schema by IRI.
2638
- * For built-in schemas, this will lazy-load them on first access.
2639
- *
2640
- * @param iri - The schema IRI
2641
- * @returns The schema, or undefined if not found
2642
- */
2643
- get(iri: SchemaIRI): Promise<DefinedSchema | undefined>;
2644
- /**
2645
- * Get a schema synchronously (only works for already-loaded schemas).
2646
- *
2647
- * @param iri - The schema IRI
2648
- * @returns The schema, or undefined if not loaded
2649
- */
2650
- getSync(iri: SchemaIRI): DefinedSchema | undefined;
2651
- /**
2652
- * Check if a schema is registered (either loaded or built-in).
2653
- */
2654
- has(iri: SchemaIRI): boolean;
2655
- /**
2656
- * Check if a schema is a built-in schema.
2657
- */
2658
- isBuiltIn(iri: SchemaIRI): boolean;
2659
- /**
2660
- * Get all registered schema IRIs (including built-in).
2661
- */
2662
- getAllIRIs(): SchemaIRI[];
2663
- /**
2664
- * Unregister a custom schema.
2665
- * Built-in schemas cannot be unregistered.
2666
- *
2667
- * @param iri - The schema IRI to unregister
2668
- * @returns true if the schema was unregistered
2669
- */
2670
- unregister(iri: SchemaIRI): boolean;
2671
- /**
2672
- * Clear all custom schemas (keeps built-in schemas).
2673
- */
2674
- clear(): void;
2675
- /**
2676
- * Set a remote resolver for fetching schemas by IRI.
2677
- * When a schema is not found locally, the resolver is queried.
2678
- */
2679
- setRemoteResolver(resolver: (iri: SchemaIRI) => Promise<Schema | null>): void;
2680
- /**
2681
- * Get the version of a registered schema.
2682
- *
2683
- * @param iri - The schema IRI (versioned or unversioned)
2684
- * @returns The version string, or undefined if not found
2685
- */
2686
- getVersion(iri: SchemaIRI): string | undefined;
2687
- /**
2688
- * Get all versions of a schema by its base name.
2689
- *
2690
- * @param baseIRI - The unversioned base IRI (e.g., 'xnet://xnet.fyi/Task')
2691
- * @returns Array of versioned schemas, sorted by version
2692
- */
2693
- getAllVersions(baseIRI: SchemaIRI): Array<{
2694
- iri: SchemaIRI;
2695
- version: string;
2696
- schema: DefinedSchema;
2697
- }>;
2698
- /**
2699
- * Parse a schema IRI into its components.
2700
- */
2701
- parseIRI(iri: SchemaIRI): ParsedSchemaIRI;
2702
- }
2703
- /**
2704
- * Default global schema registry instance.
2705
- */
2706
- declare const schemaRegistry: SchemaRegistry;
2707
-
2708
- /**
2709
- * Lens Builder Utilities - Helper functions for creating schema lenses.
2710
- *
2711
- * These utilities make it easy to define common schema transformations
2712
- * like renaming properties, converting values, or adding defaults.
2713
- *
2714
- * @example
2715
- * ```typescript
2716
- * import { composeLens, rename, convert, addDefault } from '@xnetjs/data'
2717
- *
2718
- * const taskV1toV2 = composeLens(
2719
- * 'xnet://xnet.fyi/Task@1.0.0',
2720
- * 'xnet://xnet.fyi/Task@2.0.0',
2721
- * rename('complete', 'status'),
2722
- * convert('status', { true: 'done', false: 'todo' }, { done: true, todo: false }),
2723
- * addDefault('priority', 'medium')
2724
- * )
2725
- * ```
2726
- */
2727
-
2728
- /**
2729
- * Rename a property from one name to another.
2730
- *
2731
- * @example
2732
- * ```typescript
2733
- * rename('complete', 'status')
2734
- * // { complete: true } → { status: true }
2735
- * ```
2736
- */
2737
- declare function rename(from: string, to: string): LensOperation;
2738
- /**
2739
- * Convert property values using a mapping.
2740
- *
2741
- * @example
2742
- * ```typescript
2743
- * convert('status',
2744
- * { true: 'done', false: 'todo' }, // forward map
2745
- * { done: true, todo: false } // backward map
2746
- * )
2747
- * // { status: true } → { status: 'done' }
2748
- * ```
2749
- */
2750
- declare function convert<T extends string | number | boolean, U extends string | number | boolean>(prop: string, forwardMap: Record<string, U>, backwardMap: Record<string, T>): LensOperation;
2751
- /**
2752
- * Add a property with a default value if it doesn't exist.
2753
- * On backward transform, the property is removed.
2754
- *
2755
- * @example
2756
- * ```typescript
2757
- * addDefault('priority', 'medium')
2758
- * // {} → { priority: 'medium' }
2759
- * // { priority: 'high' } → { priority: 'high' } (unchanged)
2760
- * ```
2761
- */
2762
- declare function addDefault(prop: string, defaultValue: unknown): LensOperation;
2763
- /**
2764
- * Remove a property from the data.
2765
- * On backward transform, the property is restored with undefined.
2766
- *
2767
- * @example
2768
- * ```typescript
2769
- * remove('legacyField')
2770
- * // { legacyField: 'old', other: 1 } → { other: 1 }
2771
- * ```
2772
- */
2773
- declare function remove(prop: string): LensOperation;
2774
- /**
2775
- * Transform a property value using custom functions.
2776
- *
2777
- * @example
2778
- * ```typescript
2779
- * transform('count',
2780
- * (v) => v * 100, // forward: multiply by 100
2781
- * (v) => v / 100 // backward: divide by 100
2782
- * )
2783
- * // { count: 5 } → { count: 500 }
2784
- * ```
2785
- */
2786
- declare function transform(prop: string, forwardFn: (value: unknown) => unknown, backwardFn: (value: unknown) => unknown, options?: {
2787
- lossless?: boolean;
2788
- }): LensOperation;
2789
- /**
2790
- * Copy a property to a new name (keeping the original).
2791
- *
2792
- * @example
2793
- * ```typescript
2794
- * copy('name', 'displayName')
2795
- * // { name: 'John' } → { name: 'John', displayName: 'John' }
2796
- * ```
2797
- */
2798
- declare function copy(from: string, to: string): LensOperation;
2799
- /**
2800
- * Merge multiple properties into a new property.
2801
- *
2802
- * @example
2803
- * ```typescript
2804
- * merge(['firstName', 'lastName'], 'fullName', (first, last) => `${first} ${last}`)
2805
- * // { firstName: 'John', lastName: 'Doe' } → { firstName: 'John', lastName: 'Doe', fullName: 'John Doe' }
2806
- * ```
2807
- */
2808
- declare function merge(fromProps: string[], toProp: string, mergeFn: (...values: unknown[]) => unknown, splitFn?: (value: unknown) => unknown[]): LensOperation;
2809
- /**
2810
- * Apply a condition to determine whether to apply an operation.
2811
- *
2812
- * @example
2813
- * ```typescript
2814
- * when(
2815
- * (data) => data.type === 'task',
2816
- * addDefault('priority', 'medium')
2817
- * )
2818
- * ```
2819
- */
2820
- declare function when(condition: (data: Record<string, unknown>) => boolean, operation: LensOperation): LensOperation;
2821
- /**
2822
- * Compose multiple lens operations into a single SchemaLens.
2823
- *
2824
- * @example
2825
- * ```typescript
2826
- * const taskV1toV2 = composeLens(
2827
- * 'xnet://xnet.fyi/Task@1.0.0',
2828
- * 'xnet://xnet.fyi/Task@2.0.0',
2829
- * rename('complete', 'status'),
2830
- * convert('status', { true: 'done', false: 'todo' }, { done: true, todo: false }),
2831
- * addDefault('priority', 'medium')
2832
- * )
2833
- * ```
2834
- */
2835
- declare function composeLens(source: SchemaIRI, target: SchemaIRI, ...operations: LensOperation[]): SchemaLens;
2836
- /**
2837
- * Create a lens from just operations (without source/target).
2838
- * Useful for testing or when IRIs will be added later.
2839
- */
2840
- declare function createOperations(...operations: LensOperation[]): {
2841
- forward: (data: Record<string, unknown>) => Record<string, unknown>;
2842
- backward: (data: Record<string, unknown>) => Record<string, unknown>;
2843
- lossless: boolean;
2844
- };
2845
- /**
2846
- * Create an identity lens that does no transformation.
2847
- * Useful as a placeholder or for testing.
2848
- */
2849
- declare function identity(source: SchemaIRI, target: SchemaIRI): SchemaLens;
2850
-
2851
- /**
2852
- * Signed update handling for document changes
2853
- */
2854
-
2855
- /**
2856
- * Options for signing an update
2857
- */
2858
- interface SignUpdateOptions {
2859
- doc: Doc;
2860
- update: Uint8Array;
2861
- authorDID: string;
2862
- signingKey: Uint8Array;
2863
- parentHash: string;
2864
- vectorClock: VectorClock;
2865
- }
2866
- /**
2867
- * Sign a Yjs update with the author's key
2868
- */
2869
- declare function signUpdate(options: SignUpdateOptions): SignedUpdate;
2870
- /**
2871
- * Verify a signed update
2872
- */
2873
- declare function verifyUpdate(update: SignedUpdate, getPublicKey: (did: string) => Uint8Array | null): boolean;
2874
- /**
2875
- * Apply a signed update to a document
2876
- */
2877
- declare function applySignedUpdate(doc: Doc, update: SignedUpdate): void;
2878
- /**
2879
- * Capture an update during a callback and sign it
2880
- */
2881
- declare function captureUpdate(doc: Doc, authorDID: string, signingKey: Uint8Array, parentHash: string, vectorClock: VectorClock, callback: () => void): SignedUpdate | null;
2882
- /**
2883
- * Merge multiple documents into one, handling concurrent updates
2884
- */
2885
- declare function mergeDocuments(target: Doc, sources: Doc[]): void;
2886
- /**
2887
- * Get missing updates between two state vectors
2888
- */
2889
- declare function getMissingUpdates(doc: Doc, remoteStateVector: Uint8Array): Uint8Array;
2890
-
2891
- /**
2892
- * Block type registry for document content
2893
- */
2894
-
2895
- type BlockType = 'paragraph' | 'heading' | 'list' | 'todo' | 'code' | 'quote' | 'divider' | 'image' | 'embed' | 'table' | 'callout' | 'toggle';
2896
- type Block = {
2897
- id: string;
2898
- type: BlockType;
2899
- parent: string;
2900
- content: Y.XmlFragment | Y.Map<unknown>;
2901
- children: string[];
2902
- properties: Record<string, unknown>;
2903
- };
2904
- /**
2905
- * Block definition for registering new block types
2906
- */
2907
- interface BlockDefinition {
2908
- type: BlockType;
2909
- create: (id: string, parent: string) => Block;
2910
- validate: (block: Block) => boolean;
2911
- }
2912
- /**
2913
- * Register a new block type
2914
- */
2915
- declare function registerBlockType(definition: BlockDefinition): void;
2916
- /**
2917
- * Create a block of a specific type
2918
- */
2919
- declare function createBlock(type: BlockType, id: string, parent: string): Block;
2920
- /**
2921
- * Validate a block
2922
- */
2923
- declare function validateBlock(block: Block): boolean;
2924
- /**
2925
- * Get all registered block types
2926
- */
2927
- declare function getRegisteredBlockTypes(): BlockType[];
2928
-
2929
- /**
2930
- * Awareness/presence tracking for collaborative editing
2931
- */
2932
-
2933
- /**
2934
- * User presence information
2935
- */
2936
- interface UserPresence {
2937
- did: string;
2938
- name: string;
2939
- color: string;
2940
- cursor?: CursorPosition;
2941
- selection?: SelectionRange;
2942
- }
2943
- /**
2944
- * Cursor position in a document
2945
- */
2946
- interface CursorPosition {
2947
- blockId: string;
2948
- offset: number;
2949
- }
2950
- /**
2951
- * Selection range in a document
2952
- */
2953
- interface SelectionRange {
2954
- anchor: CursorPosition;
2955
- head: CursorPosition;
2956
- }
2957
- /**
2958
- * Create an awareness instance for a document
2959
- */
2960
- declare function createAwareness(doc: Doc): Awareness;
2961
- /**
2962
- * Set local user presence
2963
- */
2964
- declare function setLocalPresence(awareness: Awareness, presence: UserPresence): void;
2965
- /**
2966
- * Clear local user presence
2967
- */
2968
- declare function clearLocalPresence(awareness: Awareness): void;
2969
- /**
2970
- * Get remote user presences
2971
- */
2972
- declare function getRemotePresences(awareness: Awareness): Map<number, UserPresence>;
2973
- /**
2974
- * Get all presences including local
2975
- */
2976
- declare function getAllPresences(awareness: Awareness): Map<number, UserPresence>;
2977
- /**
2978
- * Subscribe to presence changes
2979
- */
2980
- declare function onPresenceChange(awareness: Awareness, callback: (changes: {
2981
- added: number[];
2982
- updated: number[];
2983
- removed: number[];
2984
- }) => void): () => void;
2985
- /**
2986
- * Get local client ID
2987
- */
2988
- declare function getLocalClientId(awareness: Awareness): number;
2989
- /**
2990
- * Generate a random color for user presence
2991
- */
2992
- declare function generateUserColor(): string;
2993
-
2994
- /**
2995
- * BlobService - High-level file upload and retrieval.
2996
- *
2997
- * Provides a simple API for storing and retrieving files,
2998
- * handling chunking, URL generation, and cleanup.
2999
- */
3000
-
3001
- interface BlobServiceOptions {
3002
- /** Maximum file size in bytes (default: 100MB) */
3003
- maxSize?: number;
3004
- }
3005
- declare class BlobService {
3006
- private chunkManager;
3007
- private options;
3008
- private urlCache;
3009
- constructor(chunkManager: ChunkManager, options?: BlobServiceOptions);
3010
- /**
3011
- * Upload a File and return a FileRef for storage in node properties.
3012
- */
3013
- upload(file: File): Promise<FileRef$1>;
3014
- /**
3015
- * Upload from Uint8Array (for programmatic use).
3016
- */
3017
- uploadData(data: Uint8Array, metadata: {
3018
- filename: string;
3019
- mimeType: string;
3020
- }): Promise<FileRef$1>;
3021
- /**
3022
- * Get a URL for displaying/downloading a file.
3023
- * Creates a blob URL that should be revoked when no longer needed.
3024
- */
3025
- getUrl(ref: FileRef$1): Promise<string>;
3026
- /**
3027
- * Get raw data for a file.
3028
- */
3029
- getData(ref: FileRef$1): Promise<Uint8Array | null>;
3030
- /**
3031
- * Check if a file exists locally.
3032
- */
3033
- has(ref: FileRef$1): Promise<boolean>;
3034
- /**
3035
- * Get list of missing chunk CIDs (for sync).
3036
- */
3037
- getMissingChunks(ref: FileRef$1): Promise<ContentId[]>;
3038
- /**
3039
- * Revoke a blob URL to free memory.
3040
- */
3041
- revokeUrl(ref: FileRef$1): void;
3042
- /**
3043
- * Revoke all cached blob URLs.
3044
- */
3045
- revokeAllUrls(): void;
3046
- }
3047
-
3048
- /**
3049
- * Cell value types for database rows.
3050
- *
3051
- * Cell values are stored as dynamic properties on DatabaseRow nodes,
3052
- * keyed by column ID with a `cell_` prefix to avoid collisions with
3053
- * schema-defined properties.
3054
- */
3055
- /**
3056
- * Reference to a file stored in the system.
3057
- */
3058
- interface FileRef {
3059
- /** Unique file identifier */
3060
- id: string;
3061
- /** Original file name */
3062
- name: string;
3063
- /** File size in bytes */
3064
- size: number;
3065
- /** MIME type */
3066
- type: string;
3067
- /** URL to access the file */
3068
- url: string;
3069
- }
3070
- /**
3071
- * A date range with start and end dates.
3072
- */
3073
- interface DateRange {
3074
- /** Start date (ISO 8601 string) */
3075
- start: string;
3076
- /** End date (ISO 8601 string) */
3077
- end: string;
3078
- }
3079
- /**
3080
- * All possible cell value types.
3081
- *
3082
- * - string: text, url, email, phone, select (option ID), person (DID)
3083
- * - number: number
3084
- * - boolean: checkbox
3085
- * - string (ISO 8601): date
3086
- * - DateRange: dateRange
3087
- * - string[]: multiSelect (option IDs), relation (row IDs)
3088
- * - FileRef: file
3089
- * - null: empty cell
3090
- */
3091
- type CellValue = string | number | boolean | DateRange | string[] | FileRef | null;
3092
- /**
3093
- * Prefix for cell value property keys.
3094
- * This prevents collisions with schema-defined properties like 'database' and 'sortKey'.
3095
- */
3096
- declare const CELL_PREFIX = "cell_";
3097
- /**
3098
- * Convert a column ID to a cell property key.
3099
- *
3100
- * @example
3101
- * cellKey('name') // 'cell_name'
3102
- * cellKey('status') // 'cell_status'
3103
- */
3104
- declare function cellKey(columnId: string): string;
3105
- /**
3106
- * Check if a property key is a cell value key.
3107
- *
3108
- * @example
3109
- * isCellKey('cell_name') // true
3110
- * isCellKey('database') // false
3111
- */
3112
- declare function isCellKey(key: string): boolean;
3113
- /**
3114
- * Extract the column ID from a cell property key.
3115
- *
3116
- * @example
3117
- * columnIdFromKey('cell_name') // 'name'
3118
- * columnIdFromKey('cell_status') // 'status'
3119
- */
3120
- declare function columnIdFromKey(key: string): string;
3121
- /**
3122
- * Convert a record of column ID -> value to cell key -> value.
3123
- *
3124
- * @example
3125
- * toCellProperties({ name: 'John', age: 30 })
3126
- * // { cell_name: 'John', cell_age: 30 }
3127
- */
3128
- declare function toCellProperties(cells: Record<string, CellValue>): Record<string, CellValue>;
3129
- /**
3130
- * Extract cell values from a node's properties, converting cell keys back to column IDs.
3131
- *
3132
- * @example
3133
- * fromCellProperties({ cell_name: 'John', cell_age: 30, database: 'db1' })
3134
- * // { name: 'John', age: 30 }
3135
- */
3136
- declare function fromCellProperties(properties: Record<string, unknown>): Record<string, CellValue>;
3137
- /**
3138
- * Check if a value is a valid DateRange.
3139
- */
3140
- declare function isDateRange(value: unknown): value is DateRange;
3141
- /**
3142
- * Check if a value is a valid FileRef.
3143
- */
3144
- declare function isFileRef(value: unknown): value is FileRef;
3145
- /**
3146
- * Check if a value is a valid CellValue.
3147
- */
3148
- declare function isCellValue(value: unknown): value is CellValue;
3149
-
3150
- /**
3151
- * Row CRUD operations for database rows.
3152
- *
3153
- * These functions provide a high-level API for creating, updating,
3154
- * and querying database rows. They handle:
3155
- * - Cell value storage with column ID prefixes
3156
- * - Sort key generation for row ordering
3157
- * - Database row count maintenance
3158
- */
3159
-
3160
- /**
3161
- * Options for creating a new row.
3162
- */
3163
- interface CreateRowOptions {
3164
- /** Parent database ID */
3165
- databaseId: string;
3166
- /** Initial cell values (columnId -> value) */
3167
- cells?: Record<string, CellValue>;
3168
- /**
3169
- * Insert position: before this row's sortKey.
3170
- * If neither before nor after is specified, appends to end.
3171
- */
3172
- before?: string;
3173
- /**
3174
- * Insert position: after this row's sortKey.
3175
- * If neither before nor after is specified, appends to end.
3176
- */
3177
- after?: string;
3178
- }
3179
- /**
3180
- * Options for querying rows.
3181
- */
3182
- interface QueryRowsOptions {
3183
- /** Maximum number of rows to return */
3184
- limit?: number;
3185
- /** Cursor for pagination (sortKey of last row from previous page) */
3186
- cursor?: string;
3187
- /** Property to sort by (default: 'sortKey') */
3188
- sortBy?: string;
3189
- /** Sort direction (default: 'asc') */
3190
- sortDirection?: 'asc' | 'desc';
3191
- }
3192
- /**
3193
- * Result of a row query.
3194
- */
3195
- interface QueryRowsResult {
3196
- /** The rows matching the query */
3197
- rows: DatabaseRowNode[];
3198
- /** Cursor for the next page (undefined if no more rows) */
3199
- cursor?: string;
3200
- /** Whether there are more rows after this page */
3201
- hasMore: boolean;
3202
- }
3203
- /**
3204
- * A database row node with extracted cell values.
3205
- */
3206
- interface DatabaseRowNode extends NodeState {
3207
- /** Extracted cell values (columnId -> value) */
3208
- cells: Record<string, CellValue>;
3209
- }
3210
- /**
3211
- * Create a new row in a database.
3212
- *
3213
- * @example
3214
- * ```typescript
3215
- * const rowId = await createRow(store, {
3216
- * databaseId: 'db_abc123',
3217
- * cells: {
3218
- * name: 'John Doe',
3219
- * status: 'active',
3220
- * priority: 3
3221
- * }
3222
- * })
3223
- * ```
3224
- */
3225
- declare function createRow(store: NodeStore, options: CreateRowOptions): Promise<string>;
3226
- /**
3227
- * Update a single cell value in a row.
3228
- *
3229
- * @example
3230
- * ```typescript
3231
- * await updateCell(store, rowId, 'status', 'completed')
3232
- * ```
3233
- */
3234
- declare function updateCell(store: NodeStore, rowId: string, columnId: string, value: CellValue): Promise<void>;
3235
- /**
3236
- * Update multiple cell values in a row.
3237
- *
3238
- * @example
3239
- * ```typescript
3240
- * await updateCells(store, rowId, {
3241
- * name: 'Jane Doe',
3242
- * status: 'active'
3243
- * })
3244
- * ```
3245
- */
3246
- declare function updateCells(store: NodeStore, rowId: string, cells: Record<string, CellValue>): Promise<void>;
3247
- /**
3248
- * Delete a row from a database.
3249
- *
3250
- * @example
3251
- * ```typescript
3252
- * await deleteRow(store, rowId)
3253
- * ```
3254
- */
3255
- declare function deleteRow(store: NodeStore, rowId: string): Promise<void>;
3256
- /**
3257
- * Get a single row by ID with extracted cell values.
3258
- *
3259
- * @example
3260
- * ```typescript
3261
- * const row = await getRow(store, rowId)
3262
- * console.log(row.cells.name) // 'John Doe'
3263
- * ```
3264
- */
3265
- declare function getRow(store: NodeStore, rowId: string): Promise<DatabaseRowNode | null>;
3266
- /**
3267
- * Query rows for a database with pagination.
3268
- *
3269
- * @example
3270
- * ```typescript
3271
- * const { rows, hasMore, cursor } = await queryRows(store, databaseId, {
3272
- * limit: 50
3273
- * })
3274
- *
3275
- * // Get next page
3276
- * if (hasMore) {
3277
- * const nextPage = await queryRows(store, databaseId, {
3278
- * limit: 50,
3279
- * cursor
3280
- * })
3281
- * }
3282
- * ```
3283
- */
3284
- declare function queryRows(store: NodeStore, databaseId: string, options?: QueryRowsOptions): Promise<QueryRowsResult>;
3285
- /**
3286
- * Move a row to a new position.
3287
- *
3288
- * @example
3289
- * ```typescript
3290
- * // Move row between two other rows
3291
- * await moveRow(store, rowId, {
3292
- * after: 'row_abc',
3293
- * before: 'row_xyz'
3294
- * })
3295
- * ```
3296
- */
3297
- declare function moveRow(store: NodeStore, rowId: string, position: {
3298
- before?: string;
3299
- after?: string;
3300
- }): Promise<void>;
3301
- /**
3302
- * Rebalance all rows in a database.
3303
- * Use this when sort keys get too long (> 10 chars) due to many
3304
- * insertions at the same position.
3305
- *
3306
- * @example
3307
- * ```typescript
3308
- * if (await checkNeedsRebalancing(store, databaseId)) {
3309
- * await rebalanceDatabase(store, databaseId)
3310
- * }
3311
- * ```
3312
- */
3313
- declare function rebalanceDatabase(store: NodeStore, databaseId: string): Promise<void>;
3314
- /**
3315
- * Check if a database needs rebalancing.
3316
- * Returns true if any sort key exceeds the maximum recommended length.
3317
- *
3318
- * @param maxKeyLength - Maximum key length before rebalancing (default: 10)
3319
- */
3320
- declare function checkNeedsRebalancing(store: NodeStore, databaseId: string, maxKeyLength?: number): Promise<boolean>;
3321
-
3322
- /**
3323
- * Fractional indexing for O(1) row ordering.
3324
- *
3325
- * Row order uses fractional indexing instead of array positions. Each row has
3326
- * a `sortKey` string that can be sorted lexicographically. Inserting between
3327
- * two rows generates a key that sorts between them, without updating any other rows.
3328
- *
3329
- * This approach is used by Figma, Linear, and other collaborative apps because
3330
- * it enables O(1) insert/reorder operations and works naturally with database
3331
- * queries (`ORDER BY sort_key`).
3332
- *
3333
- * @example
3334
- * ```typescript
3335
- * generateSortKey() // "a0" - first key
3336
- * generateSortKey("a0") // "a1" - append
3337
- * generateSortKey("a0", "a1") // "a0V" - insert between
3338
- * ```
3339
- */
3340
- /**
3341
- * Generate a sort key that orders between `before` and `after`.
3342
- *
3343
- * @param before - The key to sort after (or undefined for start)
3344
- * @param after - The key to sort before (or undefined for end)
3345
- * @returns A new key that sorts between before and after
3346
- *
3347
- * @example
3348
- * ```typescript
3349
- * generateSortKey() // "a0" - first key
3350
- * generateSortKey("a0") // "a1" - append
3351
- * generateSortKey(undefined, "a0") // key before a0
3352
- * generateSortKey("a0", "a1") // "a0V" - insert between
3353
- * ```
3354
- */
3355
- declare function generateSortKey(before?: string, after?: string): string;
3356
- /**
3357
- * Generate a sort key with random jitter to prevent collisions.
3358
- * Use this in high-concurrency scenarios where multiple users might
3359
- * insert at the same position simultaneously.
3360
- *
3361
- * @param before - The key to sort after (or undefined for start)
3362
- * @param after - The key to sort before (or undefined for end)
3363
- * @returns A new key with random suffix
3364
- */
3365
- declare function generateSortKeyWithJitter(before?: string, after?: string): string;
3366
- /**
3367
- * Validate that a key is well-formed.
3368
- */
3369
- declare function isValidSortKey(key: string): boolean;
3370
- /**
3371
- * Compare two sort keys.
3372
- * Returns negative if a < b, positive if a > b, 0 if equal.
3373
- *
3374
- * Uses simple string comparison (not locale-aware) to ensure
3375
- * consistent ordering across all environments.
3376
- */
3377
- declare function compareSortKeys(a: string, b: string): number;
3378
- /**
3379
- * Rebalance sort keys for a set of rows.
3380
- * Generates evenly-spaced keys for all rows.
3381
- *
3382
- * Use this when sort keys get too long (> 10 chars) due to many
3383
- * insertions at the same position.
3384
- *
3385
- * @param rowIds - Row IDs in current sorted order
3386
- * @returns Map of rowId -> new sortKey
3387
- *
3388
- * @example
3389
- * ```typescript
3390
- * const newKeys = rebalanceSortKeys(['row1', 'row2', 'row3'])
3391
- * // Map { 'row1' => '0U', 'row2' => '0q', 'row3' => '1C' }
3392
- * ```
3393
- */
3394
- declare function rebalanceSortKeys(rowIds: string[]): Map<string, string>;
3395
- /**
3396
- * Get the maximum recommended key length before rebalancing.
3397
- */
3398
- declare const MAX_KEY_LENGTH = 10;
3399
- /**
3400
- * Check if any keys in a list exceed the maximum recommended length.
3401
- */
3402
- declare function needsRebalancing(sortKeys: string[]): boolean;
3403
-
3404
- /**
3405
- * Column type definitions for database columns.
3406
- *
3407
- * Columns are stored in the database's Y.Doc as a Y.Array of Y.Maps,
3408
- * enabling CRDT-based ordering and real-time schema sync.
3409
- */
3410
- /**
3411
- * All supported column types.
3412
- */
3413
- type ColumnType = 'text' | 'number' | 'checkbox' | 'date' | 'dateRange' | 'select' | 'multiSelect' | 'person' | 'url' | 'email' | 'phone' | 'file' | 'relation' | 'rollup' | 'formula' | 'richText' | 'created' | 'createdBy' | 'updated' | 'updatedBy';
3414
- /**
3415
- * Column definition stored in the database's Y.Doc.
3416
- */
3417
- interface ColumnDefinition {
3418
- /** Unique column ID (nanoid) */
3419
- id: string;
3420
- /** Display name */
3421
- name: string;
3422
- /** Column type */
3423
- type: ColumnType;
3424
- /** Type-specific configuration */
3425
- config: ColumnConfig;
3426
- /** Width in pixels (for table view) */
3427
- width?: number;
3428
- /** Whether this is the title column */
3429
- isTitle?: boolean;
3430
- }
3431
- /**
3432
- * Union of all column configuration types.
3433
- */
3434
- type ColumnConfig = TextColumnConfig | NumberColumnConfig | SelectColumnConfig | RelationColumnConfig | RollupColumnConfig | FormulaColumnConfig | DateColumnConfig | FileColumnConfig | EmptyConfig;
3435
- /**
3436
- * Empty config for simple types with no configuration.
3437
- */
3438
- type EmptyConfig = Record<string, never>;
3439
- /**
3440
- * Text column configuration.
3441
- */
3442
- interface TextColumnConfig {
3443
- /** Maximum length (optional) */
3444
- maxLength?: number;
3445
- }
3446
- /**
3447
- * Number column configuration.
3448
- */
3449
- interface NumberColumnConfig {
3450
- /** Number format */
3451
- format?: 'number' | 'percent' | 'currency';
3452
- /** Currency code (if format is currency) */
3453
- currency?: string;
3454
- /** Decimal places */
3455
- precision?: number;
3456
- }
3457
- /**
3458
- * Select/MultiSelect column configuration.
3459
- */
3460
- interface SelectColumnConfig {
3461
- /** Available options */
3462
- options: SelectOption[];
3463
- /** Allow creating new options inline */
3464
- allowCreate?: boolean;
3465
- }
3466
- /**
3467
- * A single select option.
3468
- */
3469
- interface SelectOption {
3470
- id: string;
3471
- name: string;
3472
- color?: SelectColor;
3473
- }
3474
- /**
3475
- * Available colors for select options.
3476
- */
3477
- type SelectColor = 'gray' | 'brown' | 'orange' | 'yellow' | 'green' | 'blue' | 'purple' | 'pink' | 'red';
3478
- /**
3479
- * Relation column configuration.
3480
- */
3481
- interface RelationColumnConfig {
3482
- /** Target database ID */
3483
- targetDatabase: string;
3484
- /** Allow multiple relations */
3485
- allowMultiple?: boolean;
3486
- }
3487
- /**
3488
- * Rollup column configuration.
3489
- */
3490
- interface RollupColumnConfig {
3491
- /** Column ID of the relation to aggregate */
3492
- relationColumn: string;
3493
- /** Column ID on related rows to aggregate */
3494
- targetColumn: string;
3495
- /** Aggregation function */
3496
- aggregation: RollupAggregation;
3497
- }
3498
- /**
3499
- * Available rollup aggregation functions.
3500
- */
3501
- type RollupAggregation = 'sum' | 'avg' | 'count' | 'min' | 'max' | 'concat' | 'unique' | 'empty' | 'notEmpty' | 'percentEmpty' | 'percentNotEmpty';
3502
- /**
3503
- * Formula column configuration.
3504
- */
3505
- interface FormulaColumnConfig {
3506
- /** Formula expression with {{columnId}} references */
3507
- expression: string;
3508
- /** Result type */
3509
- resultType: 'text' | 'number' | 'date' | 'checkbox';
3510
- /** Cached dependencies (auto-computed from expression) */
3511
- dependencies?: string[];
3512
- }
3513
- /**
3514
- * Date column configuration.
3515
- */
3516
- interface DateColumnConfig {
3517
- /** Include time */
3518
- includeTime?: boolean;
3519
- /** Date format */
3520
- format?: 'full' | 'short' | 'relative';
3521
- }
3522
- /**
3523
- * File column configuration.
3524
- */
3525
- interface FileColumnConfig {
3526
- /** Accepted MIME types */
3527
- accept?: string[];
3528
- /** Allow multiple files */
3529
- allowMultiple?: boolean;
3530
- }
3531
- /**
3532
- * Check if a column type stores data in NodeStore (vs Y.Doc).
3533
- */
3534
- declare function isNodeStoreColumnType(type: ColumnType): boolean;
3535
- /**
3536
- * Check if a column type is computed (formula/rollup).
3537
- */
3538
- declare function isComputedColumnType(type: ColumnType): boolean;
3539
- /**
3540
- * Check if a column type is auto-populated.
3541
- */
3542
- declare function isAutoColumnType(type: ColumnType): boolean;
3543
- /**
3544
- * Check if a column type uses Y.Doc for storage.
3545
- */
3546
- declare function isYDocColumnType(type: ColumnType): boolean;
3547
-
3548
- /**
3549
- * Rich text cell support for database rows.
3550
- *
3551
- * Rich text cells use the row's Y.Doc for collaborative editing.
3552
- * Each rich text column gets its own Y.XmlFragment in the doc,
3553
- * which supports TipTap/ProseMirror content.
3554
- *
3555
- * Not every row needs a Y.Doc - only rows with rich text columns.
3556
- * This is determined by the database's column definitions.
3557
- */
3558
-
3559
- /**
3560
- * Prefix for rich text cell fragments in the Y.Doc.
3561
- */
3562
- declare const RICHTEXT_PREFIX = "richtext_";
3563
- /**
3564
- * Get or create a rich text cell in the row's Y.Doc.
3565
- * The XML fragment supports TipTap/ProseMirror content.
3566
- *
3567
- * @example
3568
- * ```typescript
3569
- * const doc = await store.getOrCreateDoc(rowId)
3570
- * const fragment = getRichTextCell(doc, 'notes')
3571
- *
3572
- * // Use with TipTap editor
3573
- * const editor = new Editor({
3574
- * extensions: [Collaboration.configure({ fragment })]
3575
- * })
3576
- * ```
3577
- */
3578
- declare function getRichTextCell(doc: Y.Doc, columnId: string): Y.XmlFragment;
3579
- /**
3580
- * Check if a row has any rich text content for a specific column.
3581
- */
3582
- declare function hasRichTextContent(doc: Y.Doc, columnId: string): boolean;
3583
- /**
3584
- * Check if any columns in the list are rich text columns.
3585
- * Used to decide whether to create/sync a Y.Doc for a row.
3586
- *
3587
- * @example
3588
- * ```typescript
3589
- * const columns = await getColumns(databaseId)
3590
- * if (hasRichTextColumns(columns)) {
3591
- * // Row needs a Y.Doc
3592
- * const doc = await store.getOrCreateDoc(rowId)
3593
- * }
3594
- * ```
3595
- */
3596
- declare function hasRichTextColumns(columns: ColumnDefinition[]): boolean;
3597
- /**
3598
- * Get all rich text column IDs from a list of columns.
3599
- */
3600
- declare function getRichTextColumnIds(columns: ColumnDefinition[]): string[];
3601
- /**
3602
- * Delete a rich text cell from the row's Y.Doc.
3603
- * Used when a rich text column is deleted.
3604
- */
3605
- declare function deleteRichTextCell(doc: Y.Doc, columnId: string): void;
3606
- /**
3607
- * Get plain text content from a rich text cell.
3608
- * Useful for search indexing and previews.
3609
- */
3610
- declare function getRichTextPlainText(doc: Y.Doc, columnId: string): string;
3611
-
3612
- /**
3613
- * Database Y.Doc initialization and management.
3614
- *
3615
- * The database's Y.Doc contains:
3616
- * - columns: Y.Array of column definitions
3617
- * - views: Y.Map of view configurations
3618
- * - meta: Y.Map of metadata (row count cache, etc.)
3619
- */
3620
-
3621
- /**
3622
- * Initialize the Y.Doc structure for a new database.
3623
- * Creates the columns array, views map, and meta map if they don't exist.
3624
- *
3625
- * @example
3626
- * ```typescript
3627
- * const doc = new Y.Doc()
3628
- * initializeDatabaseDoc(doc)
3629
- * ```
3630
- */
3631
- declare function initializeDatabaseDoc(doc: Y.Doc): void;
3632
- /**
3633
- * Check if a Y.Doc has been initialized as a database doc.
3634
- */
3635
- declare function isDatabaseDocInitialized(doc: Y.Doc): boolean;
3636
- /**
3637
- * Add a default title column to a new database.
3638
- * Returns the column ID.
3639
- *
3640
- * @example
3641
- * ```typescript
3642
- * const doc = new Y.Doc()
3643
- * initializeDatabaseDoc(doc)
3644
- * const titleColumnId = addDefaultTitleColumn(doc)
3645
- * ```
3646
- */
3647
- declare function addDefaultTitleColumn(doc: Y.Doc): string;
3648
- /**
3649
- * Add a default table view to a new database.
3650
- * Returns the view ID.
3651
- *
3652
- * @example
3653
- * ```typescript
3654
- * const doc = new Y.Doc()
3655
- * initializeDatabaseDoc(doc)
3656
- * addDefaultTitleColumn(doc)
3657
- * const viewId = addDefaultTableView(doc)
3658
- * ```
3659
- */
3660
- declare function addDefaultTableView(doc: Y.Doc): string;
3661
- /**
3662
- * Set up a new database with default title column and table view.
3663
- * Returns the column ID and view ID.
3664
- *
3665
- * @example
3666
- * ```typescript
3667
- * const doc = new Y.Doc()
3668
- * const { columnId, viewId } = setupNewDatabase(doc)
3669
- * ```
3670
- */
3671
- declare function setupNewDatabase(doc: Y.Doc): {
3672
- columnId: string;
3673
- viewId: string;
3674
- };
3675
- /**
3676
- * Get a metadata value from the database doc.
3677
- */
3678
- declare function getMeta<T>(doc: Y.Doc, key: string): T | undefined;
3679
- /**
3680
- * Set a metadata value in the database doc.
3681
- */
3682
- declare function setMeta<T>(doc: Y.Doc, key: string, value: T): void;
3683
- /**
3684
- * Delete a metadata value from the database doc.
3685
- */
3686
- declare function deleteMeta(doc: Y.Doc, key: string): void;
3687
-
3688
- /**
3689
- * Column CRUD operations for database columns.
3690
- *
3691
- * Columns are stored in the database's Y.Doc as a Y.Array of Y.Maps.
3692
- * This enables CRDT-based ordering and real-time schema sync.
3693
- */
3694
-
3695
- /**
3696
- * Get all columns from a database doc.
3697
- *
3698
- * @example
3699
- * ```typescript
3700
- * const columns = getColumns(doc)
3701
- * console.log(columns.map(c => c.name))
3702
- * ```
3703
- */
3704
- declare function getColumns(doc: Y.Doc): ColumnDefinition[];
3705
- /**
3706
- * Get a single column by ID.
3707
- *
3708
- * @example
3709
- * ```typescript
3710
- * const column = getColumn(doc, 'abc123')
3711
- * if (column) {
3712
- * console.log(column.name, column.type)
3713
- * }
3714
- * ```
3715
- */
3716
- declare function getColumn(doc: Y.Doc, columnId: string): ColumnDefinition | null;
3717
- /**
3718
- * Get the index of a column by ID.
3719
- * Returns -1 if not found.
3720
- */
3721
- declare function getColumnIndex(doc: Y.Doc, columnId: string): number;
3722
- /**
3723
- * Get the title column from a database doc.
3724
- * Returns null if no title column is defined.
3725
- */
3726
- declare function getTitleColumn(doc: Y.Doc): ColumnDefinition | null;
3727
- /**
3728
- * Create a new column.
3729
- * Returns the new column ID.
3730
- *
3731
- * @example
3732
- * ```typescript
3733
- * const id = createColumn(doc, {
3734
- * name: 'Status',
3735
- * type: 'select',
3736
- * config: {
3737
- * options: [
3738
- * { id: 'todo', name: 'To Do', color: 'gray' },
3739
- * { id: 'done', name: 'Done', color: 'green' }
3740
- * ]
3741
- * }
3742
- * })
3743
- * ```
3744
- */
3745
- declare function createColumn(doc: Y.Doc, definition: Omit<ColumnDefinition, 'id'>): string;
3746
- /**
3747
- * Update a column's properties.
3748
- *
3749
- * @example
3750
- * ```typescript
3751
- * updateColumn(doc, 'abc123', { name: 'Project Status' })
3752
- * ```
3753
- */
3754
- declare function updateColumn(doc: Y.Doc, columnId: string, updates: Partial<Omit<ColumnDefinition, 'id'>>): void;
3755
- /**
3756
- * Delete a column.
3757
- * Also removes the column from all views' visible columns.
3758
- *
3759
- * @example
3760
- * ```typescript
3761
- * deleteColumn(doc, 'abc123')
3762
- * ```
3763
- */
3764
- declare function deleteColumn(doc: Y.Doc, columnId: string): void;
3765
- /**
3766
- * Reorder a column to a new position.
3767
- *
3768
- * @example
3769
- * ```typescript
3770
- * // Move column to the beginning
3771
- * reorderColumn(doc, 'abc123', 0)
3772
- * ```
3773
- */
3774
- declare function reorderColumn(doc: Y.Doc, columnId: string, newIndex: number): void;
3775
- /**
3776
- * Duplicate a column.
3777
- * Returns the new column ID.
3778
- *
3779
- * @example
3780
- * ```typescript
3781
- * const newId = duplicateColumn(doc, 'abc123', 'Status (Copy)')
3782
- * ```
3783
- */
3784
- declare function duplicateColumn(doc: Y.Doc, columnId: string, newName?: string): string | null;
3785
-
3786
- /**
3787
- * View type definitions for database views.
3788
- *
3789
- * Views are stored in the database's Y.Doc as a Y.Map of view configs,
3790
- * enabling collaborative view editing and real-time sync.
3791
- */
3792
- /**
3793
- * Available view types.
3794
- */
3795
- type ViewType = 'table' | 'board' | 'list' | 'gallery' | 'calendar' | 'timeline';
3796
- /**
3797
- * View configuration stored in the database's Y.Doc.
3798
- */
3799
- interface ViewConfig {
3800
- /** Unique view ID */
3801
- id: string;
3802
- /** Display name */
3803
- name: string;
3804
- /** View type */
3805
- type: ViewType;
3806
- /** Column visibility and order */
3807
- visibleColumns: string[];
3808
- /** Per-column widths (overrides column.width) */
3809
- columnWidths?: Record<string, number>;
3810
- /** Filter configuration */
3811
- filters?: FilterGroup | null;
3812
- /** Sort configuration */
3813
- sorts?: SortConfig[];
3814
- /** Group by column ID */
3815
- groupBy?: string | null;
3816
- /** Group sort direction */
3817
- groupSort?: 'asc' | 'desc';
3818
- /** Collapsed group IDs */
3819
- collapsedGroups?: string[];
3820
- /** Cover image column ID */
3821
- coverColumn?: string;
3822
- /** Card size */
3823
- cardSize?: 'small' | 'medium' | 'large';
3824
- /** Start date column ID */
3825
- dateColumn?: string;
3826
- /** End date column ID */
3827
- endDateColumn?: string;
3828
- }
3829
- /**
3830
- * A group of filter conditions combined with AND/OR.
3831
- */
3832
- interface FilterGroup {
3833
- /** Logical operator */
3834
- operator: 'and' | 'or';
3835
- /** Conditions or nested groups */
3836
- conditions: Array<FilterCondition | FilterGroup>;
3837
- }
3838
- /**
3839
- * A single filter condition.
3840
- */
3841
- interface FilterCondition {
3842
- /** Column ID to filter on */
3843
- columnId: string;
3844
- /** Filter operator */
3845
- operator: FilterOperator;
3846
- /** Filter value (type depends on column type and operator) */
3847
- value: unknown;
3848
- }
3849
- /**
3850
- * Available filter operators.
3851
- */
3852
- type FilterOperator = 'equals' | 'notEquals' | 'contains' | 'notContains' | 'startsWith' | 'endsWith' | 'isEmpty' | 'isNotEmpty' | 'greaterThan' | 'lessThan' | 'greaterOrEqual' | 'lessOrEqual' | 'before' | 'after' | 'between' | 'hasAny' | 'hasAll' | 'hasNone';
3853
- /**
3854
- * Sort configuration for a column.
3855
- */
3856
- interface SortConfig {
3857
- /** Column ID to sort by */
3858
- columnId: string;
3859
- /** Sort direction */
3860
- direction: 'asc' | 'desc';
3861
- }
3862
- /**
3863
- * Check if a filter item is a group (vs a condition).
3864
- */
3865
- declare function isFilterGroup(item: FilterCondition | FilterGroup): item is FilterGroup;
3866
- /**
3867
- * Check if a filter item is a condition (vs a group).
3868
- */
3869
- declare function isFilterCondition(item: FilterCondition | FilterGroup): item is FilterCondition;
3870
- /**
3871
- * Check if a view type supports grouping.
3872
- */
3873
- declare function supportsGrouping(type: ViewType): boolean;
3874
- /**
3875
- * Check if a view type requires a date column.
3876
- */
3877
- declare function requiresDateColumn(type: ViewType): boolean;
3878
-
3879
- /**
3880
- * View CRUD operations for database views.
3881
- *
3882
- * Views are stored in the database's Y.Doc as a Y.Map of view configs.
3883
- * This enables collaborative view editing and real-time sync.
3884
- */
3885
-
3886
- /**
3887
- * Get all views from a database doc.
3888
- *
3889
- * @example
3890
- * ```typescript
3891
- * const views = getViews(doc)
3892
- * console.log(views.map(v => v.name))
3893
- * ```
3894
- */
3895
- declare function getViews(doc: Y.Doc): ViewConfig[];
3896
- /**
3897
- * Get a single view by ID.
3898
- *
3899
- * @example
3900
- * ```typescript
3901
- * const view = getView(doc, 'abc123')
3902
- * if (view) {
3903
- * console.log(view.name, view.type)
3904
- * }
3905
- * ```
3906
- */
3907
- declare function getView(doc: Y.Doc, viewId: string): ViewConfig | null;
3908
- /**
3909
- * Get the first view of a specific type.
3910
- */
3911
- declare function getViewByType(doc: Y.Doc, type: ViewType): ViewConfig | null;
3912
- /**
3913
- * Create a new view.
3914
- * Returns the new view ID.
3915
- *
3916
- * @example
3917
- * ```typescript
3918
- * const id = createView(doc, {
3919
- * name: 'Board View',
3920
- * type: 'board',
3921
- * visibleColumns: ['col1', 'col2'],
3922
- * groupBy: 'col1'
3923
- * })
3924
- * ```
3925
- */
3926
- declare function createView(doc: Y.Doc, config: Omit<ViewConfig, 'id'>): string;
3927
- /**
3928
- * Update a view's properties.
3929
- *
3930
- * @example
3931
- * ```typescript
3932
- * updateView(doc, 'abc123', { name: 'My Board' })
3933
- * ```
3934
- */
3935
- declare function updateView(doc: Y.Doc, viewId: string, updates: Partial<Omit<ViewConfig, 'id'>>): void;
3936
- /**
3937
- * Delete a view.
3938
- *
3939
- * @example
3940
- * ```typescript
3941
- * deleteView(doc, 'abc123')
3942
- * ```
3943
- */
3944
- declare function deleteView(doc: Y.Doc, viewId: string): void;
3945
- /**
3946
- * Duplicate a view.
3947
- * Returns the new view ID.
3948
- *
3949
- * @example
3950
- * ```typescript
3951
- * const newId = duplicateView(doc, 'abc123', 'My Copy')
3952
- * ```
3953
- */
3954
- declare function duplicateView(doc: Y.Doc, viewId: string, newName?: string): string;
3955
- /**
3956
- * Set the filters for a view.
3957
- *
3958
- * @example
3959
- * ```typescript
3960
- * setViewFilters(doc, 'view123', {
3961
- * operator: 'and',
3962
- * conditions: [
3963
- * { columnId: 'status', operator: 'equals', value: 'done' }
3964
- * ]
3965
- * })
3966
- * ```
3967
- */
3968
- declare function setViewFilters(doc: Y.Doc, viewId: string, filters: FilterGroup | null): void;
3969
- /**
3970
- * Clear all filters from a view.
3971
- */
3972
- declare function clearViewFilters(doc: Y.Doc, viewId: string): void;
3973
- /**
3974
- * Set the sorts for a view.
3975
- *
3976
- * @example
3977
- * ```typescript
3978
- * setViewSorts(doc, 'view123', [
3979
- * { columnId: 'date', direction: 'desc' },
3980
- * { columnId: 'name', direction: 'asc' }
3981
- * ])
3982
- * ```
3983
- */
3984
- declare function setViewSorts(doc: Y.Doc, viewId: string, sorts: SortConfig[]): void;
3985
- /**
3986
- * Add a sort to a view.
3987
- */
3988
- declare function addViewSort(doc: Y.Doc, viewId: string, sort: SortConfig): void;
3989
- /**
3990
- * Remove a sort from a view by column ID.
3991
- */
3992
- declare function removeViewSort(doc: Y.Doc, viewId: string, columnId: string): void;
3993
- /**
3994
- * Clear all sorts from a view.
3995
- */
3996
- declare function clearViewSorts(doc: Y.Doc, viewId: string): void;
3997
- /**
3998
- * Set the group by column for a view.
3999
- */
4000
- declare function setViewGroupBy(doc: Y.Doc, viewId: string, columnId: string | null): void;
4001
- /**
4002
- * Toggle a group's collapsed state.
4003
- */
4004
- declare function toggleGroupCollapsed$1(doc: Y.Doc, viewId: string, groupId: string): void;
4005
- /**
4006
- * Set which columns are visible in a view.
4007
- */
4008
- declare function setVisibleColumns(doc: Y.Doc, viewId: string, columnIds: string[]): void;
4009
- /**
4010
- * Show a column in a view.
4011
- */
4012
- declare function showColumn(doc: Y.Doc, viewId: string, columnId: string): void;
4013
- /**
4014
- * Hide a column in a view.
4015
- */
4016
- declare function hideColumn(doc: Y.Doc, viewId: string, columnId: string): void;
4017
- /**
4018
- * Reorder columns in a view.
4019
- */
4020
- declare function reorderViewColumns(doc: Y.Doc, viewId: string, columnId: string, newIndex: number): void;
4021
- /**
4022
- * Set a column's width in a view.
4023
- */
4024
- declare function setColumnWidth(doc: Y.Doc, viewId: string, columnId: string, width: number): void;
4025
-
4026
- /**
4027
- * Filter operators by column type.
4028
- *
4029
- * Maps each column type to the filter operators that are valid for that type.
4030
- */
4031
-
4032
- /**
4033
- * Valid filter operators for each column type.
4034
- */
4035
- declare const OPERATORS_BY_TYPE: Record<ColumnType, FilterOperator[]>;
4036
- /**
4037
- * Human-readable labels for filter operators.
4038
- */
4039
- declare const OPERATOR_LABELS: Record<FilterOperator, string>;
4040
- /**
4041
- * Get valid operators for a column type.
4042
- */
4043
- declare function getOperatorsForType(type: ColumnType): FilterOperator[];
4044
- /**
4045
- * Check if an operator is valid for a column type.
4046
- */
4047
- declare function isValidOperator(type: ColumnType, operator: FilterOperator): boolean;
4048
- /**
4049
- * Get the human-readable label for an operator.
4050
- */
4051
- declare function getOperatorLabel(operator: FilterOperator): string;
4052
- /**
4053
- * Check if an operator requires a value.
4054
- */
4055
- declare function operatorRequiresValue(operator: FilterOperator): boolean;
4056
-
4057
- /**
4058
- * Filter engine for in-memory row filtering.
4059
- *
4060
- * Evaluates filter groups and conditions against database rows.
4061
- */
4062
-
4063
- /**
4064
- * A database row with cells.
4065
- */
4066
- interface FilterableRow {
4067
- id: string;
4068
- cells: Record<string, unknown>;
4069
- }
4070
- /**
4071
- * Filter rows in memory using a filter group.
4072
- *
4073
- * @param rows - Rows to filter
4074
- * @param columns - Column definitions for type information
4075
- * @param filter - Filter group to apply (null returns all rows)
4076
- * @returns Filtered rows
4077
- *
4078
- * @example
4079
- * ```typescript
4080
- * const filtered = filterRows(rows, columns, {
4081
- * operator: 'and',
4082
- * conditions: [
4083
- * { columnId: 'status', operator: 'equals', value: 'active' }
4084
- * ]
4085
- * })
4086
- * ```
4087
- */
4088
- declare function filterRows<T extends FilterableRow>(rows: T[], columns: ColumnDefinition[], filter: FilterGroup | null): T[];
4089
- /**
4090
- * Create a simple equals filter.
4091
- */
4092
- declare function createEqualsFilter(columnId: string, value: unknown): FilterGroup;
4093
- /**
4094
- * Create a filter that matches any of the given values.
4095
- */
4096
- declare function createAnyOfFilter(columnId: string, values: unknown[]): FilterGroup;
4097
- /**
4098
- * Combine multiple filter groups with AND.
4099
- */
4100
- declare function combineFiltersAnd(filters: FilterGroup[]): FilterGroup;
4101
- /**
4102
- * Combine multiple filter groups with OR.
4103
- */
4104
- declare function combineFiltersOr(filters: FilterGroup[]): FilterGroup;
4105
-
4106
- /**
4107
- * Sort engine for in-memory row sorting.
4108
- *
4109
- * Supports multi-column sorting with type-aware comparison.
4110
- */
4111
-
4112
- /**
4113
- * A database row with cells and sortKey.
4114
- */
4115
- interface SortableRow {
4116
- id: string;
4117
- sortKey: string;
4118
- cells: Record<string, unknown>;
4119
- }
4120
- /**
4121
- * Sort rows in memory using multi-column sort config.
4122
- *
4123
- * @param rows - Rows to sort
4124
- * @param columns - Column definitions for type information
4125
- * @param sorts - Sort configurations (applied in order)
4126
- * @returns Sorted rows (new array)
4127
- *
4128
- * @example
4129
- * ```typescript
4130
- * const sorted = sortRows(rows, columns, [
4131
- * { columnId: 'status', direction: 'asc' },
4132
- * { columnId: 'name', direction: 'desc' }
4133
- * ])
4134
- * ```
4135
- */
4136
- declare function sortRows<T extends SortableRow>(rows: T[], columns: ColumnDefinition[], sorts: SortConfig[]): T[];
4137
- /**
4138
- * Create a single-column sort config.
4139
- */
4140
- declare function createSort(columnId: string, direction?: 'asc' | 'desc'): SortConfig;
4141
- /**
4142
- * Toggle sort direction.
4143
- */
4144
- declare function toggleSortDirection(direction: 'asc' | 'desc'): 'asc' | 'desc';
4145
- /**
4146
- * Add or update a sort in a sort list.
4147
- * If the column already exists, toggles direction.
4148
- * If it doesn't exist, adds it at the beginning.
4149
- */
4150
- declare function addOrToggleSort(sorts: SortConfig[], columnId: string): SortConfig[];
4151
- /**
4152
- * Remove a sort from a sort list.
4153
- */
4154
- declare function removeSort(sorts: SortConfig[], columnId: string): SortConfig[];
4155
-
4156
- /**
4157
- * Group engine for in-memory row grouping.
4158
- *
4159
- * Groups rows by column value and calculates aggregates.
4160
- */
4161
-
4162
- /**
4163
- * A database row with cells.
4164
- */
4165
- interface GroupableRow {
4166
- id: string;
4167
- cells: Record<string, unknown>;
4168
- }
4169
- /**
4170
- * Group configuration.
4171
- */
4172
- interface GroupConfig {
4173
- /** Column ID to group by */
4174
- columnId: string;
4175
- /** Sort direction for groups */
4176
- sort?: 'asc' | 'desc';
4177
- /** Collapsed group keys */
4178
- collapsedGroups?: string[];
4179
- }
4180
- /**
4181
- * A group of rows.
4182
- */
4183
- interface RowGroup<T extends GroupableRow = GroupableRow> {
4184
- /** Group key (column value or special key like '_empty') */
4185
- key: string;
4186
- /** Display label */
4187
- label: string;
4188
- /** Group color (for select columns) */
4189
- color?: string;
4190
- /** Rows in this group */
4191
- rows: T[];
4192
- /** Calculated aggregates */
4193
- aggregates: GroupAggregates;
4194
- /** Whether this group is collapsed */
4195
- collapsed?: boolean;
4196
- }
4197
- /**
4198
- * Aggregate values for a group.
4199
- */
4200
- interface GroupAggregates {
4201
- /** Row count */
4202
- count: number;
4203
- /** Sum of number columns (keyed by columnId_sum) */
4204
- [key: string]: number | undefined;
4205
- }
4206
- /**
4207
- * Group rows by a column value.
4208
- *
4209
- * @param rows - Rows to group
4210
- * @param columns - Column definitions for type information
4211
- * @param groupBy - Group configuration (null returns single group with all rows)
4212
- * @returns Array of row groups
4213
- *
4214
- * @example
4215
- * ```typescript
4216
- * const groups = groupRows(rows, columns, { columnId: 'status' })
4217
- * // Returns: [{ key: 'active', label: 'Active', rows: [...] }, ...]
4218
- * ```
4219
- */
4220
- declare function groupRows<T extends GroupableRow>(rows: T[], columns: ColumnDefinition[], groupBy: GroupConfig | null): RowGroup<T>[];
4221
- /**
4222
- * Toggle a group's collapsed state.
4223
- */
4224
- declare function toggleGroupCollapsed(collapsedGroups: string[] | undefined, groupKey: string): string[];
4225
- /**
4226
- * Expand all groups.
4227
- */
4228
- declare function expandAllGroups(): string[];
4229
- /**
4230
- * Collapse all groups.
4231
- */
4232
- declare function collapseAllGroups<T extends GroupableRow>(groups: RowGroup<T>[]): string[];
4233
-
4234
- /**
4235
- * Query pipeline for database rows.
4236
- *
4237
- * Executes filter -> sort -> group pipeline on rows.
4238
- */
4239
-
4240
- /**
4241
- * A row that can be processed by the query pipeline.
4242
- */
4243
- interface QueryableRow extends FilterableRow, SortableRow, GroupableRow {
4244
- id: string;
4245
- sortKey: string;
4246
- cells: Record<string, unknown>;
4247
- }
4248
- /**
4249
- * Query options for the pipeline.
4250
- */
4251
- interface QueryOptions {
4252
- /** Filter configuration */
4253
- filter?: FilterGroup | null;
4254
- /** Sort configurations (applied in order) */
4255
- sorts?: SortConfig[];
4256
- /** Group configuration */
4257
- groupBy?: GroupConfig | null;
4258
- /** Maximum rows to return */
4259
- limit?: number;
4260
- /** Offset for pagination */
4261
- offset?: number;
4262
- }
4263
- /**
4264
- * Result of a query execution.
4265
- */
4266
- interface QueryResult<T extends QueryableRow = QueryableRow> {
4267
- /** Grouped rows */
4268
- groups: RowGroup<T>[];
4269
- /** Total row count (before filtering) */
4270
- total: number;
4271
- /** Filtered row count (after filtering, before pagination) */
4272
- filtered: number;
4273
- }
4274
- /**
4275
- * Execute a full query pipeline: filter -> sort -> group.
4276
- *
4277
- * @param rows - Rows to query
4278
- * @param columns - Column definitions for type information
4279
- * @param options - Query options
4280
- * @returns Query result with groups, total, and filtered counts
4281
- *
4282
- * @example
4283
- * ```typescript
4284
- * const result = executeQuery(rows, columns, {
4285
- * filter: { operator: 'and', conditions: [{ columnId: 'status', operator: 'equals', value: 'active' }] },
4286
- * sorts: [{ columnId: 'name', direction: 'asc' }],
4287
- * groupBy: { columnId: 'status' }
4288
- * })
4289
- * ```
4290
- */
4291
- declare function executeQuery<T extends QueryableRow>(rows: T[], columns: ColumnDefinition[], options?: QueryOptions): QueryResult<T>;
4292
- /**
4293
- * Create a simple query with just filtering.
4294
- */
4295
- declare function createFilterQuery(filter: FilterGroup): QueryOptions;
4296
- /**
4297
- * Create a simple query with just sorting.
4298
- */
4299
- declare function createSortQuery(sorts: SortConfig[]): QueryOptions;
4300
- /**
4301
- * Create a paginated query.
4302
- */
4303
- declare function createPaginatedQuery(page: number, pageSize: number, options?: Omit<QueryOptions, 'limit' | 'offset'>): QueryOptions;
4304
- /**
4305
- * Flatten groups into a single array of rows.
4306
- */
4307
- declare function flattenGroups<T extends QueryableRow>(groups: RowGroup<T>[]): T[];
4308
- /**
4309
- * Get total row count from groups.
4310
- */
4311
- declare function getTotalFromGroups<T extends QueryableRow>(groups: RowGroup<T>[]): number;
4312
-
4313
- /**
4314
- * Database Schema Utilities
4315
- *
4316
- * Utilities for generating unique, versioned schema IRIs for databases
4317
- * and managing schema metadata stored in Y.Doc.
4318
- */
4319
-
4320
- /**
4321
- * Schema metadata stored in a database's Y.Doc.
4322
- */
4323
- interface DatabaseSchemaMetadata {
4324
- /** User-editable schema name */
4325
- name: string;
4326
- /** Optional description */
4327
- description?: string;
4328
- /** Semver version (auto-incremented) */
4329
- version: string;
4330
- /** When the database was created */
4331
- createdAt: number;
4332
- /** Last column modification time */
4333
- updatedAt: number;
4334
- }
4335
- /**
4336
- * A stored column in a database's Y.Doc.
4337
- */
4338
- interface StoredColumn {
4339
- id: string;
4340
- name: string;
4341
- type: PropertyType;
4342
- config?: Record<string, unknown>;
4343
- }
4344
- /**
4345
- * Schema version history entry.
4346
- */
4347
- interface SchemaVersionEntry {
4348
- version: string;
4349
- timestamp: number;
4350
- columns: StoredColumn[];
4351
- changeType: 'initial' | 'add' | 'update' | 'delete';
4352
- changeDescription?: string;
4353
- }
4354
- /**
4355
- * Type of version bump.
4356
- */
4357
- type VersionBumpType = 'patch' | 'minor';
4358
- /**
4359
- * Default namespace for database-defined schemas.
4360
- */
4361
- declare const DATABASE_SCHEMA_NAMESPACE = "xnet://xnet.fyi/";
4362
- /**
4363
- * Prefix for database schema IRIs.
4364
- */
4365
- declare const DATABASE_SCHEMA_PREFIX = "xnet://xnet.fyi/db/";
4366
- /**
4367
- * Generate a schema IRI from a database ID and version.
4368
- *
4369
- * @example
4370
- * buildSchemaIRI('abc123', '1.0.0') // => 'xnet://xnet.fyi/db/abc123@1.0.0'
4371
- */
4372
- declare function buildSchemaIRI(databaseId: string, version: string): SchemaIRI;
4373
- /**
4374
- * Parse a database schema IRI to extract the database ID and version.
4375
- *
4376
- * @returns { databaseId, version } or null if the IRI doesn't match the pattern
4377
- *
4378
- * @example
4379
- * parseSchemaIRI('xnet://xnet.fyi/db/abc123@1.0.0')
4380
- * // => { databaseId: 'abc123', version: '1.0.0' }
4381
- */
4382
- declare function parseDatabaseSchemaIRI(iri: string): {
4383
- databaseId: string;
4384
- version: string;
4385
- } | null;
4386
- /**
4387
- * Check if an IRI is a database-defined schema IRI.
4388
- */
4389
- declare function isDatabaseSchemaIRI(iri: string): boolean;
4390
- /**
4391
- * Parse a semver version string.
4392
- *
4393
- * @returns { major, minor, patch } or null if invalid
4394
- */
4395
- declare function parseVersion(version: string): {
4396
- major: number;
4397
- minor: number;
4398
- patch: number;
4399
- } | null;
4400
- /**
4401
- * Bump a schema version.
4402
- *
4403
- * - patch: 1.0.0 -> 1.0.1 (add column, update column, rename)
4404
- * - minor: 1.0.0 -> 1.1.0 (delete column, change column type)
4405
- *
4406
- * @example
4407
- * bumpSchemaVersion('1.0.0', 'patch') // => '1.0.1'
4408
- * bumpSchemaVersion('1.0.5', 'minor') // => '1.1.0'
4409
- */
4410
- declare function bumpSchemaVersion(current: string, type: VersionBumpType): string;
4411
- /**
4412
- * Create initial schema metadata for a new database.
4413
- */
4414
- declare function createInitialSchemaMetadata(name: string): DatabaseSchemaMetadata;
4415
- /**
4416
- * Build a Schema object from database metadata and columns.
4417
- *
4418
- * This creates a unique, versioned schema for the database.
4419
- *
4420
- * @example
4421
- * const schema = buildDatabaseSchema('db123', metadata, columns)
4422
- * // schema['@id'] === 'xnet://xnet.fyi/db/db123@1.0.0'
4423
- */
4424
- declare function buildDatabaseSchema(databaseId: string, metadata: DatabaseSchemaMetadata, columns: StoredColumn[]): Schema;
4425
- /**
4426
- * Create a schema version history entry.
4427
- */
4428
- declare function createVersionEntry(version: string, columns: StoredColumn[], changeType: SchemaVersionEntry['changeType'], changeDescription?: string): SchemaVersionEntry;
4429
- /**
4430
- * Maximum number of version history entries to keep.
4431
- */
4432
- declare const MAX_VERSION_HISTORY = 50;
4433
- /**
4434
- * Prune version history to stay within limits.
4435
- */
4436
- declare function pruneVersionHistory(history: SchemaVersionEntry[]): SchemaVersionEntry[];
4437
- /**
4438
- * Determine the version bump type for a column operation.
4439
- */
4440
- declare function getVersionBumpType(operation: 'add' | 'update' | 'rename' | 'delete' | 'changeType'): VersionBumpType;
4441
-
4442
- /**
4443
- * Database Schema Resolver
4444
- *
4445
- * Factory for creating a remote resolver that can fetch database-defined schemas
4446
- * from their Y.Doc storage.
4447
- */
4448
-
4449
- /**
4450
- * Interface for fetching Y.Doc by document ID.
4451
- * This allows the resolver to work with any sync mechanism.
4452
- */
4453
- interface DocFetcher {
4454
- /**
4455
- * Fetch a Y.Doc by its document ID.
4456
- * @returns The Y.Doc, or null if not found
4457
- */
4458
- getDoc(docId: string): Promise<Y.Doc | null>;
4459
- }
4460
- /**
4461
- * Options for creating a database schema resolver.
4462
- */
4463
- interface CreateDatabaseSchemaResolverOptions {
4464
- /** The doc fetcher to use for retrieving Y.Doc instances */
4465
- docFetcher: DocFetcher;
4466
- }
4467
- /**
4468
- * Create a remote resolver for database-defined schemas.
4469
- *
4470
- * The resolver:
4471
- * 1. Parses the IRI to extract database ID and version
4472
- * 2. Fetches the database's Y.Doc
4473
- * 3. Extracts schema metadata and columns
4474
- * 4. Builds and returns the Schema object
4475
- *
4476
- * @example
4477
- * const resolver = createDatabaseSchemaResolver({
4478
- * docFetcher: syncManager
4479
- * })
4480
- * schemaRegistry.setRemoteResolver(resolver)
4481
- */
4482
- declare function createDatabaseSchemaResolver(options: CreateDatabaseSchemaResolverOptions): (iri: SchemaIRI) => Promise<Schema | null>;
4483
- /**
4484
- * Extract schema from a loaded Y.Doc.
4485
- * Useful for direct access without going through the resolver.
4486
- *
4487
- * @param databaseId - The database node ID
4488
- * @param doc - The database's Y.Doc
4489
- * @returns The Schema object, or null if data is missing
4490
- */
4491
- declare function extractSchemaFromDoc(databaseId: string, doc: Y.Doc): Schema | null;
4492
- /**
4493
- * Get the current schema IRI for a database from its Y.Doc.
4494
- *
4495
- * @param databaseId - The database node ID
4496
- * @param doc - The database's Y.Doc
4497
- * @returns The schema IRI, or null if metadata is missing
4498
- */
4499
- declare function getSchemaIRIFromDoc(databaseId: string, doc: Y.Doc): SchemaIRI | null;
4500
-
4501
- /**
4502
- * Database Schema Clone
4503
- *
4504
- * Utilities for cloning a database schema to create a new database
4505
- * with the same structure but fresh data.
4506
- */
4507
-
4508
- /**
4509
- * Options for cloning a database schema.
4510
- */
4511
- interface CloneSchemaOptions {
4512
- /** Name for the new database (defaults to "Original Name (Copy)") */
4513
- name?: string;
4514
- /** Description for the new database */
4515
- description?: string;
4516
- /** Whether to include sample rows (default: false) */
4517
- includeRows?: boolean;
4518
- /** Maximum number of sample rows to include (default: 10) */
4519
- maxSampleRows?: number;
4520
- }
4521
- /**
4522
- * Result of cloning a database schema.
4523
- */
4524
- interface CloneSchemaResult {
4525
- /** New column definitions with remapped IDs */
4526
- columns: StoredColumn[];
4527
- /** Mapping from old column IDs to new column IDs */
4528
- columnIdMap: Map<string, string>;
4529
- /** New schema metadata */
4530
- metadata: DatabaseSchemaMetadata;
4531
- /** Remapped view configurations */
4532
- views: {
4533
- tableView?: ViewConfig;
4534
- boardView?: ViewConfig;
4535
- [key: string]: ViewConfig | undefined;
4536
- };
4537
- /** Sample rows (if includeRows was true) */
4538
- sampleRows?: Array<Record<string, unknown>>;
4539
- }
4540
- /**
4541
- * Source data for cloning.
4542
- */
4543
- interface CloneSourceData {
4544
- columns: StoredColumn[];
4545
- metadata: DatabaseSchemaMetadata;
4546
- tableView?: ViewConfig;
4547
- boardView?: ViewConfig;
4548
- rows?: Array<Record<string, unknown>>;
4549
- }
4550
- /**
4551
- * Generate new column IDs for cloning.
4552
- * Returns a map from old IDs to new IDs.
4553
- */
4554
- declare function generateColumnIdMap(columns: StoredColumn[]): Map<string, string>;
4555
- /**
4556
- * Clone columns with new IDs.
4557
- */
4558
- declare function cloneColumns(columns: StoredColumn[], idMap: Map<string, string>): StoredColumn[];
4559
- /**
4560
- * Remap column IDs in a view configuration.
4561
- * This handles all the places where column IDs are referenced.
4562
- */
4563
- declare function remapViewColumnIds(view: ViewConfig, idMap: Map<string, string>): ViewConfig;
4564
- /**
4565
- * Clone sample rows with new IDs.
4566
- */
4567
- declare function cloneSampleRows(rows: Array<Record<string, unknown>>, idMap: Map<string, string>, maxRows?: number): Array<Record<string, unknown>>;
4568
- /**
4569
- * Clone a database schema to create a new database.
4570
- *
4571
- * This creates new column definitions, remapped view configs,
4572
- * and fresh schema metadata with version 1.0.0.
4573
- *
4574
- * @param source - The source database data
4575
- * @param options - Clone options
4576
- * @returns The cloned schema data ready to be saved to a new Y.Doc
4577
- *
4578
- * @example
4579
- * ```typescript
4580
- * const source = {
4581
- * columns: getColumns(doc),
4582
- * metadata: getSchemaMetadata(doc),
4583
- * tableView: getTableView(doc),
4584
- * boardView: getBoardView(doc),
4585
- * rows: getRows(doc)
4586
- * }
4587
- *
4588
- * const result = cloneSchema(source, { name: 'My New Database' })
4589
- *
4590
- * // Apply to new Y.Doc
4591
- * newDoc.getMap('data').set('columns', result.columns)
4592
- * newDoc.getMap('data').set('schema', result.metadata)
4593
- * // etc.
4594
- * ```
4595
- */
4596
- declare function cloneSchema(source: CloneSourceData, options?: CloneSchemaOptions): CloneSchemaResult;
4597
-
4598
- export { type AnchorData, type AnchorType, type Grant$1 as AuthGrant, BlobService, type BlobServiceOptions, type BlockDefinition, type BuiltInSchemaIRI, CELL_PREFIX, type Canvas, type CanvasObjectAnchor, type CanvasPositionAnchor, CanvasSchema, type CellAnchor, type DateRange as CellDateRange, type FileRef as CellFileRef, type CellValue, type CheckboxOptions, type CloneSchemaOptions, type CloneSchemaResult, type CloneSourceData, type ColumnAnchor, type ColumnConfig, type ColumnDefinition, type SelectOption as ColumnSelectOption, type ColumnType, type Comment, CommentSchema, type ConflictResult, type ContentKeyCache, type CountNodesOptions, type CreateDatabaseSchemaResolverOptions, type CreateNodeOptions, type CreateNodeOptions$1 as CreateNodeStoreOptions, type CreateRowOptions, type CreatedByOptions, type CreatedOptions, type CursorPosition, DATABASE_SCHEMA_NAMESPACE, DATABASE_SCHEMA_PREFIX, DEFAULT_OFFLINE_POLICY, type DID, type Database, type DatabaseRow, type DatabaseRowNode, DatabaseRowSchema, DatabaseSchema, type DatabaseSchemaMetadata, type DateColumnConfig, type DateOptions, type DateRange$1 as DateRange, type DateRangeOptions, DecisionCache, DefaultPolicyEvaluator, DefaultRoleResolver, type DefineSchemaOptions, type DefinedSchema, type DocFetcher, type EmailOptions, type EmptyConfig, type FileColumnConfig, type FileOptions, type FileRef$1 as FileRef, type FilterCondition, type FilterGroup, type FilterOperator, type FilterableRow, type FormulaColumnConfig, GRANT_SCHEMA_IRI, type GetWithMigrationOptions, type Grant, GrantExpirationCleaner, GrantIndex, type GrantInput, GrantRateLimiter, GrantSchema, type GroupAggregates, type GroupConfig, type GroupableRow, type InferCreateProps, type InferNode, type InferProperties, type InferPropertyType, type LensOperation, LensRegistry, type ListNodesOptions, MAX_KEY_LENGTH, MAX_VERSION_HISTORY, MemoryNodeStorageAdapter, type MergeConflict, type MigratedNodeState, MigrationError, type MigrationInfo, type MigrationResult, type MultiSelectOptions, type Node, type NodeAnchor, type NodeChange, type NodeChangeEvent, type NodeChangeListener, type NodeContentCipher, type NodeId, type NodePayload, type NodeState, type NodeStorageAdapter, NodeStore, type NodeStoreOptions, type NumberColumnConfig, type NumberOptions, OPERATORS_BY_TYPE, OPERATOR_LABELS, type OfflineAuthPolicy, type OrphanReason, type OrphanResolvers, type OrphanStatus, type Page, PageSchema, PermissionError, type PersonOptions, type PhoneOptions, type PropertyBuilder, type PropertyDefinition, type PropertyKey, type PropertyTimestamp, type PropertyType, type QueryOptions, type QueryResult, type QueryRowsOptions, type QueryRowsResult, type QueryableRow, RICHTEXT_PREFIX, type RelationColumnConfig, type RelationOptions, type RollupAggregation, type RollupColumnConfig, type RowAnchor, type RowGroup, SQLiteNodeStorageAdapter, type Schema, type SchemaIRI, type SchemaLens, type SchemaLookup, SchemaRegistry, type SchemaVersionEntry, type SelectColor, type SelectColumnConfig, type SelectOption$1 as SelectOption, type SelectOptions, type SelectionRange, type SignUpdateOptions, type SortConfig, type SortableRow, StoreAuth, type StoreAuthAPI, StoreAuthError, type StoreAuthErrorCode, type StoreAuthKeyManager, type StoreAuthOptions, type StoreAuthStore, type StoredColumn, TEMP_ID_PREFIX, type Task, TaskSchema, type TempIdResolution, type TextAnchor, type TextColumnConfig, type TextOptions, type TransactionOperation, type TransactionResult, type UpdateNodeOptions, type UpdatedOptions, type UrlOptions, type UserPresence, type ValidationError, type ValidationResult, type VersionBumpType, type ViewConfig, type ViewType, addDefault, addDefaultTableView, addDefaultTitleColumn, addOrToggleSort, addViewSort, applySignedUpdate, buildDatabaseSchema, buildSchemaIRI, builtInSchemas, bumpSchemaVersion, captureUpdate, cellKey, checkNeedsRebalancing, checkOrphanStatus, checkbox, clearLocalPresence, clearViewFilters, clearViewSorts, cloneColumns, cloneSampleRows, cloneSchema, collapseAllGroups, columnIdFromKey, combineFiltersAnd, combineFiltersOr, compareSortKeys, composeLens, convert, copy, createAnyOfFilter, createAwareness, createBlock, createColumn, createDatabaseSchemaResolver, createEqualsFilter, createFilterQuery, createInitialSchemaMetadata, createNodeId, createOperations, createPaginatedQuery, createRow, createSchemaLookup, createSort, createSortQuery, createVersionEntry, createView, created, createdBy, date, dateRange, decodeAnchor, defineSchema, deleteColumn, deleteMeta, deleteRichTextCell, deleteRow, deleteView, duplicateColumn, duplicateView, email, encodeAnchor, executeQuery, expandAllGroups, extractSchemaFromDoc, file, filterOrphanedComments, filterRows, flattenGroups, fromCellProperties, generateColumnIdMap, generateSortKey, generateSortKeyWithJitter, generateUserColor, getAllPresences, getColumn, getColumnIndex, getColumns, getLocalClientId, getMeta, getMissingUpdates, getOperatorLabel, getOperatorsForType, getRegisteredBlockTypes, getRemotePresences, getRichTextCell, getRichTextColumnIds, getRichTextPlainText, getRow, getSchemaIRIFromDoc, getTitleColumn, getTotalFromGroups, getVersionBumpType, getView, getViewByType, getViews, groupRows, hasRichTextColumns, hasRichTextContent, hideColumn, identity, initializeDatabaseDoc, isAutoColumnType, isCanvasObjectAnchor, isCanvasPositionAnchor, isCellAnchor, isDateRange as isCellDateRange, isFileRef as isCellFileRef, isCellKey, isCellValue, isColumnAnchor, isComputedColumnType, isDatabaseDocInitialized, isDatabaseSchemaIRI, isFilterCondition, isFilterGroup, isGrantActive, isNode, isNodeAnchor, isNodeStoreColumnType, isRowAnchor, isTempId, isTextAnchor, isValidOperator, isValidSortKey, isYDocColumnType, lensRegistry, merge, mergeDocuments, mergeOfflinePolicy, moveRow, multiSelect, needsRebalancing, number, onPresenceChange, operatorRequiresValue, parseDatabaseSchemaIRI, parseVersion, person, phone, pruneVersionHistory, queryRows, rebalanceDatabase, rebalanceSortKeys, registerBlockType, relation, remapViewColumnIds, remove, removeSort, removeViewSort, rename, reorderColumn, reorderViewColumns, requiresDateColumn, resolveTempIds, schemaRegistry, select, setColumnWidth, setLocalPresence, setMeta, setViewFilters, setViewGroupBy, setViewSorts, setVisibleColumns, setupNewDatabase, showColumn, signUpdate, sortRows, supportsGrouping, text, toCellProperties, toggleGroupCollapsed$1 as toggleGroupCollapsed, toggleGroupCollapsed as toggleGroupCollapsedState, toggleSortDirection, transform, updateCell, updateCells, updateColumn, updateView, updated, url, validateBlock, verifyUpdate, when };
274
+ export { BlobService, type BlobServiceOptions, type BlockDefinition, DEFAULT_EXTERNAL_REFERENCE_IFRAME_ALLOW, EMBED_PROVIDERS, type EmbedProvider, type EmbedRegistryIframeSecurityAttributes, type EmbedRegistryPolicyDecision, type EmbedRegistryProvider, type EmbedRegistryProviderPolicy, type EvaluateEmbedRegistryPolicyInput, type EvaluateExternalReferenceEmbedPolicyInput, type ExternalReferenceDescriptor, type ExternalReferenceEmbedBlockReason, type ExternalReferenceEmbedPolicy, type ExternalReferenceEmbedPolicyDecision, type ExternalReferenceIframeSandboxToken, type ExternalReferenceKind, type ExternalReferenceMetadataFetcher, type ExternalReferenceMetadataResult, type ExternalReferenceMetadataSource, type ExternalReferenceMetadataStatus, type ExternalReferenceProvider, type ExternalReferenceResolvedMetadata, FileRef, type ResolveExternalReferenceMetadataInput, createBlock, detectEmbedProvider, evaluateEmbedRegistryPolicy, evaluateExternalReferenceEmbedPolicy, getEmbedRegistryProviderPolicies, getEmbedRegistryProviderPolicy, getExternalReferenceOEmbedEndpoint, getRegisteredBlockTypes, normalizeExternalReferenceUrl, parseEmbedUrl, parseExternalReferenceUrl, parseOpenGraphMetadata, registerBlockType, resolveExternalReferenceMetadata, validateBlock };