@haverstack/core 0.41.0 → 0.43.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 (317) hide show
  1. package/README.md +124 -64
  2. package/dist/access.d.ts +43 -47
  3. package/dist/access.d.ts.map +1 -1
  4. package/dist/access.js +66 -101
  5. package/dist/access.js.map +1 -1
  6. package/dist/{combine.d.ts → adapter/combine.d.ts} +8 -1
  7. package/dist/adapter/combine.d.ts.map +1 -0
  8. package/dist/{combine.js → adapter/combine.js} +18 -3
  9. package/dist/adapter/combine.js.map +1 -0
  10. package/dist/adapter/index.d.ts +19 -0
  11. package/dist/adapter/index.d.ts.map +1 -0
  12. package/dist/adapter/index.js +16 -0
  13. package/dist/adapter/index.js.map +1 -0
  14. package/dist/adapter/reach.d.ts +14 -0
  15. package/dist/adapter/reach.d.ts.map +1 -0
  16. package/dist/adapter/reach.js +31 -0
  17. package/dist/adapter/reach.js.map +1 -0
  18. package/dist/{sort.d.ts → adapter/sort.d.ts} +20 -20
  19. package/dist/adapter/sort.d.ts.map +1 -0
  20. package/dist/{sort.js → adapter/sort.js} +37 -27
  21. package/dist/adapter/sort.js.map +1 -0
  22. package/dist/associations/identity.d.ts +69 -0
  23. package/dist/associations/identity.d.ts.map +1 -0
  24. package/dist/associations/identity.js +174 -0
  25. package/dist/associations/identity.js.map +1 -0
  26. package/dist/associations/validation.d.ts +83 -0
  27. package/dist/associations/validation.d.ts.map +1 -0
  28. package/dist/associations/validation.js +312 -0
  29. package/dist/associations/validation.js.map +1 -0
  30. package/dist/attachment-records.d.ts +48 -0
  31. package/dist/attachment-records.d.ts.map +1 -0
  32. package/dist/attachment-records.js +52 -0
  33. package/dist/attachment-records.js.map +1 -0
  34. package/dist/collection.d.ts +178 -0
  35. package/dist/collection.d.ts.map +1 -0
  36. package/dist/collection.js +397 -0
  37. package/dist/collection.js.map +1 -0
  38. package/dist/content-match.d.ts +25 -0
  39. package/dist/content-match.d.ts.map +1 -0
  40. package/dist/content-match.js +51 -0
  41. package/dist/content-match.js.map +1 -0
  42. package/dist/content-translation.d.ts +42 -0
  43. package/dist/content-translation.d.ts.map +1 -0
  44. package/dist/content-translation.js +108 -0
  45. package/dist/content-translation.js.map +1 -0
  46. package/dist/did/did.d.ts.map +1 -0
  47. package/dist/{did.js → did/did.js} +3 -4
  48. package/dist/did/did.js.map +1 -0
  49. package/dist/{did-entry.d.ts → did/index.d.ts} +1 -1
  50. package/dist/did/index.d.ts.map +1 -0
  51. package/dist/{did-entry.js → did/index.js} +3 -3
  52. package/dist/did/index.js.map +1 -0
  53. package/dist/errors.d.ts +54 -66
  54. package/dist/errors.d.ts.map +1 -1
  55. package/dist/errors.js +58 -62
  56. package/dist/errors.js.map +1 -1
  57. package/dist/grants.d.ts +20 -44
  58. package/dist/grants.d.ts.map +1 -1
  59. package/dist/grants.js +69 -151
  60. package/dist/grants.js.map +1 -1
  61. package/dist/id.d.ts +13 -31
  62. package/dist/id.d.ts.map +1 -1
  63. package/dist/id.js +13 -31
  64. package/dist/id.js.map +1 -1
  65. package/dist/index.d.ts +13 -9
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +9 -6
  68. package/dist/index.js.map +1 -1
  69. package/dist/install.d.ts +3 -6
  70. package/dist/install.d.ts.map +1 -1
  71. package/dist/install.js +6 -10
  72. package/dist/install.js.map +1 -1
  73. package/dist/lazy.d.ts +13 -0
  74. package/dist/lazy.d.ts.map +1 -0
  75. package/dist/lazy.js +27 -0
  76. package/dist/lazy.js.map +1 -0
  77. package/dist/merge.d.ts +1 -1
  78. package/dist/merge.d.ts.map +1 -1
  79. package/dist/merge.js +6 -12
  80. package/dist/merge.js.map +1 -1
  81. package/dist/migration-steps.d.ts +102 -0
  82. package/dist/migration-steps.d.ts.map +1 -0
  83. package/dist/migration-steps.js +293 -0
  84. package/dist/migration-steps.js.map +1 -0
  85. package/dist/query-validation.d.ts +68 -121
  86. package/dist/query-validation.d.ts.map +1 -1
  87. package/dist/query-validation.js +214 -380
  88. package/dist/query-validation.js.map +1 -1
  89. package/dist/record-changes.d.ts +11 -150
  90. package/dist/record-changes.d.ts.map +1 -1
  91. package/dist/record-changes.js +14 -305
  92. package/dist/record-changes.js.map +1 -1
  93. package/dist/schema.d.ts +18 -7
  94. package/dist/schema.d.ts.map +1 -1
  95. package/dist/schema.js +59 -30
  96. package/dist/schema.js.map +1 -1
  97. package/dist/scoped-stack/authority-snapshot.d.ts +37 -0
  98. package/dist/scoped-stack/authority-snapshot.d.ts.map +1 -0
  99. package/dist/scoped-stack/authority-snapshot.js +49 -0
  100. package/dist/scoped-stack/authority-snapshot.js.map +1 -0
  101. package/dist/scoped-stack/authority.d.ts +169 -0
  102. package/dist/scoped-stack/authority.d.ts.map +1 -0
  103. package/dist/scoped-stack/authority.js +408 -0
  104. package/dist/scoped-stack/authority.js.map +1 -0
  105. package/dist/scoped-stack/family-policy.d.ts +59 -0
  106. package/dist/scoped-stack/family-policy.d.ts.map +1 -0
  107. package/dist/scoped-stack/family-policy.js +68 -0
  108. package/dist/scoped-stack/family-policy.js.map +1 -0
  109. package/dist/scoped-stack/scoped-stack.d.ts +318 -0
  110. package/dist/scoped-stack/scoped-stack.d.ts.map +1 -0
  111. package/dist/scoped-stack/scoped-stack.js +695 -0
  112. package/dist/scoped-stack/scoped-stack.js.map +1 -0
  113. package/dist/scoped-stack/subscription.d.ts +36 -0
  114. package/dist/scoped-stack/subscription.d.ts.map +1 -0
  115. package/dist/scoped-stack/subscription.js +69 -0
  116. package/dist/scoped-stack/subscription.js.map +1 -0
  117. package/dist/stack/arguments.d.ts +27 -0
  118. package/dist/stack/arguments.d.ts.map +1 -0
  119. package/dist/stack/arguments.js +53 -0
  120. package/dist/stack/arguments.js.map +1 -0
  121. package/dist/stack/attachments.d.ts +24 -0
  122. package/dist/stack/attachments.d.ts.map +1 -0
  123. package/dist/stack/attachments.js +113 -0
  124. package/dist/stack/attachments.js.map +1 -0
  125. package/dist/{changes.d.ts → stack/changes.d.ts} +30 -72
  126. package/dist/stack/changes.d.ts.map +1 -0
  127. package/dist/{changes.js → stack/changes.js} +40 -74
  128. package/dist/stack/changes.js.map +1 -0
  129. package/dist/stack/client.d.ts +247 -0
  130. package/dist/stack/client.d.ts.map +1 -0
  131. package/dist/stack/client.js +9 -0
  132. package/dist/stack/client.js.map +1 -0
  133. package/dist/stack/identity-bindings.d.ts.map +1 -0
  134. package/dist/{identity-bindings.js → stack/identity-bindings.js} +5 -14
  135. package/dist/stack/identity-bindings.js.map +1 -0
  136. package/dist/stack/install-app.d.ts +22 -0
  137. package/dist/stack/install-app.d.ts.map +1 -0
  138. package/dist/stack/install-app.js +262 -0
  139. package/dist/stack/install-app.js.map +1 -0
  140. package/dist/stack/integrity.d.ts +94 -0
  141. package/dist/stack/integrity.d.ts.map +1 -0
  142. package/dist/stack/integrity.js +268 -0
  143. package/dist/stack/integrity.js.map +1 -0
  144. package/dist/{limits.d.ts → stack/limits.d.ts} +2 -5
  145. package/dist/stack/limits.d.ts.map +1 -0
  146. package/dist/{limits.js → stack/limits.js} +3 -6
  147. package/dist/stack/limits.js.map +1 -0
  148. package/dist/stack/migrations.d.ts +59 -0
  149. package/dist/stack/migrations.d.ts.map +1 -0
  150. package/dist/stack/migrations.js +141 -0
  151. package/dist/stack/migrations.js.map +1 -0
  152. package/dist/stack/reads.d.ts +69 -0
  153. package/dist/stack/reads.d.ts.map +1 -0
  154. package/dist/stack/reads.js +141 -0
  155. package/dist/stack/reads.js.map +1 -0
  156. package/dist/stack/record-id.d.ts +35 -0
  157. package/dist/stack/record-id.d.ts.map +1 -0
  158. package/dist/stack/record-id.js +82 -0
  159. package/dist/stack/record-id.js.map +1 -0
  160. package/dist/stack/stack.d.ts +444 -0
  161. package/dist/stack/stack.d.ts.map +1 -0
  162. package/dist/stack/stack.js +1339 -0
  163. package/dist/stack/stack.js.map +1 -0
  164. package/dist/stack/system-types.d.ts +16 -0
  165. package/dist/stack/system-types.d.ts.map +1 -0
  166. package/dist/stack/system-types.js +111 -0
  167. package/dist/stack/system-types.js.map +1 -0
  168. package/dist/stack/type-grants.d.ts +20 -0
  169. package/dist/stack/type-grants.d.ts.map +1 -0
  170. package/dist/stack/type-grants.js +69 -0
  171. package/dist/stack/type-grants.js.map +1 -0
  172. package/dist/stack/write-expectation.d.ts +79 -0
  173. package/dist/stack/write-expectation.d.ts.map +1 -0
  174. package/dist/stack/write-expectation.js +71 -0
  175. package/dist/stack/write-expectation.js.map +1 -0
  176. package/dist/stack/write-gate.d.ts +23 -0
  177. package/dist/stack/write-gate.d.ts.map +1 -0
  178. package/dist/stack/write-gate.js +17 -0
  179. package/dist/stack/write-gate.js.map +1 -0
  180. package/dist/testing.d.ts +44 -33
  181. package/dist/testing.d.ts.map +1 -1
  182. package/dist/testing.js +180 -176
  183. package/dist/testing.js.map +1 -1
  184. package/dist/type-handle.d.ts +67 -78
  185. package/dist/type-handle.d.ts.map +1 -1
  186. package/dist/type-handle.js +44 -111
  187. package/dist/type-handle.js.map +1 -1
  188. package/dist/types/adapter.d.ts +282 -0
  189. package/dist/types/adapter.d.ts.map +1 -0
  190. package/dist/types/adapter.js +5 -0
  191. package/dist/types/adapter.js.map +1 -0
  192. package/dist/types/associations.d.ts +140 -0
  193. package/dist/types/associations.d.ts.map +1 -0
  194. package/dist/types/associations.js +6 -0
  195. package/dist/types/associations.js.map +1 -0
  196. package/dist/types/capabilities.d.ts +89 -0
  197. package/dist/types/capabilities.d.ts.map +1 -0
  198. package/dist/types/capabilities.js +5 -0
  199. package/dist/types/capabilities.js.map +1 -0
  200. package/dist/types/events.d.ts +150 -0
  201. package/dist/types/events.d.ts.map +1 -0
  202. package/dist/types/events.js +5 -0
  203. package/dist/types/events.js.map +1 -0
  204. package/dist/types/ids.d.ts +43 -0
  205. package/dist/types/ids.d.ts.map +1 -0
  206. package/dist/types/ids.js +5 -0
  207. package/dist/types/ids.js.map +1 -0
  208. package/dist/types/index.d.ts +19 -0
  209. package/dist/types/index.d.ts.map +1 -0
  210. package/dist/types/index.js +19 -0
  211. package/dist/types/index.js.map +1 -0
  212. package/dist/types/journal.d.ts +47 -0
  213. package/dist/types/journal.d.ts.map +1 -0
  214. package/dist/types/journal.js +5 -0
  215. package/dist/types/journal.js.map +1 -0
  216. package/dist/types/query.d.ts +185 -0
  217. package/dist/types/query.d.ts.map +1 -0
  218. package/dist/types/query.js +10 -0
  219. package/dist/types/query.js.map +1 -0
  220. package/dist/types/records.d.ts +76 -0
  221. package/dist/types/records.d.ts.map +1 -0
  222. package/dist/types/records.js +5 -0
  223. package/dist/types/records.js.map +1 -0
  224. package/dist/types/schema.d.ts +74 -0
  225. package/dist/types/schema.d.ts.map +1 -0
  226. package/dist/types/schema.js +5 -0
  227. package/dist/types/schema.js.map +1 -0
  228. package/dist/types/system.d.ts +161 -0
  229. package/dist/types/system.d.ts.map +1 -0
  230. package/dist/types/system.js +32 -0
  231. package/dist/types/system.js.map +1 -0
  232. package/dist/types/tokens.d.ts +39 -0
  233. package/dist/types/tokens.d.ts.map +1 -0
  234. package/dist/types/tokens.js +5 -0
  235. package/dist/types/tokens.js.map +1 -0
  236. package/dist/validate.d.ts +31 -70
  237. package/dist/validate.d.ts.map +1 -1
  238. package/dist/validate.js +52 -92
  239. package/dist/validate.js.map +1 -1
  240. package/dist/{attachment-download.d.ts → wire/attachment-download.d.ts} +0 -57
  241. package/dist/wire/attachment-download.d.ts.map +1 -0
  242. package/dist/{attachment-download.js → wire/attachment-download.js} +0 -61
  243. package/dist/wire/attachment-download.js.map +1 -0
  244. package/dist/{auth.d.ts → wire/auth.d.ts} +5 -8
  245. package/dist/wire/auth.d.ts.map +1 -0
  246. package/dist/{auth.js → wire/auth.js} +5 -8
  247. package/dist/wire/auth.js.map +1 -0
  248. package/dist/{wire-body.d.ts → wire/body.d.ts} +35 -12
  249. package/dist/wire/body.d.ts.map +1 -0
  250. package/dist/{wire-body.js → wire/body.js} +74 -13
  251. package/dist/wire/body.js.map +1 -0
  252. package/dist/{wire-entry.d.ts → wire/index.d.ts} +12 -12
  253. package/dist/wire/index.d.ts.map +1 -0
  254. package/dist/{wire-entry.js → wire/index.js} +13 -17
  255. package/dist/wire/index.js.map +1 -0
  256. package/dist/wire/record.d.ts +31 -0
  257. package/dist/wire/record.d.ts.map +1 -0
  258. package/dist/{wire-record.js → wire/record.js} +7 -67
  259. package/dist/wire/record.js.map +1 -0
  260. package/dist/{wire-request.d.ts → wire/request.d.ts} +32 -49
  261. package/dist/wire/request.d.ts.map +1 -0
  262. package/dist/{wire-request.js → wire/request.js} +113 -83
  263. package/dist/wire/request.js.map +1 -0
  264. package/package.json +7 -7
  265. package/dist/adapter-entry.d.ts +0 -16
  266. package/dist/adapter-entry.d.ts.map +0 -1
  267. package/dist/adapter-entry.js +0 -14
  268. package/dist/adapter-entry.js.map +0 -1
  269. package/dist/attachment-download.d.ts.map +0 -1
  270. package/dist/attachment-download.js.map +0 -1
  271. package/dist/auth.d.ts.map +0 -1
  272. package/dist/auth.js.map +0 -1
  273. package/dist/changes.d.ts.map +0 -1
  274. package/dist/changes.js.map +0 -1
  275. package/dist/combine.d.ts.map +0 -1
  276. package/dist/combine.js.map +0 -1
  277. package/dist/did-entry.d.ts.map +0 -1
  278. package/dist/did-entry.js.map +0 -1
  279. package/dist/did.d.ts.map +0 -1
  280. package/dist/did.js.map +0 -1
  281. package/dist/identity-bindings.d.ts.map +0 -1
  282. package/dist/identity-bindings.js.map +0 -1
  283. package/dist/limits.d.ts.map +0 -1
  284. package/dist/limits.js.map +0 -1
  285. package/dist/record-id.d.ts +0 -70
  286. package/dist/record-id.d.ts.map +0 -1
  287. package/dist/record-id.js +0 -127
  288. package/dist/record-id.js.map +0 -1
  289. package/dist/scoped-stack.d.ts +0 -549
  290. package/dist/scoped-stack.d.ts.map +0 -1
  291. package/dist/scoped-stack.js +0 -1301
  292. package/dist/scoped-stack.js.map +0 -1
  293. package/dist/sort.d.ts.map +0 -1
  294. package/dist/sort.js.map +0 -1
  295. package/dist/stack-reads.d.ts +0 -38
  296. package/dist/stack-reads.d.ts.map +0 -1
  297. package/dist/stack-reads.js +0 -79
  298. package/dist/stack-reads.js.map +0 -1
  299. package/dist/stack.d.ts +0 -1032
  300. package/dist/stack.d.ts.map +0 -1
  301. package/dist/stack.js +0 -2337
  302. package/dist/stack.js.map +0 -1
  303. package/dist/types.d.ts +0 -1278
  304. package/dist/types.d.ts.map +0 -1
  305. package/dist/types.js +0 -51
  306. package/dist/types.js.map +0 -1
  307. package/dist/wire-body.d.ts.map +0 -1
  308. package/dist/wire-body.js.map +0 -1
  309. package/dist/wire-entry.d.ts.map +0 -1
  310. package/dist/wire-entry.js.map +0 -1
  311. package/dist/wire-record.d.ts +0 -50
  312. package/dist/wire-record.d.ts.map +0 -1
  313. package/dist/wire-record.js.map +0 -1
  314. package/dist/wire-request.d.ts.map +0 -1
  315. package/dist/wire-request.js.map +0 -1
  316. /package/dist/{did.d.ts → did/did.d.ts} +0 -0
  317. /package/dist/{identity-bindings.d.ts → stack/identity-bindings.d.ts} +0 -0
