@appling/codegen-ash 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +7 -3
  3. package/out/actors.js +3 -9
  4. package/out/api.js +10 -11
  5. package/out/application.js +10 -11
  6. package/out/behavior.js +22 -31
  7. package/out/elixir.d.ts +3 -1
  8. package/out/elixir.js +9 -4
  9. package/out/index.js +17 -16
  10. package/out/migrations.js +5 -5
  11. package/out/naming.d.ts +2 -0
  12. package/out/naming.js +5 -0
  13. package/out/pages.js +19 -63
  14. package/out/roles.js +9 -36
  15. package/out/scenario-tests.js +6 -19
  16. package/out/tests.js +3 -5
  17. package/out/vendors.js +6 -21
  18. package/package.json +7 -6
  19. package/templates/access/actor-check.ex.njk +6 -0
  20. package/templates/access/actor-struct.ex.njk +9 -0
  21. package/templates/access/check.ex.njk +14 -0
  22. package/templates/access/oban-bypass.ex.njk +4 -0
  23. package/templates/access/policy.ex.njk +19 -0
  24. package/templates/access/role-check.ex.njk +15 -0
  25. package/templates/api/router.ex.njk +4 -0
  26. package/templates/api/routes.ex.njk +7 -0
  27. package/templates/application/query.ex.njk +28 -0
  28. package/templates/behavior/action.ex.njk +23 -0
  29. package/templates/behavior/state-machine.ex.njk +4 -0
  30. package/templates/behavior/transitions.ex.njk +4 -0
  31. package/templates/behavior/trigger-read.ex.njk +4 -0
  32. package/templates/behavior/trigger.ex.njk +10 -0
  33. package/templates/config/env-key.njk +4 -0
  34. package/templates/config/env.example.njk +2 -0
  35. package/templates/config/runtime-key.exs.njk +7 -0
  36. package/templates/config/runtime.exs.njk +2 -0
  37. package/templates/migrations/migration.exs.njk +7 -0
  38. package/templates/migrations/statement.exs.njk +12 -0
  39. package/templates/pages/live.ex.njk +92 -0
  40. package/templates/resources/embedded.ex.njk +18 -0
  41. package/templates/resources/sections.ex.njk +31 -0
  42. package/templates/tests/cases.exs.njk +16 -0
  43. package/templates/tests/module.exs.njk +6 -0
  44. package/templates/tests/scenario.exs.njk +14 -0
  45. package/templates/tests/scenarios.exs.njk +14 -0
package/out/roles.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { homeAt, homeFields, homeOf, homes, rolesOf } from './actors.js';
2
2
  import { ashExpr, isActor, lastOf, parentOf } from './elixir.js';
3
- import { calculation, fileOf, moduleName, patch, snake, storedAttributes, task } from './naming.js';
3
+ import { calculation, fileOf, moduleName, patch, sectionLines, snake, storedAttributes, task } from './naming.js';
4
4
  import { addAuthorizer, addToSection } from './resource.js';
5
5
  const ACTION_TYPES = { read: ':read', create: ':create', update: ':update', delete: ':destroy' };
