@appling/codegen-go 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alexandros Fotiadis
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,33 @@
1
- # Temporary Holding Version
1
+ # @appling/codegen-go
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Appling code generation extension for Go. It turns the domain and behavior layers of an Appling model into plain Go packages, one per module, with no framework, so you can put them behind the storage and HTTP libraries you choose.
4
+
5
+ ```json
6
+ {
7
+ "generate": [
8
+ { "extension": "@appling/codegen-go", "out": "build/shop" }
9
+ ]
10
+ }
11
+ ```
12
+
13
+ Requires Go 1.22 or later. Money and decimals use [shopspring/decimal](https://github.com/shopspring/decimal).
14
+
15
+ ## What it generates
16
+
17
+ | Model | Go, in `internal/<module>/` |
18
+ |---|---|
19
+ | `module` | a package with `doc.go` |
20
+ | `enum` | a string type with one constant per value (`OrderStatusDraft`) |
21
+ | `value`, `event` | a struct with JSON tags |
22
+ | `entity` | a struct with an `ID`, `New<Entity>()` with the defaults, a method per derived field, and `Validate()` that checks the invariants |
23
+ | optional fields, entity references, lists | pointers, `*Entity`, slices |
24
+ | `action` | a function on the entity that checks the preconditions (returning the declared errors), takes the state transition (`ErrInvalidTransition` otherwise), applies the effects and returns the emitted events |
25
+ | `machine` | for transitions on an event, a function `<Machine>On<Event>(event)` |
26
+ | `errors` | `Err<Name>` variables |
27
+ | rules | skipped tests in `<module>_test.go`; writing their bodies is a registry task |
28
+
29
+ Queries, projections, interfaces, pages, use cases, external systems, jobs and policies become registry tasks: 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.
30
+
31
+ ## License
32
+
33
+ MIT
@@ -0,0 +1,25 @@
1
+ import type { ExprData, GraphNode } from '@appling/model';
2
+ /** What a translated expression is in Go, which decides the operators: decimals and times have methods. */
3
+ type Kind = 'decimal' | 'time' | 'duration' | 'int' | 'string' | 'bool' | 'list' | 'null' | 'other';
4
+ export interface GoScope {
5
+ node(qn: string): GraphNode | undefined;
6
+ /** The variable holding the record, such as `o` in a method or `order` in an action. */
7
+ self?: string;
8
+ /** The Go package the code is written in, to qualify names from other modules. */
9
+ pkg: string;
10
+ vars?: Map<string, Kind>;
11
+ imports: Set<string>;
12
+ /** The Go import path of a module, such as `shop/internal/crm`. */
13
+ importOf(module: string): string;
14
+ }
15
+ /** Translates an expression to Go, or returns undefined when Go code cannot say it, such as a policy over `actor`. */
16
+ export declare function goExpr(expr: ExprData, scope: GoScope): string | undefined;
17
+ /** The Go type of an Appling type name as the typer shows it, such as `Money`, `Line[]` or `DateTime?`. */
18
+ export declare function kindOf(type: string): Kind;
19
+ /** The Go constant of an enum value, qualified with its package outside its module. */
20
+ export declare function enumConstant(literal: GraphNode, scope: GoScope): string;
21
+ /** The Go name of a declaration, with its package prefix when it lives in another module. */
22
+ export declare function qualify(declaration: GraphNode, scope: GoScope): string;
23
+ export declare function pascal(name: string): string;
24
+ export declare function camel(name: string): string;
25
+ export {};
package/out/golang.js ADDED
@@ -0,0 +1,225 @@
1
+ const COMPARE = { '<': 'LessThan', '<=': 'LessThanOrEqual', '>': 'GreaterThan', '>=': 'GreaterThanOrEqual' };
2
+ const ARITHMETIC = { '+': 'Add', '-': 'Sub', '*': 'Mul', '/': 'Div' };
3
+ const UNITS = { ms: 'time.Millisecond', s: 'time.Second', m: 'time.Minute', h: 'time.Hour', d: '24 * time.Hour' };
4
+ /** Translates an expression to Go, or returns undefined when Go code cannot say it, such as a policy over `actor`. */
5
+ export function goExpr(expr, scope) {
6
+ const result = translate(expr, scope);
7
+ return result && value(result);
8
+ }
9
+ /** The Go type of an Appling type name as the typer shows it, such as `Money`, `Line[]` or `DateTime?`. */
10
+ export function kindOf(type) {
11
+ const base = type.replace(/\?$/, '');
12
+ if (base.endsWith('[]'))
13
+ return 'list';
14
+ return { Money: 'decimal', Decimal: 'decimal', DateTime: 'time', Date: 'time', Duration: 'duration', Int: 'int', String: 'string', Text: 'string', Bool: 'bool', null: 'null' }[base] ?? 'other';
15
+ }
16
+ function translate(expr, scope) {
17
+ switch (expr.$type) {
18
+ case 'StringExpr': return { code: JSON.stringify(expr.value), kind: 'string' };
19
+ case 'NumberExpr': return { code: String(expr.value), kind: String(expr.value).includes('.') ? 'decimal' : 'int' };
20
+ case 'BoolExpr': return { code: String(expr.value), kind: 'bool' };
21
+ case 'NullExpr': return { code: 'nil', kind: 'null' };
22
+ case 'UnaryExpr': {
23
+ const operand = translate(expr.operand, scope);
24
+ if (!operand)
25
+ return undefined;
26
+ if (expr.op === '!')
27
+ return { code: `!${wrap(value(operand))}`, kind: 'bool' };
28
+ return operand.kind === 'decimal' ? { code: `${wrap(value(operand))}.Neg()`, kind: 'decimal' } : { code: `-${wrap(value(operand))}`, kind: operand.kind };
29
+ }
30
+ case 'BinaryExpr': return binary(expr, scope);
31
+ case 'NameExpr': return expr.call ? call(expr, scope) : name(expr, scope);
32
+ case 'MemberExpr': return expr.call ? method(expr, scope) : member(expr, scope);
33
+ case 'IndexExpr': {
34
+ const [list, index] = [translate(expr.receiver, scope), translate(expr.index, scope)];
35
+ return list && index ? { code: `${value(list)}[${value(index)}]`, kind: kindOf(expr.type) } : undefined;
36
+ }
37
+ default: return undefined;
38
+ }
39
+ }
40
+ function binary(expr, scope) {
41
+ const op = expr.op;
42
+ if (op === 'in') {
43
+ const left = translate(expr.left, scope);
44
+ const items = (expr.right?.items ?? []).map(i => translate(i, scope));
45
+ if (!left || expr.right?.$type !== 'ListExpr' || items.some(i => !i))
46
+ return undefined;
47
+ scope.imports.add('slices');
48
+ return { code: `slices.Contains([]${elementType(left, expr.right.items, scope)}{${items.map(i => value(i)).join(', ')}}, ${value(left)})`, kind: 'bool' };
49
+ }
50
+ const [left, right] = [translate(expr.left, scope), translate(expr.right, scope)];
51
+ if (!left || !right)
52
+ return undefined;
53
+ if (op === '&&' || op === '||')
54
+ return { code: `${wrap(value(left))} ${op} ${wrap(value(right))}`, kind: 'bool' };
55
+ if ((op === '==' || op === '!=') && (left.kind === 'null' || right.kind === 'null')) {
56
+ const subject = left.kind === 'null' ? right : left;
57
+ return { code: `${subject.code} ${op} nil`, kind: 'bool' };
58
+ }
59
+ const kinds = [left.kind, right.kind];
60
+ if (kinds.includes('decimal')) {
61
+ const [a, b] = [decimal(left, scope), decimal(right, scope)];
62
+ if (op === '==' || op === '!=')
63
+ return { code: `${op === '!=' ? '!' : ''}${a}.Equal(${b})`, kind: 'bool' };
64
+ if (op in COMPARE)
65
+ return { code: `${a}.${COMPARE[op]}(${b})`, kind: 'bool' };
66
+ if (op in ARITHMETIC)
67
+ return { code: `${a}.${ARITHMETIC[op]}(${b})`, kind: 'decimal' };
68
+ return undefined;
69
+ }
70
+ if (left.kind === 'time') {
71
+ const [a, b] = [value(left), value(right)];
72
+ if (right.kind === 'duration' && (op === '+' || op === '-'))
73
+ return { code: `${a}.Add(${op === '-' ? `-${wrap(b)}` : b})`, kind: 'time' };
74
+ if (right.kind === 'time' && op === '-')
75
+ return { code: `${a}.Sub(${b})`, kind: 'duration' };
76
+ const compare = { '<': `${a}.Before(${b})`, '>': `${a}.After(${b})`, '<=': `!${a}.After(${b})`, '>=': `!${a}.Before(${b})`, '==': `${a}.Equal(${b})`, '!=': `!${a}.Equal(${b})` };
77
+ return op in compare ? { code: compare[op], kind: 'bool' } : undefined;
78
+ }
79
+ const comparison = ['==', '!=', '<', '<=', '>', '>='].includes(op);
80
+ return { code: `${wrap(value(left))} ${op} ${wrap(value(right))}`, kind: comparison ? 'bool' : left.kind };
81
+ }
82
+ function name(expr, scope) {
83
+ const id = expr.name;
84
+ if (scope.vars?.has(id))
85
+ return { code: id, kind: scope.vars.get(id) };
86
+ if (!expr.target) {
87
+ if (id === 'this')
88
+ return scope.self ? { code: scope.self, kind: 'other' } : undefined;
89
+ if (id === 'now') {
90
+ scope.imports.add('time');
91
+ return { code: 'time.Now()', kind: 'time' };
92
+ }
93
+ return undefined;
94
+ }
95
+ const target = scope.node(expr.target);
96
+ if (target?.kind === 'EnumLiteral')
97
+ return { code: enumConstant(target, scope), kind: 'other' };
98
+ if (target?.kind === 'Param')
99
+ return { code: camel(id), kind: kindOf(expr.type), pointer: expr.type.endsWith('?') };
100
+ if (target?.kind === 'Field' && scope.self && isRecordField(target, scope)) {
101
+ return { code: `${scope.self}.${pascal(id)}${target.data.derived ? '()' : ''}`, kind: kindOf(expr.type), pointer: optional(target) };
102
+ }
103
+ return undefined;
104
+ }
105
+ function member(expr, scope) {
106
+ const receiver = translate(expr.receiver, scope);
107
+ const target = expr.target ? scope.node(expr.target) : undefined;
108
+ if (!receiver || target?.kind !== 'Field' || !isRecordField(target, scope))
109
+ return undefined;
110
+ return { code: `${value(receiver)}.${pascal(expr.member)}${target.data.derived ? '()' : ''}`, kind: kindOf(expr.type), pointer: optional(target) };
111
+ }
112
+ function call(expr, scope) {
113
+ const [arg] = expr.args ?? [];
114
+ if (expr.name === 'duration') {
115
+ const parts = [...String(arg?.value ?? '').matchAll(/(\d+)(ms|d|h|m|s)/g)];
116
+ if (!parts.length)
117
+ return undefined;
118
+ scope.imports.add('time');
119
+ return { code: parts.map(([, amount, unit]) => `${amount} * ${UNITS[unit]}`).join(' + '), kind: 'duration' };
120
+ }
121
+ if (expr.name === 'has') {
122
+ const subject = arg && translate(arg, scope);
123
+ return subject?.pointer ? { code: `${subject.code} != nil`, kind: 'bool' } : undefined;
124
+ }
125
+ if (expr.name === 'size') {
126
+ const subject = arg && translate(arg, scope);
127
+ return subject && { code: `int64(len(${value(subject)}))`, kind: 'int' };
128
+ }
129
+ if (expr.name === 'sum' && arg)
130
+ return sum(arg, kindOf(expr.type), scope);
131
+ return undefined;
132
+ }
133
+ function method(expr, scope) {
134
+ const receiver = translate(expr.receiver, scope);
135
+ if (!receiver)
136
+ return undefined;
137
+ const args = expr.args ?? [];
138
+ if (expr.member === 'size')
139
+ return { code: `int64(len(${value(receiver)}))`, kind: 'int' };
140
+ if (expr.member === 'exists' || expr.member === 'all') {
141
+ const [variable, body] = [args[0].name, args[1]];
142
+ const test = translate(body, { ...scope, vars: new Map([...(scope.vars ?? []), [variable, 'other']]) });
143
+ if (!test)
144
+ return undefined;
145
+ const [hit, miss] = expr.member === 'exists' ? ['true', 'false'] : ['false', 'true'];
146
+ const condition = expr.member === 'exists' ? value(test) : `!${wrap(value(test))}`;
147
+ return { code: `func() bool { for _, ${variable} := range ${value(receiver)} { if ${condition} { return ${hit} } }; return ${miss} }()`, kind: 'bool' };
148
+ }
149
+ const arg = args[0] && translate(args[0], scope);
150
+ if (!arg)
151
+ return undefined;
152
+ const text = { contains: ['strings', 'strings.Contains'], startsWith: ['strings', 'strings.HasPrefix'], endsWith: ['strings', 'strings.HasSuffix'] };
153
+ if (expr.member in text) {
154
+ scope.imports.add(text[expr.member][0]);
155
+ return { code: `${text[expr.member][1]}(${value(receiver)}, ${value(arg)})`, kind: 'bool' };
156
+ }
157
+ if (expr.member === 'matches') {
158
+ scope.imports.add('regexp');
159
+ return { code: `regexp.MustCompile(${value(arg)}).MatchString(${value(receiver)})`, kind: 'bool' };
160
+ }
161
+ return undefined;
162
+ }
163
+ /** `sum(list)` and `sum(list.map(x, body))` as a loop. */
164
+ function sum(arg, kind, scope) {
165
+ const mapped = arg.$type === 'MemberExpr' && arg.call && arg.member === 'map' ? arg : undefined;
166
+ const list = translate(mapped ? mapped.receiver : arg, scope);
167
+ const variable = mapped ? mapped.args[0].name : 'item';
168
+ const item = mapped ? translate(mapped.args[1], { ...scope, vars: new Map([...(scope.vars ?? []), [variable, 'other']]) }) : { code: variable, kind };
169
+ if (!list || !item)
170
+ return undefined;
171
+ if (kind === 'decimal') {
172
+ scope.imports.add('github.com/shopspring/decimal');
173
+ return { code: `func() decimal.Decimal { total := decimal.Zero; for _, ${variable} := range ${value(list)} { total = total.Add(${value(item)}) }; return total }()`, kind };
174
+ }
175
+ return { code: `func() int64 { var total int64; for _, ${variable} := range ${value(list)} { total += ${value(item)} }; return total }()`, kind: 'int' };
176
+ }
177
+ function decimal(go, scope) {
178
+ scope.imports.add('github.com/shopspring/decimal');
179
+ if (go.kind === 'decimal')
180
+ return wrap(value(go));
181
+ return /^\d+$/.test(go.code) ? `decimal.NewFromInt(${go.code})` : /^[\d.]+$/.test(go.code) ? `decimal.RequireFromString(${JSON.stringify(go.code)})` : `decimal.NewFromInt(${value(go)})`;
182
+ }
183
+ function value(go) {
184
+ return go.pointer ? `(*${go.code})` : go.code;
185
+ }
186
+ function wrap(code) {
187
+ return /^[\w.]+(\(.*\))?$/.test(code) || /^\(.*\)$/.test(code) || /^".*"$/.test(code) ? code : `(${code})`;
188
+ }
189
+ function isRecordField(field, scope) {
190
+ const owner = scope.node(field.qn.slice(0, field.qn.lastIndexOf('.')))?.kind;
191
+ return owner === 'Entity' || owner === 'ValueType' || owner === 'Event';
192
+ }
193
+ function optional(field) {
194
+ const type = field.data.type;
195
+ return !!type?.optional && !type.many;
196
+ }
197
+ /** The Go constant of an enum value, qualified with its package outside its module. */
198
+ export function enumConstant(literal, scope) {
199
+ const enumQn = literal.qn.slice(0, literal.qn.lastIndexOf('.'));
200
+ const enumNode = scope.node(enumQn);
201
+ return `${qualify(enumNode, scope)}${pascal(literal.qn.slice(literal.qn.lastIndexOf('.') + 1))}`;
202
+ }
203
+ /** The Go name of a declaration, with its package prefix when it lives in another module. */
204
+ export function qualify(declaration, scope) {
205
+ const name = declaration.qn.slice(declaration.qn.lastIndexOf('.') + 1);
206
+ const pkg = declaration.module.split('.').pop();
207
+ if (pkg === scope.pkg)
208
+ return name;
209
+ scope.imports.add(scope.importOf(declaration.module));
210
+ return `${pkg}.${name}`;
211
+ }
212
+ /** The element type of a list literal: the enum of its values, or the Go type of the compared value. */
213
+ function elementType(left, items, scope) {
214
+ const literal = items[0]?.target ? scope.node(items[0].target) : undefined;
215
+ if (literal?.kind === 'EnumLiteral')
216
+ return qualify(scope.node(literal.qn.slice(0, literal.qn.lastIndexOf('.'))), scope);
217
+ return { string: 'string', int: 'int64', bool: 'bool' }[left.kind] ?? 'any';
218
+ }
219
+ export function pascal(name) {
220
+ return name.split('_').map(part => part.charAt(0).toUpperCase() + part.slice(1)).join('').replace(/^Id$/, 'ID');
221
+ }
222
+ export function camel(name) {
223
+ const p = pascal(name);
224
+ return p.charAt(0).toLowerCase() + p.slice(1);
225
+ }
package/out/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import type { CodegenExtension } from '@appling/codegen';
2
+ declare const extension: CodegenExtension;
3
+ export default extension;
package/out/index.js ADDED
@@ -0,0 +1,306 @@
1
+ import { camel, enumConstant, goExpr, pascal, qualify } from './golang.js';
2
+ const DECIMAL = 'github.com/shopspring/decimal';
3
+ const PRIMITIVES = {
4
+ String: ['string'], Text: ['string'], Int: ['int64'], Bool: ['bool'], File: ['string'], Uuid: ['string'],
5
+ Decimal: ['decimal.Decimal', DECIMAL], Money: ['decimal.Decimal', DECIMAL],
6
+ Date: ['time.Time', 'time'], DateTime: ['time.Time', 'time'], Duration: ['time.Duration', 'time']
7
+ };
8
+ const extension = {
9
+ name: '@appling/codegen-go',
10
+ test: ['go', 'test', './...'],
11
+ syncExclude: ['go.sum'],
12
+ prerequisites: [{ name: 'Go', command: ['go', 'version'], expect: /go1\.(2[2-9]|[3-9]\d)/, hint: 'install Go 1.22 or later' }],
13
+ setup: context => [
14
+ { kind: 'command', run: ['go', 'mod', 'init', context.name], creates: ['go.mod'] },
15
+ { kind: 'command', run: ['go', 'get', `${DECIMAL}@v1.6.0`], creates: ['go.sum'] },
16
+ { kind: 'command', run: ['gofmt', '-w', '.'], phase: 3 }
17
+ ],
18
+ steps(node, context) {
19
+ switch (node.kind) {
20
+ case 'Module': return [
21
+ goFile(node.qn, 'doc.go', context, new Set(), `// Package ${pkgOf(node.qn)} holds the ${node.qn} module of the model.`),
22
+ goFile(node.qn, 'support.go', context, new Set(), '// ptr returns a pointer to a copy of v, for optional fields.\nfunc ptr[T any](v T) *T { return &v }')
23
+ ];
24
+ case 'Enum': return [enumSteps(node, context)];
25
+ case 'ValueType': return [structStep(node, context, 'types.go')];
26
+ case 'Entity': return entitySteps(node, context);
27
+ case 'Event': return [structStep(node, context, 'events.go')];
28
+ case 'ErrorDecl': return [goFile(node.module, 'errors.go', context, new Set(['errors']), `// ${errorName(node)} is the declared error ${node.qn}.\nvar ${errorName(node)} = errors.New(${JSON.stringify(last(node.qn))})`)];
29
+ case 'Field': return fieldSteps(node, context);
30
+ case 'Invariant': return [...(validation(node, context) ? [] : [task(`check the invariant "${node.data.label}" in Validate: ${node.props.condition}`)]), ...testSteps(node, context)];
31
+ case 'Policy': return [task(`enforce the policy ${node.qn}: ${node.props.condition}`), ...testSteps(node, context)];
32
+ case 'Action': return actionSteps(node, context);
33
+ case 'Machine': return machineSteps(node, context);
34
+ case 'Transition': return testSteps(node, context);
35
+ case 'EnumLiteral':
36
+ case 'Param':
37
+ case 'SetEffect':
38
+ case 'CreateEffect':
39
+ case 'EmitEffect':
40
+ case 'ExternalOperation':
41
+ case 'ProjectionField':
42
+ case 'Endpoint':
43
+ return [];
44
+ case 'Job':
45
+ case 'Query':
46
+ case 'Projection':
47
+ case 'External':
48
+ case 'UseCase':
49
+ case 'Interface':
50
+ case 'Page':
51
+ case 'Navigation':
52
+ case 'Flow':
53
+ case 'Messages':
54
+ return [task(`implement the ${node.kind.toLowerCase()} ${last(node.qn)} on top of the generated domain package, with the storage, HTTP and scheduling libraries of your choice`)];
55
+ default: return undefined;
56
+ }
57
+ }
58
+ };
59
+ export default extension;
60
+ function enumSteps(node, context) {
61
+ const name = last(node.qn);
62
+ const values = context.children(node.qn).map(l => `\t${name}${pascal(last(l.qn))} ${name} = ${JSON.stringify(last(l.qn))}`);
63
+ return goFile(node.module, 'types.go', context, new Set(), `// ${name} is the enum ${node.qn}.\ntype ${name} string\n\nconst (\n${values.join('\n')}\n)`);
64
+ }
65
+ function structStep(node, context, file) {
66
+ const imports = new Set();
67
+ const scope = goScope(node, context, imports);
68
+ const fields = fieldsOf(node, context).filter(f => !f.data.derived).map(f => `\t${pascal(last(f.qn))} ${typeOf(f.data.type, scope)} \`json:"${last(f.qn)}"\``);
69
+ return goFile(node.module, file, context, imports, `// ${last(node.qn)} is the ${node.kind === 'Event' ? 'event' : 'value type'} ${node.qn}.\ntype ${last(node.qn)} struct {\n${fields.join('\n')}\n}`);
70
+ }
71
+ /** An entity becomes a struct with an ID, a constructor with the defaults, methods for derived fields, and Validate for the invariants. */
72
+ function entitySteps(entity, context) {
73
+ const imports = new Set();
74
+ const name = last(entity.qn);
75
+ const receiver = name.charAt(0).toLowerCase();
76
+ const scope = goScope(entity, context, imports);
77
+ const fields = fieldsOf(entity, context);
78
+ const stored = fields.filter(f => !f.data.derived);
79
+ const lines = [`// ${name} is the entity ${entity.qn}.`, `type ${name} struct {`, '\tID int64 `json:"id"`', ...stored.map(f => `\t${pascal(last(f.qn))} ${typeOf(f.data.type, scope)} \`json:"${last(f.qn)}"\``), '}'];
80
+ const defaults = stored.flatMap(f => {
81
+ const code = defaultValue(f, scope);
82
+ return code ? [`\t\t${pascal(last(f.qn))}: ${code},`] : [];
83
+ });
84
+ lines.push('', `// New${name} returns a new ${name} with the defaults of the model.`, `func New${name}() *${name} {`, `\treturn &${name}{`, ...defaults, '\t}', '}');
85
+ for (const field of fields.filter(f => f.data.derived)) {
86
+ const code = goExpr(field.data.derived, { ...scope, self: receiver });
87
+ if (code)
88
+ lines.push('', `// ${pascal(last(field.qn))} is the derived field ${field.qn}.`, `func (${receiver} *${name}) ${pascal(last(field.qn))}() ${typeOf(field.data.type, scope)} {`, `\treturn ${coerce(code, field)}`, '}');
89
+ }
90
+ const checks = context.children(entity.qn).filter(n => n.kind === 'Invariant').flatMap(invariant => {
91
+ const condition = validation(invariant, context);
92
+ return condition ? [`\tif !(${condition}) {`, `\t\terrs = append(errs, errors.New(${JSON.stringify(String(invariant.data.label))}))`, '\t}'] : [];
93
+ });
94
+ imports.add('errors');
95
+ lines.push('', `// Validate checks the invariants of ${name}.`, `func (${receiver} *${name}) Validate() error {`, '\tvar errs []error', ...checks, '\treturn errors.Join(errs...)', '}');
96
+ return [goFile(entity.module, 'types.go', context, imports, lines.join('\n'))];
97
+ }
98
+ function fieldSteps(field, context) {
99
+ const owner = context.node(parentOf(field.qn));
100
+ if (owner.kind === 'Event' || owner.kind === 'ValueType')
101
+ return [];
102
+ if (owner.kind !== 'Entity')
103
+ return undefined;
104
+ const scope = { ...goScope(owner, context, new Set()), self: 'x' };
105
+ const tasks = [];
106
+ if (field.data.derived && !goExpr(field.data.derived, scope))
107
+ tasks.push(task(`implement the derived field ${last(field.qn)} = ${field.props.derived}`));
108
+ if (field.data.default && !defaultValue(field, scope))
109
+ tasks.push(task(`set the default of ${last(field.qn)} to ${field.props.default} in New${last(owner.qn)}`));
110
+ return tasks;
111
+ }
112
+ function validation(invariant, context) {
113
+ const entity = context.node(parentOf(invariant.qn));
114
+ const name = last(entity.qn);
115
+ return goExpr(invariant.data.condition, { ...goScope(entity, context, new Set()), self: name.charAt(0).toLowerCase() });
116
+ }
117
+ /**
118
+ * An action becomes a function on its entity: preconditions return the declared errors, the transition
119
+ * checks the current state, effects change the record, and emitted events are returned.
120
+ */
121
+ function actionSteps(action, context) {
122
+ const imports = new Set();
123
+ const entity = action.data.entity ? context.node(action.data.entity) : undefined;
124
+ const self = entity ? camel(last(entity.qn)) : undefined;
125
+ const scope = { ...goScope(action, context, imports), self };
126
+ const tasks = [];
127
+ const body = ['var events []any'];
128
+ (action.data.preconditions ?? []).forEach((precondition, i) => {
129
+ const condition = goExpr(precondition.condition, scope);
130
+ const text = action.props.preconditions[i];
131
+ if (!condition) {
132
+ tasks.push(task(`check the precondition ${text} in ${last(action.qn)}`));
133
+ return;
134
+ }
135
+ const error = precondition.error ? errorName(context.node(precondition.error)) : `errors.New(${JSON.stringify(text)})`;
136
+ if (!precondition.error)
137
+ imports.add('errors');
138
+ body.push(`if !(${condition}) {`, `\treturn nil, ${error}`, '}');
139
+ });
140
+ const transitions = context.graph.nodes.filter(n => n.kind === 'Transition' && n.data.action === action.qn);
141
+ if (transitions.length && self)
142
+ body.push(...transitionSwitch(transitions, self, last(action.qn), scope, context, tasks));
143
+ for (const effect of context.children(action.qn).filter(c => c.kind.endsWith('Effect')))
144
+ body.push(...effectLines(effect, self, scope, context, tasks));
145
+ body.push('return events, nil');
146
+ const params = [
147
+ ...(entity ? [`${self} *${last(entity.qn)}`] : []),
148
+ ...context.children(action.qn).filter(c => c.kind === 'Param').map(p => `${camel(last(p.qn))} ${typeOf(p.data.type, scope)}`)
149
+ ];
150
+ const code = [`// ${last(action.qn)} is the action ${action.qn}. It returns the events it emits.`, `func ${last(action.qn)}(${params.join(', ')}) ([]any, error) {`, ...body.map(l => `\t${l}`), '}'].join('\n');
151
+ return [goFile(action.module, 'actions.go', context, imports, code), ...tasks, ...testSteps(action, context)];
152
+ }
153
+ function transitionSwitch(transitions, self, label, scope, context, tasks) {
154
+ const machine = context.node(parentOf(transitions[0].qn));
155
+ const field = context.node(machine.data.field);
156
+ const enumNode = context.node(field.data.type.decl);
157
+ const state = `${self}.${pascal(last(field.qn))}`;
158
+ const lines = ['switch {'];
159
+ for (const transition of transitions) {
160
+ const from = transition.data.from.map(s => `${state} == ${enumConstant(context.node(`${enumNode.qn}.${s}`), scope)}`).join(' || ');
161
+ let condition = from;
162
+ if (transition.data.guard) {
163
+ const guard = goExpr(transition.data.guard, scope);
164
+ if (guard)
165
+ condition = `(${from}) && (${guard})`;
166
+ else
167
+ tasks.push(task(`check the guard ${transition.props.guard} of ${last(transition.qn)}`));
168
+ }
169
+ lines.push(`case ${condition}:`);
170
+ for (const effect of context.children(transition.qn))
171
+ lines.push(...effectLines(effect, self, scope, context, tasks).map(l => `\t${l}`));
172
+ lines.push(`\t${state} = ${enumConstant(context.node(`${enumNode.qn}.${transition.data.to}`), scope)}`);
173
+ }
174
+ scope.imports.add('fmt');
175
+ scope.imports.add(scope.importOf(machine.module));
176
+ const invalid = machine.module.split('.').pop() === scope.pkg ? 'ErrInvalidTransition' : `${machine.module.split('.').pop()}.ErrInvalidTransition`;
177
+ lines.push('default:', `\treturn nil, fmt.Errorf("%w: ${label} from %s", ${invalid}, ${state})`, '}');
178
+ return lines;
179
+ }
180
+ function effectLines(effect, self, scope, context, tasks) {
181
+ if (effect.kind === 'SetEffect') {
182
+ const field = context.node(effect.data.field);
183
+ const value = goExpr(effect.data.value, scope);
184
+ if (!value || !self) {
185
+ tasks.push(task(`apply the effect set ${last(field.qn)} = ${effect.props.value}`));
186
+ return [];
187
+ }
188
+ const code = coerce(value, field);
189
+ return [`${self}.${pascal(last(field.qn))} = ${field.data.type.optional ? `ptr(${code})` : code}`];
190
+ }
191
+ if (effect.kind === 'EmitEffect') {
192
+ const event = context.node(effect.data.event);
193
+ const assignments = (effect.data.assignments ?? []).map(a => [a.name, goExpr(a.value, scope)]);
194
+ if (assignments.some(([, v]) => !v)) {
195
+ tasks.push(task(`emit ${last(event.qn)}`));
196
+ return [];
197
+ }
198
+ return [`events = append(events, ${qualify(event, scope)}{${assignments.map(([n, v]) => `${pascal(n)}: ${v}`).join(', ')}})`];
199
+ }
200
+ tasks.push(task(`apply the effect ${last(effect.qn)}, for example through your storage layer`));
201
+ return [];
202
+ }
203
+ /** Transitions on an event become a function that applies them to the record the event carries. */
204
+ function machineSteps(machine, context) {
205
+ const field = context.node(machine.data.field);
206
+ const entity = context.node(parentOf(field.qn));
207
+ const imports = new Set(['errors']);
208
+ const steps = [goFile(machine.module, 'errors.go', context, imports, `// ErrInvalidTransition is returned when the state does not allow an action.\nvar ErrInvalidTransition = errors.New("invalid transition")`)];
209
+ const byEvent = Map.groupBy(context.children(machine.qn).filter(t => t.kind === 'Transition' && t.data.event), t => t.data.event);
210
+ for (const [eventQn, transitions] of byEvent) {
211
+ const event = context.node(eventQn);
212
+ const carrier = fieldsOf(event, context).find(f => f.data.type.decl === entity.qn);
213
+ if (!carrier) {
214
+ steps.push(task(`apply the transitions of ${last(machine.qn)} on ${last(eventQn)}; the event carries no ${last(entity.qn)}`));
215
+ continue;
216
+ }
217
+ const handlerImports = new Set();
218
+ const scope = { ...goScope(machine, context, handlerImports), self: `event.${pascal(last(carrier.qn))}` };
219
+ const tasks = [];
220
+ const body = ['var events []any', ...transitionSwitch(transitions, scope.self, last(eventQn), scope, context, tasks), 'return events, nil'];
221
+ const name = `${last(machine.qn)}On${last(eventQn)}`;
222
+ steps.push(goFile(machine.module, 'machines.go', context, handlerImports, `// ${name} applies the transitions of ${machine.qn} that ${last(eventQn)} triggers.\nfunc ${name}(event ${qualify(event, scope)}) ([]any, error) {\n${body.map(l => `\t${l}`).join('\n')}\n}`), ...tasks);
223
+ }
224
+ return steps;
225
+ }
226
+ /** A skipped test per case of a rule in the module's test file; writing its body is a registry task. */
227
+ function testSteps(node, context) {
228
+ const name = `Test${pascal(last(parentOf(node.qn)))}${pascal(String(node.data.label ?? last(node.qn)).replace(/[^A-Za-z0-9]+/g, '_'))}`.replace(/_/g, '');
229
+ const code = `func ${name}(t *testing.T) {\n\tt.Skip(${JSON.stringify(`registry task: ${node.qn}`)})\n}`;
230
+ return [goFile(node.module, `${pkgOf(node.module)}_test.go`, context, new Set(['testing']), code), task(`write the test ${name}`)];
231
+ }
232
+ function defaultValue(field, scope) {
233
+ const expr = field.data.default;
234
+ if (!expr)
235
+ return undefined;
236
+ const code = goExpr(expr, scope);
237
+ if (!code)
238
+ return undefined;
239
+ const value = coerce(code, field);
240
+ return field.data.type.optional ? `ptr(${value})` : value;
241
+ }
242
+ /** Number literals assigned to decimal fields become decimals. */
243
+ function coerce(code, field) {
244
+ const type = field.data.type;
245
+ if (!(type.primitive === 'Money' || type.primitive === 'Decimal') || !/^-?[\d.]+$/.test(code))
246
+ return code;
247
+ return code.includes('.') ? `decimal.RequireFromString(${JSON.stringify(code)})` : `decimal.NewFromInt(${code})`;
248
+ }
249
+ function typeOf(type, scope) {
250
+ let base = 'any';
251
+ if (type.primitive) {
252
+ const [name, pkg] = PRIMITIVES[type.primitive];
253
+ if (pkg)
254
+ scope.imports.add(pkg);
255
+ base = name;
256
+ }
257
+ else if (type.decl) {
258
+ const declaration = scope.node(type.decl);
259
+ base = `${declaration.kind === 'Entity' ? '*' : ''}${qualify(declaration, scope)}`;
260
+ }
261
+ if (type.many)
262
+ return `[]${base}`;
263
+ return type.optional && !base.startsWith('*') ? `*${base}` : base;
264
+ }
265
+ function goScope(node, context, imports) {
266
+ return { node: context.node, pkg: pkgOf(node.module || node.qn), imports, importOf: module => importPath(module, context) };
267
+ }
268
+ /** Adds a block to a Go file of a module's package, merging its imports; gofmt formats the result at the end. */
269
+ function goFile(module, file, context, imports, block) {
270
+ const pkg = pkgOf(module);
271
+ const own = importPath(module, context);
272
+ return {
273
+ kind: 'template', file: `${dirOf(module)}/${file}`, write: existing => {
274
+ const text = existing ?? `package ${pkg}\n`;
275
+ const match = /^package \w+\n(?:\nimport \(\n([\s\S]*?)\n\)\n)?/.exec(text);
276
+ const current = (match[1] ?? '').split('\n').map(l => l.trim().replace(/"/g, '')).filter(Boolean);
277
+ const all = [...new Set([...current, ...imports])].filter(i => i !== own).sort((a, b) => Number(a.includes('.')) - Number(b.includes('.')) || a.localeCompare(b));
278
+ const header = `package ${pkg}\n${all.length ? `\nimport (\n${all.map(i => `\t"${i}"`).join('\n')}\n)\n` : ''}`;
279
+ return `${header}${text.slice(match[0].length).replace(/\s+$/, '')}\n\n${block}\n`;
280
+ }
281
+ };
282
+ }
283
+ function fieldsOf(node, context) {
284
+ return context.children(node.qn).filter(c => c.kind === 'Field');
285
+ }
286
+ function importPath(module, context) {
287
+ return `${context.name}/${dirOf(module)}`;
288
+ }
289
+ function dirOf(module) {
290
+ return ['internal', ...module.split('.')].join('/');
291
+ }
292
+ function pkgOf(module) {
293
+ return module.split('.').pop();
294
+ }
295
+ function errorName(error) {
296
+ return `Err${pascal(last(error.qn))}`;
297
+ }
298
+ function parentOf(qn) {
299
+ return qn.slice(0, qn.lastIndexOf('.'));
300
+ }
301
+ function last(qn) {
302
+ return qn.slice(qn.lastIndexOf('.') + 1);
303
+ }
304
+ function task(what) {
305
+ return { kind: 'task', what };
306
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@appling/codegen-go",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Appling code generation extension for Go",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./out/index.d.ts",
9
+ "default": "./out/index.js"
10
+ }
11
+ },
12
+ "files": [
13
+ "out"
14
+ ],
15
+ "dependencies": {
16
+ "@appling/model": "0.1.1"
17
+ },
18
+ "peerDependencies": {
19
+ "@appling/codegen": "0.1.1"
20
+ },
21
+ "devDependencies": {
22
+ "@appling/codegen": "0.1.1",
23
+ "@types/node": "^24.19.2",
24
+ "typescript": "7.0.2"
25
+ },
26
+ "license": "MIT",
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "scripts": {
31
+ "build": "tsc"
32
+ }
6
33
  }