@@ -0,0 +1,1339 @@
1
+ /**
2
+ * Stack — Core Stack Class
3
+ * -------------------------------------------------------
4
+ * The Stack class is the primary interface for apps. It sits
5
+ * on top of a StackAdapter and adds:
6
+ *
7
+ * - ID generation, and validation of every caller-supplied field
8
+ * - Type definition, schema hashing and drift detection
9
+ * - Content validation on write, and the integrity rules in integrity.ts
10
+ * - Migrations: the registry, commitMigration() and owner-driven migrateAll()
11
+ * - Version snapshots, the change journal, soft delete and purge
12
+ * - Association and permission edits, and the change feed
13
+ * - Attachments, type-level grants and app installs, whose bodies live
14
+ * beside this file
15
+ * - asEntity()/asActor(), the scoped views that enforce access control
16
+ *
17
+ * Apps should never talk to a StackAdapter directly.
18
+ */
19
+ import { generateId, generateIdForTimestamp } from '../id.js';
20
+ import { hashSchema, isCompatible, parseTypeId, baseIdOf, diffSchemas, fileRefFields, lineageProblem, } from '../schema.js';
21
+ import { dropAbsentFields, validateContent, validateContentKeys, validatePatchValues, validateReservedKeys, validateSchemaFieldNames, validateSchemaReservedNames, validateSchemaShape, } from '../validate.js';
22
+ import { applyMergePatch } from '../merge.js';
23
+ import { compareRecordedAttachments } from '../attachment-records.js';
24
+ import { stampGroupAdmin, validatePermissions } from '../access.js';
25
+ import { ChangeEmitter, RelayDelivery, PendingChange, assertSinceUsable } from './changes.js';
26
+ import { SYSTEM_TYPES } from '../types/index.js';
27
+ import { ElementSetMovedError, UseAfterCloseError, ScopeUnavailableError, InvalidAdapterError, StackConflictError, StackMigrationError, StackNotFoundError, StackBadRequestError, StackSchemaDriftError, StackValidationError, StackVersionConflictError, ARGUMENTS_INVALID, SCHEMA_INVALID, softDeletedRefusal, } from '../errors.js';
28
+ import { assertQueryCapabilities, assertValidBaseIdFilter, assertValidJournalQuery, assertValidVersionsQuery, resolveQuery, splitQuery, filtersContent, assertFamilyId, } from '../query-validation.js';
29
+ import { assertAssociationEdits, assertAuthorityAssociations, assertDataAssociations, validateAssociations, } from '../associations/validation.js';
30
+ import { applyAssociationEdits, associationDelta } from '../associations/identity.js';
31
+ import { validateGrantee, validateGrantBaseId } from '../grants.js';
32
+ import { bindingFieldsOf } from './identity-bindings.js';
33
+ import { validateInstall } from '../install.js';
34
+ import { assertAttachmentSize, assertContentSize } from './limits.js';
35
+ import { validateRecordId, validateClockField, validateIdTimestampSkew, DEFAULT_ID_TIMESTAMP_SKEW_MS, } from './record-id.js';
36
+ import { queryAllPages, lookupEntityByDid } from './reads.js';
37
+ import { contentEqual } from '../record-changes.js';
38
+ import { assertAssociationSet, assertContentPatch, assertParentArgument, assertUnlistedArgument, } from './arguments.js';
39
+ import { ScopedStack, scopeToken } from '../scoped-stack/scoped-stack.js';
40
+ import { MigrationRegistry } from './migrations.js';
41
+ import * as apps from './install-app.js';
42
+ import * as typeGrants from './type-grants.js';
43
+ import * as attachments from './attachments.js';
44
+ import { assertAttachmentImmutable, assertGroupAdminRemains, assertNoParentCycle, assertParentExists, checkAttachmentAssociationPointers, checkAttachmentMimeTypeOnCreate, checkBindingImmutable, checkBindingsOnCreate, checkBindingsOnMigrate, checkBindingsOnUpdate, checkConfigEntityIdUnchanged, } from './integrity.js';
45
+ import { systemTypeDefinitions } from './system-types.js';
46
+ import { checkFamily, checkSnapshotFamily, checkStoredVersion, WRITE_EXPECTATION, } from './write-expectation.js';
47
+ import { WRITE_GATE } from './write-gate.js';
48
+ import { createCollection } from '../collection.js';
49
+ // -------------------------------------------------------
50
+ // Supporting definitions
51
+ // -------------------------------------------------------
52
+ /**
53
+ * An Actor in the one form `Stack` stores: a `principalId` equal to the
54
+ * subject is dropped, so "acted as itself" has a single spelling, and an
55
+ * empty id is refused rather than stored as a name for nobody.
56
+ * See docs/spec/data-model.md § Actor.
57
+ */
58
+ function normalizeActor(actor) {
59
+ if (!actor)
60
+ return undefined;
61
+ for (const field of ['subjectId', 'principalId']) {
62
+ if (actor[field] === '') {
63
+ throw new StackBadRequestError(`Invalid ${field}: the empty string is not an id.`);
64
+ }
65
+ }
66
+ const { subjectId, principalId } = actor;
67
+ return principalId === undefined || principalId === subjectId
68
+ ? { subjectId }
69
+ : { subjectId, principalId };
70
+ }
71
+ /** How many Records migrateAll() reads and migrates per page. */
72
+ const MIGRATE_ALL_BATCH = 100;
73
+ /**
74
+ * One refusal for every problem a call carries, content and arguments alike,
75
+ * so a caller fixes them in one round trip. Content is itself an argument,
76
+ * so a mixed set reads "Invalid arguments"; content alone keeps its header.
77
+ */
78
+ function throwValidation(contentErrors, argumentErrors) {
79
+ if (argumentErrors.length > 0) {
80
+ throw new StackValidationError([...argumentErrors, ...contentErrors], ARGUMENTS_INVALID);
81
+ }
82
+ if (contentErrors.length > 0)
83
+ throw new StackValidationError(contentErrors);
84
+ }
85
+ /**
86
+ * Every problem `content` has as a record of `typeId`: its schema, plus the
87
+ * rules the `_grant` and `_install` families hold their content to on top
88
+ * of one. Owed by every write that sets content, whatever shape it takes.
89
+ */
90
+ function typedContentErrors(typeId, content, schema) {
91
+ return [
92
+ ...validateContent(content, schema),
93
+ ...validateGrantee(typeId, content),
94
+ ...validateGrantBaseId(typeId, content),
95
+ ...validateInstall(typeId, content),
96
+ ];
97
+ }
98
+ // -------------------------------------------------------
99
+ // Stack class
100
+ // -------------------------------------------------------
101
+ export class Stack {
102
+ adapter;
103
+ idTimestampSkewMsValue;
104
+ migrations;
105
+ /**
106
+ * Types this instance has fetched or defined, keyed by versioned id. A
107
+ * Type's schema is immutable once defined, so entries are never
108
+ * invalidated, only added; listTypes() refreshes wholesale. See
109
+ * docs/spec/data-model.md § Type cache.
110
+ */
111
+ typeCache = new Map();
112
+ /** Set by close(). See docs/spec/adapters.md § Lifecycle. */
113
+ closed = false;
114
+ /**
115
+ * Every change made through this Stack. `ScopedStack` filters this same
116
+ * stream rather than opening its own, so no scoped view can observe a
117
+ * change the stack did not emit. See docs/spec/events.md.
118
+ */
119
+ changes = new ChangeEmitter();
120
+ constructor(adapter, idTimestampSkewMsValue, migrations) {
121
+ this.adapter = adapter;
122
+ this.idTimestampSkewMsValue = idTimestampSkewMsValue;
123
+ this.migrations = migrations;
124
+ }
125
+ /**
126
+ * Announce a mutation that has already been persisted. Called after the
127
+ * adapter write resolves and before the mutating method settles, so
128
+ * `await stack.patchContent(...)` guarantees subscribers have been notified —
129
+ * and nothing about work they deferred. A handler cannot fail the write:
130
+ * there is nothing left to fail. See docs/spec/events.md § Handlers.
131
+ */
132
+ announce(change, record, at) {
133
+ this.changes.emit(change.emission(record, at));
134
+ }
135
+ /**
136
+ * The actor for a `create` journal entry, read off the record as just
137
+ * built. Create is the one journaled write that stamps the requester
138
+ * onto the row itself, so the record in hand is authoritative — and it
139
+ * carries `appId`, which ActorOptions has no field for.
140
+ */
141
+ static createActor(record) {
142
+ if (!record.updatedBy)
143
+ return undefined;
144
+ return { ...record.updatedBy, ...(record.appId !== undefined && { appId: record.appId }) };
145
+ }
146
+ async getTypeCached(id) {
147
+ const cached = this.typeCache.get(id);
148
+ if (cached)
149
+ return cached;
150
+ const type = await this.adapter.getType(id);
151
+ if (type)
152
+ this.typeCache.set(id, type);
153
+ return type;
154
+ }
155
+ /**
156
+ * Open a Stack over an adapter. Reads ownerEntityId and timezone from the adapter.
157
+ */
158
+ static async open(adapter, opts = {}) {
159
+ if (!adapter.ownerEntityId) {
160
+ throw new InvalidAdapterError('Invalid adapter: adapter has no ownerEntityId. ' +
161
+ 'Initialize the adapter with an ownerEntityId before calling Stack.open().');
162
+ }
163
+ const stack = new Stack(adapter, opts.idTimestampSkewMs === undefined ? DEFAULT_ID_TIMESTAMP_SKEW_MS : opts.idTimestampSkewMs, new MigrationRegistry(opts.migrations ?? []));
164
+ for (const type of systemTypeDefinitions())
165
+ await stack.defineType(type);
166
+ if (opts.ownerProfile) {
167
+ await stack.ensureOwnerEntity(opts.ownerProfile);
168
+ }
169
+ return stack;
170
+ }
171
+ /**
172
+ * Idempotent bootstrap for StackOptions.ownerProfile. Its probe sees every
173
+ * card the binding rules do, deleted and migrated ones included, or it
174
+ * would mint one they then refuse and the stack would not reopen.
175
+ * See docs/spec/identity.md § Entity.
176
+ */
177
+ async ensureOwnerEntity(profile) {
178
+ const entityTypeId = `${SYSTEM_TYPES.ENTITY}@1`;
179
+ const existing = await this.getEntityByDid(this.ownerEntityId);
180
+ if (existing)
181
+ return;
182
+ await this.create(entityTypeId, {
183
+ did: this.ownerEntityId,
184
+ name: profile.name,
185
+ ...(profile.handle && { handle: profile.handle }),
186
+ });
187
+ }
188
+ get ownerEntityId() {
189
+ return this.adapter.ownerEntityId;
190
+ }
191
+ async getEntityByDid(did) {
192
+ return lookupEntityByDid((q) => this.query(q), did, filtersContent(this.capabilities), true);
193
+ }
194
+ async getOwnerEntity() {
195
+ return this.getEntityByDid(this.ownerEntityId);
196
+ }
197
+ get timezone() {
198
+ return this.adapter.timezone;
199
+ }
200
+ get capabilities() {
201
+ return this.adapter.capabilities;
202
+ }
203
+ /**
204
+ * Get a permission-scoped view of this Stack, as if requests came from
205
+ * the given entity acting as itself (null = anonymous). Plain Stack
206
+ * methods are unscoped; use asEntity() when one Stack serves multiple,
207
+ * possibly untrusted, entities. See
208
+ * docs/spec/access-control.md § Enforcement: Stack.asEntity().
209
+ */
210
+ asEntity(entityId) {
211
+ return entityId === null ? this.scope(null, null) : this.asActor({ subjectId: entityId });
212
+ }
213
+ /**
214
+ * Scope to an Actor — a delegated app acting for its user, or a
215
+ * TokenSession as StackTokenStore.lookupToken() returns it, which is what
216
+ * a server should pass at its request boundary.
217
+ * See docs/spec/access-control.md § Delegation: principal and subject.
218
+ */
219
+ asActor(actor) {
220
+ const { subjectId, principalId = subjectId } = normalizeActor(actor);
221
+ return this.scope(principalId, subjectId);
222
+ }
223
+ /**
224
+ * A scoped view needs a stack that owns its storage: one whose adapter
225
+ * queries within a reach and relays no changes from elsewhere. A
226
+ * server-backed stack is scoped by the session that opened it instead.
227
+ * See docs/spec/access-control.md § Enforcement: Stack.asEntity().
228
+ */
229
+ scope(principalId, subjectId) {
230
+ this.assertOpen();
231
+ const queryReadable = this.adapter.queryReadable?.bind(this.adapter);
232
+ if (!queryReadable) {
233
+ throw new ScopeUnavailableError('This stack cannot be scoped: its adapter does not implement queryReadable(), so a ' +
234
+ "query could not be kept to the requester's reach. Every local adapter must; a " +
235
+ 'server-backed stack is scoped by opening it with the session you mean.');
236
+ }
237
+ if (this.relaysChanges) {
238
+ throw new ScopeUnavailableError('This stack cannot be scoped: it relays changes made elsewhere, whose frames were ' +
239
+ 'scoped by the session that opened the feed. Open it with the session you mean.');
240
+ }
241
+ return new ScopedStack(scopeToken, {
242
+ stack: this,
243
+ principalId,
244
+ subjectId,
245
+ idTimestampSkewMs: this.idTimestampSkewMsValue,
246
+ adapter: this.adapter,
247
+ changes: this.changes,
248
+ assertOpen: () => this.assertOpen(),
249
+ migrations: this.migrations,
250
+ queryReadable: (split, reach) => this.dispatchQuery(split, (resolved) => queryReadable(resolved, reach)),
251
+ });
252
+ }
253
+ collection(handle) {
254
+ this.assertOpen();
255
+ return createCollection(this, this.migrations, handle, () => this.listTypes());
256
+ }
257
+ // -------------------------------------------------------
258
+ // Types
259
+ // -------------------------------------------------------
260
+ /**
261
+ * Define and persist a Type; call at app startup before creating records
262
+ * of the type. Redefining an existing typeId is checked against the
263
+ * stored schema: identical is a no-op, a name-only change persists, and
264
+ * anything beyond additive evolution throws StackSchemaDriftError. See
265
+ * docs/spec/data-model.md § Schema drift detection.
266
+ */
267
+ async defineType({ id, name, schema: declared, migratesFrom, }) {
268
+ this.assertOpen();
269
+ // Only read below; the readonly view exists so a handle's literal fits.
270
+ const schema = declared;
271
+ const parsed = parseTypeId(id);
272
+ if (!parsed) {
273
+ throw new StackBadRequestError(`Invalid TypeId format: "${id}". Expected "namespace/name@version", e.g. "com.example.myapp/note@1".`);
274
+ }
275
+ // Even on the idempotent-no-op path below — see noteDefined().
276
+ this.migrations.noteDefined(parsed.baseId, parsed.version);
277
+ // Shape first: the name checks and hashSchema() below both read the
278
+ // schema as a well-formed one, and a schema off the wire is parsed
279
+ // JSON that no compiler has seen.
280
+ const shapeErrors = validateSchemaShape(schema);
281
+ if (shapeErrors.length > 0) {
282
+ throw new StackValidationError(shapeErrors, SCHEMA_INVALID);
283
+ }
284
+ const nameErrors = [
285
+ ...validateSchemaReservedNames(schema),
286
+ ...validateSchemaFieldNames(schema),
287
+ ];
288
+ if (nameErrors.length > 0) {
289
+ throw new StackValidationError(nameErrors, SCHEMA_INVALID);
290
+ }
291
+ const lineage = lineageProblem(id, migratesFrom);
292
+ if (lineage)
293
+ throw new StackBadRequestError(lineage);
294
+ const schemaHash = await hashSchema(schema);
295
+ const existing = await this.getTypeCached(id);
296
+ if (existing) {
297
+ if (existing.schemaHash === schemaHash) {
298
+ if (existing.name === name)
299
+ return existing;
300
+ // else: name-only change — falls through to the write below,
301
+ // schema/hash/createdAt all carried over unchanged.
302
+ }
303
+ else {
304
+ const violations = diffSchemas(existing.schema, schema);
305
+ if (violations.length > 0) {
306
+ throw new StackSchemaDriftError(id, violations);
307
+ }
308
+ }
309
+ }
310
+ const type = {
311
+ id,
312
+ baseId: parsed.baseId,
313
+ version: parsed.version,
314
+ name,
315
+ schema,
316
+ schemaHash,
317
+ createdAt: existing?.createdAt ?? new Date(),
318
+ ...(migratesFrom && { migratesFrom }),
319
+ };
320
+ await this.adapter.saveType(type);
321
+ this.typeCache.set(id, type);
322
+ return type;
323
+ }
324
+ async getType(id) {
325
+ this.assertOpen();
326
+ return this.getTypeCached(id);
327
+ }
328
+ /** Refreshes typeCache wholesale — the explicit way to see a rename made by another writer. */
329
+ async listTypes() {
330
+ this.assertOpen();
331
+ const types = await this.adapter.listTypes();
332
+ for (const type of types)
333
+ this.typeCache.set(type.id, type);
334
+ return types;
335
+ }
336
+ /**
337
+ * Check whether a record's type is compatible with a required schema.
338
+ * Useful for duck-typed consumption across types.
339
+ */
340
+ async typeIsCompatible(typeId, requiredSchema) {
341
+ this.assertOpen();
342
+ const type = await this.getTypeCached(typeId);
343
+ if (!type)
344
+ return false;
345
+ return isCompatible(type.schema, requiredSchema);
346
+ }
347
+ /**
348
+ * Migrate every record of a family, deleted ones included, to the latest
349
+ * version, aborting on the first that fails validation. `sweep: 'listed'`
350
+ * is for a contained app that cannot see unlisted or deleted content.
351
+ * See docs/spec/data-model.md § Type migrations.
352
+ */
353
+ async migrateAll(baseId, opts = {}) {
354
+ this.assertOpen();
355
+ assertFamilyId(baseId, 'migrateAll');
356
+ const familyTypeIds = typeIdsOfFamilies(await this.adapter.listTypes(), [baseId]);
357
+ if (familyTypeIds.length === 0) {
358
+ throw new StackMigrationError(`migrateAll: no registered types found for baseId "${baseId}"`);
359
+ }
360
+ const listedOnly = opts.sweep === 'listed';
361
+ let migrated = 0;
362
+ let skipped = 0;
363
+ for (const typeId of familyTypeIds) {
364
+ const latestId = this.migrations.latest(typeId);
365
+ if (typeId === latestId)
366
+ continue;
367
+ const migrateFn = this.migrations.path(typeId, latestId);
368
+ if (!migrateFn)
369
+ continue;
370
+ const latestType = await this.getTypeCached(latestId);
371
+ if (!latestType) {
372
+ throw new StackMigrationError(`migrateAll: target type "${latestId}" is not defined.`);
373
+ }
374
+ let cursor;
375
+ do {
376
+ const result = await this.adapter.queryRecords(resolveQuery({
377
+ filter: { typeId, includeDeleted: true, includeUnlisted: !listedOnly },
378
+ limit: MIGRATE_ALL_BATCH,
379
+ cursor,
380
+ }));
381
+ for (const record of result.records) {
382
+ if (listedOnly && record.deletedAt) {
383
+ skipped++;
384
+ continue;
385
+ }
386
+ // Same checked path commitMigration() takes — a migration
387
+ // function is no more entitled to move a DID binding or repoint
388
+ // an attachment than a request body is. No ifVersion: a batch
389
+ // pass doesn't know each record's version going in.
390
+ await this.commitMigrationChecked(record, latestId, migrateFn(record.content));
391
+ migrated++;
392
+ }
393
+ cursor = result.cursor ?? undefined;
394
+ } while (cursor);
395
+ }
396
+ return { migrated, skipped };
397
+ }
398
+ // -------------------------------------------------------
399
+ // Records
400
+ // -------------------------------------------------------
401
+ /**
402
+ * Create a record, validated against its type's schema. The one site that
403
+ * stamps a `_group`'s author as its first `admin`, for scoped creates too.
404
+ * Backdating is accepted unconditionally here; ScopedStack decides who may.
405
+ * See docs/spec/data-model.md § Backdating on import.
406
+ */
407
+ async create(typeId, input, opts = {}) {
408
+ this.assertOpen();
409
+ const type = await this.getTypeCached(typeId);
410
+ if (!type) {
411
+ throw new StackBadRequestError(`Unknown type: "${typeId}". Call defineType() first.`);
412
+ }
413
+ const content = dropAbsentFields(input, type.schema);
414
+ // Copied, never aliased: an import loop reusing one Date would otherwise
415
+ // retro-edit every record it had written. `instanceof`, so a non-Date
416
+ // off the wire reaches validateClockField() below rather than throwing
417
+ // here; the fallback never reaches storage.
418
+ const createdAt = opts.createdAt instanceof Date ? new Date(opts.createdAt.getTime()) : new Date();
419
+ const updatedAt = opts.updatedAt instanceof Date ? new Date(opts.updatedAt.getTime()) : createdAt;
420
+ // Ahead of every other check on these two lists: a caller that named
421
+ // the wrong surface asked for something this layer does not offer, and
422
+ // reporting its grantee as a malformed relationship target would
423
+ // describe the mistake as the wrong kind of problem.
424
+ assertDataAssociations(opts.associations ?? [], 'associations');
425
+ assertAuthorityAssociations(opts.permissions ?? [], 'permissions');
426
+ const argumentErrors = [
427
+ ...validateAssociations(opts.permissions, 'permissions'),
428
+ ...validatePermissions(opts.permissions),
429
+ ...validateAssociations(opts.associations),
430
+ ...validateClockField(opts.createdAt, 'createdAt'),
431
+ ...validateClockField(opts.updatedAt, 'updatedAt'),
432
+ ];
433
+ // Compared against the *effective* createdAt, so an updatedAt supplied
434
+ // on its own is caught too: defaulted-createdAt is now, which a
435
+ // backdated updatedAt alone would still precede.
436
+ if (opts.updatedAt !== undefined && updatedAt.getTime() < createdAt.getTime()) {
437
+ argumentErrors.push({ path: 'updatedAt', message: 'updatedAt cannot precede createdAt.' });
438
+ }
439
+ const contentErrors = [
440
+ ...validateReservedKeys(content),
441
+ ...validateContentKeys(content),
442
+ ...typedContentErrors(typeId, content, type.schema),
443
+ ];
444
+ throwValidation(contentErrors, argumentErrors);
445
+ assertContentSize(content, this.capabilities.limits.contentBytes, 'Content');
446
+ if (typeId === `${SYSTEM_TYPES.ATTACHMENT}@1`) {
447
+ await checkAttachmentMimeTypeOnCreate(this, content);
448
+ }
449
+ await checkAttachmentAssociationPointers(this.readRecord, opts.associations);
450
+ await checkBindingsOnCreate(this, typeId, content);
451
+ if (opts.id !== undefined) {
452
+ validateRecordId(opts.id);
453
+ // Only when both are explicit: an `id` alone is a pure position
454
+ // choice, with no second timestamp to agree with.
455
+ if (opts.createdAt !== undefined) {
456
+ validateIdTimestampSkew(opts.id, this.idTimestampSkewMsValue, opts.createdAt.getTime(), 'createdAt');
457
+ }
458
+ // A generated id names nothing, so a create under a parent cannot
459
+ // close a loop. A caller-supplied one can: existing records may
460
+ // already point at it, and the chain above the parent can lead back
461
+ // to it — so the walk is asked only for that combination.
462
+ // See docs/spec/data-model.md § Reparenting.
463
+ if (opts.parentId !== undefined)
464
+ await assertNoParentCycle(this.readRecord, opts.id, opts.parentId);
465
+ }
466
+ const createdBy = normalizeActor(opts.createdBy);
467
+ const associations = baseIdOf(typeId) === SYSTEM_TYPES.GROUP
468
+ ? stampGroupAdmin(opts.associations, createdBy?.subjectId ?? this.ownerEntityId)
469
+ : opts.associations;
470
+ // createdAt drives the id, so the two agree by construction rather than
471
+ // by coincidence. An explicit one mints via generateIdForTimestamp(),
472
+ // which never clamps to "now": generateId()'s monotonic floor would
473
+ // otherwise pull a deliberately historical id forward once this process
474
+ // has minted any live id past it.
475
+ const id = opts.id ??
476
+ (opts.createdAt !== undefined
477
+ ? generateIdForTimestamp(createdAt.getTime())
478
+ : generateId(createdAt.getTime()));
479
+ // An id field a caller supplies is a value or it is absent — never the
480
+ // empty string, which names nobody. Refused rather than dropped, so the
481
+ // caller is never silently ignored.
482
+ if (opts.appId === '') {
483
+ throw new StackBadRequestError('Invalid appId: the empty string is not an id.');
484
+ }
485
+ // Every create naming a parent owes the reference check, whether or not
486
+ // it supplied an id: a destination a caller names has to exist.
487
+ if (opts.parentId !== undefined)
488
+ await assertParentExists(this.readRecord, id, opts.parentId);
489
+ const record = {
490
+ id,
491
+ typeId,
492
+ createdAt,
493
+ updatedAt,
494
+ content,
495
+ version: 1,
496
+ // Presence, not truthiness: '' is refused above, so absence is the
497
+ // only thing a falsy value could mean here.
498
+ ...(opts.parentId !== undefined && { parentId: opts.parentId }),
499
+ ...(opts.appId !== undefined && { appId: opts.appId }),
500
+ // A create's actor is its author, so `updatedBy` is derived rather
501
+ // than taken: stamping it here keeps "absent means an unscoped write"
502
+ // true of version 1 as it is of every later version.
503
+ ...(createdBy && { createdBy, updatedBy: createdBy }),
504
+ ...(opts.permissions?.length && { permissions: opts.permissions }),
505
+ ...(associations?.length && { associations }),
506
+ ...(opts.unlisted && { unlistedAt: createdAt }),
507
+ };
508
+ const change = new PendingChange('create', { actor: Stack.createActor(record) });
509
+ const created = await this.adapter.createRecord(record, { journal: change.journal });
510
+ this.announce(change, created);
511
+ return created;
512
+ }
513
+ /**
514
+ * Get a record by ID, exactly as stored — no implicit migration. Pass
515
+ * { presentAt: 'latest' } to migrate in memory; only migrateAll()
516
+ * commits migrations to disk. A soft-deleted record answers `null` unless
517
+ * { includeDeleted: true } is passed.
518
+ */
519
+ async get(id, opts = {}) {
520
+ this.assertOpen();
521
+ const record = await this.adapter.getRecord(id);
522
+ if (!record)
523
+ return null;
524
+ if (record.deletedAt && !opts.includeDeleted)
525
+ return null;
526
+ return opts.presentAt === 'latest' ? this.migrations.presentAtLatest(record) : record;
527
+ }
528
+ /**
529
+ * Merge a patch into a record's content, checked against its current
530
+ * stored type. A patch the content already satisfies writes nothing.
531
+ * See docs/spec/data-model.md § Mutations.
532
+ */
533
+ async patchContent(id, patch, opts = {}) {
534
+ this.assertOpen();
535
+ assertContentPatch(patch);
536
+ const existing = await this.requireWritable(id, opts, true);
537
+ const merged = await this.validatePatch(id, existing, patch);
538
+ if (contentEqual(existing.content, merged))
539
+ return existing;
540
+ const change = new PendingChange('patch', { actor: normalizeActor(opts.actor) });
541
+ const updated = await this.adapter.patchContent(id, patch, {
542
+ ...this.writeOptions(existing, opts),
543
+ journal: change.journal,
544
+ });
545
+ this.announce(change, updated);
546
+ return updated;
547
+ }
548
+ /**
549
+ * Every check a content patch owes, all before anything is written.
550
+ * Returns the merged content, which the caller compares to decide whether
551
+ * content moved.
552
+ */
553
+ async validatePatch(id, existing, patch) {
554
+ const patchErrors = [
555
+ ...validateReservedKeys(patch),
556
+ ...validatePatchValues(patch),
557
+ ...validateContentKeys(patch),
558
+ ];
559
+ if (patchErrors.length > 0)
560
+ throw new StackValidationError(patchErrors);
561
+ // The patch is what travels, so the patch is what's measured — a
562
+ // small patch against a large record is not an oversized request.
563
+ assertContentSize(patch, this.capabilities.limits.contentBytes, 'Patch');
564
+ const type = await this.getTypeCached(existing.typeId);
565
+ if (!type) {
566
+ throw new StackBadRequestError(`Unknown type: "${existing.typeId}"`);
567
+ }
568
+ const merged = applyMergePatch(existing.content, patch);
569
+ const contentErrors = typedContentErrors(existing.typeId, merged, type.schema);
570
+ if (contentErrors.length > 0)
571
+ throw new StackValidationError(contentErrors);
572
+ if (existing.typeId === `${SYSTEM_TYPES.ATTACHMENT}@1`) {
573
+ // Presence decides mimeType and value decides the rest: re-sending
574
+ // the mimeType a record already holds is refused outright, while a
575
+ // client round-tripping fileId or size unchanged has claimed nothing.
576
+ assertAttachmentImmutable((field) => Object.prototype.hasOwnProperty.call(patch, field) &&
577
+ (field === 'mimeType' ||
578
+ merged[field] !==
579
+ existing.content[field]));
580
+ }
581
+ await checkBindingsOnUpdate(this, existing.typeId, id, patch, existing.content, merged);
582
+ if (id === SYSTEM_TYPES.CONFIG) {
583
+ checkConfigEntityIdUnchanged(existing.content.entityId, merged.entityId);
584
+ }
585
+ return merged;
586
+ }
587
+ /**
588
+ * Move a record under another, or to the root with `null`. The
589
+ * destination is checked only when it changes: it has to exist, and the
590
+ * move must not make the record its own ancestor.
591
+ * See docs/spec/data-model.md § Reparenting.
592
+ */
593
+ async setParent(id, parentId, opts = {}) {
594
+ this.assertOpen();
595
+ assertParentArgument(parentId);
596
+ const existing = await this.requireWritable(id, opts);
597
+ const previousParentId = existing.parentId ?? null;
598
+ if (parentId === previousParentId)
599
+ return existing;
600
+ if (parentId !== null) {
601
+ await assertParentExists(this.readRecord, id, parentId);
602
+ await assertNoParentCycle(this.readRecord, id, parentId);
603
+ }
604
+ const change = new PendingChange('reparent', {
605
+ actor: normalizeActor(opts.actor),
606
+ previousParentId,
607
+ });
608
+ return this.writeAspect(change, opts, (o) => this.adapter.setParent(id, parentId, o));
609
+ }
610
+ /**
611
+ * Withhold a record from enumeration, or restore it. Restating the
612
+ * current state writes nothing, so `unlistedAt` is never dragged forward.
613
+ * See docs/spec/unlisted.md.
614
+ */
615
+ async setUnlisted(id, unlisted, opts = {}) {
616
+ this.assertOpen();
617
+ assertUnlistedArgument(unlisted);
618
+ const existing = await this.requireWritable(id, opts);
619
+ if (Boolean(existing.unlistedAt) === unlisted)
620
+ return existing;
621
+ const change = new PendingChange(unlisted ? 'unlist' : 'list', {
622
+ actor: normalizeActor(opts.actor),
623
+ });
624
+ return this.writeAspect(change, opts, (o) => this.adapter.setUnlisted(id, unlisted, o));
625
+ }
626
+ /**
627
+ * Apply adds and removes to a record's data associations: one adapter
628
+ * write, one journal entry carrying each element in full, so the entry is
629
+ * as undoable as a single-element one. An add naming a held identity with
630
+ * a new `attachmentRecordId` re-points it — see docs/spec/attachments.md
631
+ * § Naming the upload a reference came from.
632
+ */
633
+ async editAssociations(id, edits, opts = {}) {
634
+ this.assertOpen();
635
+ assertAssociationEdits(edits, 'editAssociations()', 'data');
636
+ return this.untilSetHolds(async () => {
637
+ const existing = await this.requireWritable(id, opts);
638
+ const next = applyAssociationEdits(existing.associations ?? [], edits);
639
+ return this.writeAssociations(existing, next, opts, (o) => this.adapter.editAssociations(id, edits, o));
640
+ });
641
+ }
642
+ /**
643
+ * Make a record's data associations exactly `associations`. Its
644
+ * permissions are another aspect, which this never reads or writes.
645
+ */
646
+ async setAssociations(id, associations, opts = {}) {
647
+ this.assertOpen();
648
+ assertAssociationSet(associations, 'associations');
649
+ return this.untilSetHolds(async () => {
650
+ const existing = await this.requireWritable(id, opts);
651
+ return this.writeAssociations(existing, associations, opts, (o) => this.adapter.setAssociations(id, associations, o));
652
+ });
653
+ }
654
+ /**
655
+ * The shared half of the two data-association writes, from the set the
656
+ * write would leave: nothing moved writes nothing, a roster keeps an
657
+ * admin, and every new attachment pointer names its own upload.
658
+ */
659
+ async writeAssociations(existing, next, opts, write) {
660
+ const current = existing.associations ?? [];
661
+ const delta = associationDelta(current, next);
662
+ if (delta.length === 0)
663
+ return existing;
664
+ assertGroupAdminRemains(existing, next);
665
+ await checkAttachmentAssociationPointers(this.readRecord, next, current);
666
+ const change = new PendingChange([
667
+ ...(delta.some((c) => c.op !== 'remove') ? ['associate'] : []),
668
+ ...(delta.some((c) => c.op === 'remove') ? ['dissociate'] : []),
669
+ ], { actor: normalizeActor(opts.actor), associations: delta });
670
+ return this.writeAspect(change, opts, (o) => write({ ...o, expectSet: current }));
671
+ }
672
+ /**
673
+ * Apply adds and removes to who reaches a record. The write-implies-read
674
+ * invariant is asked once, of the set the whole list produces, so a
675
+ * downgrade is one call. See docs/spec/access-control.md § Write implies read.
676
+ */
677
+ async editAccess(id, edits, opts = {}) {
678
+ this.assertOpen();
679
+ assertAssociationEdits(edits, 'editAccess()', 'authority');
680
+ return this.untilSetHolds(async () => {
681
+ const existing = await this.requireWritable(id, opts);
682
+ const next = applyAssociationEdits(existing.permissions ?? [], edits);
683
+ return this.writeAccess(existing, next, opts, (o) => this.adapter.editAccess(id, edits, o));
684
+ });
685
+ }
686
+ /** Make who reaches a record exactly `permissions`; `[]` is private. */
687
+ async setAccess(id, permissions, opts = {}) {
688
+ this.assertOpen();
689
+ assertAssociationSet(permissions, 'permissions');
690
+ return this.untilSetHolds(async () => {
691
+ const existing = await this.requireWritable(id, opts);
692
+ return this.writeAccess(existing, permissions, opts, (o) => this.adapter.setAccess(id, permissions, o));
693
+ });
694
+ }
695
+ async writeAccess(existing, next, opts, write) {
696
+ const current = existing.permissions ?? [];
697
+ const delta = associationDelta(current, next);
698
+ if (delta.length === 0)
699
+ return existing;
700
+ // After the no-op check: a call that moves nothing is not refused for
701
+ // a stored set it did not write.
702
+ this.assertPermissionSet(next);
703
+ const change = new PendingChange('reshare', {
704
+ actor: normalizeActor(opts.actor),
705
+ associations: delta,
706
+ });
707
+ return this.writeAspect(change, opts, (o) => write({ ...o, expectSet: current }));
708
+ }
709
+ /**
710
+ * Run an element-set write from its read onward, again from a fresh read
711
+ * each time the adapter finds the set moved since the last one, so the
712
+ * rules over the resulting set are asked of the set the write lands on.
713
+ * Unbounded: each refusal means another write landed.
714
+ * See docs/spec/versioning.md § Element-set writes compare the set they read.
715
+ */
716
+ async untilSetHolds(attempt) {
717
+ for (;;) {
718
+ try {
719
+ return await attempt();
720
+ }
721
+ catch (err) {
722
+ if (!(err instanceof ElementSetMovedError))
723
+ throw err;
724
+ }
725
+ }
726
+ }
727
+ /**
728
+ * Land a write that never bumps. Its precondition and journal entry
729
+ * travel together here, so no aspect verb can drop either.
730
+ */
731
+ async writeAspect(change, opts, write) {
732
+ const updated = await write({ ifVersion: opts.ifVersion, journal: change.journal });
733
+ this.announce(change, updated);
734
+ return updated;
735
+ }
736
+ /**
737
+ * Hold a permission set to the cross-element invariant — see
738
+ * validatePermissions() in access.ts for why it reads the post-state.
739
+ */
740
+ assertPermissionSet(next) {
741
+ const errors = validatePermissions(next);
742
+ if (errors.length > 0)
743
+ throw new StackValidationError(errors, ARGUMENTS_INVALID);
744
+ }
745
+ /**
746
+ * A soft-deleted record has no current state to edit, so the verbs that
747
+ * edit one refuse it; undelete() and commitMigration() do not call this.
748
+ * Asked after the record is found and, under ScopedStack, after the
749
+ * authority decision. See docs/spec/versioning.md § Mutations are refused,
750
+ * not applied to a tombstone.
751
+ */
752
+ refuseIfDeleted(record) {
753
+ if (record.deletedAt)
754
+ throw softDeletedRefusal(record.id);
755
+ }
756
+ /**
757
+ * The record a write addresses, past every refusal owed before
758
+ * validation: missing, another family, a caller's gate, soft-deleted,
759
+ * then a stale `ifVersion` — before validation, so a caller that lost the
760
+ * race hears that first, and before any no-op, so a write that moved
761
+ * nothing never satisfies a precondition.
762
+ */
763
+ async requireWritable(id, opts, patchesContent = false) {
764
+ const existing = await this.requireRecord(id);
765
+ checkFamily(existing, opts);
766
+ await opts[WRITE_GATE]?.(existing);
767
+ this.refuseIfDeleted(existing);
768
+ this.checkIfVersion(existing, opts.ifVersion);
769
+ checkStoredVersion(existing, opts, patchesContent);
770
+ return existing;
771
+ }
772
+ /**
773
+ * A by-id read straight from the adapter, for the integrity checks a write
774
+ * runs once it is under way: they read past the open-check, as the write
775
+ * they belong to was admitted before any close() began.
776
+ */
777
+ readRecord = (id) => this.adapter.getRecord(id);
778
+ /** The record, or the not-found refusal every mutating verb owes. */
779
+ async requireRecord(id) {
780
+ const record = await this.adapter.getRecord(id);
781
+ if (!record)
782
+ throw new StackNotFoundError(`Record not found: "${id}"`);
783
+ return record;
784
+ }
785
+ /**
786
+ * Soft-delete a record, or purge it with its history, reporting the
787
+ * record as the write left it — or as a purge destroyed it — captured in
788
+ * the same write, so nothing lands unseen between a read and the delete.
789
+ * See docs/spec/versioning.md § Deletion and docs/spec/attachments.md
790
+ * § A purge strands the bytes it referenced.
791
+ */
792
+ async delete(id, opts = {}) {
793
+ this.assertOpen();
794
+ if (id === SYSTEM_TYPES.CONFIG) {
795
+ throw new StackConflictError("Cannot delete the _config record: it holds the stack's identity and is required for every permission check.");
796
+ }
797
+ if (opts.purge) {
798
+ // A purge otherwise reads nothing first, so an expectation costs it
799
+ // one read, and the purge is pinned to that read: a write in between
800
+ // is a conflict, never a purge of a record that was not checked.
801
+ let ifVersion = opts.ifVersion;
802
+ if (opts[WRITE_EXPECTATION]) {
803
+ const current = await this.adapter.getRecord(id);
804
+ if (!current)
805
+ return { record: null, referencedFileIds: [] };
806
+ checkFamily(current, opts);
807
+ ifVersion ??= current.version;
808
+ }
809
+ // The adapter hands back what it destroyed, captured inside the same
810
+ // write: a read here instead would race the delete, and afterwards
811
+ // there is nothing left to read. Null means there was no record, so
812
+ // nothing was purged and nothing is announced.
813
+ const change = new PendingChange('purge', { actor: normalizeActor(opts.actor) });
814
+ const purged = await this.adapter.deleteRecord(id, {
815
+ purge: true,
816
+ ifVersion,
817
+ journal: change.journal,
818
+ });
819
+ if (!purged)
820
+ return { record: null, referencedFileIds: [] };
821
+ this.announce(change, purged);
822
+ return { record: purged, referencedFileIds: await this.referencedFileIds(purged) };
823
+ }
824
+ const existing = await this.requireRecord(id);
825
+ checkFamily(existing, opts);
826
+ this.checkIfVersion(existing, opts.ifVersion);
827
+ // A tombstone's references stand — undelete() must find its
828
+ // attachments intact — so nothing is stranded and nothing is reported.
829
+ if (existing.deletedAt)
830
+ return { record: existing, referencedFileIds: [] };
831
+ const change = new PendingChange('delete', { actor: normalizeActor(opts.actor) });
832
+ const deleted = await this.adapter.deleteRecord(id, {
833
+ ...this.writeOptions(existing, opts),
834
+ journal: change.journal,
835
+ });
836
+ if (deleted)
837
+ this.announce(change, deleted);
838
+ return { record: deleted ?? existing, referencedFileIds: [] };
839
+ }
840
+ /**
841
+ * The files a record references, by the same definition
842
+ * deleteAttachment() and the garbage sweep use: attachment associations
843
+ * and top-level `file-ref` content fields. An `_attachment` record's own
844
+ * `fileId` is a plain string by design and is not one, which is why
845
+ * purging a metadata record reports nothing — see systemTypeDefinitions().
846
+ */
847
+ async referencedFileIds(record) {
848
+ const fromAssociations = (record.associations ?? []).flatMap((a) => a.kind === 'attachment' ? [a.fileId] : []);
849
+ const type = await this.getType(record.typeId);
850
+ const content = record.content;
851
+ const fromContent = fileRefFields(type?.schema ?? {}).flatMap((field) => typeof content[field] === 'string' ? [content[field]] : []);
852
+ return [...new Set([...fromAssociations, ...fromContent])];
853
+ }
854
+ /**
855
+ * Reverse a soft delete. Idempotent — undeleting a record that isn't
856
+ * deleted returns it unchanged. Purged records are gone, so this
857
+ * throws StackNotFoundError for them just like any other missing record.
858
+ * Snapshots and bumps version, same as delete().
859
+ */
860
+ async undelete(id, opts = {}) {
861
+ this.assertOpen();
862
+ const existing = await this.requireRecord(id);
863
+ checkFamily(existing, opts);
864
+ this.checkIfVersion(existing, opts.ifVersion);
865
+ if (!existing.deletedAt)
866
+ return existing;
867
+ const change = new PendingChange('undelete', { actor: normalizeActor(opts.actor) });
868
+ const undeleted = await this.adapter.undeleteRecord(id, {
869
+ ...this.writeOptions(existing, opts),
870
+ journal: change.journal,
871
+ });
872
+ this.announce(change, undeleted);
873
+ return undeleted;
874
+ }
875
+ /**
876
+ * Query records. filter.baseId matches every version of a type family.
877
+ * Results come back exactly as stored; pass presentAt: 'latest' to
878
+ * migrate in memory. See docs/spec/data-model.md § Queries.
879
+ */
880
+ async query(query = {}) {
881
+ this.assertOpen();
882
+ const split = splitQuery(query);
883
+ assertQueryCapabilities(split.query, this.adapter.capabilities);
884
+ return this.dispatchQuery(split, (q) => this.adapter.queryRecords(q));
885
+ }
886
+ /**
887
+ * Everything query() does around the adapter call once the query is
888
+ * split and checked: the migration on the way out. `read` is the call,
889
+ * so a scoped query within a reach gets the same treatment as any other.
890
+ */
891
+ async dispatchQuery({ query, presentAt }, read) {
892
+ this.assertOpen();
893
+ const result = await read(query);
894
+ if (presentAt !== 'latest')
895
+ return result;
896
+ return { ...result, records: result.records.map((r) => this.migrations.presentAtLatest(r)) };
897
+ }
898
+ // -------------------------------------------------------
899
+ // Versions
900
+ // -------------------------------------------------------
901
+ async getVersions(id, query = {}) {
902
+ this.assertOpen();
903
+ assertValidVersionsQuery(query);
904
+ return this.adapter.getVersions(id, query);
905
+ }
906
+ /**
907
+ * A record's change journal, oldest first, ungated. A missing or purged
908
+ * record is StackNotFoundError, since a destroyed log and an empty one
909
+ * are not the same answer. See docs/spec/journal.md § Reading it.
910
+ */
911
+ async getJournal(id, query = {}) {
912
+ this.assertOpen();
913
+ assertValidJournalQuery(query);
914
+ return this.adapter.getJournal(id, query);
915
+ }
916
+ async getVersion(id, version) {
917
+ this.assertOpen();
918
+ return this.adapter.getVersion(id, version);
919
+ }
920
+ /**
921
+ * Restore a record to a previous version by creating a new version —
922
+ * never rewrites history. The snapshot is validated against its own
923
+ * stored typeId, and puts back `content` and `typeId` alone: a snapshot
924
+ * carries nothing else. See docs/spec/versioning.md § Restore semantics.
925
+ */
926
+ async restoreVersion(id, version, opts = {}) {
927
+ this.assertOpen();
928
+ const existing = await this.requireRecord(id);
929
+ // A snapshot is validated against its own stored Type, never the
930
+ // record's current one, so only the family is held to the expectation:
931
+ // the record's here, and the snapshot's once it is read.
932
+ checkFamily(existing, opts);
933
+ this.refuseIfDeleted(existing);
934
+ this.checkIfVersion(existing, opts.ifVersion);
935
+ const target = await this.adapter.getVersion(id, version);
936
+ if (!target) {
937
+ throw new StackNotFoundError(`Version ${version} not found for record "${id}"`);
938
+ }
939
+ checkSnapshotFamily(id, target, opts);
940
+ const type = await this.getTypeCached(target.typeId);
941
+ if (!type) {
942
+ throw new StackBadRequestError(`Unknown type: "${target.typeId}"`);
943
+ }
944
+ const errors = typedContentErrors(target.typeId, target.content, type.schema);
945
+ if (errors.length > 0) {
946
+ throw new StackValidationError(errors);
947
+ }
948
+ if (id === SYSTEM_TYPES.CONFIG) {
949
+ checkConfigEntityIdUnchanged(existing.content.entityId, target.content.entityId);
950
+ }
951
+ // Restoring is a write like any other, so it owes the same immutability
952
+ // check a content patch pays: a snapshot taken before a card claimed
953
+ // its DID would otherwise move the binding by rolling content back.
954
+ // Uniqueness needs none — a restore can only put back a value this same
955
+ // card already held.
956
+ for (const field of bindingFieldsOf(baseIdOf(target.typeId))) {
957
+ checkBindingImmutable(baseIdOf(target.typeId), field, existing.content[field], target.content[field]);
958
+ }
959
+ // A restore adds no containment edge and takes none away, so there is
960
+ // no cycle for it to close and nothing for the destination checks to
961
+ // gate. See docs/spec/versioning.md § Restore semantics.
962
+ const change = new PendingChange('restore', {
963
+ actor: normalizeActor(opts.actor),
964
+ previousTypeId: existing.typeId,
965
+ });
966
+ const restored = await this.adapter.restoreVersion(id, version, {
967
+ ...this.writeOptions(existing, opts),
968
+ journal: change.journal,
969
+ });
970
+ this.announce(change, restored);
971
+ return restored;
972
+ }
973
+ /**
974
+ * Commit a per-record migration with caller-supplied content. Create-shaped
975
+ * at the destination and update-shaped over the record, so it owes both
976
+ * sets of integrity checks. See docs/spec/data-model.md § Type migrations.
977
+ */
978
+ async commitMigration(id, toTypeId, content, opts = {}) {
979
+ this.assertOpen();
980
+ const existing = await this.requireRecord(id);
981
+ this.checkIfVersion(existing, opts.ifVersion);
982
+ return this.commitMigrationChecked(existing, toTypeId, content, opts);
983
+ }
984
+ /**
985
+ * The checked migration write behind commitMigration() and migrateAll(),
986
+ * taking the record in hand so a batch pass needs no re-read. A Migration
987
+ * function is held to the same checks as a request body: app code is no
988
+ * trust boundary here.
989
+ */
990
+ async commitMigrationChecked(existing, toTypeId, input, opts = {}) {
991
+ const id = existing.id;
992
+ const type = await this.getTypeCached(toTypeId);
993
+ if (!type) {
994
+ throw new StackBadRequestError(`Unknown type: "${toTypeId}". Call defineType() first.`);
995
+ }
996
+ const content = dropAbsentFields(input, type.schema);
997
+ const errors = [
998
+ ...validateReservedKeys(content),
999
+ ...validateContentKeys(content),
1000
+ ...typedContentErrors(toTypeId, content, type.schema),
1001
+ ];
1002
+ if (errors.length > 0) {
1003
+ throw new StackValidationError(errors);
1004
+ }
1005
+ assertContentSize(content, this.capabilities.limits.contentBytes, 'Content');
1006
+ const fromFamily = baseIdOf(existing.typeId);
1007
+ const toFamily = baseIdOf(toTypeId);
1008
+ const existingContent = existing.content;
1009
+ // Only create() stamps a group's first `admin`, so a record migrated
1010
+ // *into* `_group` would have an empty roster. Version-to-version within
1011
+ // the family keeps its roster. See docs/spec/data-model.md § Type migrations.
1012
+ if (toFamily === SYSTEM_TYPES.GROUP && fromFamily !== SYSTEM_TYPES.GROUP) {
1013
+ throw new StackConflictError('Cannot migrate a record into _group: a group’s admin roster is stamped at creation. ' +
1014
+ 'Create the group instead.');
1015
+ }
1016
+ if (fromFamily === SYSTEM_TYPES.ATTACHMENT) {
1017
+ // Value-wise throughout: a migration re-sends all three required
1018
+ // fields, so presence would refuse every migration of the family.
1019
+ assertAttachmentImmutable((field) => content[field] !==
1020
+ existingContent[field]);
1021
+ }
1022
+ else if (toFamily === SYSTEM_TYPES.ATTACHMENT) {
1023
+ // A record arriving from outside the family stakes a fresh claim on
1024
+ // its fileId, exactly as create() does — so it owes create()'s check.
1025
+ await checkAttachmentMimeTypeOnCreate(this, content);
1026
+ }
1027
+ await checkBindingsOnMigrate(this, existing.typeId, toTypeId, id, existingContent, content);
1028
+ if (id === SYSTEM_TYPES.CONFIG) {
1029
+ checkConfigEntityIdUnchanged(existing.content.entityId, content.entityId);
1030
+ }
1031
+ const change = new PendingChange('migrate', {
1032
+ actor: normalizeActor(opts.actor),
1033
+ previousTypeId: existing.typeId,
1034
+ });
1035
+ const migrated = await this.adapter.commitMigration(id, toTypeId, content, {
1036
+ ...this.writeOptions(existing, opts),
1037
+ journal: change.journal,
1038
+ });
1039
+ this.announce(change, migrated);
1040
+ return migrated;
1041
+ }
1042
+ // -------------------------------------------------------
1043
+ // Attachments
1044
+ // -------------------------------------------------------
1045
+ /**
1046
+ * Store bytes and create their `_attachment@1` metadata record, returning
1047
+ * it: `content.fileId` addresses the bytes, `id` the metadata. Uses the
1048
+ * adapter's atomic putAttachmentWithMetadata() where there is one.
1049
+ * See docs/spec/wire-format.md § Attachments.
1050
+ */
1051
+ async putAttachment(data, opts) {
1052
+ this.assertOpen();
1053
+ assertAttachmentSize(data.byteLength, this.capabilities.limits.attachmentBytes);
1054
+ if (this.adapter.putAttachmentWithMetadata) {
1055
+ // The metadata record is written inside the adapter, so create()
1056
+ // never sees it and this is the only place it can be announced.
1057
+ const record = await this.adapter.putAttachmentWithMetadata(data, opts);
1058
+ // The one emission with no journal half of its own: the far side
1059
+ // wrote the record, so it appended the entry in that same write —
1060
+ // the same division saveVersion() follows over this adapter. See
1061
+ // docs/spec/journal.md § The entry set is the event set.
1062
+ this.announce(new PendingChange('create'), record);
1063
+ return record;
1064
+ }
1065
+ const fileId = await this.adapter.putBlob(data);
1066
+ return this.create(`${SYSTEM_TYPES.ATTACHMENT}@1`, attachments.uploadContent(fileId, data, opts), { appId: opts.appId });
1067
+ }
1068
+ async getAttachment(fileId) {
1069
+ this.assertOpen();
1070
+ return this.adapter.getBlob(fileId);
1071
+ }
1072
+ /**
1073
+ * Every `_attachment` record describing `fileId`, earliest-recorded first.
1074
+ * Not on StackClient: it presents an access decision already made, which
1075
+ * a scoped version would only check a second, different way. See
1076
+ * docs/spec/attachments.md § Finding a `fileId`'s metadata records.
1077
+ */
1078
+ async getAttachmentRecords(fileId) {
1079
+ this.assertOpen();
1080
+ const results = await queryAllPages((q) => this.query(q), {
1081
+ filter: {
1082
+ baseId: SYSTEM_TYPES.ATTACHMENT,
1083
+ includeDeleted: true,
1084
+ includeUnlisted: true,
1085
+ ...(filtersContent(this.capabilities) && { content: { fileId } }),
1086
+ },
1087
+ });
1088
+ return results
1089
+ .filter((r) => r.content.fileId === fileId)
1090
+ .sort(compareRecordedAttachments);
1091
+ }
1092
+ /**
1093
+ * Delete an attachment's bytes and every _attachment metadata record for
1094
+ * it, family-wide. Throws StackConflictError if any record in the stack
1095
+ * still references the file, StackNotFoundError if neither metadata
1096
+ * records nor bytes exist.
1097
+ */
1098
+ async deleteAttachment(fileId, opts = {}) {
1099
+ this.assertOpen();
1100
+ let deletedRecords;
1101
+ if (this.adapter.deleteUnreferencedAttachmentRecords) {
1102
+ // Purged inside the adapter's own transaction, so these never reach
1103
+ // delete() and are announced here instead — from the records it
1104
+ // hands back, which are the last copies that will ever exist.
1105
+ deletedRecords = await this.adapter.deleteUnreferencedAttachmentRecords(fileId, SYSTEM_TYPES.ATTACHMENT);
1106
+ const at = new Date();
1107
+ for (const record of deletedRecords) {
1108
+ this.announce(new PendingChange('purge', { actor: normalizeActor(opts.actor) }), record, at);
1109
+ }
1110
+ }
1111
+ else {
1112
+ deletedRecords = await attachments.deleteUnreferencedAttachmentRecordsFallback(this, fileId, opts);
1113
+ }
1114
+ if (!deletedRecords.length) {
1115
+ try {
1116
+ await this.adapter.getBlob(fileId);
1117
+ }
1118
+ catch {
1119
+ throw new StackNotFoundError(`Attachment not found: "${fileId}"`);
1120
+ }
1121
+ }
1122
+ await this.adapter.deleteBlob(fileId);
1123
+ }
1124
+ /**
1125
+ * Sweep for attachment bytes unreachable from any record — live or
1126
+ * soft-deleted — and delete bytes + metadata. Deletion goes through
1127
+ * deleteAttachment(), so a file re-referenced by sweep time is skipped,
1128
+ * not a failure. See docs/spec/attachments.md § Garbage collection.
1129
+ */
1130
+ async collectAttachmentGarbage(opts = {}) {
1131
+ this.assertOpen();
1132
+ return attachments.collectAttachmentGarbage(this, this.adapter.listBlobs?.bind(this.adapter), opts);
1133
+ }
1134
+ // -------------------------------------------------------
1135
+ // Lifecycle
1136
+ // -------------------------------------------------------
1137
+ /**
1138
+ * Observe every change made through this Stack, unfiltered. Async so a
1139
+ * remote stack resolves once its feed is live, making subscribe-then-query
1140
+ * gap-free. See docs/spec/events.md § Subscribing.
1141
+ */
1142
+ async subscribe(handler, opts = {}) {
1143
+ this.assertOpen();
1144
+ assertSinceUsable(opts.since, this.relaysChanges);
1145
+ assertValidBaseIdFilter(opts.filter);
1146
+ const unsubscribe = this.changes.subscribe(handler, opts);
1147
+ let stopRelay;
1148
+ try {
1149
+ stopRelay = await this.openRelay(handler, opts);
1150
+ }
1151
+ catch (err) {
1152
+ // The local half is already registered, and a failed subscribe()
1153
+ // must leave nothing behind for the caller to unsubscribe from.
1154
+ unsubscribe();
1155
+ throw err;
1156
+ }
1157
+ return () => {
1158
+ unsubscribe();
1159
+ stopRelay?.();
1160
+ };
1161
+ }
1162
+ /**
1163
+ * Ask the adapter to relay changes made elsewhere, if it can. One relay
1164
+ * per subscription, carrying its filter to the far end, which holds the
1165
+ * records that filter needs. See docs/spec/events.md § Where events come
1166
+ * from.
1167
+ */
1168
+ async openRelay(handler, opts) {
1169
+ if (!this.adapter.subscribeChanges)
1170
+ return undefined;
1171
+ const delivery = new RelayDelivery(handler, opts);
1172
+ const stop = await this.adapter.subscribeChanges({
1173
+ ...(opts.filter !== undefined && { filter: opts.filter }),
1174
+ ...(opts.since !== undefined && { since: opts.since }),
1175
+ ...(opts.includeRecords !== undefined && { includeRecords: opts.includeRecords }),
1176
+ ...(opts.onError !== undefined && { onError: opts.onError }),
1177
+ ...(opts.onReset !== undefined && { onReset: opts.onReset }),
1178
+ }, (change) => delivery.deliver(change));
1179
+ return () => {
1180
+ delivery.close();
1181
+ void stop();
1182
+ };
1183
+ }
1184
+ /** Whether changes reach this stack from elsewhere. */
1185
+ get relaysChanges() {
1186
+ return typeof this.adapter.subscribeChanges === 'function';
1187
+ }
1188
+ /**
1189
+ * Flush pending writes to the underlying storage. A no-op for adapters
1190
+ * that commit on every call (SQLite, the API adapter); meaningful for
1191
+ * ones that buffer, and for checkpointing a stack that stays open —
1192
+ * close() covers the teardown case on its own.
1193
+ */
1194
+ async flush() {
1195
+ this.assertOpen();
1196
+ await this.adapter.flush?.();
1197
+ }
1198
+ /**
1199
+ * Flush, then release any resources the adapter holds (connections, file
1200
+ * handles, lock files). A failed flush still releases them before it
1201
+ * propagates: an unwritable stack must not also leak a lock file.
1202
+ * See docs/spec/adapters.md § Lifecycle.
1203
+ */
1204
+ async close() {
1205
+ if (this.closed)
1206
+ return;
1207
+ // Marked closed up front so a failed flush can't leave the stack
1208
+ // half-open and invite a second close() onto an already-closed adapter.
1209
+ // Flushes through the adapter directly, past the now-tripped guard.
1210
+ this.closed = true;
1211
+ this.changes.closeAll();
1212
+ try {
1213
+ await this.adapter.flush?.();
1214
+ }
1215
+ finally {
1216
+ await this.adapter.close?.();
1217
+ }
1218
+ }
1219
+ /** Throws once close() has run. */
1220
+ assertOpen() {
1221
+ if (this.closed)
1222
+ throw new UseAfterCloseError();
1223
+ }
1224
+ // -------------------------------------------------------
1225
+ // Grants
1226
+ // -------------------------------------------------------
1227
+ /**
1228
+ * Create a `_grant` authorizing `grantee` to take `actions` on `baseId`'s
1229
+ * family. An app's `-own` is read as the bare verb when it acts for
1230
+ * someone, so grant it the types it needs, not the narrowest-looking
1231
+ * suffix. See docs/spec/access-control.md § Type-level grants.
1232
+ */
1233
+ async grantType(baseId, grant) {
1234
+ this.assertOpen();
1235
+ return typeGrants.grantType(this, baseId, grant);
1236
+ }
1237
+ /**
1238
+ * List `_grant` records: all of them, or those `grantType()` would have
1239
+ * written for the same grantee. The `entity` arm instead lists what
1240
+ * currently applies to that entity, so it is not a preview of what
1241
+ * `revokeType()` would withdraw. See docs/spec/access-control.md § Listing
1242
+ * and revoking.
1243
+ */
1244
+ async listTypeGrants(query) {
1245
+ this.assertOpen();
1246
+ return typeGrants.listTypeGrants(this, query);
1247
+ }
1248
+ /**
1249
+ * The inverse of grantType(): soft-deletes the matching `_grant` records,
1250
+ * grantee and actions matched exactly, and returns them. Matching nothing
1251
+ * is not an error, so re-running a revocation stays safe.
1252
+ * See docs/spec/access-control.md § Listing and revoking.
1253
+ */
1254
+ async revokeType(baseId, grant) {
1255
+ this.assertOpen();
1256
+ return typeGrants.revokeType(this, baseId, grant);
1257
+ }
1258
+ // -------------------------------------------------------
1259
+ // App installs
1260
+ // -------------------------------------------------------
1261
+ /**
1262
+ * What applying `manifest` for the key `did` would change, for the owner
1263
+ * to review before installApp(). Writes nothing. Refuses outright what no
1264
+ * approval could make valid: a type outside the app's own namespace and
1265
+ * the commons, a request the grant rules refuse, or a `did` already
1266
+ * registered to a different app. See docs/spec/apps.md § Plan, then apply.
1267
+ */
1268
+ async planInstall(submitted, opts) {
1269
+ this.assertOpen();
1270
+ return apps.planInstall(this, submitted, opts);
1271
+ }
1272
+ /**
1273
+ * Apply an approved plan: types, the key's `_app` card, the `_install`
1274
+ * Record and every linked key's grants. A plan the stack has moved on
1275
+ * from is a StackConflictError, so what lands is what was approved.
1276
+ * See docs/spec/apps.md § Plan, then apply.
1277
+ */
1278
+ async installApp(plan) {
1279
+ this.assertOpen();
1280
+ return apps.installApp(this, plan);
1281
+ }
1282
+ /**
1283
+ * Withdraw every grant an install produced and soft-delete it. The app's
1284
+ * records and `_app` cards stay: the data is the owner's, and the cards
1285
+ * are what its records' attribution resolves through. Returns the
1286
+ * install's tombstone. See docs/spec/apps.md § Uninstalling.
1287
+ */
1288
+ async uninstallApp(appId) {
1289
+ this.assertOpen();
1290
+ return apps.uninstallApp(this, appId);
1291
+ }
1292
+ // -------------------------------------------------------
1293
+ // Private helpers
1294
+ // -------------------------------------------------------
1295
+ /**
1296
+ * Fast-fail for the ifVersion precondition using the already-fetched
1297
+ * record. The adapter re-checks atomically at write time (the source of
1298
+ * truth for concurrent writers) — this just skips validation and
1299
+ * snapshotting work when the mismatch is already visible.
1300
+ */
1301
+ checkIfVersion(existing, ifVersion) {
1302
+ if (ifVersion === undefined || existing.version === ifVersion)
1303
+ return;
1304
+ throw new StackVersionConflictError(`Record "${existing.id}" is at version ${existing.version}, expected ${ifVersion}`, existing.id, ifVersion, existing.version);
1305
+ }
1306
+ /**
1307
+ * The options every version-bumping adapter write carries — precondition,
1308
+ * prior-state snapshot and actor — taken together so a new verb cannot
1309
+ * omit one. See docs/spec/versioning.md § Version history.
1310
+ */
1311
+ writeOptions(existing, opts) {
1312
+ return {
1313
+ ifVersion: opts.ifVersion,
1314
+ snapshot: this.buildVersionSnapshot(existing),
1315
+ actor: normalizeActor(opts.actor),
1316
+ };
1317
+ }
1318
+ /**
1319
+ * A record's prior state for the version it is about to leave: `content`
1320
+ * and the `typeId` it is read under, which only a snapshot keeps. The
1321
+ * journal keeps everything else. See docs/spec/versioning.md § Version
1322
+ * history.
1323
+ */
1324
+ buildVersionSnapshot(record) {
1325
+ return {
1326
+ version: record.version,
1327
+ typeId: record.typeId,
1328
+ content: record.content,
1329
+ updatedAt: record.updatedAt,
1330
+ ...(record.createdBy && { createdBy: record.createdBy }),
1331
+ ...(record.updatedBy && { updatedBy: record.updatedBy }),
1332
+ };
1333
+ }
1334
+ }
1335
+ /** Every registered version of the named families, as concrete TypeIds. */
1336
+ function typeIdsOfFamilies(types, baseIds) {
1337
+ return types.filter((t) => baseIds.includes(t.baseId)).map((t) => t.id);
1338
+ }
1339
+ //# sourceMappingURL=stack.js.map