foldkit-guard 0.5.0 → 0.6.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.
package/README.md CHANGED
@@ -428,7 +428,16 @@ writes. The guard requires each incremented member's Update rule, as for a
428
428
  member it sets, and holds the row's rules over the sum the writer will store, so
429
429
  a rule `stock >= 0` refuses a sale past zero. The row the guard summed over must
430
430
  be the row the writer writes: the input's expected revision keeps it so, or the
431
- writer's `revision` pin. An increment with neither is refused.
431
+ writer's `revision` pin. An increment with neither is refused. A computed
432
+ assignment is the same: its member's Update rule holds, the guard reads what it
433
+ computes from, and judges the row `Write.apply` works out by the writer's own
434
+ table (`EntityWriter.operators`, the binding's for the Drizzle writer), which is
435
+ the row the writer writes; one it cannot work out is refused, never judged as
436
+ it was. With a `revision` the guarded writer `pins`, so under a ledger a
437
+ real-number increment or a computed assignment needs no `expect` of its own (no
438
+ writer lands one without either); `validate`
439
+ refuses one computed from a member with a Read rule, which its answer would
440
+ disclose.
432
441
 
433
442
  An Entity's invariants (`Entity.invariant`) are the writer's to judge, over the
434
443
  row its statement writes; the guarded writer passes them through and speaks
package/dist/agent.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { j as MayAnswer, l as InteractionKey } from "./attach-BnP9_Uca.mjs";
1
+ import { j as MayAnswer, l as InteractionKey } from "./attach-BepaL930.mjs";
2
2
  import { RemoteData } from "foldkit-remote";
3
3
  /** A row read with `may`, as `Data.get(Row, id).read(model)` gives it. */
4
4
  type MayRow = RemoteData<{
@@ -37,6 +37,10 @@ declare const Condition: {
37
37
  * `input` (the principal's, from `G.inputOf`). `inherit` answers whether the
38
38
  * row a relation points at is readable, which only the caller can look up.
39
39
  * `operators` runs the guards' primitive operators: the policy's.
40
+ *
41
+ * A row guard the row's own values make an operator refuse (text holding a
42
+ * NUL, an implementation that throws) does not hold: what a write supplies
43
+ * can deny it, never end the request.
40
44
  */
41
45
  holds: (condition: Condition, values: Readonly<Record<string, unknown>>, input: Readonly<Record<string, unknown>>, inherit: (relation: string) => boolean, operators: MemoryOperators) => boolean;
42
46
  /**
@@ -507,4 +511,4 @@ interface Attachment {
507
511
  }
508
512
  declare const attached: (entity: AnyEntity) => Option.Option<Attachment>;
509
513
  export { May as A, PrincipalGuard as C, RowSpec as D, RowGuard as E, RowRule as F, MaySchema as M, Condition as N, ME as O, MemberRead as P, Policy as S, PrincipalSpec as T, Builders as _, Deny as a, Guards as b, Interaction as c, Redact as d, RuleFor as f, Body as g, AnyGuard as h, Attachment as i, MayAnswer as j, MeEntity as k, InteractionKey as l, About as m, AnyRule as n, Explain as o, Surface as p, Attach as r, Inherit as s, All as t, On as u, Decision as v, PrincipalOf as w, Placeholders as x, GuardSet as y };
510
- //# sourceMappingURL=attach-BnP9_Uca.d.mts.map
514
+ //# sourceMappingURL=attach-BepaL930.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attach-BepaL930.d.mts","names":["MemberKeys","_$__attach_js0.Attach","_$__attach_js0.AnyRule","_$__attach_js0.Inherit","_$__attach_js0.All","_$__attach_js0.Redact","_$__attach_js0.Explain","_$__attach_js0.On"],"sources":["../src/condition.ts","../src/may.ts","../src/me.ts","../src/index.ts","../src/attach.ts"],"mappings":";;KAWY;WACG;;WACA;;WACA;WAAsB,OAAO,cAAc;;;;WAE3C;WAA0B;;WAC1B;WAAsB,YAAY,cAAc;;WAChD;WAAqB,YAAY,cAAc;;;cAMxD,MAAG,YAAgB,cAAc,eAAa;;cAY9C,KAAE,YAAgB,cAAc,eAAa;cAWtC;;aAnCQ;;;aACA;;;;;;;;;;;;;;EAmDN,QAAA,WAAA,WAAS,QACZ,SAAS,0BAAwB,OAClC,SAAS,0BAAwB,UAC9B,8BAA4B,WAC3B;;;;;;;EAqBU,YAAA,WAAA,WAAS,OAAS,wBAAsB;;EAiB1C,UAAA,WAAA,cAAY;;;UAelB;WACN;WACA,WAAW;WACX,MAAM;;;UAwDA;WACN,WAAW;WACX,MAAM;;;;;;;;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OAAO,UAAU,WAAW,gBAAgB,gBAAgB,aAAa;;KAGlE,OAAO,MAAM,oBAAoB,UAAU;WAC5C;aACE,OAAO,cAAc,QAAQ,MAAM,KAAK,aAAa,QAAQ,aAAa;aAC1E,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;;aAEtC,QAAQ,UAAU,QAAQ,MAAM,KAAK;;;;;;;;WAQvC;cACG,GAAG,iBAAiB,UAAU,QAAQ,MAAM,KAAK;;;WAGpD,sBACG,KAAK,WAAW;aACf,OAAO,KAAK,QAAQ,MAAM,KAAK,YAAY,OAAO,OAAO,GAAG;;aAE5D,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;;WAG1C,wBACG,WAAW;aACV,OAAO,cAAc,QAAQ,MAAM,KAAK;aACxC,OAAO,UAAU,QAAQ,MAAM,KAAK;aACpC,SAAS,UAAU,QAAQ,MAAM,KAAK;;;WAI1C,SAAS,cAAc,QAAQ,MAAM,KAAK;;;UAIpC;WACN,OAAO,cAAc;WACrB,MAAM,OAAO,OAAO;;KAG1B,WAAW,SAAS,eAAe;;UAGvB;WACN;WACA;WACA,KAAK;WACL,SAAS,SAAS,eAAe;WACjC,WAAW,SAAS,eAAe;WACnC,QAAQ,cAAc;;cAoRpB,WAAQ,QAAY,cAAY,OAAO,OAAO"}
@@ -1,6 +1,6 @@
1
1
  import { a as defaultDeny, d as surfaceOf, r as attached } from "./attach-CRCF5XHS.mjs";
2
2
  import { Effect, Match, Option } from "effect";
3
- import { Query, evaluate } from "foldkit-entity";
3
+ import { Query, evaluateEach } from "foldkit-entity";
4
4
  // src/condition.ts
5
5
  /**
6
6
  * What an attachment's read rules come to for one principal, once its
@@ -48,12 +48,16 @@ const Condition = {
48
48
  * `input` (the principal's, from `G.inputOf`). `inherit` answers whether the
49
49
  * row a relation points at is readable, which only the caller can look up.
50
50
  * `operators` runs the guards' primitive operators: the policy's.
51
+ *
52
+ * A row guard the row's own values make an operator refuse (text holding a
53
+ * NUL, an implementation that throws) does not hold: what a write supplies
54
+ * can deny it, never end the request.
51
55
  */
52
56
  holds: (condition, values, input, inherit, operators) => {
53
57
  const holds = (each) => Match.valueTags(each, {
54
58
  Always: () => true,
55
59
  Never: () => false,
56
- Row: ({ guard }) => evaluate(guard.query, input, [values], { operators }).length === 1,
60
+ Row: ({ guard }) => evaluateEach(guard.query, input, [values], { operators }).matched.length === 1,
57
61
  Inherit: ({ relation }) => inherit(relation),
58
62
  And: ({ conditions }) => conditions.every(holds),
59
63
  Or: ({ conditions }) => conditions.some(holds)
@@ -210,4 +214,4 @@ const rowTarget = (interaction) => ({
210
214
  });
211
215
  export { deciding as n, readsPrincipal as r, Condition as t };
212
216
 
213
- //# sourceMappingURL=condition-Bl1UgEpM.mjs.map
217
+ //# sourceMappingURL=condition-Dx54lL7v.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"condition-Dx54lL7v.mjs","names":[],"sources":["../src/condition.ts"],"sourcesContent":["/**\n * What an attachment's read rules come to for one principal, once its\n * principal guards are decided: a condition over the row, which an\n * interpreter runs (`evaluate` in memory, SQL in a binding). Principal guards\n * never reach it, so their bodies stay on the server that decided them.\n */\nimport { Effect, Match, Option } from 'effect'\nimport { Query, evaluateEach, type AnyEntity, type MemoryOperators } from 'foldkit-entity'\nimport { attached, defaultDeny, surfaceOf, type AnyRule, type Deny } from './attach.js'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\nexport type Condition =\n | { readonly _tag: 'Always' }\n | { readonly _tag: 'Never' }\n | { readonly _tag: 'Row'; readonly guard: RowGuard<any, AnyEntity> }\n /** The row its `one` relation points at is readable. */\n | { readonly _tag: 'Inherit'; readonly relation: string }\n | { readonly _tag: 'And'; readonly conditions: ReadonlyArray<Condition> }\n | { readonly _tag: 'Or'; readonly conditions: ReadonlyArray<Condition> }\n\nconst always: Condition = Object.freeze({ _tag: 'Always' })\nconst never: Condition = Object.freeze({ _tag: 'Never' })\n\n/** A conjunction, with what it settles already folded away. */\nconst and = (conditions: ReadonlyArray<Condition>): Condition => {\n const kept: Array<Condition> = []\n for (const condition of conditions) {\n if (condition._tag === 'Never') return never\n if (condition._tag !== 'Always') kept.push(condition)\n }\n if (kept.length === 0) return always\n if (kept.length === 1) return kept[0]!\n return Object.freeze({ _tag: 'And', conditions: Object.freeze(kept) })\n}\n\n/** A disjunction, with what it settles already folded away. */\nconst or = (conditions: ReadonlyArray<Condition>): Condition => {\n const kept: Array<Condition> = []\n for (const condition of conditions) {\n if (condition._tag === 'Always') return always\n if (condition._tag !== 'Never') kept.push(condition)\n }\n if (kept.length === 0) return never\n if (kept.length === 1) return kept[0]!\n return Object.freeze({ _tag: 'Or', conditions: Object.freeze(kept) })\n}\n\nexport const Condition = {\n always,\n never,\n and,\n or,\n\n /**\n * Whether a row's stored values meet `condition`, its row guards read with\n * `input` (the principal's, from `G.inputOf`). `inherit` answers whether the\n * row a relation points at is readable, which only the caller can look up.\n * `operators` runs the guards' primitive operators: the policy's.\n *\n * A row guard the row's own values make an operator refuse (text holding a\n * NUL, an implementation that throws) does not hold: what a write supplies\n * can deny it, never end the request.\n */\n holds: (\n condition: Condition,\n values: Readonly<Record<string, unknown>>,\n input: Readonly<Record<string, unknown>>,\n inherit: (relation: string) => boolean,\n operators: MemoryOperators,\n ): boolean => {\n const holds = (each: Condition): boolean =>\n Match.valueTags(each, {\n Always: () => true,\n Never: () => false,\n Row: ({ guard }) =>\n evaluateEach(guard.query, input, [values], { operators }).matched.length === 1,\n Inherit: ({ relation }) => inherit(relation),\n And: ({ conditions }) => conditions.every(holds),\n Or: ({ conditions }) => conditions.some(holds),\n })\n return holds(condition)\n },\n\n /**\n * `condition` with every row guard that reads one of `unset`, and every\n * relation of them it follows, refused: a field a create leaves unset\n * matches no guard, `isNull` and `isNotNull` alike, since the create never\n * said what it holds.\n */\n unsetting: (condition: Condition, unset: ReadonlySet<string>): Condition => {\n const kept = (each: Condition): Condition =>\n Match.valueTags(each, {\n Always: () => each,\n Never: () => each,\n Row: ({ guard }) =>\n Query.dependencies(guard.query).predicate.some(field => unset.has(field.key))\n ? never\n : each,\n Inherit: ({ relation }) => (unset.has(relation) ? never : each),\n And: ({ conditions }) => and(conditions.map(kept)),\n Or: ({ conditions }) => or(conditions.map(kept)),\n })\n return kept(condition)\n },\n\n /** The members a condition reads: its row guards' fields, and each relation it follows. */\n members: (condition: Condition): ReadonlyArray<string> => {\n const read = (each: Condition): ReadonlyArray<string> =>\n Match.valueTags(each, {\n Always: () => [],\n Never: () => [],\n Row: ({ guard }) => Query.dependencies(guard.query).predicate.map(field => field.key),\n Inherit: ({ relation }) => [relation],\n And: ({ conditions }) => conditions.flatMap(read),\n Or: ({ conditions }) => conditions.flatMap(read),\n })\n return [...new Set(read(condition))]\n },\n}\n\n/** A member's read rule for one principal: the condition, and what a refusal shows. */\nexport interface MemberRead {\n readonly member: string\n readonly condition: Condition\n readonly deny: Deny\n}\n\n/**\n * Whether a row guard reads the principal's fields. A visitor has none, so\n * passes no guard that does; one over the row alone (`publishedAt` is set)\n * holds for a visitor as for anyone.\n */\nexport const readsPrincipal = (guard: RowGuard<any, AnyEntity>): boolean =>\n Query.dependencies(guard.query).inputs.length > 0\n\n/** Every principal guard the rules name, each once. */\nconst principalGuardsIn = (rules: ReadonlyArray<AnyRule>): ReadonlyArray<PrincipalGuard<any>> => {\n const found = new Map<string, PrincipalGuard<any>>()\n const visit = (rule: AnyRule): void =>\n Match.valueTags(rule, {\n PrincipalGuard: guard => void found.set(guard.name, guard),\n RowGuard: () => {},\n All: ({ rules }) => rules.forEach(visit),\n Inherit: () => {},\n })\n rules.forEach(visit)\n return [...found.values()]\n}\n\n/**\n * Turns `rules` into a condition for one principal. Each principal guard is\n * decided once, however many rules name it; a visitor passes no row guard\n * that reads the principal.\n */\nconst conditionsFor = <R>(\n rules: ReadonlyArray<AnyRule>,\n decide: (guard: PrincipalGuard<any>) => Effect.Effect<boolean, never, R>,\n visitor: boolean,\n): Effect.Effect<(rules: ReadonlyArray<AnyRule>, join: typeof and) => Condition, never, R> =>\n Effect.map(\n Effect.forEach(principalGuardsIn(rules), guard =>\n Effect.map(decide(guard), allowed => [guard.name, allowed] as const),\n ),\n decisions => {\n const allowed = new Map(decisions)\n const conditionOf = (rule: AnyRule): Condition =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => (allowed.get(name) === true ? always : never),\n RowGuard: guard =>\n visitor && readsPrincipal(guard)\n ? never\n : Object.freeze({ _tag: 'Row' as const, guard }),\n All: ({ rules }) => and(rules.map(conditionOf)),\n Inherit: ({ relation }) => Object.freeze({ _tag: 'Inherit' as const, relation }),\n })\n return (rules, join) => join(rules.map(conditionOf))\n },\n )\n\n/** A row's rule for one interaction and principal: the condition, and what a refusal shows. */\nexport interface RowRule {\n readonly condition: Condition\n readonly deny: Deny\n}\n\n/**\n * How a Policy decides one interaction, given the set's principal guards as\n * decided for it.\n */\nexport const deciding = <R>(\n decide: (guard: PrincipalGuard<any>) => Effect.Effect<boolean, never, R>,\n visitor: boolean,\n interaction: string,\n) => ({\n /** Who may do it to which rows of `entity`: `always`, then the row's rules for it. */\n row: (entity: AnyEntity): Effect.Effect<RowRule, never, R> =>\n Option.match(attached(entity), {\n onNone: () =>\n Effect.succeed({ condition: always, deny: defaultDeny(rowTarget(interaction)) }),\n onSome: attachment => {\n const target = rowTarget(interaction)\n const row = surfaceOf(attachment, target)\n const rules = Option.match(row, {\n onNone: (): ReadonlyArray<AnyRule> => [],\n onSome: ({ rules }) => rules,\n })\n // An interaction left without rules falls to the set's default.\n const unguarded = attachment.unguarded === 'allow' ? always : never\n return Effect.map(\n conditionsFor([...attachment.always, ...rules], decide, visitor),\n condition => ({\n condition: and([\n condition(attachment.always, and),\n Option.isSome(row) ? condition(rules, or) : unguarded,\n ]),\n deny: Option.getOrElse(\n Option.flatMap(row, ({ deny }) => deny),\n () => defaultDeny(target),\n ),\n }),\n )\n },\n }),\n\n /**\n * The rule of each of `members` that has one for this interaction. One\n * without follows its row. A relation key's Read is its relation's, decided\n * over the parent row as a member's is.\n */\n members: (\n entity: AnyEntity,\n members: ReadonlyArray<string>,\n ): Effect.Effect<ReadonlyArray<MemberRead>, never, R> =>\n Option.match(attached(entity), {\n onNone: () => Effect.succeed([]),\n onSome: attachment => {\n const surfaces = members.flatMap(member => {\n const target = Object.hasOwn(entity.relations, member)\n ? ({ _tag: 'Relation', relation: member, interaction } as const)\n : ({ _tag: 'Member', member, interaction } as const)\n return Option.match(surfaceOf(attachment, target), {\n onNone: () => [],\n onSome: ({ rules, deny }) => [\n { member, rules, deny: Option.getOrElse(deny, () => defaultDeny(target)) },\n ],\n })\n })\n return Effect.map(\n conditionsFor(\n surfaces.flatMap(({ rules }) => rules),\n decide,\n visitor,\n ),\n condition =>\n surfaces.map(({ member, rules, deny }) => ({\n member,\n condition: condition(rules, or),\n deny,\n })),\n )\n },\n }),\n\n /** A relation's rule for this interaction (`Link`, `Unlink`), when it has one. */\n relation: (\n entity: AnyEntity,\n relation: string,\n ): Effect.Effect<Option.Option<RowRule>, never, R> => {\n const target = { _tag: 'Relation', relation, interaction } as const\n return Option.match(\n Option.flatMap(attached(entity), attachment => surfaceOf(attachment, target)),\n {\n onNone: () => Effect.succeed(Option.none()),\n onSome: ({ rules, deny }) =>\n Effect.map(conditionsFor(rules, decide, visitor), condition =>\n Option.some({\n condition: condition(rules, or),\n deny: Option.getOrElse(deny, () => defaultDeny(target)),\n }),\n ),\n },\n )\n },\n})\n\nconst rowTarget = (interaction: string) => ({ _tag: 'Row', interaction }) as const\n"],"mappings":";;;;;;;;;;AAoBA,MAAM,SAAoB,OAAO,OAAO,EAAE,MAAM,SAAS,CAAC;AAC1D,MAAM,QAAmB,OAAO,OAAO,EAAE,MAAM,QAAQ,CAAC;;AAGxD,MAAM,OAAO,eAAoD;CAC/D,MAAM,OAAyB,CAAC;CAChC,KAAK,MAAM,aAAa,YAA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eAAc;GACpB,MAAM,WAAW,QAAQ,SAAQ,WAAU;IACzC,MAAM,SAAS,OAAO,OAAO,OAAO,WAAW,MAAM,IAChD;KAAE,MAAM;KAAY,UAAU;KAAQ;IAAY,IAClD;KAAE,MAAM;KAAU;KAAQ;IAAY;IAC3C,OAAO,OAAO,MAAM,UAAU,YAAY,MAAM,GAAG;KACjD,cAAc,CAAC;KACf,SAAS,EAAE,OAAO,WAAW,CAC3B;MAAE;MAAQ;MAAO,MAAM,OAAO,UAAU,YAAY,YAAY,MAAM,CAAC;KAAE,CAC3E;IACF,CAAC;GACH,CAAC;GACD,OAAO,OAAO,IACZ,cACE,SAAS,SAAS,EAAE,YAAY,KAAK,GACrC,QACA,OACF,IACA,cACE,SAAS,KAAK,EAAE,QAAQ,OAAO,YAAY;IACzC;IACA,WAAW,UAAU,OAAO,EAAE;IAC9B;GACF,EAAE,CACN;EACF;CACF,CAAC;;CAGH,WACE,QACA,aACoD;EACpD,MAAM,SAAS;GAAE,MAAM;GAAY;GAAU;EAAY;EACzD,OAAO,OAAO,MACZ,OAAO,QAAQ,SAAS,MAAM,IAAG,eAAc,UAAU,YAAY,MAAM,CAAC,GAC5E;GACE,cAAc,OAAO,QAAQ,OAAO,KAAK,CAAC;GAC1C,SAAS,EAAE,OAAO,WAChB,OAAO,IAAI,cAAc,OAAO,QAAQ,OAAO,IAAG,cAChD,OAAO,KAAK;IACV,WAAW,UAAU,OAAO,EAAE;IAC9B,MAAM,OAAO,UAAU,YAAY,YAAY,MAAM,CAAC;GACxD,CAAC,CACH;EACJ,CACF;CACF;AACF;AAEA,MAAM,aAAa,iBAAyB;CAAE,MAAM;CAAO;AAAY"}
@@ -1,4 +1,4 @@
1
- import { S as Policy } from "./attach-BnP9_Uca.mjs";
1
+ import { S as Policy } from "./attach-BepaL930.mjs";
2
2
  import { AnyEntity } from "foldkit-entity";
3
3
  import { DrizzleOperators, Visible } from "foldkit-remote-drizzle";
4
4
  export declare const GuardDrizzle: {
@@ -7,9 +7,11 @@ export declare const GuardDrizzle: {
7
7
  * returned them, by name, for `bind`'s storage. Checked here, before any
8
8
  * request: a row guard this compiler cannot run, and an inherited Read whose
9
9
  * Entity is not listed, has no Read rule, or leads back to itself, throw.
10
- * `operators` is the SQL table the bindings compile by (`bind(…, { operators })`),
11
- * so a rule calling an operator it lacks is refused here; the kernel's when
12
- * not given. Give both the same table.
10
+ * `operators` is the SQL table each rule is checked against here and compiled
11
+ * by (the kernel's when not given), and the policy's table decides what a rule
12
+ * reads from the input alone, so a server that starts can compile every rule
13
+ * whatever table its bindings were given. Give it the bindings' SQL table, so
14
+ * a rule and a query over one operator compile it alike.
13
15
  *
14
16
  * ```ts
15
17
  * const visible = GuardDrizzle.visible(Policy, [Todo, Project])
@@ -1 +1 @@
1
- {"version":3,"file":"drizzle.d.mts","names":[],"sources":["../src/drizzle.ts"],"mappings":";;;qBAoCa;;;;;;;;;;;;;;;EAeX,UAAU,YAAY,WAAW,cAAc,YAAU,QAC/C,OAAO,OAAK,UACV,IAAE;aACQ,YAAY;oBACnB,KAAK,qBAAqB"}
1
+ {"version":3,"file":"drizzle.d.mts","names":[],"sources":["../src/drizzle.ts"],"mappings":";;;qBAoCa;;;;;;;;;;;;;;;;;EAiBX,UAAU,YAAY,WAAW,cAAc,YAAU,QAC/C,OAAO,OAAK,UACV,IAAE;aACQ,YAAY;oBACnB,KAAK,qBAAqB"}
package/dist/drizzle.mjs CHANGED
@@ -26,9 +26,11 @@ const GuardDrizzle = {
26
26
  * returned them, by name, for `bind`'s storage. Checked here, before any
27
27
  * request: a row guard this compiler cannot run, and an inherited Read whose
28
28
  * Entity is not listed, has no Read rule, or leads back to itself, throw.
29
- * `operators` is the SQL table the bindings compile by (`bind(…, { operators })`),
30
- * so a rule calling an operator it lacks is refused here; the kernel's when
31
- * not given. Give both the same table.
29
+ * `operators` is the SQL table each rule is checked against here and compiled
30
+ * by (the kernel's when not given), and the policy's table decides what a rule
31
+ * reads from the input alone, so a server that starts can compile every rule
32
+ * whatever table its bindings were given. Give it the bindings' SQL table, so
33
+ * a rule and a query over one operator compile it alike.
32
34
  *
33
35
  * ```ts
34
36
  * const visible = GuardDrizzle.visible(Policy, [Todo, Project])
@@ -67,7 +69,13 @@ visible: (policy, entities, options = {}) => {
67
69
  const of = (condition) => Match.valueTags(condition, {
68
70
  Always: () => void 0,
69
71
  Never: () => nothing,
70
- Row: ({ guard }) => and(...compileWhere(guard.query, binding, input, `${name}.${guard.name}`)),
72
+ Row: ({ guard }) => and(...compileWhere(guard.query, {
73
+ ...binding,
74
+ operators: {
75
+ memory: policy.operators,
76
+ sql: sqlOperators
77
+ }
78
+ }, input, `${name}.${guard.name}`)),
71
79
  And: ({ conditions: parts }) => and(...parts.map(of)),
72
80
  Or: ({ conditions: parts }) => or(...parts.map(of)),
73
81
  Inherit: ({ relation }) => {
@@ -1 +1 @@
1
- {"version":3,"file":"drizzle.mjs","names":["supported"],"sources":["../src/drizzle.ts"],"sourcesContent":["/**\n * A guard set's read rules as `foldkit-remote-drizzle` bindings' `visible`:\n * each principal guard decided, what is left compiled to SQL over the table,\n * and an inherited Read a subquery over the related table's own rule.\n */\nimport { and, or, sql, type SQL } from 'drizzle-orm'\nimport { Effect, Match, Option } from 'effect'\nimport { Query, type AnyEntity } from 'foldkit-entity'\nimport {\n DrizzleOperators,\n compileWhere,\n idColumn,\n supported,\n type AnyEntityBinding,\n type Visible,\n} from 'foldkit-remote-drizzle'\nimport { RemoteServerError } from 'foldkit-remote-server'\nimport { attached, flattenRules, type AnyRule } from './attach.js'\nimport type { Condition } from './condition.js'\nimport type { Policy } from './index.js'\nimport { rowRules } from './placed.js'\n\n// A declaration, not an arrow, so a call narrows what follows it.\nfunction fail(message: string): never {\n throw new Error(`[foldkit-guard] GuardDrizzle.visible: ${message}`)\n}\n\n/** Every rule that decides who may read a row of `entity`. */\nconst readRules = (entity: AnyEntity): ReadonlyArray<AnyRule> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [...attachment.always, ...(attachment.row['Read']?.rules ?? [])],\n })\n\nconst nothing = sql`1 = 0`\n\nexport const GuardDrizzle = {\n /**\n * The `visible` rule of each of `entities`, the Entities as `Guards.attach`\n * returned them, by name, for `bind`'s storage. Checked here, before any\n * request: a row guard this compiler cannot run, and an inherited Read whose\n * Entity is not listed, has no Read rule, or leads back to itself, throw.\n * `operators` is the SQL table the bindings compile by (`bind(…, { operators })`),\n * so a rule calling an operator it lacks is refused here; the kernel's when\n * not given. Give both the same table.\n *\n * ```ts\n * const visible = GuardDrizzle.visible(Policy, [Todo, Project])\n * bind(Domain, { Todo: { table: todos, visible: visible.Todo, … }, … })\n * ```\n */\n visible: <User, const Es extends ReadonlyArray<AnyEntity>>(\n policy: Policy<User>,\n entities: Es,\n options: { readonly operators?: DrizzleOperators | undefined } = {},\n ): { readonly [K in Es[number]['name']]: Visible } => {\n const sqlOperators = options.operators ?? DrizzleOperators.kernel\n const byName = new Map(entities.map(entity => [entity.name, entity] as const))\n const inherits = new Map<string, ReadonlyArray<string>>()\n for (const entity of entities) {\n const targets: Array<string> = []\n for (const rule of flattenRules(readRules(entity))) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n const missing = Query.unsupported(guard.query, supported, sqlOperators)\n if (missing.length > 0) {\n fail(\n `${entity.name}'s ${guard.name} needs ${missing.join(', ')}, which SQL here does not run`,\n )\n }\n },\n All: () => {},\n Inherit: ({ relation }) => {\n const target = entity.relations[relation]!.target().name\n const guarded = byName.get(target)\n if (guarded === undefined) {\n fail(`${entity.name} inherits ${target}'s Read, but ${target} is not listed`)\n }\n if (readRules(guarded).length === 0) {\n fail(`${entity.name} inherits ${target}'s Read, but ${target} has no Read rule`)\n }\n targets.push(target)\n },\n })\n }\n inherits.set(entity.name, targets)\n }\n // A loop of inherited Reads would be a subquery that never ends.\n const closure = (name: string, path: ReadonlyArray<string>): ReadonlyArray<string> => {\n if (path.includes(name)) fail(`inherited Reads loop: ${[...path, name].join(' → ')}`)\n return [name, ...(inherits.get(name) ?? []).flatMap(next => closure(next, [...path, name]))]\n }\n const reaches = new Map(\n entities.map(entity => [entity.name, [...new Set(closure(entity.name, []))]]),\n )\n\n const compile = (\n name: string,\n binding: AnyEntityBinding,\n conditions: ReadonlyMap<string, Condition>,\n input: Readonly<Record<string, unknown>>,\n ): SQL | undefined => {\n const of = (condition: Condition): SQL | undefined =>\n Match.valueTags(condition, {\n Always: () => undefined,\n Never: () => nothing,\n Row: ({ guard }) =>\n and(...compileWhere(guard.query, binding, input, `${name}.${guard.name}`)),\n And: ({ conditions: parts }) => and(...parts.map(of)),\n // `Condition.or` folds away a part that admits every row, so each part here is SQL.\n Or: ({ conditions: parts }) => or(...parts.map(of)),\n Inherit: ({ relation }) => {\n const storage = binding.relations[relation]\n if (storage === undefined || storage.kind !== 'one') {\n return fail(\n `${name}.${relation} is inherited, so it must be stored as a foreign key here`,\n )\n }\n const target = storage.entity\n const where = compile(target.name, target, conditions, input) ?? sql`1 = 1`\n return sql`${storage.field} in (select ${idColumn(target)} from ${target.table} where ${where})`\n },\n })\n return of(conditions.get(name)!)\n }\n\n const visible =\n (name: string): Visible =>\n (principal, self) => {\n if (!policy.isPrincipal(principal)) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: the principal is not an Option of the guard set's`),\n )\n }\n return Effect.flatMap(\n Effect.forEach(reaches.get(name)!, each =>\n Effect.map(\n policy.readable(byName.get(each)!, principal),\n condition => [each, condition] as const,\n ),\n ),\n decided =>\n Effect.try({\n try: () => compile(name, self, new Map(decided), policy.inputOf(principal)),\n catch: error =>\n new RemoteServerError({\n message: error instanceof Error ? error.message : String(error),\n }),\n }),\n )\n }\n return Object.fromEntries(\n entities.map(entity => [entity.name, rowRules.add(visible(entity.name), policy, [entity])]),\n ) as {\n readonly [K in Es[number]['name']]: Visible\n }\n },\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,SAAS,KAAK,SAAwB;CACpC,MAAM,IAAI,MAAM,yCAAyC,SAAS;AAC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oBACZ,IAAI,MAAM,mBAAmB,KAAK,oDAAoD,CACxF;EAEF,OAAO,OAAO,QACZ,OAAO,QAAQ,QAAQ,IAAI,IAAI,IAAI,SACjC,OAAO,IACL,OAAO,SAAS,OAAO,IAAI,IAAI,GAAI,SAAS,IAC5C,cAAa,CAAC,MAAM,SAAS,CAC/B,CACF,IACA,YACE,OAAO,IAAI;GACT,WAAW,QAAQ,MAAM,MAAM,IAAI,IAAI,OAAO,GAAG,OAAO,QAAQ,SAAS,CAAC;GAC1E,QAAO,UACL,IAAI,kBAAkB,EACpB,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAChE,CAAC;EACL,CAAC,CACL;CACF;CACF,OAAO,OAAO,YACZ,SAAS,KAAI,WAAU,CAAC,OAAO,MAAM,SAAS,IAAI,QAAQ,OAAO,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAC5F;AAGF,EACF"}
1
+ {"version":3,"file":"drizzle.mjs","names":["supported"],"sources":["../src/drizzle.ts"],"sourcesContent":["/**\n * A guard set's read rules as `foldkit-remote-drizzle` bindings' `visible`:\n * each principal guard decided, what is left compiled to SQL over the table,\n * and an inherited Read a subquery over the related table's own rule.\n */\nimport { and, or, sql, type SQL } from 'drizzle-orm'\nimport { Effect, Match, Option } from 'effect'\nimport { Query, type AnyEntity } from 'foldkit-entity'\nimport {\n DrizzleOperators,\n compileWhere,\n idColumn,\n supported,\n type AnyEntityBinding,\n type Visible,\n} from 'foldkit-remote-drizzle'\nimport { RemoteServerError } from 'foldkit-remote-server'\nimport { attached, flattenRules, type AnyRule } from './attach.js'\nimport type { Condition } from './condition.js'\nimport type { Policy } from './index.js'\nimport { rowRules } from './placed.js'\n\n// A declaration, not an arrow, so a call narrows what follows it.\nfunction fail(message: string): never {\n throw new Error(`[foldkit-guard] GuardDrizzle.visible: ${message}`)\n}\n\n/** Every rule that decides who may read a row of `entity`. */\nconst readRules = (entity: AnyEntity): ReadonlyArray<AnyRule> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [...attachment.always, ...(attachment.row['Read']?.rules ?? [])],\n })\n\nconst nothing = sql`1 = 0`\n\nexport const GuardDrizzle = {\n /**\n * The `visible` rule of each of `entities`, the Entities as `Guards.attach`\n * returned them, by name, for `bind`'s storage. Checked here, before any\n * request: a row guard this compiler cannot run, and an inherited Read whose\n * Entity is not listed, has no Read rule, or leads back to itself, throw.\n * `operators` is the SQL table each rule is checked against here and compiled\n * by (the kernel's when not given), and the policy's table decides what a rule\n * reads from the input alone, so a server that starts can compile every rule\n * whatever table its bindings were given. Give it the bindings' SQL table, so\n * a rule and a query over one operator compile it alike.\n *\n * ```ts\n * const visible = GuardDrizzle.visible(Policy, [Todo, Project])\n * bind(Domain, { Todo: { table: todos, visible: visible.Todo, … }, … })\n * ```\n */\n visible: <User, const Es extends ReadonlyArray<AnyEntity>>(\n policy: Policy<User>,\n entities: Es,\n options: { readonly operators?: DrizzleOperators | undefined } = {},\n ): { readonly [K in Es[number]['name']]: Visible } => {\n const sqlOperators = options.operators ?? DrizzleOperators.kernel\n const byName = new Map(entities.map(entity => [entity.name, entity] as const))\n const inherits = new Map<string, ReadonlyArray<string>>()\n for (const entity of entities) {\n const targets: Array<string> = []\n for (const rule of flattenRules(readRules(entity))) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n const missing = Query.unsupported(guard.query, supported, sqlOperators)\n if (missing.length > 0) {\n fail(\n `${entity.name}'s ${guard.name} needs ${missing.join(', ')}, which SQL here does not run`,\n )\n }\n },\n All: () => {},\n Inherit: ({ relation }) => {\n const target = entity.relations[relation]!.target().name\n const guarded = byName.get(target)\n if (guarded === undefined) {\n fail(`${entity.name} inherits ${target}'s Read, but ${target} is not listed`)\n }\n if (readRules(guarded).length === 0) {\n fail(`${entity.name} inherits ${target}'s Read, but ${target} has no Read rule`)\n }\n targets.push(target)\n },\n })\n }\n inherits.set(entity.name, targets)\n }\n // A loop of inherited Reads would be a subquery that never ends.\n const closure = (name: string, path: ReadonlyArray<string>): ReadonlyArray<string> => {\n if (path.includes(name)) fail(`inherited Reads loop: ${[...path, name].join(' → ')}`)\n return [name, ...(inherits.get(name) ?? []).flatMap(next => closure(next, [...path, name]))]\n }\n const reaches = new Map(\n entities.map(entity => [entity.name, [...new Set(closure(entity.name, []))]]),\n )\n\n const compile = (\n name: string,\n binding: AnyEntityBinding,\n conditions: ReadonlyMap<string, Condition>,\n input: Readonly<Record<string, unknown>>,\n ): SQL | undefined => {\n const of = (condition: Condition): SQL | undefined =>\n Match.valueTags(condition, {\n Always: () => undefined,\n Never: () => nothing,\n // By the tables the rule was checked against: the SQL one given here, and\n // the policy's for what is decided from the input alone, as Guard judges.\n Row: ({ guard }) =>\n and(\n ...compileWhere(\n guard.query,\n { ...binding, operators: { memory: policy.operators, sql: sqlOperators } },\n input,\n `${name}.${guard.name}`,\n ),\n ),\n And: ({ conditions: parts }) => and(...parts.map(of)),\n // `Condition.or` folds away a part that admits every row, so each part here is SQL.\n Or: ({ conditions: parts }) => or(...parts.map(of)),\n Inherit: ({ relation }) => {\n const storage = binding.relations[relation]\n if (storage === undefined || storage.kind !== 'one') {\n return fail(\n `${name}.${relation} is inherited, so it must be stored as a foreign key here`,\n )\n }\n const target = storage.entity\n const where = compile(target.name, target, conditions, input) ?? sql`1 = 1`\n return sql`${storage.field} in (select ${idColumn(target)} from ${target.table} where ${where})`\n },\n })\n return of(conditions.get(name)!)\n }\n\n const visible =\n (name: string): Visible =>\n (principal, self) => {\n if (!policy.isPrincipal(principal)) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: the principal is not an Option of the guard set's`),\n )\n }\n return Effect.flatMap(\n Effect.forEach(reaches.get(name)!, each =>\n Effect.map(\n policy.readable(byName.get(each)!, principal),\n condition => [each, condition] as const,\n ),\n ),\n decided =>\n Effect.try({\n try: () => compile(name, self, new Map(decided), policy.inputOf(principal)),\n catch: error =>\n new RemoteServerError({\n message: error instanceof Error ? error.message : String(error),\n }),\n }),\n )\n }\n return Object.fromEntries(\n entities.map(entity => [entity.name, rowRules.add(visible(entity.name), policy, [entity])]),\n ) as {\n readonly [K in Es[number]['name']]: Visible\n }\n },\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,SAAS,KAAK,SAAwB;CACpC,MAAM,IAAI,MAAM,yCAAyC,SAAS;AACpE;;AAGA,MAAM,aAAa,WACjB,OAAO,MAAM,SAAS,MAAM,GAAG;CAC7B,cAAc,CAAC;CACf,SAAQ,eAAc,CAAC,GAAG,WAAW,QAAQ,GAAI,WAAW,IAAI,OAAO,EAAE,SAAS,CAAC,CAAE;AACvF,CAAC;AAEH,MAAM,UAAU,GAAG;AAEnB,MAAa,eAAe;;;;;;;;;;;;;;;;;AAiB1B,UACE,QACA,UACA,UAAiE,CAAC,MACd;CACpD,MAAM,eAAe,QAAQ,aAAa,iBAAiB;CAC3D,MAAM,SAAS,IAAI,IAAI,SAAS,KAAI,WAAU,CAAC,OAAO,MAAM,MAAM,CAAU,CAAC;CAC7E,MAAM,2BAAW,IAAI,IAAmC;CACxD,KAAK,MAAM,UAAU,UAAU;EAC7B,MAAM,UAAyB,CAAC;EAChC,KAAK,MAAM,QAAQ,aAAa,UAAU,MAAM,CAAC,GAC/C,MAAM,UAAU,MAAM;GACpB,sBAAsB,CAAC;GACvB,WAAU,UAAS;IACjB,MAAM,UAAU,MAAM,YAAY,MAAM,OAAOA,aAAW,YAAY;IACtE,IAAI,QAAQ,SAAS,GACnB,KACE,GAAG,OAAO,KAAK,KAAK,MAAM,KAAK,SAAS,QAAQ,KAAK,IAAI,EAAE,8BAC7D;GAEJ;GACA,WAAW,CAAC;GACZ,UAAU,EAAE,eAAe;IACzB,MAAM,SAAS,OAAO,UAAU,SAAS,CAAE,OAAO,CAAC,CAAC;IACpD,MAAM,UAAU,OAAO,IAAI,MAAM;IACjC,IAAI,YAAY,KAAA,GACd,KAAK,GAAG,OAAO,KAAK,YAAY,OAAO,eAAe,OAAO,eAAe;I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AO,MAAM,QAAQ,YAAY,KAAK,KAAK,GAAG;IACpE,OAAO,GAAG,GAAG,QAAQ,MAAM,cAAc,SAAS,MAAM,EAAE,QAAQ,OAAO,MAAM,SAAS,MAAM;GAChG;EACF,CAAC;EACH,OAAO,GAAG,WAAW,IAAI,IAAI,CAAE;CACjC;CAEA,MAAM,WACH,UACA,WAAW,SAAS;EACnB,IAAI,CAAC,OAAO,YAAY,SAAS,GAC/B,OAAO,OAAO,oBACZ,IAAI,MAAM,mBAAmB,KAAK,oDAAoD,CACxF;EAEF,OAAO,OAAO,QACZ,OAAO,QAAQ,QAAQ,IAAI,IAAI,IAAI,SACjC,OAAO,IACL,OAAO,SAAS,OAAO,IAAI,IAAI,GAAI,SAAS,IAC5C,cAAa,CAAC,MAAM,SAAS,CAC/B,CACF,IACA,YACE,OAAO,IAAI;GACT,WAAW,QAAQ,MAAM,MAAM,IAAI,IAAI,OAAO,GAAG,OAAO,QAAQ,SAAS,CAAC;GAC1E,QAAO,UACL,IAAI,kBAAkB,EACpB,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAChE,CAAC;EACL,CAAC,CACL;CACF;CACF,OAAO,OAAO,YACZ,SAAS,KAAI,WAAU,CAAC,OAAO,MAAM,SAAS,IAAI,QAAQ,OAAO,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAC5F;AAGF,EACF"}
package/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as May, C as PrincipalGuard, D as RowSpec, E as RowGuard, F as RowRule, M as MaySchema, N as Condition, O as ME, P as MemberRead, S as Policy, T as PrincipalSpec, _ as Builders, a as Deny, b as Guards, c as Interaction, d as Redact, f as RuleFor, g as Body, h as AnyGuard, i as Attachment, j as MayAnswer, k as MeEntity, l as InteractionKey, m as About, n as AnyRule, o as Explain, p as Surface, r as Attach, s as Inherit, t as All, u as On, v as Decision, w as PrincipalOf, x as Placeholders, y as GuardSet } from "./attach-BnP9_Uca.mjs";
1
+ import { A as May, C as PrincipalGuard, D as RowSpec, E as RowGuard, F as RowRule, M as MaySchema, N as Condition, O as ME, P as MemberRead, S as Policy, T as PrincipalSpec, _ as Builders, a as Deny, b as Guards, c as Interaction, d as Redact, f as RuleFor, g as Body, h as AnyGuard, i as Attachment, j as MayAnswer, k as MeEntity, l as InteractionKey, m as About, n as AnyRule, o as Explain, p as Surface, r as Attach, s as Inherit, t as All, u as On, v as Decision, w as PrincipalOf, x as Placeholders, y as GuardSet } from "./attach-BepaL930.mjs";
2
2
  export { About, type All, AnyGuard, type AnyRule, type Attach, type Attachment, Body, Builders, Condition, Decision, type Deny, type Explain, GuardSet, Guards, type Inherit, Interaction, type InteractionKey, ME, May, type MayAnswer, MaySchema, type MeEntity, type MemberRead, type On, Placeholders, Policy, PrincipalGuard, PrincipalOf, PrincipalSpec, type Redact, RowGuard, type RowRule, RowSpec, type RuleFor, type Surface };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as Interaction, r as attached, t as Attaching } from "./attach-CRCF5XHS.mjs";
2
- import { n as deciding, r as readsPrincipal, t as Condition } from "./condition-Bl1UgEpM.mjs";
2
+ import { n as deciding, r as readsPrincipal, t as Condition } from "./condition-Dx54lL7v.mjs";
3
3
  import { n as MaySchema, t as May } from "./may-DzCAt_5M.mjs";
4
4
  import { n as me, t as ME } from "./me-BYpuVqJE.mjs";
5
5
  import { n as providedFrom } from "./origin-igJoiz74.mjs";
package/dist/media.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as PrincipalGuard, S as Policy } from "./attach-BnP9_Uca.mjs";
1
+ import { C as PrincipalGuard, S as Policy } from "./attach-BepaL930.mjs";
2
2
  import { Effect, Layer, Option } from "effect";
3
3
  import { UploadPolicy } from "foldkit-media/server";
4
4
  export interface UploadPolicyConfig<User, E, R> {
package/dist/server.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { S as Policy, k as MeEntity, l as InteractionKey } from "./attach-BnP9_Uca.mjs";
1
+ import { S as Policy, k as MeEntity, l as InteractionKey } from "./attach-BepaL930.mjs";
2
2
  import { Effect, Option } from "effect";
3
3
  import { AnyEntity, AnyQuery } from "foldkit-entity";
4
4
  import { EntitySource, EntityWriter, MemoryReadable, MutationOutcome, MutationRefused, MutationSource, ReadPlan, RemoteServerError, ServerDefinition } from "foldkit-remote-server";
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";;;;;qBAkEa;;;;;;;;;;EAUX,KAAK,MAAM,GAAC,QACF,UAAQ,QACR,OAAO,MAAM,OACpB,aAAa,OAAO,OAAO,OAAO;;;;;;;;;;EA6CrC,SAAS,MAAM,GAAC,QAAU,WAAS,QAAU,OAAO,MAAM,QAAE,WAG3C,OAAO,OAAO,OAAK,8BAE7B,OAAO,OAAO,iBAAiB;;;;;;;EAuEtC,SAAS,MAAI,QAAU,OAAO,OAAK,UAAY,cAAc;IAC3D,WAAQ,WAEO,OAAO,OAAO,OAAK,MACxB,gBAAgB,eAAe,OAAO,OAAO,SAAS,8BAC3D,OAAO,OAAO;IA4CnB;OAzHY,aAAA,WAAA,OAAA,OAAA,OAAA,8BAAiB,OAAA,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+J/B,SAAS,UAAU,WAAW,MAAM,GAAG,IAAE,QAC/B,GAAC,QACD,OAAO,MAAM,IAAE,QACf,aAAa,OAAO,OAAO,OAAO,KAAG;aAElC,sBACG,WAAW,gBAAgB,MAAM,SAAS,YAAY;aAEzD,iBAAiB;QAE3B,aAAa,OAAO,OAAO,OAAO,IAAI;;;;;;;;;;;;;;;;;;;;;EA6dzC,WAAW,MAAM,GAAG,IAAI,IAAI,qBAAqB,OAAO,QAAQ,SAAO,UAC3D,mBAAmB,MAAM,OAAO,QAAQ,UAAQ;aAE/C,QAAQ;aACR,QAAQ,OAAO,MAAM;aACrB,8CAA8C;;;;;;aAM9C,OAAO,OAAO,mBAAmB,OAAO;;aAExC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AO,UAC3D,mBAAmB,MAAM,OAAO,QAAQ,UAAQ;aAE/C,QAAQ;aACR,QAAQ,OAAO,MAAM;aACrB,8CAA8C;;;;;;aAM9C,OAAO,OAAO,mBAAmB,OAAO;;aAExC,QAAQ,aAAa,OAAO,OAAO,OAAO;;aAE1C,SAAS;KACnB,MACK;aACK,OAAO;aACP,WAAW,OAAO,OAAO;aACzB;aACA,KAAK,OAAO,OAAO,SAAS;QACjC,OAAO,OACX,gBAAgB,SAChB,oBAAoB,kBAAkB,iBACtC,QAED,eAAe,OAAO,OAAO,OAAO,IAAI,KAAK;;;;;;;;;;;;;;;;;;EA6FhD,WAAW,MAAM,GAAC,QACR,OAAO,MAAM,IAAE;aAEZ,UAAU,cAAc;;aAExB;eACE;iBACE,SAAS;mBAEL;mBAA0B,OAAO;;;;aAIzC,QAAQ"}
package/dist/server.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  import { c as readRowsRuled, i as attachedRules, l as readRuled, r as attached } from "./attach-CRCF5XHS.mjs";
2
- import { t as Condition } from "./condition-Bl1UgEpM.mjs";
2
+ import { t as Condition } from "./condition-Dx54lL7v.mjs";
3
3
  import "./me-BYpuVqJE.mjs";
4
4
  import { n as rowRules, r as writeRules, t as memberRules } from "./placed-BvdNmZJu.mjs";
5
5
  import { Effect, Match, Option, Schema, SchemaAST } from "effect";
6
- import { Entity, Query, supported } from "foldkit-entity";
6
+ import { Entity, Expr, Query, QueryEvaluateError, Write, dependenciesOf, supported } from "foldkit-entity";
7
7
  import { RemoteInvalid, RemoteServer, RemoteServerError } from "foldkit-remote-server";
8
8
  // src/server.ts
9
9
  /**
@@ -257,11 +257,12 @@ const GuardServer = {
257
257
  }));
258
258
  const told = (error) => error instanceof RemoteInvalid && Option.exists(error.rule, (rule) => unnamed.has(rule)) ? RemoteServer.invalid("The row would be invalid") : error;
259
259
  /**
260
- * Fails a write whose `when` reads, or whose `expect` names, a member with
261
- * a Read rule: Unmet or written, Conflict or not, would answer for it.
260
+ * Fails a write whose `when` reads, whose `expect` names, or whose
261
+ * computed assignment reads, a member with a Read rule: Unmet or written,
262
+ * Conflict or not, and the computed value answered, would answer for it.
262
263
  * `validate` refuses the same at startup; this holds where it was not run.
263
264
  */
264
- const discloses = (expect, when) => Option.match(attachment, {
265
+ const discloses = (expect, when, assignments = {}) => Option.match(attachment, {
265
266
  onNone: () => Effect.void,
266
267
  onSome: (ruled) => {
267
268
  const read = Option.match(when, {
@@ -278,7 +279,15 @@ const GuardServer = {
278
279
  onNone: () => [],
279
280
  onSome: ({ field }) => readRuled(ruled, field) ? [field] : []
280
281
  });
281
- const hidden = [.../* @__PURE__ */ new Set([...read, ...expected])];
282
+ const computed = Write.boundReads({
283
+ increments: {},
284
+ assignments
285
+ }).filter((field) => readRuled(ruled, field));
286
+ const hidden = [.../* @__PURE__ */ new Set([
287
+ ...read,
288
+ ...expected,
289
+ ...computed
290
+ ])];
282
291
  return hidden.length === 0 ? Effect.void : Effect.fail(new RemoteServerError({ message: `${entity.name}'s write reads ${hidden.join(", ")}, which a Read rule hides from its writer` }));
283
292
  }
284
293
  });
@@ -301,28 +310,62 @@ const GuardServer = {
301
310
  };
302
311
  const memberRead = GuardServer.filter(entity, policy);
303
312
  /** Refused before any rule, for what the write declares rather than what the row holds. */
304
- const admitUpdate = (context) => Effect.andThen(discloses(context.expect, context.when), () => Object.keys(context.increments).length > 0 && Option.isNone(context.expect) && revision === void 0 ? Effect.fail(new RemoteServerError({ message: `${entity.name}'s increment expects no revision and its writer pins none, so its rules would judge a sum over a row that may move; give the writer a revision` })) : Effect.void);
313
+ const admitUpdate = (context) => Effect.andThen(discloses(context.expect, context.when, context.assignments), () => Object.keys(context.increments).length + Object.keys(context.assignments).length > 0 && Option.isNone(context.expect) && revision === void 0 ? Effect.fail(new RemoteServerError({ message: `${entity.name}'s write moves a field and expects no revision, and its writer pins none, so its rules would judge a value over a row that may move; give the writer a revision` })) : Effect.void);
305
314
  /** The rules an update must meet: the row's, each member it sets, each relation it points. */
306
315
  const updateRules = (context) => Effect.gen(function* () {
307
316
  return {
308
317
  row: yield* policy.writable(entity, context.principal, "Update"),
309
- members: yield* policy.writeMembers(entity, context.principal, [...Object.keys(context.values), ...Object.keys(context.increments)], "Update"),
318
+ members: yield* policy.writeMembers(entity, context.principal, [
319
+ ...Object.keys(context.values),
320
+ ...Object.keys(context.increments),
321
+ ...Object.keys(context.assignments)
322
+ ], "Update"),
310
323
  relating: yield* linkRules(context.principal, context.links)
311
324
  };
312
325
  });
313
- /** The row as its writer may see it, with every field the rules and the version read. */
326
+ /**
327
+ * The row as its writer may see it, with every field the rules and the
328
+ * version read, and those the write's amounts and assignments read to
329
+ * work out the row it leaves.
330
+ */
314
331
  const readBefore = (context, rules) => read({
315
332
  id: context.id,
316
333
  fields: fieldsOf([
317
334
  rules.row,
318
335
  ...rules.members,
319
336
  ...ruleOf(rules.relating)
320
- ], [...Object.keys(context.links), ...versionFields(context.expect)]),
337
+ ], [
338
+ ...Object.keys(context.links),
339
+ ...versionFields(context.expect),
340
+ ...Write.boundReads(context)
341
+ ]),
321
342
  principal: context.principal
322
343
  });
344
+ /**
345
+ * The memory table the row a write leaves is worked out by: the writer's,
346
+ * so the rules judge the value its statement writes, else the policy's.
347
+ */
348
+ const computing = writer.operators ?? policy.operators;
349
+ /**
350
+ * The row `context` would leave `before` as. An operator's refusal (text
351
+ * holding NUL, an implementation that throws) is a server error, as the
352
+ * writer answers what it cannot compile: logged here, and never sent, since
353
+ * an implementation's own message may say anything. So is a field it cannot
354
+ * work out at all: judging its old value would let a rule over it pass.
355
+ */
356
+ const leaves = (before, context) => Effect.suspend(() => {
357
+ const unworkable = Effect.fail(new RemoteServerError({ message: `${entity.name}'s write could not be worked out to judge its rules` }));
358
+ try {
359
+ const applied = Write.apply(before, context, { operators: computing });
360
+ return applied.unknown.length === 0 ? Effect.succeed(applied.row) : unworkable;
361
+ } catch (error) {
362
+ if (!(error instanceof QueryEvaluateError)) throw error;
363
+ return Effect.logError("[foldkit-guard] a computed value could not be worked out", error).pipe(Effect.andThen(unworkable));
364
+ }
365
+ });
323
366
  /** The rules, over the row as it is and as the write would leave it. */
324
367
  const decideUpdate = (context, rules, before) => Effect.gen(function* () {
325
- const { principal, values, increments, links } = context;
368
+ const { principal, links } = context;
326
369
  const linked = Object.keys(links);
327
370
  const stored = writer.linked === void 0 || linked.length === 0 ? Option.none() : yield* writer.linked({
328
371
  id: context.id,
@@ -338,26 +381,33 @@ const GuardServer = {
338
381
  exact: true
339
382
  })
340
383
  })));
341
- const after = {
342
- ...before,
343
- ...values,
344
- ...Object.fromEntries(Object.entries(increments).map(([field, amount]) => [field, Number(before[field]) + amount])),
345
- ...Object.fromEntries(Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]))
346
- };
347
384
  yield* require([
348
385
  rules.row,
349
386
  ...rules.members,
350
387
  ...relations
351
388
  ], before, principal);
389
+ const after = {
390
+ ...yield* leaves(before, context),
391
+ ...Object.fromEntries(Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]))
392
+ };
352
393
  yield* require([rules.row], after, principal);
353
394
  });
354
395
  const guarded = {
355
396
  entity: writer.entity,
356
397
  ...writer.preconditions === true ? { preconditions: true } : {},
357
398
  ...writer.increments === true ? { increments: true } : {},
399
+ ...writer.assignments === true ? { assignments: true } : {},
400
+ ...revision === void 0 ? {} : { pins: true },
358
401
  ...writer.ledger === true ? { ledger: true } : {},
359
402
  ...writer.invariants === true ? { invariants: true } : {},
360
- ...writer.refuses === void 0 ? {} : { refuses: writer.refuses },
403
+ refuses: (write) => [
404
+ ...writer.refuses?.(write) ?? [],
405
+ ...write.assignments.flatMap(({ field, expr }) => Expr.unsupported([expr], {
406
+ operations: supported,
407
+ operators: computing
408
+ }).map((missing) => `its assignment to "${field.key}" calls ${missing}, which the guard cannot work out`)),
409
+ ...(write.increments.length > 0 || write.assignments.length > 0) && write.expect === void 0 && revision === void 0 ? ["it moves a field and expects no revision, and the guarded writer pins none, so its rules would judge a value over a row that may move; give the writer a revision"] : []
410
+ ],
361
411
  ...writer.recorded === void 0 ? {} : { recorded: writer.recorded },
362
412
  read: ({ id, fields, principal }) => seenRow({ filter: memberRead }, (seen) => read({
363
413
  id,
@@ -547,10 +597,12 @@ const GuardServer = {
547
597
  onNone: () => [],
548
598
  onSome: (body) => hiddenOf(attachment, Query.dependencies(body).predicate)
549
599
  });
600
+ const computed = write.assignments.flatMap((assignment) => hiddenOf(attachment, dependenciesOf(assignment.expr).fields).map((member) => `write ${mutation} computes ${name}'s ${assignment.field.key} from its ${member}, which has a Read rule`));
550
601
  const expected = write.expect?.field.key;
551
602
  const pin = typeof writer === "object" && writer !== null ? pins.get(writer) : void 0;
552
603
  return [
553
604
  ...when.map((member) => `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`),
605
+ ...computed,
554
606
  ...expected !== void 0 && readRuled(attachment, expected) ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`] : [],
555
607
  ...expected !== void 0 && pin !== void 0 && Option.exists(pin, (field) => field !== expected) ? [`write ${mutation} expects ${name}'s ${expected}, but its writer pins ${Option.getOrThrow(pin)}`] : []
556
608
  ];
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","names":[],"sources":["../src/server.ts"],"sourcesContent":["/**\n * A guard set's read rules as `foldkit-remote-server`'s seams: an\n * `EntitySource.filter` from each member's Read rule, and `RemoteServer.memory`'s\n * `readable` and `filter` from the row's, and a check at startup that a server\n * applies them. A subpath, so the shared declaration the browser imports never\n * brings the server along.\n */\nimport { Effect, Match, Option, Schema, SchemaAST } from 'effect'\nimport { Entity, Query, supported, type AnyEntity, type AnyQuery } from 'foldkit-entity'\nimport type { MutationDescriptor, RemoteForbidden } from 'foldkit-remote'\nimport {\n RemoteInvalid,\n RemoteServer,\n RemoteServerError,\n type EntityRecord,\n type EntitySource,\n type EntityWriter,\n type MutationOutcome,\n type MutationRefused,\n type MutationSource,\n type MemoryReadable,\n type ReadPlan,\n type ServerDefinition,\n type WriteWhen,\n} from 'foldkit-remote-server'\nimport {\n attached,\n attachedRules,\n readRowsRuled,\n readRuled,\n type Attachment,\n type Deny,\n type InteractionKey,\n} from './attach.js'\nimport { Condition, type RowRule } from './condition.js'\nimport type { Policy } from './index.js'\nimport type { MayAnswer } from './may.js'\nimport { ME, type MeEntity } from './me.js'\nimport { memberRules, rowRules, writeRules } from './placed.js'\n\nconst noMembers = (record: EntityRecord) => record\n\n/** Two stored values, which are JSON: equal when they encode the same. */\nconst sameStored = (left: unknown, right: unknown): boolean =>\n JSON.stringify(left) === JSON.stringify(right)\n\n/** The members of `fields` that have a Read rule, once each. */\nconst hiddenOf = (\n attachment: Attachment,\n fields: ReadonlyArray<{ readonly key: string }>,\n): ReadonlyArray<string> => [\n ...new Set(fields.map(field => field.key).filter(key => readRuled(attachment, key))),\n]\n\n/** Each guarded writer's `revision`, or none: one a change can fall between check and write of. */\nconst pins = new WeakMap<object, Option.Option<string>>()\n\n/** A ref key's two halves, `Entity:id`; `none` for anything else. */\nconst refOf = (value: unknown): Option.Option<{ readonly entity: string; readonly id: string }> => {\n if (typeof value !== 'string') return Option.none()\n const split = value.indexOf(':')\n return split <= 0\n ? Option.none()\n : Option.some({ entity: value.slice(0, split), id: value.slice(split + 1) })\n}\n\nexport const GuardServer = {\n /**\n * `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`\n * answered by `policy`. `signedIn` is whether the server answered as\n * someone; `key` is their `key`. Any other id is no row.\n *\n * ```ts\n * RemoteServer.make({ entities: [GuardServer.me(Me, Policy), …] })\n * ```\n */\n me: <User, R>(\n entity: MeEntity,\n policy: Policy<User, R>,\n ): EntitySource<Option.Option<User>, R> => {\n // Otherwise every read would die deciding another set's guards.\n Option.map(attached(entity), ({ set }) => {\n if (set !== policy.set) {\n throw new Error(\n `[foldkit-guard] GuardServer.me: Me carries the guards of ${set}, not ${policy.set}`,\n )\n }\n })\n return {\n ...RemoteServer.entity<Option.Option<User>, R>(entity, {\n read: ({ ids, principal }) =>\n Effect.succeed(\n ids\n .filter(id => id === ME)\n .map(id => ({\n id,\n values: {\n signedIn: Option.isSome(principal),\n // Encoded, as a Source answers: `null` for a visitor.\n key: Option.match(principal, {\n onNone: () => null,\n onSome: policy.key,\n }),\n },\n })),\n ),\n filter: GuardServer.filter(entity, policy),\n }),\n // Its Read rule as this Source applies it: only the asker's own row,\n // which `Guards.me` lets anyone read. One per call: the registry is keyed\n // by it, and another call is for another Policy.\n visible: rowRules.add(Object.freeze({ reads: 'the asker’s own row' }), policy, [entity]),\n }\n },\n\n /**\n * An `EntitySource.filter` for `entity`: each requested member with a Read\n * rule is decided per record, omitted or redacted where the rule refuses.\n * The fields a rule reads are read too, so it can be decided.\n *\n * ```ts\n * RemoteServer.entity(Todo, { read, filter: GuardServer.filter(Todo, Policy) })\n * ```\n */\n filter: <User, R>(entity: AnyEntity, policy: Policy<User, R>) =>\n memberRules.add(\n (\n principal: Option.Option<User>,\n fields: readonly string[],\n ): Effect.Effect<ReadPlan, never, R> =>\n Effect.map(\n Effect.all([\n policy.readMembers(entity, principal, fields),\n // `may` is answered here, where the row is read as its principal sees it.\n asksMay(entity, fields)\n ? Effect.map(mayOf(entity, policy, principal), Option.some)\n : Effect.succeed(Option.none<MayPlan>()),\n ]),\n ([members, may]): ReadPlan => {\n if (members.length === 0 && Option.isNone(may)) return { fields, apply: noMembers }\n const input = policy.inputOf(principal)\n const decided = members.map(member => ({\n ...member,\n // A redacted value is a decoded one; the record holds what the store holds.\n redacted:\n member.deny._tag === 'Redact'\n ? Option.some(\n Schema.encodeSync(\n (\n entity.members as Readonly<\n Record<string, { readonly schema: Schema.Top }>\n >\n )[member.member]!.schema as unknown as Schema.Codec<unknown, unknown>,\n )(member.deny.value),\n )\n : Option.none(),\n }))\n return {\n fields: [\n ...new Set([\n ...fields,\n ...members.flatMap(({ condition }) => Condition.members(condition)),\n ...Option.match(may, { onNone: () => [], onSome: ({ fields }) => fields }),\n ]),\n ],\n apply: record => {\n const values: Record<string, unknown> = { ...record.values }\n for (const { member, condition, redacted } of decided) {\n // Member rules carry no inherited Read: only a row's Read may inherit.\n if (\n Condition.holds(condition, record.values, input, () => false, policy.operators)\n )\n continue\n Option.match(redacted, {\n onNone: () => {\n delete values[member]\n },\n onSome: value => {\n values[member] = value\n },\n })\n }\n Option.map(may, ({ answer }) => {\n values.may = answer(record.values)\n })\n return { id: record.id, values }\n },\n }\n },\n ),\n policy,\n [entity],\n ),\n\n /**\n * `RemoteServer.memory`'s `readable` and `filter` for `entities`, the\n * Entities as `Guards.attach` returned them. A row's Read is decided per\n * stored row, an inherited Read by looking the related row up; an Entity\n * not listed is read by everyone.\n */\n memory: <User>(policy: Policy<User>, entities: ReadonlyArray<AnyEntity>) => ({\n readable: rowRules.add(\n (\n principal: Option.Option<User>,\n row: (entity: string, id: string) => Option.Option<Readonly<Record<string, unknown>>>,\n ): Effect.Effect<MemoryReadable> =>\n Effect.map(\n Effect.forEach(entities, entity =>\n Effect.map(\n policy.readable(entity, principal),\n condition => [entity.name, condition] as const,\n ),\n ),\n (decided): MemoryReadable => {\n const conditions = new Map(decided)\n const input = policy.inputOf(principal)\n // `seen` stops a cycle of inherited Reads, which would otherwise never end.\n const holds = (\n entity: string,\n values: Readonly<Record<string, unknown>>,\n seen: ReadonlySet<string>,\n ): boolean => {\n const condition = conditions.get(entity)\n if (condition === undefined) return true\n return Condition.holds(\n condition,\n values,\n input,\n relation =>\n Option.match(refOf(values[relation]), {\n onNone: () => false,\n onSome: ref => {\n const key = `${ref.entity}:${ref.id}`\n if (seen.has(key)) return false\n return Option.match(row(ref.entity, ref.id), {\n onNone: () => false,\n onSome: target => holds(ref.entity, target, new Set([...seen, key])),\n })\n },\n }),\n policy.operators,\n )\n }\n return (entity, values) => holds(entity, values, new Set())\n },\n ),\n policy,\n entities,\n ),\n filter: Object.fromEntries(\n entities.map(entity => [entity.name, GuardServer.filter(entity, policy)] as const),\n ),\n }),\n\n /**\n * `writer` with `entity`'s write rules checked before each write lands, for\n * `RemoteServer.write`. An update or a delete reads the row first under\n * the writer's own `read` (its Source's read rule): a row the writer may not\n * see is refused as one that is not there, and a delete of it changes\n * nothing. Then the row's rule for the command must hold over the row (an\n * update's over the row as it would be after it too, so a write cannot move\n * a row out of its writer's reach), each member it sets must allow setting\n * it, and each relation it points elsewhere must allow the unlink and the\n * link. A create's rules hold over the values it proposes, where a field the\n * create leaves unset matches no guard, not even one for an empty value. A refusal is\n * `Forbidden`, with the sentence an `explain` gave; the write never runs.\n *\n * `presets` are fields a create takes from who is asking, never from the\n * client (`ownerId: user => user.id`): set before the rules are checked, so\n * a rule over them holds of the creator. A visitor has nothing to preset\n * from, and a create whose input sets a preset field is a mistake of the\n * server's, refused.\n *\n * `revision` names a field stored as a number, which the writer moves on by\n * one with each write it lands. An update or a delete then lands only on the\n * revision its rules were decided over (the writer's `expect`), so a change\n * between the check and the write is never written over; it is decided\n * again against the row as it now is, up to three times. A change that does\n * not move the revision (a handler's, `applyEdits`', raw SQL) is not seen.\n * Without `revision`, none is, and `validate` warns. An input that expects a\n * revision the row read is not at is a `Conflict`, decided before any rule;\n * an input may expect only the field the writer pins.\n *\n * ```ts\n * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))\n * ```\n */\n writer: <E extends AnyEntity, User, R, RW>(\n entity: E,\n policy: Policy<User, R>,\n writer: EntityWriter<Option.Option<User>, RW>,\n options: {\n readonly presets?: {\n readonly [K in keyof E['fields']]?: (user: User) => E['fields'][K]['schema']['Type']\n }\n readonly revision?: keyof E['fields'] & string\n } = {},\n ): EntityWriter<Option.Option<User>, R | RW> => {\n const revision = options.revision\n if (revision !== undefined) {\n const field = Object.hasOwn(entity.fields, revision)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[revision]\n : undefined\n if (field === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${revision}\" for its revision`,\n )\n }\n // The writer moves it on by one in the statement it writes with, so it is stored as a number.\n if (!SchemaAST.isNumber(Schema.toEncoded(field.schema).ast)) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s revision \"${revision}\" is not stored as a number`,\n )\n }\n }\n const presets = Object.entries(options.presets ?? {}).map(([field, preset]) => {\n const declared = Object.hasOwn(entity.fields, field)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[field]\n : undefined\n if (declared === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${field}\" to preset`,\n )\n }\n const encode = Schema.encodeUnknownSync(\n declared.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n return { field, value: (user: User) => encode((preset as (user: User) => unknown)(user)) }\n })\n if (writer.entity !== entity.name) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s rules over a writer for ${writer.entity}`,\n )\n }\n const read = writer.read\n if (read === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s writer reads no row as its writer may see it; bind it with a visible rule (GuardDrizzle.visible)`,\n )\n }\n const holds = (\n rule: { readonly condition: Condition },\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Condition.holds(\n rule.condition,\n values,\n policy.inputOf(principal),\n () => false,\n policy.operators,\n )\n /** Fails with the first rule of `rules` that does not hold over `values`. */\n const require = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Option.match(Option.fromUndefinedOr(rules.find(rule => !holds(rule, values, principal))), {\n onNone: () => Effect.void,\n onSome: rule => Effect.fail(refused(rule.deny)),\n })\n type Links = Readonly<\n Record<string, Option.Option<{ readonly entity: string; readonly id: string }>>\n >\n /** Each relation `links` points: its rules for unlinking and for linking a row. */\n const linkRules = (principal: Option.Option<User>, links: Links) =>\n Effect.forEach(Object.entries(links), ([relation, target]) =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Unlink'),\n policy.linkable(entity, principal, relation, 'Link'),\n ]),\n ([unlink, link]) => ({ relation, now: linkKey(target), unlink, link }),\n ),\n )\n /**\n * The rules a change from what each relation was linked to, to what it now\n * points at, must meet; none `before` is a create, which unlinks nothing.\n * Where `exact` is false, `links` are the row as its writer sees it, where\n * a link to a row hidden from them reads as none: a relation seen unlinked\n * may be linked after all, so changing it unlinks too.\n */\n const linking = (\n rules: ReadonlyArray<{\n readonly relation: string\n readonly now: string | null\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n before: Option.Option<{\n readonly links: Readonly<Record<string, unknown>>\n readonly exact: boolean\n }>,\n ): ReadonlyArray<RowRule> =>\n rules.flatMap(({ relation, now, unlink, link }) =>\n Option.match(before, {\n onNone: () => (now === null ? [] : Option.toArray(link)),\n onSome: ({ links, exact }) => {\n const was = links[relation] ?? null\n if (was === now && (exact || was !== null)) return []\n return [\n ...(was === null && exact ? [] : Option.toArray(unlink)),\n ...(now === null ? [] : Option.toArray(link)),\n ]\n },\n }),\n )\n const ruleOf = (\n rules: ReadonlyArray<{\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n ) => rules.flatMap(({ unlink, link }) => [...Option.toArray(unlink), ...Option.toArray(link)])\n const fieldsOf = (\n rules: ReadonlyArray<{ readonly condition: Condition }>,\n more: Iterable<string>,\n ) => [\n ...new Set([\n 'id',\n ...more,\n ...rules.flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n type Expect = Option.Option<{ readonly field: string; readonly revision: unknown }>\n /** The fields that say which version of the row was read: the revision, and the input's. */\n const versionFields = (expect: Expect) => [\n ...(revision === undefined ? [] : [revision]),\n ...Option.match(expect, { onNone: () => [], onSome: ({ field }) => [field] }),\n ]\n /** Whether the row read is not at the revision the input expects. */\n const moved = (expect: Expect, before: Readonly<Record<string, unknown>>) =>\n Option.exists(expect, ({ field, revision }) => !sameStored(before[field], revision))\n /** The write held to the row its rules were decided over, where there is a revision. */\n const pin = (expect: Expect, before: Readonly<Record<string, unknown>>): Expect =>\n revision === undefined ? expect : Option.some({ field: revision, revision: before[revision] })\n /**\n * `attempt` run again while its pinned write misses: the row moved after it\n * was read, so it is decided again over the row as it now is. A write the\n * input pinned misses as a conflict, and is not run again.\n */\n const pinned = <A, E, RA>(\n id: string,\n expect: Expect,\n missed: (outcome: A) => boolean,\n attempt: () => Effect.Effect<A, E, RA>,\n ): Effect.Effect<A, E | RemoteServerError, RA> => {\n if (revision === undefined) return attempt()\n if (Option.isSome(expect)) {\n // The pin is the one revision the write moves on; another would stand still.\n return expect.value.field === revision\n ? attempt()\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s input expects \"${expect.value.field}\", but its writer pins \"${revision}\"`,\n }),\n )\n }\n const loop = (left: number): Effect.Effect<A, E | RemoteServerError, RA> =>\n Effect.flatMap(attempt(), outcome =>\n !missed(outcome)\n ? Effect.succeed(outcome)\n : left > 1\n ? loop(left - 1)\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name} ${id} changed while it was written`,\n }),\n ),\n )\n return loop(3)\n }\n const attachment = attached(entity)\n const hiddenByBody = new WeakMap<AnyQuery, ReadonlyArray<string>>()\n // An invariant reading a member a Read rule hides is still enforced, but named to no\n // one: which one failed, and where, would say what that member holds.\n const unnamed = new Set(\n Option.match(attachment, {\n onNone: () => [],\n onSome: ruled =>\n Entity.invariants(entity)\n .filter(held => [...held.before, ...held.after].some(key => readRuled(ruled, key)))\n .map(held => held.id),\n }),\n )\n const told = <E>(error: E | RemoteInvalid): E | RemoteInvalid =>\n error instanceof RemoteInvalid && Option.exists(error.rule, rule => unnamed.has(rule))\n ? RemoteServer.invalid('The row would be invalid')\n : error\n /**\n * Fails a write whose `when` reads, or whose `expect` names, a member with\n * a Read rule: Unmet or written, Conflict or not, would answer for it.\n * `validate` refuses the same at startup; this holds where it was not run.\n */\n const discloses = (\n expect: Expect,\n when: Option.Option<WriteWhen>,\n ): Effect.Effect<void, RemoteServerError> =>\n Option.match(attachment, {\n onNone: () => Effect.void,\n onSome: ruled => {\n const read = Option.match(when, {\n onNone: () => [],\n onSome: ({ body }) => {\n const known = hiddenByBody.get(body)\n if (known !== undefined) return known\n const hidden = hiddenOf(ruled, Query.dependencies(body).predicate)\n hiddenByBody.set(body, hidden)\n return hidden\n },\n })\n const expected = Option.match(expect, {\n onNone: () => [],\n onSome: ({ field }) => (readRuled(ruled, field) ? [field] : []),\n })\n const hidden = [...new Set([...read, ...expected])]\n return hidden.length === 0\n ? Effect.void\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write reads ${hidden.join(', ')}, which a Read rule hides from its writer`,\n }),\n )\n },\n })\n /**\n * The answer the writer's ledger holds for this operation, or else `write`:\n * a retry of a write that landed is answered as it landed, not decided\n * again over a row that may have moved since.\n */\n const answeredOr = <E, RA>(\n context: {\n readonly id: string\n readonly operation: Option.Option<string>\n readonly principal: Option.Option<User>\n },\n write: () => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, E, RA>,\n ) => {\n const recorded = writer.recorded\n if (recorded === undefined || Option.isNone(context.operation)) return write()\n return Effect.flatMap(\n recorded({\n operation: context.operation.value,\n id: context.id,\n principal: context.principal,\n }),\n Option.match({ onSome: answer => Effect.succeed(Option.some(answer)), onNone: write }),\n )\n }\n // What an answer shows: the row as the writer may see it, members ruled.\n const memberRead = GuardServer.filter(entity, policy)\n // An update, step by step: admitted for what it declares, its rules chosen, the\n // row they read read, the rules decided over it as it is and as it would be, then\n // written pinned to that row. Each step refuses before the next can speak.\n type UpdateContext = Parameters<EntityWriter<Option.Option<User>, RW>['update']>[0]\n interface UpdateRules {\n readonly row: RowRule\n readonly members: ReadonlyArray<RowRule>\n readonly relating: Effect.Success<ReturnType<typeof linkRules>>\n }\n /** Refused before any rule, for what the write declares rather than what the row holds. */\n const admitUpdate = (context: UpdateContext): Effect.Effect<void, RemoteServerError> =>\n Effect.andThen(discloses(context.expect, context.when), () =>\n // The rules judge a sum over the row read: unpinned, that is not the row written.\n Object.keys(context.increments).length > 0 &&\n Option.isNone(context.expect) &&\n revision === undefined\n ? Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s increment expects no revision and its writer pins none, so its rules would judge a sum over a row that may move; give the writer a revision`,\n }),\n )\n : Effect.void,\n )\n /** The rules an update must meet: the row's, each member it sets, each relation it points. */\n const updateRules = (context: UpdateContext) =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Update')\n // An incremented field is set as surely as a written one: its Update rule holds.\n const members = yield* policy.writeMembers(\n entity,\n context.principal,\n [...Object.keys(context.values), ...Object.keys(context.increments)],\n 'Update',\n )\n const relating = yield* linkRules(context.principal, context.links)\n return { row, members, relating } satisfies UpdateRules\n })\n /** The row as its writer may see it, with every field the rules and the version read. */\n const readBefore = (context: UpdateContext, rules: UpdateRules) =>\n read({\n id: context.id,\n fields: fieldsOf(\n [rules.row, ...rules.members, ...ruleOf(rules.relating)],\n [...Object.keys(context.links), ...versionFields(context.expect)],\n ),\n principal: context.principal,\n })\n /** The rules, over the row as it is and as the write would leave it. */\n const decideUpdate = (\n context: UpdateContext,\n rules: UpdateRules,\n before: Readonly<Record<string, unknown>>,\n ) =>\n Effect.gen(function* () {\n const { principal, values, increments, links } = context\n const linked = Object.keys(links)\n const stored =\n writer.linked === undefined || linked.length === 0\n ? Option.none()\n : yield* writer.linked({ id: context.id, relations: linked })\n const relations = linking(\n rules.relating,\n Option.some(\n Option.match(stored, {\n onNone: () => ({ links: before, exact: false }),\n onSome: links => ({ links, exact: true }),\n }),\n ),\n )\n // The sum the writer will store, over the row read, which the pin keeps as the row\n // written. Only a rule reads it, and `fieldsOf` read every field a rule reads.\n const after = {\n ...before,\n ...values,\n ...Object.fromEntries(\n Object.entries(increments).map(([field, amount]) => [\n field,\n Number(before[field]) + amount,\n ]),\n ),\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n yield* require([rules.row, ...rules.members, ...relations], before, principal)\n yield* require([rules.row], after, principal)\n })\n const guarded: EntityWriter<Option.Option<User>, R | RW> = {\n entity: writer.entity,\n // The precondition is the writer's to check, in the statement that writes.\n ...(writer.preconditions === true ? { preconditions: true } : {}),\n ...(writer.increments === true ? { increments: true } : {}),\n ...(writer.ledger === true ? { ledger: true } : {}),\n // Invariants are the writer's to judge, over the row its statement writes.\n ...(writer.invariants === true ? { invariants: true } : {}),\n // What the store refuses, the store knows: the guard adds no reason and drops none.\n ...(writer.refuses === undefined ? {} : { refuses: writer.refuses }),\n ...(writer.recorded === undefined ? {} : { recorded: writer.recorded }),\n read: ({ id, fields, principal }) =>\n seenRow(\n { filter: memberRead },\n seen => read({ id, fields: seen, principal }),\n principal,\n fields,\n id,\n ),\n update: context =>\n Effect.mapError(\n Effect.andThen(admitUpdate(context), () =>\n answeredOr(context, () =>\n pinned(context.id, context.expect, Option.isNone, () =>\n Effect.gen(function* () {\n const rules = yield* updateRules(context)\n const current = yield* readBefore(context, rules)\n if (Option.isNone(current)) return yield* Effect.fail(refused(rules.row.deny))\n if (moved(context.expect, current.value)) return Option.none()\n yield* decideUpdate(context, rules, current.value)\n return yield* writer.update({\n ...context,\n expect: pin(context.expect, current.value),\n })\n }),\n ),\n ),\n ),\n told,\n ),\n insert: given =>\n Effect.gen(function* () {\n const preset = presets.find(({ field }) => Object.hasOwn(given.values, field))\n if (preset !== undefined) {\n return yield* new RemoteServerError({\n message: `${entity.name}'s \"${preset.field}\" is preset by the server; the input may not set it`,\n })\n }\n if (presets.length > 0 && Option.isNone(given.principal)) {\n return yield* Effect.fail(RemoteServer.forbid())\n }\n const context = Option.match(given.principal, {\n onNone: () => given,\n onSome: user => ({\n ...given,\n values: {\n ...given.values,\n ...Object.fromEntries(presets.map(({ field, value }) => [field, value(user)])),\n },\n }),\n })\n const { principal, values, links } = context\n const row = yield* policy.writable(entity, principal, 'Create')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n Object.keys(values),\n 'Create',\n )\n const relations = linking(yield* linkRules(principal, links), Option.none())\n const proposed = {\n ...values,\n id: context.id,\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n const rules = [row, ...members, ...relations]\n const ruled = rules.flatMap(({ condition }) => Condition.members(condition))\n const unset = new Set(ruled.filter(field => !Object.hasOwn(proposed, field)))\n yield* require(rules.map(rule => ({\n ...rule,\n condition: Condition.unsetting(rule.condition, unset),\n })), proposed, principal)\n return yield* Effect.mapError(writer.insert(context), told)\n }),\n delete: context =>\n Effect.andThen(discloses(context.expect, context.when), () =>\n pinned(\n context.id,\n context.expect,\n outcome => outcome === 'moved',\n () =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Delete')\n const current = yield* read({\n id: context.id,\n fields: fieldsOf([row], versionFields(context.expect)),\n principal: context.principal,\n })\n // Hidden or gone, the writer sees no row: there is nothing of theirs to delete.\n if (Option.isNone(current)) return 'absent' as const\n if (moved(context.expect, current.value)) return 'moved' as const\n yield* require([row], current.value, context.principal)\n return yield* writer.delete({\n ...context,\n expect: pin(context.expect, current.value),\n })\n }),\n ),\n ),\n }\n pins.set(guarded, Option.fromUndefinedOr(revision))\n return writeRules.add(guarded, policy, [entity])\n },\n\n /**\n * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for\n * `interaction` checked before it runs. The row the input names (`id`) is\n * read through `source`, which must apply the Entity's Read rules, and the\n * rule must hold over it; a row its writer may not see is refused. With no\n * `id` (a create), the rule must hold of who is asking alone, a field it\n * reads matching no guard. `run` is given the row as read: its fields the\n * rule reads, its `id`, and `fields`. A refusal is `Forbidden`; `run` never\n * runs. What `run` writes is its own: check members it sets there. Each\n * row of `entity` its answer carries is read back through `source`, so the\n * answer shows its writer only what they may see, a row it hid from them\n * as deleted.\n *\n * ```ts\n * GuardServer.mutation(ArchiveTodo, {\n * entity: Todo, policy: Policy, interaction: Archive.key,\n * id: input => input.id, source: source(Db.Todo),\n * }, ({ input, row }) => …)\n * ```\n */\n mutation: <User, R, RS, RM, Name extends string, Input, Output, Refused>(\n mutation: MutationDescriptor<Name, Input, Output, Refused>,\n guard: {\n readonly entity: AnyEntity\n readonly policy: Policy<User, R>\n readonly interaction: 'Create' | 'Update' | 'Delete' | InteractionKey\n /**\n * The row the input acts on; none for a create. An input whose id may be\n * absent (`Option`, as one editor's for create and edit) creates when it\n * is, checked against `Create`.\n */\n readonly id?: ((input: Input) => string | Option.Option<string>) | undefined\n /** Reads the row as its writer may see it: the Entity's guarded Source. */\n readonly source: EntitySource<Option.Option<User>, RS>\n /** More of the row for `run`, beside what the rule reads. */\n readonly fields?: ReadonlyArray<string> | undefined\n },\n run: (context: {\n readonly input: Input\n readonly principal: Option.Option<User>\n readonly requestId: string\n readonly row: Option.Option<Readonly<Record<string, unknown>>>\n }) => Effect.Effect<\n MutationOutcome<Output>,\n RemoteServerError | MutationRefused | RemoteForbidden,\n RM\n >,\n ): MutationSource<Option.Option<User>, R | RS | RM> => {\n const { entity, policy, interaction, id, source } = guard\n if (!rowRules.has(source.visible, policy, entity)) {\n throw new Error(\n `[foldkit-guard] GuardServer.mutation: ${mutation.name}'s Source does not apply ${entity.name}'s Read rules`,\n )\n }\n /**\n * The answer as its writer may now see it: each row of `entity` it carries\n * read back through `source`, and one the handler hid from them deleted.\n */\n const shown = (outcome: MutationOutcome<Output>, principal: Option.Option<User>) =>\n Effect.map(\n Effect.forEach(outcome.entities ?? [], patch =>\n patch.entity !== entity.name\n ? Effect.succeed(Option.some(patch))\n : Effect.map(\n seenRow(\n source,\n fields =>\n Effect.map(rowOf(source, principal, fields, patch.id), Option.fromUndefinedOr),\n principal,\n Object.keys(patch.values),\n patch.id,\n ),\n Option.map(seen => ({ ...patch, values: seen })),\n ),\n ),\n read => ({\n ...outcome,\n entities: read.flatMap(Option.toArray),\n deleted: [\n ...(outcome.deleted ?? []),\n ...(outcome.entities ?? [])\n .filter((_, index) => Option.isNone(read[index]!))\n .map(({ entity, id }) => ({ entity, id })),\n ],\n }),\n )\n return RemoteServer.mutation<Option.Option<User>, R | RS | RM, Name, Input, Output, Refused>(\n mutation,\n context =>\n Effect.gen(function* () {\n const { principal } = context\n // `context.input` was decoded against the mutation's Input before this runs.\n const target = Option.flatMap(Option.fromUndefinedOr(id), of => {\n const named = of(context.input)\n return typeof named === 'string' ? Option.some(named) : named\n })\n const rule = yield* policy.writable(\n entity,\n principal,\n id !== undefined && Option.isNone(target) ? 'Create' : interaction,\n )\n const ruled = Condition.members(rule.condition)\n const input = policy.inputOf(principal)\n if (Option.isNone(target)) {\n const unset = Condition.unsetting(rule.condition, new Set(ruled))\n if (!Condition.holds(unset, {}, input, () => false, policy.operators)) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row: Option.none() }), principal)\n }\n const fields = [...new Set(['id', ...ruled, ...(guard.fields ?? [])])]\n const row = Option.fromUndefinedOr(yield* rowOf(source, principal, fields, target.value))\n if (\n Option.isNone(row) ||\n !Condition.holds(rule.condition, row.value, input, () => false, policy.operators)\n ) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row }), principal)\n }),\n )\n },\n\n /**\n * Checks, at startup, that `server` applies the guards of `entities`, the\n * Entities as `Guards.attach` returned them: each one's Source and each\n * query listing it apply its row's Read rules (`GuardDrizzle.visible`, or\n * `GuardServer.memory`), its Source applies its members' and relations'\n * (`GuardServer.filter`), and each declared write of it lands through\n * `GuardServer.writer`, all built from `policy`; and that no query's body\n * filters or orders by a member with a Read rule, which would answer for the\n * value it hides. A hand-written Source over a guarded Entity would serve\n * every row, and a bare writer would take every write; this throws instead,\n * naming each. A handler (`RemoteServer.mutation`) writes what its code\n * writes, which no check at startup can read.\n *\n * ```ts\n * GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })\n * ```\n */\n validate: <User, R>(\n policy: Policy<User, R>,\n config: {\n readonly entities: ReadonlyArray<AnyEntity>\n /** The Remote domain the server answers, for which Entity each query lists. */\n readonly domain: {\n readonly registry: {\n readonly queries: ReadonlyMap<\n string,\n { readonly Result: unknown; readonly body?: AnyQuery | undefined }\n >\n }\n }\n readonly server: ServerDefinition<any, any>\n },\n ): void => {\n const byName = new Map(config.entities.map(entity => [entity.name, entity]))\n /** Whether who may read the rows of `entity` depends on who is asking. */\n const rowsRuled = (entity: AnyEntity | undefined) =>\n Option.exists(Option.flatMap(Option.fromUndefinedOr(entity), attached), attachment =>\n readRowsRuled(attachment),\n )\n // A query the domain does not declare lists an Entity no one can name.\n const undeclared = [...config.server.queries.keys()]\n .filter(query => !config.domain.registry.queries.has(query))\n .map(query => `query ${query} is served, but the domain does not declare it`)\n const entityProblems = config.entities.flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => {\n const name = entity.name\n if (attachment.set !== policy.set) {\n return [`${name} carries the guards of ${attachment.set}, not ${policy.set}`]\n }\n // Every guarded Entity's, whether or not it has rules there yet: a rule\n // attached later is then applied, not served past.\n const source = Option.fromUndefinedOr(config.server.entities.get(name))\n const sourceProblems = Option.match(source, {\n onNone: () => [],\n onSome: ({ visible, filter }) => [\n ...(rowRules.has(visible, policy, entity)\n ? []\n : [`${name}'s Source does not apply its Read rules`]),\n ...(memberRules.has(filter, policy, entity)\n ? []\n : [`${name}'s Source does not apply its members' Read rules`]),\n ],\n })\n const queryProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, query]) => {\n const listed = config.server.queries.get(queryName)\n return listed !== undefined &&\n lists(query.Result, name) &&\n !rowRules.has(listed.visible, policy, entity)\n ? [`query ${queryName} lists ${name} without its Read rules`]\n : []\n },\n )\n // A row the reader may see with a member it may not still answers a\n // filter or an order on that member: `cost < $max`, halved twenty\n // times, reads the cost the row came back without.\n const bodyProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, { body }]) => {\n if (body === undefined || body.entity.name !== name) return []\n const { predicate, order } = Query.dependencies(body)\n return [\n ...hiddenOf(attachment, predicate).map(\n member =>\n `query ${queryName} filters ${name} by ${member}, which has a Read rule`,\n ),\n ...hiddenOf(attachment, order).map(\n member => `query ${queryName} orders ${name} by ${member}, which has a Read rule`,\n ),\n ]\n },\n )\n const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => {\n if (source.writes === undefined || source.writes.entity !== name) return []\n if (!writeRules.has(source.writes.writer, policy, entity)) {\n return [`write ${mutation} writes ${name} without its write rules`]\n }\n const { write, writer } = source.writes\n // Unmet or written, Conflict or not, answers for a member its writer may not read.\n const when = Option.match(write.when, {\n onNone: () => [],\n onSome: body => hiddenOf(attachment, Query.dependencies(body).predicate),\n })\n const expected = write.expect?.field.key\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n return [\n ...when.map(\n member =>\n `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`,\n ),\n ...(expected !== undefined && readRuled(attachment, expected)\n ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`]\n : []),\n ...(expected !== undefined &&\n pin !== undefined &&\n Option.exists(pin, field => field !== expected)\n ? [\n `write ${mutation} expects ${name}'s ${expected}, but its writer pins ${Option.getOrThrow(pin)}`,\n ]\n : []),\n ]\n })\n // A shared field goes to every live subscriber as written: no rule may tell them apart.\n const shared = Option.match(source, {\n onNone: () => [],\n onSome: source => [...(source.shared ?? [])],\n })\n const sharedProblems = [\n ...(shared.length > 0 && readRowsRuled(attachment)\n ? [`${name}'s Source shares ${shared.join(', ')}, but its rows have a Read rule`]\n : []),\n ...shared.flatMap(member => {\n const own = readRuled(attachment, member)\n ? [`${name}'s Source shares ${member}, which has a Read rule`]\n : []\n if (!Object.hasOwn(entity.relations, member)) return own\n const target = entity.relations[member]!.target().name\n if (!byName.has(target))\n return [\n ...own,\n `${name}'s Source shares ${member}, whose ${target} is not validated`,\n ]\n return rowsRuled(byName.get(target))\n ? [...own, `${name}'s Source shares ${member}, whose rows have a Read rule`]\n : own\n }),\n ]\n // A rule calling an operator the policy's table does not run would fail when\n // asked, so the server does not start with one (expr-operations-DESIGN §5.6).\n const operatorProblems = attachedRules(attachment).flatMap(rule =>\n rule._tag === 'RowGuard'\n ? Query.unsupported(rule.query, supported, policy.operators).map(\n missing =>\n `${name}'s ${rule.name} calls ${missing}, which the policy does not run`,\n )\n : [],\n )\n // A live Source of its own streams whatever it reads: nothing here can check it.\n const liveProblems = config.server.live.has(name)\n ? [`${name} has a live Source of its own; serve its changes through a live hub`]\n : []\n return [\n ...sourceProblems,\n ...queryProblems,\n ...bodyProblems,\n ...writeProblems,\n ...sharedProblems,\n ...operatorProblems,\n ...liveProblems,\n ]\n },\n }),\n )\n const problems = [...undeclared, ...entityProblems]\n if (problems.length > 0) {\n throw new Error(`[foldkit-guard] GuardServer.validate: ${problems.join('; ')}`)\n }\n // Not refused yet: a writer given no revision is how every writer was made before it.\n const unpinnedWrites = [...config.server.mutations].flatMap(([mutation, source]) => {\n const writer = source.writes?.writer\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n return pin !== undefined && Option.isNone(pin) ? [mutation] : []\n })\n if (unpinnedWrites.length > 0) {\n console.warn(\n `[foldkit-guard] GuardServer.validate: ${unpinnedWrites.join(', ')} ${unpinnedWrites.length === 1 ? 'writes' : 'write'} through a GuardServer.writer with no revision, so a change between its check and its write is not seen; pass { revision }`,\n )\n }\n },\n}\n\n/** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */\nconst asksMay = (entity: AnyEntity, fields: ReadonlyArray<string>) =>\n fields.includes('may') && Object.hasOwn(entity.derived, 'may')\n\n/** How one principal's `may` is answered: the fields its rules read, and the answer over a row. */\ninterface MayPlan {\n readonly fields: ReadonlyArray<string>\n readonly answer: (values: Readonly<Record<string, unknown>>) => MayAnswer\n}\n\n/** The interactions a row answers `may` for: `Update`, `Delete`, and each one the set named. */\nconst builtInRow = new Set(['Read', 'Create', 'Update', 'Delete'])\n\n/**\n * `may` for `principal`: each row interaction's rule, each member's own\n * `Update`, each relation's `Link` and `Unlink`, decided once and held over\n * each row as a write's check would hold them over it as it is.\n */\nconst mayOf = <User, R>(\n entity: AnyEntity,\n policy: Policy<User, R>,\n principal: Option.Option<User>,\n): Effect.Effect<MayPlan, never, R> => {\n const attachment = attached(entity)\n const named = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ row }) => Object.keys(row).filter(interaction => !builtInRow.has(interaction)),\n })\n const ruledMembers = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ members }) => Object.keys(members),\n })\n const ruledRelations = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ relations }) => Object.keys(relations),\n })\n return Effect.map(\n Effect.all([\n Effect.forEach(['Update', 'Delete', ...named], interaction =>\n Effect.map(\n // A named one was attached as an `InteractionKey`; its key is the name.\n policy.writable(entity, principal, interaction as InteractionKey),\n rule => [interaction, rule] as const,\n ),\n ),\n policy.writeMembers(entity, principal, ruledMembers, 'Update'),\n Effect.forEach(ruledRelations, relation =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Link'),\n policy.linkable(entity, principal, relation, 'Unlink'),\n ]),\n ([link, unlink]) => ({ relation, link, unlink }),\n ),\n ),\n ]),\n ([rows, members, relations]): MayPlan => {\n const input = policy.inputOf(principal)\n const holds = (condition: Condition, values: Readonly<Record<string, unknown>>) =>\n Condition.holds(condition, values, input, () => false, policy.operators)\n // A relation without a rule for one direction leaves it to the row's Update.\n const allows = (rule: Option.Option<RowRule>, values: Readonly<Record<string, unknown>>) =>\n Option.match(rule, {\n onNone: () => true,\n onSome: ({ condition }) => holds(condition, values),\n })\n const conditions = [\n ...rows.map(([, { condition }]) => condition),\n ...members.map(({ condition }) => condition),\n ...relations.flatMap(({ link, unlink }) =>\n [...Option.toArray(link), ...Option.toArray(unlink)].map(({ condition }) => condition),\n ),\n ]\n return {\n // `id` too, so a row is read when its rules read none of it (an admin's).\n fields: ['id', ...new Set(conditions.flatMap(Condition.members))],\n answer: values => ({\n row: Object.fromEntries(\n rows.map(([interaction, { condition }]) => [interaction, holds(condition, values)]),\n ),\n // Only an `explain`'s sentence is for whoever asked.\n reasons: Object.fromEntries(\n rows.flatMap(([interaction, { condition, deny }]) =>\n holds(condition, values)\n ? []\n : Match.valueTags(deny, {\n Explain: ({ reason }) => [[interaction, reason] as const],\n Forbidden: () => [],\n NotFound: () => [],\n Omit: () => [],\n Redact: () => [],\n }),\n ),\n ),\n members: Object.fromEntries(\n members.map(({ member, condition }) => [member, holds(condition, values)]),\n ),\n relations: Object.fromEntries(\n relations.map(({ relation, link, unlink }) => [\n relation,\n { Link: allows(link, values), Unlink: allows(unlink, values) },\n ]),\n ),\n }),\n }\n },\n )\n}\n\n/** A refused write as the client receives it: the sentence an `explain` gave, or none. */\nconst refused = (deny: Deny) =>\n Match.valueTags(deny, {\n Explain: ({ reason }) => RemoteServer.forbid(reason),\n Forbidden: () => RemoteServer.forbid(),\n NotFound: () => RemoteServer.forbid(),\n Omit: () => RemoteServer.forbid(),\n Redact: () => RemoteServer.forbid(),\n })\n\n/** One row, by id, as `principal` may read it through `source`. */\nconst rowOf = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n) =>\n Effect.map(\n source.read({ ids: [id], fields: [...fields], principal }),\n records => records.find(record => record.id === id)?.values,\n )\n\n/**\n * Row `id` of `fields` as `principal` may see it, through `see`'s `authorize`\n * and `filter` as a Source applies them, and no more than was asked: what an\n * answer shows its writer. None when the row is not there to them.\n */\nconst seenRow = <P, R, RS>(\n see: Pick<EntitySource<P, RS>, 'authorize' | 'filter'>,\n read: (\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n): Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R | RS> =>\n Effect.gen(function* () {\n const allowed = see.authorize === undefined ? fields : see.authorize(principal, [...fields])\n const plan: ReadPlan =\n see.filter === undefined\n ? { fields: allowed, apply: noMembers }\n : yield* see.filter(principal, allowed)\n // The id too: a row asked for nothing else is still there or not.\n const row = yield* read([...new Set(['id', ...plan.fields])])\n return Option.map(row, values => {\n const shown = plan.apply({ id, values }).values\n return Object.fromEntries(\n allowed.filter(field => Object.hasOwn(shown, field)).map(field => [field, shown[field]]),\n )\n })\n })\n\n/** A link's value as a row holds it: the ref's key, or `null` for none. */\nconst linkKey = (link: Option.Option<{ readonly entity: string; readonly id: string }>) =>\n Option.match(link, { onNone: () => null, onSome: ref => `${ref.entity}:${ref.id}` })\n\n/** Whether a query's result is a connection over `entity`. */\nconst lists = (result: unknown, entity: string): boolean =>\n typeof result === 'object' && result !== null && 'entity' in result && result.entity === entity\n"],"mappings":";;;;;;;;;;;;;;;AAwCA,MAAM,aAAa,WAAyB;;AAG5C,MAAM,cAAc,MAAe,UACjC,KAAK,UAAU,IAAI,MAAM,KAAK,UAAU,KAAK;;AAG/C,MAAM,YACJ,YACA,WAC0B,CAC1B,GAAG,IAAI,IAAI,OAAO,KAAI,UAAS,MAAM,GAAG,CAAC,CAAC,QAAO,QAAO,UAAU,YAAY,GAAG,CAAC,CAAC,CACrF;;AAGA,MAAM,uBAAO,IAAI,QAAuC;;AAGxD,MAAM,SAAS,UAAoF;CACjG,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,KAAK;CAClD,MAAM,QAAQ,MAAM,QAAQ,GAAG;CAC/B,OAAO,SAAS,IACZ,OAAO,KAAK,IACZ,OAAO,KAAK;EAAE,QAAQ,MAAM,MAAM,GAAG,KAAK;EAAG,IAAI,MAAM,MAAM,QAAQ,CAAC;CAAE,CAAC;AAC/E;AAEA,MAAa,cAAc;;;;;;;;;;CAUzB,KACE,QACA,WACyC;EAEzC,OAAO,IAAI,SAAS,MAAM,IAAI,EAAE,UAAU;GACxC,IAAI,QAAQ,OAAO,KACjB,MAAM,IAAI,MACR,4DAA4D,IAAI,QAAQ,OAAO,KACjF;EAEJ,CAAC;EACD,OAAO;GACL,GAAG,aAAa,OAA+B,QAAQ;IACrD,OAAO,EAAE,KAAK,gBACZ,OAAO,QACL,IACG,QAA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AAO,IAAI,OAAO,WAAW,OAAO;CAE1C,MAAM,MAAM,OAAO,KAAK,CAAC,mBAAG,IAAI,IAAI,CAAC,MAAM,GAAG,KAAK,MAAM,CAAC,CAAC,CAAC;CAC5D,OAAO,OAAO,IAAI,MAAK,WAAU;EAC/B,MAAM,QAAQ,KAAK,MAAM;GAAE;GAAI;EAAO,CAAC,CAAC,CAAC;EACzC,OAAO,OAAO,YACZ,QAAQ,QAAO,UAAS,OAAO,OAAO,OAAO,KAAK,CAAC,CAAC,CAAC,KAAI,UAAS,CAAC,OAAO,MAAM,MAAM,CAAC,CACzF;CACF,CAAC;AACH,CAAC;;AAGH,MAAM,WAAW,SACf,OAAO,MAAM,MAAM;CAAE,cAAc;CAAM,SAAQ,QAAO,GAAG,IAAI,OAAO,GAAG,IAAI;AAAK,CAAC;;AAGrF,MAAM,SAAS,QAAiB,WAC9B,OAAO,WAAW,YAAY,WAAW,QAAQ,YAAY,UAAU,OAAO,WAAW"}
1
+ {"version":3,"file":"server.mjs","names":[],"sources":["../src/server.ts"],"sourcesContent":["/**\n * A guard set's read rules as `foldkit-remote-server`'s seams: an\n * `EntitySource.filter` from each member's Read rule, and `RemoteServer.memory`'s\n * `readable` and `filter` from the row's, and a check at startup that a server\n * applies them. A subpath, so the shared declaration the browser imports never\n * brings the server along.\n */\nimport { Effect, Match, Option, Schema, SchemaAST } from 'effect'\nimport {\n Entity,\n Expr,\n Query,\n QueryEvaluateError,\n Write,\n dependenciesOf,\n supported,\n type AnyEntity,\n type AnyQuery,\n} from 'foldkit-entity'\nimport type { MutationDescriptor, RemoteForbidden } from 'foldkit-remote'\nimport {\n RemoteInvalid,\n RemoteServer,\n RemoteServerError,\n type EntityRecord,\n type EntitySource,\n type EntityWriter,\n type MutationOutcome,\n type MutationRefused,\n type MutationSource,\n type MemoryReadable,\n type ReadPlan,\n type ServerDefinition,\n type WriteWhen,\n} from 'foldkit-remote-server'\nimport {\n attached,\n attachedRules,\n readRowsRuled,\n readRuled,\n type Attachment,\n type Deny,\n type InteractionKey,\n} from './attach.js'\nimport { Condition, type RowRule } from './condition.js'\nimport type { Policy } from './index.js'\nimport type { MayAnswer } from './may.js'\nimport { ME, type MeEntity } from './me.js'\nimport { memberRules, rowRules, writeRules } from './placed.js'\n\nconst noMembers = (record: EntityRecord) => record\n\n/** Two stored values, which are JSON: equal when they encode the same. */\nconst sameStored = (left: unknown, right: unknown): boolean =>\n JSON.stringify(left) === JSON.stringify(right)\n\n/** The members of `fields` that have a Read rule, once each. */\nconst hiddenOf = (\n attachment: Attachment,\n fields: ReadonlyArray<{ readonly key: string }>,\n): ReadonlyArray<string> => [\n ...new Set(fields.map(field => field.key).filter(key => readRuled(attachment, key))),\n]\n\n/** Each guarded writer's `revision`, or none: one a change can fall between check and write of. */\nconst pins = new WeakMap<object, Option.Option<string>>()\n\n/** A ref key's two halves, `Entity:id`; `none` for anything else. */\nconst refOf = (value: unknown): Option.Option<{ readonly entity: string; readonly id: string }> => {\n if (typeof value !== 'string') return Option.none()\n const split = value.indexOf(':')\n return split <= 0\n ? Option.none()\n : Option.some({ entity: value.slice(0, split), id: value.slice(split + 1) })\n}\n\nexport const GuardServer = {\n /**\n * `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`\n * answered by `policy`. `signedIn` is whether the server answered as\n * someone; `key` is their `key`. Any other id is no row.\n *\n * ```ts\n * RemoteServer.make({ entities: [GuardServer.me(Me, Policy), …] })\n * ```\n */\n me: <User, R>(\n entity: MeEntity,\n policy: Policy<User, R>,\n ): EntitySource<Option.Option<User>, R> => {\n // Otherwise every read would die deciding another set's guards.\n Option.map(attached(entity), ({ set }) => {\n if (set !== policy.set) {\n throw new Error(\n `[foldkit-guard] GuardServer.me: Me carries the guards of ${set}, not ${policy.set}`,\n )\n }\n })\n return {\n ...RemoteServer.entity<Option.Option<User>, R>(entity, {\n read: ({ ids, principal }) =>\n Effect.succeed(\n ids\n .filter(id => id === ME)\n .map(id => ({\n id,\n values: {\n signedIn: Option.isSome(principal),\n // Encoded, as a Source answers: `null` for a visitor.\n key: Option.match(principal, {\n onNone: () => null,\n onSome: policy.key,\n }),\n },\n })),\n ),\n filter: GuardServer.filter(entity, policy),\n }),\n // Its Read rule as this Source applies it: only the asker's own row,\n // which `Guards.me` lets anyone read. One per call: the registry is keyed\n // by it, and another call is for another Policy.\n visible: rowRules.add(Object.freeze({ reads: 'the asker’s own row' }), policy, [entity]),\n }\n },\n\n /**\n * An `EntitySource.filter` for `entity`: each requested member with a Read\n * rule is decided per record, omitted or redacted where the rule refuses.\n * The fields a rule reads are read too, so it can be decided.\n *\n * ```ts\n * RemoteServer.entity(Todo, { read, filter: GuardServer.filter(Todo, Policy) })\n * ```\n */\n filter: <User, R>(entity: AnyEntity, policy: Policy<User, R>) =>\n memberRules.add(\n (\n principal: Option.Option<User>,\n fields: readonly string[],\n ): Effect.Effect<ReadPlan, never, R> =>\n Effect.map(\n Effect.all([\n policy.readMembers(entity, principal, fields),\n // `may` is answered here, where the row is read as its principal sees it.\n asksMay(entity, fields)\n ? Effect.map(mayOf(entity, policy, principal), Option.some)\n : Effect.succeed(Option.none<MayPlan>()),\n ]),\n ([members, may]): ReadPlan => {\n if (members.length === 0 && Option.isNone(may)) return { fields, apply: noMembers }\n const input = policy.inputOf(principal)\n const decided = members.map(member => ({\n ...member,\n // A redacted value is a decoded one; the record holds what the store holds.\n redacted:\n member.deny._tag === 'Redact'\n ? Option.some(\n Schema.encodeSync(\n (\n entity.members as Readonly<\n Record<string, { readonly schema: Schema.Top }>\n >\n )[member.member]!.schema as unknown as Schema.Codec<unknown, unknown>,\n )(member.deny.value),\n )\n : Option.none(),\n }))\n return {\n fields: [\n ...new Set([\n ...fields,\n ...members.flatMap(({ condition }) => Condition.members(condition)),\n ...Option.match(may, { onNone: () => [], onSome: ({ fields }) => fields }),\n ]),\n ],\n apply: record => {\n const values: Record<string, unknown> = { ...record.values }\n for (const { member, condition, redacted } of decided) {\n // Member rules carry no inherited Read: only a row's Read may inherit.\n if (\n Condition.holds(condition, record.values, input, () => false, policy.operators)\n )\n continue\n Option.match(redacted, {\n onNone: () => {\n delete values[member]\n },\n onSome: value => {\n values[member] = value\n },\n })\n }\n Option.map(may, ({ answer }) => {\n values.may = answer(record.values)\n })\n return { id: record.id, values }\n },\n }\n },\n ),\n policy,\n [entity],\n ),\n\n /**\n * `RemoteServer.memory`'s `readable` and `filter` for `entities`, the\n * Entities as `Guards.attach` returned them. A row's Read is decided per\n * stored row, an inherited Read by looking the related row up; an Entity\n * not listed is read by everyone.\n */\n memory: <User>(policy: Policy<User>, entities: ReadonlyArray<AnyEntity>) => ({\n readable: rowRules.add(\n (\n principal: Option.Option<User>,\n row: (entity: string, id: string) => Option.Option<Readonly<Record<string, unknown>>>,\n ): Effect.Effect<MemoryReadable> =>\n Effect.map(\n Effect.forEach(entities, entity =>\n Effect.map(\n policy.readable(entity, principal),\n condition => [entity.name, condition] as const,\n ),\n ),\n (decided): MemoryReadable => {\n const conditions = new Map(decided)\n const input = policy.inputOf(principal)\n // `seen` stops a cycle of inherited Reads, which would otherwise never end.\n const holds = (\n entity: string,\n values: Readonly<Record<string, unknown>>,\n seen: ReadonlySet<string>,\n ): boolean => {\n const condition = conditions.get(entity)\n if (condition === undefined) return true\n return Condition.holds(\n condition,\n values,\n input,\n relation =>\n Option.match(refOf(values[relation]), {\n onNone: () => false,\n onSome: ref => {\n const key = `${ref.entity}:${ref.id}`\n if (seen.has(key)) return false\n return Option.match(row(ref.entity, ref.id), {\n onNone: () => false,\n onSome: target => holds(ref.entity, target, new Set([...seen, key])),\n })\n },\n }),\n policy.operators,\n )\n }\n return (entity, values) => holds(entity, values, new Set())\n },\n ),\n policy,\n entities,\n ),\n filter: Object.fromEntries(\n entities.map(entity => [entity.name, GuardServer.filter(entity, policy)] as const),\n ),\n }),\n\n /**\n * `writer` with `entity`'s write rules checked before each write lands, for\n * `RemoteServer.write`. An update or a delete reads the row first under\n * the writer's own `read` (its Source's read rule): a row the writer may not\n * see is refused as one that is not there, and a delete of it changes\n * nothing. Then the row's rule for the command must hold over the row (an\n * update's over the row as it would be after it too, so a write cannot move\n * a row out of its writer's reach), each member it sets must allow setting\n * it, and each relation it points elsewhere must allow the unlink and the\n * link. A create's rules hold over the values it proposes, where a field the\n * create leaves unset matches no guard, not even one for an empty value. A refusal is\n * `Forbidden`, with the sentence an `explain` gave; the write never runs.\n *\n * `presets` are fields a create takes from who is asking, never from the\n * client (`ownerId: user => user.id`): set before the rules are checked, so\n * a rule over them holds of the creator. A visitor has nothing to preset\n * from, and a create whose input sets a preset field is a mistake of the\n * server's, refused.\n *\n * `revision` names a field stored as a number, which the writer moves on by\n * one with each write it lands. An update or a delete then lands only on the\n * revision its rules were decided over (the writer's `expect`), so a change\n * between the check and the write is never written over; it is decided\n * again against the row as it now is, up to three times. A change that does\n * not move the revision (a handler's, `applyEdits`', raw SQL) is not seen.\n * Without `revision`, none is, and `validate` warns. An input that expects a\n * revision the row read is not at is a `Conflict`, decided before any rule;\n * an input may expect only the field the writer pins.\n *\n * ```ts\n * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))\n * ```\n */\n writer: <E extends AnyEntity, User, R, RW>(\n entity: E,\n policy: Policy<User, R>,\n writer: EntityWriter<Option.Option<User>, RW>,\n options: {\n readonly presets?: {\n readonly [K in keyof E['fields']]?: (user: User) => E['fields'][K]['schema']['Type']\n }\n readonly revision?: keyof E['fields'] & string\n } = {},\n ): EntityWriter<Option.Option<User>, R | RW> => {\n const revision = options.revision\n if (revision !== undefined) {\n const field = Object.hasOwn(entity.fields, revision)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[revision]\n : undefined\n if (field === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${revision}\" for its revision`,\n )\n }\n // The writer moves it on by one in the statement it writes with, so it is stored as a number.\n if (!SchemaAST.isNumber(Schema.toEncoded(field.schema).ast)) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s revision \"${revision}\" is not stored as a number`,\n )\n }\n }\n const presets = Object.entries(options.presets ?? {}).map(([field, preset]) => {\n const declared = Object.hasOwn(entity.fields, field)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[field]\n : undefined\n if (declared === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${field}\" to preset`,\n )\n }\n const encode = Schema.encodeUnknownSync(\n declared.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n return { field, value: (user: User) => encode((preset as (user: User) => unknown)(user)) }\n })\n if (writer.entity !== entity.name) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s rules over a writer for ${writer.entity}`,\n )\n }\n const read = writer.read\n if (read === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s writer reads no row as its writer may see it; bind it with a visible rule (GuardDrizzle.visible)`,\n )\n }\n const holds = (\n rule: { readonly condition: Condition },\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Condition.holds(\n rule.condition,\n values,\n policy.inputOf(principal),\n () => false,\n policy.operators,\n )\n /** Fails with the first rule of `rules` that does not hold over `values`. */\n const require = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Option.match(Option.fromUndefinedOr(rules.find(rule => !holds(rule, values, principal))), {\n onNone: () => Effect.void,\n onSome: rule => Effect.fail(refused(rule.deny)),\n })\n type Links = Readonly<\n Record<string, Option.Option<{ readonly entity: string; readonly id: string }>>\n >\n /** Each relation `links` points: its rules for unlinking and for linking a row. */\n const linkRules = (principal: Option.Option<User>, links: Links) =>\n Effect.forEach(Object.entries(links), ([relation, target]) =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Unlink'),\n policy.linkable(entity, principal, relation, 'Link'),\n ]),\n ([unlink, link]) => ({ relation, now: linkKey(target), unlink, link }),\n ),\n )\n /**\n * The rules a change from what each relation was linked to, to what it now\n * points at, must meet; none `before` is a create, which unlinks nothing.\n * Where `exact` is false, `links` are the row as its writer sees it, where\n * a link to a row hidden from them reads as none: a relation seen unlinked\n * may be linked after all, so changing it unlinks too.\n */\n const linking = (\n rules: ReadonlyArray<{\n readonly relation: string\n readonly now: string | null\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n before: Option.Option<{\n readonly links: Readonly<Record<string, unknown>>\n readonly exact: boolean\n }>,\n ): ReadonlyArray<RowRule> =>\n rules.flatMap(({ relation, now, unlink, link }) =>\n Option.match(before, {\n onNone: () => (now === null ? [] : Option.toArray(link)),\n onSome: ({ links, exact }) => {\n const was = links[relation] ?? null\n if (was === now && (exact || was !== null)) return []\n return [\n ...(was === null && exact ? [] : Option.toArray(unlink)),\n ...(now === null ? [] : Option.toArray(link)),\n ]\n },\n }),\n )\n const ruleOf = (\n rules: ReadonlyArray<{\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n ) => rules.flatMap(({ unlink, link }) => [...Option.toArray(unlink), ...Option.toArray(link)])\n const fieldsOf = (\n rules: ReadonlyArray<{ readonly condition: Condition }>,\n more: Iterable<string>,\n ) => [\n ...new Set([\n 'id',\n ...more,\n ...rules.flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n type Expect = Option.Option<{ readonly field: string; readonly revision: unknown }>\n /** The fields that say which version of the row was read: the revision, and the input's. */\n const versionFields = (expect: Expect) => [\n ...(revision === undefined ? [] : [revision]),\n ...Option.match(expect, { onNone: () => [], onSome: ({ field }) => [field] }),\n ]\n /** Whether the row read is not at the revision the input expects. */\n const moved = (expect: Expect, before: Readonly<Record<string, unknown>>) =>\n Option.exists(expect, ({ field, revision }) => !sameStored(before[field], revision))\n /** The write held to the row its rules were decided over, where there is a revision. */\n const pin = (expect: Expect, before: Readonly<Record<string, unknown>>): Expect =>\n revision === undefined ? expect : Option.some({ field: revision, revision: before[revision] })\n /**\n * `attempt` run again while its pinned write misses: the row moved after it\n * was read, so it is decided again over the row as it now is. A write the\n * input pinned misses as a conflict, and is not run again.\n */\n const pinned = <A, E, RA>(\n id: string,\n expect: Expect,\n missed: (outcome: A) => boolean,\n attempt: () => Effect.Effect<A, E, RA>,\n ): Effect.Effect<A, E | RemoteServerError, RA> => {\n if (revision === undefined) return attempt()\n if (Option.isSome(expect)) {\n // The pin is the one revision the write moves on; another would stand still.\n return expect.value.field === revision\n ? attempt()\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s input expects \"${expect.value.field}\", but its writer pins \"${revision}\"`,\n }),\n )\n }\n const loop = (left: number): Effect.Effect<A, E | RemoteServerError, RA> =>\n Effect.flatMap(attempt(), outcome =>\n !missed(outcome)\n ? Effect.succeed(outcome)\n : left > 1\n ? loop(left - 1)\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name} ${id} changed while it was written`,\n }),\n ),\n )\n return loop(3)\n }\n const attachment = attached(entity)\n const hiddenByBody = new WeakMap<AnyQuery, ReadonlyArray<string>>()\n // An invariant reading a member a Read rule hides is still enforced, but named to no\n // one: which one failed, and where, would say what that member holds.\n const unnamed = new Set(\n Option.match(attachment, {\n onNone: () => [],\n onSome: ruled =>\n Entity.invariants(entity)\n .filter(held => [...held.before, ...held.after].some(key => readRuled(ruled, key)))\n .map(held => held.id),\n }),\n )\n const told = <E>(error: E | RemoteInvalid): E | RemoteInvalid =>\n error instanceof RemoteInvalid && Option.exists(error.rule, rule => unnamed.has(rule))\n ? RemoteServer.invalid('The row would be invalid')\n : error\n /**\n * Fails a write whose `when` reads, whose `expect` names, or whose\n * computed assignment reads, a member with a Read rule: Unmet or written,\n * Conflict or not, and the computed value answered, would answer for it.\n * `validate` refuses the same at startup; this holds where it was not run.\n */\n const discloses = (\n expect: Expect,\n when: Option.Option<WriteWhen>,\n assignments: UpdateContext['assignments'] = {},\n ): Effect.Effect<void, RemoteServerError> =>\n Option.match(attachment, {\n onNone: () => Effect.void,\n onSome: ruled => {\n const read = Option.match(when, {\n onNone: () => [],\n onSome: ({ body }) => {\n const known = hiddenByBody.get(body)\n if (known !== undefined) return known\n const hidden = hiddenOf(ruled, Query.dependencies(body).predicate)\n hiddenByBody.set(body, hidden)\n return hidden\n },\n })\n const expected = Option.match(expect, {\n onNone: () => [],\n onSome: ({ field }) => (readRuled(ruled, field) ? [field] : []),\n })\n const computed = Write.boundReads({ increments: {}, assignments }).filter(field =>\n readRuled(ruled, field),\n )\n const hidden = [...new Set([...read, ...expected, ...computed])]\n return hidden.length === 0\n ? Effect.void\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write reads ${hidden.join(', ')}, which a Read rule hides from its writer`,\n }),\n )\n },\n })\n /**\n * The answer the writer's ledger holds for this operation, or else `write`:\n * a retry of a write that landed is answered as it landed, not decided\n * again over a row that may have moved since.\n */\n const answeredOr = <E, RA>(\n context: {\n readonly id: string\n readonly operation: Option.Option<string>\n readonly principal: Option.Option<User>\n },\n write: () => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, E, RA>,\n ) => {\n const recorded = writer.recorded\n if (recorded === undefined || Option.isNone(context.operation)) return write()\n return Effect.flatMap(\n recorded({\n operation: context.operation.value,\n id: context.id,\n principal: context.principal,\n }),\n Option.match({ onSome: answer => Effect.succeed(Option.some(answer)), onNone: write }),\n )\n }\n // What an answer shows: the row as the writer may see it, members ruled.\n const memberRead = GuardServer.filter(entity, policy)\n // An update, step by step: admitted for what it declares, its rules chosen, the\n // row they read read, the rules decided over it as it is and as it would be, then\n // written pinned to that row. Each step refuses before the next can speak.\n type UpdateContext = Parameters<EntityWriter<Option.Option<User>, RW>['update']>[0]\n interface UpdateRules {\n readonly row: RowRule\n readonly members: ReadonlyArray<RowRule>\n readonly relating: Effect.Success<ReturnType<typeof linkRules>>\n }\n /** Refused before any rule, for what the write declares rather than what the row holds. */\n const admitUpdate = (context: UpdateContext): Effect.Effect<void, RemoteServerError> =>\n Effect.andThen(discloses(context.expect, context.when, context.assignments), () =>\n // The rules judge a sum over the row read: unpinned, that is not the row written.\n Object.keys(context.increments).length + Object.keys(context.assignments).length > 0 &&\n Option.isNone(context.expect) &&\n revision === undefined\n ? Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write moves a field and expects no revision, and its writer pins none, so its rules would judge a value over a row that may move; give the writer a revision`,\n }),\n )\n : Effect.void,\n )\n /** The rules an update must meet: the row's, each member it sets, each relation it points. */\n const updateRules = (context: UpdateContext) =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Update')\n // A field moved or computed is set as surely as a written one: its Update rule holds.\n const members = yield* policy.writeMembers(\n entity,\n context.principal,\n [\n ...Object.keys(context.values),\n ...Object.keys(context.increments),\n ...Object.keys(context.assignments),\n ],\n 'Update',\n )\n const relating = yield* linkRules(context.principal, context.links)\n return { row, members, relating } satisfies UpdateRules\n })\n /**\n * The row as its writer may see it, with every field the rules and the\n * version read, and those the write's amounts and assignments read to\n * work out the row it leaves.\n */\n const readBefore = (context: UpdateContext, rules: UpdateRules) =>\n read({\n id: context.id,\n fields: fieldsOf(\n [rules.row, ...rules.members, ...ruleOf(rules.relating)],\n [\n ...Object.keys(context.links),\n ...versionFields(context.expect),\n ...Write.boundReads(context),\n ],\n ),\n principal: context.principal,\n })\n /**\n * The memory table the row a write leaves is worked out by: the writer's,\n * so the rules judge the value its statement writes, else the policy's.\n */\n const computing = writer.operators ?? policy.operators\n /**\n * The row `context` would leave `before` as. An operator's refusal (text\n * holding NUL, an implementation that throws) is a server error, as the\n * writer answers what it cannot compile: logged here, and never sent, since\n * an implementation's own message may say anything. So is a field it cannot\n * work out at all: judging its old value would let a rule over it pass.\n */\n const leaves = (before: Readonly<Record<string, unknown>>, context: UpdateContext) =>\n Effect.suspend(() => {\n const unworkable = Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write could not be worked out to judge its rules`,\n }),\n )\n try {\n const applied = Write.apply(before, context, { operators: computing })\n return applied.unknown.length === 0 ? Effect.succeed(applied.row) : unworkable\n } catch (error) {\n if (!(error instanceof QueryEvaluateError)) throw error\n return Effect.logError(\n '[foldkit-guard] a computed value could not be worked out',\n error,\n ).pipe(Effect.andThen(unworkable))\n }\n })\n /** The rules, over the row as it is and as the write would leave it. */\n const decideUpdate = (\n context: UpdateContext,\n rules: UpdateRules,\n before: Readonly<Record<string, unknown>>,\n ) =>\n Effect.gen(function* () {\n const { principal, links } = context\n const linked = Object.keys(links)\n const stored =\n writer.linked === undefined || linked.length === 0\n ? Option.none()\n : yield* writer.linked({ id: context.id, relations: linked })\n const relations = linking(\n rules.relating,\n Option.some(\n Option.match(stored, {\n onNone: () => ({ links: before, exact: false }),\n onSome: links => ({ links, exact: true }),\n }),\n ),\n )\n // The rules over the row as stored refuse first: a writer they refuse learns\n // nothing of what its input would compute.\n yield* require([rules.row, ...rules.members, ...relations], before, principal)\n // What the writer will store, over the row read, which the pin keeps as the row\n // written: `Write.apply`'s, as the writer works it out.\n const after = {\n ...(yield* leaves(before, context)),\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n yield* require([rules.row], after, principal)\n })\n const guarded: EntityWriter<Option.Option<User>, R | RW> = {\n entity: writer.entity,\n // The precondition is the writer's to check, in the statement that writes.\n ...(writer.preconditions === true ? { preconditions: true } : {}),\n ...(writer.increments === true ? { increments: true } : {}),\n ...(writer.assignments === true ? { assignments: true } : {}),\n // With a revision every update lands over the row its rules read. Without one an\n // unpinned move is refused, so what the writer would say commutes is not passed on.\n ...(revision === undefined ? {} : { pins: true }),\n ...(writer.ledger === true ? { ledger: true } : {}),\n // Invariants are the writer's to judge, over the row its statement writes.\n ...(writer.invariants === true ? { invariants: true } : {}),\n // What the store refuses, the store knows: the guard drops none of its reasons. It\n // adds one: its rules judge the row the write leaves, worked out by the policy's\n // table, so an assignment that table cannot run would be judged as its old value.\n refuses: write => [\n ...(writer.refuses?.(write) ?? []),\n ...write.assignments.flatMap(({ field, expr }) =>\n Expr.unsupported([expr], { operations: supported, operators: computing }).map(\n missing =>\n `its assignment to \"${field.key}\" calls ${missing}, which the guard cannot work out`,\n ),\n ),\n // Refused per request too (`admitUpdate`), for a caller that registers none.\n ...((write.increments.length > 0 || write.assignments.length > 0) &&\n write.expect === undefined &&\n revision === undefined\n ? [\n 'it moves a field and expects no revision, and the guarded writer pins none, so its rules would judge a value over a row that may move; give the writer a revision',\n ]\n : []),\n ],\n ...(writer.recorded === undefined ? {} : { recorded: writer.recorded }),\n read: ({ id, fields, principal }) =>\n seenRow(\n { filter: memberRead },\n seen => read({ id, fields: seen, principal }),\n principal,\n fields,\n id,\n ),\n update: context =>\n Effect.mapError(\n Effect.andThen(admitUpdate(context), () =>\n answeredOr(context, () =>\n pinned(context.id, context.expect, Option.isNone, () =>\n Effect.gen(function* () {\n const rules = yield* updateRules(context)\n const current = yield* readBefore(context, rules)\n if (Option.isNone(current)) return yield* Effect.fail(refused(rules.row.deny))\n if (moved(context.expect, current.value)) return Option.none()\n yield* decideUpdate(context, rules, current.value)\n return yield* writer.update({\n ...context,\n expect: pin(context.expect, current.value),\n })\n }),\n ),\n ),\n ),\n told,\n ),\n insert: given =>\n Effect.gen(function* () {\n const preset = presets.find(({ field }) => Object.hasOwn(given.values, field))\n if (preset !== undefined) {\n return yield* new RemoteServerError({\n message: `${entity.name}'s \"${preset.field}\" is preset by the server; the input may not set it`,\n })\n }\n if (presets.length > 0 && Option.isNone(given.principal)) {\n return yield* Effect.fail(RemoteServer.forbid())\n }\n const context = Option.match(given.principal, {\n onNone: () => given,\n onSome: user => ({\n ...given,\n values: {\n ...given.values,\n ...Object.fromEntries(presets.map(({ field, value }) => [field, value(user)])),\n },\n }),\n })\n const { principal, values, links } = context\n const row = yield* policy.writable(entity, principal, 'Create')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n Object.keys(values),\n 'Create',\n )\n const relations = linking(yield* linkRules(principal, links), Option.none())\n const proposed = {\n ...values,\n id: context.id,\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n const rules = [row, ...members, ...relations]\n const ruled = rules.flatMap(({ condition }) => Condition.members(condition))\n const unset = new Set(ruled.filter(field => !Object.hasOwn(proposed, field)))\n yield* require(rules.map(rule => ({\n ...rule,\n condition: Condition.unsetting(rule.condition, unset),\n })), proposed, principal)\n return yield* Effect.mapError(writer.insert(context), told)\n }),\n delete: context =>\n Effect.andThen(discloses(context.expect, context.when), () =>\n pinned(\n context.id,\n context.expect,\n outcome => outcome === 'moved',\n () =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Delete')\n const current = yield* read({\n id: context.id,\n fields: fieldsOf([row], versionFields(context.expect)),\n principal: context.principal,\n })\n // Hidden or gone, the writer sees no row: there is nothing of theirs to delete.\n if (Option.isNone(current)) return 'absent' as const\n if (moved(context.expect, current.value)) return 'moved' as const\n yield* require([row], current.value, context.principal)\n return yield* writer.delete({\n ...context,\n expect: pin(context.expect, current.value),\n })\n }),\n ),\n ),\n }\n pins.set(guarded, Option.fromUndefinedOr(revision))\n return writeRules.add(guarded, policy, [entity])\n },\n\n /**\n * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for\n * `interaction` checked before it runs. The row the input names (`id`) is\n * read through `source`, which must apply the Entity's Read rules, and the\n * rule must hold over it; a row its writer may not see is refused. With no\n * `id` (a create), the rule must hold of who is asking alone, a field it\n * reads matching no guard. `run` is given the row as read: its fields the\n * rule reads, its `id`, and `fields`. A refusal is `Forbidden`; `run` never\n * runs. What `run` writes is its own: check members it sets there. Each\n * row of `entity` its answer carries is read back through `source`, so the\n * answer shows its writer only what they may see, a row it hid from them\n * as deleted.\n *\n * ```ts\n * GuardServer.mutation(ArchiveTodo, {\n * entity: Todo, policy: Policy, interaction: Archive.key,\n * id: input => input.id, source: source(Db.Todo),\n * }, ({ input, row }) => …)\n * ```\n */\n mutation: <User, R, RS, RM, Name extends string, Input, Output, Refused>(\n mutation: MutationDescriptor<Name, Input, Output, Refused>,\n guard: {\n readonly entity: AnyEntity\n readonly policy: Policy<User, R>\n readonly interaction: 'Create' | 'Update' | 'Delete' | InteractionKey\n /**\n * The row the input acts on; none for a create. An input whose id may be\n * absent (`Option`, as one editor's for create and edit) creates when it\n * is, checked against `Create`.\n */\n readonly id?: ((input: Input) => string | Option.Option<string>) | undefined\n /** Reads the row as its writer may see it: the Entity's guarded Source. */\n readonly source: EntitySource<Option.Option<User>, RS>\n /** More of the row for `run`, beside what the rule reads. */\n readonly fields?: ReadonlyArray<string> | undefined\n },\n run: (context: {\n readonly input: Input\n readonly principal: Option.Option<User>\n readonly requestId: string\n readonly row: Option.Option<Readonly<Record<string, unknown>>>\n }) => Effect.Effect<\n MutationOutcome<Output>,\n RemoteServerError | MutationRefused | RemoteForbidden,\n RM\n >,\n ): MutationSource<Option.Option<User>, R | RS | RM> => {\n const { entity, policy, interaction, id, source } = guard\n if (!rowRules.has(source.visible, policy, entity)) {\n throw new Error(\n `[foldkit-guard] GuardServer.mutation: ${mutation.name}'s Source does not apply ${entity.name}'s Read rules`,\n )\n }\n /**\n * The answer as its writer may now see it: each row of `entity` it carries\n * read back through `source`, and one the handler hid from them deleted.\n */\n const shown = (outcome: MutationOutcome<Output>, principal: Option.Option<User>) =>\n Effect.map(\n Effect.forEach(outcome.entities ?? [], patch =>\n patch.entity !== entity.name\n ? Effect.succeed(Option.some(patch))\n : Effect.map(\n seenRow(\n source,\n fields =>\n Effect.map(rowOf(source, principal, fields, patch.id), Option.fromUndefinedOr),\n principal,\n Object.keys(patch.values),\n patch.id,\n ),\n Option.map(seen => ({ ...patch, values: seen })),\n ),\n ),\n read => ({\n ...outcome,\n entities: read.flatMap(Option.toArray),\n deleted: [\n ...(outcome.deleted ?? []),\n ...(outcome.entities ?? [])\n .filter((_, index) => Option.isNone(read[index]!))\n .map(({ entity, id }) => ({ entity, id })),\n ],\n }),\n )\n return RemoteServer.mutation<Option.Option<User>, R | RS | RM, Name, Input, Output, Refused>(\n mutation,\n context =>\n Effect.gen(function* () {\n const { principal } = context\n // `context.input` was decoded against the mutation's Input before this runs.\n const target = Option.flatMap(Option.fromUndefinedOr(id), of => {\n const named = of(context.input)\n return typeof named === 'string' ? Option.some(named) : named\n })\n const rule = yield* policy.writable(\n entity,\n principal,\n id !== undefined && Option.isNone(target) ? 'Create' : interaction,\n )\n const ruled = Condition.members(rule.condition)\n const input = policy.inputOf(principal)\n if (Option.isNone(target)) {\n const unset = Condition.unsetting(rule.condition, new Set(ruled))\n if (!Condition.holds(unset, {}, input, () => false, policy.operators)) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row: Option.none() }), principal)\n }\n const fields = [...new Set(['id', ...ruled, ...(guard.fields ?? [])])]\n const row = Option.fromUndefinedOr(yield* rowOf(source, principal, fields, target.value))\n if (\n Option.isNone(row) ||\n !Condition.holds(rule.condition, row.value, input, () => false, policy.operators)\n ) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row }), principal)\n }),\n )\n },\n\n /**\n * Checks, at startup, that `server` applies the guards of `entities`, the\n * Entities as `Guards.attach` returned them: each one's Source and each\n * query listing it apply its row's Read rules (`GuardDrizzle.visible`, or\n * `GuardServer.memory`), its Source applies its members' and relations'\n * (`GuardServer.filter`), and each declared write of it lands through\n * `GuardServer.writer`, all built from `policy`; and that no query's body\n * filters or orders by a member with a Read rule, which would answer for the\n * value it hides. A hand-written Source over a guarded Entity would serve\n * every row, and a bare writer would take every write; this throws instead,\n * naming each. A handler (`RemoteServer.mutation`) writes what its code\n * writes, which no check at startup can read.\n *\n * ```ts\n * GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })\n * ```\n */\n validate: <User, R>(\n policy: Policy<User, R>,\n config: {\n readonly entities: ReadonlyArray<AnyEntity>\n /** The Remote domain the server answers, for which Entity each query lists. */\n readonly domain: {\n readonly registry: {\n readonly queries: ReadonlyMap<\n string,\n { readonly Result: unknown; readonly body?: AnyQuery | undefined }\n >\n }\n }\n readonly server: ServerDefinition<any, any>\n },\n ): void => {\n const byName = new Map(config.entities.map(entity => [entity.name, entity]))\n /** Whether who may read the rows of `entity` depends on who is asking. */\n const rowsRuled = (entity: AnyEntity | undefined) =>\n Option.exists(Option.flatMap(Option.fromUndefinedOr(entity), attached), attachment =>\n readRowsRuled(attachment),\n )\n // A query the domain does not declare lists an Entity no one can name.\n const undeclared = [...config.server.queries.keys()]\n .filter(query => !config.domain.registry.queries.has(query))\n .map(query => `query ${query} is served, but the domain does not declare it`)\n const entityProblems = config.entities.flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => {\n const name = entity.name\n if (attachment.set !== policy.set) {\n return [`${name} carries the guards of ${attachment.set}, not ${policy.set}`]\n }\n // Every guarded Entity's, whether or not it has rules there yet: a rule\n // attached later is then applied, not served past.\n const source = Option.fromUndefinedOr(config.server.entities.get(name))\n const sourceProblems = Option.match(source, {\n onNone: () => [],\n onSome: ({ visible, filter }) => [\n ...(rowRules.has(visible, policy, entity)\n ? []\n : [`${name}'s Source does not apply its Read rules`]),\n ...(memberRules.has(filter, policy, entity)\n ? []\n : [`${name}'s Source does not apply its members' Read rules`]),\n ],\n })\n const queryProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, query]) => {\n const listed = config.server.queries.get(queryName)\n return listed !== undefined &&\n lists(query.Result, name) &&\n !rowRules.has(listed.visible, policy, entity)\n ? [`query ${queryName} lists ${name} without its Read rules`]\n : []\n },\n )\n // A row the reader may see with a member it may not still answers a\n // filter or an order on that member: `cost < $max`, halved twenty\n // times, reads the cost the row came back without.\n const bodyProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, { body }]) => {\n if (body === undefined || body.entity.name !== name) return []\n const { predicate, order } = Query.dependencies(body)\n return [\n ...hiddenOf(attachment, predicate).map(\n member =>\n `query ${queryName} filters ${name} by ${member}, which has a Read rule`,\n ),\n ...hiddenOf(attachment, order).map(\n member => `query ${queryName} orders ${name} by ${member}, which has a Read rule`,\n ),\n ]\n },\n )\n const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => {\n if (source.writes === undefined || source.writes.entity !== name) return []\n if (!writeRules.has(source.writes.writer, policy, entity)) {\n return [`write ${mutation} writes ${name} without its write rules`]\n }\n const { write, writer } = source.writes\n // Unmet or written, Conflict or not, answers for a member its writer may not read.\n const when = Option.match(write.when, {\n onNone: () => [],\n onSome: body => hiddenOf(attachment, Query.dependencies(body).predicate),\n })\n const computed = write.assignments.flatMap(assignment =>\n hiddenOf(attachment, dependenciesOf(assignment.expr).fields).map(\n member =>\n `write ${mutation} computes ${name}'s ${assignment.field.key} from its ${member}, which has a Read rule`,\n ),\n )\n const expected = write.expect?.field.key\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n return [\n ...when.map(\n member =>\n `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`,\n ),\n ...computed,\n ...(expected !== undefined && readRuled(attachment, expected)\n ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`]\n : []),\n ...(expected !== undefined &&\n pin !== undefined &&\n Option.exists(pin, field => field !== expected)\n ? [\n `write ${mutation} expects ${name}'s ${expected}, but its writer pins ${Option.getOrThrow(pin)}`,\n ]\n : []),\n ]\n })\n // A shared field goes to every live subscriber as written: no rule may tell them apart.\n const shared = Option.match(source, {\n onNone: () => [],\n onSome: source => [...(source.shared ?? [])],\n })\n const sharedProblems = [\n ...(shared.length > 0 && readRowsRuled(attachment)\n ? [`${name}'s Source shares ${shared.join(', ')}, but its rows have a Read rule`]\n : []),\n ...shared.flatMap(member => {\n const own = readRuled(attachment, member)\n ? [`${name}'s Source shares ${member}, which has a Read rule`]\n : []\n if (!Object.hasOwn(entity.relations, member)) return own\n const target = entity.relations[member]!.target().name\n if (!byName.has(target))\n return [\n ...own,\n `${name}'s Source shares ${member}, whose ${target} is not validated`,\n ]\n return rowsRuled(byName.get(target))\n ? [...own, `${name}'s Source shares ${member}, whose rows have a Read rule`]\n : own\n }),\n ]\n // A rule calling an operator the policy's table does not run would fail when\n // asked, so the server does not start with one (expr-operations-DESIGN §5.6).\n const operatorProblems = attachedRules(attachment).flatMap(rule =>\n rule._tag === 'RowGuard'\n ? Query.unsupported(rule.query, supported, policy.operators).map(\n missing =>\n `${name}'s ${rule.name} calls ${missing}, which the policy does not run`,\n )\n : [],\n )\n // A live Source of its own streams whatever it reads: nothing here can check it.\n const liveProblems = config.server.live.has(name)\n ? [`${name} has a live Source of its own; serve its changes through a live hub`]\n : []\n return [\n ...sourceProblems,\n ...queryProblems,\n ...bodyProblems,\n ...writeProblems,\n ...sharedProblems,\n ...operatorProblems,\n ...liveProblems,\n ]\n },\n }),\n )\n const problems = [...undeclared, ...entityProblems]\n if (problems.length > 0) {\n throw new Error(`[foldkit-guard] GuardServer.validate: ${problems.join('; ')}`)\n }\n // Not refused yet: a writer given no revision is how every writer was made before it.\n const unpinnedWrites = [...config.server.mutations].flatMap(([mutation, source]) => {\n const writer = source.writes?.writer\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n return pin !== undefined && Option.isNone(pin) ? [mutation] : []\n })\n if (unpinnedWrites.length > 0) {\n console.warn(\n `[foldkit-guard] GuardServer.validate: ${unpinnedWrites.join(', ')} ${unpinnedWrites.length === 1 ? 'writes' : 'write'} through a GuardServer.writer with no revision, so a change between its check and its write is not seen; pass { revision }`,\n )\n }\n },\n}\n\n/** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */\nconst asksMay = (entity: AnyEntity, fields: ReadonlyArray<string>) =>\n fields.includes('may') && Object.hasOwn(entity.derived, 'may')\n\n/** How one principal's `may` is answered: the fields its rules read, and the answer over a row. */\ninterface MayPlan {\n readonly fields: ReadonlyArray<string>\n readonly answer: (values: Readonly<Record<string, unknown>>) => MayAnswer\n}\n\n/** The interactions a row answers `may` for: `Update`, `Delete`, and each one the set named. */\nconst builtInRow = new Set(['Read', 'Create', 'Update', 'Delete'])\n\n/**\n * `may` for `principal`: each row interaction's rule, each member's own\n * `Update`, each relation's `Link` and `Unlink`, decided once and held over\n * each row as a write's check would hold them over it as it is.\n */\nconst mayOf = <User, R>(\n entity: AnyEntity,\n policy: Policy<User, R>,\n principal: Option.Option<User>,\n): Effect.Effect<MayPlan, never, R> => {\n const attachment = attached(entity)\n const named = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ row }) => Object.keys(row).filter(interaction => !builtInRow.has(interaction)),\n })\n const ruledMembers = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ members }) => Object.keys(members),\n })\n const ruledRelations = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ relations }) => Object.keys(relations),\n })\n return Effect.map(\n Effect.all([\n Effect.forEach(['Update', 'Delete', ...named], interaction =>\n Effect.map(\n // A named one was attached as an `InteractionKey`; its key is the name.\n policy.writable(entity, principal, interaction as InteractionKey),\n rule => [interaction, rule] as const,\n ),\n ),\n policy.writeMembers(entity, principal, ruledMembers, 'Update'),\n Effect.forEach(ruledRelations, relation =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Link'),\n policy.linkable(entity, principal, relation, 'Unlink'),\n ]),\n ([link, unlink]) => ({ relation, link, unlink }),\n ),\n ),\n ]),\n ([rows, members, relations]): MayPlan => {\n const input = policy.inputOf(principal)\n const holds = (condition: Condition, values: Readonly<Record<string, unknown>>) =>\n Condition.holds(condition, values, input, () => false, policy.operators)\n // A relation without a rule for one direction leaves it to the row's Update.\n const allows = (rule: Option.Option<RowRule>, values: Readonly<Record<string, unknown>>) =>\n Option.match(rule, {\n onNone: () => true,\n onSome: ({ condition }) => holds(condition, values),\n })\n const conditions = [\n ...rows.map(([, { condition }]) => condition),\n ...members.map(({ condition }) => condition),\n ...relations.flatMap(({ link, unlink }) =>\n [...Option.toArray(link), ...Option.toArray(unlink)].map(({ condition }) => condition),\n ),\n ]\n return {\n // `id` too, so a row is read when its rules read none of it (an admin's).\n fields: ['id', ...new Set(conditions.flatMap(Condition.members))],\n answer: values => ({\n row: Object.fromEntries(\n rows.map(([interaction, { condition }]) => [interaction, holds(condition, values)]),\n ),\n // Only an `explain`'s sentence is for whoever asked.\n reasons: Object.fromEntries(\n rows.flatMap(([interaction, { condition, deny }]) =>\n holds(condition, values)\n ? []\n : Match.valueTags(deny, {\n Explain: ({ reason }) => [[interaction, reason] as const],\n Forbidden: () => [],\n NotFound: () => [],\n Omit: () => [],\n Redact: () => [],\n }),\n ),\n ),\n members: Object.fromEntries(\n members.map(({ member, condition }) => [member, holds(condition, values)]),\n ),\n relations: Object.fromEntries(\n relations.map(({ relation, link, unlink }) => [\n relation,\n { Link: allows(link, values), Unlink: allows(unlink, values) },\n ]),\n ),\n }),\n }\n },\n )\n}\n\n/** A refused write as the client receives it: the sentence an `explain` gave, or none. */\nconst refused = (deny: Deny) =>\n Match.valueTags(deny, {\n Explain: ({ reason }) => RemoteServer.forbid(reason),\n Forbidden: () => RemoteServer.forbid(),\n NotFound: () => RemoteServer.forbid(),\n Omit: () => RemoteServer.forbid(),\n Redact: () => RemoteServer.forbid(),\n })\n\n/** One row, by id, as `principal` may read it through `source`. */\nconst rowOf = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n) =>\n Effect.map(\n source.read({ ids: [id], fields: [...fields], principal }),\n records => records.find(record => record.id === id)?.values,\n )\n\n/**\n * Row `id` of `fields` as `principal` may see it, through `see`'s `authorize`\n * and `filter` as a Source applies them, and no more than was asked: what an\n * answer shows its writer. None when the row is not there to them.\n */\nconst seenRow = <P, R, RS>(\n see: Pick<EntitySource<P, RS>, 'authorize' | 'filter'>,\n read: (\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n): Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R | RS> =>\n Effect.gen(function* () {\n const allowed = see.authorize === undefined ? fields : see.authorize(principal, [...fields])\n const plan: ReadPlan =\n see.filter === undefined\n ? { fields: allowed, apply: noMembers }\n : yield* see.filter(principal, allowed)\n // The id too: a row asked for nothing else is still there or not.\n const row = yield* read([...new Set(['id', ...plan.fields])])\n return Option.map(row, values => {\n const shown = plan.apply({ id, values }).values\n return Object.fromEntries(\n allowed.filter(field => Object.hasOwn(shown, field)).map(field => [field, shown[field]]),\n )\n })\n })\n\n/** A link's value as a row holds it: the ref's key, or `null` for none. */\nconst linkKey = (link: Option.Option<{ readonly entity: string; readonly id: string }>) =>\n Option.match(link, { onNone: () => null, onSome: ref => `${ref.entity}:${ref.id}` })\n\n/** Whether a query's result is a connection over `entity`. */\nconst lists = (result: unknown, entity: string): boolean =>\n typeof result === 'object' && result !== null && 'entity' in result && result.entity === entity\n"],"mappings":";;;;;;;;;;;;;;;AAkDA,MAAM,aAAa,WAAyB;;AAG5C,MAAM,cAAc,MAAe,UACjC,KAAK,UAAU,IAAI,MAAM,KAAK,UAAU,KAAK;;AAG/C,MAAM,YACJ,YACA,WAC0B,CAC1B,GAAG,IAAI,IAAI,OAAO,KAAI,UAAS,MAAM,GAAG,CAAC,CAAC,QAAO,QAAO,UAAU,YAAY,GAAG,CAAC,CAAC,CACrF;;AAGA,MAAM,uBAAO,IAAI,QAAuC;;AAGxD,MAAM,SAAS,UAAoF;CACjG,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,KAAK;CAClD,MAAM,QAAQ,MAAM,QAAQ,GAAG;CAC/B,OAAO,SAAS,IACZ,OAAO,KAAK,IACZ,OAAO,KAAK;EAAE,QAAQ,MAAM,MAAM,GAAG,KAAK;EAAG,IAAI,MAAM,MAAM,QAAQ,CAAC;CAAE,CAAC;AAC/E;AAEA,MAAa,cAAc;;;;;;;;;;CAUzB,KACE,QACA,WACyC;EAEzC,OAAO,IAAI,SAAS,MAAM,IAAI,EAAE,UAAU;GACxC,IAAI,QAAQ,OAAO,KACjB,MAAM,IAAI,MACR,4DAA4D,IAAI,QAAQ,OAAO,KAC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AAY,SAAS,IAAI,UAAU,WAAW,CAAC,GAAG,MAAM,CAAC;CAC3F,MAAM,OACJ,IAAI,WAAW,KAAA,IACX;EAAE,QAAQ;EAAS,OAAO;CAAU,IACpC,OAAO,IAAI,OAAO,WAAW,OAAO;CAE1C,MAAM,MAAM,OAAO,KAAK,CAAC,mBAAG,IAAI,IAAI,CAAC,MAAM,GAAG,KAAK,MAAM,CAAC,CAAC,CAAC;CAC5D,OAAO,OAAO,IAAI,MAAK,WAAU;EAC/B,MAAM,QAAQ,KAAK,MAAM;GAAE;GAAI;EAAO,CAAC,CAAC,CAAC;EACzC,OAAO,OAAO,YACZ,QAAQ,QAAO,UAAS,OAAO,OAAO,OAAO,KAAK,CAAC,CAAC,CAAC,KAAI,UAAS,CAAC,OAAO,MAAM,MAAM,CAAC,CACzF;CACF,CAAC;AACH,CAAC;;AAGH,MAAM,WAAW,SACf,OAAO,MAAM,MAAM;CAAE,cAAc;CAAM,SAAQ,QAAO,GAAG,IAAI,OAAO,GAAG,IAAI;AAAK,CAAC;;AAGrF,MAAM,SAAS,QAAiB,WAC9B,OAAO,WAAW,YAAY,WAAW,QAAQ,YAAY,UAAU,OAAO,WAAW"}
package/dist/sync.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as PrincipalGuard, S as Policy } from "./attach-BnP9_Uca.mjs";
1
+ import { C as PrincipalGuard, S as Policy } from "./attach-BepaL930.mjs";
2
2
  import { Effect, Option } from "effect";
3
3
  import { AnyEntity } from "foldkit-entity";
4
4
  import { EntitySource } from "foldkit-remote-server";
package/dist/sync.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { d as surfaceOf, r as attached, s as isAnyone, u as restricts } from "./attach-CRCF5XHS.mjs";
2
- import { t as Condition } from "./condition-Bl1UgEpM.mjs";
2
+ import { t as Condition } from "./condition-Dx54lL7v.mjs";
3
3
  import { Effect, Match, Option, Schema } from "effect";
4
4
  // src/sync.ts
5
5
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-guard",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Who may do what, declared once on a Foldkit Plus domain: principal guards implemented on the server, row guards as query expressions.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -61,17 +61,17 @@
61
61
  "LICENSE"
62
62
  ],
63
63
  "dependencies": {
64
- "foldkit-entity": "0.12.0",
65
- "foldkit-metadata": "0.1.0"
64
+ "foldkit-metadata": "0.1.0",
65
+ "foldkit-entity": "0.13.0"
66
66
  },
67
67
  "peerDependencies": {
68
68
  "drizzle-orm": "1.0.0-rc.5",
69
69
  "effect": "^4.0.0",
70
- "foldkit-media": "^0.3.0",
71
- "foldkit-remote": "^0.20.0",
72
- "foldkit-remote-drizzle": "^0.14.0",
73
- "foldkit-remote-server": "^0.17.0",
74
- "foldkit-sync": "^0.12.3"
70
+ "foldkit-media": "^0.3.1",
71
+ "foldkit-remote": "^0.21.0",
72
+ "foldkit-remote-drizzle": "^0.15.0",
73
+ "foldkit-remote-server": "^0.18.0",
74
+ "foldkit-sync": "^0.12.4"
75
75
  },
76
76
  "peerDependenciesMeta": {
77
77
  "drizzle-orm": {
@@ -99,13 +99,13 @@
99
99
  "foldkit": "0.169.0",
100
100
  "tsdown": "^0.23.1",
101
101
  "typescript": "7.0.2",
102
- "foldkit-media": "0.3.0",
103
102
  "foldkit-agent": "0.8.3",
104
- "foldkit-remote": "0.20.0",
105
- "foldkit-remote-drizzle": "0.14.0",
106
- "foldkit-remote-server": "0.17.0",
103
+ "foldkit-media": "0.3.1",
104
+ "foldkit-remote": "0.21.0",
105
+ "foldkit-remote-server": "0.18.0",
107
106
  "foldkit-surface": "0.10.2",
108
- "foldkit-sync": "0.12.3"
107
+ "foldkit-sync": "0.12.4",
108
+ "foldkit-remote-drizzle": "0.15.0"
109
109
  },
110
110
  "scripts": {
111
111
  "build": "tsdown",
@@ -1 +0,0 @@
1
- {"version":3,"file":"attach-BnP9_Uca.d.mts","names":["MemberKeys","_$__attach_js0.Attach","_$__attach_js0.AnyRule","_$__attach_js0.Inherit","_$__attach_js0.All","_$__attach_js0.Redact","_$__attach_js0.Explain","_$__attach_js0.On"],"sources":["../src/condition.ts","../src/may.ts","../src/me.ts","../src/index.ts","../src/attach.ts"],"mappings":";;KAWY;WACG;;WACA;;WACA;WAAsB,OAAO,cAAc;;;;WAE3C;WAA0B;;WAC1B;WAAsB,YAAY,cAAc;;WAChD;WAAqB,YAAY,cAAc;;;cAMxD,MAAG,YAAgB,cAAc,eAAa;;cAY9C,KAAE,YAAgB,cAAc,eAAa;cAWtC;;aAnCQ;;;aACA;;;;;;;;;;EA+CN,QAAA,WAAA,WAAS,QACZ,SAAS,0BAAwB,OAClC,SAAS,0BAAwB,UAC9B,8BAA4B,WAC3B;;;;;;;EAoBU,YAAA,WAAA,WAAS,OAAS,wBAAsB;;EAiB1C,UAAA,WAAA,cAAY;;;UAelB;WACN;WACA,WAAW;WACX,MAAM;;;UAwDA;WACN,WAAW;WACX,MAAM;;;;;;;;cCjKJ,WAAS,OAAA;;;;;;;;;KASV,mBAAmB,UAAU;KAEpCA,aAAW,UAAU,oBAAoB,oBAAoB;cAerD;;;;;;EAMX,SAAM,UAAA,WAAA,QAAA,mBAAA;;;;;;;;;;;;;;;;;;EAON,MAAG,KAAQ,WAAS,mCAAqC;;;;;;EAQzD,SAAM,KACC,WAAS,mCACqB,mBAClC,OAAO;;EAGV,SAAS,UAAU,WAAS,KAAO,WAAS,SAAW,GAAC,QAAUA,aAAW;;EAI7E,UAAU,UAAU,WAAS,KACtB,WAAS,SACL,GAAC,gBACM,yBAAuB;;;;;;;;;;;EAczC,QAAK,QAAW;IACd;eAAU;;IACV,SAAM,KAAQ,SAAS,0BAAwB;;;;cCjFtC;cAEP,UAAQ;;;;;;;;KAYF,WAAW,kBAAkB,IAAI,cAAc;;;;;;;;;;;cAY9C,KAAM,qBAAqB,MAAI;WAE/B,MAAM;WACN,QAAQ,OAAO,MAAM;WACrB;GACV;WAE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,MAAM,KAAK;aACpC,SAAS,UAAU,QAAQ,MAAM,KAAK;;;WAI1C,SAAS,cAAc,QAAQ,MAAM,KAAK;;;UAIpC;WACN,OAAO,cAAc;WACrB,MAAM,OAAO,OAAO;;KAG1B,WAAW,SAAS,eAAe;;UAGvB;WACN;WACA;WACA,KAAK;WACL,SAAS,SAAS,eAAe;WACjC,WAAW,SAAS,eAAe;WACnC,QAAQ,cAAc;;cAoRpB,WAAQ,QAAY,cAAY,OAAO,OAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"condition-Bl1UgEpM.mjs","names":[],"sources":["../src/condition.ts"],"sourcesContent":["/**\n * What an attachment's read rules come to for one principal, once its\n * principal guards are decided: a condition over the row, which an\n * interpreter runs (`evaluate` in memory, SQL in a binding). Principal guards\n * never reach it, so their bodies stay on the server that decided them.\n */\nimport { Effect, Match, Option } from 'effect'\nimport { Query, evaluate, type AnyEntity, type MemoryOperators } from 'foldkit-entity'\nimport { attached, defaultDeny, surfaceOf, type AnyRule, type Deny } from './attach.js'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\nexport type Condition =\n | { readonly _tag: 'Always' }\n | { readonly _tag: 'Never' }\n | { readonly _tag: 'Row'; readonly guard: RowGuard<any, AnyEntity> }\n /** The row its `one` relation points at is readable. */\n | { readonly _tag: 'Inherit'; readonly relation: string }\n | { readonly _tag: 'And'; readonly conditions: ReadonlyArray<Condition> }\n | { readonly _tag: 'Or'; readonly conditions: ReadonlyArray<Condition> }\n\nconst always: Condition = Object.freeze({ _tag: 'Always' })\nconst never: Condition = Object.freeze({ _tag: 'Never' })\n\n/** A conjunction, with what it settles already folded away. */\nconst and = (conditions: ReadonlyArray<Condition>): Condition => {\n const kept: Array<Condition> = []\n for (const condition of conditions) {\n if (condition._tag === 'Never') return never\n if (condition._tag !== 'Always') kept.push(condition)\n }\n if (kept.length === 0) return always\n if (kept.length === 1) return kept[0]!\n return Object.freeze({ _tag: 'And', conditions: Object.freeze(kept) })\n}\n\n/** A disjunction, with what it settles already folded away. */\nconst or = (conditions: ReadonlyArray<Condition>): Condition => {\n const kept: Array<Condition> = []\n for (const condition of conditions) {\n if (condition._tag === 'Always') return always\n if (condition._tag !== 'Never') kept.push(condition)\n }\n if (kept.length === 0) return never\n if (kept.length === 1) return kept[0]!\n return Object.freeze({ _tag: 'Or', conditions: Object.freeze(kept) })\n}\n\nexport const Condition = {\n always,\n never,\n and,\n or,\n\n /**\n * Whether a row's stored values meet `condition`, its row guards read with\n * `input` (the principal's, from `G.inputOf`). `inherit` answers whether the\n * row a relation points at is readable, which only the caller can look up.\n * `operators` runs the guards' primitive operators: the policy's.\n */\n holds: (\n condition: Condition,\n values: Readonly<Record<string, unknown>>,\n input: Readonly<Record<string, unknown>>,\n inherit: (relation: string) => boolean,\n operators: MemoryOperators,\n ): boolean => {\n const holds = (each: Condition): boolean =>\n Match.valueTags(each, {\n Always: () => true,\n Never: () => false,\n Row: ({ guard }) => evaluate(guard.query, input, [values], { operators }).length === 1,\n Inherit: ({ relation }) => inherit(relation),\n And: ({ conditions }) => conditions.every(holds),\n Or: ({ conditions }) => conditions.some(holds),\n })\n return holds(condition)\n },\n\n /**\n * `condition` with every row guard that reads one of `unset`, and every\n * relation of them it follows, refused: a field a create leaves unset\n * matches no guard, `isNull` and `isNotNull` alike, since the create never\n * said what it holds.\n */\n unsetting: (condition: Condition, unset: ReadonlySet<string>): Condition => {\n const kept = (each: Condition): Condition =>\n Match.valueTags(each, {\n Always: () => each,\n Never: () => each,\n Row: ({ guard }) =>\n Query.dependencies(guard.query).predicate.some(field => unset.has(field.key))\n ? never\n : each,\n Inherit: ({ relation }) => (unset.has(relation) ? never : each),\n And: ({ conditions }) => and(conditions.map(kept)),\n Or: ({ conditions }) => or(conditions.map(kept)),\n })\n return kept(condition)\n },\n\n /** The members a condition reads: its row guards' fields, and each relation it follows. */\n members: (condition: Condition): ReadonlyArray<string> => {\n const read = (each: Condition): ReadonlyArray<string> =>\n Match.valueTags(each, {\n Always: () => [],\n Never: () => [],\n Row: ({ guard }) => Query.dependencies(guard.query).predicate.map(field => field.key),\n Inherit: ({ relation }) => [relation],\n And: ({ conditions }) => conditions.flatMap(read),\n Or: ({ conditions }) => conditions.flatMap(read),\n })\n return [...new Set(read(condition))]\n },\n}\n\n/** A member's read rule for one principal: the condition, and what a refusal shows. */\nexport interface MemberRead {\n readonly member: string\n readonly condition: Condition\n readonly deny: Deny\n}\n\n/**\n * Whether a row guard reads the principal's fields. A visitor has none, so\n * passes no guard that does; one over the row alone (`publishedAt` is set)\n * holds for a visitor as for anyone.\n */\nexport const readsPrincipal = (guard: RowGuard<any, AnyEntity>): boolean =>\n Query.dependencies(guard.query).inputs.length > 0\n\n/** Every principal guard the rules name, each once. */\nconst principalGuardsIn = (rules: ReadonlyArray<AnyRule>): ReadonlyArray<PrincipalGuard<any>> => {\n const found = new Map<string, PrincipalGuard<any>>()\n const visit = (rule: AnyRule): void =>\n Match.valueTags(rule, {\n PrincipalGuard: guard => void found.set(guard.name, guard),\n RowGuard: () => {},\n All: ({ rules }) => rules.forEach(visit),\n Inherit: () => {},\n })\n rules.forEach(visit)\n return [...found.values()]\n}\n\n/**\n * Turns `rules` into a condition for one principal. Each principal guard is\n * decided once, however many rules name it; a visitor passes no row guard\n * that reads the principal.\n */\nconst conditionsFor = <R>(\n rules: ReadonlyArray<AnyRule>,\n decide: (guard: PrincipalGuard<any>) => Effect.Effect<boolean, never, R>,\n visitor: boolean,\n): Effect.Effect<(rules: ReadonlyArray<AnyRule>, join: typeof and) => Condition, never, R> =>\n Effect.map(\n Effect.forEach(principalGuardsIn(rules), guard =>\n Effect.map(decide(guard), allowed => [guard.name, allowed] as const),\n ),\n decisions => {\n const allowed = new Map(decisions)\n const conditionOf = (rule: AnyRule): Condition =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => (allowed.get(name) === true ? always : never),\n RowGuard: guard =>\n visitor && readsPrincipal(guard)\n ? never\n : Object.freeze({ _tag: 'Row' as const, guard }),\n All: ({ rules }) => and(rules.map(conditionOf)),\n Inherit: ({ relation }) => Object.freeze({ _tag: 'Inherit' as const, relation }),\n })\n return (rules, join) => join(rules.map(conditionOf))\n },\n )\n\n/** A row's rule for one interaction and principal: the condition, and what a refusal shows. */\nexport interface RowRule {\n readonly condition: Condition\n readonly deny: Deny\n}\n\n/**\n * How a Policy decides one interaction, given the set's principal guards as\n * decided for it.\n */\nexport const deciding = <R>(\n decide: (guard: PrincipalGuard<any>) => Effect.Effect<boolean, never, R>,\n visitor: boolean,\n interaction: string,\n) => ({\n /** Who may do it to which rows of `entity`: `always`, then the row's rules for it. */\n row: (entity: AnyEntity): Effect.Effect<RowRule, never, R> =>\n Option.match(attached(entity), {\n onNone: () =>\n Effect.succeed({ condition: always, deny: defaultDeny(rowTarget(interaction)) }),\n onSome: attachment => {\n const target = rowTarget(interaction)\n const row = surfaceOf(attachment, target)\n const rules = Option.match(row, {\n onNone: (): ReadonlyArray<AnyRule> => [],\n onSome: ({ rules }) => rules,\n })\n // An interaction left without rules falls to the set's default.\n const unguarded = attachment.unguarded === 'allow' ? always : never\n return Effect.map(\n conditionsFor([...attachment.always, ...rules], decide, visitor),\n condition => ({\n condition: and([\n condition(attachment.always, and),\n Option.isSome(row) ? condition(rules, or) : unguarded,\n ]),\n deny: Option.getOrElse(\n Option.flatMap(row, ({ deny }) => deny),\n () => defaultDeny(target),\n ),\n }),\n )\n },\n }),\n\n /**\n * The rule of each of `members` that has one for this interaction. One\n * without follows its row. A relation key's Read is its relation's, decided\n * over the parent row as a member's is.\n */\n members: (\n entity: AnyEntity,\n members: ReadonlyArray<string>,\n ): Effect.Effect<ReadonlyArray<MemberRead>, never, R> =>\n Option.match(attached(entity), {\n onNone: () => Effect.succeed([]),\n onSome: attachment => {\n const surfaces = members.flatMap(member => {\n const target = Object.hasOwn(entity.relations, member)\n ? ({ _tag: 'Relation', relation: member, interaction } as const)\n : ({ _tag: 'Member', member, interaction } as const)\n return Option.match(surfaceOf(attachment, target), {\n onNone: () => [],\n onSome: ({ rules, deny }) => [\n { member, rules, deny: Option.getOrElse(deny, () => defaultDeny(target)) },\n ],\n })\n })\n return Effect.map(\n conditionsFor(\n surfaces.flatMap(({ rules }) => rules),\n decide,\n visitor,\n ),\n condition =>\n surfaces.map(({ member, rules, deny }) => ({\n member,\n condition: condition(rules, or),\n deny,\n })),\n )\n },\n }),\n\n /** A relation's rule for this interaction (`Link`, `Unlink`), when it has one. */\n relation: (\n entity: AnyEntity,\n relation: string,\n ): Effect.Effect<Option.Option<RowRule>, never, R> => {\n const target = { _tag: 'Relation', relation, interaction } as const\n return Option.match(\n Option.flatMap(attached(entity), attachment => surfaceOf(attachment, target)),\n {\n onNone: () => Effect.succeed(Option.none()),\n onSome: ({ rules, deny }) =>\n Effect.map(conditionsFor(rules, decide, visitor), condition =>\n Option.some({\n condition: condition(rules, or),\n deny: Option.getOrElse(deny, () => defaultDeny(target)),\n }),\n ),\n },\n )\n },\n})\n\nconst rowTarget = (interaction: string) => ({ _tag: 'Row', interaction }) as const\n"],"mappings":";;;;;;;;;;AAoBA,MAAM,SAAoB,OAAO,OAAO,EAAE,MAAM,SAAS,CAAC;AAC1D,MAAM,QAAmB,OAAO,OAAO,EAAE,MAAM,QAAQ,CAAC;;AAGxD,MAAM,OAAO,eAAoD;CAC/D,MAAM,OAAyB,CAAC;CAChC,KAAK,MAAM,aAAa,YAAY;EAClC,IAAI,UAAU,SAAS,SAAS,OAAO;EACvC,IAAI,UAAU,SAAS,UAAU,KAAK,KAAK,SAAS;CACtD;CACA,IAAI,KAAK,WAAW,GAAG,OAAO;CAC9B,IAAI,KAAK,WAAW,GAAG,OAAO,KAAK;CACnC,OAAO,OAAO,OAAO;EAAE,MAAM;EAAO,YAAY,OAAO,OAAO,IAAI;CAAE,CAAC;AACvE;;AAGA,MAAM,MAAM,eAAoD;CAC9D,MAAM,OAAyB,CAAC;CAChC,KAAK,MAAM,aAAa,YAAY;EAClC,IAAI,UAAU,SAAS,UAAU,OAAO;EACxC,I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