@appling/codegen-ash 0.1.1 → 0.1.3

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/out/index.js CHANGED
@@ -1,11 +1,17 @@
1
1
  import { interfaceSteps } from './api.js';
2
2
  import { projectionFieldSteps, querySteps } from './application.js';
3
3
  import { actionSteps, jobSteps, machineSteps } from './behavior.js';
4
- import { constant, lastOf, parentOf, validation } from './elixir.js';
4
+ import { elixirString, lastOf, parentOf, withModuledoc } from './elixir.js';
5
5
  import { migrationSteps } from './migrations.js';
6
6
  import { hasPages, navigationSteps, pageSteps } from './pages.js';
7
- import { testSteps } from './tests.js';
8
- import { app, attributeType, calculation, fieldsOf, fileOf, mix, moduleName, patch, relationTarget, storedAttributes, task, typeModule } from './naming.js';
7
+ import { actorAttributeSpecs, actorFieldSteps, actorSteps, constrainRoles, homeAt, homeFields } from './actors.js';
8
+ import { actorCheckSteps, closeResource, enforced, policySteps, policyTask, roleCalculations, roleSteps } from './roles.js';
9
+ import { tenantSteps } from './tenants.js';
10
+ import { check, defaultValue, invariantTests, transitionTests } from './model-tests.js';
11
+ import { policyTests } from './policy-tests.js';
12
+ import { coveredByScenario, scenarioSteps } from './scenario-tests.js';
13
+ import { externalKeySteps, secretPlaceholders } from './vendors.js';
14
+ import { app, attributeType, calculation, fieldPolicyOf, fieldsOf, fileOf, mix, moduleName, patch, relationTarget, leftToCode, task, typeModule } from './naming.js';
9
15
  const extension = {
10
16
  name: '@appling/codegen-ash',
11
17
  test: ['mix', 'test'],
@@ -21,13 +27,14 @@ const extension = {
21
27
  const pages = hasPages(context);
22
28
  const api = has('Interface', i => i.data.protocol === 'rest');
23
29
  const install = [
24
- 'ash', 'ash_postgres', ...(pages ? ['ash_phoenix'] : []), ...(has('Machine') ? ['ash_state_machine'] : []),
30
+ // Ash policies need a SAT solver; simple_sat is pure Elixir, so the project builds without a C compiler.
31
+ 'ash', 'ash_postgres', ...(enforced(context) ? ['simple_sat'] : []), ...(pages ? ['ash_phoenix'] : []), ...(has('Machine') ? ['ash_state_machine'] : []),
25
32
  ...(has('Job', j => !!j.data.schedule) ? ['ash_oban'] : []), ...(pages && api ? ['ash_json_api'] : [])
26
33
  ];
27
34
  return [
28
35
  { kind: 'command', run: ['mix', 'igniter.new', app(context), ...(pages ? ['--with', 'phx.new', '--with-args=--no-install'] : []), '--install', install.join(','), '--yes', '--no-git'], cwd: '..', creates: ['mix.exs', 'lib/'] },
29
36
  ...(api && !pages ? [mix(['igniter.install', 'ash_json_api,bandit'])] : []),
30
- { kind: 'command', run: ['mix', 'ash.codegen', 'initial_resources'], phase: 3 }
37
+ { kind: 'command', run: ['mix', 'ash.codegen', 'initial_resources'], phase: 3, ...secretPlaceholders(context) }
31
38
  ];
32
39
  },
33
40
  steps(node, context) {
@@ -40,15 +47,17 @@ const extension = {
40
47
  case 'Field': return fieldSteps(node, context);
41
48
  case 'Invariant': return [
42
49
  ...(check(node, context) ? [] : [task(`enforce the invariant "${node.data.label}": ${node.props.condition}`)]),
43
- ...testSteps(node, owner(node, context), `invariant ${node.data.label}`, ['holds for valid records', 'rejects violations'], context)
50
+ ...invariantTests(node, context)
44
51
  ];
45
52
  case 'Policy': return [
46
- task(`add an Ash policy to ${parentOf(node.qn)} for ${node.data.operations?.join(', ') ?? 'any action'}: ${node.props.condition}`),
53
+ ...(policySteps(node, context) ?? [policyTask(node)]),
47
54
  ...(context.node(parentOf(node.qn)).kind === 'Entity'
48
- ? testSteps(node, owner(node, context), lastOf(node.qn), ['allows permitted actors', 'denies other actors'], context)
55
+ ? policyTests(node, context)
49
56
  : [])
50
57
  ];
51
- case 'Transition': return transitionTests(node, context);
58
+ // A scenario that runs the transition's action replaces its guessed tests.
59
+ case 'Transition': return coveredByScenario(node.qn, context) ? [] : transitionTests(node, context);
60
+ case 'Scenario': return scenarioSteps(node, context);
52
61
  case 'Action': return actionSteps(node, context);
53
62
  case 'Machine': return machineSteps(node, context);
54
63
  case 'Job': return jobSteps(node, context);
@@ -60,14 +69,20 @@ const extension = {
60
69
  case 'Messages': return [];
61
70
  case 'Flow': return [task(`guide people through ${(node.data.pages ?? []).map(p => p.split('.').pop()).join(', ')} for the use case ${String(node.data.usecase).split('.').pop()}, for example with links between the LiveViews`)];
62
71
  case 'Event': return [task(`publish ${lastOf(node.qn)} with an Ash notifier, for example Ash.Notifier.PubSub`)];
63
- case 'External': return [task(`implement ${lastOf(node.qn)} as a client module or generic actions`)];
72
+ case 'External': return [leftToCode(`implement ${lastOf(node.qn)} as a client module or generic actions`)];
73
+ case 'ExternalKey': return externalKeySteps(node, context);
64
74
  case 'UseCase': return [task(`implement ${lastOf(node.qn)} as a Reactor or a generic action`)];
65
- case 'Role': return [task(`model the role ${lastOf(node.qn)} on the actor resource`)];
75
+ case 'Role': return roleSteps(node, context);
76
+ case 'Actor': return [...actorSteps(node, context, patchResource), ...actorCheckSteps(node, context)];
77
+ case 'Tenant': return tenantSteps(node, context);
66
78
  case 'Param':
67
79
  case 'ErrorDecl':
68
80
  case 'SetEffect':
69
81
  case 'CreateEffect':
70
82
  case 'EmitEffect':
83
+ case 'ForEffect':
84
+ case 'UpdateEffect':
85
+ case 'DeleteEffect':
71
86
  case 'Projection':
72
87
  case 'ExternalOperation':
73
88
  case 'Endpoint':
@@ -77,25 +92,18 @@ const extension = {
77
92
  }
78
93
  };
79
94
  export default extension;
80
- function owner(node, context) {
81
- return context.node(parentOf(node.qn));
82
- }
83
- function transitionTests(transition, context) {
84
- const machine = owner(transition, context);
85
- const entity = owner(context.node(machine.data.field), context);
86
- const title = `transition ${transition.data.from.join(', ')} -> ${transition.data.to}`;
87
- return testSteps(transition, entity, title, ['moves from allowed states', 'refuses other states'], context);
88
- }
89
95
  function entitySteps(entity, context) {
90
96
  const attributes = fieldsOf(entity, context).filter(f => !f.data.derived && !relationTarget(f, context));
91
97
  const specs = attributes.map(f => {
92
98
  const type = f.data.type;
93
99
  return [lastOf(f.qn), attributeType(type, context), ...(type.many ? ['array'] : []), ...(type.optional ? [] : ['required']), 'public'].join(':');
94
100
  });
101
+ // The fields of the actors bound to the entity, and their roles, which are not public, so nobody assigns roles to themselves through the API.
102
+ specs.push(...actorAttributeSpecs(entity, context));
95
103
  return [
96
- mix(['ash.gen.resource', typeModule(entity, context), '--domain', moduleName(entity.module, context),
97
- '--default-actions', 'read,create,update,destroy', '--uuid-primary-key', 'id', ...(specs.length ? ['--attribute', specs.join(',')] : []),
98
- '--extend', 'postgres', '--timestamps']),
104
+ { ...mix(['ash.gen.resource', typeModule(entity, context), '--domain', moduleName(entity.module, context),
105
+ '--default-actions', 'read,create,update,destroy', '--uuid-primary-key', 'id', ...(specs.length ? ['--attribute', specs.join(',')] : []),
106
+ '--extend', 'postgres', '--timestamps']), creates: [fileOf(entity, context)] },
99
107
  patch(fileOf(entity, context), existing => patchResource(existing, entity, context))
100
108
  ];
101
109
  }
@@ -105,6 +113,8 @@ function fieldSteps(field, context) {
105
113
  return field.data.derived || field.data.default ? [task(`add ${lastOf(field.qn)} to the embedded resource: ${field.props.derived ?? field.props.default}`)] : [];
106
114
  if (owner.kind === 'Event')
107
115
  return [];
116
+ if (owner.kind === 'Actor')
117
+ return actorFieldSteps(field, context);
108
118
  if (owner.kind !== 'Entity')
109
119
  return undefined;
110
120
  const type = field.data.type;
@@ -116,49 +126,47 @@ function fieldSteps(field, context) {
116
126
  return [{ ...mix(['ash.gen.resource', typeModule(owner, context), '--relationship', spec]), phase: 1 }];
117
127
  }
118
128
  const tasks = [];
119
- if (field.data.derived && !calculation(field, context))
120
- tasks.push(task(`add the calculation ${lastOf(field.qn)} = ${field.props.derived}`));
129
+ if (field.data.derived && !calculation(field, context)) {
130
+ // Until the calculation exists, its field policy has nothing to name; the task carries the policy's condition.
131
+ const policy = fieldPolicyOf(field, context);
132
+ tasks.push(task(`add the calculation ${lastOf(field.qn)} = ${field.props.derived}${policy ? `, public?: true, and add it to the field policy of ${policy.qn}: ${policy.props.condition}` : ''}`));
133
+ }
121
134
  if (field.data.default && defaultValue(field, context) === undefined)
122
135
  tasks.push(task(`set the default of ${lastOf(field.qn)} to ${field.props.default}`));
123
136
  return tasks;
124
137
  }
125
- /** Adds defaults, identities, calculations and validations to the resource `ash.gen.resource` created. */
138
+ /** Adds defaults, identities, calculations and validations to the resource `ash.gen.resource` created, for an entity or an actor. */
126
139
  function patchResource(text, entity, context) {
127
- const fields = fieldsOf(entity, context);
140
+ const home = homeAt(entity, context);
141
+ const fields = home?.resource ? homeFields(home, context) : fieldsOf(entity, context);
142
+ if (home?.resource)
143
+ text = constrainRoles(text, home);
128
144
  for (const field of fields) {
129
145
  const value = defaultValue(field, context);
130
146
  if (value !== undefined)
131
147
  text = text.replace(new RegExp(`(\\n([ \\t]*)attribute :${lastOf(field.qn)}, [^\\n]* do\\n)`), `$1$2 default ${value}\n`);
148
+ if (typeof field.data.does === 'string')
149
+ text = text.replace(new RegExp(`(\\n([ \\t]*)attribute :${lastOf(field.qn)}, [^\\n]* do\\n)`), (_, head, indent) => `${head}${indent} description ${elixirString(field.data.does)}\n`);
132
150
  }
151
+ text = withModuledoc(text, entity);
133
152
  const blocks = [
134
153
  block('identities', fields.filter(f => (f.data.modifiers ?? []).includes('unique')).map(f => `identity :unique_${lastOf(f.qn)}, [:${lastOf(f.qn)}]`)),
135
- block('calculations', fields.flatMap(f => calculation(f, context) ?? [])),
154
+ block('calculations', [...fields.flatMap(f => calculation(f, context) ?? []), ...roleCalculations(entity, context)]),
136
155
  block('validations', context.children(entity.qn).filter(n => n.kind === 'Invariant').flatMap(n => {
137
156
  const rule = check(n, context);
138
157
  return rule ? [`validate ${rule}, message: ${JSON.stringify(n.data.label)}`] : [];
139
158
  }))
140
159
  ].filter(Boolean).join('');
141
- return blocks ? text.replace(/\nend\n?$/, `\n${blocks}end\n`) : text;
160
+ return closeResource(blocks ? text.replace(/\nend\n?$/, `\n${blocks}end\n`) : text, entity, context);
142
161
  }
143
162
  function block(name, lines) {
144
163
  return lines.length ? `\n ${name} do\n${lines.map(l => ` ${l}\n`).join('')} end\n` : '';
145
164
  }
146
- function check(invariant, context) {
147
- return validation(invariant.data.condition, storedAttributes(context.node(parentOf(invariant.qn)), context), context.node);
148
- }
149
- function defaultValue(field, context) {
150
- const expr = field.data.default;
151
- if (!expr)
152
- return undefined;
153
- if (expr.$type === 'NameExpr' && expr.name === 'now' && !expr.target)
154
- return '&DateTime.utc_now/0';
155
- return constant(expr, context.node);
156
- }
157
165
  function embedded(node, context) {
158
166
  const attributes = fieldsOf(node, context).filter(f => !f.data.derived).map(f => {
159
167
  const type = f.data.type;
160
168
  const elixirType = type.many ? `{:array, ${attributeType(type, context, true)}}` : attributeType(type, context, true);
161
169
  return ` attribute :${lastOf(f.qn)}, ${elixirType}, allow_nil?: ${type.optional ? 'true' : 'false'}, public?: true\n`;
162
170
  });
163
- return `defmodule ${typeModule(node, context)} do\n use Ash.Resource, data_layer: :embedded\n\n attributes do\n${attributes.join('')} end\nend\n`;
171
+ return withModuledoc(`defmodule ${typeModule(node, context)} do\n use Ash.Resource, data_layer: :embedded\n\n attributes do\n${attributes.join('')} end\nend\n`, node);
164
172
  }
@@ -0,0 +1,47 @@
1
+ import type { MapContext, Step } from '@appling/codegen';
2
+ import { Simulator, type GraphNode, type Record as SimRecord, type TypeData, type Value } from '@appling/model';
3
+ /** A value a test may give an attribute, as Elixir and as the simulator sees it (UNKNOWN when the test must not rely on it). */
4
+ interface Sample {
5
+ elixir: string;
6
+ value: Value;
7
+ }
8
+ /** One simulator per graph, used to prove what a test may rely on. */
9
+ export declare function simulator(context: MapContext): Simulator;
10
+ /** The invariant as one of Ash's builtin validations, or undefined when it does not translate. */
11
+ export declare function check(invariant: GraphNode, context: MapContext): string | undefined;
12
+ /** A field's default as an Elixir attribute default, or undefined when it has none that translates. */
13
+ export declare function defaultValue(field: GraphNode, context: MapContext): string | undefined;
14
+ /**
15
+ * The tests of an invariant enforced as a validation. They build a changeset for the resource's `create`
16
+ * action, which runs the validations without a database: the sample input must be valid, and an input whose
17
+ * one attribute the simulator proves to break this invariant (and no other validation) must not. Without a
18
+ * sample input or without such an attribute value, a case stays a registry task.
19
+ */
20
+ export declare function invariantTests(invariant: GraphNode, context: MapContext): Step[];
21
+ /**
22
+ * The tests of a transition. They build a changeset for the update action AshStateMachine runs it with, on a
23
+ * record struct built from the sample input, which runs the transition check without a database: from an
24
+ * allowed state the changeset must be valid, from a state no transition of that action leaves it must carry
25
+ * AshStateMachine's NoMatchingTransition error. The first case needs the simulator to prove the action's
26
+ * preconditions and guards true and the entity's translated invariants true after the transition, with no
27
+ * effect changing a field they read. Without a single target state for the action, a sample input or sample
28
+ * values for its required arguments, a case stays a registry task.
29
+ */
30
+ export declare function transitionTests(transition: GraphNode, context: MapContext): Step[];
31
+ /**
32
+ * The tests of an action's preconditions. Each builds a changeset for the action's update action on a record
33
+ * struct from the sample input, in the first state the action's transitions leave, which runs the precondition
34
+ * validations without a database. A case gets a body when the precondition translates to a validation, the
35
+ * simulator proves the earlier preconditions true and this one false on that record, and every attribute the
36
+ * condition compares is set (Ash's `compare` and `attribute_*` validations pass on nil); the changeset must
37
+ * then be invalid with the precondition's message. Without a sample input or sample values for the action's
38
+ * required arguments every case stays a registry task.
39
+ */
40
+ export declare function preconditionTests(action: GraphNode, entity: GraphNode, context: MapContext): Step[];
41
+ export declare function enforcedInvariants(entity: GraphNode, context: MapContext): GraphNode[];
42
+ export declare function holds(invariant: GraphNode, context: MapContext, self: SimRecord): boolean;
43
+ /** A sample value of a required attribute without a default; undefined when there is none, such as for a file. */
44
+ export declare function sample(name: string, type: TypeData, context: MapContext): Sample | undefined;
45
+ /** The qualified names the expression compares; a name only tested by `has()` is left out, its nil is meant. */
46
+ export declare function targets(expr: unknown, found?: Set<string>): Set<string>;
47
+ export {};
@@ -0,0 +1,320 @@
1
+ import { Simulator, UNKNOWN } from '@appling/model';
2
+ import { homeAt } from './actors.js';
3
+ import { constant, lastOf, parentOf, validation } from './elixir.js';
4
+ import { fieldsOf, relationTarget, snake, storedAttributes, typeModule } from './naming.js';
5
+ import { testSteps } from './tests.js';
6
+ const simulators = new WeakMap();
7
+ /** One simulator per graph, used to prove what a test may rely on. */
8
+ export function simulator(context) {
9
+ let found = simulators.get(context.graph);
10
+ if (!found)
11
+ simulators.set(context.graph, found = new Simulator(context.graph));
12
+ return found;
13
+ }
14
+ /** The invariant as one of Ash's builtin validations, or undefined when it does not translate. */
15
+ export function check(invariant, context) {
16
+ return validation(invariant.data.condition, storedAttributes(context.node(parentOf(invariant.qn)), context), context.node);
17
+ }
18
+ /** A field's default as an Elixir attribute default, or undefined when it has none that translates. */
19
+ export function defaultValue(field, context) {
20
+ const expr = field.data.default;
21
+ if (!expr)
22
+ return undefined;
23
+ if (expr.$type === 'NameExpr' && expr.name === 'now' && !expr.target)
24
+ return '&DateTime.utc_now/0';
25
+ return constant(expr, context.node);
26
+ }
27
+ /**
28
+ * The tests of an invariant enforced as a validation. They build a changeset for the resource's `create`
29
+ * action, which runs the validations without a database: the sample input must be valid, and an input whose
30
+ * one attribute the simulator proves to break this invariant (and no other validation) must not. Without a
31
+ * sample input or without such an attribute value, a case stays a registry task.
32
+ */
33
+ export function invariantTests(invariant, context) {
34
+ const entity = context.node(parentOf(invariant.qn));
35
+ const title = `invariant ${invariant.data.label}`;
36
+ const cases = ['holds for valid records', 'rejects violations'];
37
+ const input = check(invariant, context) ? sampleInput(entity, context) : undefined;
38
+ if (!input)
39
+ return testSteps(invariant, entity, title, cases, context);
40
+ const resource = typeModule(entity, context);
41
+ const changeset = (attributes) => `changeset = Ash.Changeset.for_create(${resource}, :create, %{${attributes.map(([n, v]) => `${n}: ${v}`).join(', ')}}, authorize?: false)`;
42
+ const violation = violating(invariant, entity, input.record, context);
43
+ const tests = [
44
+ { name: cases[0], body: [changeset(input.attributes), 'assert changeset.valid?'] },
45
+ {
46
+ name: cases[1],
47
+ body: violation && [changeset([...input.attributes.filter(([n]) => n !== violation[0]), violation]), 'refute changeset.valid?']
48
+ }
49
+ ];
50
+ return testSteps(invariant, entity, title, tests, context);
51
+ }
52
+ /**
53
+ * An input for the `create` action that every translated invariant accepts: a sample value for every required
54
+ * stored attribute without a default. Undefined when the model does not say enough, such as a required
55
+ * relationship, a value type, a file, a default that does not translate, or an actor resource.
56
+ */
57
+ function sampleInput(entity, context) {
58
+ if (homeAt(entity, context))
59
+ return undefined;
60
+ const record = { $type: entity.qn };
61
+ const attributes = [];
62
+ const defaults = [];
63
+ for (const field of fieldsOf(entity, context)) {
64
+ const type = field.data.type;
65
+ const name = lastOf(field.qn);
66
+ if (field.data.derived)
67
+ continue;
68
+ if (relationTarget(field, context)) {
69
+ if (!type.optional && !type.many)
70
+ return undefined;
71
+ continue;
72
+ }
73
+ if (type.many) {
74
+ record[name] = [];
75
+ continue;
76
+ }
77
+ if (field.data.default) {
78
+ const value = defaultValue(field, context);
79
+ if (value === undefined)
80
+ return undefined;
81
+ defaults.push([name, value === '&DateTime.utc_now/0' ? 'DateTime.utc_now()' : value]);
82
+ record[name] = simulator(context).evaluate(field.data.default, { self: record });
83
+ continue;
84
+ }
85
+ if (type.optional) {
86
+ record[name] = null;
87
+ continue;
88
+ }
89
+ const value = sample(name, type, context);
90
+ if (!value)
91
+ return undefined;
92
+ attributes.push([name, value.elixir]);
93
+ record[name] = value.value;
94
+ }
95
+ if (!enforcedInvariants(entity, context).every(i => holds(i, context, record)))
96
+ return undefined;
97
+ return { attributes, defaults, record };
98
+ }
99
+ /**
100
+ * An attribute and a value for which the invariant is false and every other translated invariant true. The
101
+ * attributes the condition compares must stay non nil, since Ash's `compare` and `attribute_*` validations
102
+ * pass on nil.
103
+ */
104
+ function violating(invariant, entity, record, context) {
105
+ const condition = invariant.data.condition;
106
+ const read = targets(condition);
107
+ const fields = fieldsOf(entity, context).filter(f => read.has(f.qn) && !f.data.derived && !relationTarget(f, context) && !f.data.type.many);
108
+ const others = enforcedInvariants(entity, context).filter(i => i.qn !== invariant.qn);
109
+ for (const field of fields) {
110
+ const name = lastOf(field.qn);
111
+ for (const candidate of candidates(field.data.type, context)) {
112
+ const row = { ...record, [name]: candidate.value };
113
+ if (fields.some(f => row[lastOf(f.qn)] === null || row[lastOf(f.qn)] === undefined))
114
+ continue;
115
+ if (simulator(context).evaluate(condition, { self: row }) !== false)
116
+ continue;
117
+ if (!others.every(i => holds(i, context, row)))
118
+ continue;
119
+ return [name, candidate.elixir];
120
+ }
121
+ }
122
+ return undefined;
123
+ }
124
+ /**
125
+ * The tests of a transition. They build a changeset for the update action AshStateMachine runs it with, on a
126
+ * record struct built from the sample input, which runs the transition check without a database: from an
127
+ * allowed state the changeset must be valid, from a state no transition of that action leaves it must carry
128
+ * AshStateMachine's NoMatchingTransition error. The first case needs the simulator to prove the action's
129
+ * preconditions and guards true and the entity's translated invariants true after the transition, with no
130
+ * effect changing a field they read. Without a single target state for the action, a sample input or sample
131
+ * values for its required arguments, a case stays a registry task.
132
+ */
133
+ export function transitionTests(transition, context) {
134
+ const machine = context.node(parentOf(transition.qn));
135
+ const stateField = context.node(machine.data.field);
136
+ const entity = context.node(parentOf(stateField.qn));
137
+ const title = `transition ${transition.data.from.join(', ')} -> ${transition.data.to}`;
138
+ const cases = ['moves from allowed states', 'refuses other states'];
139
+ const plan = transitionPlan(transition, entity, context);
140
+ const input = plan && sampleInput(entity, context);
141
+ if (!plan || !input)
142
+ return testSteps(transition, entity, title, cases, context);
143
+ const state = lastOf(stateField.qn);
144
+ const resource = typeModule(entity, context);
145
+ const pairs = (values) => values.map(([n, v]) => `${n}: ${v}`).join(', ');
146
+ const changeset = (from) => [
147
+ `record = struct!(${resource}, %{${pairs([...input.attributes, ...input.defaults.filter(([n]) => n !== state), [state, `:${from}`]])}})`,
148
+ `changeset = Ash.Changeset.for_update(record, :${plan.action}, %{${pairs(plan.arguments)}}, authorize?: false)`
149
+ ];
150
+ const literals = context.children(stateField.data.type.decl).map(l => lastOf(l.qn));
151
+ const allowed = new Set(plan.transitions.flatMap(t => t.data.from));
152
+ const other = literals.find(l => !allowed.has(l));
153
+ const from = transition.data.from.find(f => movesFrom(f, transition, plan, entity, input.record, state, context));
154
+ const tests = [
155
+ { name: cases[0], body: from ? [...changeset(from), 'assert changeset.valid?'] : undefined },
156
+ {
157
+ name: cases[1],
158
+ body: other ? [...changeset(other), 'refute changeset.valid?', 'assert Enum.any?(changeset.errors, &match?(%AshStateMachine.Errors.NoMatchingTransition{}, &1))'] : undefined
159
+ }
160
+ ];
161
+ return testSteps(transition, entity, title, tests, context);
162
+ }
163
+ /**
164
+ * The tests of an action's preconditions. Each builds a changeset for the action's update action on a record
165
+ * struct from the sample input, in the first state the action's transitions leave, which runs the precondition
166
+ * validations without a database. A case gets a body when the precondition translates to a validation, the
167
+ * simulator proves the earlier preconditions true and this one false on that record, and every attribute the
168
+ * condition compares is set (Ash's `compare` and `attribute_*` validations pass on nil); the changeset must
169
+ * then be invalid with the precondition's message. Without a sample input or sample values for the action's
170
+ * required arguments every case stays a registry task.
171
+ */
172
+ export function preconditionTests(action, entity, context) {
173
+ const preconditions = (action.data.preconditions ?? []);
174
+ const texts = action.props.preconditions;
175
+ const title = `action ${snake(lastOf(action.qn))} precondition`;
176
+ const cases = preconditions.map((_, i) => `${i + 1} is enforced`);
177
+ const args = requiredArguments(action, context);
178
+ const input = args && sampleInput(entity, context);
179
+ if (!args || !input)
180
+ return testSteps(action, entity, title, cases, context);
181
+ const transition = context.graph.nodes.find(n => n.kind === 'Transition' && n.data.action === action.qn);
182
+ const stateField = transition && context.node(context.node(parentOf(transition.qn)).data.field);
183
+ const state = stateField && parentOf(stateField.qn) === entity.qn ? lastOf(stateField.qn) : undefined;
184
+ const from = state ? transition.data.from[0] : undefined;
185
+ const record = state ? { ...input.record, [state]: from } : input.record;
186
+ const values = [...input.attributes, ...input.defaults.filter(([n]) => n !== state), ...(state ? [[state, `:${from}`]] : [])];
187
+ const resource = typeModule(entity, context);
188
+ const pairs = (list) => list.map(([n, v]) => `${n}: ${v}`).join(', ');
189
+ const stored = storedAttributes(entity, context);
190
+ const tests = preconditions.map((precondition, i) => {
191
+ const earlier = preconditions.slice(0, i).every(p => simulator(context).evaluate(p.condition, { self: record }) === true);
192
+ const fails = simulator(context).evaluate(precondition.condition, { self: record }) === false;
193
+ const set = [...targets(precondition.condition)].every(qn => record[lastOf(qn)] !== null && record[lastOf(qn)] !== undefined);
194
+ if (!earlier || !fails || !set || !validation(precondition.condition, stored, context.node))
195
+ return { name: cases[i] };
196
+ const message = precondition.error ? lastOf(precondition.error) : texts[i];
197
+ return {
198
+ name: cases[i],
199
+ body: [
200
+ `record = struct!(${resource}, %{${pairs(values)}})`,
201
+ `changeset = Ash.Changeset.for_update(record, :${snake(lastOf(action.qn))}, %{${pairs(args)}}, authorize?: false)`,
202
+ 'refute changeset.valid?',
203
+ `assert Enum.any?(changeset.errors, &(Map.get(&1, :message) == ${JSON.stringify(message)}))`
204
+ ]
205
+ };
206
+ });
207
+ return testSteps(action, entity, title, tests, context);
208
+ }
209
+ /** Sample values for an action's required arguments, or undefined when one has none. */
210
+ function requiredArguments(action, context) {
211
+ const args = [];
212
+ for (const param of context.children(action.qn).filter(c => c.kind === 'Param')) {
213
+ const type = param.data.type;
214
+ if (type.optional)
215
+ continue;
216
+ const value = type.many ? { elixir: '[]' } : sample(lastOf(param.qn), type, context);
217
+ if (!value)
218
+ return undefined;
219
+ args.push([lastOf(param.qn), value.elixir]);
220
+ }
221
+ return args;
222
+ }
223
+ /** The update action the generator writes for the transition, or undefined when it writes none with transition_state. */
224
+ function transitionPlan(transition, entity, context) {
225
+ const action = transition.data.action;
226
+ const event = transition.data.event;
227
+ if (!action && !event)
228
+ return undefined;
229
+ // An action's update action is written once for every transition it drives, an event's per machine.
230
+ const transitions = action
231
+ ? context.graph.nodes.filter(n => n.kind === 'Transition' && n.data.action === action)
232
+ : context.children(parentOf(transition.qn)).filter(n => n.kind === 'Transition' && n.data.event === event);
233
+ if (new Set(transitions.map(t => t.data.to)).size !== 1)
234
+ return undefined;
235
+ if (!action)
236
+ return { action: snake(lastOf(event)), transitions, arguments: [] };
237
+ const node = context.node(action);
238
+ if (node.data.entity !== entity.qn)
239
+ return undefined;
240
+ const args = requiredArguments(node, context);
241
+ if (!args)
242
+ return undefined;
243
+ return { action: snake(lastOf(action)), transitions, node, arguments: args };
244
+ }
245
+ /** Whether the simulator proves the action's changeset valid on the sample record in the given state. */
246
+ function movesFrom(from, transition, plan, entity, record, state, context) {
247
+ const before = { ...record, [state]: from };
248
+ const conditions = [
249
+ ...(plan.node?.data.preconditions ?? []).map(p => p.condition),
250
+ ...plan.transitions.filter(t => t.data.guard).map(t => t.data.guard)
251
+ ];
252
+ if (!conditions.every(c => simulator(context).evaluate(c, { self: before }) === true))
253
+ return false;
254
+ const invariants = enforcedInvariants(entity, context);
255
+ const read = new Set(invariants.flatMap(i => [...targets(i.data.condition)]));
256
+ const effects = [...(plan.node ? context.children(plan.node.qn) : []), ...context.children(transition.qn)].filter(c => c.kind === 'SetEffect');
257
+ if (effects.some(e => read.has(e.data.field)))
258
+ return false;
259
+ const after = { ...before, [state]: transition.data.to };
260
+ return invariants.every(i => holds(i, context, after));
261
+ }
262
+ export function enforcedInvariants(entity, context) {
263
+ return context.children(entity.qn).filter(n => n.kind === 'Invariant' && check(n, context));
264
+ }
265
+ export function holds(invariant, context, self) {
266
+ return simulator(context).evaluate(invariant.data.condition, { self }) === true;
267
+ }
268
+ /** A sample value of a required attribute without a default; undefined when there is none, such as for a file. */
269
+ export function sample(name, type, context) {
270
+ if (type.decl) {
271
+ const decl = context.node(type.decl);
272
+ const first = decl.kind === 'Enum' ? context.children(decl.qn)[0] : undefined;
273
+ return first && { elixir: `:${lastOf(first.qn)}`, value: lastOf(first.qn) };
274
+ }
275
+ switch (type.primitive) {
276
+ case 'String':
277
+ case 'Text': return { elixir: JSON.stringify(`${name}-1`), value: UNKNOWN };
278
+ case 'Int': return { elixir: '1', value: 1 };
279
+ case 'Decimal':
280
+ case 'Money': return { elixir: 'Decimal.new("1")', value: 1 };
281
+ case 'Bool': return { elixir: 'false', value: false };
282
+ case 'Date': return { elixir: 'Date.utc_today()', value: UNKNOWN };
283
+ case 'DateTime': return { elixir: 'DateTime.utc_now()', value: UNKNOWN };
284
+ case 'Duration': return { elixir: 'Duration.new!(hour: 1)', value: 3_600_000 };
285
+ case 'Uuid': return { elixir: 'Ash.UUID.generate()', value: UNKNOWN };
286
+ }
287
+ return undefined;
288
+ }
289
+ /** The values tried on an attribute: a few numbers, both booleans, every enum literal; none for other types. */
290
+ function candidates(type, context) {
291
+ if (type.decl) {
292
+ const decl = context.node(type.decl);
293
+ return decl?.kind === 'Enum' ? context.children(decl.qn).map(l => ({ elixir: `:${lastOf(l.qn)}`, value: lastOf(l.qn) })) : [];
294
+ }
295
+ const numbers = [-1, 0, 1_000_000];
296
+ switch (type.primitive) {
297
+ case 'Int': return numbers.map(n => ({ elixir: String(n), value: n }));
298
+ case 'Decimal':
299
+ case 'Money': return numbers.map(n => ({ elixir: `Decimal.new("${n}")`, value: n }));
300
+ case 'Bool': return [{ elixir: 'true', value: true }, { elixir: 'false', value: false }];
301
+ }
302
+ return [];
303
+ }
304
+ /** The qualified names the expression compares; a name only tested by `has()` is left out, its nil is meant. */
305
+ export function targets(expr, found = new Set()) {
306
+ if (Array.isArray(expr)) {
307
+ for (const item of expr)
308
+ targets(item, found);
309
+ }
310
+ else if (expr && typeof expr === 'object') {
311
+ const node = expr;
312
+ if (node.$type === 'NameExpr' && node.call && node.name === 'has')
313
+ return found;
314
+ if (node.$type === 'NameExpr' && typeof node.target === 'string')
315
+ found.add(node.target);
316
+ for (const value of Object.values(expr))
317
+ targets(value, found);
318
+ }
319
+ return found;
320
+ }
package/out/naming.d.ts CHANGED
@@ -12,10 +12,17 @@ export declare function pascal(name: string): string;
12
12
  export declare function snake(name: string): string;
13
13
  export declare function mix(args: string[]): CommandStep;
14
14
  export declare function task(what: string): Step;
15
+ /** A registry task the model leaves to the code by design (`docs/concept.md` section 8): it does not lower the coverage. */
16
+ export declare function leftToCode(what: string): Step;
15
17
  export declare function children(node: GraphNode, context: MapContext, kind?: string): GraphNode[];
16
18
  /** The attributes of a resource that are stored columns, not calculations or relationships. */
17
19
  export declare function storedAttributes(entity: GraphNode, context: MapContext): Set<string>;
18
20
  /** Patches a generated module after every resource and relationship exists, so expressions may follow relationships. */
19
21
  export declare function patch(file: string, write: (existing: string) => string): Step;
20
- /** The calculation for a derived field, or undefined when Ash expressions cannot say it. */
22
+ /**
23
+ * The calculation for a derived field, or undefined when Ash expressions cannot say it. It is private unless a field
24
+ * policy names it: Ash field policies take only public attributes and calculations.
25
+ */
21
26
  export declare function calculation(field: GraphNode, context: MapContext): string | undefined;
27
+ /** The first policy that guards reads of a field (`policy read fields ...`), if any. */
28
+ export declare function fieldPolicyOf(field: GraphNode, context: MapContext): GraphNode | undefined;
package/out/naming.js CHANGED
@@ -40,6 +40,10 @@ export function mix(args) {
40
40
  export function task(what) {
41
41
  return { kind: 'task', what };
42
42
  }
43
+ /** A registry task the model leaves to the code by design (`docs/concept.md` section 8): it does not lower the coverage. */
44
+ export function leftToCode(what) {
45
+ return { kind: 'task', what, leftToCode: true };
46
+ }
43
47
  export function children(node, context, kind) {
44
48
  return context.children(node.qn).filter(c => !kind || c.kind === kind);
45
49
  }
@@ -51,9 +55,17 @@ export function storedAttributes(entity, context) {
51
55
  export function patch(file, write) {
52
56
  return { kind: 'template', file, write: existing => write(existing), phase: 2 };
53
57
  }
54
- /** The calculation for a derived field, or undefined when Ash expressions cannot say it. */
58
+ /**
59
+ * The calculation for a derived field, or undefined when Ash expressions cannot say it. It is private unless a field
60
+ * policy names it: Ash field policies take only public attributes and calculations.
61
+ */
55
62
  export function calculation(field, context) {
56
63
  const type = field.data.type;
57
64
  const body = field.data.derived && !type.many && ashExpr(field.data.derived, context.node);
58
- return body ? `calculate :${lastOf(field.qn)}, ${attributeType(type, context, true)}, expr(${body})` : undefined;
65
+ return body ? `calculate :${lastOf(field.qn)}, ${attributeType(type, context, true)}, expr(${body})${fieldPolicyOf(field, context) ? ', public?: true' : ''}` : undefined;
66
+ }
67
+ /** The first policy that guards reads of a field (`policy read fields ...`), if any. */
68
+ export function fieldPolicyOf(field, context) {
69
+ return context.graph.nodes.find(p => p.kind === 'Policy' && (p.data.fields ?? []).includes(field.qn)
70
+ && (!(p.data.operations ?? []).length || (p.data.operations ?? []).includes('read')));
59
71
  }
package/out/pages.js CHANGED
@@ -20,6 +20,7 @@ export function pageSteps(page, context) {
20
20
  const assigns = [];
21
21
  const markup = [];
22
22
  const events = new Map();
23
+ let params = false;
23
24
  page.data.components.forEach((component, i) => {
24
25
  const id = `${component.$type === 'ListView' ? 'list' : component.$type === 'DetailView' ? 'record' : 'form'}_${i + 1}`;
25
26
  const actions = (component.actions ?? []).map(qn => context.node(qn)).filter(action => {
@@ -36,7 +37,14 @@ export function pageSteps(page, context) {
36
37
  const entity = context.node(query.data.entity);
37
38
  const columns = columnsOf(component.projection, component.picks, context, tasks);
38
39
  const load = columns.filter(c => c.load).map(c => `:${c.field}`);
39
- const read = `Ash.read!(${typeModule(entity, context)}, action: :${snake(lastOf(query.qn))}${load.length ? `, load: [${load.join(', ')}]` : ''}${query.data.pageSize ? `, page: [limit: ${query.data.pageSize}]` : ''})`;
40
+ const options = `${load.length ? `, load: [${load.join(', ')}]` : ''}${query.data.pageSize ? `, page: [limit: ${query.data.pageSize}]` : ''}`;
41
+ // The query's inputs come from the page's parameters, the route and the query string.
42
+ const inputs = children(query, context, 'Param').map(p => JSON.stringify(lastOf(p.qn)));
43
+ if (inputs.length)
44
+ params = true;
45
+ const read = inputs.length
46
+ ? `Ash.read!(Ash.Query.for_read(${typeModule(entity, context)}, :${snake(lastOf(query.qn))}, Map.take(socket.assigns.params, [${inputs.join(', ')}]))${options})`
47
+ : `Ash.read!(${typeModule(entity, context)}, action: :${snake(lastOf(query.qn))}${options})`;
40
48
  assigns.push(`|> assign(:${id}, ${query.data.pageSize ? `${read}.results` : read})`);
41
49
  markup.push(`<.table id="${id.replace('_', '-')}" rows={@${id}}>`, ...columns.map(c => ` <:col :let={row} label=${JSON.stringify(c.label)}>{to_string(row.${c.field})}</:col>`), ...(actions.length ? [` <:action :let={row}>${buttons('row')}</:action>`] : []), '</.table>');
42
50
  }
@@ -77,8 +85,8 @@ export function pageSteps(page, context) {
77
85
  ` use ${web(context)}, :live_view`,
78
86
  '',
79
87
  ' @impl true',
80
- ` def mount(${byId ? '%{"id" => id}' : '_params'}, _session, socket) do`,
81
- ` {:ok, socket |> assign(:page_title, ${JSON.stringify(title(lastOf(page.qn)))})${byId ? ' |> assign(:id, id)' : ''} |> load()}`,
88
+ ` def mount(${params ? 'params' : byId ? '%{"id" => id}' : '_params'}, _session, socket) do`,
89
+ ` {:ok, socket |> assign(:page_title, ${JSON.stringify(title(lastOf(page.qn)))})${params ? ' |> assign(:params, params)' : ''}${byId ? ` |> assign(:id, ${params ? 'params["id"]' : 'id'})` : ''} |> load()}`,
82
90
  ' end',
83
91
  '',
84
92
  ' defp load(socket) do',