@minca/core 0.1.16 → 0.1.18

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 (125) hide show
  1. package/README.md +10 -9
  2. package/dist/elements/auth-styles.d.ts +1 -1
  3. package/dist/elements/auth-styles.d.ts.map +1 -1
  4. package/dist/elements/auth-styles.js +14 -5
  5. package/dist/elements/auth-styles.js.map +1 -1
  6. package/dist/elements/minca-auth.d.ts.map +1 -1
  7. package/dist/elements/minca-auth.js +18 -15
  8. package/dist/elements/minca-auth.js.map +1 -1
  9. package/dist/files/space-files.d.ts +2 -2
  10. package/dist/files/space-files.d.ts.map +1 -1
  11. package/dist/files/space-files.js +7 -5
  12. package/dist/files/space-files.js.map +1 -1
  13. package/dist/inbox/names.d.ts +1 -1
  14. package/dist/inbox/names.js +1 -1
  15. package/dist/index.d.ts +2 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +2 -0
  18. package/dist/index.js.map +1 -1
  19. package/dist/network/ws-transport.d.ts.map +1 -1
  20. package/dist/network/ws-transport.js +3 -0
  21. package/dist/network/ws-transport.js.map +1 -1
  22. package/dist/node/actions.d.ts +5 -0
  23. package/dist/node/actions.d.ts.map +1 -1
  24. package/dist/node/actions.js +39 -20
  25. package/dist/node/actions.js.map +1 -1
  26. package/dist/node/api.d.ts +2 -0
  27. package/dist/node/api.d.ts.map +1 -1
  28. package/dist/node/api.js +2 -0
  29. package/dist/node/api.js.map +1 -1
  30. package/dist/node/carrier.js +1 -1
  31. package/dist/node/carrier.js.map +1 -1
  32. package/dist/node/node-carriers.d.ts.map +1 -1
  33. package/dist/node/node-carriers.js +6 -1
  34. package/dist/node/node-carriers.js.map +1 -1
  35. package/dist/node/node-contacts.d.ts.map +1 -1
  36. package/dist/node/node-contacts.js +1 -0
  37. package/dist/node/node-contacts.js.map +1 -1
  38. package/dist/node/node-hosting.d.ts.map +1 -1
  39. package/dist/node/node-hosting.js +11 -4
  40. package/dist/node/node-hosting.js.map +1 -1
  41. package/dist/node/node-records.d.ts.map +1 -1
  42. package/dist/node/node-records.js +6 -1
  43. package/dist/node/node-records.js.map +1 -1
  44. package/dist/node/node.d.ts.map +1 -1
  45. package/dist/node/node.js +14 -1
  46. package/dist/node/node.js.map +1 -1
  47. package/dist/node/remote.d.ts.map +1 -1
  48. package/dist/node/remote.js +7 -1
  49. package/dist/node/remote.js.map +1 -1
  50. package/dist/node/space-holding.d.ts +7 -3
  51. package/dist/node/space-holding.d.ts.map +1 -1
  52. package/dist/node/space-holding.js +90 -18
  53. package/dist/node/space-holding.js.map +1 -1
  54. package/dist/node/space-peers.d.ts.map +1 -1
  55. package/dist/node/space-peers.js +58 -24
  56. package/dist/node/space-peers.js.map +1 -1
  57. package/dist/node/space-runtime.d.ts +11 -3
  58. package/dist/node/space-runtime.d.ts.map +1 -1
  59. package/dist/node/space-runtime.js +22 -1
  60. package/dist/node/space-runtime.js.map +1 -1
  61. package/dist/node/space-writing.d.ts +2 -0
  62. package/dist/node/space-writing.d.ts.map +1 -1
  63. package/dist/node/space-writing.js +2 -0
  64. package/dist/node/space-writing.js.map +1 -1
  65. package/dist/node/types.d.ts +130 -36
  66. package/dist/node/types.d.ts.map +1 -1
  67. package/dist/query/types.d.ts +1 -0
  68. package/dist/query/types.d.ts.map +1 -1
  69. package/dist/query/types.js.map +1 -1
  70. package/dist/records/contract-builder.d.ts +22 -6
  71. package/dist/records/contract-builder.d.ts.map +1 -1
  72. package/dist/records/contract-builder.js.map +1 -1
  73. package/dist/schemas/automations.d.ts +6 -2
  74. package/dist/schemas/automations.d.ts.map +1 -1
  75. package/dist/schemas/automations.js.map +1 -1
  76. package/dist/schemas/connectors.d.ts +4 -3
  77. package/dist/schemas/connectors.d.ts.map +1 -1
  78. package/dist/schemas/connectors.js +4 -3
  79. package/dist/schemas/connectors.js.map +1 -1
  80. package/dist/schemas/library/media.js +1 -1
  81. package/dist/schemas/library/media.js.map +1 -1
  82. package/dist/schemas/library/social.d.ts +258 -0
  83. package/dist/schemas/library/social.d.ts.map +1 -1
  84. package/dist/schemas/library/social.js +28 -1
  85. package/dist/schemas/library/social.js.map +1 -1
  86. package/dist/session/auth.d.ts +7 -3
  87. package/dist/session/auth.d.ts.map +1 -1
  88. package/dist/session/auth.js.map +1 -1
  89. package/dist/session/hosting.d.ts.map +1 -1
  90. package/dist/session/hosting.js +8 -2
  91. package/dist/session/hosting.js.map +1 -1
  92. package/dist/space/presets.d.ts +2 -2
  93. package/dist/space/presets.d.ts.map +1 -1
  94. package/dist/space/presets.js +3 -2
  95. package/dist/space/presets.js.map +1 -1
  96. package/dist/storage/blob-store.d.ts +3 -0
  97. package/dist/storage/blob-store.d.ts.map +1 -1
  98. package/dist/types.d.ts +11 -2
  99. package/dist/types.d.ts.map +1 -1
  100. package/dist/types.js.map +1 -1
  101. package/docs/README.md +86 -93
  102. package/docs/actions.md +212 -144
  103. package/docs/agents.md +198 -155
  104. package/docs/automations.md +296 -204
  105. package/docs/blueprints-and-guides.md +405 -295
  106. package/docs/bots.md +208 -134
  107. package/docs/building-an-app.md +74 -163
  108. package/docs/collections.md +248 -328
  109. package/docs/computed.md +112 -89
  110. package/docs/contacts.md +151 -112
  111. package/docs/contracts.md +299 -120
  112. package/docs/direct-messages.md +80 -61
  113. package/docs/inbox.md +138 -93
  114. package/docs/node.md +1072 -972
  115. package/docs/permissions.md +142 -0
  116. package/docs/proposing-collections.md +74 -55
  117. package/docs/query-format.md +150 -126
  118. package/docs/records-and-queries.md +205 -126
  119. package/docs/sign-in.md +496 -418
  120. package/docs/spaces.md +261 -245
  121. package/docs/standard-library.md +473 -504
  122. package/docs/storage.md +325 -348
  123. package/docs/usernames.md +164 -97
  124. package/docs/warrants.md +100 -67
  125. package/package.json +1 -2
