@appling/codegen-ash 0.1.0 → 0.1.2
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 +2 -1
- package/out/index.js +7 -3
- package/out/resource.d.ts +2 -0
- package/out/resource.js +7 -0
- package/out/roles.d.ts +13 -0
- package/out/roles.js +101 -0
- package/package.json +11 -5
package/README.md
CHANGED
|
@@ -33,6 +33,7 @@ Requires Elixir 1.17 or later and the `igniter_new` archive (`mix archive.instal
|
|
|
33
33
|
| scheduled `job` | an AshOban trigger with `where` and `scheduler_cron`; `now - duration("720h")` becomes `ago(720, :hour)` |
|
|
34
34
|
| `query` | a read action with filter, sort and offset pagination |
|
|
35
35
|
| computed projection field | a calculation on the source resource |
|
|
36
|
+
| `role` | an `Ash.Policy.SimpleCheck` per role on the resource actors are bound to with `is` (a private `roles` attribute and a calculation per role condition); policies that only name roles become `authorize_if` lines with `Ash.Policy.Authorizer` |
|
|
36
37
|
| `interface rest` | AshJsonApi routes on the domain (`index` for queries with `default_fields` from picks, `patch` for update actions), served by Phoenix under `/api/json` when the model has pages, otherwise by a JSON:API router that Bandit serves on port 4000 |
|
|
37
38
|
| `page`, `navigation`, `messages` | Phoenix LiveViews with lists, details, AshPhoenix forms and action buttons, navigation links and column labels; models with pages need the `phx_new` archive |
|
|
38
39
|
| rules | skipped ExUnit tests in `test/<app>/<module>/<resource>_test.exs` for invariants, policies, transitions and preconditions; writing their bodies is a registry task |
|
|
@@ -43,7 +44,7 @@ The project ends with `mix ash.codegen initial_resources`, so migrations and res
|
|
|
43
44
|
|
|
44
45
|
Machines, scheduled jobs and REST interfaces add `ash_state_machine`, `ash_oban`, and `ash_json_api` with `bandit` to the project.
|
|
45
46
|
|
|
46
|
-
What cannot be translated becomes a registry task: many to many relationships, calculations over embedded lists, invariants and preconditions over calculations or other resources, policies, events (Ash notifiers), externals and use cases (generic actions or Reactor), effects that create rows or emit events, jobs on events, authentication, rate limits and CORS.
|
|
47
|
+
What cannot be translated becomes a registry task: many to many relationships, calculations over embedded lists, invariants and preconditions over calculations or other resources, policies that say more than which roles may act, events (Ash notifiers), externals and use cases (generic actions or Reactor), effects that create rows or emit events, jobs on events, authentication, rate limits and CORS.
|
|
47
48
|
|
|
48
49
|
## License
|
|
49
50
|
|
package/out/index.js
CHANGED
|
@@ -4,6 +4,7 @@ import { actionSteps, jobSteps, machineSteps } from './behavior.js';
|
|
|
4
4
|
import { constant, lastOf, parentOf, validation } from './elixir.js';
|
|
5
5
|
import { migrationSteps } from './migrations.js';
|
|
6
6
|
import { hasPages, navigationSteps, pageSteps } from './pages.js';
|
|
7
|
+
import { roleCalculations, rolePolicySteps, roleSteps, userEntity } from './roles.js';
|
|
7
8
|
import { testSteps } from './tests.js';
|
|
8
9
|
import { app, attributeType, calculation, fieldsOf, fileOf, mix, moduleName, patch, relationTarget, storedAttributes, task, typeModule } from './naming.js';
|
|
9
10
|
const extension = {
|
|
@@ -43,7 +44,7 @@ const extension = {
|
|
|
43
44
|
...testSteps(node, owner(node, context), `invariant ${node.data.label}`, ['holds for valid records', 'rejects violations'], context)
|
|
44
45
|
];
|
|
45
46
|
case 'Policy': return [
|
|
46
|
-
task(`add an Ash policy to ${parentOf(node.qn)} for ${node.data.operations?.join(', ') ?? 'any action'}: ${node.props.condition}`),
|
|
47
|
+
...(rolePolicySteps(node, context) ?? [task(`add an Ash policy to ${parentOf(node.qn)} for ${node.data.operations?.join(', ') ?? 'any action'}: ${node.props.condition}`)]),
|
|
47
48
|
...(context.node(parentOf(node.qn)).kind === 'Entity'
|
|
48
49
|
? testSteps(node, owner(node, context), lastOf(node.qn), ['allows permitted actors', 'denies other actors'], context)
|
|
49
50
|
: [])
|
|
@@ -62,7 +63,7 @@ const extension = {
|
|
|
62
63
|
case 'Event': return [task(`publish ${lastOf(node.qn)} with an Ash notifier, for example Ash.Notifier.PubSub`)];
|
|
63
64
|
case 'External': return [task(`implement ${lastOf(node.qn)} as a client module or generic actions`)];
|
|
64
65
|
case 'UseCase': return [task(`implement ${lastOf(node.qn)} as a Reactor or a generic action`)];
|
|
65
|
-
case 'Role': return
|
|
66
|
+
case 'Role': return roleSteps(node, context);
|
|
66
67
|
case 'Param':
|
|
67
68
|
case 'ErrorDecl':
|
|
68
69
|
case 'SetEffect':
|
|
@@ -92,6 +93,9 @@ function entitySteps(entity, context) {
|
|
|
92
93
|
const type = f.data.type;
|
|
93
94
|
return [lastOf(f.qn), attributeType(type, context), ...(type.many ? ['array'] : []), ...(type.optional ? [] : ['required']), 'public'].join(':');
|
|
94
95
|
});
|
|
96
|
+
// The roles of the actor resource are not public, so nobody assigns roles to themselves through the API.
|
|
97
|
+
if (userEntity(context)?.qn === entity.qn)
|
|
98
|
+
specs.push('roles:atom:array');
|
|
95
99
|
return [
|
|
96
100
|
mix(['ash.gen.resource', typeModule(entity, context), '--domain', moduleName(entity.module, context),
|
|
97
101
|
'--default-actions', 'read,create,update,destroy', '--uuid-primary-key', 'id', ...(specs.length ? ['--attribute', specs.join(',')] : []),
|
|
@@ -132,7 +136,7 @@ function patchResource(text, entity, context) {
|
|
|
132
136
|
}
|
|
133
137
|
const blocks = [
|
|
134
138
|
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) ?? [])),
|
|
139
|
+
block('calculations', [...fields.flatMap(f => calculation(f, context) ?? []), ...roleCalculations(entity, context)]),
|
|
136
140
|
block('validations', context.children(entity.qn).filter(n => n.kind === 'Invariant').flatMap(n => {
|
|
137
141
|
const rule = check(n, context);
|
|
138
142
|
return rule ? [`validate ${rule}, message: ${JSON.stringify(n.data.label)}`] : [];
|
package/out/resource.d.ts
CHANGED
|
@@ -6,3 +6,5 @@
|
|
|
6
6
|
export declare function addToSection(text: string, name: string, lines: string[], inner?: string): string;
|
|
7
7
|
/** Adds an extension to the `use Ash.Resource` or `use Ash.Domain` options. */
|
|
8
8
|
export declare function addExtension(text: string, extension: string): string;
|
|
9
|
+
/** Adds `Ash.Policy.Authorizer` to the `use Ash.Resource` options, so the resource's policies apply. */
|
|
10
|
+
export declare function addAuthorizer(text: string): string;
|
package/out/resource.js
CHANGED
|
@@ -35,3 +35,10 @@ export function addExtension(text, extension) {
|
|
|
35
35
|
: `${match[0]},\n extensions: [${extension}]`;
|
|
36
36
|
return text.replace(match[0], updated);
|
|
37
37
|
}
|
|
38
|
+
/** Adds `Ash.Policy.Authorizer` to the `use Ash.Resource` options, so the resource's policies apply. */
|
|
39
|
+
export function addAuthorizer(text) {
|
|
40
|
+
const match = /use Ash\.Resource,?[^\n]*(?:\n {4,}[^\n]*)*/.exec(text);
|
|
41
|
+
if (!match || match[0].includes('Ash.Policy.Authorizer'))
|
|
42
|
+
return text;
|
|
43
|
+
return text.replace(match[0], `${match[0].replace(/,$/, '')},\n authorizers: [Ash.Policy.Authorizer]`);
|
|
44
|
+
}
|
package/out/roles.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { MapContext, Step } from '@appling/codegen';
|
|
2
|
+
import type { GraphNode } from '@appling/model';
|
|
3
|
+
/** The entity the actors are bound to with `is`, whose resource is the actor; undefined unless there is exactly one. */
|
|
4
|
+
export declare function userEntity(context: MapContext): GraphNode | undefined;
|
|
5
|
+
/** One `Ash.Policy.SimpleCheck` per role: the actor has the role in its `roles` and the role's condition holds. */
|
|
6
|
+
export declare function roleSteps(role: GraphNode, context: MapContext): Step[];
|
|
7
|
+
/** The calculations of the actor resource that hold the role conditions, such as `calculate :operator?, :boolean, expr(active)`. */
|
|
8
|
+
export declare function roleCalculations(entity: GraphNode, context: MapContext): string[];
|
|
9
|
+
/**
|
|
10
|
+
* A policy whose condition only names roles (`actor.is(A) || actor.is(B)`) becomes an Ash policy with one
|
|
11
|
+
* `authorize_if` per role check, on the entity's resource or on the action. Undefined for any other policy.
|
|
12
|
+
*/
|
|
13
|
+
export declare function rolePolicySteps(policy: GraphNode, context: MapContext): Step[] | undefined;
|
package/out/roles.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { ashExpr, lastOf, parentOf } from './elixir.js';
|
|
2
|
+
import { fileOf, moduleName, patch, snake, task, typeModule } from './naming.js';
|
|
3
|
+
import { addAuthorizer, addToSection } from './resource.js';
|
|
4
|
+
const ACTION_TYPES = { read: ':read', create: ':create', update: ':update', delete: ':destroy' };
|
|
5
|
+
/** The entity the actors are bound to with `is`, whose resource is the actor; undefined unless there is exactly one. */
|
|
6
|
+
export function userEntity(context) {
|
|
7
|
+
const bound = new Set(context.graph.nodes.filter(n => n.kind === 'Actor' && n.data.entity).map(n => n.data.entity));
|
|
8
|
+
return bound.size === 1 ? context.node([...bound][0]) : undefined;
|
|
9
|
+
}
|
|
10
|
+
/** One `Ash.Policy.SimpleCheck` per role: the actor has the role in its `roles` and the role's condition holds. */
|
|
11
|
+
export function roleSteps(role, context) {
|
|
12
|
+
const name = lastOf(role.qn);
|
|
13
|
+
const user = userEntity(context);
|
|
14
|
+
if (!user)
|
|
15
|
+
return [task(`model the role ${name} on the actor resource`)];
|
|
16
|
+
const condition = roleCondition(role, context);
|
|
17
|
+
const holds = [`:${snake(name)} in (actor.roles || [])`, ...(condition ? [`actor.${snake(name)}?`] : [])].join(' and ');
|
|
18
|
+
const code = [
|
|
19
|
+
`defmodule ${checkModule(role, context)} do`,
|
|
20
|
+
' use Ash.Policy.SimpleCheck',
|
|
21
|
+
'',
|
|
22
|
+
' @impl true',
|
|
23
|
+
` def describe(_opts), do: ${JSON.stringify(`actor is ${name}`)}`,
|
|
24
|
+
'',
|
|
25
|
+
' @impl true',
|
|
26
|
+
` def match?(%${typeModule(user, context)}{} = actor, _context, _opts) do`,
|
|
27
|
+
...(condition ? [` actor = Ash.load!(actor, :${snake(name)}?, authorize?: false)`] : []),
|
|
28
|
+
` ${holds}`,
|
|
29
|
+
' end',
|
|
30
|
+
'',
|
|
31
|
+
' def match?(_actor, _context, _opts), do: false',
|
|
32
|
+
'end',
|
|
33
|
+
''
|
|
34
|
+
].join('\n');
|
|
35
|
+
const file = ['lib', ...fileOf(role, context).split('/').slice(1, -1), 'checks', `${snake(name)}.ex`].join('/');
|
|
36
|
+
return [
|
|
37
|
+
{ kind: 'template', file, write: () => code },
|
|
38
|
+
...(role.data.condition && !condition ? [task(`check the condition of ${name} in ${checkModule(role, context)}: ${role.props.condition}`)] : [])
|
|
39
|
+
];
|
|
40
|
+
}
|
|
41
|
+
/** The calculations of the actor resource that hold the role conditions, such as `calculate :operator?, :boolean, expr(active)`. */
|
|
42
|
+
export function roleCalculations(entity, context) {
|
|
43
|
+
if (userEntity(context)?.qn !== entity.qn)
|
|
44
|
+
return [];
|
|
45
|
+
return context.graph.nodes.filter(n => n.kind === 'Role').flatMap(role => {
|
|
46
|
+
const condition = roleCondition(role, context);
|
|
47
|
+
return condition ? [`calculate :${snake(lastOf(role.qn))}?, :boolean, expr(${condition})`] : [];
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* A policy whose condition only names roles (`actor.is(A) || actor.is(B)`) becomes an Ash policy with one
|
|
52
|
+
* `authorize_if` per role check, on the entity's resource or on the action. Undefined for any other policy.
|
|
53
|
+
*/
|
|
54
|
+
export function rolePolicySteps(policy, context) {
|
|
55
|
+
const owner = context.node(parentOf(policy.qn));
|
|
56
|
+
const checks = userEntity(context) && roleChecks(policy.data.condition, context);
|
|
57
|
+
if (!checks)
|
|
58
|
+
return undefined;
|
|
59
|
+
const operations = (policy.data.operations ?? []);
|
|
60
|
+
const target = owner.kind === 'Entity' && !policy.data.fields?.length
|
|
61
|
+
? { entity: owner, condition: operations.length ? `action_type(${operations.length === 1 ? ACTION_TYPES[operations[0]] : `[${operations.map(o => ACTION_TYPES[o]).join(', ')}]`})` : 'always()' }
|
|
62
|
+
: owner.kind === 'Action' && owner.data.entity
|
|
63
|
+
? { entity: context.node(owner.data.entity), condition: `action(:${snake(lastOf(owner.qn))})` }
|
|
64
|
+
: undefined;
|
|
65
|
+
if (!target)
|
|
66
|
+
return undefined;
|
|
67
|
+
const lines = [`policy ${target.condition} do`, ...checks.map(c => ` authorize_if ${c}`), 'end'];
|
|
68
|
+
return [patch(fileOf(target.entity, context), existing => addAuthorizer(addToSection(existing, 'policies', lines)))];
|
|
69
|
+
}
|
|
70
|
+
function checkModule(role, context) {
|
|
71
|
+
return `${moduleName(role.module, context)}.Checks.${lastOf(role.qn)}`;
|
|
72
|
+
}
|
|
73
|
+
/** The check modules of `actor.is(Role)` branches joined by `||`, or undefined when the condition says anything else. */
|
|
74
|
+
function roleChecks(expr, context) {
|
|
75
|
+
if (expr.$type === 'BinaryExpr' && expr.op === '||') {
|
|
76
|
+
const [left, right] = [roleChecks(expr.left, context), roleChecks(expr.right, context)];
|
|
77
|
+
return left && right && [...left, ...right];
|
|
78
|
+
}
|
|
79
|
+
const role = expr.$type === 'MemberExpr' && expr.call && expr.member === 'is' && expr.receiver?.name === 'actor' && !expr.receiver.target && expr.args?.[0]?.target
|
|
80
|
+
? context.node(expr.args[0].target)
|
|
81
|
+
: undefined;
|
|
82
|
+
return role?.kind === 'Role' ? [checkModule(role, context)] : undefined;
|
|
83
|
+
}
|
|
84
|
+
/** The role condition as an expression on the actor resource itself, where `actor.active` is the attribute `active`. */
|
|
85
|
+
function roleCondition(role, context) {
|
|
86
|
+
const condition = role.data.condition;
|
|
87
|
+
return condition && ashExpr(onActor(condition), context.node);
|
|
88
|
+
}
|
|
89
|
+
function onActor(expr) {
|
|
90
|
+
if (expr.$type === 'MemberExpr' && !expr.call && expr.receiver?.$type === 'NameExpr' && expr.receiver.name === 'actor' && !expr.receiver.target) {
|
|
91
|
+
return { $type: 'NameExpr', name: expr.member, type: expr.type, target: expr.target };
|
|
92
|
+
}
|
|
93
|
+
const mapped = { ...expr };
|
|
94
|
+
for (const key of ['left', 'right', 'operand', 'receiver', 'index'])
|
|
95
|
+
if (expr[key])
|
|
96
|
+
mapped[key] = onActor(expr[key]);
|
|
97
|
+
for (const key of ['args', 'items'])
|
|
98
|
+
if (expr[key])
|
|
99
|
+
mapped[key] = expr[key].map(onActor);
|
|
100
|
+
return mapped;
|
|
101
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@appling/codegen-ash",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Appling code generation extension for Ash",
|
|
5
|
+
"homepage": "https://www.appling.tools/docs/",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/alex20465/appling.git",
|
|
9
|
+
"directory": "packages/codegen-ash"
|
|
10
|
+
},
|
|
5
11
|
"type": "module",
|
|
6
12
|
"exports": {
|
|
7
13
|
".": {
|
|
@@ -13,15 +19,15 @@
|
|
|
13
19
|
"out"
|
|
14
20
|
],
|
|
15
21
|
"dependencies": {
|
|
16
|
-
"@appling/model": "0.1.
|
|
22
|
+
"@appling/model": "0.1.2"
|
|
17
23
|
},
|
|
18
24
|
"peerDependencies": {
|
|
19
|
-
"@appling/codegen": "0.1.
|
|
25
|
+
"@appling/codegen": "0.1.2"
|
|
20
26
|
},
|
|
21
27
|
"devDependencies": {
|
|
28
|
+
"@appling/codegen": "0.1.2",
|
|
22
29
|
"@types/node": "^24.19.2",
|
|
23
|
-
"typescript": "7.0.2"
|
|
24
|
-
"@appling/codegen": "0.1.0"
|
|
30
|
+
"typescript": "7.0.2"
|
|
25
31
|
},
|
|
26
32
|
"license": "MIT",
|
|
27
33
|
"publishConfig": {
|