@statedelta-actions/actions 0.6.0 → 0.8.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # @statedelta-actions/actions
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - update
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies
12
+ - @statedelta-actions/core@0.6.0
13
+
14
+ ## 0.7.0
15
+
16
+ ### Minor Changes
17
+
18
+ - fc436a7: Add sub-directives descriptor (ADR-029)
19
+
20
+ Handlers can now declare child sub-array fields via `subDirectives` —
21
+ feeds register validation (with `required` throw), normalize, mini-graph
22
+ propagation (async/interactive transitive) and analyzer walks
23
+ (denied-scan, capabilities). `if` and `catch` remain hardcoded with
24
+ their optimizations; descriptor is additive.
25
+
26
+ `HandlerDefinition` and `SubDirectiveFieldConfig` gain inspection
27
+ metadata exposed via `engine.handlerDefinitions`: `description`, `tags`,
28
+ `deprecated`, `since`, `aliasOf` on the handler; `description`,
29
+ `purpose`, `examples`, `tags` on sub-fields.
30
+
31
+ The analyzer's `IAnalyzableEngine` interface gains
32
+ `subDirectiveFieldsForGraph` (consumers implementing it for tests/mocks
33
+ must add the field). Bug fix bundled: denied-scan and capabilities walk
34
+ now recurse into `if.then`/`if.else` (previously only `catch`).
35
+
36
+ New `validate` script (`pnpm typecheck && pnpm lint`) on both packages.
37
+
3
38
  ## 0.6.0
4
39
 
5
40
  ### Minor Changes
