@protobase/cli 0.54.6 → 0.55.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.
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.54.6";
2
+ var version = "0.55.0";
3
3
  //#endregion
4
4
  export { version };
@@ -3,8 +3,8 @@ import { anyOf, compare, holds, searchFor } from "./shape-filters.js";
3
3
  const filterOn = (field) => field.type === "json" ? holds(field) : compare(field);
4
4
  /**
5
5
  * What the API takes of a resource from any caller, whatever the views show: a filter on each `.filterable()` field, a
6
- * sort by each `.sortable()` one, `search("...")` over its search fields, and the rows of a role limited to its own
7
- * records, which `.owner()` names.
6
+ * sort by each `.sortable()` one, `search("...")` over its search fields, the rows of a role limited to its own
7
+ * records, which `.owner()` names, and the records whose parent the caller reads, which `.parent(fk, 'read')` names.
8
8
  */
9
9
  const fieldShapes = (model) => {
10
10
  const fields = Object.values(model.fields);
@@ -28,9 +28,17 @@ const fieldShapes = (model) => {
28
28
  from: `the search over ${model.search.join(", ")}`,
29
29
  query: { filter: searchFor }
30
30
  }] : [],
31
- ...ownerShapes(model)
31
+ ...ownerShapes(model),
32
+ ...parentShapes(model)
32
33
  ];
33
34
  };