6
6
  /**
@@ -12,23 +12,11 @@ export function roleSteps(role, context) {
12
12
  const name = lastOf(role.qn);
13
13
  const carriers = homes(context).filter(h => rolesOf(h).includes(role.qn));
14
14
  const clauses = carriers.map(home => ({ home, clause: roleClause(role, home, context) }));
15
- const lines = clauses.flatMap(({ home, clause }) => {
16
- if (clause === 'never' || clause === 'unknown')
17
- return [];
18
- const uses = clause.calculation !== undefined || clause.checks.length > 0;
19
- const holds = [`:${snake(name)} in (actor.roles || [])`, ...clause.checks.map(c => `${c}.match?(actor, context, [])`), ...(clause.calculation ? [`actor.${snake(name)}?`] : [])];
20
- return [
21
- ` def match?(%${home.module}{} = actor, ${uses ? 'context' : '_context'}, _opts) do`,
22
- ...(clause.calculation ? [` actor = Ash.load!(actor, :${snake(name)}?, authorize?: false, tenant: context.subject.tenant)`] : []),
23
- ` ${holds.join(' and ')}`,
24
- ' end',
25
- ''
26
- ];
27
- });
15
+ const matching = clauses.flatMap(({ home, clause }) => clause === 'never' || clause === 'unknown' ? [] : [{ module: home.module, checks: clause.checks, calculation: clause.calculation }]);
28
16
  const unknown = clauses.filter(c => c.clause === 'unknown').map(c => c.home.module);
29
17
  return [
30
18
  // Phase 2: the clauses match the actor resources' structs, which exist only once every resource is generated.
31
- { kind: 'template', file: checkFile(role, context), write: () => checkModuleCode(checkModule(role, context), `actor is ${name}`, lines), phase: 2 },
19
+ { kind: 'template', file: checkFile(role, context), write: () => `${context.render('access/role-check.ex.njk', { module: checkModule(role, context), description: `actor is ${name}`, role: snake(name), clauses: matching })}\n`, phase: 2 },
32
20
  ...(unknown.length ? [task(`check the condition of ${name} for ${unknown.join(', ')} in ${checkModule(role, context)}: ${role.props.condition}`)] : [])
33
21
  ];
34
22
  }
@@ -40,8 +28,8 @@ export function actorCheckSteps(actor, context) {
40
28
  if (home.actors.length > 1) {
41
29
  return [task(`tell ${lastOf(actor.qn)} apart from ${home.actors.filter(a => a !== actor).map(a => lastOf(a.qn)).join(', ')} on ${home.module} for actor.is(${lastOf(actor.qn)})`)];
42
30
  }
43
- const lines = [` def match?(%${home.module}{}, _context, _opts), do: true`, ''];
44
- return [{ kind: 'template', file: checkFile(actor, context), write: () => checkModuleCode(checkModule(actor, context), `actor is ${lastOf(actor.qn)}`, lines), phase: 2 }];
31
+ const data = { module: checkModule(actor, context), description: `actor is ${lastOf(actor.qn)}`, actor: home.module };
32
+ return [{ kind: 'template', file: checkFile(actor, context), write: () => `${context.render('access/actor-check.ex.njk', data)}\n`, phase: 2 }];
45
33
  }
46
34
  /** The calculations of an actor resource that hold the role conditions, such as `calculate :operator?, :boolean, expr(active)`. */