package/README.md CHANGED
@@ -131,6 +131,123 @@ const handlers = {
131
131
  | `execute` | Runtime | Processa a diretiva e retorna resultado |
132
132
  | `analyze` | — | Consumido pelo `ActionAnalyzer` externo, não pelo engine |
133
133
  | `async` (flag) | Construct | Marca handler como assíncrono (opt-in explícito) |
134
+ | `subDirectives` | Register | Declara campos com sub-arrays que entram no grafo |
135
+
136
+ ### Sub-Directives — handlers com filhos no grafo
137
+
138
+ Handlers customizados podem ter **sub-arrays de diretivas** que participam do grafo de análise (deps, async/interactive transitivo, denied-scan, capabilities). Em vez de o engine hardcodear nomes como `then`/`else`/`catch`, o handler declara explicitamente quais campos da sua diretiva são sub-blocos:
139
+
140
+ ```typescript
141
+ const handlers = {
142
+ simulate: {
143
+ subDirectives: {
144
+ directives: { required: true },
145
+ },
146
+ execute(d, frame, engine) {
147
+ beginTransaction(frame.ctx);
148
+ const r = engine.runDirectives(d.directives, frame);
149
+ if (!r.success) rollback(frame.ctx);
150
+ else commit(frame.ctx);
151
+ return { ok: r.success, data: r.data };
152
+ },
153
+ },
154
+
155
+ try_: {
156
+ subDirectives: {
157
+ body: { required: true },
158
+ catch: { required: false },
159
+ finally: { required: false },
160
+ },
161
+ execute(d, frame, engine) {
162
+ const r = engine.runDirectives(d.body, frame);
163
+ if (!r.success && d.catch) {
164
+ frame.scope.$exception = r.errors[0]?.message;
165
+ engine.runDirectives(d.catch, frame);
166
+ }
167
+ if (d.finally) engine.runDirectives(d.finally, frame);
168
+ return { ok: r.success, data: r.data };
169
+ },
170
+ },
171
+ };
172
+ ```
173
+
174
+ Uso na action:
175
+
176
+ ```typescript
177
+ engine.register([{
178
+ id: "checkout",
179
+ directives: [
180
+ {
181
+ type: "simulate",
182
+ directives: [ // ← entra no grafo
183
+ { type: "action", id: "charge" }, // edge: checkout → charge
184
+ { type: "fetchUserAsync", id: 1 }, // checkout vira async transitivo
185
+ ],
186
+ },
187
+ ],
188
+ }]);
189
+ ```
190
+
191
+ **Comportamento estrutural:**
192
+
193
+ | Campo | Default | Efeito |
194
+ |-------|---------|--------|
195
+ | `required: true` | — | Campo ausente ou não-array → throw em register-time |
196
+ | `required: false` | ✓ | Campo ausente é tratado como `[]` silenciosamente |
197
+ | `graph: true` | ✓ | Sub-array participa de mini-graph e walks do analyzer |
198
+ | `graph: false` | — | Sub-array é validado estruturalmente mas NÃO conta como path de execução (ex: campos de metadata/preview) |
199
+
200
+ **Importante:**
201
+ - O descritor é **puramente estrutural** — não interfere na execução. O handler `execute` decide se, quando e como rodar os sub-blocos via `engine.runDirectives` / `runDirectivesAsync`.
202
+ - `if` e `catch` permanecem hardcoded — primitivas do engine com otimizações específicas. O novo descritor é **aditivo**.
203
+ - Sub-directives são **propagadas transitivamente**: action que usa `simulate` cujo sub-bloco invoca handler async automaticamente vira async — `engine.isActionAsync("checkout")` retorna `true`.
204
+
205
+ ### Inspection metadata
206
+
207
+ Tanto o `HandlerDefinition` quanto cada `SubDirectiveFieldConfig` aceitam campos de inspeção opcionais — zero custo runtime, expostos via `engine.handlerDefinitions` accessor pra tooling, DSL JSON externo, IDE hover docs, documentação auto-gerada:
208
+
209
+ ```typescript
210
+ const try_: HandlerDefinition = {
211
+ description: "Executa body; em falha executa catch; finally roda sempre.",
212
+ tags: ["control-flow", "error-handling"],
213
+ since: "0.5.0",
214
+ // deprecated: "use 'tryAsync' since v0.6",
215
+ // aliasOf: "tryAsync",
216
+
217
+ subDirectives: {
218
+ body: {
219
+ required: true,
220
+ purpose: "body",
221
+ description: "Diretivas tentadas. Falha dispara catch.",
222
+ examples: [[{ type: "action", id: "charge" }]],
223
+ tags: ["execution"],
224
+ },
225
+ catch: {
226
+ required: false,
227
+ purpose: "catch",
228
+ description: "Diretivas executadas em falha. scope.$exception disponível.",
229
+ },
230
+ finally: {
231
+ required: false,
232
+ purpose: "finalizer",
233
+ },
234
+ },
235
+
236
+ execute(d, frame, engine) { /* ... */ },
237
+ };
238
+ ```
239
+
240
+ Campos suportados:
241
+
242
+ | Campo | Nível | Tipo | Uso típico |
243
+ |-------|-------|------|-----------|
244
+ | `description` | handler + sub-campo | `string` | Hover docs em IDE, descoberta de esquema por DSL |
245
+ | `tags` | handler + sub-campo | `string[]` | Categorização cruzada, filtros |
246
+ | `purpose` | sub-campo | `string` | Label semântico (`"body"`, `"catch"`, `"branch"`, `"finalizer"`, `"metadata"`, custom) |
247
+ | `examples` | sub-campo | `Directive[][]` | DSL/IDE autocomplete, docs auto-geradas |
248
+ | `deprecated` | handler | `boolean \| string` | Marca obsolescência, mensagem de migração |
249
+ | `since` | handler | `string` | Versionamento (semver ou livre) |
250
+ | `aliasOf` | handler | `string` | Declara alias semântico de outro handler |
134
251
 
135
252
  ### Handlers Async
136
253
 
@@ -388,6 +505,10 @@ engine.getActionDefinition("heal"); // ActionDefinition | undefined
388
505
  // Campo de tipo pra dispatch de diretivas
389
506
  engine.typeField; // string (default: "type")
390
507
 
508
+ // Map `type → readonly fieldNames[]` dos campos de sub-directives no grafo
509
+ // (HandlerDefinition.subDirectives com graph !== false; "catch" filtrado)
510
+ engine.subDirectiveFieldsForGraph; // ReadonlyMap<string, readonly string[]>
511
+
391
512
  // Mapa de permissões de diretivas (computado no boot, imutável)
392
513
  engine.directivePermissions; // ReadonlyMap<string, DirectivePermission>
393
514
 
@@ -598,6 +719,7 @@ import type {
598
719
  HandlerDefinition,
599
720
  HandlerAnalysis,
600
721
  ValidationResult,
722
+ SubDirectiveFieldConfig,
601
723
  HandlerInput,
602
724
  HandlerInputMap,
603
725
  ActionDefinition,
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
- 'use strict';var core=require('@statedelta-actions/core');function Ae(s,e){let r;for(;;){let i=s.next(r);if(i.done)return i.value;r=e?e(i.value):void 0;}}async function Re(s,e){let r;for(;;){let i=await s.next(r);if(i.done)return i.value;r=e?await e(i.value):void 0;}}function Ie(s){let e=0;return ()=>{if(!(e>=s.length))return s[e++]}}var j=class{_listeners=new Map;on(e,r){let i=this._listeners.get(e);i||(i=new Set,this._listeners.set(e,i)),i.add(r);let o=false;return ()=>{o||(o=true,i.delete(r),i.size===0&&this._listeners.delete(e));}}once(e,r){let i=this.on(e,o=>{i(),r(o);});return i}emit(e,r){let i=this._listeners.get(e);if(!i||i.size===0)return;let o=[...i];for(let t=0;t<o.length;t++)try{o[t](r);}catch(n){console.error(`[SimpleEmitter] Listener error on "${e}":`,n);}}listenerCount(e){return this._listeners.get(e)?.size??0}hasListeners(e){let r=this._listeners.get(e);return r!==void 0&&r.size>0}off(e){this._listeners.delete(e);}removeAllListeners(){this._listeners.clear();}};var L=new Set(["const","let","return","throw","pause","if"]);function ue(s,e,r,i){let o=[];return X(s.directives,e,r,i,"directive",o,s.id),o}function X(s,e,r,i,o,t,n){for(let a=0;a<s.length;a++){let d=s[a],f=d[i],x=`${o}[${a}]`;if(!f){t.push(`${x}: missing type field "${i}"`);continue}if(f==="if"){let l=d.cond;typeof l!="function"&&typeof l!="boolean"&&t.push(`${x}: "if" requires cond as function or boolean`);let _=d.then;Array.isArray(_)?X(_,e,r,i,`${x}.then`,t,n):t.push(`${x}: "if" requires then as array`);let m=d.else;m!==void 0&&(Array.isArray(m)?X(m,e,r,i,`${x}.else`,t,n):t.push(`${x}.else: must be array`));continue}if(L.has(f))continue;if(!e[f])throw new Error(`Action "${n}" ${x}: no handler registered for type "${f}". Register the handler in createActionEngine({ handlers }) before registering this action.`);let C=r.get(f);if(C?.validate)try{let l=C.validate(d);l&&!l.valid&&t.push(`${x}: ${l.error??"validation failed"}`);}catch(l){t.push(`${x}: validate threw: ${l}`);}let y=d.catch;if(y&&Array.isArray(y))for(let l=0;l<y.length;l++){let m=y[l][i];if(!(m&&L.has(m))&&m&&!e[m])throw new Error(`Action "${n}" ${x}.catch[${l}]: no handler registered for type "${m}". Register the handler in createActionEngine({ handlers }) before registering this action.`)}}}function N(s,e){let r=s.length,i=new Array(r);for(let o=0;o<r;o++){let t=s[o],n=t[e],a=t,d=false,f=t.catch;if(Array.isArray(f)&&f.length>0&&(a={...a,catch:N(f,e)},d=true),n==="if"){let x=t.then;Array.isArray(x)&&x.length>0&&(a={...a,then:N(x,e)},d=true);let C=t.else;Array.isArray(C)&&C.length>0&&(a={...a,else:N(C,e)},d=true);}i[o]=d?a:t;}return i}function z(s,e,r,i,o,t,n){return {success:false,aborted:true,abortedBy:s,appliedCount:e,skippedCount:r,errors:i,processedCount:o,totalCount:t,counters:n}}function ke(s){let e=s.filledNames.has("beforeDirective"),r=s.filledNames.has("afterDirective"),i=s.filledNames.has("onDirectivesComplete");return function(t,n,a,d,f,x,C){let y=Math.min(t.length,C),l=[],_=0,m=0,{counters:p,scope:A}=n,$=n.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],k=0;for(;w.length>0;){let R=w[w.length-1];if(R.i>=R.len){w.pop();continue}let T=R.i++,S=R.topLevelIfIndex!==-1,b=S?R.topLevelIfIndex:T;S||(k=T+1);let h=R.dirs[T],E=h[f];if(E==="const"||E==="let"){let c=h.name;if(typeof h.resolve=="function")try{A[c]=h.resolve($,A).value;}catch(u){l.push({directiveIndex:b,error:`Binding resolve: ${u}`}),p.errors++;}else A[c]=h.value;continue}if(E==="return"){let c=k;if(typeof h.resolve=="function")try{let u=h.resolve($,A),v="value"in u?u.value:"return"in u?u.return:h.value;return {success:!0,aborted:!1,appliedCount:_,skippedCount:m,errors:l,processedCount:c,totalCount:y,counters:p,data:v}}catch(u){l.push({directiveIndex:b,error:`Control resolve: ${u}`}),p.errors++;}else return {success:true,aborted:false,appliedCount:_,skippedCount:m,errors:l,processedCount:c,totalCount:y,counters:p,data:h.value};continue}if(E==="throw"){let c=k;if(typeof h.resolve=="function")try{let u=h.resolve($,A),v="message"in u?u.message:"throw"in u?u.throw:h.message;return {success:!1,aborted:!0,abortedBy:"throw",appliedCount:_,skippedCount:m,errors:l,processedCount:c,totalCount:y,counters:p,data:v}}catch(u){l.push({directiveIndex:b,error:`Control resolve: ${u}`}),p.errors++;}else return {success:false,aborted:true,abortedBy:"throw",appliedCount:_,skippedCount:m,errors:l,processedCount:c,totalCount:y,counters:p,data:h.message};continue}if(E==="if"){let c;try{let v=h.cond;c=typeof v=="function"?!!v($,A):!!v;}catch(v){l.push({directiveIndex:b,error:`if cond: ${v}`}),p.errors++;continue}let u=c?h.then:h.else;if(Array.isArray(u)&&u.length>0){let v=Math.min(u.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:u,i:0,len:v,topLevelIfIndex:G});}continue}let g=h,I=n;if(e)try{let c=core.processIntercept(d.beforeDirective(g,n),"beforeDirective");if(c.action===core.Intercept.SKIP){m++,p.directivesSkipped++;continue}if(c.action===core.Intercept.ABORT)return z(c.abortReason,_,m,l,k===0?T:k-1,y,p);c.ctx!==void 0&&(I=n.withCtx(c.ctx)),c.directive!==void 0&&(g=c.directive);}catch(c){l.push({directiveIndex:b,error:`Hook beforeDirective: ${c}`}),p.errors++;}if(typeof g.resolve=="function")try{let c=g.resolve(I.ctx,I.scope);g={...g,...c};}catch(c){l.push({directiveIndex:b,error:`Directive resolve: ${c}`}),p.errors++;continue}let F=g[f],M=F?a[F]:void 0;if(!M){l.push({directiveIndex:b,error:`No handler for directive type: ${F??"undefined"}`}),p.errors++;continue}let D;try{D=M(g,I,x);}catch(c){D={ok:false,error:String(c)};}let H=k;if(D.ok){if(_++,p.directivesApplied++,typeof g.as=="string"&&(A[g.as]=D.data),D.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:_,skippedCount:m,errors:l,processedCount:H,totalCount:y,counters:p,data:D.data}}else {if(D.halt)return {success:false,aborted:true,abortedBy:"halt",appliedCount:_,skippedCount:m,errors:l,processedCount:H,totalCount:y,counters:p,data:D.data};let c=g.catch;if(Array.isArray(c)&&c.length>0){A.$exception=D.error??"handler failed";let u=x.runDirectives(c,I);_+=u.appliedCount;for(let v=0;v<u.errors.length;v++)l.push(u.errors[v]);if(u.aborted)return {success:u.success,aborted:true,abortedBy:u.abortedBy,appliedCount:_,skippedCount:m,errors:l,processedCount:H,totalCount:y,counters:p,data:u.data}}else l.push({directiveIndex:b,error:D.error??"handler failed"}),p.errors++;}if(r)try{if(d.afterDirective(g,D,I)==="abort")return z("afterDirective",_,m,l,H,y,p)}catch(c){l.push({directiveIndex:b,error:`Hook afterDirective: ${c}`}),p.errors++;}}let P={success:true,aborted:false,appliedCount:_,skippedCount:m,errors:l,processedCount:y,totalCount:y,counters:p};if(i)try{d.onDirectivesComplete(P);}catch{}return P}}function Ee(s){let e=s.filledNames.has("beforeDirective"),r=s.filledNames.has("afterDirective"),i=s.filledNames.has("onDirectivesComplete");return async function(t,n,a,d,f,x,C){let y=Math.min(t.length,C),l=[],_=0,m=0,{counters:p,scope:A}=n,$=n.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],k=0;for(;w.length>0;){let R=w[w.length-1];if(R.i>=R.len){w.pop();continue}let T=R.i++,S=R.topLevelIfIndex!==-1,b=S?R.topLevelIfIndex:T;S||(k=T+1);let h=R.dirs[T],E=h[f];if(E==="const"||E==="let"){let c=h.name;if(typeof h.resolve=="function")try{A[c]=h.resolve($,A).value;}catch(u){l.push({directiveIndex:b,error:`Binding resolve: ${u}`}),p.errors++;}else A[c]=h.value;continue}if(E==="return"){let c=k;if(typeof h.resolve=="function")try{let u=h.resolve($,A),v="value"in u?u.value:"return"in u?u.return:h.value;return {success:!0,aborted:!1,appliedCount:_,skippedCount:m,errors:l,processedCount:c,totalCount:y,counters:p,data:v}}catch(u){l.push({directiveIndex:b,error:`Control resolve: ${u}`}),p.errors++;}else return {success:true,aborted:false,appliedCount:_,skippedCount:m,errors:l,processedCount:c,totalCount:y,counters:p,data:h.value};continue}if(E==="throw"){let c=k;if(typeof h.resolve=="function")try{let u=h.resolve($,A),v="message"in u?u.message:"throw"in u?u.throw:h.message;return {success:!1,aborted:!0,abortedBy:"throw",appliedCount:_,skippedCount:m,errors:l,processedCount:c,totalCount:y,counters:p,data:v}}catch(u){l.push({directiveIndex:b,error:`Control resolve: ${u}`}),p.errors++;}else return {success:false,aborted:true,abortedBy:"throw",appliedCount:_,skippedCount:m,errors:l,processedCount:c,totalCount:y,counters:p,data:h.message};continue}if(E==="if"){let c;try{let v=h.cond;c=typeof v=="function"?!!v($,A):!!v;}catch(v){l.push({directiveIndex:b,error:`if cond: ${v}`}),p.errors++;continue}let u=c?h.then:h.else;if(Array.isArray(u)&&u.length>0){let v=Math.min(u.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:u,i:0,len:v,topLevelIfIndex:G});}continue}let g=h,I=n;if(e)try{let c=core.processIntercept(await d.beforeDirective(g,n),"beforeDirective");if(c.action===core.Intercept.SKIP){m++,p.directivesSkipped++;continue}if(c.action===core.Intercept.ABORT)return z(c.abortReason,_,m,l,k===0?T:k-1,y,p);c.ctx!==void 0&&(I=n.withCtx(c.ctx)),c.directive!==void 0&&(g=c.directive);}catch(c){l.push({directiveIndex:b,error:`Hook beforeDirective: ${c}`}),p.errors++;}if(typeof g.resolve=="function")try{let c=g.resolve(I.ctx,I.scope);g={...g,...c};}catch(c){l.push({directiveIndex:b,error:`Directive resolve: ${c}`}),p.errors++;continue}let F=g[f],M=F?a[F]:void 0;if(!M){l.push({directiveIndex:b,error:`No handler for directive type: ${F??"undefined"}`}),p.errors++;continue}let D;try{D=await M(g,I,x);}catch(c){D={ok:false,error:String(c)};}let H=k;if(D.ok){if(_++,p.directivesApplied++,typeof g.as=="string"&&(A[g.as]=D.data),D.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:_,skippedCount:m,errors:l,processedCount:H,totalCount:y,counters:p,data:D.data}}else {if(D.halt)return {success:false,aborted:true,abortedBy:"halt",appliedCount:_,skippedCount:m,errors:l,processedCount:H,totalCount:y,counters:p,data:D.data};let c=g.catch;if(Array.isArray(c)&&c.length>0){A.$exception=D.error??"handler failed";let u=await x.runDirectivesAsync(c,I);_+=u.appliedCount;for(let v=0;v<u.errors.length;v++)l.push(u.errors[v]);if(u.aborted)return {success:u.success,aborted:true,abortedBy:u.abortedBy,appliedCount:_,skippedCount:m,errors:l,processedCount:H,totalCount:y,counters:p,data:u.data}}else l.push({directiveIndex:b,error:D.error??"handler failed"}),p.errors++;}if(r)try{if(await d.afterDirective(g,D,I)==="abort")return z("afterDirective",_,m,l,H,y,p)}catch(c){l.push({directiveIndex:b,error:`Hook afterDirective: ${c}`}),p.errors++;}}let P={success:true,aborted:false,appliedCount:_,skippedCount:m,errors:l,processedCount:y,totalCount:y,counters:p};if(i)try{await d.onDirectivesComplete(P);}catch{}return P}}function U(s,e){return e?Ee(s):ke(s)}function B(s,e,r,i,o,t,n,a){return {success:false,aborted:true,abortedBy:s,appliedCount:e,skippedCount:r,errors:i,processedCount:o,totalCount:t,counters:n,data:a}}function fe(s){if(s===null||typeof s!="object")return null;if(typeof s.next=="function")return s;let e=s.iterator;return e!=null&&typeof e=="object"&&typeof e.next=="function"?e:null}function we(s){let e=s.filledNames.has("beforeDirective"),r=s.filledNames.has("afterDirective"),i=s.filledNames.has("onDirectivesComplete");return function*(t,n,a,d,f,x,C){let y=Math.min(t.length,C),l=[],_=0,m=0,{counters:p,scope:A}=n,$=n.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],k=0;for(;w.length>0;){let R=w[w.length-1];if(R.i>=R.len){w.pop();continue}let T=R.i++,S=R.topLevelIfIndex!==-1,b=S?R.topLevelIfIndex:T;S||(k=T+1);let h=R.dirs[T],E=h[f];if(E==="const"||E==="let"){let c=h.name;if(typeof h.resolve=="function")try{A[c]=h.resolve($,A).value;}catch(u){l.push({directiveIndex:b,error:`Binding resolve: ${u}`}),p.errors++;}else A[c]=h.value;continue}if(E==="return"){let c=k,u=h.value;if(typeof h.resolve=="function")try{let v=h.resolve($,A);u="value"in v?v.value:"return"in v?v.return:u;}catch(v){l.push({directiveIndex:b,error:`Control resolve: ${v}`}),p.errors++;continue}return {success:true,aborted:false,appliedCount:_,skippedCount:m,errors:l,processedCount:c,totalCount:y,counters:p,data:u}}if(E==="throw"){let c=k,u=h.message;if(typeof h.resolve=="function")try{let v=h.resolve($,A);u="message"in v?v.message:"throw"in v?v.throw:u;}catch(v){l.push({directiveIndex:b,error:`Control resolve: ${v}`}),p.errors++;continue}return B("throw",_,m,l,c,y,p,u)}if(E==="pause"){let c=k,u=yield {source:"pause",directive:h,frame:n,index:b,payload:{message:h.message}};if(u===false||u==="abort"||u==="cancel")return B("pause",_,m,l,c,y,p,u);_++,p.directivesApplied++,typeof h.as=="string"&&u!==void 0&&(A[h.as]=u);continue}if(E==="if"){let c;try{let v=h.cond;c=typeof v=="function"?!!v($,A):!!v;}catch(v){l.push({directiveIndex:b,error:`if cond: ${v}`}),p.errors++;continue}let u=c?h.then:h.else;if(Array.isArray(u)&&u.length>0){let v=Math.min(u.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:u,i:0,len:v,topLevelIfIndex:G});}continue}let g=h,I=n;if(e)try{let c=core.processIntercept(d.beforeDirective(g,n),"beforeDirective");if(c.action===core.Intercept.SKIP){m++,p.directivesSkipped++;continue}if(c.action===core.Intercept.ABORT)return B(c.abortReason,_,m,l,k===0?T:k-1,y,p);c.ctx!==void 0&&(I=n.withCtx(c.ctx)),c.directive!==void 0&&(g=c.directive);}catch(c){l.push({directiveIndex:b,error:`Hook beforeDirective: ${c}`}),p.errors++;}if(typeof g.resolve=="function")try{let c=g.resolve(I.ctx,I.scope);g={...g,...c};}catch(c){l.push({directiveIndex:b,error:`Directive resolve: ${c}`}),p.errors++;continue}let F=g[f],M=F?a[F]:void 0;if(!M){l.push({directiveIndex:b,error:`No handler for directive type: ${F??"undefined"}`}),p.errors++;continue}let D;try{let c=M(g,I,x),u=fe(c);u!==null?D=yield*u:D=c;}catch(c){D={ok:false,error:String(c)};}let H=k;if(D.ok){if(_++,p.directivesApplied++,typeof g.as=="string"&&(A[g.as]=D.data),D.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:_,skippedCount:m,errors:l,processedCount:H,totalCount:y,counters:p,data:D.data}}else {if(D.halt)return B("halt",_,m,l,H,y,p,D.data);let c=g.catch;if(Array.isArray(c)&&c.length>0){A.$exception=D.error??"handler failed";let u=x.runDirectives(c,I);_+=u.appliedCount;for(let v=0;v<u.errors.length;v++)l.push(u.errors[v]);if(u.aborted)return {success:u.success,aborted:true,abortedBy:u.abortedBy,appliedCount:_,skippedCount:m,errors:l,processedCount:H,totalCount:y,counters:p,data:u.data}}else l.push({directiveIndex:b,error:D.error??"handler failed"}),p.errors++;}if(r)try{if(d.afterDirective(g,D,I)==="abort")return B("afterDirective",_,m,l,H,y,p)}catch(c){l.push({directiveIndex:b,error:`Hook afterDirective: ${c}`}),p.errors++;}}let P={success:true,aborted:false,appliedCount:_,skippedCount:m,errors:l,processedCount:y,totalCount:y,counters:p};if(i)try{d.onDirectivesComplete(P);}catch{}return P}}function Te(s){let e=s.filledNames.has("beforeDirective"),r=s.filledNames.has("afterDirective"),i=s.filledNames.has("onDirectivesComplete");return async function*(t,n,a,d,f,x,C){let y=Math.min(t.length,C),l=[],_=0,m=0,{counters:p,scope:A}=n,$=n.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],k=0;for(;w.length>0;){let R=w[w.length-1];if(R.i>=R.len){w.pop();continue}let T=R.i++,S=R.topLevelIfIndex!==-1,b=S?R.topLevelIfIndex:T;S||(k=T+1);let h=R.dirs[T],E=h[f];if(E==="const"||E==="let"){let c=h.name;if(typeof h.resolve=="function")try{A[c]=h.resolve($,A).value;}catch(u){l.push({directiveIndex:b,error:`Binding resolve: ${u}`}),p.errors++;}else A[c]=h.value;continue}if(E==="return"){let c=k,u=h.value;if(typeof h.resolve=="function")try{let v=h.resolve($,A);u="value"in v?v.value:"return"in v?v.return:u;}catch(v){l.push({directiveIndex:b,error:`Control resolve: ${v}`}),p.errors++;continue}return {success:true,aborted:false,appliedCount:_,skippedCount:m,errors:l,processedCount:c,totalCount:y,counters:p,data:u}}if(E==="throw"){let c=k,u=h.message;if(typeof h.resolve=="function")try{let v=h.resolve($,A);u="message"in v?v.message:"throw"in v?v.throw:u;}catch(v){l.push({directiveIndex:b,error:`Control resolve: ${v}`}),p.errors++;continue}return B("throw",_,m,l,c,y,p,u)}if(E==="pause"){let c=k,u=yield {source:"pause",directive:h,frame:n,index:b,payload:{message:h.message}};if(u===false||u==="abort"||u==="cancel")return B("pause",_,m,l,c,y,p,u);_++,p.directivesApplied++,typeof h.as=="string"&&u!==void 0&&(A[h.as]=u);continue}if(E==="if"){let c;try{let v=h.cond;c=typeof v=="function"?!!v($,A):!!v;}catch(v){l.push({directiveIndex:b,error:`if cond: ${v}`}),p.errors++;continue}let u=c?h.then:h.else;if(Array.isArray(u)&&u.length>0){let v=Math.min(u.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:u,i:0,len:v,topLevelIfIndex:G});}continue}let g=h,I=n;if(e)try{let c=core.processIntercept(await d.beforeDirective(g,n),"beforeDirective");if(c.action===core.Intercept.SKIP){m++,p.directivesSkipped++;continue}if(c.action===core.Intercept.ABORT)return B(c.abortReason,_,m,l,k===0?T:k-1,y,p);c.ctx!==void 0&&(I=n.withCtx(c.ctx)),c.directive!==void 0&&(g=c.directive);}catch(c){l.push({directiveIndex:b,error:`Hook beforeDirective: ${c}`}),p.errors++;}if(typeof g.resolve=="function")try{let c=g.resolve(I.ctx,I.scope);g={...g,...c};}catch(c){l.push({directiveIndex:b,error:`Directive resolve: ${c}`}),p.errors++;continue}let F=g[f],M=F?a[F]:void 0;if(!M){l.push({directiveIndex:b,error:`No handler for directive type: ${F??"undefined"}`}),p.errors++;continue}let D;try{let c=await M(g,I,x),u=fe(c);u!==null?D=yield*u:D=c;}catch(c){D={ok:false,error:String(c)};}let H=k;if(D.ok){if(_++,p.directivesApplied++,typeof g.as=="string"&&(A[g.as]=D.data),D.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:_,skippedCount:m,errors:l,processedCount:H,totalCount:y,counters:p,data:D.data}}else {if(D.halt)return B("halt",_,m,l,H,y,p,D.data);let c=g.catch;if(Array.isArray(c)&&c.length>0){A.$exception=D.error??"handler failed";let u=await x.runDirectivesAsync(c,I);_+=u.appliedCount;for(let v=0;v<u.errors.length;v++)l.push(u.errors[v]);if(u.aborted)return {success:u.success,aborted:true,abortedBy:u.abortedBy,appliedCount:_,skippedCount:m,errors:l,processedCount:H,totalCount:y,counters:p,data:u.data}}else l.push({directiveIndex:b,error:D.error??"handler failed"}),p.errors++;}if(r)try{if(await d.afterDirective(g,D,I)==="abort")return B("afterDirective",_,m,l,H,y,p)}catch(c){l.push({directiveIndex:b,error:`Hook afterDirective: ${c}`}),p.errors++;}}let P={success:true,aborted:false,appliedCount:_,skippedCount:m,errors:l,processedCount:y,totalCount:y,counters:p};if(i)try{await d.onDirectivesComplete(P);}catch{}return P}}function Z(s,e){return e?Te(s):we(s)}function ee(s,e=s.hasAnyAsync){let{filledNames:r}=s,i=x=>r.has(x),o=x=>s.asyncNames.has(x)?"await ":"",t=e?"await ":"",n=[];for(let x of r)n.push(`const ${x} = directiveHooks.${x};`);n.push("const len = Math.min(directives.length, maxDirectives);"),n.push("const errors = []; let appliedCount = 0; let skippedCount = 0;"),n.push("const counters = frame.counters;"),n.push("for (let i = 0; i < len; i++) {"),n.push(" let directive = directives[i];"),i("beforeDirective")?(n.push(" let _df = frame;"),n.push(" try {"),n.push(` const _bd = ${o("beforeDirective")}beforeDirective(directive, frame);`),n.push(' if (_bd === "skip") { skippedCount++; counters.directivesSkipped++; continue; }'),n.push(' if (_bd === "abort") return { success: false, aborted: true, abortedBy: "beforeDirective", appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),n.push(' if (typeof _bd === "object" && _bd !== null) {'),n.push(' if ("abort" in _bd) return { success: false, aborted: true, abortedBy: _bd.abort, appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),n.push(' if ("ctx" in _bd) _df = frame.withCtx(_bd.ctx);'),n.push(' if ("directive" in _bd) directive = _bd.directive;'),n.push(" }"),n.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook beforeDirective: " + _e }); counters.errors++; }')):n.push(" const _df = frame;"),n.push(' if (typeof directive.resolve === "function") {'),n.push(" try { const _r = directive.resolve(_df.ctx); directive = Object.assign({}, directive, _r); }"),n.push(' catch (_e) { errors.push({ directiveIndex: i, error: "Directive resolve: " + _e }); counters.errors++; continue; }'),n.push(" }"),n.push(" const _type = directive[typeField];"),n.push(" const _handler = _type ? handlers[_type] : undefined;"),n.push(' if (!_handler) { errors.push({ directiveIndex: i, error: "No handler for directive type: " + (_type || "undefined") }); counters.errors++; continue; }'),n.push(" let _result;"),n.push(` try { _result = ${t}_handler(directive, _df, engine); } catch (_e) { errors.push({ directiveIndex: i, error: String(_e) }); counters.errors++; continue; }`),n.push(" if (_result.ok) { appliedCount++; counters.directivesApplied++; }"),n.push(' else { errors.push({ directiveIndex: i, error: _result.error || "handler failed" }); counters.errors++; }'),i("afterDirective")&&(n.push(" try {"),n.push(` const _ad = ${o("afterDirective")}afterDirective(directive, _result, _df);`),n.push(' if (_ad === "abort") return { success: false, aborted: true, abortedBy: "afterDirective", appliedCount, skippedCount, errors, processedCount: i + 1, totalCount: len, counters };'),n.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook afterDirective: " + _e }); counters.errors++; }')),n.push("}"),n.push("const _finalResult = { success: true, aborted: false, appliedCount, skippedCount, errors, processedCount: len, totalCount: len, counters };"),i("onDirectivesComplete")&&n.push(`try { ${o("onDirectivesComplete")}onDirectivesComplete(_finalResult); } catch (_e) {}`),n.push("return _finalResult;");let a=n.join(`
2
- `),d=e?"async ":"";return {fn:new Function("directives","frame","handlers","directiveHooks","typeField","engine","maxDirectives",`"use strict";
3
- return (${d}() => {
1
+ 'use strict';var core=require('@statedelta-actions/core');function We(i,e){let t;for(;;){let r=i.next(t);if(r.done)return r.value;t=e?e(r.value):void 0;}}async function Je(i,e){let t;for(;;){let r=await i.next(t);if(r.done)return r.value;t=e?await e(r.value):void 0;}}function Ye(i){let e=0;return ()=>{if(!(e>=i.length))return i[e++]}}var X=class{_listeners=new Map;on(e,t){let r=this._listeners.get(e);r||(r=new Set,this._listeners.set(e,r)),r.add(t);let o=false;return ()=>{o||(o=true,r.delete(t),r.size===0&&this._listeners.delete(e));}}once(e,t){let r=this.on(e,o=>{r(),t(o);});return r}emit(e,t){let r=this._listeners.get(e);if(!r||r.size===0)return;let o=[...r];for(let n=0;n<o.length;n++)try{o[n](t);}catch(s){console.error(`[SimpleEmitter] Listener error on "${e}":`,s);}}listenerCount(e){return this._listeners.get(e)?.size??0}hasListeners(e){let t=this._listeners.get(e);return t!==void 0&&t.size>0}off(e){this._listeners.delete(e);}removeAllListeners(){this._listeners.clear();}};var N=new Set(["const","let","return","throw","pause","if"]);function ke(i,e,t,r){let o=[];return se(i.directives,e,t,r,"directive",o,i.id),o}function se(i,e,t,r,o,n,s){for(let a=0;a<i.length;a++){let c=i[a],u=c[r],d=`${o}[${a}]`;if(!u){n.push(`${d}: missing type field "${r}"`);continue}if(u==="if"){let g=c.cond;typeof g!="function"&&typeof g!="boolean"&&n.push(`${d}: "if" requires cond as function or boolean`);let A=c.then;Array.isArray(A)?se(A,e,t,r,`${d}.then`,n,s):n.push(`${d}: "if" requires then as array`);let D=c.else;D!==void 0&&(Array.isArray(D)?se(D,e,t,r,`${d}.else`,n,s):n.push(`${d}.else: must be array`));continue}if(N.has(u))continue;if(!e[u])throw new Error(`Action "${s}" ${d}: no handler registered for type "${u}". Register the handler in createActionEngine({ handlers }) before registering this action.`);let h=t.get(u);if(h?.validate)try{let g=h.validate(c);g&&!g.valid&&n.push(`${d}: ${g.error??"validation failed"}`);}catch(g){n.push(`${d}: validate threw: ${g}`);}let f=c.catch;if(f&&Array.isArray(f))for(let g=0;g<f.length;g++){let D=f[g][r];if(!(D&&N.has(D))&&D&&!e[D])throw new Error(`Action "${s}" ${d}.catch[${g}]: no handler registered for type "${D}". Register the handler in createActionEngine({ handlers }) before registering this action.`)}let p=h?.subDirectives;if(p===void 0)continue;let l=Object.keys(p);for(let g=0;g<l.length;g++){let A=l[g];if(A==="catch")continue;let D=c[A];if(D===void 0){if(p[A].required)throw new Error(`Action "${s}" ${d}: handler "${u}" requires sub-directives field "${A}"`);continue}if(!Array.isArray(D))throw new Error(`Action "${s}" ${d}.${A}: must be an array of directives`);se(D,e,t,r,`${d}.${A}`,n,s);}}}var Qe=new Map;function B(i,e,t=Qe){let r=i.length,o=new Array(r);for(let n=0;n<r;n++){let s=i[n],a=s[e],c=s,u=false,d=s.catch;if(Array.isArray(d)&&d.length>0&&(c={...c,catch:B(d,e,t)},u=true),a==="if"){let h=s.then;Array.isArray(h)&&h.length>0&&(c={...c,then:B(h,e,t)},u=true);let f=s.else;Array.isArray(f)&&f.length>0&&(c={...c,else:B(f,e,t)},u=true);}else if(a!==void 0){let h=t.get(a);if(h!==void 0)for(let f=0;f<h.length;f++){let p=h[f],l=s[p];!Array.isArray(l)||l.length===0||(c={...c,[p]:B(l,e,t)},u=true);}}o[n]=u?c:s;}return o}function Ee(i,e,t,r,o,n,s){let a=new Set;return Z(i,e,t,r,o,n,s,a),a}function Z(i,e,t,r,o,n,s,a){for(let c of i){let u=c[e];if(u!==void 0){let f=t.get(u);if(f!==void 0&&f.subDirectives!==void 0){let p=r.get(u);if(p!==void 0){let l=false;for(let g=0;g<p.length;g++){let A=c[p[g]];if(!(!Array.isArray(A)||A.length===0)&&ee(A,e,r,o,n)){l=true;break}}l&&(f.executeInteractive!==void 0||f.interactive===true||s(f.execute)||a.add(u));}}}let d=c.catch;if(Array.isArray(d)&&d.length>0&&Z(d,e,t,r,o,n,s,a),u==="if"){let f=c.then;Array.isArray(f)&&f.length>0&&Z(f,e,t,r,o,n,s,a);let p=c.else;Array.isArray(p)&&p.length>0&&Z(p,e,t,r,o,n,s,a);continue}if(u===void 0)continue;let h=r.get(u);if(h!==void 0)for(let f=0;f<h.length;f++){let p=c[h[f]];!Array.isArray(p)||p.length===0||Z(p,e,t,r,o,n,s,a);}}}function ee(i,e,t,r,o){for(let n of i){let s=n[e];if(s==="pause"||s!==void 0&&r.has(s)||s==="action"&&typeof n.id=="string"&&o(n.id))return true;let a=n.catch;if(Array.isArray(a)&&a.length>0&&ee(a,e,t,r,o))return true;if(s==="if"){let u=n.then;if(Array.isArray(u)&&u.length>0&&ee(u,e,t,r,o))return true;let d=n.else;if(Array.isArray(d)&&d.length>0&&ee(d,e,t,r,o))return true;continue}if(s===void 0)continue;let c=t.get(s);if(c!==void 0)for(let u=0;u<c.length;u++){let d=n[c[u]];if(!(!Array.isArray(d)||d.length===0)&&ee(d,e,t,r,o))return true}}return false}function j(i,e,t,r,o,n){let s=i.name;if(typeof i.resolve=="function")try{t[s]=i.resolve(e,t).value;}catch(a){r.push({directiveIndex:o,error:`Binding resolve: ${a}`}),n.errors++;}else t[s]=i.value;}function L(i,e,t,r,o,n){let s=i.value;if(typeof i.resolve=="function")try{let a=i.resolve(e,t);s="value"in a?a.value:"return"in a?a.return:s;}catch(a){return r.push({directiveIndex:o,error:`Control resolve: ${a}`}),n.errors++,{ok:false}}return {ok:true,data:s}}function O(i,e,t,r,o,n){let s=i.message;if(typeof i.resolve=="function")try{let a=i.resolve(e,t);s="message"in a?a.message:"throw"in a?a.throw:s;}catch(a){return r.push({directiveIndex:o,error:`Control resolve: ${a}`}),n.errors++,{ok:false}}return {ok:true,data:s}}function V(i,e,t,r,o,n,s,a,c,u,d){let h;try{let p=i.cond;h=typeof p=="function"?!!p(e,t):!!p;}catch(p){c.push({directiveIndex:u,error:`if cond: ${p}`}),d.errors++;return}let f=h?i.then:i.else;if(Array.isArray(f)&&f.length>0){let p=Math.min(f.length,a),l=o?n:s;r.push({dirs:f,i:0,len:p,topLevelIfIndex:l});}}function z(i,e,t){let r=core.processIntercept(i,"beforeDirective");if(r.action===core.Intercept.SKIP)return {action:"skip"};if(r.action===core.Intercept.ABORT)return {action:"abort",reason:r.abortReason};let o=t,n=e;return r.ctx!==void 0&&(o=t.withCtx(r.ctx)),r.directive!==void 0&&(n=r.directive),{action:"continue",directive:n,dFrame:o}}function G(i,e,t,r,o){i.push({directiveIndex:t,error:`Hook ${r}: ${o}`}),e.errors++;}function S(i,e,t,r,o){return {success:false,aborted:true,abortedBy:i,appliedCount:e.appliedCount,skippedCount:e.skippedCount,errors:e.errors,processedCount:t,totalCount:r,counters:e.counters,data:o}}function K(i,e,t,r){return {success:true,aborted:true,abortedBy:"halt",appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r}}function U(i,e,t,r){return {success:true,aborted:false,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r}}function q(i,e){return {success:true,aborted:false,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:e,counters:i.counters}}function W(i,e,t,r){return {success:r.success,aborted:true,abortedBy:r.abortedBy,appliedCount:i.appliedCount,skippedCount:i.skippedCount,errors:i.errors,processedCount:e,totalCount:t,counters:i.counters,data:r.data}}function J(i,e,t,r,o){if(typeof i.resolve!="function")return i;try{let n=i.resolve(e.ctx,e.scope);return {...i,...n}}catch(n){return t.push({directiveIndex:r,error:`Directive resolve: ${n}`}),o.errors++,null}}function Y(i,e){return [{dirs:i,i:0,len:e,topLevelIfIndex:-1}]}function Ze(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return function(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{m=F(x,E,d);}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=d.runDirectives(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{c.onDirectivesComplete(P);}catch{}return P}}function et(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return async function(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=await c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{m=await F(x,E,d);}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=await d.runDirectivesAsync(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(await c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{await c.onDirectivesComplete(P);}catch{}return P}}function oe(i,e){return e?et(i):Ze(i)}function de(i){if(i===null||typeof i!="object")return null;if(typeof i.next=="function")return i;let e=i.iterator;return e!=null&&typeof e=="object"&&typeof e.next=="function"?e:null}function fe(i,e,t){return {source:"pause",directive:i,frame:e,index:t,payload:{message:i.message}}}function pe(i){return i===false||i==="abort"||i==="cancel"}function ve(i,e,t,r){r.directivesApplied++,typeof i.as=="string"&&e!==void 0&&(t[i.as]=e);}function tt(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return function*(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="pause"){let v=R,y=yield fe(C,s,_);if(pe(y))return S("pause",l,v,f,y);l.appliedCount++,ve(C,y,g,l.counters);continue}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{let v=F(x,E,d),y=de(v);y!==null?m=yield*y:m=v;}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=d.runDirectives(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{c.onDirectivesComplete(P);}catch{}return P}}function rt(i){let e=i.filledNames.has("beforeDirective"),t=i.filledNames.has("afterDirective"),r=i.filledNames.has("onDirectivesComplete");return async function*(n,s,a,c,u,d,h){let f=Math.min(n.length,h),p=[],l={appliedCount:0,skippedCount:0,errors:p,counters:s.counters},{scope:g}=s,A=s.ctx,D=Y(n,f),R=0;for(;D.length>0;){let b=D[D.length-1];if(b.i>=b.len){D.pop();continue}let I=b.i++,T=b.topLevelIfIndex!==-1,_=T?b.topLevelIfIndex:I;T||(R=I+1);let C=b.dirs[I],k=C[u];if(k==="const"||k==="let"){j(C,A,g,p,_,l.counters);continue}if(k==="return"){let v=L(C,A,g,p,_,l.counters);if(!v.ok)continue;return U(l,R,f,v.data)}if(k==="throw"){let v=O(C,A,g,p,_,l.counters);if(!v.ok)continue;return S("throw",l,R,f,v.data)}if(k==="pause"){let v=R,y=yield fe(C,s,_);if(pe(y))return S("pause",l,v,f,y);l.appliedCount++,ve(C,y,g,l.counters);continue}if(k==="if"){V(C,A,g,D,T,b.topLevelIfIndex,I,h,p,_,l.counters);continue}let x=C,E=s;if(e)try{let v=await c.beforeDirective(x,s),y=z(v,x,s);if(y.action==="skip"){l.skippedCount++,l.counters.directivesSkipped++;continue}if(y.action==="abort"){let w=R===0?I:R-1;return S(y.reason,l,w,f)}x=y.directive,E=y.dFrame;}catch(v){G(p,l.counters,_,"beforeDirective",v);}let H=J(x,E,p,_,l.counters);if(H===null)continue;x=H;let M=x[u],F=M?a[M]:void 0;if(!F){p.push({directiveIndex:_,error:`No handler for directive type: ${M??"undefined"}`}),l.counters.errors++;continue}let m;try{let v=await F(x,E,d),y=de(v);y!==null?m=yield*y:m=v;}catch(v){m={ok:false,error:String(v)};}let $=R;if(m.ok){if(l.appliedCount++,l.counters.directivesApplied++,typeof x.as=="string"&&(g[x.as]=m.data),m.halt)return K(l,$,f,m.data)}else {if(m.halt)return S("halt",l,$,f,m.data);let v=x.catch;if(Array.isArray(v)&&v.length>0){g.$exception=m.error??"handler failed";let y=await d.runDirectivesAsync(v,E);l.appliedCount+=y.appliedCount;for(let w=0;w<y.errors.length;w++)p.push(y.errors[w]);if(y.aborted)return W(l,$,f,y)}else p.push({directiveIndex:_,error:m.error??"handler failed"}),l.counters.errors++;}if(t)try{if(await c.afterDirective(x,m,E)==="abort")return S("afterDirective",l,$,f)}catch(v){G(p,l.counters,_,"afterDirective",v);}}let P=q(l,f);if(r)try{await c.onDirectivesComplete(P);}catch{}return P}}function he(i,e){return e?rt(i):tt(i)}function ye(i,e=i.hasAnyAsync){let{filledNames:t}=i,r=d=>t.has(d),o=d=>i.asyncNames.has(d)?"await ":"",n=e?"await ":"",s=[];for(let d of t)s.push(`const ${d} = directiveHooks.${d};`);s.push("const len = Math.min(directives.length, maxDirectives);"),s.push("const errors = []; let appliedCount = 0; let skippedCount = 0;"),s.push("const counters = frame.counters;"),s.push("for (let i = 0; i < len; i++) {"),s.push(" let directive = directives[i];"),r("beforeDirective")?(s.push(" let _df = frame;"),s.push(" try {"),s.push(` const _bd = ${o("beforeDirective")}beforeDirective(directive, frame);`),s.push(' if (_bd === "skip") { skippedCount++; counters.directivesSkipped++; continue; }'),s.push(' if (_bd === "abort") return { success: false, aborted: true, abortedBy: "beforeDirective", appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),s.push(' if (typeof _bd === "object" && _bd !== null) {'),s.push(' if ("abort" in _bd) return { success: false, aborted: true, abortedBy: _bd.abort, appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),s.push(' if ("ctx" in _bd) _df = frame.withCtx(_bd.ctx);'),s.push(' if ("directive" in _bd) directive = _bd.directive;'),s.push(" }"),s.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook beforeDirective: " + _e }); counters.errors++; }')):s.push(" const _df = frame;"),s.push(' if (typeof directive.resolve === "function") {'),s.push(" try { const _r = directive.resolve(_df.ctx); directive = Object.assign({}, directive, _r); }"),s.push(' catch (_e) { errors.push({ directiveIndex: i, error: "Directive resolve: " + _e }); counters.errors++; continue; }'),s.push(" }"),s.push(" const _type = directive[typeField];"),s.push(" const _handler = _type ? handlers[_type] : undefined;"),s.push(' if (!_handler) { errors.push({ directiveIndex: i, error: "No handler for directive type: " + (_type || "undefined") }); counters.errors++; continue; }'),s.push(" let _result;"),s.push(` try { _result = ${n}_handler(directive, _df, engine); } catch (_e) { errors.push({ directiveIndex: i, error: String(_e) }); counters.errors++; continue; }`),s.push(" if (_result.ok) { appliedCount++; counters.directivesApplied++; }"),s.push(' else { errors.push({ directiveIndex: i, error: _result.error || "handler failed" }); counters.errors++; }'),r("afterDirective")&&(s.push(" try {"),s.push(` const _ad = ${o("afterDirective")}afterDirective(directive, _result, _df);`),s.push(' if (_ad === "abort") return { success: false, aborted: true, abortedBy: "afterDirective", appliedCount, skippedCount, errors, processedCount: i + 1, totalCount: len, counters };'),s.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook afterDirective: " + _e }); counters.errors++; }')),s.push("}"),s.push("const _finalResult = { success: true, aborted: false, appliedCount, skippedCount, errors, processedCount: len, totalCount: len, counters };"),r("onDirectivesComplete")&&s.push(`try { ${o("onDirectivesComplete")}onDirectivesComplete(_finalResult); } catch (_e) {}`),s.push("return _finalResult;");let a=s.join(`
2
+ `),c=e?"async ":"";return {fn:new Function("directives","frame","handlers","directiveHooks","typeField","engine","maxDirectives",`"use strict";
3
+ return (${c}() => {
4
4
  ${a}
5
- })();`),isAsync:e}}function te(s,e,r){return `return{success:false,aborted:true,abortedBy:${s},appliedCount,skippedCount,errors,processedCount:${e},totalCount:${r},counters};`}function $e(s,e){return `return{success:true,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${e},counters,data:_result.data};`}function Se(s,e){return `return{success:false,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${e},counters,data:_result.data};`}function He(s,e,r,i){let o=JSON.stringify(e.name);typeof e.resolve=="function"?(s.push("try{"),s.push(`scope[${o}]=${r}.resolve(ctx,scope).value;`),s.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Binding resolve: "+_e});counters.errors++;}`)):s.push(`scope[${o}]=${r}.value;`);}function Fe(s,e,r,i,o,t){typeof e.resolve=="function"?(s.push("try{"),s.push(`const _rv=${r}.resolve(ctx,scope);`),s.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${o},totalCount:${t},counters,data:"value" in _rv?_rv.value:"return" in _rv?_rv.return:${r}.value};`),s.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Control resolve: "+_e});counters.errors++;}`)):s.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${o},totalCount:${t},counters,data:${r}.value};`);}function Pe(s,e,r,i,o,t){typeof e.resolve=="function"?(s.push("try{"),s.push(`const _rv=${r}.resolve(ctx,scope);`),s.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${t},counters,data:"message" in _rv?_rv.message:"throw" in _rv?_rv.throw:${r}.message};`),s.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Control resolve: "+_e});counters.errors++;}`)):s.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${t},counters,data:${r}.message};`);}function Me(s,e,r,i,o,t){let n=typeof e.as=="string",a=n?JSON.stringify(e.as):"";s.push(`{const _ack=yield{source:"pause",directive:${r},frame,index:${i},payload:{message:${r}.message}};`),s.push(`if(_ack===false||_ack==="abort"||_ack==="cancel")return{success:false,aborted:true,abortedBy:"pause",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${t},counters,data:_ack};`),s.push("appliedCount++;counters.directivesApplied++;"),n&&s.push(`if(_ack!==undefined)scope[${a}]=_ack;`),s.push("}");}function Be(s,e,r,i,o){let{L:t,total:n,typeField:a,handlerVars:d,hasBefore:f,hasAfter:x,awBefore:C,awAfter:y,awHandler:l,actionIsAsync:_,actionIsInteractive:m,interactiveHandlerSet:p}=o,A=s[a],$=d.get(A),w=typeof s.resolve=="function",k=typeof s.as=="string",P=Array.isArray(s.catch)&&s.catch.length>0,R=k?JSON.stringify(s.as):"",T=m&&p.has(A),S=o.blockCounter.n++;t.push(`_b${S}:{`);let b=f||w,h=f;b&&t.push(`let _dir=${e};`),h&&t.push("let _df=frame;"),f&&(t.push("try{"),t.push(`const _bd=${C}_hookBefore(${e},frame);`),t.push(`if(_bd==="skip"){skippedCount++;counters.directivesSkipped++;break _b${S};}`),t.push(`if(_bd==="abort")${te('"beforeDirective"',i-1,n)}`),t.push('if(typeof _bd==="object"&&_bd!==null){'),t.push(`if("abort" in _bd)${te("_bd.abort",i-1,n)}`),t.push('if("ctx" in _bd)_df=frame.withCtx(_bd.ctx);'),t.push('if("directive" in _bd)_dir=_bd.directive;'),t.push("}"),t.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Hook beforeDirective: "+_e});counters.errors++;}`)),f?(t.push('if(typeof _dir.resolve==="function"){'),t.push("try{const _r=_dir.resolve(_df.ctx,scope);_dir=Object.assign({},_dir,_r);}"),t.push(`catch(_e){errors.push({directiveIndex:${r},error:"Directive resolve: "+_e});counters.errors++;break _b${S};}}`)):w&&(t.push(`try{const _r=${e}.resolve(ctx,scope);_dir=Object.assign({},${e},_r);}`),t.push(`catch(_e){errors.push({directiveIndex:${r},error:"Directive resolve: "+_e});counters.errors++;break _b${S};}`));let E=b?"_dir":e,g=h?"_df":"frame";if(t.push("let _result;"),T?(t.push(`try{_result=yield* ${$}(${E},${g},$.engine);}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")):m?(t.push(`try{_result=${l}${$}(${E},${g},$.engine);if(_result&&_result.iterator)_result=yield* _result.iterator;}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")):(t.push(`try{_result=${l}${$}(${E},${g},$.engine);}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")),t.push("if(_result.ok){"),t.push("appliedCount++;counters.directivesApplied++;"),k&&t.push(`scope[${R}]=_result.data;`),t.push(`if(_result.halt)${$e(i,n)}`),t.push("}else{"),t.push(`if(_result.halt)${Se(i,n)}`),P){t.push('scope.$exception=_result.error||"handler failed";');let I=_?"$.runner":"$.runnerSync";t.push(`const _cr=${l}${I}(${e}.catch,${g});`),t.push("appliedCount+=_cr.appliedCount;"),t.push("for(let _j=0;_j<_cr.errors.length;_j++)errors.push(_cr.errors[_j]);"),t.push(`if(_cr.aborted)return{success:_cr.success,aborted:true,abortedBy:_cr.abortedBy,appliedCount,skippedCount,errors,processedCount:${i},totalCount:${n},counters,data:_cr.data};`);}else t.push(`errors.push({directiveIndex:${r},error:_result.error||"handler failed"});counters.errors++;`);t.push("}"),x&&(t.push("try{"),t.push(`const _ad=${y}_hookAfter(${E},_result,${g});`),t.push(`if(_ad==="abort")${te('"afterDirective"',i,n)}`),t.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Hook afterDirective: "+_e});counters.errors++;}`)),t.push("}");}function Ge(s,e,r,i,o,t){let{L:n}=t,a=s.cond,d=typeof a=="boolean";n.push("{"),d?n.push(`if(${a?"true":"false"}){`):(n.push("let _cond=false,_condOk=true;"),n.push(`try{const _c=${e}.cond;_cond=typeof _c==="function"?!!_c(ctx,scope):!!_c;}`),n.push(`catch(_e){errors.push({directiveIndex:${r},error:"if cond: "+_e});counters.errors++;_condOk=false;}`),n.push("if(_condOk){"),n.push("if(_cond){"));let f=s.then;Array.isArray(f)&&f.length>0&&re(f,`${e}.then`,i,o,t),n.push("}");let x=s.else;Array.isArray(x)&&x.length>0&&(n.push("else{"),re(x,`${e}.else`,i,o,t),n.push("}")),d||n.push("}"),n.push("}");}function re(s,e,r,i,o){let t=r!==-1;for(let n=0;n<s.length;n++){let a=s[n],d=`${e}[${n}]`,f=t?r:n,x=t?i:n+1;switch(a[o.typeField]){case "const":case "let":He(o.L,a,d,f);break;case "return":Fe(o.L,a,d,f,x,o.total);break;case "throw":Pe(o.L,a,d,f,x,o.total);break;case "pause":Me(o.L,a,d,f,x,o.total);break;case "if":{let y=t?r:n,l=t?i:n+1;Ge(a,d,f,y,l,o);break}default:Be(a,d,f,x,o);break}}}function ne(s,e,r){for(let i of s){let o=i[e];if(o&&!L.has(o)&&r.add(o),o==="if"){let t=i.then;Array.isArray(t)&&t.length>0&&ne(t,e,r);let n=i.else;Array.isArray(n)&&n.length>0&&ne(n,e,r);}}}var pe=new Set;function ie(s,e,r,i=pe,o,t=false,n=pe){let a=[],d=s.length,{filledNames:f,hasAnyAsync:x,asyncNames:C}=e,y=f.has("beforeDirective"),l=f.has("afterDirective"),_=f.has("onDirectivesComplete"),m=o!==void 0?o:V(s,i,r),p=x||m,A=p?"await ":"",$=C.has("beforeDirective")?"await ":"",w=C.has("afterDirective")?"await ":"",k=C.has("onDirectivesComplete")?"await ":"",P=new Set;ne(s,r,P);let R=new Map,T=0;for(let I of P)R.set(I,`_h${T++}`);a.push("const counters=frame.counters;"),a.push("const ctx=frame.ctx;"),a.push("const errors=[];"),a.push("let appliedCount=0;"),a.push("let skippedCount=0;");for(let[I,F]of R)a.push(`const ${F}=$.h[${JSON.stringify(I)}];`);y&&a.push("const _hookBefore=$.hooks.beforeDirective;"),l&&a.push("const _hookAfter=$.hooks.afterDirective;"),re(s,"$.d",-1,0,{L:a,total:d,typeField:r,handlerVars:R,hasBefore:y,hasAfter:l,awBefore:$,awAfter:w,awHandler:A,actionIsAsync:p,actionIsInteractive:t,interactiveHandlerSet:n,blockCounter:{n:0}}),a.push(`const _finalResult={success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${d},totalCount:${d},counters};`),_&&a.push(`try{${k}$.hooks.onDirectivesComplete(_finalResult);}catch(_e){}`),a.push("return _finalResult;");let h=`{
6
- ${a.join(`
7
- `)}
8
- }`,E;return t?E=`(${p?"async function*()":"function*()"}${h})()`:E=`(${p?"async ()=>":"()=>"}${h})()`,{fn:new Function("frame","scope","$",`"use strict";
9
- return ${E};`),isAsync:p,isInteractive:t}}function V(s,e,r){for(let i of s){let o=i[r];if(o&&e.has(o))return true;if(o==="if"){let n=i.then;if(Array.isArray(n)&&n.length>0&&V(n,e,r))return true;let a=i.else;if(Array.isArray(a)&&a.length>0&&V(a,e,r))return true}let t=i.catch;if(Array.isArray(t)&&t.length>0&&V(t,e,r))return true}return false}function se(s,e,r){return {success:false,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[{directiveIndex:-1,error:e}],counters:s,...r}}function ve(s,e){return se(e,`Action not found: "${s}"`,{aborted:true,abortedBy:"action-not-found"})}function he(s,e,r){return se(r,`Max depth ${e} exceeded invoking "${s}"`,{aborted:true,abortedBy:"maxDepth"})}function ye(s,e){return se(e,`Action "${s}" is private (sub-action). Can only be invoked from within its parent scope.`)}function W(s,e){return {success:true,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[],data:s,counters:e}}function Le(s){return typeof s=="object"&&s!==null&&"execute"in s}function xe(s){let e=Object.create(null),r=new Map;for(let i of Object.keys(s)){let o=s[i];Le(o)?(e[i]=o.execute,r.set(i,o)):(e[i]=o,r.set(i,{execute:o}));}return {handlers:e,definitions:r}}function me(s,e){if(s==="*")return true;if(!s.includes("*"))return s===e;let r=s.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+r.replace(/\*/g,".*")+"$").test(e)}function _e(s){return typeof s=="string"?{pattern:s}:s}function ge(s,e,r){let i=new Map;if(!e&&!r){for(let o of s)i.set(o,{status:"available"});return i}if(e){let o=e.map(_e);for(let t of s){let n=o.some(a=>me(a.pattern,t));i.set(t,{status:n?"available":"denied"});}}else {let o=r.map(_e);for(let t of s){let n=o.find(a=>me(a.pattern,t));n?i.set(t,{status:"denied",reason:n.reason,source:n.source}):i.set(t,{status:"available"});}}return i}function Ce(s){let{typeField:e,asyncHandlerSet:r,interactiveHandlerSet:i}=s,o=new Map,t=new Set,n=new Set,a=new Set,d=new Set;return {upsert(f,x,C){o.set(f,Ne(x,e)),Y(x,r,e)?t.add(f):t.delete(f),C||Q(x,i,e)?n.add(f):n.delete(f);},remove(f){o.delete(f),t.delete(f),n.delete(f);},recompute(){a=De(o,t),d=De(o,n);},isAsync(f){return a.has(f)},isInteractive(f){return d.has(f)},has(f){return o.has(f)}}}function Ne(s,e){let r=new Set;return J(s,e,r),r}function J(s,e,r){for(let i of s){i[e]==="action"&&typeof i.id=="string"&&r.add(i.id);let o=i.catch;if(Array.isArray(o)&&o.length>0&&J(o,e,r),i[e]==="if"){let t=i.then;Array.isArray(t)&&t.length>0&&J(t,e,r);let n=i.else;Array.isArray(n)&&n.length>0&&J(n,e,r);}}}function Y(s,e,r){for(let i of s){let o=i[r];if(o&&e.has(o))return true;let t=i.catch;if(Array.isArray(t)&&t.length>0&&Y(t,e,r))return true;if(o==="if"){let n=i.then;if(Array.isArray(n)&&n.length>0&&Y(n,e,r))return true;let a=i.else;if(Array.isArray(a)&&a.length>0&&Y(a,e,r))return true}}return false}function Q(s,e,r){for(let i of s){let o=i[r];if(o==="pause"||o&&e.has(o))return true;let t=i.catch;if(Array.isArray(t)&&t.length>0&&Q(t,e,r))return true;if(o==="if"){let n=i.then;if(Array.isArray(n)&&n.length>0&&Q(n,e,r))return true;let a=i.else;if(Array.isArray(a)&&a.length>0&&Q(a,e,r))return true}}return false}function O(s,e){for(let r of s){let i=r[e];if(i==="pause")return true;let o=r.catch;if(Array.isArray(o)&&o.length>0&&O(o,e))return true;if(i==="if"){let t=r.then;if(Array.isArray(t)&&t.length>0&&O(t,e))return true;let n=r.else;if(Array.isArray(n)&&n.length>0&&O(n,e))return true}}return false}function De(s,e){let r=new Set(e),i=true;for(;i;){i=false;for(let[o,t]of s)if(!r.has(o)){for(let n of t)if(r.has(n)){r.add(o),i=true;break}}}return r}var Ue=8,qe="type",ce={maxDepth:10,maxRules:1e4,maxDirectives:1e5},ae=class{_directiveExecutor;_mode;_ctx;_requestedMode;_threshold;_limits;_typeField;_handlers;_definitions;_directiveHooks;_directiveAnalysis;_asyncHandlerSet;_interactiveHandlerSet;_isAsync;_isInteractive;_directivePermissions;_miniGraph;_interactiveExecutor;_beforeAction;_afterAction;_registry=new Map;_emitter=new j;_batchDepth=0;_batchErrors=[];_batchWarnings=[];_batchActions=[];_batchRegistered=[];_registeredIds=new Set;_directiveRunner;_directiveRunnerSync;_engineRef;constructor(e){this._requestedMode=e.mode??"auto",this._threshold=e.autoJitThreshold??Ue,this._typeField=e.typeField??qe,this._limits={maxDepth:e.limits?.maxDepth??ce.maxDepth,maxRules:e.limits?.maxRules??ce.maxRules,maxDirectives:e.limits?.maxDirectives??ce.maxDirectives};let{handlers:r,definitions:i}=xe(e.handlers);for(let a of Object.keys(e.handlers))if(L.has(a))throw new Error(`Handler type "${a}" is reserved for engine-internal directives`);if(e.allowedDirectives&&e.blockedDirectives)throw new Error("allowedDirectives and blockedDirectives are mutually exclusive. Provide one or neither.");this._handlers=r,this._definitions=i,this._directivePermissions=ge(Object.keys(r),e.allowedDirectives,e.blockedDirectives),this._directiveHooks=e.directiveHooks??{},this._beforeAction=e.actionHooks?.beforeAction??null,this._afterAction=e.actionHooks?.afterAction??null,this._directiveAnalysis=core.analyzeSlots(this._directiveHooks,core.DIRECTIVE_SLOT_NAMES);let o=new Set,t=new Set;for(let[a,d]of this._definitions)(d.async===true||core.isAsyncFunction(d.execute))&&o.add(a),(d.interactive===true||core.isGeneratorFunction(d.execute))&&t.add(a);if(this._asyncHandlerSet=o,this._interactiveHandlerSet=t,this._isInteractive=e.interactive!==void 0,!this._isInteractive&&t.size>0){let a=Array.from(t).join(", ");throw new Error(`Handler(s) [${a}] are interactive but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}this._isAsync=this._directiveAnalysis.hasAnyAsync||o.size>0,this._miniGraph=Ce({typeField:this._typeField,asyncHandlerSet:o,interactiveHandlerSet:t}),this._engineRef={runDirectives:(a,d)=>this._executeDirectives(a,d),runDirectivesAsync:(a,d)=>this._executeDirectivesAsync(a,d),invoke:(a,d,f)=>this._invokeInternal(a,d,f),invokeAsync:(a,d,f)=>this._invokeInternalAsync(a,d,f),isActionAsync:a=>this._miniGraph.has(a)?this._miniGraph.isAsync(a):void 0,isActionInteractive:a=>this._miniGraph.has(a)?this._miniGraph.isInteractive(a):void 0,invokeInteractive:(a,d,f)=>this._invokeInteractiveInternal(a,d,f),evaluateRules:()=>{throw new Error("evaluateRules() not available in ActionEngine context. Use createRuleEngine().")},evaluateRulesAsync:()=>{throw new Error("evaluateRulesAsync() not available in ActionEngine context. Use createRuleEngine().")}},this._directiveRunner=(a,d)=>this._directiveExecutor(a,d,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);let n=U(this._directiveAnalysis,false);this._directiveRunnerSync=(a,d)=>n(a,d,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives),this._requestedMode==="jit"?(this._directiveExecutor=this._buildJitDirectiveExecutor(),this._mode="jit"):this._isAsync?(this._directiveExecutor=U(this._directiveAnalysis,true),this._mode="interpret"):(this._directiveExecutor=n,this._mode="interpret"),this._interactiveExecutor=this._isInteractive?this._isAsync?Z(this._directiveAnalysis,true):Z(this._directiveAnalysis,false):null;}register(e){let r=[],i=[],o=[],t=[];for(let a of e){if(!a.id){i.push({actionId:"",error:"Action must have an id"});continue}if(!this._isInteractive&&O(a.directives,this._typeField)){i.push({actionId:a.id,error:'Action uses directive type:"pause" but engine has no `interactive` config. Add `interactive: {}` to enable.'});continue}let d=ue(a,this._handlers,this._definitions,this._typeField);if(d.length>0){for(let f of d)i.push({actionId:a.id,error:f});continue}t.push(a);}for(let a of t){let d=N(a.directives,this._typeField),f={definition:a,directives:d,compiled:null,invokeCount:0};this._registry.set(a.id,f),this._registeredIds.add(a.id),this._miniGraph.upsert(a.id,d,a.interactive===true),r.push(a.id);}if(this._batchDepth>0){this._batchErrors.push(...i),this._batchWarnings.push(...o);for(let a of t)this._batchActions.push(a);return this._batchRegistered.push(...r),{registered:r,errors:i,warnings:o}}t.length>0&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile());let n={registered:r,errors:i,warnings:o};return r.length>0&&this._emitter.emit("register",{actions:t,result:n,registered:r}),n}unregister(e){let r=this._registry.delete(e);r&&(this._registeredIds.delete(e),this._miniGraph.remove(e));let i=e+"/",o=[];for(let t of this._registry.keys())t.startsWith(i)&&(this._registry.delete(t),this._registeredIds.delete(t),this._miniGraph.remove(t),o.push(t));return r&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile(),this._emitter.emit("unregister",{id:e,cascaded:o})),r}invoke(e,r,i){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);if(this._miniGraph.isAsync(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is async (transitively). Use invokeAsync() instead.`);if(this._directiveAnalysis.hasAnyAsync)throw new Error(`Cannot call invoke("${e}") \u2014 engine has async directive hooks. Use invokeAsync() instead.`);let o=i!==void 0?i:this._requireCtx(),t=core.createRootFrame(o,this._limits);return this._invokeInternal(e,r,t)}async invokeAsync(e,r,i){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invokeAsync("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);let o=i!==void 0?i:this._requireCtx(),t=core.createRootFrame(o,this._limits);return this._invokeInternalAsync(e,r,t)}setContext(e){this._ctx=e;}context(e,r){let i=this._ctx;this._ctx=e;try{return r()}finally{this._ctx=i;}}beginBatch(){this._batchDepth++,this._batchDepth===1&&(this._batchErrors=[],this._batchWarnings=[],this._batchActions=[],this._batchRegistered=[]);}endBatch(){if(this._batchDepth<=0)throw new Error("endBatch() called without matching beginBatch()");if(this._batchDepth--,this._batchDepth>0)return {registered:[],errors:[],warnings:[]};let e={registered:this._batchRegistered,errors:this._batchErrors,warnings:this._batchWarnings};return this._batchRegistered.length>0&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile()),this._batchRegistered.length>0&&this._emitter.emit("register",{actions:this._batchActions,result:e,registered:this._batchRegistered}),e}on(e,r){return this._emitter.on(e,r)}get handlerDefinitions(){return this._definitions}get registeredIds(){return this._registeredIds}getActionDefinition(e){return this._registry.get(e)?.definition}get typeField(){return this._typeField}get directivePermissions(){return this._directivePermissions}get isAsync(){return this._isAsync}get isInteractive(){return this._isInteractive}isActionAsync(e){if(this._miniGraph.has(e))return this._miniGraph.isAsync(e)}isActionInteractive(e){if(this._miniGraph.has(e))return this._miniGraph.isInteractive(e)}invokeInteractive(e,r,i){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("Cannot call invokeInteractive() \u2014 engine has no `interactive` config. Add `interactive: {}` to enable.");let o=i!==void 0?i:this._requireCtx(),t=core.createRootFrame(o,this._limits);return this._invokeInteractiveInternal(e,r,t)}_invokeInteractiveInternal(e,r,i){let o=this._prepareInvoke(e,r,i);if("success"in o)return be(o,this._isAsync);let{stored:t,childFrame:n,childScope:a}=o;if(this._beforeAction!==null){let f=this._beforeAction(e,r,n);if(f?.skip)return be(W(f.data,n.counters),this._isAsync)}let d;if(t.compiled&&t.compiled.isInteractive)d=t.compiled.fn(n,n.scope,t.compiled.$);else {let f=this._interactiveExecutor;d=f(t.directives,n,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);}return Ve(d,e,r,n,this._afterAction,this._isAsync)}get compilationMode(){return this._mode}get directiveHookSlots(){return this._directiveAnalysis.filledNames}get asyncSlots(){return this._directiveAnalysis.asyncNames}compile(){if(this._requestedMode!=="interpret"){this._mode!=="jit"&&this._promote();for(let[e,r]of this._registry)r.compiled||(r.compiled=this._compileAction(e,r.directives));}}_invokeInternal(e,r,i){let o=this._prepareInvoke(e,r,i);if("success"in o)return o;let{stored:t,childFrame:n,childScope:a}=o;if(this._beforeAction!==null){let f=this._beforeAction(e,r,n);if(f?.skip)return W(f.data,n.counters)}let d;if(t.compiled?d=t.compiled.fn(n,a,t.compiled.$):this._isAsync&&!this._miniGraph.isAsync(e)?(t.compiled=this._compileAction(e,t.directives),d=t.compiled.fn(n,a,t.compiled.$)):(d=this._directiveRunner(t.directives,n),this._maybeAutoPromote(t)),this._afterAction!==null){let f=this._afterAction(e,r,d,n);f!==void 0&&(d=f);}return d}async _invokeInternalAsync(e,r,i){let o=this._prepareInvoke(e,r,i);if("success"in o)return o;let{stored:t,childFrame:n,childScope:a}=o;if(this._beforeAction!==null){let f=this._beforeAction(e,r,n);if(f?.skip)return W(f.data,n.counters)}let d;if(t.compiled?d=await t.compiled.fn(n,a,t.compiled.$):(d=await this._directiveRunner(t.directives,n),this._maybeAutoPromote(t)),this._afterAction!==null){let f=this._afterAction(e,r,d,n);f!==void 0&&(d=f);}return d}_prepareInvoke(e,r,i){let o=this._registry.get(e);if(!o)return ve(e,i.counters);if(e.includes("/")&&!this._isAccessible(e,i))return ye(e,i.counters);if(i.depth>=i.limits.maxDepth)return he(e,i.limits.maxDepth,i.counters);let t=Object.create(i.scope);r&&Object.assign(t,r);let n=i.child("action:"+e,0,e).withScope(t);return {stored:o,childFrame:n,childScope:t}}_maybeAutoPromote(e){this._requestedMode==="auto"&&++e.invokeCount>=this._threshold&&(e.compiled=this._compileAction(e.definition.id,e.directives),this._mode!=="jit"&&this._promote());}_executeDirectives(e,r){return this._directiveExecutor(e,r,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}async _executeDirectivesAsync(e,r){return this._directiveExecutor(e,r,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_compileAction(e,r){let i=this._miniGraph.isAsync(e),o=this._miniGraph.isInteractive(e),{fn:t,isAsync:n,isInteractive:a}=ie(r,this._directiveAnalysis,this._typeField,this._asyncHandlerSet,i,o,this._interactiveHandlerSet),d={d:r,h:this._handlers,hooks:this._directiveHooks,engine:this._engineRef,runner:this._directiveRunner,runnerSync:this._directiveRunnerSync};return {fn:t,$:d,isAsync:n,isInteractive:a}}_isAccessible(e,r){let o="action:"+e.slice(0,e.lastIndexOf("/"));return r.path.includes(o)}_requireCtx(){if(this._ctx===void 0)throw new Error("No context set. Pass ctx to invoke(id, params, ctx), call setContext(ctx), or use context(ctx, fn).");return this._ctx}_promote(){this._directiveExecutor=this._buildJitDirectiveExecutor(),this._mode="jit";}_buildJitDirectiveExecutor(){let{fn:e}=ee(this._directiveAnalysis,this._isAsync);return e}_invalidateAndMaybeRecompile(){for(let e of this._registry.values())e.compiled=null;if(this._requestedMode==="jit")for(let[e,r]of this._registry)r.compiled=this._compileAction(e,r.directives);}};function be(s,e){return e?{next:()=>Promise.resolve({value:s,done:true}),return:()=>Promise.resolve({value:s,done:true}),throw:o=>Promise.reject(o),[Symbol.asyncIterator](){return this}}:{next:()=>({value:s,done:true}),return:()=>({value:s,done:true}),throw:i=>{throw i},[Symbol.iterator](){return this}}}function Ve(s,e,r,i,o,t){if(t){let d=s;return {async next(x){let C=await d.next(x);if(C.done){let y=C.value;if(o!==null){let l=o(e,r,y,i);l!==void 0&&(y=l);}return {value:y,done:true}}return {value:C.value,done:false}},async return(){let x=await d.return(void 0),C=x.value;if(x.done&&o!==null){let y=o(e,r,C,i);y!==void 0&&(C=y);}return {value:C,done:true}},async throw(x){let C=await d.throw(x);if(C.done){let y=C.value;if(o!==null){let l=o(e,r,y,i);l!==void 0&&(y=l);}return {value:y,done:true}}return {value:C.value,done:false}},[Symbol.asyncIterator](){return this}}}let n=s;return {next(d){let f=n.next(d);if(f.done){let x=f.value;if(o!==null){let C=o(e,r,x,i);C!==void 0&&(x=C);}return {value:x,done:true}}return {value:f.value,done:false}},return(){let d=n.return(void 0),f=d.value;if(d.done&&o!==null){let x=o(e,r,f,i);x!==void 0&&(f=x);}return {value:f,done:true}},throw(d){let f=n.throw(d);if(f.done){let x=f.value;if(o!==null){let C=o(e,r,x,i);C!==void 0&&(x=C);}return {value:x,done:true}}return {value:f.value,done:false}},[Symbol.iterator](){return this}}}function We(s){return new ae(s)}exports.RESERVED_TYPES=L;exports.SimpleEmitter=j;exports.buildActionExecutor=ie;exports.buildDirectiveExecutor=ee;exports.createActionEngine=We;exports.createDirectiveInterpreter=U;exports.drainAsync=Re;exports.drainSync=Ae;exports.normalizeDirectives=N;exports.replayResponder=Ie;
5
+ })();`),isAsync:e}}function ge(i,e,t){return `return{success:false,aborted:true,abortedBy:${i},appliedCount,skippedCount,errors,processedCount:${e},totalCount:${t},counters};`}function nt(i,e){return `return{success:true,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${i},totalCount:${e},counters,data:_result.data};`}function it(i,e){return `return{success:false,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${i},totalCount:${e},counters,data:_result.data};`}function st(i,e,t,r){i.push("const counters=frame.counters;"),i.push("const ctx=frame.ctx;"),i.push("const errors=[];"),i.push("let appliedCount=0;"),i.push("let skippedCount=0;");for(let[o,n]of e)i.push(`const ${n}=$.h[${JSON.stringify(o)}];`);t&&i.push("const _hookBefore=$.hooks.beforeDirective;"),r&&i.push("const _hookAfter=$.hooks.afterDirective;");}function ot(i,e,t,r){i.push(`const _finalResult={success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${e},totalCount:${e},counters};`),t&&i.push(`try{${r}$.hooks.onDirectivesComplete(_finalResult);}catch(_e){}`),i.push("return _finalResult;");}function ct(i,e,t){let r=`{
6
+ ${i}
7
+ }`;return t?`(${e?"async function*()":"function*()"}${r})()`:`(${e?"async ()=>":"()=>"}${r})()`}function at(i,e,t,r){let o=JSON.stringify(e.name);typeof e.resolve=="function"?(i.push("try{"),i.push(`scope[${o}]=${t}.resolve(ctx,scope).value;`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Binding resolve: "+_e});counters.errors++;}`)):i.push(`scope[${o}]=${t}.value;`);}function ut(i,e,t,r,o,n){typeof e.resolve=="function"?(i.push("try{"),i.push(`const _rv=${t}.resolve(ctx,scope);`),i.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:"value" in _rv?_rv.value:"return" in _rv?_rv.return:${t}.value};`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Control resolve: "+_e});counters.errors++;}`)):i.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:${t}.value};`);}function lt(i,e,t,r,o,n){typeof e.resolve=="function"?(i.push("try{"),i.push(`const _rv=${t}.resolve(ctx,scope);`),i.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:"message" in _rv?_rv.message:"throw" in _rv?_rv.throw:${t}.message};`),i.push(`}catch(_e){errors.push({directiveIndex:${r},error:"Control resolve: "+_e});counters.errors++;}`)):i.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:${t}.message};`);}function dt(i,e,t,r,o,n){let s=typeof e.as=="string",a=s?JSON.stringify(e.as):"";i.push(`{const _ack=yield{source:"pause",directive:${t},frame,index:${r},payload:{message:${t}.message}};`),i.push(`if(_ack===false||_ack==="abort"||_ack==="cancel")return{success:false,aborted:true,abortedBy:"pause",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${n},counters,data:_ack};`),i.push("appliedCount++;counters.directivesApplied++;"),s&&i.push(`if(_ack!==undefined)scope[${a}]=_ack;`),i.push("}");}function ft(i,e,t,r,o){let{L:n,total:s,typeField:a,handlerVars:c,hasBefore:u,hasAfter:d,awBefore:h,awAfter:f,awHandler:p,actionIsAsync:l,actionIsInteractive:g,interactiveHandlerSet:A}=o,D=i[a],R=c.get(D),P=typeof i.resolve=="function",b=typeof i.as=="string",I=Array.isArray(i.catch)&&i.catch.length>0,T=b?JSON.stringify(i.as):"",_=g&&A.has(D),C=o.blockCounter.n++;n.push(`_b${C}:{`);let k=u||P,x=u;k&&n.push(`let _dir=${e};`),x&&n.push("let _df=frame;"),u&&(n.push("try{"),n.push(`const _bd=${h}_hookBefore(${e},frame);`),n.push(`if(_bd==="skip"){skippedCount++;counters.directivesSkipped++;break _b${C};}`),n.push(`if(_bd==="abort")${ge('"beforeDirective"',r-1,s)}`),n.push('if(typeof _bd==="object"&&_bd!==null){'),n.push(`if("abort" in _bd)${ge("_bd.abort",r-1,s)}`),n.push('if("ctx" in _bd)_df=frame.withCtx(_bd.ctx);'),n.push('if("directive" in _bd)_dir=_bd.directive;'),n.push("}"),n.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook beforeDirective: "+_e});counters.errors++;}`)),u?(n.push('if(typeof _dir.resolve==="function"){'),n.push("try{const _r=_dir.resolve(_df.ctx,scope);_dir=Object.assign({},_dir,_r);}"),n.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${C};}}`)):P&&(n.push(`try{const _r=${e}.resolve(ctx,scope);_dir=Object.assign({},${e},_r);}`),n.push(`catch(_e){errors.push({directiveIndex:${t},error:"Directive resolve: "+_e});counters.errors++;break _b${C};}`));let E=k?"_dir":e,H=x?"_df":"frame";if(n.push("let _result;"),_?(n.push(`try{_result=yield* ${R}(${E},${H},$.engine);}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")):g?(n.push(`try{_result=${p}${R}(${E},${H},$.engine);if(_result&&_result.iterator)_result=yield* _result.iterator;}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")):(n.push(`try{_result=${p}${R}(${E},${H},$.engine);}`),n.push("catch(_e){_result={ok:false,error:String(_e)};}")),n.push("if(_result.ok){"),n.push("appliedCount++;counters.directivesApplied++;"),b&&n.push(`scope[${T}]=_result.data;`),n.push(`if(_result.halt)${nt(r,s)}`),n.push("}else{"),n.push(`if(_result.halt)${it(r,s)}`),I){n.push('scope.$exception=_result.error||"handler failed";');let M=l?"$.runner":"$.runnerSync";n.push(`const _cr=${p}${M}(${e}.catch,${H});`),n.push("appliedCount+=_cr.appliedCount;"),n.push("for(let _j=0;_j<_cr.errors.length;_j++)errors.push(_cr.errors[_j]);"),n.push(`if(_cr.aborted)return{success:_cr.success,aborted:true,abortedBy:_cr.abortedBy,appliedCount,skippedCount,errors,processedCount:${r},totalCount:${s},counters,data:_cr.data};`);}else n.push(`errors.push({directiveIndex:${t},error:_result.error||"handler failed"});counters.errors++;`);n.push("}"),d&&(n.push("try{"),n.push(`const _ad=${f}_hookAfter(${E},_result,${H});`),n.push(`if(_ad==="abort")${ge('"afterDirective"',r,s)}`),n.push(`}catch(_e){errors.push({directiveIndex:${t},error:"Hook afterDirective: "+_e});counters.errors++;}`)),n.push("}");}function pt(i,e,t,r,o,n){let{L:s}=n,a=i.cond,c=typeof a=="boolean";s.push("{"),c?s.push(`if(${a?"true":"false"}){`):(s.push("let _cond=false,_condOk=true;"),s.push(`try{const _c=${e}.cond;_cond=typeof _c==="function"?!!_c(ctx,scope):!!_c;}`),s.push(`catch(_e){errors.push({directiveIndex:${t},error:"if cond: "+_e});counters.errors++;_condOk=false;}`),s.push("if(_condOk){"),s.push("if(_cond){"));let u=i.then;Array.isArray(u)&&u.length>0&&xe(u,`${e}.then`,r,o,n),s.push("}");let d=i.else;Array.isArray(d)&&d.length>0&&(s.push("else{"),xe(d,`${e}.else`,r,o,n),s.push("}")),c||s.push("}"),s.push("}");}function xe(i,e,t,r,o){let n=t!==-1;for(let s=0;s<i.length;s++){let a=i[s],c=`${e}[${s}]`,u=n?t:s,d=n?r:s+1;switch(a[o.typeField]){case "const":case "let":at(o.L,a,c,u);break;case "return":ut(o.L,a,c,u,d,o.total);break;case "throw":lt(o.L,a,c,u,d,o.total);break;case "pause":dt(o.L,a,c,u,d,o.total);break;case "if":{let f=n?t:s,p=n?r:s+1;pt(a,c,u,f,p,o);break}default:ft(a,c,u,d,o);break}}}function me(i,e,t){for(let r of i){let o=r[e];if(o&&!N.has(o)&&t.add(o),o==="if"){let n=r.then;Array.isArray(n)&&n.length>0&&me(n,e,t);let s=r.else;Array.isArray(s)&&s.length>0&&me(s,e,t);}}}var we=new Set;function _e(i,e,t,r=we,o,n=false,s=we){let a=[],c=i.length,{filledNames:u,hasAnyAsync:d,asyncNames:h}=e,f=u.has("beforeDirective"),p=u.has("afterDirective"),l=u.has("onDirectivesComplete"),g=o!==void 0?o:ce(i,r,t),A=d||g,D=A?"await ":"",R=h.has("beforeDirective")?"await ":"",P=h.has("afterDirective")?"await ":"",b=h.has("onDirectivesComplete")?"await ":"",I=new Set;me(i,t,I);let T=new Map,_=0;for(let E of I)T.set(E,`_h${_++}`);st(a,T,f,p),xe(i,"$.d",-1,0,{L:a,total:c,typeField:t,handlerVars:T,hasBefore:f,hasAfter:p,awBefore:R,awAfter:P,awHandler:D,actionIsAsync:A,actionIsInteractive:n,interactiveHandlerSet:s,blockCounter:{n:0}}),ot(a,c,l,b);let k=ct(a.join(`
8
+ `),A,n);return {fn:new Function("frame","scope","$",`"use strict";
9
+ return ${k};`),isAsync:A,isInteractive:n}}function ce(i,e,t){for(let r of i){let o=r[t];if(o&&e.has(o))return true;if(o==="if"){let s=r.then;if(Array.isArray(s)&&s.length>0&&ce(s,e,t))return true;let a=r.else;if(Array.isArray(a)&&a.length>0&&ce(a,e,t))return true}let n=r.catch;if(Array.isArray(n)&&n.length>0&&ce(n,e,t))return true}return false}function De(i,e,t){return {success:false,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[{directiveIndex:-1,error:e}],counters:i,...t}}function Te(i,e){return De(e,`Action not found: "${i}"`,{aborted:true,abortedBy:"action-not-found"})}function Se(i,e,t){return De(t,`Max depth ${e} exceeded invoking "${i}"`,{aborted:true,abortedBy:"maxDepth"})}function $e(i,e){return De(e,`Action "${i}" is private (sub-action). Can only be invoked from within its parent scope.`)}function ae(i,e){return {success:true,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[],data:i,counters:e}}function vt(i){return typeof i=="object"&&i!==null&&"execute"in i}function He(i){let e=new Map;for(let[t,r]of i){let o=r.subDirectives;if(!o)continue;let n=Object.keys(o);if(n.length===0)continue;let s=null;for(let a=0;a<n.length;a++){let c=n[a];c!=="catch"&&o[c].graph!==false&&(s===null&&(s=[]),s.push(c));}s!==null&&e.set(t,s);}return e}function Me(i){let e=new Map;for(let[t,r]of i){let o=r.subDirectives;if(!o)continue;let n=Object.keys(o);if(n.length===0)continue;let s=null;for(let a=0;a<n.length;a++){let c=n[a];c!=="catch"&&(s===null&&(s=[]),s.push(c));}s!==null&&e.set(t,s);}return e}function Pe(i,e,t){if(!e)return t;let r=new Set(t);for(let[o,n]of i)n.executeInteractive!==void 0&&r.add(o);return r}function te(i,e,t){let r=Object.create(null);for(let[o,n]of i){let s;t&&n.executeInteractive!==void 0?s=n.executeInteractive:e&&n.executeAsync!==void 0?s=n.executeAsync:s=n.execute,r[o]=s;}return r}function Fe(i){let e=Object.create(null),t=new Map;for(let r of Object.keys(i)){let o=i[r];vt(o)?(e[r]=o.execute,t.set(r,o)):(e[r]=o,t.set(r,{execute:o}));}return {handlers:e,definitions:t}}function Ge(i,e){if(i==="*")return true;if(!i.includes("*"))return i===e;let t=i.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)}function Be(i){return typeof i=="string"?{pattern:i}:i}function Ne(i,e,t){let r=new Map;if(!e&&!t){for(let o of i)r.set(o,{status:"available"});return r}if(e){let o=e.map(Be);for(let n of i){let s=o.some(a=>Ge(a.pattern,n));r.set(n,{status:s?"available":"denied"});}}else {let o=t.map(Be);for(let n of i){let s=o.find(a=>Ge(a.pattern,n));s?r.set(n,{status:"denied",reason:s.reason,source:s.source}):r.set(n,{status:"available"});}}return r}function Le(i){let{typeField:e,asyncHandlerSet:t,interactiveHandlerSet:r,subDirectiveFieldsForGraph:o}=i,n=new Map,s=new Set,a=new Set,c=new Set,u=new Set;return {upsert(d,h,f){n.set(d,ht(h,e,o)),ne(h,t,e,o)?s.add(d):s.delete(d),f||ie(h,r,e,o)?a.add(d):a.delete(d);},remove(d){n.delete(d),s.delete(d),a.delete(d);},recompute(){c=je(n,s),u=je(n,a);},isAsync(d){return c.has(d)},isInteractive(d){return u.has(d)},has(d){return n.has(d)}}}var ue=new Map;function ht(i,e,t=ue){let r=new Set;return re(i,e,t,r),r}function re(i,e,t,r){for(let o of i){let n=o[e];n==="action"&&typeof o.id=="string"&&r.add(o.id);let s=o.catch;if(Array.isArray(s)&&s.length>0&&re(s,e,t,r),n==="if"){let c=o.then;Array.isArray(c)&&c.length>0&&re(c,e,t,r);let u=o.else;Array.isArray(u)&&u.length>0&&re(u,e,t,r);continue}if(n===void 0)continue;let a=t.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];!Array.isArray(u)||u.length===0||re(u,e,t,r);}}}function ne(i,e,t,r=ue){for(let o of i){let n=o[t];if(n!==void 0&&e.has(n))return true;let s=o.catch;if(Array.isArray(s)&&s.length>0&&ne(s,e,t,r))return true;if(n==="if"){let c=o.then;if(Array.isArray(c)&&c.length>0&&ne(c,e,t,r))return true;let u=o.else;if(Array.isArray(u)&&u.length>0&&ne(u,e,t,r))return true;continue}if(n===void 0)continue;let a=r.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];if(!(!Array.isArray(u)||u.length===0)&&ne(u,e,t,r))return true}}return false}function ie(i,e,t,r=ue){for(let o of i){let n=o[t];if(n==="pause"||n!==void 0&&e.has(n))return true;let s=o.catch;if(Array.isArray(s)&&s.length>0&&ie(s,e,t,r))return true;if(n==="if"){let c=o.then;if(Array.isArray(c)&&c.length>0&&ie(c,e,t,r))return true;let u=o.else;if(Array.isArray(u)&&u.length>0&&ie(u,e,t,r))return true;continue}if(n===void 0)continue;let a=r.get(n);if(a!==void 0)for(let c=0;c<a.length;c++){let u=o[a[c]];if(!(!Array.isArray(u)||u.length===0)&&ie(u,e,t,r))return true}}return false}function Q(i,e,t=ue){for(let r of i){let o=r[e];if(o==="pause")return true;let n=r.catch;if(Array.isArray(n)&&n.length>0&&Q(n,e,t))return true;if(o==="if"){let a=r.then;if(Array.isArray(a)&&a.length>0&&Q(a,e,t))return true;let c=r.else;if(Array.isArray(c)&&c.length>0&&Q(c,e,t))return true;continue}if(o===void 0)continue;let s=t.get(o);if(s!==void 0)for(let a=0;a<s.length;a++){let c=r[s[a]];if(!(!Array.isArray(c)||c.length===0)&&Q(c,e,t))return true}}return false}function je(i,e){let t=new Set(e),r=true;for(;r;){r=false;for(let[o,n]of i)if(!t.has(o)){for(let s of n)if(t.has(s)){t.add(o),r=true;break}}}return t}var le=class{depth=0;errors=[];warnings=[];actions=[];registered=[];begin(){this.depth++,this.depth===1&&(this.errors=[],this.warnings=[],this.actions=[],this.registered=[]);}endDepth(){if(this.depth<=0)throw new Error("endBatch() called without matching beginBatch()");return this.depth--,this.depth===0}isActive(){return this.depth>0}accumulate(e,t,r,o){this.errors.push(...e),this.warnings.push(...t);for(let n of r)this.actions.push(n);this.registered.push(...o);}};function Oe(i){for(let e of i)if(N.has(e))throw new Error(`Handler type "${e}" is reserved for engine-internal directives`)}function Ve(i,e){if(i&&e)throw new Error("allowedDirectives and blockedDirectives are mutually exclusive. Provide one or neither.")}function ze(i,e,t){if(i)return;if(e.size>0){let o=Array.from(e).join(", ");throw new Error(`Handler(s) [${o}] are interactive but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}let r=[];for(let[o,n]of t)n.executeInteractive!==void 0&&r.push(o);if(r.length>0)throw new Error(`Handler(s) [${r.join(", ")}] declare \`executeInteractive\` variant but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}function Ke(i){let e=new Set,t=new Set;for(let[r,o]of i)(o.async===true||core.isAsyncFunction(o.execute))&&e.add(r),(o.interactive===true||core.isGeneratorFunction(o.execute))&&t.add(r);return {asyncHandlerSet:e,interactiveHandlerSet:t}}function Ue(i,e,t,r){let o=t?te(i,true,false):e,n=r?te(i,t,true):null;return {handlersAsync:o,handlersInteractive:n}}function Ae(i,e){return e?{next:()=>Promise.resolve({value:i,done:true}),return:()=>Promise.resolve({value:i,done:true}),throw:o=>Promise.reject(o),[Symbol.asyncIterator](){return this}}:{next:()=>({value:i,done:true}),return:()=>({value:i,done:true}),throw:r=>{throw r},[Symbol.iterator](){return this}}}function qe(i,e,t,r,o,n){if(n){let c=i;return {async next(d){let h=await c.next(d);if(h.done){let f=h.value;if(o!==null){let p=o(e,t,f,r);p!==void 0&&(f=p);}return {value:f,done:true}}return {value:h.value,done:false}},async return(){let d=await c.return(void 0),h=d.value;if(d.done&&o!==null){let f=o(e,t,h,r);f!==void 0&&(h=f);}return {value:h,done:true}},async throw(d){let h=await c.throw(d);if(h.done){let f=h.value;if(o!==null){let p=o(e,t,f,r);p!==void 0&&(f=p);}return {value:f,done:true}}return {value:h.value,done:false}},[Symbol.asyncIterator](){return this}}}let s=i;return {next(c){let u=s.next(c);if(u.done){let d=u.value;if(o!==null){let h=o(e,t,d,r);h!==void 0&&(d=h);}return {value:d,done:true}}return {value:u.value,done:false}},return(){let c=s.return(void 0),u=c.value;if(c.done&&o!==null){let d=o(e,t,u,r);d!==void 0&&(u=d);}return {value:u,done:true}},throw(c){let u=s.throw(c);if(u.done){let d=u.value;if(o!==null){let h=o(e,t,d,r);h!==void 0&&(d=h);}return {value:d,done:true}}return {value:u.value,done:false}},[Symbol.iterator](){return this}}}var Dt=8,At="type",be={maxDepth:10,maxRules:1e4,maxDirectives:1e5},Re=class{_directiveExecutor;_mode;_ctx;_requestedMode;_threshold;_limits;_typeField;_handlers;_handlersAsync;_handlersInteractive;_definitions;_directiveHooks;_directiveAnalysis;_asyncHandlerSet;_interactiveHandlerSet;_isAsync;_isInteractive;_directivePermissions;_subDirectiveFieldsForGraph;_subDirectiveFieldsAll;_miniGraph;_interactiveExecutor;_beforeAction;_afterAction;_registry=new Map;_emitter=new X;_batch=new le;_registeredIds=new Set;_directiveRunner;_directiveRunnerSync;_engineRef;constructor(e){this._requestedMode=e.mode??"auto",this._threshold=e.autoJitThreshold??Dt,this._typeField=e.typeField??At,this._limits={maxDepth:e.limits?.maxDepth??be.maxDepth,maxRules:e.limits?.maxRules??be.maxRules,maxDirectives:e.limits?.maxDirectives??be.maxDirectives};let{handlers:t,definitions:r}=Fe(e.handlers);Oe(Object.keys(e.handlers)),Ve(e.allowedDirectives,e.blockedDirectives),this._handlers=t,this._definitions=r,this._directivePermissions=Ne(Object.keys(t),e.allowedDirectives,e.blockedDirectives),this._directiveHooks=e.directiveHooks??{},this._beforeAction=e.actionHooks?.beforeAction??null,this._afterAction=e.actionHooks?.afterAction??null,this._directiveAnalysis=core.analyzeSlots(this._directiveHooks,core.DIRECTIVE_SLOT_NAMES);let{asyncHandlerSet:o,interactiveHandlerSet:n}=Ke(this._definitions);this._asyncHandlerSet=o,this._interactiveHandlerSet=n,this._isInteractive=e.interactive!==void 0,ze(this._isInteractive,n,this._definitions),this._isAsync=this._directiveAnalysis.hasAnyAsync||o.size>0;let{handlersAsync:s,handlersInteractive:a}=Ue(this._definitions,this._handlers,this._isAsync,this._isInteractive);this._handlersAsync=s,this._handlersInteractive=a;let c=He(this._definitions);this._subDirectiveFieldsForGraph=c,this._subDirectiveFieldsAll=Me(this._definitions),this._miniGraph=Le({typeField:this._typeField,asyncHandlerSet:o,interactiveHandlerSet:n,subDirectiveFieldsForGraph:c}),this._engineRef=this._buildEngineRef();let u=oe(this._directiveAnalysis,false);this._directiveRunner=this._buildDirectiveRunner(),this._directiveRunnerSync=this._buildDirectiveRunnerSync(u);let d=this._buildExecutors(u);this._directiveExecutor=d.directiveExecutor,this._mode=d.mode,this._interactiveExecutor=d.interactiveExecutor;}_buildEngineRef(){return {runDirectives:(e,t)=>this._executeDirectives(e,t),runDirectivesAsync:(e,t)=>this._executeDirectivesAsync(e,t),invoke:(e,t,r)=>this._invokeInternal(e,t,r),invokeAsync:(e,t,r)=>this._invokeInternalAsync(e,t,r),isActionAsync:e=>this._miniGraph.has(e)?this._miniGraph.isAsync(e):void 0,isActionInteractive:e=>this._miniGraph.has(e)?this._miniGraph.isInteractive(e):void 0,invokeInteractive:(e,t,r)=>this._invokeInteractiveInternal(e,t,r),runDirectivesInteractive:(e,t)=>this._executeDirectivesInteractive(e,t),evaluateRules:()=>{throw new Error("evaluateRules() not available in ActionEngine context. Use createRuleEngine().")},evaluateRulesAsync:()=>{throw new Error("evaluateRulesAsync() not available in ActionEngine context. Use createRuleEngine().")}}}_buildDirectiveRunner(){let e=this._isAsync?this._handlersAsync:this._handlers;return (t,r)=>this._directiveExecutor(t,r,e,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_buildDirectiveRunnerSync(e){return (t,r)=>e(t,r,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_buildExecutors(e){let t,r;this._requestedMode==="jit"?(t=this._buildJitDirectiveExecutor(),r="jit"):this._isAsync?(t=oe(this._directiveAnalysis,true),r="interpret"):(t=e,r="interpret");let o=this._isInteractive?this._isAsync?he(this._directiveAnalysis,true):he(this._directiveAnalysis,false):null;return {directiveExecutor:t,mode:r,interactiveExecutor:o}}register(e){let t=[],r=[],o=[],n=[];for(let c of e){if(!c.id){r.push({actionId:"",error:"Action must have an id"});continue}if(!this._isInteractive&&Q(c.directives,this._typeField,this._subDirectiveFieldsForGraph)){r.push({actionId:c.id,error:'Action uses directive type:"pause" but engine has no `interactive` config. Add `interactive: {}` to enable.'});continue}let u=ke(c,this._handlers,this._definitions,this._typeField);if(u.length>0){for(let d of u)r.push({actionId:c.id,error:d});continue}n.push(c);}for(let c of n){let u=B(c.directives,this._typeField,this._subDirectiveFieldsAll),d={definition:c,directives:u,compiled:null,invokeCount:0};this._registry.set(c.id,d),this._registeredIds.add(c.id),this._miniGraph.upsert(c.id,u,c.interactive===true),t.push(c.id);}if(this._batch.isActive())return this._batch.accumulate(r,o,n,t),{registered:t,errors:r,warnings:o};let s=t;if(n.length>0){this._miniGraph.recompute();let c=this._validateInteractiveVariants(t);c.errors.length>0&&r.push(...c.errors),c.warnings.length>0&&o.push(...c.warnings),s=c.validRegistered,this._invalidateAndMaybeRecompile();}let a={registered:s,errors:r,warnings:o};if(s.length>0){let c=new Set(s),u=n.filter(d=>c.has(d.id));this._emitter.emit("register",{actions:u,result:a,registered:s});}return a}unregister(e){let t=this._registry.delete(e);t&&(this._registeredIds.delete(e),this._miniGraph.remove(e));let r=e+"/",o=[];for(let n of this._registry.keys())n.startsWith(r)&&(this._registry.delete(n),this._registeredIds.delete(n),this._miniGraph.remove(n),o.push(n));return t&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile(),this._emitter.emit("unregister",{id:e,cascaded:o})),t}invoke(e,t,r){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);if(this._miniGraph.isAsync(e))throw new Error(`Cannot call invoke("${e}") \u2014 action is async (transitively). Use invokeAsync() instead.`);if(this._directiveAnalysis.hasAnyAsync)throw new Error(`Cannot call invoke("${e}") \u2014 engine has async directive hooks. Use invokeAsync() instead.`);let o=r!==void 0?r:this._requireCtx(),n=core.createRootFrame(o,this._limits);return this._invokeInternal(e,t,n)}async invokeAsync(e,t,r){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invokeAsync("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);let o=r!==void 0?r:this._requireCtx(),n=core.createRootFrame(o,this._limits);return this._invokeInternalAsync(e,t,n)}setContext(e){this._ctx=e;}context(e,t){let r=this._ctx;this._ctx=e;try{return t()}finally{this._ctx=r;}}beginBatch(){this._batch.begin();}endBatch(){if(!this._batch.endDepth())return {registered:[],errors:[],warnings:[]};let t=this._batch.registered;if(this._batch.registered.length>0){this._miniGraph.recompute();let o=this._validateInteractiveVariants(this._batch.registered);this._batch.errors.push(...o.errors),this._batch.warnings.push(...o.warnings),t=o.validRegistered,this._invalidateAndMaybeRecompile();}let r={registered:t,errors:this._batch.errors,warnings:this._batch.warnings};if(t.length>0){let o=new Set(t),n=this._batch.actions.filter(s=>o.has(s.id));this._emitter.emit("register",{actions:n,result:r,registered:t});}return r}on(e,t){return this._emitter.on(e,t)}get handlerDefinitions(){return this._definitions}get registeredIds(){return this._registeredIds}getActionDefinition(e){return this._registry.get(e)?.definition}get typeField(){return this._typeField}get subDirectiveFieldsForGraph(){return this._subDirectiveFieldsForGraph}get directivePermissions(){return this._directivePermissions}get isAsync(){return this._isAsync}get isInteractive(){return this._isInteractive}isActionAsync(e){if(this._miniGraph.has(e))return this._miniGraph.isAsync(e)}isActionInteractive(e){if(this._miniGraph.has(e))return this._miniGraph.isInteractive(e)}invokeInteractive(e,t,r){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("Cannot call invokeInteractive() \u2014 engine has no `interactive` config. Add `interactive: {}` to enable.");let o=r!==void 0?r:this._requireCtx(),n=core.createRootFrame(o,this._limits);return this._invokeInteractiveInternal(e,t,n)}_invokeInteractiveInternal(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return Ae(o,this._isAsync);let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return Ae(ae(u.data,s.counters),this._isAsync)}let c;if(n.compiled&&n.compiled.isInteractive)c=n.compiled.fn(s,s.scope,n.compiled.$);else {let u=this._interactiveExecutor;c=u(n.directives,s,this._handlersInteractive,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);}return qe(c,e,t,s,this._afterAction,this._isAsync)}_executeDirectivesInteractive(e,t){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("runDirectivesInteractive: engine has no `interactive` config");return this._interactiveExecutor(e,t,this._handlersInteractive,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}get compilationMode(){return this._mode}get directiveHookSlots(){return this._directiveAnalysis.filledNames}get asyncSlots(){return this._directiveAnalysis.asyncNames}compile(){if(this._requestedMode!=="interpret"){this._mode!=="jit"&&this._promote();for(let[e,t]of this._registry)t.compiled||(t.compiled=this._compileAction(e,t.directives));}}_invokeInternal(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return o;let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return ae(u.data,s.counters)}let c;if(n.compiled?c=n.compiled.fn(s,a,n.compiled.$):this._isAsync&&!this._miniGraph.isAsync(e)?(n.compiled=this._compileAction(e,n.directives),c=n.compiled.fn(s,a,n.compiled.$)):(c=this._directiveRunner(n.directives,s),this._maybeAutoPromote(n)),this._afterAction!==null){let u=this._afterAction(e,t,c,s);u!==void 0&&(c=u);}return c}async _invokeInternalAsync(e,t,r){let o=this._prepareInvoke(e,t,r);if("success"in o)return o;let{stored:n,childFrame:s,childScope:a}=o;if(this._beforeAction!==null){let u=this._beforeAction(e,t,s);if(u?.skip)return ae(u.data,s.counters)}let c;if(n.compiled?c=await n.compiled.fn(s,a,n.compiled.$):(c=await this._directiveRunner(n.directives,s),this._maybeAutoPromote(n)),this._afterAction!==null){let u=this._afterAction(e,t,c,s);u!==void 0&&(c=u);}return c}_prepareInvoke(e,t,r){let o=this._registry.get(e);if(!o)return Te(e,r.counters);if(e.includes("/")&&!this._isAccessible(e,r))return $e(e,r.counters);if(r.depth>=r.limits.maxDepth)return Se(e,r.limits.maxDepth,r.counters);let n=Object.create(r.scope);t&&Object.assign(n,t);let s=r.child("action:"+e,0,e).withScope(n);return {stored:o,childFrame:s,childScope:n}}_maybeAutoPromote(e){this._requestedMode==="auto"&&++e.invokeCount>=this._threshold&&(e.compiled=this._compileAction(e.definition.id,e.directives),this._mode!=="jit"&&this._promote());}_executeDirectives(e,t){return this._directiveExecutor(e,t,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}async _executeDirectivesAsync(e,t){return this._directiveExecutor(e,t,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_compileAction(e,t){let r=this._miniGraph.isAsync(e),o=this._miniGraph.isInteractive(e),n=Pe(this._definitions,o,this._interactiveHandlerSet),{fn:s,isAsync:a,isInteractive:c}=_e(t,this._directiveAnalysis,this._typeField,this._asyncHandlerSet,r,o,n),u=te(this._definitions,a,c),d={d:t,h:u,hooks:this._directiveHooks,engine:this._engineRef,runner:this._directiveRunner,runnerSync:this._directiveRunnerSync};return {fn:s,$:d,isAsync:a,isInteractive:c}}_isAccessible(e,t){let o="action:"+e.slice(0,e.lastIndexOf("/"));return t.path.includes(o)}_requireCtx(){if(this._ctx===void 0)throw new Error("No context set. Pass ctx to invoke(id, params, ctx), call setContext(ctx), or use context(ctx, fn).");return this._ctx}_promote(){this._directiveExecutor=this._buildJitDirectiveExecutor(),this._mode="jit";}_buildJitDirectiveExecutor(){let{fn:e}=ye(this._directiveAnalysis,this._isAsync);return e}_validateInteractiveVariants(e){let t=[],r=[],o=new Set(e),n=new Set;for(let a of this._registeredIds){if(!this._miniGraph.isInteractive(a))continue;let c=this._registry.get(a);if(c===void 0)continue;let u=Ee(c.directives,this._typeField,this._definitions,this._subDirectiveFieldsForGraph,this._interactiveHandlerSet,h=>this._miniGraph.isInteractive(h),core.isGeneratorFunction);if(u.size===0)continue;let d=o.has(a);for(let h of u){let f=`Action "${a}" is transitively interactive but handler "${h}" has no executeInteractive variant (and execute is not a generator function, and interactive flag is not set)`;d?(t.push({actionId:a,error:f,code:"MISSING_INTERACTIVE_VARIANT"}),n.add(a)):r.push({actionId:a,code:"MISSING_INTERACTIVE_VARIANT",message:f});}}if(n.size>0){for(let a of n)this._registry.delete(a),this._registeredIds.delete(a),this._miniGraph.remove(a);this._miniGraph.recompute();}return {validRegistered:e.filter(a=>!n.has(a)),errors:t,warnings:r}}_invalidateAndMaybeRecompile(){for(let e of this._registry.values())e.compiled=null;if(this._requestedMode==="jit")for(let[e,t]of this._registry)t.compiled=this._compileAction(e,t.directives);}};function Ct(i){return new Re(i)}exports.RESERVED_TYPES=N;exports.SimpleEmitter=X;exports.buildActionExecutor=_e;exports.buildDirectiveExecutor=ye;exports.createActionEngine=Ct;exports.createDirectiveInterpreter=oe;exports.drainAsync=Je;exports.drainSync=We;exports.normalizeDirectives=B;exports.replayResponder=Ye;