@appling/codegen-go 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.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Alexandros Fotiadis
3
+ Copyright (c) 2026 Alexandros Fotiadis, alexandros.fotiadis@techthos.net
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -30,10 +30,15 @@ Requires Go 1.22 or later. Money and decimals use [shopspring/decimal](https://g
30
30
  | transitions | a test in `<module>_test.go` per transition an action runs: `valid<Entity>()` in a `from` state reaches the `to` state, a state the action does not leave fails with `ErrInvalidTransition`; with policies it passes an actor the simulator proves allowed. Skipped as a registry task when the simulator cannot prove the preconditions, the guard or the actor |
31
31
  | entity policies | a test in `<module>_test.go` per policy on a whole entity that reads the actor only through `actor.is(...)`: `Can<Op><Entity>` on `valid<Entity>()` holds for an actor the simulator proves allowed and fails for one it proves denied. Other policies, and a case without such an actor, stay skipped as registry tasks |
32
32
  | preconditions | skipped tests in `<module>_test.go`; writing their bodies is a registry task |
33
+ | `describe`, `holds`, `does`, `handles` | paragraphs of the doc comment of the generated type or function |
33
34
  | `scenario` | a test `TestScenario<Name>` in `scenarios_test.go` (package `<module>_test`): the given rows with an ID each, the actor (`access.System()` without `as`), one call of the action, and the assertions of `then`. It replaces the transition and precondition tests of the action it calls. A scenario that calls a use case, or an action or policy Go does not fully translate, stays a skipped test with a registry task |
34
35
 
35
36
  Queries, projections, interfaces, pages, use cases, external systems and jobs become registry tasks (a query whose filter translates still gets `In<Query>(record, inputs...)`, which says whether a record belongs to its results), as do policies Go cannot translate (their check returns false until written): they need storage, HTTP and scheduling choices the model does not make. The project ends with `gofmt -w .`, and `go test ./...` is the registry's test command. The extension stays at the domain and behavior layers on purpose: generating the layers above means picking a storage, HTTP and scheduling stack, and that choice is deferred while Django and Ash catch up.
36
37
 
38
+ ## Templates
39
+
40
+ The generated code comes from the Nunjucks templates in `templates/` of this package, one per element kind. Override one with a file at the same path in `.appling/templates/go/` of your project; see [Templates](https://www.appling.tools/docs/codegen/templates/).
41
+
37
42
  ## License
38
43
 
39
44
  MIT
package/out/access.js CHANGED
@@ -94,52 +94,18 @@ function accessCode(context, access) {
94
94
  const roles = context.graph.nodes.filter(n => n.kind === 'Role');
95
95
  const actors = context.graph.nodes.filter(n => n.kind === 'Actor');
96
96
  const tenant = tenantOf(context);
97
- const tenantEntity = tenant && tenant.data.entity;
98
- const blocks = [
99
- '// ErrForbidden is returned by an action when its policies do not grant it to the actor.\nvar ErrForbidden = errors.New("forbidden")',
100
- `// Role is a role of the model, by qualified name.\ntype Role string${roles.length ? `\n\nconst (\n${roles.map(r => `\t// Role${access.name(r.qn)} is the role ${r.qn}.\n\tRole${access.name(r.qn)} Role = ${JSON.stringify(r.qn)}`).join('\n')}\n)` : ''}`,
101
- `// ActorType is a declared actor of the model, by qualified name.\ntype ActorType string${actors.length ? `\n\nconst (\n${actors.map(a => `\t// Actor${access.name(a.qn)} is the ${a.data.kind} actor ${a.qn}.\n\tActor${access.name(a.qn)} ActorType = ${JSON.stringify(a.qn)}`).join('\n')}\n)` : ''}`
102
- ];
103
97
  const fields = actorFields(context).flatMap(field => {
104
98
  const type = actorFieldType(field, context, imports);
105
- if (!type)
106
- return [];
107
- const owner = parentOf(field.qn);
108
- const record = field.data.type.decl ? `, the ID of a ${field.data.type.decl}` : '';
109
- return [`\t// ${pascal(last(field.qn))} is the field ${last(field.qn)} of ${owner}${record}.`, `\t${pascal(last(field.qn))} ${type} \`json:"${last(field.qn)}"\``];
99
+ return type ? [{ name: pascal(last(field.qn)), field: last(field.qn), owner: parentOf(field.qn), record: field.data.type.decl, type }] : [];
110
100
  });
111
- blocks.push([
112
- '// Actor is who acts: a declared actor with the roles it carries, the tenant it acts in, and the fields',
113
- '// the actors declare. A field is nil for actors that do not declare it; fields that hold records hold their ID.',
114
- 'type Actor struct {',
115
- '\tType ActorType `json:"type"`',
116
- '\tRoles []Role `json:"roles"`',
117
- '\t// ID is the record the actor is stored as, for actors declared with `is`.',
118
- '\tID *int64 `json:"id"`',
119
- ...(tenant ? [`\t// Tenant is the ID of the ${tenantEntity} the actor acts in (the tenant ${tenant.qn}); nil when it acts across tenants.`, '\tTenant *int64 `json:"tenant"`'] : []),
120
- ...fields,
121
- '\t// system marks a call the system makes; only System sets it.',
122
- '\tsystem bool',
123
- '}'
124
- ].join('\n'));
125
- blocks.push('// System returns the actor of a call the system makes, such as a job, an event handler or a scenario without\n// an actor: the actions check no policy and no tenant for it. The zero Actor is not the system.\nfunc System() Actor {\n\treturn Actor{system: true}\n}', '// IsSystem reports whether the call is one the system makes, which the actions do not check.\nfunc (a Actor) IsSystem() bool {\n\treturn a.system\n}');
126
- for (const actor of actors) {
127
- const name = access.name(actor.qn);
128
- const roleList = (actor.data.roles ?? []).map(r => `Role${access.name(r)}`).join(', ');
129
- blocks.push(`// New${name} returns the actor ${actor.qn} with the roles it declares.\nfunc New${name}() Actor {\n\treturn Actor{Type: Actor${name}, Roles: []Role{${roleList}}}\n}`);
130
- }
131
- blocks.push('// Has reports whether the actor carries the role, without checking the role\'s condition.\nfunc (a Actor) Has(role Role) bool {\n\treturn slices.Contains(a.Roles, role)\n}');
132
- for (const role of roles) {
133
- const name = access.name(role.qn);
134
- const condition = role.data.condition ? roleCondition(role, context, access, imports) : undefined;
135
- const body = !role.data.condition ? `actor.Has(Role${name})` : condition ? `actor.Has(Role${name}) && (${condition})` : 'false';
136
- blocks.push(`// Is${name} reports whether the actor is ${role.qn}: it carries the role${role.data.condition ? ' and the role\'s condition holds' : ''}.\nfunc Is${name}(actor Actor) bool {\n\treturn ${body}\n}`);
137
- }
138
- blocks.push('// Value returns what an optional actor field points to, or the zero value when the actor does not have it.\nfunc Value[T any](p *T) T {\n\tif p == nil {\n\t\tvar zero T\n\t\treturn zero\n\t}\n\treturn *p\n}', '// Same reports whether a record ID of the actor refers to the record with the given ID.\nfunc Same(ref *int64, id int64) bool {\n\treturn ref != nil && *ref == id\n}', '// SameRef reports whether two record IDs of the actor refer to the same record.\nfunc SameRef(a, b *int64) bool {\n\treturn a != nil && b != nil && *a == *b\n}');
139
- if (tenant)
140
- blocks.push(`// Tenanted is a record that belongs to a ${tenantEntity}, the entity of the tenant ${tenant.qn}.\ntype Tenanted interface {\n\t// TenantID returns the ID of the ${tenantEntity}, and false when the record does not reach one.\n\tTenantID() (int64, bool)\n}`, '// InTenant reports whether the record belongs to the tenant the actor acts in. An actor without a tenant acts across tenants.\nfunc InTenant(actor Actor, record Tenanted) bool {\n\tif actor.Tenant == nil {\n\t\treturn true\n\t}\n\tid, ok := record.TenantID()\n\treturn ok && id == *actor.Tenant\n}');
141
- const all = [...imports].sort((a, b) => Number(a.includes('.')) - Number(b.includes('.')) || a.localeCompare(b));
142
- return `// Package ${access.pkg} holds the actors, roles and tenant of the model and the checks its policies call.\npackage ${access.pkg}\n\nimport (\n${all.map(i => `\t"${i}"`).join('\n')}\n)\n\n${blocks.join('\n\n')}\n`;
101
+ return context.render('access/access.go.njk', {
102
+ pkg: access.pkg,
103
+ tenant: tenant && { entity: tenant.data.entity, qn: tenant.qn },
104
+ fields,
105
+ actors: actors.map(a => ({ name: access.name(a.qn), qn: a.qn, kind: a.data.kind, roles: (a.data.roles ?? []).map(r => `Role${access.name(r)}`) })),
106
+ roles: roles.map(r => ({ name: access.name(r.qn), qn: r.qn, conditional: !!r.data.condition, condition: r.data.condition ? roleCondition(r, context, access, imports) : undefined })),
107
+ imports: [...imports].sort((a, b) => Number(a.includes('.')) - Number(b.includes('.')) || a.localeCompare(b))
108
+ }) + '\n';
143
109
  }
144
110
  function roleCondition(role, context, access, imports) {
145
111
  const scope = { node: context.node, pkg: access.pkg, imports, importOf: () => access.path, actor: 'actor', access };
package/out/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import type { CodegenExtension } from '@appling/codegen';
1
+ import { type CodegenExtension } from '@appling/codegen';
2
2
  declare const extension: CodegenExtension;
3
3
  export default extension;