47
35
  export function roleCalculations(node, context) {
@@ -90,12 +78,12 @@ export function policySteps(policy, context) {
90
78
  if (!target)
91
79
  return undefined;
92
80
  const checks = checkLines(policy.data.condition, context, fields.length > 0);
93
- const lines = [`${target.header} do`, ...(checks ?? ['forbid_if always()']).map(c => ` ${c}`), 'end'];
81
+ const lines = (otherFields) => sectionLines(context, 'access/policy.ex.njk', { header: target.header, checks: checks ?? [], otherFields });
94
82
  return [
95
83
  patch(fileOf(target.entity, context), existing => {
96
84
  const withPolicy = fields.length
97
- ? addToSection(existing, 'field_policies', existing.includes('\n field_policies do\n') ? lines : [...lines, '', 'field_policy :* do', ' authorize_if always()', 'end'])
98
- : addToSection(existing, 'policies', lines);
85
+ ? addToSection(existing, 'field_policies', lines(!existing.includes('\n field_policies do\n')))
86
+ : addToSection(existing, 'policies', lines(false));
99
87
  return addAuthorizer(withPolicy);
100
88
  }),
101
89
  ...(checks ? [] : [policyTask(policy)]),
@@ -120,7 +108,7 @@ export function closeResource(text, node, context) {
120
108
  const target = policyTarget(context.node(parentOf(p.qn)), (p.data.operations ?? []), (p.data.fields ?? []), context);
121
109
  return target?.entity.qn === node.qn && target.header.startsWith('policy ');
122
110
  });
123
- return addAuthorizer(guarded ? text : addToSection(text, 'policies', ['policy always() do', ' forbid_if always()', 'end']));
111
+ return addAuthorizer(guarded ? text : addToSection(text, 'policies', sectionLines(context, 'access/policy.ex.njk', { header: 'policy always()', checks: [], otherFields: false })));
124
112
  }
125
113
  function policyTarget(owner, operations, fields, context) {
126
114
  if (owner.kind === 'Entity' && fields.length) {
@@ -209,21 +197,6 @@ function checkModule(node, context) {
209
197
  function checkFile(node, context) {
210
198
  return ['lib', ...fileOf(node, context).split('/').slice(1, -1), 'checks', `${snake(lastOf(node.qn))}.ex`].join('/');
211
199
  }
212
- function checkModuleCode(module, description, clauses) {
213
- return [
214
- `defmodule ${module} do`,
215
- ' use Ash.Policy.SimpleCheck',
216
- '',
217
- ' @impl true',
218
- ` def describe(_opts), do: ${JSON.stringify(description)}`,
219
- '',
220
- ' @impl true',
221
- ...clauses,
222
- ' def match?(_actor, _context, _opts), do: false',
223
- 'end',
224
- ''
225
- ].join('\n');
226
- }
227
200
  /** The role or actor of `actor.is(X)`, or undefined for any other expression. */
228
201
  export function isTarget(expr, context) {
229
202
  const target = expr.$type === 'MemberExpr' && expr.call && expr.member === 'is' && isActor(expr.receiver) ? expr.args?.[0]?.target : undefined;
@@ -35,28 +35,15 @@ export function scenarioSteps(scenario, context) {
35
35
  throw error;
36
36
  why = error.message;
37
37
  }
38
- const does = typeof scenario.data.describe === 'string' && scenario.data.describe.trim() ? ` # ${scenario.data.describe.trim().replace(/\s*\n\s*/g, ' ')}\n` : '';
39
- const test = body
40
- ? `${does} test ${JSON.stringify(title)} do\n${body.map(l => ` ${l}\n`).join('')} end\n`
41
- : `${does} @tag skip: ${JSON.stringify(`registry task: ${scenario.qn}`)}\n test ${JSON.stringify(title)}\n`;
42
- const repo = `${pascal(app(context))}.Repo`;
38
+ const data = {
39
+ module: `${moduleName(scenario.module, context)}.ScenariosTest`, repo: `${pascal(app(context))}.Repo`, title, qn: scenario.qn, body,
40
+ describe: typeof scenario.data.describe === 'string' ? scenario.data.describe.trim().replace(/\s*\n\s*/g, ' ') : ''
41
+ };
43
42
  return [
44
43
  {
45
44
  kind: 'template', file, write: existing => existing
46
- ? existing.replace(/end\n?$/, `\n${test}end\n`)
47
- : [
48
- `defmodule ${moduleName(scenario.module, context)}.ScenariosTest do`,
49
- ' use ExUnit.Case, async: false',
50
- '',
51
- ' setup do',
52
- ` pid = Ecto.Adapters.SQL.Sandbox.start_owner!(${repo}, shared: true)`,
53
- ' on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)',
54
- ' :ok',
55
- ' end',
56
- '',
57
- `${test}end`,
58
- ''
59
- ].join('\n')
45
+ ? existing.replace(/end\n?$/, `\n${context.render('tests/scenario.exs.njk', data)}\nend\n`)
46
+ : `${context.render('tests/scenarios.exs.njk', data)}\n`
60
47
  },
61
48
  ...(body ? [] : [task(`write the test "${title}" in ${file}: ${why}`)])
62
49
  ];
package/out/tests.js CHANGED
@@ -8,15 +8,13 @@ export function testSteps(node, resource, title, cases, context) {
8
8
  const module = `${typeModule(resource, context)}Test`;
9
9
  const file = ['test', app(context), ...resource.module.split('.').map(snake), `${snake(lastOf(resource.qn))}_test.exs`].join('/');
10
10
  const all = cases.map(c => typeof c === 'string' ? { name: c } : c);
11
- const tests = all.map(c => c.body
12
- ? ` test ${JSON.stringify(`${title} ${c.name}`)} do\n${c.body.map(l => ` ${l}\n`).join('')} end\n`
13
- : ` @tag skip: ${JSON.stringify(`registry task: ${node.qn}`)}\n test ${JSON.stringify(`${title} ${c.name}`)}\n`).join('\n');
11
+ const data = { module, title, qn: node.qn, cases: all };
14
12
  const missing = all.filter(c => !c.body);
15
13
  return [
16
14
  {
17
15
  kind: 'template', file, write: existing => existing
18
- ? existing.replace(/end\n?$/, `\n${tests}end\n`)
19
- : `defmodule ${module} do\n use ExUnit.Case, async: true\n\n${tests}end\n`
16
+ ? existing.replace(/end\n?$/, `\n${context.render('tests/cases.exs.njk', data)}\nend\n`)
17
+ : `${context.render('tests/module.exs.njk', data)}\n`
20
18
  },
21
19
  ...(missing.length ? [task(`write the tests "${title}" in ${file}${missing.length < all.length ? ` (${missing.map(c => `"${title} ${c.name}"`).join(', ')})` : ''}`)] : [])
22
20
  ];
package/out/vendors.js CHANGED
@@ -14,11 +14,12 @@ function externalOf(key) {
14
14
  */
15
15
  export function externalKeySteps(key, context) {
16
16
  const name = envName(key);
17
- const line = `config :${app(context)}, ${moduleName(key.module, context)}.${externalOf(key)}, ${lastOf(key.qn)}: ${elixirRead(name, key.data.type, key.data.kind === 'secret')}`;
17
+ const type = key.data.type.primitive;
18
+ const line = context.render('config/runtime-key.exs.njk', { app: app(context), module: `${moduleName(key.module, context)}.${externalOf(key)}`, key: lastOf(key.qn), env: name, type, secret: key.data.kind === 'secret' });
18
19
  return [
19
20
  {
20
21
  kind: 'template', phase: 2, file: 'config/runtime.exs', write: existing => {
21
- const text = existing ?? 'import Config\n';
22
+ const text = existing ?? `${context.render('config/runtime.exs.njk', {})}\n`;
22
23
  return text.includes(line) ? text : `${text.trimEnd()}\n\n${line}\n`;
23
24
  }
24
25
  },
@@ -26,29 +27,13 @@ export function externalKeySteps(key, context) {
26
27
  kind: 'template', phase: 2, file: '.env.example', write: existing => {
27
28
  if (existing?.split('\n').includes(`${name}=`))
28
29
  return existing;
29
- const head = existing ?? '# The settings and secrets of the vendors this app needs. Copy to .env and fill in; never commit values.\n';
30
- const about = `# ${key.data.kind} of ${externalOf(key)}${key.data.describe ? `: ${String(key.data.describe).replace(/\s+/g, ' ').trim()}` : ''}`;
31
- return `${head.trimEnd()}\n\n${about}\n${name}=\n`;
30
+ const head = existing ?? context.render('config/env.example.njk', {});
31
+ const about = context.render('config/env-key.njk', { kind: key.data.kind, external: externalOf(key), describe: key.data.describe ? String(key.data.describe).replace(/\s+/g, ' ').trim() : '', env: name });
32
+ return `${head.trimEnd()}\n\n${about}\n`;
32
33
  }
33
34
  }
34
35
  ];
35
36
  }
36
- function elixirRead(name, type, required) {
37
- if (required) {
38
- const fetch = `System.fetch_env!(${JSON.stringify(name)})`;
39
- switch (type.primitive) {
40
- case 'Int': return `${fetch} |> String.to_integer()`;
41
- case 'Bool': return `${fetch} in ~w(1 true yes)`;
42
- default: return fetch;
43
- }
44
- }
45
- const get = `System.get_env(${JSON.stringify(name)})`;
46
- switch (type.primitive) {
47
- case 'Int': return `${get} |> then(&(&1 && String.to_integer(&1)))`;
48
- case 'Bool': return `${get} in ~w(1 true yes)`;
49
- default: return get;
50
- }
51
- }
52
37
  /**
53
38
  * Placeholder values for every secret, for the generator's own commands that load the settings
54
39
  * (which stop without them). Empty when the model has no secrets.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@appling/codegen-ash",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "Appling code generation extension for Ash",
5
5
  "homepage": "https://www.appling.tools/docs/",
6
6
  "repository": {
@@ -16,18 +16,19 @@
16
16
  }
17
17
  },
18
18
  "files": [
19
- "out"
19
+ "out",
20
+ "templates"
20
21
  ],
21
22
  "dependencies": {
22
- "@appling/model": "0.1.5"
23
+ "@appling/model": "0.1.6"
23
24
  },
24
25
  "peerDependencies": {
25
- "@appling/codegen": "0.2.1"
26
+ "@appling/codegen": "0.2.2"
26
27
  },
27
28
  "devDependencies": {
28
- "@appling/codegen": "0.2.1",
29
29
  "@types/node": "^24.19.2",
30
- "typescript": "7.0.2"
30
+ "typescript": "7.0.2",
31
+ "@appling/codegen": "0.2.2"
31
32
  },
32
33
  "license": "MIT",
33
34
  "publishConfig": {
@@ -0,0 +1,6 @@
1
+ {# The check of an actor that `actor.is(Actor)` names: it matches every record of the actor's resource or struct. -#}
2
+ {% extends "access/check.ex.njk" %}
3
+ {% block clauses %}
4
+ def match?(%{{ actor }}{}, _context, _opts), do: true
5
+
6
+ {% endblock %}
@@ -0,0 +1,9 @@
1
+ {# A system or service actor without `is`: a struct whose roles default to the roles it declares. In lib/<app>/<module>/<actor>.ex. -#}
2
+ defmodule {{ module }} do
3
+ {% block moduledoc %}
4
+ @moduledoc "The {{ kind }} actor {{ name }}. Pass %{{ module }}{} as the actor."
5
+ {% endblock %}
6
+ {% block struct %}
7
+ defstruct [{% for key in keys %}{{ key.name }}: {{ key.value }}, {% endfor %}roles: [{{ roles | join(", ") }}]]
8
+ {% endblock %}
9
+ end
@@ -0,0 +1,14 @@
1
+ {# An Ash.Policy.SimpleCheck that `actor.is(...)` names: a role or an actor. In lib/<app>/<module>/checks/<name>.ex. -#}
2
+ defmodule {{ module }} do
3
+ use Ash.Policy.SimpleCheck
4
+
5
+ {% block describe %}
6
+ @impl true
7
+ def describe(_opts), do: {{ description | dump }}
8
+ {% endblock %}
9
+
10
+ @impl true
11
+ {% block clauses %}
12
+ {% endblock %}
13
+ def match?(_actor, _context, _opts), do: false
14
+ end
@@ -0,0 +1,4 @@
1
+ {# Jobs run as the system, as in the model: AshOban's scheduler and worker pass the policies of the resource. First in its `policies`. -#}
2
+ bypass AshOban.Checks.AshObanInteraction do
3
+ authorize_if always()
4
+ end
@@ -0,0 +1,19 @@
1
+ {# A policy in the `policies` or `field_policies` section of a resource. A condition that does not translate forbids until
2
+ it is written. The first field policy of a resource comes with `field_policy :*`, which keeps every other field readable. -#}
3
+ {% block policy %}
4
+ {{ header }} do
5
+ {% for check in checks %}
6
+ {{ check }}
7
+ {% else %}
8
+ forbid_if always()
9
+ {% endfor %}
10
+ end
11
+ {% endblock %}
12
+ {% block other_fields %}
13
+ {% if otherFields %}
14
+
15
+ field_policy :* do
16
+ authorize_if always()
17
+ end
18
+ {% endif %}
19
+ {% endblock %}
@@ -0,0 +1,15 @@
1
+ {# The check of a role: one clause per actor record that carries the role. The record has the role in its `roles`, the
2
+ roles the condition names hold, and the rest of the condition holds as the calculation `:<role>?` of the actor resource. -#}
3
+ {% extends "access/check.ex.njk" %}
4
+ {% block clauses %}
5
+ {% for c in clauses %}
6
+ def match?(%{{ c.module }}{} = actor, {{ "context" if (c.calculation or c.checks.length) else "_context" }}, _opts) do
7
+ {% if c.calculation %}
8
+ actor = Ash.load!(actor, :{{ role }}?, authorize?: false, tenant: context.subject.tenant)
9
+ {% endif %}
10
+ :{{ role }} in (actor.roles || []){% for check in c.checks %} and {{ check }}.match?(actor, context, []){% endfor %}{% if c.calculation %} and actor.{{ role }}?{% endif %}
11
+
12
+ end
13
+
14
+ {% endfor %}
15
+ {% endblock %}
@@ -0,0 +1,4 @@
1
+ {# The JSON:API router of the REST interfaces, which Bandit serves without Phoenix. In lib/<app>/api_router.ex. -#}
2
+ defmodule {{ module }} do
3
+ use AshJsonApi.Router, domains: [{{ domain }}], open_api: "/open_api"
4
+ end
@@ -0,0 +1,7 @@
1
+ {# The endpoints of a REST interface on one resource, in `json_api` > `routes` of the domain: queries as index, actions as patch routes, each described by the interface's `describe` text and annotation. -#}
2
+ base_route "/", {{ resource }} do
3
+ {% for r in routes %}
4
+ {{ r.verb }} :{{ r.action }}, route: {{ r.path | dump }}{% if r.fields.length %}, default_fields: [{% for f in r.fields %}:{{ f }}{{ ", " if not loop.last }}{% endfor %}]{% endif %}{% if description %}, description: {{ description }}{% endif %}
5
+
6
+ {% endfor %}
7
+ end
@@ -0,0 +1,28 @@
1
+ {# A query: a read action, described by its `describe` text and annotation, in the `actions` section of its entity's resource with its inputs as arguments, filter, sort and pagination. -#}
2
+ read :{{ name }} do
3
+ {% block description %}
4
+ {% if description %}
5
+ description {{ description }}
6
+ {% endif %}
7
+ {% endblock %}
8
+ {% block arguments %}
9
+ {% for a in arguments %}
10
+ argument :{{ a.name }}, {{ a.type }}, allow_nil?: {{ "true" if a.optional else "false" }}
11
+ {% endfor %}
12
+ {% endblock %}
13
+ {% block filter %}
14
+ {% if filter %}
15
+ filter expr({{ filter }})
16
+ {% endif %}
17
+ {% endblock %}
18
+ {% block sort %}
19
+ {% if sorts.length %}
20
+ prepare build(sort: [{% for s in sorts %}{{ s.field }}: :{{ s.direction }}{{ ", " if not loop.last }}{% endfor %}])
21
+ {% endif %}
22
+ {% endblock %}
23
+ {% block pagination %}
24
+ {% if pageSize %}
25
+ pagination offset?: true, default_limit: {{ pageSize }}, required?: false
26
+ {% endif %}
27
+ {% endblock %}
28
+ end
@@ -0,0 +1,23 @@
1
+ {# An action on an entity, or the action of an event's transitions: an update (or destroy) action in the `actions`
2
+ section of its resource with its inputs as arguments, preconditions and guards as validations, effects as changes. -#}
3
+ {{ type }} :{{ name }} do
4
+ require_atomic? false
5
+ {% block arguments %}
6
+ {% for a in arguments %}
7
+ argument :{{ a.name }}, {{ a.type }}, allow_nil?: {{ "true" if a.optional else "false" }}
8
+ {% endfor %}
9
+ {% endblock %}
10
+ {% block validations %}
11
+ {% for v in validations %}
12
+ validate {{ v.rule }}, message: {{ v.message | dump }}
13
+ {% endfor %}
14
+ {% endblock %}
15
+ {% block changes %}
16
+ {% for change in changes %}
17
+ change {{ change }}
18
+ {% endfor %}
19
+ {% if state %}
20
+ change transition_state(:{{ state }})
21
+ {% endif %}
22
+ {% endblock %}
23
+ end
@@ -0,0 +1,4 @@
1
+ {# The settings of a machine in the `state_machine` section of the resource of its state field. -#}
2
+ initial_states [:{{ initial }}]
3
+ default_initial_state :{{ initial }}
4
+ state_attribute :{{ field }}
@@ -0,0 +1,4 @@
1
+ {# A machine's transitions in `state_machine` > `transitions`, each run by the update action of its action or event. -#}
2
+ {% for t in transitions %}
3
+ transition :{{ t.action }}, from: [{% for s in t.from %}:{{ s }}{{ ", " if not loop.last }}{% endfor %}], to: :{{ t.to }}
4
+ {% endfor %}
@@ -0,0 +1,4 @@
1
+ {# The read action a job's trigger reads its rows with, in the `actions` section. -#}
2
+ read :{{ name }}_targets do
3
+ pagination keyset?: true, required?: false
4
+ end
@@ -0,0 +1,10 @@
1
+ {# A scheduled job: an AshOban trigger in `oban` > `triggers` that runs the action for every row the condition matches. -#}
2
+ trigger :{{ name }} do
3
+ action :{{ action }}
4
+ read_action :{{ name }}_targets
5
+ queue :{{ queue }}
6
+ where expr({{ where }})
7
+ scheduler_cron {{ schedule | dump }}
8
+ worker_module_name {{ module }}.AshOban.Worker.{{ job }}
9
+ scheduler_module_name {{ module }}.AshOban.Scheduler.{{ job }}
10
+ end
@@ -0,0 +1,4 @@
1
+ {# A setting or secret of an external in .env.example, to fill in. -#}
2
+ # {{ kind }} of {{ external }}{% if describe %}: {{ describe }}{% endif %}
3
+
4
+ {{ env }}=
@@ -0,0 +1,2 @@
1
+ {# The head of .env.example. -#}
2
+ # The settings and secrets of the vendors this app needs. Copy to .env and fill in; never commit values.
@@ -0,0 +1,7 @@
1
+ {# A setting or secret of an external, read from the environment in config/runtime.exs. A missing setting is nil (false for
2
+ a Bool); a missing secret stops the app at startup. -#}
3
+ config :{{ app }}, {{ module }}, {{ key }}: {{ "System.fetch_env!" if secret else "System.get_env" }}({{ env | dump }})
4
+ {%- if type == "Int" and secret %} |> String.to_integer()
5
+ {%- elif type == "Int" %} |> then(&(&1 && String.to_integer(&1)))
6
+ {%- elif type == "Bool" %} in ~w(1 true yes)
7
+ {%- endif %}
@@ -0,0 +1,2 @@
1
+ {# The head of config/runtime.exs, which reads the settings and secrets of the vendors from the environment. -#}
2
+ import Config
@@ -0,0 +1,7 @@
1
+ {# The Ecto migration of one migration block of the model. In priv/repo/migrations/<stamp>_appling_<block>.exs. -#}
2
+ defmodule {{ module }} do
3
+ use Ecto.Migration
4
+
5
+ def change do
6
+ end
7
+ end
@@ -0,0 +1,12 @@
1
+ {# One migration step on a column, in the `change` of the block's Ecto migration: rename, retype or remove. -#}
2
+ {% if kind == "rename" %}
3
+ rename table(:{{ table }}), :{{ column }}, to: :{{ newName }}
4
+ {% elif kind == "retype" %}
5
+ alter table(:{{ table }}) do
6
+ modify :{{ column }}, {{ type }}
7
+ end
8
+ {% else %}
9
+ alter table(:{{ table }}) do
10
+ remove :{{ column }}
11
+ end
12
+ {% endif %}
@@ -0,0 +1,92 @@
1
+ {# A page: a LiveView. Lists read through the query's read action into a `.table`, details load the record of the route's
2
+ `:id` into a `.list`, forms are AshPhoenix forms for the action. Row actions and forms run the action and report the
3
+ outcome as a flash. In lib/<app>_web/live/<page>_live.ex. -#}
4
+ {% macro buttons(actions, record) %}{% for a in actions %}<.button phx-click="{{ a.event }}" phx-value-id={{ "{" + record + ".id}" }}>{{ a.label }}</.button>{{ " " if not loop.last }}{% endfor %}{% endmacro %}
5
+ defmodule {{ web }}.{{ name }} do
6
+ {% block moduledoc %}
7
+ {% if moduledoc %}
8
+ {{ moduledoc }}
9
+
10
+ {% endif %}
11
+ {% endblock %}
12
+ use {{ web }}, :live_view
13
+
14
+ {% block mount %}
15
+ @impl true
16
+ def mount({% if params %}params{% elif byId %}%{"id" => id}{% else %}_params{% endif %}, _session, socket) do
17
+ {:ok, socket |> assign(:page_title, {{ title | dump }}){% if params %} |> assign(:params, params){% endif %}{% if byId %} |> assign(:id, {{ 'params["id"]' if params else "id" }}){% endif %} |> load()}
18
+ end
19
+ {% endblock %}
20
+
21
+ {% block load %}
22
+ defp load(socket) do
23
+ socket
24
+ {% for c in components %}
25
+ |> assign(:{{ c.id }}, {{ c.load }})
26
+ {% endfor %}
27
+ end
28
+ {% endblock %}
29
+ {% block events %}
30
+ {% for e in events %}
31
+
32
+ @impl true
33
+ {% if e.kind == "run" %}
34
+ def handle_event("{{ e.event }}", %{"id" => id}, socket) do
35
+ case Ash.update(Ash.get!({{ e.resource }}, id), %{}, action: :{{ e.action }}) do
36
+ {:ok, _} -> {:noreply, socket |> put_flash(:info, {{ (e.label + " done.") | dump }}) |> load()}
37
+ {:error, error} -> {:noreply, put_flash(socket, :error, {{ (e.label + " failed: ") | dump }} <> Exception.message(error))}
38
+ end
39
+ end
40
+ {% else %}
41
+ def handle_event("{{ e.event }}", %{"form" => params}, socket) do
42
+ case AshPhoenix.Form.submit(socket.assigns.{{ e.id }}, params: params) do
43
+ {:ok, _} -> {:noreply, socket |> put_flash(:info, {{ (e.label + " done.") | dump }}) |> load()}
44
+ {:error, form} -> {:noreply, assign(socket, :{{ e.id }}, form)}
45
+ end
46
+ end
47
+ {% endif %}
48
+ {% endfor %}
49
+ {% endblock %}
50
+
51
+ {% block render %}
52
+ @impl true
53
+ def render(assigns) do
54
+ ~H"""
55
+ <Layouts.app flash={@flash}>
56
+ {% if nav.length %}
57
+ <nav class="flex gap-4 mb-6">{% for link in nav %}<.link navigate="{{ link.route }}">{{ link.label }}</.link>{{ " " if not loop.last }}{% endfor %}</nav>
58
+ {% endif %}
59
+ <.header>{{ title }}</.header>
60
+ {% for c in components %}
61
+ {% if c.type == "list" %}
62
+ <.table id="{{ c.domId }}" rows={@{{ c.id }}}>
63
+ {% for col in c.columns %}
64
+ <:col :let={row} label={{ col.label | dump }}>{to_string(row.{{ col.field }})}</:col>
65
+ {% endfor %}
66
+ {% if c.actions.length %}
67
+ <:action :let={row}>{{ buttons(c.actions, "row") }}</:action>
68
+ {% endif %}
69
+ </.table>
70
+ {% elif c.type == "detail" %}
71
+ <.list>
72
+ {% for col in c.columns %}
73
+ <:item title={{ col.label | dump }}>{to_string(@{{ c.id }}.{{ col.field }})}</:item>
74
+ {% endfor %}
75
+ </.list>
76
+ {% if c.actions.length %}
77
+ {{ buttons(c.actions, "@" + c.id) }}
78
+ {% endif %}
79
+ {% else %}
80
+ <.form for={@{{ c.id }}} phx-submit="{{ c.event }}">
81
+ {% for input in c.inputs %}
82
+ <.input field={@{{ c.id }}[:{{ input.name }}]} label={{ input.label | dump }} />
83
+ {% endfor %}
84
+ <.button>{{ c.label }}</.button>
85
+ </.form>
86
+ {% endif %}
87
+ {% endfor %}
88
+ </Layouts.app>
89
+ """
90
+ end
91
+ {% endblock %}
92
+ end
@@ -0,0 +1,18 @@
1
+ {# A value type: an embedded resource with its stored fields as public attributes. In lib/<app>/<module>/<value>.ex. -#}
2
+ defmodule {{ module }} do
3
+ {% block moduledoc %}
4
+ {% if moduledoc %}
5
+ {{ moduledoc }}
6
+
7
+ {% endif %}
8
+ {% endblock %}
9
+ use Ash.Resource, data_layer: :embedded
10
+
11
+ {% block attributes %}
12
+ attributes do
13
+ {% for a in attributes %}
14
+ attribute :{{ a.name }}, {{ a.type }}, allow_nil?: {{ "true" if a.optional else "false" }}, public?: true
15
+ {% endfor %}
16
+ end
17
+ {% endblock %}
18
+ end
@@ -0,0 +1,31 @@
1
+ {# The sections an entity's resource gets after `mix ash.gen.resource`: unique fields as identities, derived fields and role
2
+ conditions as calculations, invariants as validations. Appended to lib/<app>/<module>/<entity>.ex. -#}
3
+ {% block identities %}
4
+ {% if identities.length %}
5
+ identities do
6
+ {% for name in identities %}
7
+ identity :unique_{{ name }}, [:{{ name }}]
8
+ {% endfor %}
9
+ end
10
+
11
+ {% endif %}
12
+ {% endblock %}
13
+ {% block calculations %}
14
+ {% if calculations.length %}
15
+ calculations do
16
+ {% for line in calculations %}
17
+ {{ line }}
18
+ {% endfor %}
19
+ end
20
+
21
+ {% endif %}
22
+ {% endblock %}
23
+ {% block validations %}
24
+ {% if validations.length %}
25
+ validations do
26
+ {% for v in validations %}
27
+ validate {{ v.rule }}, message: {{ v.message | dump }}
28
+ {% endfor %}
29
+ end
30
+ {% endif %}
31
+ {% endblock %}
@@ -0,0 +1,16 @@
1
+ {# The ExUnit tests of one rule: a case with a body runs; one without is skipped with a pointer to its registry entry. -#}
2
+ {% for case in cases %}
3
+ {% if case.body %}
4
+ test {{ (title + " " + case.name) | dump }} do
5
+ {% for line in case.body %}
6
+ {{ line }}
7
+ {% endfor %}
8
+ end
9
+ {% else %}
10
+ @tag skip: {{ ("registry task: " + qn) | dump }}
11
+ test {{ (title + " " + case.name) | dump }}
12
+ {% endif %}
13
+ {% if not loop.last %}
14
+
15
+ {% endif %}
16
+ {% endfor %}
@@ -0,0 +1,6 @@
1
+ {# The test module of a resource, with the tests of its first rule. In test/<app>/<module>/<entity>_test.exs. -#}
2
+ defmodule {{ module }} do
3
+ use ExUnit.Case, async: true
4
+
5
+ {% include "tests/cases.exs.njk" %}
6
+ end
@@ -0,0 +1,14 @@
1
+ {# The test of a scenario; one the generated project cannot pass yet is skipped with a pointer to its registry entry. -#}
2
+ {% if describe %}
3
+ # {{ describe }}
4
+ {% endif %}
5
+ {% if body %}
6
+ test {{ title | dump }} do
7
+ {% for line in body %}
8
+ {{ line }}
9
+ {% endfor %}
10
+ end
11
+ {% else %}
12
+ @tag skip: {{ ("registry task: " + qn) | dump }}
13
+ test {{ title | dump }}
14
+ {% endif %}