35
+ const parentShapes = (model) => (model.parents ?? []).filter((parent) => parent.access === "read").map(({ field }) => ({
36
+ resource: model.name,
37
+ request: `GET /${model.name}`,
38
+ from: `its records keep to the "${field}" parents the caller reads`,
39
+ query: {},
40
+ scope: { parents: [{ field: model.fields[field] }] }
41
+ }));
34
42
  const ownerShapes = (model) => {
35
43
  const owner = model.owner === void 0 ? void 0 : model.fields[model.owner];
36
44
  if (!owner) return [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.54.6",
3
+ "version": "0.55.0",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -42,12 +42,12 @@
42
42
  "dependencies": {
43
43
  "@better-auth/core": "^1.7.12",
44
44
  "@hono/node-server": "^2.1.3",
45
- "@protobase/config": "0.54.6",
46
- "@protobase/layout": "0.54.6",
47
- "@protobase/query": "0.54.6",
48
- "@protobase/schema": "0.54.6",
49
- "@protobase/server": "0.54.6",
50
- "@protobase/ui": "0.54.6",
45
+ "@protobase/config": "0.55.0",
46
+ "@protobase/layout": "0.55.0",
47
+ "@protobase/query": "0.55.0",
48
+ "@protobase/schema": "0.55.0",
49
+ "@protobase/server": "0.55.0",
50
+ "@protobase/ui": "0.55.0",
51
51
  "@react-email/render": "^2.1.0",
52
52
  "@scalar/hono-api-reference": "^0.12.10",
53
53
  "@tailwindcss/vite": "^4.3.3",
@@ -12,7 +12,7 @@ Decide who may read and change which records and fields.
12
12
  - [Rules on the stored record](../reference/data-config.md#access): A rule can read the record as it is stored, such as one that refuses changes to a locked invoice.
13
13
  - [Write-only fields](../reference/access.md#write-only-fields): A role can set a field it can never read back, such as a secret only a worker reads. The admin app edits it only where the layout names it, with no stored value to reveal.
14
14
  - [Lists across organizations](../reference/access.md#lists-across-organizations) (beta): One list shows the records of every organization someone is a member of, each read with their role there, with the organization as a filter. Opening a record of another organization switches to it.
15
- - [Access through a parent record](../reference/access.md#records-that-belong-to-another): Writing a child record can require access to the record it belongs to.
15
+ - [Access through a parent record](../reference/access.md#records-that-belong-to-another): Writing a child record can require access to the record it belongs to, and a child can be read only by those who read its parent, such as the messages of a private channel.
16
16
  - [Anonymous access](../reference/access.md#anonymous-access): Visitors without an account can read listed fields of chosen records, such as a public product catalog, and send the public forms you open to them.
17
17
  - [Public browsing](../reference/access.md#browsing-the-admin-app): With anonymous access on, visitors browse what they may read in the admin app without signing in, read-only, with a Sign in button.
18
18
  - [Checked on every request](../reference/api.md#access): The server applies the caller's operations, fields and rows to every request, on lists, record pages, composed pages and the API alike. Each record says what the caller may change in it, so the admin app offers no edit the server would refuse.
@@ -9,6 +9,7 @@ The page of one record, with its sections, related records, galleries, charts an
9
9
  - [Unsaved edits](../reference/ui-config.md#editing-a-record): Unsaved changes to a record stay in the browser and can be resumed, and leaving a form, a dialog or a comment with changes asks first.
10
10
  - [Record forms](../reference/ui-config.md#editing-a-record): Relations are picked from a list that narrows as you type, numbers are read as the browser's language writes them, and a refused save says under each field what is wrong.
11
11
  - [Titles per reader](../reference/ui-config.md#titles-per-reader): A record without a name of its own, such as a direct message, is titled for each reader from its fields, such as after the other members, in the sidebar, breadcrumbs, heading, browser tab, relation links and search.
12
+ - [Member fields](../reference/plugins.md#members): A field that holds a list of people, such as a private channel's members, picks the organization's members by name on forms and shows them by avatar and name.
12
13
  - [Save feedback](../reference/ui-config.md#the-record-page): A view shows saving on the Save button instead of in a toast.
13
14
  - [Save conflicts](../reference/ui-config.md#editing-a-record): When someone else changed a record while you edited it, Save shows their value beside yours for each field you both changed, and you keep yours or take theirs.
14
15
  - [Groups and tabs](../reference/ui-config.md#groups): Parts of a record page sit under headings that open on click, or in tabs, and the open ones are kept in the address.
@@ -162,7 +162,11 @@ export const operations = resource('operations')
162
162
  - **The caller's own rules decide.** The parent is read as the caller would read it, with its tenant, row filters, soft delete and record-level rules; for `update`, also its update row filter and record-level update rule, given an empty input. A parent the caller cannot see, may not update, that is soft deleted or does not exist gets the same `403` as a refused create (`You may not create this operations record`), and nothing is written: the answer does not tell which VM ids exist.
163
163
  - **One column, to a key of one field.** <gap>A relation of several columns cannot be a parent: the config does not load with one.</gap> The server does not start with a parent resource the app does not have. <gap>A resource whose key has several fields cannot be a parent: the server does not start with one.</gap>
164
164
  - **A null relation checks nothing.** A relation set by a column default or a trigger is checked from the record as written.
165
- - **`update` follows the parent's own parents**, so with VMs under `.parent((r) => r.folder_id, 'update')` an operation needs update on the VM's folder too. A write that would put a record under itself, or under a cycle already in the data, is refused. A `read` parent is not followed further.
165
+ - **`update` follows the parent's own parents**, so with VMs under `.parent((r) => r.folder_id, 'update')` an operation needs update on the VM's folder too. A write that would put a record under itself, or under a cycle already in the data, is refused. A `read` parent is followed only as far as reading it does (below).
166
+ - **`read` also narrows every read.** With `.parent((r) => r.channel_id, 'read')`, a caller reads only the messages of channels they read: lists, `:search` and `:seek`, their counts, facets, charts and aggregates, a get (`404` outside, as for a row filter), relation labels, history, comments and reveals, through `/api/v1`, its batches and MCP, and the deliveries of a [subscription](webhooks.md#subscription) that runs as a role. The parent is read with the caller's own tenant, row filter and soft delete there, and its own `read` parents, so a channel whose members are listed in a `member_ids` JSON field with the read rule `where.or(where.eq('kind', 'public'), where.has('member_ids', ctx.user.id))` keeps its messages to its members, and taking someone off `member_ids` hides them on the next read. A message with a null `channel_id` names no channel and stays visible under its own rules, so a message with two nullable parents, `channel_id` or `direct_message_id`, keeps to the one it names.
167
+ - **One indexed subquery.** The narrowing is `channel_id in (select id from channels where <the caller's channel filter>)` ANDed into the child's query (`channel_id is null or ...` for a nullable relation), so the [scan guard](api.md#safety) needs an index on `channel_id` and indexes serving the columns of the parent's row filter, such as a GIN index on `member_ids`, and `protobase doctor` names a missing index on the relation.
168
+ - **A parent whose read rule reads the record hides its children.** Such a rule is no filter a query can hold, so a caller whose read rule on the parent needs the record, or who cannot read the parent resource, reads only the children with a null relation. <gap>A child under a parent whose read rule reads the record cannot be read because checking the parent per record is not implemented.</gap> Make the parent's read rule return a row filter instead. A resource that is its own parent, such as a folder tree, is checked one level up: a folder needs its parent folder readable. <gap>A record of a tree cannot keep to every ancestor because a transitive parent check is not implemented.</gap>
169
+ - **Across organizations, the session's own only.** <gap>A list across organizations cannot read a resource with a `read` parent beyond the session's own organization because resolving the parent in each organization is not implemented.</gap> The server warns at startup and lists the session's organization alone.
166
170
  - **Several parents** are each checked with their own access, also two of one resource, such as a transfer that reads its `source_vm_id` and updates its `target_vm_id`.
167
171
  - **The parent is locked until the write commits** (`FOR NO KEY UPDATE`), so a VM handed to someone else or deleted at the same moment is waited for and checked again. That is the cost: writes of records under one parent, and through an `update` parent under one ancestor, run one after another. The server's database role needs `UPDATE` on the parent's table to take the lock. Two writes that lock the same records in opposite orders, such as two batches writing under VM A then B and B then A, can deadlock: Postgres rolls one back, which answers `409` and writes nothing, and the client sends it again.
168
172
  - The record page and `/api/meta` count the check, so the admin app offers no Edit or Delete the server would refuse. `/api/sb/rest/v1` does not use Protobase's access rules at all, so this check is not part of it.
@@ -94,6 +94,7 @@ Access is resolved once per request and resource ([`resolveAccess`](https://docs
94
94
  - **Sensitive fields** are readable fields that no response carries and no request may name, except `:reveal`; they can be written. See [Sensitive fields and audit](#sensitive-fields-and-audit).
95
95
  - **Writable fields**: only fields the caller may write and read are accepted, and [write-only](access.md#write-only-fields) ones; any other is `400`, worded as unknown (hidden) or read-only.
96
96
  - **Row filters**: a rule that returns a filter (`.own`, `.team`) narrows every read (list, get, aggregates) and the rows a write may target; the database applies it, so it may use columns the caller cannot see. A row outside it is a `404`.
97
+ - **Parents**: a resource declared with `.parent(fk, 'read')` narrows every read to the rows whose parent the caller reads under the parent's own access, a row outside being a `404` (see [Records that belong to another](access.md#records-that-belong-to-another)).
97
98
  - **Record-level rules** (a rule that needs the record, such as `status != 'locked'`) run in the write transaction with the stored record; a filter they return is checked in the database against the row as written, and a miss rolls the write back with `403`.
98
99
  - **`.own` on create**: when the create rule is limited to rows, the owner field is set to the caller unless given, and a row owned by someone else is refused with `403`.
99
100
  - **Seeking**: `:seek` resolves a row position to a page on the server, inside the caller's tenant, row filter and filter. No anchor value, column statistic or boundary token is ever returned (table-wide statistics include rows the caller may not see), only the page and the tokens of its own rows.
@@ -198,7 +199,7 @@ The API sends no CORS headers until it has something to allow: other websites in
198
199
 
199
200
  - Every request runs in a transaction with `SET LOCAL statement_timeout` (`statementTimeoutMs`, default 1 s), so a slow query fails where it runs instead of holding a connection that other requests wait for. List, search, get, histogram, series, map and seek transactions are read-only. A query that runs longer is stopped: a `504` `statement-timeout` that names the request, its limit and the ways out, such as `GET /api/v1/orders ran a query longer than 1 s, so the database stopped it. Make the query faster, such as with an index or a narrower filter, or move the work into a function or job with longQueries: true, whose queries may run up to 30 s.` It goes to the app's error hook (`hooks/error.ts`, `createAdmin`'s `options.onUnhandledError`) and the [error tracker](#error-reporting) like a `500`. A read that needs longer has no way to opt out: give it an index, or move it into a [function](../guides/api-functions.md#long-queries) or [job](jobs.md) with `longQueries`.
200
201
  - Under `protobase dev` and `serve`, a request waits at most 2 seconds for a free database connection. When every connection stays busy that long, it is a `503` `connections-busy` with `Retry-After: 1` that names the request, reported the same way, rather than a request that hangs behind slow ones.
201
- - **Scan guard**: a list, `:search`, `:seek`, `:map` page, card photos, `:facets` and `:aggregate` read only columns an index serves, so they stay cheap however many rows match. The server reads each table's valid indexes from the catalog once, then checks every column the caller's filter, the role's row filter, the sort's first field and a facet's or an aggregate's grouped field read:
202
+ - **Scan guard**: a list, `:search`, `:seek`, `:map` page, card photos, `:facets` and `:aggregate` read only columns an index serves, so they stay cheap however many rows match. The server reads each table's valid indexes from the catalog once, then checks every column the caller's filter, the role's row filter, the sort's first field, a facet's or an aggregate's grouped field and a [`read` parent](access.md#records-that-belong-to-another)'s relation read, and the columns of the parent's own row filter against the parent's table:
202
203
  - Comparisons, `in`, null checks, sorts and facets need a btree index with the column as a key, every key before it pinned by the query: by `=` or `in` in the filter (outside `OR` and `NOT`), by the tenant or by soft delete. `(for_sale, status, published_at desc)` serves `for_sale = true AND status = "available"` sorted by `published_at desc`, but not `status` alone. `=` on text may use a pg_trgm index instead.
203
204
  - Patterns (`name = "*port*"`), `regex()`, `similar()` and `search()` need a pg_trgm (GIN or GiST) index on each column they read, a `digitsEnd` search field one on its digits; JSON `field:value` needs a GIN index.
204
205
  - A partial index counts for nothing, and a resource on a plain view or a foreign table, which has no indexes of its own, is not checked.
@@ -64,7 +64,7 @@ export const repairs = resource('repairs')
64
64
  | `.author((r) => r.author_id)` | The field holding the id of the user who created the record, such as a chat message's sender: every create sets it to the signed-in user's id, and no request may write it, so a body that names it is refused as read-only. A create by no one signed in, through a [public form](forms.md), leaves it empty. Its column is checked at startup as an owner's is. |
65
65
  | `.search((r) => [r.number, r.name])` | The fields that `search("...")` and bare words in a filter match, and what the admin's [global search](client.md#global-search) looks in. Every word of the text must appear in one of them, ignoring case, and part of a word is enough: `port` finds "Portfolio". `r.phone.digitsEnd()` matches only the end of a field's digits instead, ignoring spaces, `+` and dashes, and only words written like phone numbers: `9623`, `47069623` and `+31 6 47069623` find "+31 6 47069623", `4706` and `+316` do not. Each field needs a pg_trgm index (`using gin (name gin_trgm_ops)`), a `digitsEnd` one on `regexp_replace(phone, '[^0-9]', '', 'g')`, or the API refuses the search. |
66
66
  | `.position((r) => r.position, { within?, after? })` | The integer field holding the records' order by hand, 1 the first, which a list's **Reorder** button changes by dragging; with `within: (r) => r.invoice_id`, a filterable relation, each parent's records have an order of their own, sorted in its related section; with `after`, a record never ranks above the records it depends on. The field must be sortable. See [Reordering by hand](ui-config.md#reordering-by-hand) and [Ranked after what they depend on](ui-config.md#ranked-after-what-they-depend-on). |
67
- | `.parent((r) => r.vm_id, 'update')` | The relation whose record each record belongs to, and the access on it (`'read'` or `'update'`) that creating, changing, deleting and undeleting a record needs, checked with the caller's own rules on that resource. The relation is one column, to a resource with a key of one field. See [Records that belong to another](access.md#records-that-belong-to-another). |
67
+ | `.parent((r) => r.vm_id, 'update')` | The relation whose record each record belongs to, and the access on it (`'read'` or `'update'`) that creating, changing, deleting and undeleting a record needs, checked with the caller's own rules on that resource. With `'read'`, every read of its records also keeps to those whose parent the caller reads. The relation is one column, to a resource with a key of one field. See [Records that belong to another](access.md#records-that-belong-to-another). |
68
68
  | `.validate((record) => issues)` | A rule over the whole record, run after the field checks on every create and update. It returns `[{ field, message }]` or `undefined`; issues answer `400` with the field named. |
69
69
  | `.access({ ... })` | Rules per operation. See [Access](#access). |
70
70
  | `.events((e, r) => [...])` | What changes of its records mean, such as `orders.created`, captured in the database for every write. See [Events](events.md). |
@@ -126,7 +126,7 @@ view<typeof repairs>('repairs').fields((r) => ({ status: r.status.widget('steps'
126
126
  | --- | --- |
127
127
  | `of` | The storage types it shows, from `f.*`: `'text'`, `'integer'`, `'decimal'`, `'enum'`, `'boolean'`, `'date'`, ... A field of another type shows as it would without the field type. |
128
128
  | `display` | Shows a value: on the record page when the field may not change, in the record's summary, on cards and in page elements. |
129
- | `editor` | Edits a value, on the record page and the create form, when the field may change. Without it, the field keeps its built-in input. Files and relations are uploaded and chosen as the app does it; their field types only show them. |
129
+ | `editor` | Edits a value, on the record page and the create form, when the field may change. Without it, the field keeps its built-in input. A JSON field has no built-in input: it is on these forms only when the view picks a field type for it, and only that field type's editor changes it. Files and relations are uploaded and chosen as the app does it; their field types only show them. |
130
130
  | `cell` | Shows a value in a table cell; `display` when left out. |
131
131
 
132
132
  Each part gets:
@@ -147,6 +147,20 @@ Each part gets:
147
147
 
148
148
  [Adding a field type](../guides/field-type.md) builds one step by step.
149
149
 
150
+ ### Members
151
+
152
+ `members` is a field type Protobase brings, for a JSON field that holds an array of user ids, such as who may read a private channel. No plugin registers it; a view picks it as it picks any other:
153
+
154
+ ```ts
155
+ // config/channels/data.ts
156
+ resource('channels').fields({ id: f.uuid(), name: f.text(), member_ids: f.json() })
157
+
158
+ // config/channels/ui.ts
159
+ view<typeof channels>('channels').fields((r) => ({ member_ids: r.member_ids.widget('members') }))
160
+ ```
161
+
162
+ The create form and the record's form pick the members of the organization the session works in by name: typing narrows them, each choice is a token whose button takes it off again, and choosing a chosen member takes them off too. It stores their user ids, the ids `.author()` stores and [`useMembers()`](custom-components.md#members-names) gives, never membership ids. The record page, cards and the list's table show each member by avatar and name; an id that is no longer a member shows as an unknown member. A JSON field is on a form only through a field type that edits it, so without the hint `member_ids` stays read-only. The field needs [organizations](auth.md#organizations); in an app without them it says so in place of the members. <gap>The members picker cannot search on the server because a server-side people resource is not implemented, so it loads the whole list in the browser, as `useMembers()` does.</gap> A plugin that registers a field type named `members` replaces it, and the server refuses to start when a view picks it for a field that is no JSON.
163
+
150
164
  ## Building
151
165
 
152
166
  ```sh
@@ -101,7 +101,7 @@ Field hints:
101
101
  | `.icon(name)` | An icon before the value on a card's meta row: one of the names [actions](layouts.md#named-actions) take, such as `bed`, `calendar` or `cpu`, and above the value in a section of [key facts](#key-facts). Nowhere else shows it. |
102
102
  | `.valueLabels({ value: text })` | How an enum's values read: `r.method.valueLabels({ ideal: 'iDEAL' })`. Only the enum's values are accepted. A value without a label shows as stored (`direct_debit`), so label every value that should read as words. |
103
103
  | `.valueColors({ value: '#hex' })`, `.badgeShape('arrow')` | An enum's badges filled with a colour per value (the text turns white or black, whichever reads), and drawn as arrows pointing right, as on a rating scale. The property portal's energy label: `r.energy_label.format('badge').valueColors({ a: '#00a651', g: '#ed1c24' }).badgeShape('arrow')`. Only the enum's values are accepted. |
104
- | `.widget(name, props?)` | Shows and edits the field with a [field type](plugins.md#field-types) of the project or a plugin, such as `r.status.widget('steps')` or `r.score.widget('rating', { max: 5 })`; `props` are plain data. Without it, or on a storage type it does not show, the field shows as it would without the hint. |
104
+ | `.widget(name, props?)` | Shows and edits the field with a [field type](plugins.md#field-types) of the project or a plugin, such as `r.status.widget('steps')` or `r.score.widget('rating', { max: 5 })`, or with the built-in [`members`](plugins.md#members), which picks an organization's members into a JSON array of user ids; `props` are plain data. Without it, or on a storage type it does not show, the field shows as it would without the hint. |
105
105
 
106
106
  An enum's value labels show everywhere the admin shows its values: badges, select options, list and related-table cells, filter options and chips, record titles, the sidebar and search results. They are part of the view in `/api/meta`, so an app with its own screens can show them too, and [`enumLabel(value, labels)`](https://docs.protobase.net/api/schema/functions/enumlabel/) from `@protobase/schema` reads a value the same way. A label for a value the enum does not have stops the server at startup, so renaming a value cannot leave a stale label behind.
107
107