# Action lifecycle hooks, result extension and administrator guards

> Exercise oninput, onoutput, extend, sa and su with valid, invalid and failed actions.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: en
Content-SHA256: 96d006ef7a49b5e38bca290fca66dc60e4ee9d0bd9b5924585c9a2bbf2646d17
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`oninput($)` runs after input validation and declared middleware, immediately before the action function. `onoutput(error,response,$)` runs on the successful completion path after output filtering and optional extension. In 0.0.19 an invalid input or `$.invalid()` does not call this hook; do not treat it as a universal error/finally hook.

`extend:'result'` adds the action result to its validated input under that key and returns the extended input. A dotted path uses nested assignment. It is useful for deliberate action composition; it changes the public response contract.

Either `sa:true` or `su:true` requires a user with either administrator flag. They do not define two different privilege tiers. Normal permissions checks remain separate. Set these administrator flags only from trusted server authentication.

```js definitions/hooks.js
MAIN.hooks = [];
AUTH(function($) {
	var role = $.headers['x-demo-role'];
	if (role === 'sa' || role === 'su') $.success({ id:'admin', [role]:true });
	else if (role === 'member') $.success({id:'member'});
	else $.invalid();
});
NEWACTION('Hooks|extend', {
	input: '*name:String',
	extend: 'result',
	oninput: function($) { MAIN.hooks.push('input:' + $.payload.name); },
	onoutput: function(err, response) { MAIN.hooks.push('output:' + response.result.greeting); },
	action: function($, model) { $.callback({greeting:'Hello ' + model.name}); }
});
NEWACTION('Hooks|fail', {
	onoutput: function() { MAIN.hooks.push('unexpected'); },
	action: function($) { $.invalid('failed'); }
});
for (var flag of ['sa','su']) {
	var action = { action:function($) { $.success(); } };
	action[flag] = true;
	NEWACTION('Hooks|' + flag, action);
}
```

```js controllers/hooks.js
exports.install = function() {
	ROUTE('POST /extend/ @json --> Hooks|extend');
	ROUTE('GET /fail/ --> Hooks|fail');
	ROUTE('GET /sa/ --> Hooks|sa');
	ROUTE('GET /su/ --> Hooks|su');
	ROUTE('GET /hook-events/', $ => $.json(MAIN.hooks));
};
```