@@ -1,198 +1,235 @@
1
1
  # Collections
2
2
 
3
- A collection is a named kind of record in a space. Its definition is stored in
4
- the space as a signed record, so another app, or an agent, can open the space
5
- and know what its data means without your code.
3
+ A collection is a named kind of record in a space, like a table in a
4
+ database. You define one when your app keeps something of its own. For things
5
+ many apps share, like events, comments and polls, look in the
6
+ [standard library](#the-standard-library) first.
7
+
8
+ ## Defining a collection
9
+
10
+ A collection has a name, a title and a schema for its records' bodies:
6
11
 
7
12
  ```typescript
8
- import * as z from 'zod'; // or Valibot, ArkType, or plain JSON Schema
13
+ import * as z from 'zod';
9
14
  import { collection } from '@minca/core';
10
15
 
11
- const Poll = z.object({
12
- question: z.string().min(1).max(500),
13
- options: z.array(z.string().min(1)).min(2).max(10),
14
- });
15
-
16
16
  export const polls = collection({
17
17
  name: 'app.poll',
18
18
  title: 'Poll',
19
- schema: Poll,
20
- rules: { fixed: ['options'] },
19
+ schema: z.object({
20
+ question: z.string().min(1).max(500),
21
+ options: z.array(z.string().min(1)).min(2).max(10),
22
+ }),
21
23
  });
22
24
 
23
25
  await node.collections.define(space.id, polls);
24
26
  ```
25
27
 
26
- `collection(…)` only keeps the definition's types, so queries and writes that
27
- name `polls` are typed from the schema. Pass it where a collection name goes.
28
+ `define` stores the definition in the space as a signed record. Any app or
29
+ agent that opens the space can read it and know what a poll is, without your
30
+ code.
31
+
32
+ `collection(…)` itself only attaches types. Pass `polls` wherever a
33
+ collection name goes, and writes and queries are typed from its schema.
28
34
 
29
35
  ## Names
30
36
 
31
- Reverse-DNS, lower case, at least two parts: `app.poll`, `com.example.recipe`.
32
- Letters, digits and `-` in each part. `sys.*` is the protocol's own and
33
- `std.*` is the standard library.
37
+ A name is reverse-DNS, lower case, with at least two parts: `app.poll`,
38
+ `com.example.recipe`. Each part holds letters, digits and `-`. Names starting
39
+ `sys.` belong to the protocol, and `std.` to the standard library.
34
40
 
35
- Names are local to a space: nothing registers or owns one across spaces. Two
36
- apps sharing a space settle a clash over a name before anything is defined,
37
- when a person reads what each would define
41
+ A name means something only inside its space. Nobody registers or owns one
42
+ across spaces. When two apps share a space, a person settles any clash
43
+ before anything is defined, as they read what each app would add
38
44
  ([the blueprint review](blueprints-and-guides.md#the-review)).
39
45
 
40
46
  ## Schemas
41
47
 
42
- What gets stored is JSON Schema, in a small subset every app agrees on:
48
+ Write the schema with the validator you already use. Zod 4.2+, ArkType
49
+ 2.1.28+ and Valibot with `toStandardJsonSchema` all work, and so does plain
50
+ JSON Schema.
51
+
52
+ What gets stored is JSON Schema, in a small subset every app understands:
43
53
 
44
54
  `type`, `properties`, `required`, `items`, `enum`, `const`, `minimum`,
45
55
  `maximum`, `minLength`, `maxLength`, `minItems`, `maxItems`,
46
56
  `additionalProperties` (true or false), `title`, `description`
47
57
 
48
- and three that say what a value means, so any app can show it well:
49
-
50
- - `oneOf: [{ const, title }]`: fixed choices with labels.
51
- - `x-choicesFrom: { rel, field }`: the value picks from a list in the record
52
- this one links to as `rel`, in its field `field`. A number is a position in
53
- that list; anything else is the option itself. A vote's `choice` picks from
54
- its poll's `options`. It is a display hint, never checked when validating.
55
- - `x-kind: "<name>"`: what kind of value a field holds. The names apps read:
56
-
57
- | `x-kind` | The value | An app shows |
58
- | ---------- | ------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------- |
59
- | `did` | an account's DID, `did:key:z…` ([spec 01 §4](https://github.com/leifriksheim/minca/blob/main/spec/01-identity.md)) | who it is, and a list of people to pick from |
60
- | `when` | a moment, RFC 3339, or a whole day, `YYYY-MM-DD` | the time in the reader's words, a date and time picker with "all day" |
61
- | `day` | a day, `YYYY-MM-DD` | the day in the reader's words, a date picker |
62
- | `url` | a web address | a link, opened only when it is `http` or `https` |
63
- | `money` | `{ amount, currency }`, `amount` a decimal string | `€12.50` in the reader's format; an amount and a currency |
64
- | `file` | a file, as `records.addFile` gives it | its name and size, a picture when it is one; a file picker |
65
- | `image` | `{ blob, alt }`: a picture and what it shows | the picture; a picker and its description |
66
- | `position` | a sort key (`positionBetween`) | nothing: it orders records, nobody reads it |
67
-
68
- Each is what the fragment of the same name writes (`person` writes `did`,
69
- `blob` writes `file`). An app shows a kind it doesn't know as the plain
70
- value. A definition
71
- already in a space keeps the labels it was written with: a space defined
72
- before these labels shows those fields plainly until the collection is
73
- redefined.
74
-
75
- Any keyword starting `x-` is an annotation like these: any JSON, and it says
76
- nothing about whether a body fits. A new one, or a new `x-kind`, is a row
77
- here, never a change to the protocol. With Zod, add one with
78
- `.meta({ 'x-kind': 'did' })`. Keep annotations to plain values: a validator
79
- that can't build from a schema (an `$id` inside one is enough) checks
80
- nothing against it, so the collection's shape goes unchecked.
81
-
82
58
  Anything else, like `pattern` or `format`, is refused when you define the
83
- collection, with the reason. A Zod `.regex()` or `.email()` fails for that
84
- reason. Validators that can describe themselves as JSON Schema work directly:
85
- Zod 4.2+, ArkType 2.1.28+, Valibot with `toStandardJsonSchema`. They are
86
- converted with target `draft-2020-12` before storing, a `$schema` member is
87
- dropped, and the result is checked like any other. For checks that stay
88
- local, `createSchemaEngine().registerCollection({ name, schema })` takes any
89
- [Standard Schema v1](https://standardschema.dev/) validator directly.
59
+ collection, with the reason. So a Zod `.regex()` or `.email()` won't define.
60
+
61
+ A validator's schema is converted with target `draft-2020-12`, its `$schema`
62
+ member is dropped, and the result is checked like any other. For checks that
63
+ stay on your own device, `createSchemaEngine().registerCollection({ name, schema })`
64
+ takes any [Standard Schema v1](https://standardschema.dev/) validator as it
65
+ is.
66
+
67
+ ### Choices
68
+
69
+ Two keywords say what a field may be chosen from, so any app can show a
70
+ picker:
71
+
72
+ - `oneOf: [{ const, title }]` is a fixed set of choices, each with a label.
73
+ - `x-choicesFrom: { rel, field }` picks from a list in another record: the
74
+ one this record links to as `rel`, in its field `field`. A number is a
75
+ position in that list. Anything else is the option itself. A vote's
76
+ `choice` picks from its poll's `options` this way.
77
+
78
+ `x-choicesFrom` is only a display hint. It is never checked when validating.
79
+
80
+ ### Kinds of value
81
+
82
+ `x-kind` says what kind of value a field holds, so any app can show it well:
83
+
84
+ | `x-kind` | The value | An app shows |
85
+ | ---------- | ---------------------------------------------------------- | ----------------------------------------- |
86
+ | `did` | an account's DID, `did:key:z…` | who it is; a list of people to pick from |
87
+ | `when` | a moment (RFC 3339) or a whole day (`YYYY-MM-DD`) | the time in the reader's words; a picker |
88
+ | `day` | a day, `YYYY-MM-DD` | the day in the reader's words; a picker |
89
+ | `url` | a web address | a link, opened only for `http` or `https` |
90
+ | `money` | `{ amount, currency }`, `amount` a decimal string | `€12.50` in the reader's format |
91
+ | `file` | a file, as `records.addFile` gives it | its name and size, or the picture |
92
+ | `image` | `{ blob, alt }`: a picture and what it shows | the picture; a picker and a description |
93
+ | `position` | a sort key from [`positionBetween`](#the-standard-library) | nothing: it only orders records |
94
+
95
+ The standard library's fragments write these for you: `person` writes `did`,
96
+ `blob` writes `file`, and so on. With Zod, add one yourself with
97
+ `.meta({ 'x-kind': 'did' })`.
98
+
99
+ An app shows a kind it doesn't know as the plain value. A definition keeps
100
+ the kinds it was written with, so a collection defined before a kind existed
101
+ shows that field plainly until it is defined again.
102
+
103
+ ### Your own annotations
104
+
105
+ Any keyword starting `x-` is an annotation. It can hold any JSON, and it never
106
+ affects whether a body fits. A new annotation, or a new `x-kind`, is a
107
+ convention between apps, not a change to the protocol.
108
+
109
+ Keep annotations to plain values. If the validator can't build from a schema,
110
+ it checks nothing against it. An `$id` inside an annotation is enough to
111
+ cause that.
90
112
 
91
113
  ### Validating
92
114
 
93
- A body is checked against a stored schema as draft 2020-12 JSON Schema, with
94
- unknown keywords ignored, so a space written by a newer app that allows more
95
- stays readable by an older one. Every failing leaf is reported, not only the
96
- first, with a JSON Pointer to the value. The validator is
97
- `@cfworker/json-schema`, which interprets rather than compiles, so it runs
98
- under a strict CSP. A schema it can't build a validator from (it follows
99
- `$id`s into any key it doesn't know, so a bad one in an annotation is enough)
100
- checks nothing, like an invalid definition; reading never fails on it.
115
+ A body is checked against the stored schema as draft 2020-12 JSON Schema.
116
+ Keywords it doesn't know are ignored, so a space written by a newer app stays
117
+ readable by an older one. Every failing value is reported, not only the
118
+ first, each with a JSON Pointer to it.
101
119
 
102
- A record that doesn't fit the schema is still kept and synced, and comes back
103
- with `conforms: false` and the issues. Shape is checked when you write, not
104
- enforced on arrival, because two peers may have seen different versions of a
105
- definition ([spec 02 §9.6](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md)).
106
- Rules, below, are enforced everywhere.
120
+ The validator interprets the schema rather than compiling it, so it runs
121
+ under a strict Content Security Policy. A schema it can't build a validator
122
+ from checks nothing, as if there were no definition. Reading never fails
123
+ because of one.
107
124
 
108
- _Source: `packages/core/src/schema/collection-def.ts` (`validateJsonSchema`, `toJsonSchema`, `asStandardSchema`), `packages/core/src/node/space-catalog.ts` (`contentIssues`). Tests: `packages/core/tests/space-catalog.test.ts` ("validate and reject within the supported subset", "an unknown keyword is ignored when validating, so newer spaces stay readable", "choices can carry labels, or come from a linked record", "an x-\* keyword is an annotation: any one publishes, and no value is checked against it", "a record that does not fit is kept and flagged when it arrives, never rejected"), `packages/core/tests/attacks.test.ts` ("a definition the validator can't use can't break reading the collection, or the space"), `packages/core/tests/schemas.test.ts` ("schemas from a validator you already use")._
125
+ Shape is checked when you write. It is not enforced when a record arrives,
126
+ because two peers may have seen different versions of a definition. A record
127
+ that doesn't fit is still kept and synced, and comes back with
128
+ `conforms: false` and its issues. [Rules](#rules) are different: every peer
129
+ enforces them.
109
130
 
110
131
  ## Links
111
132
 
112
133
  Records point at each other with links: `{ rel: 'about', to: <record key> }`.
113
- A definition declares the roles its records may carry:
134
+ A definition says which link roles its records may carry, and where each may
135
+ point:
114
136
 
115
137
  ```typescript
116
- links: {
117
- about: { to: ['app.poll'], cardinality: 'one' }, // only at polls, at most one
118
- mentions: { to: '*' }, // at anything, many
119
- },
120
- ```
138
+ import type { DefineCollection } from '@minca/core';
121
139
 
122
- A link role is lower camel case. Queries follow links with `include`, and
123
- filter on them with `link:<rel>` ([records-and-queries.md](records-and-queries.md)).
140
+ const links: DefineCollection['links'] = {
141
+ about: { to: ['app.poll'], cardinality: 'one' }, // only at polls, at most one
142
+ mentions: { to: '*' }, // at anything, many
143
+ };
144
+ ```
124
145
 
125
- **A record that points at another record says so with a link**, never with
126
- the other record's key in a body field. Everything that follows relations
127
- works on links and only on links: declarations and conformance, `onePer`,
128
- contracts, `include` and counts, automations ([automations.md](automations.md)), and the "what
129
- points here" a record's page shows. A key in a body field is a string to all
130
- of them. Fields are for values and for people (DIDs); links are for records.
131
- If a keeper must match on a link without reading, make it a topic:
132
- `topics: ['link:channel']`.
146
+ A role's name is lower camel case. Queries follow links with `include`, and
147
+ filter on them with `link:<rel>` ([records and queries](records-and-queries.md)).
133
148
 
134
- Like a schema, link declarations are checked when you write: the node refuses
135
- to sign links that don't conform. A record that arrives with links that
136
- don't conform is kept and comes back with `conforms: false`.
149
+ When a record points at another record, use a link. Don't put the other
150
+ record's key in a body field. Everything that follows relations reads links
151
+ and only links: rules, contracts, `include` and counts,
152
+ [automations](automations.md), and the "what points here" on a record's
153
+ page. To all of them, a key in a body field is just a string. Use fields for
154
+ values and for people (DIDs), and links for records.
137
155
 
138
- _Source: `packages/core/src/records/links.ts` (`checkLinks`), `packages/core/src/node/space-catalog.ts` (`linkIssues`), `packages/core/src/node/space-writing.ts` (`write`). Tests: `packages/core/tests/links.test.ts` ("refused on write when they break the declaration; flagged, never rejected, when they arrive")._
156
+ Links are checked like a schema. Your node refuses to sign links that don't
157
+ fit the declaration. A record that arrives with links that don't fit is kept,
158
+ and comes back with `conforms: false`.
139
159
 
140
160
  ## Rules
141
161
 
142
- A definition says what its records must keep to, not who may write them:
143
- who may create, change and delete records is the space's grants, held by its
144
- roles ([roles](#roles)). Its rules are about the records alone
145
- ([spec 02 §7](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md)):
162
+ Rules say what a collection's records must keep to. Every peer enforces them.
163
+
164
+ | Rule | Means |
165
+ | -------- | ------------------------------------------------------ |
166
+ | `onePer` | at most one record per combination of these values |
167
+ | `fixed` | fields that keep the value the record was created with |
168
+ | `final` | `true`: written once, then never edited or deleted |
146
169
 
147
- | Rule | Means | Default |
148
- | -------- | ------------------------------------------------------ | ------- |
149
- | `onePer` | At most one record per combination of these | none |
150
- | `fixed` | Fields that keep the value the record was created with | none |
151
- | `final` | `true`: written once, then never edited or deleted | none |
170
+ None is set by default. To keep a poll's options from changing after people
171
+ vote:
152
172
 
173
+ ```typescript
174
+ import type { CollectionRules } from '@minca/core';
175
+
176
+ const rules: CollectionRules = { fixed: ['options'] };
177
+ ```
178
+
179
+ Rules don't say who may write. That belongs to the space's [roles](permissions.md).
153
180
  A definition with `create`, `edit`, `delete` or `check` in its rules is
154
- invalid: every peer treats it as no definition at all, and the node refuses
155
- to write it. What a version must be to count is not a rule but the
156
- definition's `contract` ([below](#contracts)).
181
+ invalid: every peer treats it as no definition at all, and your node refuses
182
+ to write it.
157
183
 
158
- `onePer` names `@author` (the writer), `link:<rel>` (the record a link points
159
- at) or a body field. It works by construction: the record's key is derived
160
- from those values, so a second vote from the same person on the same poll is
161
- the first vote's next version, not a new record.
184
+ ### One per
185
+
186
+ `onePer` names `@author` (the writer), `link:<rel>` (the record a link
187
+ points at) or a body field. One vote per person per poll is:
162
188
 
163
189
  ```typescript
164
- rules: {
165
- onePer: ['@author', 'link:about'];
166
- } // one vote per person per poll
190
+ import type { CollectionRules } from '@minca/core';
191
+
192
+ const rules: CollectionRules = { onePer: ['@author', 'link:about'] };
167
193
  ```
168
194
 
195
+ It works by giving the record a key made from those values. A second vote
196
+ from the same person on the same poll lands on the same key, so it becomes
197
+ the first vote's next version.
198
+
169
199
  With `@author`, the key is the writer's own, so nobody else can write their
170
- vote. Without it (one decision per proposal) the key is shared: anyone
171
- allowed to write there may write first, and two who do so apart each start a
172
- version of their own, the later edits of one outranking the other's. A grant
173
- on `.byCreator` only keeps others from editing your version. If a collection
174
- needs one writer per key, grant creating it to fewer roles, or name
175
- `@author`. `node.records.onePerKey(space, collection, body, { links })` gives
176
- the key a body would have, to read a record without searching for it.
200
+ vote. Without it, as in one decision per proposal, the key is shared. Anyone
201
+ allowed to write may write first, and two people who do so apart each start a
202
+ version of their own, with the later edits of one outranking the other's. A
203
+ grant on `.byCreator` only keeps others from editing your version. If a
204
+ collection needs one writer per key, name `@author`, or let fewer roles
205
+ create it.
177
206
 
178
- _Source: `packages/core/src/records/rules.ts` (`checkRules`, `onePerKey`). Tests: `packages/core/tests/rules.test.ts`, `packages/core/tests/record-keys.test.ts` ("onePer keys")._
207
+ `node.records.onePerKey(space, collection, body, { links })` gives the key a
208
+ body would have, so you can read the record without searching for it.
179
209
 
180
- ## Contracts
210
+ ## Roles
211
+
212
+ Who may write lives in the space, not in a definition: in its roles. See
213
+ [Permissions](permissions.md).
181
214
 
182
- What only needs to look the same in every app, like a todo that is done
183
- once two people react 👍, is a [computed field](computed.md): every node
184
- derives it from what it holds, with nothing to cite. A contract is for what
185
- must be fixed and the same on every node.
215
+ ## Contracts
186
216
 
187
- Grants say who may write, and the rules above what a record must keep to;
188
- every peer enforces both. A contract, the definition's `contract`, says
189
- what a version must be to count: conditions over the body, the version before
190
- it, and other versions it **cites** as evidence. With them a space can hold things
191
- that normally need a server or a smart contract: a proposal that passes only
192
- with enough votes, a game whose moves must be legal, points that can't be
193
- spent twice, a reward that unlocks when its condition is met.
217
+ A contract says what a version must be to count. It can check the body, the
218
+ version before it, and other versions it cites as evidence. With one, a space
219
+ can hold things that usually need a server: a proposal that passes only with
220
+ enough votes, points that can't be spent twice.
194
221
 
195
222
  ```typescript
223
+ import * as z from 'zod';
224
+ import { collection, type NodeRecord } from '@minca/core';
225
+
226
+ const vote = collection({
227
+ name: 'app.proposal.vote',
228
+ schema: z.object({ choice: z.enum(['yes', 'no']) }),
229
+ links: { about: { to: ['app.proposal'], cardinality: 'one' } },
230
+ rules: { onePer: ['@author', 'link:about'], final: true },
231
+ });
232
+
196
233
  export const passed = collection({
197
234
  name: 'app.proposal.passed',
198
235
  schema: z.object({ votes: z.array(z.string()) }),
@@ -212,219 +249,102 @@ export const passed = collection({
212
249
  });
213
250
 
214
251
  // The app finds the votes and cites them by version id
215
- const votes = await node.records.linked(space.id, proposal.key, { collection: 'app.proposal.vote' });
216
- await node.records.put(
217
- space.id,
218
- passed,
219
- { votes: votes.map((v) => v.version) },
220
- { links: [{ rel: 'about', to: proposal.key }] },
221
- );
252
+ async function pass(proposal: NodeRecord) {
253
+ const votes = await node.records.linked(space.id, proposal.key, { collection: vote.name });
254
+ await node.records.put(
255
+ space.id,
256
+ passed,
257
+ { votes: votes.map((v) => v.version) },
258
+ { links: [{ rel: 'about', to: proposal.key }] },
259
+ );
260
+ }
222
261
  ```
223
262
 
224
- A contract never searches, because no device holds everything. The writer does
225
- the work (finds the votes, adds up the balances, picks the move) and cites
226
- what proves it. Every reader then checks that exactly what was cited proves
227
- it.
228
-
229
- Contracts are judged by readers, not enforced by peers
230
- ([spec 09](../../../spec/09-contracts.md), [contracts.md](contracts.md)). A version that fails them is kept and synced
231
- everywhere like any other, but `get`, `list` and queries count only a
232
- record's newest version that passes: one that fails is skipped, and the
233
- version before shows instead. Your own node refuses to sign a version that
234
- fails, with the condition's `else` as the reason. `node.records.contracts(space, key)`
235
- says how a record's newest version fares, and why. A version citing one that
236
- hasn't arrived yet is pending, and doesn't count until it does.
237
-
238
- A condition is a [CEL](https://cel.dev) expression: the Common Expression
239
- Language that Kubernetes, Firebase and Envoy use for policies. It reads `body`,
240
- `links`, `key`, `seq`, `collection`, `author` (the account), `creator`,
241
- `createdAt` and `prev` (the version before, or `null`). It has CEL's
242
- operators, `has()`, the macros `all` `exists` `exists_one` `filter` `map`,
243
- `size`, `contains` `startsWith` `endsWith`, the conversions `int` `uint`
244
- `double` `string` `bool`, and from CEL's extensions `distinct()`,
245
- `math.greatest` and `math.least`. Minca adds `sum(list)`, `hash(x)`,
246
- `link("rel")` and `v.link("rel")`, and two that ask the space:
247
- `versions(ids)` (read cited versions by id) and `member(did)`.
248
-
249
- Some things to know:
250
-
251
- - A body's numbers are doubles, as JSON's are, and a literal like `1` is an
252
- int. They compare with each other freely, but don't mix in arithmetic:
253
- write `body.n + 1.0`, or `int(body.n) + 1`.
254
- - Reading a field that isn't there is an error, not `null`: ask
255
- `has(body.note)` first. `&&` and `||` let an error pass when the other side
256
- decides.
257
- - A condition holds only when it gives `true`, and it always ends: its
258
- only loops are over lists in hand, and there is a step limit.
259
-
260
- `contractCostHints(check)` flags what makes a condition costly as records grow:
261
- macros nested three deep, or `versions()` called inside a macro. A condition
262
- over more than its limits is refused, so one that passes on small
263
- records can fail on large ones; the hints say where to look.
264
-
265
- `check` written as a function, as above, builds that CEL from TypeScript,
266
- typed from the collection's own schema and, through `cited(ids, collection)`,
267
- from the schemas of what it cites: a misspelled field is a compile error
268
- ([contracts.md](contracts.md#writing-one-in-typescript)). A list of
269
- `{ that, else }` with the CEL written by hand is stored the same way. Either
270
- way, `collections.define` refuses a condition that misreads the schema.
271
-
272
- Bytes, timestamps, durations, regular expressions and types as values are
273
- left out. The exact subset, and its limits, are in [spec 09](../../../spec/09-contracts.md).
274
-
275
- **Lines.** A collection whose contract has `line: { once: [...] }` is one line per
276
- account, at `lineKey(account, collection)`: each version names the account's
277
- previous one, so a payment can carry a running balance its contract checks.
278
- Two versions after the same one are a double spend, and neither counts, nor
279
- anything after either; there is no way back, so keep a line on one device at
280
- a time. Each citation in a `once` field may appear only once along the line
281
- ([spec 09 §7](../../../spec/09-contracts.md#7-lines)).
282
-
283
- **What can be cited.** Only versions kept whole, so every device reads the
284
- same thing however late it joins: any version in a collection with
285
- `history: 'all'` or with a contract of its own (the node keeps those whole), and
286
- a first version under `onePer` or `fixed`. A cited version must also pass its
287
- own contract. Give a collection you mean to cite `history: 'all'`,
288
- or an edited vote's latest version can't be cited. A cited version proves
289
- what was signed, not that it is still current, so make evidence final where
290
- it matters: `final: true` on a vote, so nobody can change or delete it once
291
- it is counted, or `fixed: ['choice']` to allow other edits.
292
-
293
- **A proof stays a proof.** A cited version is judged as of what the citing
294
- version saw: removing a voter later, or revoking the device that voted,
295
- doesn't undo a decision that already counted the vote. A decision written
296
- after seeing the removal can't count it. Peers keep such withdrawn versions,
297
- and the library reads them for this, without showing them.
298
-
299
- The standard library has two ready-made: `std.decision`, a proposal decided
300
- by a quorum of ballots, and `std.goal-reached`, a goal reached by pledges
301
- ([standard-library.md](standard-library.md)).
302
-
303
- **Patterns.**
304
-
305
- - **Quorums and multisig.** "Three members approved": cite the approvals, and
306
- check `distinct()` authors with `member(v.author)`. Who may approve at all
307
- is the grant on the approvals' collection.
308
- - **State machines.** Check each version against `prev`: a task moves from
309
- `open` to `done` only, a counter goes up by one, a chess move is legal from
310
- the board before. Each step is small, and there is no limit on steps.
311
- - **Ledgers.** A transfer cites the balance records it spends, and checks
312
- that they are the sender's and add up. Two spends of one balance are two
313
- versions of it, which everyone sees.
314
- - **Commit, then reveal.** A player first writes `hash` of a secret, then
315
- reveals it: `hash(body.secret) == "<the commitment>"`.
316
- Shared dice, lotteries and sealed bids need nothing else.
317
- - **Closing a set.** A contract can prove that something exists, not that nothing
318
- else does. For "a majority" or "nobody objected", someone granted it
319
- signs a record that closes the vote and lists what counts, and the result
320
- cites that.
321
- - **Time.** There is no clock. "Before Friday" is a record from someone
322
- trusted to say it (a host, a witness) that the result cites.
323
-
324
- ## Roles
325
-
326
- Who may write lives in the space, not in your code, and not in a
327
- definition. A role holds grants: a command and a UCAN policy over its
328
- arguments ([spec 03 §2](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md)).
329
- "Members change only their own polls, hosts delete any" is:
263
+ The writer does the work of finding the votes, and cites them. Every reader
264
+ checks that what was cited proves the claim. A version that fails is kept and
265
+ synced, but reads skip it and show the version before.
330
266
 
331
- ```typescript
332
- import { RECORD_DELETE, RECORD_WRITE } from '@minca/core';
267
+ When a value only needs to look the same in every app, like a to-do that is
268
+ done once two people react, a [computed field](computed.md) is simpler. How
269
+ to write contracts, and what they can check, is in [Contracts](contracts.md).
333
270
 
334
- await node.spaces.defineRole(space.id, {
335
- name: 'host',
336
- title: 'Host',
337
- grants: [{ cmd: RECORD_DELETE, pol: [['==', '.collection', 'app.poll']] }],
338
- nests: ['member'], // a host holds what a member holds too
339
- });
340
- await node.spaces.assign(space.id, did, 'host');
341
- ```
271
+ ## Other options
342
272
 
343
- - `/record/write` and `/record/delete` see `collection` and `byCreator`
344
- (whether the writer's account made the record's first version; true for a
345
- new one); a write also sees `body`. So `['==', '.byCreator', true]` is
346
- "only your own".
347
- - `/collection/define` adds or changes collections; it also needs a note that
348
- grants `/collection/define`, which an agent's doesn't (spec 01 §8).
349
- - A definition holds only what its writer could do: you can't grant what you
350
- don't hold. Roles defining roles, assigning, removing and the rest are in
351
- the spec.
352
- - The space's founders, if it has any, hold every command.
353
-
354
- `node.spaces.may(space.id, cmd, args)` says whether this account may do
355
- something now; `node.records.can(space, action, target)` asks it for a
356
- record.
273
+ A definition also takes `history`, `topics` and `version`. Each option is
274
+ described on [`DefineCollection`](https://minca.dev/api/core/interfaces/DefineCollection/).
357
275
 
358
- ## Other options
276
+ Under `history: 'latest'`, some earlier versions are still kept whole. A
277
+ record's first version is, when the rules have `onePer` or `fixed`, since
278
+ those rules are checked against it. With a `contract`, every version is, so
279
+ the contract can read and cite them.
359
280
 
360
- - `history: 'all'` keeps every version of every record whole, hash-linked
361
- (`node.records.history`). The default, `latest`, keeps the current one
362
- whole and forgets what earlier ones said, and what a deleted record said.
363
- With `onePer` or `fixed` in the rules, a record's first version is kept
364
- whole too: those rules are checked against it. With a `contract`, the node
365
- keeps every version whole, so its contract can read the one before and cite it.
366
- - `topics: ['mentions', 'link:channel']` lets a node that can't read the
367
- space still match records by a field's value, or by where a link of that
368
- role points, for the account's wakes ([automations](automations.md#the-accounts-own)).
369
- At most 8.
370
- - `version`: see [below](#versions-of-a-definition).
281
+ The account's wakes match records by their `topics`
282
+ ([automations](automations.md#the-accounts-own)). How `version` is numbered
283
+ is [below](#versions-of-a-definition).
371
284
 
372
285
  ## Versions of a definition
373
286
 
374
287
  Defining a collection again writes the next version of its definition, one
375
- higher unless you give a `version`. The node refuses a `version` that is not
376
- higher than the one in force, or not below 2^53; peers don't check it. One in
377
- force at 2^53 or more, which nothing could follow, is followed by 1. Records don't name the
378
- version they were written under: each is judged by the definition in force
379
- as of the access changes it saw
380
- ([spec 03 §5](https://github.com/leifriksheim/minca/blob/main/spec/03-spaces.md)).
381
- A change to the rules is not retroactive: it binds what saw it. A record that
382
- names an older point counts if its writer could have written it then, since
383
- nobody can tell it from one written offline. To stop someone at once, take
384
- their role or remove them: what they wrote that you had not seen stops
385
- counting. A
386
- write that races a change to its collection's rules is retried once, under
387
- the new ones.
388
-
389
- `node.collections.delete` removes a definition only once its collection has
390
- no records left, since records left behind would lose their shape and their
391
- rules.
392
-
393
- Whoever first defined a collection may change it, while a member, as well as
394
- anyone granted `/collection/define` for it. If two accounts each defined it
395
- first without seeing the other's, `definedBy` is `null` and only those
396
- granted `/collection/define` may change it. Until one does, the
397
- collection has a definition only if the rivals say the same thing; if they
398
- differ, `collections.list` leaves it out and its records are judged by no
399
- rules
400
- ([spec 02 §6.3](https://github.com/leifriksheim/minca/blob/main/spec/02-records.md)).
401
-
402
- _Source: `packages/core/src/node/space-runtime.ts` (`define`, `undefine`), `packages/core/src/node/space-writing.ts` (`write`), `packages/core/src/node/types.ts` (`NodeCollections`). Tests: `packages/core/tests/space-catalog.test.ts`, `packages/core/tests/rules.test.ts` ("grants: changing them")._
288
+ higher unless you give a `version`. Your node refuses a `version` that isn't
289
+ higher than the one in force, or isn't below 2^53. Peers don't check it. A
290
+ definition in force at 2^53 or more, which nothing could follow, is followed
291
+ by 1.
292
+
293
+ Records don't name the version they were written under. Each is judged by
294
+ the definition in force as of the access changes its writer had seen. So a
295
+ change to the rules binds only what was written after seeing it. A record
296
+ written against an older definition counts if its writer could have written
297
+ it then, since nobody can tell it from one written offline. To stop someone
298
+ at once, take their role or remove them: what they wrote that you hadn't
299
+ seen stops counting.
300
+
301
+ A write that races a change to its collection's rules is retried once, under
302
+ the new rules.
303
+
304
+ `node.collections.delete` removes a definition only once the collection has
305
+ no records left, since records left behind would lose their shape and rules.
306
+
307
+ Whoever first defined a collection may change it while they are a member, as
308
+ may anyone granted `/collection/define` for it. If two accounts each defined
309
+ it first without seeing the other, `definedBy` is `null` and only those
310
+ granted `/collection/define` may change it. Until one does, the collection
311
+ has a definition only if both say the same thing. If they differ,
312
+ `collections.list` leaves it out and its records are judged by no rules.
403
313
 
404
314
  ## The standard library
405
315
 
316
+ The standard library is about eighty ready-made collections. Using the same
317
+ one is how two apps agree: a poll asked in one app can be voted on in
318
+ another.
319
+
406
320
  ```typescript
407
321
  import { reaction, comment, poll, vote, useSchemas } from '@minca/core/schemas';
408
322
 
409
323
  await useSchemas(node, space.id, [poll, vote, reaction, comment]); // defines only what the space is missing
410
324
  ```
411
325
 
412
- About eighty definitions, by area (`standardGroups`): annotations that attach
413
- to any record (`reaction`, `comment`, `rating`, `bookmark`, `claim`…), people
414
- (`profile`, `follow`…), messaging and publishing (`message`, `post`,
415
- `article`, `doc` and `docBlock`, `note`…), lists (`list`, `listItem`), files
416
- and media, time and planning (`event`, `rsvp`, `task`, `booking`…), places,
417
- home and life (`recipe`, `meal`…), money (`expense`, `settlement`…) and
418
- community (`poll`, `vote`, `proposal`, `decision`, `goal`…). The full list is in
419
- [standard-library.md](standard-library.md).
420
-
421
- They are ordinary collections. Using the same one is how two apps agree: a
422
- poll asked in one can be voted on in another. For shapes of your own, the
423
- `fragments` export builds times, money, places and files the same way the
424
- library does, and `fragments.define(definition)` gives records a type worked
425
- out from the schema, as every library definition's is (`Task` is
426
- `BodyOf<typeof task>`).
427
-
428
- Hand-made order (cards on a board) uses a `position` string.
326
+ They are ordinary collections, grouped by area in `standardGroups`:
327
+
328
+ - annotations on any record: `reaction`, `comment`, `rating`, `bookmark`,
329
+ `claim`…
330
+ - people: `profile`, `follow`…
331
+ - messaging and publishing: `message`, `post`, `article`, `doc` and
332
+ `docBlock`, `note`…
333
+ - lists: `list`, `listItem`
334
+ - files and media
335
+ - time and planning: `event`, `rsvp`, `task`, `booking`…
336
+ - places
337
+ - home and life: `recipe`, `meal`…
338
+ - money: `expense`, `settlement`…
339
+ - community: `poll`, `vote`, `proposal`, `decision`, `goal`…
340
+
341
+ The full list is in [the standard library](standard-library.md).
342
+
343
+ For shapes of your own, the `fragments` export builds times, money, places
344
+ and files the way the library does. `fragments.define(definition)` gives
345
+ records a type worked out from the schema, as every library definition has:
346
+ `Task` is `BodyOf<typeof task>`.
347
+
348
+ For order people set by hand, like cards on a board, use a `position` string.
429
349
  `positionBetween(before, after)` makes one that sorts between two others, so
430
350
  moving a card rewrites only that card.