@statedelta-actions/actions 0.6.0 → 0.7.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,29 @@
1
1
  # @statedelta-actions/actions
2
2
 
3
+ ## 0.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - fc436a7: Add sub-directives descriptor (ADR-029)
8
+
9
+ Handlers can now declare child sub-array fields via `subDirectives` —
10
+ feeds register validation (with `required` throw), normalize, mini-graph
11
+ propagation (async/interactive transitive) and analyzer walks
12
+ (denied-scan, capabilities). `if` and `catch` remain hardcoded with
13
+ their optimizations; descriptor is additive.
14
+
15
+ `HandlerDefinition` and `SubDirectiveFieldConfig` gain inspection
16
+ metadata exposed via `engine.handlerDefinitions`: `description`, `tags`,
17
+ `deprecated`, `since`, `aliasOf` on the handler; `description`,
18
+ `purpose`, `examples`, `tags` on sub-fields.
19
+
20
+ The analyzer's `IAnalyzableEngine` interface gains
21
+ `subDirectiveFieldsForGraph` (consumers implementing it for tests/mocks
22
+ must add the field). Bug fix bundled: denied-scan and capabilities walk
23
+ now recurse into `if.then`/`if.else` (previously only `catch`).
24
+
25
+ New `validate` script (`pnpm typecheck && pnpm lint`) on both packages.
26
+
3
27
  ## 0.6.0
4
28
 
5
29
  ### 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}() => {
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(`
1
+ 'use strict';var core=require('@statedelta-actions/core');function Ie(o,e){let n;for(;;){let i=o.next(n);if(i.done)return i.value;n=e?e(i.value):void 0;}}async function Ee(o,e){let n;for(;;){let i=await o.next(n);if(i.done)return i.value;n=e?await e(i.value):void 0;}}function we(o){let e=0;return ()=>{if(!(e>=o.length))return o[e++]}}var O=class{_listeners=new Map;on(e,n){let i=this._listeners.get(e);i||(i=new Set,this._listeners.set(e,i)),i.add(n);let s=false;return ()=>{s||(s=true,i.delete(n),i.size===0&&this._listeners.delete(e));}}once(e,n){let i=this.on(e,s=>{i(),n(s);});return i}emit(e,n){let i=this._listeners.get(e);if(!i||i.size===0)return;let s=[...i];for(let t=0;t<s.length;t++)try{s[t](n);}catch(r){console.error(`[SimpleEmitter] Listener error on "${e}":`,r);}}listenerCount(e){return this._listeners.get(e)?.size??0}hasListeners(e){let n=this._listeners.get(e);return n!==void 0&&n.size>0}off(e){this._listeners.delete(e);}removeAllListeners(){this._listeners.clear();}};var N=new Set(["const","let","return","throw","pause","if"]);function le(o,e,n,i){let s=[];return q(o.directives,e,n,i,"directive",s,o.id),s}function q(o,e,n,i,s,t,r){for(let d=0;d<o.length;d++){let c=o[d],u=c[i],h=`${s}[${d}]`;if(!u){t.push(`${h}: missing type field "${i}"`);continue}if(u==="if"){let g=c.cond;typeof g!="function"&&typeof g!="boolean"&&t.push(`${h}: "if" requires cond as function or boolean`);let f=c.then;Array.isArray(f)?q(f,e,n,i,`${h}.then`,t,r):t.push(`${h}: "if" requires then as array`);let D=c.else;D!==void 0&&(Array.isArray(D)?q(D,e,n,i,`${h}.else`,t,r):t.push(`${h}.else: must be array`));continue}if(N.has(u))continue;if(!e[u])throw new Error(`Action "${r}" ${h}: no handler registered for type "${u}". Register the handler in createActionEngine({ handlers }) before registering this action.`);let C=n.get(u);if(C?.validate)try{let g=C.validate(c);g&&!g.valid&&t.push(`${h}: ${g.error??"validation failed"}`);}catch(g){t.push(`${h}: validate threw: ${g}`);}let y=c.catch;if(y&&Array.isArray(y))for(let g=0;g<y.length;g++){let D=y[g][i];if(!(D&&N.has(D))&&D&&!e[D])throw new Error(`Action "${r}" ${h}.catch[${g}]: no handler registered for type "${D}". Register the handler in createActionEngine({ handlers }) before registering this action.`)}let p=C?.subDirectives;if(p===void 0)continue;let m=Object.keys(p);for(let g=0;g<m.length;g++){let f=m[g];if(f==="catch")continue;let D=c[f];if(D===void 0){if(p[f].required)throw new Error(`Action "${r}" ${h}: handler "${u}" requires sub-directives field "${f}"`);continue}if(!Array.isArray(D))throw new Error(`Action "${r}" ${h}.${f}: must be an array of directives`);q(D,e,n,i,`${h}.${f}`,t,r);}}}var Te=new Map;function L(o,e,n=Te){let i=o.length,s=new Array(i);for(let t=0;t<i;t++){let r=o[t],d=r[e],c=r,u=false,h=r.catch;if(Array.isArray(h)&&h.length>0&&(c={...c,catch:L(h,e,n)},u=true),d==="if"){let C=r.then;Array.isArray(C)&&C.length>0&&(c={...c,then:L(C,e,n)},u=true);let y=r.else;Array.isArray(y)&&y.length>0&&(c={...c,else:L(y,e,n)},u=true);}else if(d!==void 0){let C=n.get(d);if(C!==void 0)for(let y=0;y<C.length;y++){let p=C[y],m=r[p];!Array.isArray(m)||m.length===0||(c={...c,[p]:L(m,e,n)},u=true);}}s[t]=u?c:r;}return s}function W(o,e,n,i,s,t,r){return {success:false,aborted:true,abortedBy:o,appliedCount:e,skippedCount:n,errors:i,processedCount:s,totalCount:t,counters:r}}function $e(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return function(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=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,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="value"in l?l.value:"return"in l?l.return:x.value;return {success:!0,aborted:!1,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.value};continue}if(E==="throw"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="message"in l?l.message:"throw"in l?l.throw:x.message;return {success:!1,aborted:!0,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:false,aborted:true,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.message};continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=core.processIntercept(c.beforeDirective(_,r),"beforeDirective");if(a.action===core.Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===core.Intercept.ABORT)return W(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{b=F(_,k,h);}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return {success:false,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data};let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=h.runDirectives(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(c.afterDirective(_,b,k)==="abort")return W("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{c.onDirectivesComplete(P);}catch{}return P}}function Se(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return async function(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=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,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="value"in l?l.value:"return"in l?l.return:x.value;return {success:!0,aborted:!1,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.value};continue}if(E==="throw"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="message"in l?l.message:"throw"in l?l.throw:x.message;return {success:!1,aborted:!0,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:false,aborted:true,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.message};continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=core.processIntercept(await c.beforeDirective(_,r),"beforeDirective");if(a.action===core.Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===core.Intercept.ABORT)return W(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{b=await F(_,k,h);}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return {success:false,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data};let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=await h.runDirectivesAsync(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(await c.afterDirective(_,b,k)==="abort")return W("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{await c.onDirectivesComplete(P);}catch{}return P}}function J(o,e){return e?Se(o):$e(o)}function B(o,e,n,i,s,t,r,d){return {success:false,aborted:true,abortedBy:o,appliedCount:e,skippedCount:n,errors:i,processedCount:s,totalCount:t,counters:r,data:d}}function pe(o){if(o===null||typeof o!="object")return null;if(typeof o.next=="function")return o;let e=o.iterator;return e!=null&&typeof e=="object"&&typeof e.next=="function"?e:null}function He(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return function*(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=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,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I,l=x.value;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="value"in v?v.value:"return"in v?v.return:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:l}}if(E==="throw"){let a=I,l=x.message;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="message"in v?v.message:"throw"in v?v.throw:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return B("throw",m,g,p,a,y,f,l)}if(E==="pause"){let a=I,l=yield {source:"pause",directive:x,frame:r,index:A,payload:{message:x.message}};if(l===false||l==="abort"||l==="cancel")return B("pause",m,g,p,a,y,f,l);m++,f.directivesApplied++,typeof x.as=="string"&&l!==void 0&&(D[x.as]=l);continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=core.processIntercept(c.beforeDirective(_,r),"beforeDirective");if(a.action===core.Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===core.Intercept.ABORT)return B(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{let a=F(_,k,h),l=pe(a);l!==null?b=yield*l:b=a;}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return B("halt",m,g,p,H,y,f,b.data);let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=h.runDirectives(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(c.afterDirective(_,b,k)==="abort")return B("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{c.onDirectivesComplete(P);}catch{}return P}}function Me(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return async function*(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=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,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I,l=x.value;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="value"in v?v.value:"return"in v?v.return:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:l}}if(E==="throw"){let a=I,l=x.message;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="message"in v?v.message:"throw"in v?v.throw:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return B("throw",m,g,p,a,y,f,l)}if(E==="pause"){let a=I,l=yield {source:"pause",directive:x,frame:r,index:A,payload:{message:x.message}};if(l===false||l==="abort"||l==="cancel")return B("pause",m,g,p,a,y,f,l);m++,f.directivesApplied++,typeof x.as=="string"&&l!==void 0&&(D[x.as]=l);continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=core.processIntercept(await c.beforeDirective(_,r),"beforeDirective");if(a.action===core.Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===core.Intercept.ABORT)return B(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{let a=await F(_,k,h),l=pe(a);l!==null?b=yield*l:b=a;}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return B("halt",m,g,p,H,y,f,b.data);let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=await h.runDirectivesAsync(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(await c.afterDirective(_,b,k)==="abort")return B("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{await c.onDirectivesComplete(P);}catch{}return P}}function ee(o,e){return e?Me(o):He(o)}function te(o,e=o.hasAnyAsync){let{filledNames:n}=o,i=h=>n.has(h),s=h=>o.asyncNames.has(h)?"await ":"",t=e?"await ":"",r=[];for(let h of n)r.push(`const ${h} = directiveHooks.${h};`);r.push("const len = Math.min(directives.length, maxDirectives);"),r.push("const errors = []; let appliedCount = 0; let skippedCount = 0;"),r.push("const counters = frame.counters;"),r.push("for (let i = 0; i < len; i++) {"),r.push(" let directive = directives[i];"),i("beforeDirective")?(r.push(" let _df = frame;"),r.push(" try {"),r.push(` const _bd = ${s("beforeDirective")}beforeDirective(directive, frame);`),r.push(' if (_bd === "skip") { skippedCount++; counters.directivesSkipped++; continue; }'),r.push(' if (_bd === "abort") return { success: false, aborted: true, abortedBy: "beforeDirective", appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),r.push(' if (typeof _bd === "object" && _bd !== null) {'),r.push(' if ("abort" in _bd) return { success: false, aborted: true, abortedBy: _bd.abort, appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),r.push(' if ("ctx" in _bd) _df = frame.withCtx(_bd.ctx);'),r.push(' if ("directive" in _bd) directive = _bd.directive;'),r.push(" }"),r.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook beforeDirective: " + _e }); counters.errors++; }')):r.push(" const _df = frame;"),r.push(' if (typeof directive.resolve === "function") {'),r.push(" try { const _r = directive.resolve(_df.ctx); directive = Object.assign({}, directive, _r); }"),r.push(' catch (_e) { errors.push({ directiveIndex: i, error: "Directive resolve: " + _e }); counters.errors++; continue; }'),r.push(" }"),r.push(" const _type = directive[typeField];"),r.push(" const _handler = _type ? handlers[_type] : undefined;"),r.push(' if (!_handler) { errors.push({ directiveIndex: i, error: "No handler for directive type: " + (_type || "undefined") }); counters.errors++; continue; }'),r.push(" let _result;"),r.push(` try { _result = ${t}_handler(directive, _df, engine); } catch (_e) { errors.push({ directiveIndex: i, error: String(_e) }); counters.errors++; continue; }`),r.push(" if (_result.ok) { appliedCount++; counters.directivesApplied++; }"),r.push(' else { errors.push({ directiveIndex: i, error: _result.error || "handler failed" }); counters.errors++; }'),i("afterDirective")&&(r.push(" try {"),r.push(` const _ad = ${s("afterDirective")}afterDirective(directive, _result, _df);`),r.push(' if (_ad === "abort") return { success: false, aborted: true, abortedBy: "afterDirective", appliedCount, skippedCount, errors, processedCount: i + 1, totalCount: len, counters };'),r.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook afterDirective: " + _e }); counters.errors++; }')),r.push("}"),r.push("const _finalResult = { success: true, aborted: false, appliedCount, skippedCount, errors, processedCount: len, totalCount: len, counters };"),i("onDirectivesComplete")&&r.push(`try { ${s("onDirectivesComplete")}onDirectivesComplete(_finalResult); } catch (_e) {}`),r.push("return _finalResult;");let d=r.join(`
2
+ `),c=e?"async ":"";return {fn:new Function("directives","frame","handlers","directiveHooks","typeField","engine","maxDirectives",`"use strict";
3
+ return (${c}() => {
4
+ ${d}
5
+ })();`),isAsync:e}}function re(o,e,n){return `return{success:false,aborted:true,abortedBy:${o},appliedCount,skippedCount,errors,processedCount:${e},totalCount:${n},counters};`}function Pe(o,e){return `return{success:true,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${e},counters,data:_result.data};`}function Fe(o,e){return `return{success:false,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${e},counters,data:_result.data};`}function Be(o,e,n,i){let s=JSON.stringify(e.name);typeof e.resolve=="function"?(o.push("try{"),o.push(`scope[${s}]=${n}.resolve(ctx,scope).value;`),o.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Binding resolve: "+_e});counters.errors++;}`)):o.push(`scope[${s}]=${n}.value;`);}function Ge(o,e,n,i,s,t){typeof e.resolve=="function"?(o.push("try{"),o.push(`const _rv=${n}.resolve(ctx,scope);`),o.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:"value" in _rv?_rv.value:"return" in _rv?_rv.return:${n}.value};`),o.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Control resolve: "+_e});counters.errors++;}`)):o.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:${n}.value};`);}function Le(o,e,n,i,s,t){typeof e.resolve=="function"?(o.push("try{"),o.push(`const _rv=${n}.resolve(ctx,scope);`),o.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:"message" in _rv?_rv.message:"throw" in _rv?_rv.throw:${n}.message};`),o.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Control resolve: "+_e});counters.errors++;}`)):o.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:${n}.message};`);}function Ne(o,e,n,i,s,t){let r=typeof e.as=="string",d=r?JSON.stringify(e.as):"";o.push(`{const _ack=yield{source:"pause",directive:${n},frame,index:${i},payload:{message:${n}.message}};`),o.push(`if(_ack===false||_ack==="abort"||_ack==="cancel")return{success:false,aborted:true,abortedBy:"pause",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:_ack};`),o.push("appliedCount++;counters.directivesApplied++;"),r&&o.push(`if(_ack!==undefined)scope[${d}]=_ack;`),o.push("}");}function je(o,e,n,i,s){let{L:t,total:r,typeField:d,handlerVars:c,hasBefore:u,hasAfter:h,awBefore:C,awAfter:y,awHandler:p,actionIsAsync:m,actionIsInteractive:g,interactiveHandlerSet:f}=s,D=o[d],$=c.get(D),w=typeof o.resolve=="function",I=typeof o.as=="string",P=Array.isArray(o.catch)&&o.catch.length>0,R=I?JSON.stringify(o.as):"",T=g&&f.has(D),S=s.blockCounter.n++;t.push(`_b${S}:{`);let A=u||w,x=u;A&&t.push(`let _dir=${e};`),x&&t.push("let _df=frame;"),u&&(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")${re('"beforeDirective"',i-1,r)}`),t.push('if(typeof _bd==="object"&&_bd!==null){'),t.push(`if("abort" in _bd)${re("_bd.abort",i-1,r)}`),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:${n},error:"Hook beforeDirective: "+_e});counters.errors++;}`)),u?(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:${n},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:${n},error:"Directive resolve: "+_e});counters.errors++;break _b${S};}`));let E=A?"_dir":e,_=x?"_df":"frame";if(t.push("let _result;"),T?(t.push(`try{_result=yield* ${$}(${E},${_},$.engine);}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")):g?(t.push(`try{_result=${p}${$}(${E},${_},$.engine);if(_result&&_result.iterator)_result=yield* _result.iterator;}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")):(t.push(`try{_result=${p}${$}(${E},${_},$.engine);}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")),t.push("if(_result.ok){"),t.push("appliedCount++;counters.directivesApplied++;"),I&&t.push(`scope[${R}]=_result.data;`),t.push(`if(_result.halt)${Pe(i,r)}`),t.push("}else{"),t.push(`if(_result.halt)${Fe(i,r)}`),P){t.push('scope.$exception=_result.error||"handler failed";');let k=m?"$.runner":"$.runnerSync";t.push(`const _cr=${p}${k}(${e}.catch,${_});`),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:${r},counters,data:_cr.data};`);}else t.push(`errors.push({directiveIndex:${n},error:_result.error||"handler failed"});counters.errors++;`);t.push("}"),h&&(t.push("try{"),t.push(`const _ad=${y}_hookAfter(${E},_result,${_});`),t.push(`if(_ad==="abort")${re('"afterDirective"',i,r)}`),t.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Hook afterDirective: "+_e});counters.errors++;}`)),t.push("}");}function Oe(o,e,n,i,s,t){let{L:r}=t,d=o.cond,c=typeof d=="boolean";r.push("{"),c?r.push(`if(${d?"true":"false"}){`):(r.push("let _cond=false,_condOk=true;"),r.push(`try{const _c=${e}.cond;_cond=typeof _c==="function"?!!_c(ctx,scope):!!_c;}`),r.push(`catch(_e){errors.push({directiveIndex:${n},error:"if cond: "+_e});counters.errors++;_condOk=false;}`),r.push("if(_condOk){"),r.push("if(_cond){"));let u=o.then;Array.isArray(u)&&u.length>0&&ne(u,`${e}.then`,i,s,t),r.push("}");let h=o.else;Array.isArray(h)&&h.length>0&&(r.push("else{"),ne(h,`${e}.else`,i,s,t),r.push("}")),c||r.push("}"),r.push("}");}function ne(o,e,n,i,s){let t=n!==-1;for(let r=0;r<o.length;r++){let d=o[r],c=`${e}[${r}]`,u=t?n:r,h=t?i:r+1;switch(d[s.typeField]){case "const":case "let":Be(s.L,d,c,u);break;case "return":Ge(s.L,d,c,u,h,s.total);break;case "throw":Le(s.L,d,c,u,h,s.total);break;case "pause":Ne(s.L,d,c,u,h,s.total);break;case "if":{let y=t?n:r,p=t?i:r+1;Oe(d,c,u,y,p,s);break}default:je(d,c,u,h,s);break}}}function ie(o,e,n){for(let i of o){let s=i[e];if(s&&!N.has(s)&&n.add(s),s==="if"){let t=i.then;Array.isArray(t)&&t.length>0&&ie(t,e,n);let r=i.else;Array.isArray(r)&&r.length>0&&ie(r,e,n);}}}var he=new Set;function se(o,e,n,i=he,s,t=false,r=he){let d=[],c=o.length,{filledNames:u,hasAnyAsync:h,asyncNames:C}=e,y=u.has("beforeDirective"),p=u.has("afterDirective"),m=u.has("onDirectivesComplete"),g=s!==void 0?s:Q(o,i,n),f=h||g,D=f?"await ":"",$=C.has("beforeDirective")?"await ":"",w=C.has("afterDirective")?"await ":"",I=C.has("onDirectivesComplete")?"await ":"",P=new Set;ie(o,n,P);let R=new Map,T=0;for(let k of P)R.set(k,`_h${T++}`);d.push("const counters=frame.counters;"),d.push("const ctx=frame.ctx;"),d.push("const errors=[];"),d.push("let appliedCount=0;"),d.push("let skippedCount=0;");for(let[k,M]of R)d.push(`const ${M}=$.h[${JSON.stringify(k)}];`);y&&d.push("const _hookBefore=$.hooks.beforeDirective;"),p&&d.push("const _hookAfter=$.hooks.afterDirective;"),ne(o,"$.d",-1,0,{L:d,total:c,typeField:n,handlerVars:R,hasBefore:y,hasAfter:p,awBefore:$,awAfter:w,awHandler:D,actionIsAsync:f,actionIsInteractive:t,interactiveHandlerSet:r,blockCounter:{n:0}}),d.push(`const _finalResult={success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${c},totalCount:${c},counters};`),m&&d.push(`try{${I}$.hooks.onDirectivesComplete(_finalResult);}catch(_e){}`),d.push("return _finalResult;");let x=`{
6
+ ${d.join(`
7
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;
8
+ }`,E;return t?E=`(${f?"async function*()":"function*()"}${x})()`:E=`(${f?"async ()=>":"()=>"}${x})()`,{fn:new Function("frame","scope","$",`"use strict";
9
+ return ${E};`),isAsync:f,isInteractive:t}}function Q(o,e,n){for(let i of o){let s=i[n];if(s&&e.has(s))return true;if(s==="if"){let r=i.then;if(Array.isArray(r)&&r.length>0&&Q(r,e,n))return true;let d=i.else;if(Array.isArray(d)&&d.length>0&&Q(d,e,n))return true}let t=i.catch;if(Array.isArray(t)&&t.length>0&&Q(t,e,n))return true}return false}function oe(o,e,n){return {success:false,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[{directiveIndex:-1,error:e}],counters:o,...n}}function ve(o,e){return oe(e,`Action not found: "${o}"`,{aborted:true,abortedBy:"action-not-found"})}function ye(o,e,n){return oe(n,`Max depth ${e} exceeded invoking "${o}"`,{aborted:true,abortedBy:"maxDepth"})}function xe(o,e){return oe(e,`Action "${o}" is private (sub-action). Can only be invoked from within its parent scope.`)}function X(o,e){return {success:true,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[],data:o,counters:e}}function Ke(o){return typeof o=="object"&&o!==null&&"execute"in o}function ge(o){let e=new Map;for(let[n,i]of o){let s=i.subDirectives;if(!s)continue;let t=Object.keys(s);if(t.length===0)continue;let r=null;for(let d=0;d<t.length;d++){let c=t[d];c!=="catch"&&s[c].graph!==false&&(r===null&&(r=[]),r.push(c));}r!==null&&e.set(n,r);}return e}function me(o){let e=new Map;for(let[n,i]of o){let s=i.subDirectives;if(!s)continue;let t=Object.keys(s);if(t.length===0)continue;let r=null;for(let d=0;d<t.length;d++){let c=t[d];c!=="catch"&&(r===null&&(r=[]),r.push(c));}r!==null&&e.set(n,r);}return e}function _e(o){let e=Object.create(null),n=new Map;for(let i of Object.keys(o)){let s=o[i];Ke(s)?(e[i]=s.execute,n.set(i,s)):(e[i]=s,n.set(i,{execute:s}));}return {handlers:e,definitions:n}}function De(o,e){if(o==="*")return true;if(!o.includes("*"))return o===e;let n=o.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)}function Ce(o){return typeof o=="string"?{pattern:o}:o}function be(o,e,n){let i=new Map;if(!e&&!n){for(let s of o)i.set(s,{status:"available"});return i}if(e){let s=e.map(Ce);for(let t of o){let r=s.some(d=>De(d.pattern,t));i.set(t,{status:r?"available":"denied"});}}else {let s=n.map(Ce);for(let t of o){let r=s.find(d=>De(d.pattern,t));r?i.set(t,{status:"denied",reason:r.reason,source:r.source}):i.set(t,{status:"available"});}}return i}function Re(o){let{typeField:e,asyncHandlerSet:n,interactiveHandlerSet:i,subDirectiveFieldsForGraph:s}=o,t=new Map,r=new Set,d=new Set,c=new Set,u=new Set;return {upsert(h,C,y){t.set(h,Ue(C,e,s)),U(C,n,e,s)?r.add(h):r.delete(h),y||z(C,i,e,s)?d.add(h):d.delete(h);},remove(h){t.delete(h),r.delete(h),d.delete(h);},recompute(){c=Ae(t,r),u=Ae(t,d);},isAsync(h){return c.has(h)},isInteractive(h){return u.has(h)},has(h){return t.has(h)}}}var Z=new Map;function Ue(o,e,n=Z){let i=new Set;return K(o,e,n,i),i}function K(o,e,n,i){for(let s of o){let t=s[e];t==="action"&&typeof s.id=="string"&&i.add(s.id);let r=s.catch;if(Array.isArray(r)&&r.length>0&&K(r,e,n,i),t==="if"){let c=s.then;Array.isArray(c)&&c.length>0&&K(c,e,n,i);let u=s.else;Array.isArray(u)&&u.length>0&&K(u,e,n,i);continue}if(t===void 0)continue;let d=n.get(t);if(d!==void 0)for(let c=0;c<d.length;c++){let u=s[d[c]];!Array.isArray(u)||u.length===0||K(u,e,n,i);}}}function U(o,e,n,i=Z){for(let s of o){let t=s[n];if(t!==void 0&&e.has(t))return true;let r=s.catch;if(Array.isArray(r)&&r.length>0&&U(r,e,n,i))return true;if(t==="if"){let c=s.then;if(Array.isArray(c)&&c.length>0&&U(c,e,n,i))return true;let u=s.else;if(Array.isArray(u)&&u.length>0&&U(u,e,n,i))return true;continue}if(t===void 0)continue;let d=i.get(t);if(d!==void 0)for(let c=0;c<d.length;c++){let u=s[d[c]];if(!(!Array.isArray(u)||u.length===0)&&U(u,e,n,i))return true}}return false}function z(o,e,n,i=Z){for(let s of o){let t=s[n];if(t==="pause"||t!==void 0&&e.has(t))return true;let r=s.catch;if(Array.isArray(r)&&r.length>0&&z(r,e,n,i))return true;if(t==="if"){let c=s.then;if(Array.isArray(c)&&c.length>0&&z(c,e,n,i))return true;let u=s.else;if(Array.isArray(u)&&u.length>0&&z(u,e,n,i))return true;continue}if(t===void 0)continue;let d=i.get(t);if(d!==void 0)for(let c=0;c<d.length;c++){let u=s[d[c]];if(!(!Array.isArray(u)||u.length===0)&&z(u,e,n,i))return true}}return false}function j(o,e,n=Z){for(let i of o){let s=i[e];if(s==="pause")return true;let t=i.catch;if(Array.isArray(t)&&t.length>0&&j(t,e,n))return true;if(s==="if"){let d=i.then;if(Array.isArray(d)&&d.length>0&&j(d,e,n))return true;let c=i.else;if(Array.isArray(c)&&c.length>0&&j(c,e,n))return true;continue}if(s===void 0)continue;let r=n.get(s);if(r!==void 0)for(let d=0;d<r.length;d++){let c=i[r[d]];if(!(!Array.isArray(c)||c.length===0)&&j(c,e,n))return true}}return false}function Ae(o,e){let n=new Set(e),i=true;for(;i;){i=false;for(let[s,t]of o)if(!n.has(s)){for(let r of t)if(n.has(r)){n.add(s),i=true;break}}}return n}var Je=8,Ye="type",ae={maxDepth:10,maxRules:1e4,maxDirectives:1e5},ue=class{_directiveExecutor;_mode;_ctx;_requestedMode;_threshold;_limits;_typeField;_handlers;_definitions;_directiveHooks;_directiveAnalysis;_asyncHandlerSet;_interactiveHandlerSet;_isAsync;_isInteractive;_directivePermissions;_subDirectiveFieldsForGraph;_subDirectiveFieldsAll;_miniGraph;_interactiveExecutor;_beforeAction;_afterAction;_registry=new Map;_emitter=new O;_batchDepth=0;_batchErrors=[];_batchWarnings=[];_batchActions=[];_batchRegistered=[];_registeredIds=new Set;_directiveRunner;_directiveRunnerSync;_engineRef;constructor(e){this._requestedMode=e.mode??"auto",this._threshold=e.autoJitThreshold??Je,this._typeField=e.typeField??Ye,this._limits={maxDepth:e.limits?.maxDepth??ae.maxDepth,maxRules:e.limits?.maxRules??ae.maxRules,maxDirectives:e.limits?.maxDirectives??ae.maxDirectives};let{handlers:n,definitions:i}=_e(e.handlers);for(let c of Object.keys(e.handlers))if(N.has(c))throw new Error(`Handler type "${c}" 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=n,this._definitions=i,this._directivePermissions=be(Object.keys(n),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 s=new Set,t=new Set;for(let[c,u]of this._definitions)(u.async===true||core.isAsyncFunction(u.execute))&&s.add(c),(u.interactive===true||core.isGeneratorFunction(u.execute))&&t.add(c);if(this._asyncHandlerSet=s,this._interactiveHandlerSet=t,this._isInteractive=e.interactive!==void 0,!this._isInteractive&&t.size>0){let c=Array.from(t).join(", ");throw new Error(`Handler(s) [${c}] are interactive but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}this._isAsync=this._directiveAnalysis.hasAnyAsync||s.size>0;let r=ge(this._definitions);this._subDirectiveFieldsForGraph=r,this._subDirectiveFieldsAll=me(this._definitions),this._miniGraph=Re({typeField:this._typeField,asyncHandlerSet:s,interactiveHandlerSet:t,subDirectiveFieldsForGraph:r}),this._engineRef={runDirectives:(c,u)=>this._executeDirectives(c,u),runDirectivesAsync:(c,u)=>this._executeDirectivesAsync(c,u),invoke:(c,u,h)=>this._invokeInternal(c,u,h),invokeAsync:(c,u,h)=>this._invokeInternalAsync(c,u,h),isActionAsync:c=>this._miniGraph.has(c)?this._miniGraph.isAsync(c):void 0,isActionInteractive:c=>this._miniGraph.has(c)?this._miniGraph.isInteractive(c):void 0,invokeInteractive:(c,u,h)=>this._invokeInteractiveInternal(c,u,h),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=(c,u)=>this._directiveExecutor(c,u,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);let d=J(this._directiveAnalysis,false);this._directiveRunnerSync=(c,u)=>d(c,u,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=J(this._directiveAnalysis,true),this._mode="interpret"):(this._directiveExecutor=d,this._mode="interpret"),this._interactiveExecutor=this._isInteractive?this._isAsync?ee(this._directiveAnalysis,true):ee(this._directiveAnalysis,false):null;}register(e){let n=[],i=[],s=[],t=[];for(let d of e){if(!d.id){i.push({actionId:"",error:"Action must have an id"});continue}if(!this._isInteractive&&j(d.directives,this._typeField,this._subDirectiveFieldsForGraph)){i.push({actionId:d.id,error:'Action uses directive type:"pause" but engine has no `interactive` config. Add `interactive: {}` to enable.'});continue}let c=le(d,this._handlers,this._definitions,this._typeField);if(c.length>0){for(let u of c)i.push({actionId:d.id,error:u});continue}t.push(d);}for(let d of t){let c=L(d.directives,this._typeField,this._subDirectiveFieldsAll),u={definition:d,directives:c,compiled:null,invokeCount:0};this._registry.set(d.id,u),this._registeredIds.add(d.id),this._miniGraph.upsert(d.id,c,d.interactive===true),n.push(d.id);}if(this._batchDepth>0){this._batchErrors.push(...i),this._batchWarnings.push(...s);for(let d of t)this._batchActions.push(d);return this._batchRegistered.push(...n),{registered:n,errors:i,warnings:s}}t.length>0&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile());let r={registered:n,errors:i,warnings:s};return n.length>0&&this._emitter.emit("register",{actions:t,result:r,registered:n}),r}unregister(e){let n=this._registry.delete(e);n&&(this._registeredIds.delete(e),this._miniGraph.remove(e));let i=e+"/",s=[];for(let t of this._registry.keys())t.startsWith(i)&&(this._registry.delete(t),this._registeredIds.delete(t),this._miniGraph.remove(t),s.push(t));return n&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile(),this._emitter.emit("unregister",{id:e,cascaded:s})),n}invoke(e,n,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 s=i!==void 0?i:this._requireCtx(),t=core.createRootFrame(s,this._limits);return this._invokeInternal(e,n,t)}async invokeAsync(e,n,i){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invokeAsync("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);let s=i!==void 0?i:this._requireCtx(),t=core.createRootFrame(s,this._limits);return this._invokeInternalAsync(e,n,t)}setContext(e){this._ctx=e;}context(e,n){let i=this._ctx;this._ctx=e;try{return n()}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,n){return this._emitter.on(e,n)}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,n,i){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("Cannot call invokeInteractive() \u2014 engine has no `interactive` config. Add `interactive: {}` to enable.");let s=i!==void 0?i:this._requireCtx(),t=core.createRootFrame(s,this._limits);return this._invokeInteractiveInternal(e,n,t)}_invokeInteractiveInternal(e,n,i){let s=this._prepareInvoke(e,n,i);if("success"in s)return ke(s,this._isAsync);let{stored:t,childFrame:r,childScope:d}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,n,r);if(u?.skip)return ke(X(u.data,r.counters),this._isAsync)}let c;if(t.compiled&&t.compiled.isInteractive)c=t.compiled.fn(r,r.scope,t.compiled.$);else {let u=this._interactiveExecutor;c=u(t.directives,r,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);}return Qe(c,e,n,r,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,n]of this._registry)n.compiled||(n.compiled=this._compileAction(e,n.directives));}}_invokeInternal(e,n,i){let s=this._prepareInvoke(e,n,i);if("success"in s)return s;let{stored:t,childFrame:r,childScope:d}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,n,r);if(u?.skip)return X(u.data,r.counters)}let c;if(t.compiled?c=t.compiled.fn(r,d,t.compiled.$):this._isAsync&&!this._miniGraph.isAsync(e)?(t.compiled=this._compileAction(e,t.directives),c=t.compiled.fn(r,d,t.compiled.$)):(c=this._directiveRunner(t.directives,r),this._maybeAutoPromote(t)),this._afterAction!==null){let u=this._afterAction(e,n,c,r);u!==void 0&&(c=u);}return c}async _invokeInternalAsync(e,n,i){let s=this._prepareInvoke(e,n,i);if("success"in s)return s;let{stored:t,childFrame:r,childScope:d}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,n,r);if(u?.skip)return X(u.data,r.counters)}let c;if(t.compiled?c=await t.compiled.fn(r,d,t.compiled.$):(c=await this._directiveRunner(t.directives,r),this._maybeAutoPromote(t)),this._afterAction!==null){let u=this._afterAction(e,n,c,r);u!==void 0&&(c=u);}return c}_prepareInvoke(e,n,i){let s=this._registry.get(e);if(!s)return ve(e,i.counters);if(e.includes("/")&&!this._isAccessible(e,i))return xe(e,i.counters);if(i.depth>=i.limits.maxDepth)return ye(e,i.limits.maxDepth,i.counters);let t=Object.create(i.scope);n&&Object.assign(t,n);let r=i.child("action:"+e,0,e).withScope(t);return {stored:s,childFrame:r,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,n){return this._directiveExecutor(e,n,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}async _executeDirectivesAsync(e,n){return this._directiveExecutor(e,n,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_compileAction(e,n){let i=this._miniGraph.isAsync(e),s=this._miniGraph.isInteractive(e),{fn:t,isAsync:r,isInteractive:d}=se(n,this._directiveAnalysis,this._typeField,this._asyncHandlerSet,i,s,this._interactiveHandlerSet),c={d:n,h:this._handlers,hooks:this._directiveHooks,engine:this._engineRef,runner:this._directiveRunner,runnerSync:this._directiveRunnerSync};return {fn:t,$:c,isAsync:r,isInteractive:d}}_isAccessible(e,n){let s="action:"+e.slice(0,e.lastIndexOf("/"));return n.path.includes(s)}_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}=te(this._directiveAnalysis,this._isAsync);return e}_invalidateAndMaybeRecompile(){for(let e of this._registry.values())e.compiled=null;if(this._requestedMode==="jit")for(let[e,n]of this._registry)n.compiled=this._compileAction(e,n.directives);}};function ke(o,e){return e?{next:()=>Promise.resolve({value:o,done:true}),return:()=>Promise.resolve({value:o,done:true}),throw:s=>Promise.reject(s),[Symbol.asyncIterator](){return this}}:{next:()=>({value:o,done:true}),return:()=>({value:o,done:true}),throw:i=>{throw i},[Symbol.iterator](){return this}}}function Qe(o,e,n,i,s,t){if(t){let c=o;return {async next(h){let C=await c.next(h);if(C.done){let y=C.value;if(s!==null){let p=s(e,n,y,i);p!==void 0&&(y=p);}return {value:y,done:true}}return {value:C.value,done:false}},async return(){let h=await c.return(void 0),C=h.value;if(h.done&&s!==null){let y=s(e,n,C,i);y!==void 0&&(C=y);}return {value:C,done:true}},async throw(h){let C=await c.throw(h);if(C.done){let y=C.value;if(s!==null){let p=s(e,n,y,i);p!==void 0&&(y=p);}return {value:y,done:true}}return {value:C.value,done:false}},[Symbol.asyncIterator](){return this}}}let r=o;return {next(c){let u=r.next(c);if(u.done){let h=u.value;if(s!==null){let C=s(e,n,h,i);C!==void 0&&(h=C);}return {value:h,done:true}}return {value:u.value,done:false}},return(){let c=r.return(void 0),u=c.value;if(c.done&&s!==null){let h=s(e,n,u,i);h!==void 0&&(u=h);}return {value:u,done:true}},throw(c){let u=r.throw(c);if(u.done){let h=u.value;if(s!==null){let C=s(e,n,h,i);C!==void 0&&(h=C);}return {value:h,done:true}}return {value:u.value,done:false}},[Symbol.iterator](){return this}}}function Xe(o){return new ue(o)}exports.RESERVED_TYPES=N;exports.SimpleEmitter=O;exports.buildActionExecutor=se;exports.buildDirectiveExecutor=te;exports.createActionEngine=Xe;exports.createDirectiveInterpreter=J;exports.drainAsync=Ee;exports.drainSync=Ie;exports.normalizeDirectives=L;exports.replayResponder=we;
package/dist/index.d.cts CHANGED
@@ -12,6 +12,59 @@ interface ValidationResult {
12
12
  error?: string;
13
13
  warnings?: string[];
14
14
  }
15
+ /**
16
+ * Configuração de um campo da diretiva que contém sub-array de Directive[].
17
+ *
18
+ * Comportamento (afeta o engine):
19
+ * - `required`: campo precisa estar presente e ser array. Default: false.
20
+ * - `graph`: se false, ignorado por walks de grafo (mini-graph, analyzer).
21
+ * Default: true.
22
+ *
23
+ * Inspeção (metadata pura — não lida pelo engine, exposta via accessor):
24
+ * - `description`, `purpose`, `examples`, `tags`
25
+ */
26
+ interface SubDirectiveFieldConfig {
27
+ /**
28
+ * Se true, o campo precisa estar presente na diretiva e ser um array
29
+ * de Directive. Ausente ou não-array → throw em register-time.
30
+ * Default: false.
31
+ */
32
+ readonly required?: boolean;
33
+ /**
34
+ * Se false, o campo é ignorado por todos os walks de grafo
35
+ * (mini-graph, analyzer denied-scan, propagators). Útil pra campos
36
+ * de metadata/preview que não representam path de execução real.
37
+ * Default: true.
38
+ */
39
+ readonly graph?: boolean;
40
+ /**
41
+ * Descrição do campo. Hover docs em IDEs, descoberta de esquema
42
+ * por DSL JSON externo, documentação auto-gerada.
43
+ */
44
+ readonly description?: string;
45
+ /**
46
+ * Label semântico machine-readable. Tooling/analyzer pode dar
47
+ * tratamento diferente sem hardcode no engine.
48
+ *
49
+ * Valores comuns (não exaustivo, string livre):
50
+ * - "body" — caminho principal de execução
51
+ * - "catch" — caminho de fallback em erro
52
+ * - "branch" — caminho condicional
53
+ * - "finalizer" — caminho garantido (try/finally)
54
+ * - "metadata" — não é execução real (combine com graph: false)
55
+ */
56
+ readonly purpose?: string;
57
+ /**
58
+ * Exemplos de sub-arrays válidos. DSL/IDE pode usar pra autocomplete
59
+ * e docs auto-geradas.
60
+ */
61
+ readonly examples?: ReadonlyArray<ReadonlyArray<Directive>>;
62
+ /**
63
+ * Tags livres pra categorização cruzada em tooling/analyzer.
64
+ * Ex: ["transaction", "rollback-safe"].
65
+ */
66
+ readonly tags?: ReadonlyArray<string>;
67
+ }
15
68
  /**
16
69
  * Campos comuns a todo handler V2, independente do modo de execução.
17
70
  * `execute` fica nos subtipos — cada modo refina seu retorno. Não é genérico
@@ -24,6 +77,50 @@ interface HandlerBaseDefinition {
24
77
  validate?: (directive: Directive) => ValidationResult | void;
25
78
  /** JIT-time: contribui código inline per-action (Fase 2c). */
26
79
  compile?: (directive: Directive, compiler: unknown) => string | void;
80
+ /**
81
+ * Declara campos da diretiva que contêm sub-arrays de Directive[].
82
+ * O engine usa essa informação para:
83
+ * - Validação recursiva em register-time (com `required`)
84
+ * - Normalização recursiva (catch internos aninhados)
85
+ * - Walks do mini-graph (deps, async/interactive transitivo) — quando `graph !== false`
86
+ * - Walks do analyzer (denied-scan, capabilities, composition)
87
+ *
88
+ * NÃO afeta execução. Handler.execute é responsável por rodar
89
+ * as sub-directives via engine.runDirectives() ou runDirectivesAsync().
90
+ *
91
+ * Ver: docs/proposals/REFACTOR-SUBDIRECTIVES-DESCRIPTOR.md
92
+ */
93
+ readonly subDirectives?: {
94
+ readonly [fieldName: string]: SubDirectiveFieldConfig;
95
+ };
96
+ /**
97
+ * Descrição do handler. Hover docs, descoberta de esquema por DSL,
98
+ * documentação auto-gerada.
99
+ */
100
+ readonly description?: string;
101
+ /**
102
+ * Tags livres pra categorização cruzada (control-flow, transaction,
103
+ * io, query, etc.). Tooling pode agrupar/filtrar handlers por tag.
104
+ */
105
+ readonly tags?: ReadonlyArray<string>;
106
+ /**
107
+ * Marca o handler como obsoleto. boolean = deprecated sem motivo;
108
+ * string = mensagem de migração ("use 'try' since v0.5").
109
+ * Tooling/analyzer pode emitir warning quando handler é usado.
110
+ */
111
+ readonly deprecated?: boolean | string;
112
+ /**
113
+ * Versão em que o handler foi introduzido. SemVer ou string livre.
114
+ * Útil pra versionamento de DSL e compat checks no analyzer.
115
+ */
116
+ readonly since?: string;
117
+ /**
118
+ * Declara que esse handler é alias semântico de outro
119
+ * (mesma forma estrutural, mesma intenção). Tooling pode dedup
120
+ * referências e documentação. NÃO afeta dispatch — cada handler
121
+ * permanece independente em runtime.
122
+ */
123
+ readonly aliasOf?: string;
27
124
  }
28
125
  /** Função `execute` de um handler sync — retorna `ApplyResult` direto. */
29
126
  type SyncHandlerExecute<TCtx> = (directive: Directive, frame: ExecutionFrame<TCtx>, engine: ActionEngineRef<TCtx>) => ApplyResult;
@@ -221,6 +318,7 @@ type DirectivePermissionEntry = string | DirectivePermissionConfig;
221
318
  * - diretiva `type: "pause"` → erro no register
222
319
  */
223
320
  interface InteractiveConfig {
321
+ readonly [key: string]: unknown;
224
322
  }
225
323
  /**
226
324
  * Evento yieldado durante execução de uma action interactive.
@@ -391,6 +489,13 @@ interface IActionEngine<TCtx> {
391
489
  getActionDefinition(id: string): ActionDefinition<TCtx> | undefined;
392
490
  /** Campo de tipo pra dispatch de diretivas (default: "type"). */
393
491
  readonly typeField: string;
492
+ /**
493
+ * Mapa `type → readonly fieldNames[]` dos campos declarados pelo
494
+ * `subDirectives` dos handlers que entram no grafo (graph !== false).
495
+ * Pré-computado no construct-time. Consumido pelo mini-graph interno
496
+ * e por walks externos (analyzer denied-scan, capabilities, composition).
497
+ */
498
+ readonly subDirectiveFieldsForGraph: ReadonlyMap<string, readonly string[]>;
394
499
  /**
395
500
  * Mapa de permissões de diretivas, computado no boot (imutável).
396
501
  * Contém apenas handlers registrados (available ou denied).
@@ -535,7 +640,7 @@ declare class SimpleEmitter<TEvents = Record<string, unknown>> {
535
640
  }
536
641
 
537
642
  declare const RESERVED_TYPES: Set<string>;
538
- declare function normalizeDirectives<TCtx>(directives: readonly Directive<TCtx>[], typeField: string): Directive<TCtx>[];
643
+ declare function normalizeDirectives<TCtx>(directives: readonly Directive<TCtx>[], typeField: string, subDirectiveFieldsAll?: ReadonlyMap<string, readonly string[]>): Directive<TCtx>[];
539
644
 
540
645
  declare function createDirectiveInterpreter<TCtx>(analysis: SlotAnalysis, isAsync: boolean): DirectiveExecutorFn<TCtx>;
541
646
 
@@ -557,9 +662,22 @@ interface GeneratedDirectiveExecutor {
557
662
  */
558
663
  declare function buildDirectiveExecutor(analysis: SlotAnalysis, isAsync?: boolean): GeneratedDirectiveExecutor;
559
664
 
560
- type RuntimeActionExecutorFn = (frame: unknown, scope: unknown, $: unknown) => unknown;
665
+ /**
666
+ * Assinatura da função compilada pelo JIT per-action.
667
+ *
668
+ * Os parâmetros são tipados como `unknown` propositalmente: a função é
669
+ * criada via `new Function(...)` e recebe `frame`/`scope`/`$` que o
670
+ * caller (engine) já tem em tipos concretos. O retorno é `unknown`
671
+ * porque o JIT compila 4 shapes possíveis (sync/async/generator/
672
+ * async-generator) e o caller faz narrowing baseado em
673
+ * `GeneratedActionExecutor.{isAsync,isInteractive}`.
674
+ *
675
+ * Exportada pra que o engine possa tipar `CompiledAction.fn` sem
676
+ * cair em `Function` (que perde toda checagem de assinatura).
677
+ */
678
+ type GeneratedActionExecutorFn = (frame: unknown, scope: unknown, $: unknown) => unknown;
561
679
  interface GeneratedActionExecutor {
562
- fn: RuntimeActionExecutorFn;
680
+ fn: GeneratedActionExecutorFn;
563
681
  /** Wrapper async (`async function`/`async function*`)? */
564
682
  isAsync: boolean;
565
683
  /** Wrapper generator (`function*`/`async function*`)? Quando true, `fn(...)` retorna Generator/AsyncGenerator. */
@@ -595,4 +713,4 @@ interface GeneratedActionExecutor {
595
713
  */
596
714
  declare function buildActionExecutor(directives: readonly Directive[], analysis: SlotAnalysis, typeField: string, asyncHandlerSet?: ReadonlySet<string>, actionUsesAsyncOverride?: boolean, actionIsInteractive?: boolean, interactiveHandlerSet?: ReadonlySet<string>): GeneratedActionExecutor;
597
715
 
598
- export { type ActionDefinition, type ActionHooks, type ActionInterceptResult, type AsyncHandlerDefinition, type AsyncHandlerExecute, type AsyncInteractiveSession, type DirectiveExecutorFn, type DirectiveHandler, type DirectiveHandlerMap, type DirectiveHooks, type DirectivePermission, type DirectivePermissionConfig, type DirectivePermissionEntry, type DirectivePermissionStatus, type DirectiveRunnerFn, type EngineEventMap, type EngineEventName, type GeneratedActionExecutor, type GeneratedDirectiveExecutor, type HandlerAnalysis, type HandlerBaseDefinition, type HandlerDefinition, type HandlerInput, type HandlerInputMap, type IActionEngine, type IActionEngineConfig, type InteractiveApplyResult, type InteractiveConfig, type InteractiveHandlerDefinition, type InteractiveHandlerExecute, type InteractiveSession, type Listener, type PauseEvent, RESERVED_TYPES, type RegisterError, type RegisterEvent, type RegisterResult, type Responder, SimpleEmitter, type SyncHandlerDefinition, type SyncHandlerExecute, type UnregisterEvent, type ValidationResult, buildActionExecutor, buildDirectiveExecutor, createActionEngine, createDirectiveInterpreter, drainAsync, drainSync, normalizeDirectives, replayResponder };
716
+ export { type ActionDefinition, type ActionHooks, type ActionInterceptResult, type AsyncHandlerDefinition, type AsyncHandlerExecute, type AsyncInteractiveSession, type DirectiveExecutorFn, type DirectiveHandler, type DirectiveHandlerMap, type DirectiveHooks, type DirectivePermission, type DirectivePermissionConfig, type DirectivePermissionEntry, type DirectivePermissionStatus, type DirectiveRunnerFn, type EngineEventMap, type EngineEventName, type GeneratedActionExecutor, type GeneratedActionExecutorFn, type GeneratedDirectiveExecutor, type HandlerAnalysis, type HandlerBaseDefinition, type HandlerDefinition, type HandlerInput, type HandlerInputMap, type IActionEngine, type IActionEngineConfig, type InteractiveApplyResult, type InteractiveConfig, type InteractiveHandlerDefinition, type InteractiveHandlerExecute, type InteractiveSession, type Listener, type PauseEvent, RESERVED_TYPES, type RegisterError, type RegisterEvent, type RegisterResult, type Responder, SimpleEmitter, type SubDirectiveFieldConfig, type SyncHandlerDefinition, type SyncHandlerExecute, type UnregisterEvent, type ValidationResult, buildActionExecutor, buildDirectiveExecutor, createActionEngine, createDirectiveInterpreter, drainAsync, drainSync, normalizeDirectives, replayResponder };
package/dist/index.d.ts CHANGED
@@ -12,6 +12,59 @@ interface ValidationResult {
12
12
  error?: string;
13
13
  warnings?: string[];
14
14
  }
15
+ /**
16
+ * Configuração de um campo da diretiva que contém sub-array de Directive[].
17
+ *
18
+ * Comportamento (afeta o engine):
19
+ * - `required`: campo precisa estar presente e ser array. Default: false.
20
+ * - `graph`: se false, ignorado por walks de grafo (mini-graph, analyzer).
21
+ * Default: true.
22
+ *
23
+ * Inspeção (metadata pura — não lida pelo engine, exposta via accessor):
24
+ * - `description`, `purpose`, `examples`, `tags`
25
+ */
26
+ interface SubDirectiveFieldConfig {
27
+ /**
28
+ * Se true, o campo precisa estar presente na diretiva e ser um array
29
+ * de Directive. Ausente ou não-array → throw em register-time.
30
+ * Default: false.
31
+ */
32
+ readonly required?: boolean;
33
+ /**
34
+ * Se false, o campo é ignorado por todos os walks de grafo
35
+ * (mini-graph, analyzer denied-scan, propagators). Útil pra campos
36
+ * de metadata/preview que não representam path de execução real.
37
+ * Default: true.
38
+ */
39
+ readonly graph?: boolean;
40
+ /**
41
+ * Descrição do campo. Hover docs em IDEs, descoberta de esquema
42
+ * por DSL JSON externo, documentação auto-gerada.
43
+ */
44
+ readonly description?: string;
45
+ /**
46
+ * Label semântico machine-readable. Tooling/analyzer pode dar
47
+ * tratamento diferente sem hardcode no engine.
48
+ *
49
+ * Valores comuns (não exaustivo, string livre):
50
+ * - "body" — caminho principal de execução
51
+ * - "catch" — caminho de fallback em erro
52
+ * - "branch" — caminho condicional
53
+ * - "finalizer" — caminho garantido (try/finally)
54
+ * - "metadata" — não é execução real (combine com graph: false)
55
+ */
56
+ readonly purpose?: string;
57
+ /**
58
+ * Exemplos de sub-arrays válidos. DSL/IDE pode usar pra autocomplete
59
+ * e docs auto-geradas.
60
+ */
61
+ readonly examples?: ReadonlyArray<ReadonlyArray<Directive>>;
62
+ /**
63
+ * Tags livres pra categorização cruzada em tooling/analyzer.
64
+ * Ex: ["transaction", "rollback-safe"].
65
+ */
66
+ readonly tags?: ReadonlyArray<string>;
67
+ }
15
68
  /**
16
69
  * Campos comuns a todo handler V2, independente do modo de execução.
17
70
  * `execute` fica nos subtipos — cada modo refina seu retorno. Não é genérico
@@ -24,6 +77,50 @@ interface HandlerBaseDefinition {
24
77
  validate?: (directive: Directive) => ValidationResult | void;
25
78
  /** JIT-time: contribui código inline per-action (Fase 2c). */
26
79
  compile?: (directive: Directive, compiler: unknown) => string | void;
80
+ /**
81
+ * Declara campos da diretiva que contêm sub-arrays de Directive[].
82
+ * O engine usa essa informação para:
83
+ * - Validação recursiva em register-time (com `required`)
84
+ * - Normalização recursiva (catch internos aninhados)
85
+ * - Walks do mini-graph (deps, async/interactive transitivo) — quando `graph !== false`
86
+ * - Walks do analyzer (denied-scan, capabilities, composition)
87
+ *
88
+ * NÃO afeta execução. Handler.execute é responsável por rodar
89
+ * as sub-directives via engine.runDirectives() ou runDirectivesAsync().
90
+ *
91
+ * Ver: docs/proposals/REFACTOR-SUBDIRECTIVES-DESCRIPTOR.md
92
+ */
93
+ readonly subDirectives?: {
94
+ readonly [fieldName: string]: SubDirectiveFieldConfig;
95
+ };
96
+ /**
97
+ * Descrição do handler. Hover docs, descoberta de esquema por DSL,
98
+ * documentação auto-gerada.
99
+ */
100
+ readonly description?: string;
101
+ /**
102
+ * Tags livres pra categorização cruzada (control-flow, transaction,
103
+ * io, query, etc.). Tooling pode agrupar/filtrar handlers por tag.
104
+ */
105
+ readonly tags?: ReadonlyArray<string>;
106
+ /**
107
+ * Marca o handler como obsoleto. boolean = deprecated sem motivo;
108
+ * string = mensagem de migração ("use 'try' since v0.5").
109
+ * Tooling/analyzer pode emitir warning quando handler é usado.
110
+ */
111
+ readonly deprecated?: boolean | string;
112
+ /**
113
+ * Versão em que o handler foi introduzido. SemVer ou string livre.
114
+ * Útil pra versionamento de DSL e compat checks no analyzer.
115
+ */
116
+ readonly since?: string;
117
+ /**
118
+ * Declara que esse handler é alias semântico de outro
119
+ * (mesma forma estrutural, mesma intenção). Tooling pode dedup
120
+ * referências e documentação. NÃO afeta dispatch — cada handler
121
+ * permanece independente em runtime.
122
+ */
123
+ readonly aliasOf?: string;
27
124
  }
28
125
  /** Função `execute` de um handler sync — retorna `ApplyResult` direto. */
29
126
  type SyncHandlerExecute<TCtx> = (directive: Directive, frame: ExecutionFrame<TCtx>, engine: ActionEngineRef<TCtx>) => ApplyResult;
@@ -221,6 +318,7 @@ type DirectivePermissionEntry = string | DirectivePermissionConfig;
221
318
  * - diretiva `type: "pause"` → erro no register
222
319
  */
223
320
  interface InteractiveConfig {
321
+ readonly [key: string]: unknown;
224
322
  }
225
323
  /**
226
324
  * Evento yieldado durante execução de uma action interactive.
@@ -391,6 +489,13 @@ interface IActionEngine<TCtx> {
391
489
  getActionDefinition(id: string): ActionDefinition<TCtx> | undefined;
392
490
  /** Campo de tipo pra dispatch de diretivas (default: "type"). */
393
491
  readonly typeField: string;
492
+ /**
493
+ * Mapa `type → readonly fieldNames[]` dos campos declarados pelo
494
+ * `subDirectives` dos handlers que entram no grafo (graph !== false).
495
+ * Pré-computado no construct-time. Consumido pelo mini-graph interno
496
+ * e por walks externos (analyzer denied-scan, capabilities, composition).
497
+ */
498
+ readonly subDirectiveFieldsForGraph: ReadonlyMap<string, readonly string[]>;
394
499
  /**
395
500
  * Mapa de permissões de diretivas, computado no boot (imutável).
396
501
  * Contém apenas handlers registrados (available ou denied).
@@ -535,7 +640,7 @@ declare class SimpleEmitter<TEvents = Record<string, unknown>> {
535
640
  }
536
641
 
537
642
  declare const RESERVED_TYPES: Set<string>;
538
- declare function normalizeDirectives<TCtx>(directives: readonly Directive<TCtx>[], typeField: string): Directive<TCtx>[];
643
+ declare function normalizeDirectives<TCtx>(directives: readonly Directive<TCtx>[], typeField: string, subDirectiveFieldsAll?: ReadonlyMap<string, readonly string[]>): Directive<TCtx>[];
539
644
 
540
645
  declare function createDirectiveInterpreter<TCtx>(analysis: SlotAnalysis, isAsync: boolean): DirectiveExecutorFn<TCtx>;
541
646
 
@@ -557,9 +662,22 @@ interface GeneratedDirectiveExecutor {
557
662
  */
558
663
  declare function buildDirectiveExecutor(analysis: SlotAnalysis, isAsync?: boolean): GeneratedDirectiveExecutor;
559
664
 
560
- type RuntimeActionExecutorFn = (frame: unknown, scope: unknown, $: unknown) => unknown;
665
+ /**
666
+ * Assinatura da função compilada pelo JIT per-action.
667
+ *
668
+ * Os parâmetros são tipados como `unknown` propositalmente: a função é
669
+ * criada via `new Function(...)` e recebe `frame`/`scope`/`$` que o
670
+ * caller (engine) já tem em tipos concretos. O retorno é `unknown`
671
+ * porque o JIT compila 4 shapes possíveis (sync/async/generator/
672
+ * async-generator) e o caller faz narrowing baseado em
673
+ * `GeneratedActionExecutor.{isAsync,isInteractive}`.
674
+ *
675
+ * Exportada pra que o engine possa tipar `CompiledAction.fn` sem
676
+ * cair em `Function` (que perde toda checagem de assinatura).
677
+ */
678
+ type GeneratedActionExecutorFn = (frame: unknown, scope: unknown, $: unknown) => unknown;
561
679
  interface GeneratedActionExecutor {
562
- fn: RuntimeActionExecutorFn;
680
+ fn: GeneratedActionExecutorFn;
563
681
  /** Wrapper async (`async function`/`async function*`)? */
564
682
  isAsync: boolean;
565
683
  /** Wrapper generator (`function*`/`async function*`)? Quando true, `fn(...)` retorna Generator/AsyncGenerator. */
@@ -595,4 +713,4 @@ interface GeneratedActionExecutor {
595
713
  */
596
714
  declare function buildActionExecutor(directives: readonly Directive[], analysis: SlotAnalysis, typeField: string, asyncHandlerSet?: ReadonlySet<string>, actionUsesAsyncOverride?: boolean, actionIsInteractive?: boolean, interactiveHandlerSet?: ReadonlySet<string>): GeneratedActionExecutor;
597
715
 
598
- export { type ActionDefinition, type ActionHooks, type ActionInterceptResult, type AsyncHandlerDefinition, type AsyncHandlerExecute, type AsyncInteractiveSession, type DirectiveExecutorFn, type DirectiveHandler, type DirectiveHandlerMap, type DirectiveHooks, type DirectivePermission, type DirectivePermissionConfig, type DirectivePermissionEntry, type DirectivePermissionStatus, type DirectiveRunnerFn, type EngineEventMap, type EngineEventName, type GeneratedActionExecutor, type GeneratedDirectiveExecutor, type HandlerAnalysis, type HandlerBaseDefinition, type HandlerDefinition, type HandlerInput, type HandlerInputMap, type IActionEngine, type IActionEngineConfig, type InteractiveApplyResult, type InteractiveConfig, type InteractiveHandlerDefinition, type InteractiveHandlerExecute, type InteractiveSession, type Listener, type PauseEvent, RESERVED_TYPES, type RegisterError, type RegisterEvent, type RegisterResult, type Responder, SimpleEmitter, type SyncHandlerDefinition, type SyncHandlerExecute, type UnregisterEvent, type ValidationResult, buildActionExecutor, buildDirectiveExecutor, createActionEngine, createDirectiveInterpreter, drainAsync, drainSync, normalizeDirectives, replayResponder };
716
+ export { type ActionDefinition, type ActionHooks, type ActionInterceptResult, type AsyncHandlerDefinition, type AsyncHandlerExecute, type AsyncInteractiveSession, type DirectiveExecutorFn, type DirectiveHandler, type DirectiveHandlerMap, type DirectiveHooks, type DirectivePermission, type DirectivePermissionConfig, type DirectivePermissionEntry, type DirectivePermissionStatus, type DirectiveRunnerFn, type EngineEventMap, type EngineEventName, type GeneratedActionExecutor, type GeneratedActionExecutorFn, type GeneratedDirectiveExecutor, type HandlerAnalysis, type HandlerBaseDefinition, type HandlerDefinition, type HandlerInput, type HandlerInputMap, type IActionEngine, type IActionEngineConfig, type InteractiveApplyResult, type InteractiveConfig, type InteractiveHandlerDefinition, type InteractiveHandlerExecute, type InteractiveSession, type Listener, type PauseEvent, RESERVED_TYPES, type RegisterError, type RegisterEvent, type RegisterResult, type Responder, SimpleEmitter, type SubDirectiveFieldConfig, type SyncHandlerDefinition, type SyncHandlerExecute, type UnregisterEvent, type ValidationResult, buildActionExecutor, buildDirectiveExecutor, createActionEngine, createDirectiveInterpreter, drainAsync, drainSync, normalizeDirectives, replayResponder };
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import {processIntercept,Intercept,analyzeSlots,DIRECTIVE_SLOT_NAMES,isAsyncFunction,isGeneratorFunction,createRootFrame}from'@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=processIntercept(d.beforeDirective(g,n),"beforeDirective");if(c.action===Intercept.SKIP){m++,p.directivesSkipped++;continue}if(c.action===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=processIntercept(await d.beforeDirective(g,n),"beforeDirective");if(c.action===Intercept.SKIP){m++,p.directivesSkipped++;continue}if(c.action===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=processIntercept(d.beforeDirective(g,n),"beforeDirective");if(c.action===Intercept.SKIP){m++,p.directivesSkipped++;continue}if(c.action===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=processIntercept(await d.beforeDirective(g,n),"beforeDirective");if(c.action===Intercept.SKIP){m++,p.directivesSkipped++;continue}if(c.action===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}() => {
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(`
1
+ import {processIntercept,Intercept,analyzeSlots,DIRECTIVE_SLOT_NAMES,isAsyncFunction,isGeneratorFunction,createRootFrame}from'@statedelta-actions/core';function Ie(o,e){let n;for(;;){let i=o.next(n);if(i.done)return i.value;n=e?e(i.value):void 0;}}async function Ee(o,e){let n;for(;;){let i=await o.next(n);if(i.done)return i.value;n=e?await e(i.value):void 0;}}function we(o){let e=0;return ()=>{if(!(e>=o.length))return o[e++]}}var O=class{_listeners=new Map;on(e,n){let i=this._listeners.get(e);i||(i=new Set,this._listeners.set(e,i)),i.add(n);let s=false;return ()=>{s||(s=true,i.delete(n),i.size===0&&this._listeners.delete(e));}}once(e,n){let i=this.on(e,s=>{i(),n(s);});return i}emit(e,n){let i=this._listeners.get(e);if(!i||i.size===0)return;let s=[...i];for(let t=0;t<s.length;t++)try{s[t](n);}catch(r){console.error(`[SimpleEmitter] Listener error on "${e}":`,r);}}listenerCount(e){return this._listeners.get(e)?.size??0}hasListeners(e){let n=this._listeners.get(e);return n!==void 0&&n.size>0}off(e){this._listeners.delete(e);}removeAllListeners(){this._listeners.clear();}};var N=new Set(["const","let","return","throw","pause","if"]);function le(o,e,n,i){let s=[];return q(o.directives,e,n,i,"directive",s,o.id),s}function q(o,e,n,i,s,t,r){for(let d=0;d<o.length;d++){let c=o[d],u=c[i],h=`${s}[${d}]`;if(!u){t.push(`${h}: missing type field "${i}"`);continue}if(u==="if"){let g=c.cond;typeof g!="function"&&typeof g!="boolean"&&t.push(`${h}: "if" requires cond as function or boolean`);let f=c.then;Array.isArray(f)?q(f,e,n,i,`${h}.then`,t,r):t.push(`${h}: "if" requires then as array`);let D=c.else;D!==void 0&&(Array.isArray(D)?q(D,e,n,i,`${h}.else`,t,r):t.push(`${h}.else: must be array`));continue}if(N.has(u))continue;if(!e[u])throw new Error(`Action "${r}" ${h}: no handler registered for type "${u}". Register the handler in createActionEngine({ handlers }) before registering this action.`);let C=n.get(u);if(C?.validate)try{let g=C.validate(c);g&&!g.valid&&t.push(`${h}: ${g.error??"validation failed"}`);}catch(g){t.push(`${h}: validate threw: ${g}`);}let y=c.catch;if(y&&Array.isArray(y))for(let g=0;g<y.length;g++){let D=y[g][i];if(!(D&&N.has(D))&&D&&!e[D])throw new Error(`Action "${r}" ${h}.catch[${g}]: no handler registered for type "${D}". Register the handler in createActionEngine({ handlers }) before registering this action.`)}let p=C?.subDirectives;if(p===void 0)continue;let m=Object.keys(p);for(let g=0;g<m.length;g++){let f=m[g];if(f==="catch")continue;let D=c[f];if(D===void 0){if(p[f].required)throw new Error(`Action "${r}" ${h}: handler "${u}" requires sub-directives field "${f}"`);continue}if(!Array.isArray(D))throw new Error(`Action "${r}" ${h}.${f}: must be an array of directives`);q(D,e,n,i,`${h}.${f}`,t,r);}}}var Te=new Map;function L(o,e,n=Te){let i=o.length,s=new Array(i);for(let t=0;t<i;t++){let r=o[t],d=r[e],c=r,u=false,h=r.catch;if(Array.isArray(h)&&h.length>0&&(c={...c,catch:L(h,e,n)},u=true),d==="if"){let C=r.then;Array.isArray(C)&&C.length>0&&(c={...c,then:L(C,e,n)},u=true);let y=r.else;Array.isArray(y)&&y.length>0&&(c={...c,else:L(y,e,n)},u=true);}else if(d!==void 0){let C=n.get(d);if(C!==void 0)for(let y=0;y<C.length;y++){let p=C[y],m=r[p];!Array.isArray(m)||m.length===0||(c={...c,[p]:L(m,e,n)},u=true);}}s[t]=u?c:r;}return s}function W(o,e,n,i,s,t,r){return {success:false,aborted:true,abortedBy:o,appliedCount:e,skippedCount:n,errors:i,processedCount:s,totalCount:t,counters:r}}function $e(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return function(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=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,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="value"in l?l.value:"return"in l?l.return:x.value;return {success:!0,aborted:!1,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.value};continue}if(E==="throw"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="message"in l?l.message:"throw"in l?l.throw:x.message;return {success:!1,aborted:!0,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:false,aborted:true,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.message};continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=processIntercept(c.beforeDirective(_,r),"beforeDirective");if(a.action===Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===Intercept.ABORT)return W(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{b=F(_,k,h);}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return {success:false,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data};let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=h.runDirectives(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(c.afterDirective(_,b,k)==="abort")return W("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{c.onDirectivesComplete(P);}catch{}return P}}function Se(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return async function(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=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,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="value"in l?l.value:"return"in l?l.return:x.value;return {success:!0,aborted:!1,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.value};continue}if(E==="throw"){let a=I;if(typeof x.resolve=="function")try{let l=x.resolve($,D),v="message"in l?l.message:"throw"in l?l.throw:x.message;return {success:!1,aborted:!0,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:v}}catch(l){p.push({directiveIndex:A,error:`Control resolve: ${l}`}),f.errors++;}else return {success:false,aborted:true,abortedBy:"throw",appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:x.message};continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=processIntercept(await c.beforeDirective(_,r),"beforeDirective");if(a.action===Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===Intercept.ABORT)return W(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{b=await F(_,k,h);}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return {success:false,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data};let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=await h.runDirectivesAsync(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(await c.afterDirective(_,b,k)==="abort")return W("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{await c.onDirectivesComplete(P);}catch{}return P}}function J(o,e){return e?Se(o):$e(o)}function B(o,e,n,i,s,t,r,d){return {success:false,aborted:true,abortedBy:o,appliedCount:e,skippedCount:n,errors:i,processedCount:s,totalCount:t,counters:r,data:d}}function pe(o){if(o===null||typeof o!="object")return null;if(typeof o.next=="function")return o;let e=o.iterator;return e!=null&&typeof e=="object"&&typeof e.next=="function"?e:null}function He(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return function*(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=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,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I,l=x.value;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="value"in v?v.value:"return"in v?v.return:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:l}}if(E==="throw"){let a=I,l=x.message;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="message"in v?v.message:"throw"in v?v.throw:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return B("throw",m,g,p,a,y,f,l)}if(E==="pause"){let a=I,l=yield {source:"pause",directive:x,frame:r,index:A,payload:{message:x.message}};if(l===false||l==="abort"||l==="cancel")return B("pause",m,g,p,a,y,f,l);m++,f.directivesApplied++,typeof x.as=="string"&&l!==void 0&&(D[x.as]=l);continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=processIntercept(c.beforeDirective(_,r),"beforeDirective");if(a.action===Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===Intercept.ABORT)return B(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{let a=F(_,k,h),l=pe(a);l!==null?b=yield*l:b=a;}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return B("halt",m,g,p,H,y,f,b.data);let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=h.runDirectives(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(c.afterDirective(_,b,k)==="abort")return B("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{c.onDirectivesComplete(P);}catch{}return P}}function Me(o){let e=o.filledNames.has("beforeDirective"),n=o.filledNames.has("afterDirective"),i=o.filledNames.has("onDirectivesComplete");return async function*(t,r,d,c,u,h,C){let y=Math.min(t.length,C),p=[],m=0,g=0,{counters:f,scope:D}=r,$=r.ctx,w=[{dirs:t,i:0,len:y,topLevelIfIndex:-1}],I=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,A=S?R.topLevelIfIndex:T;S||(I=T+1);let x=R.dirs[T],E=x[u];if(E==="const"||E==="let"){let a=x.name;if(typeof x.resolve=="function")try{D[a]=x.resolve($,D).value;}catch(l){p.push({directiveIndex:A,error:`Binding resolve: ${l}`}),f.errors++;}else D[a]=x.value;continue}if(E==="return"){let a=I,l=x.value;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="value"in v?v.value:"return"in v?v.return:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return {success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:a,totalCount:y,counters:f,data:l}}if(E==="throw"){let a=I,l=x.message;if(typeof x.resolve=="function")try{let v=x.resolve($,D);l="message"in v?v.message:"throw"in v?v.throw:l;}catch(v){p.push({directiveIndex:A,error:`Control resolve: ${v}`}),f.errors++;continue}return B("throw",m,g,p,a,y,f,l)}if(E==="pause"){let a=I,l=yield {source:"pause",directive:x,frame:r,index:A,payload:{message:x.message}};if(l===false||l==="abort"||l==="cancel")return B("pause",m,g,p,a,y,f,l);m++,f.directivesApplied++,typeof x.as=="string"&&l!==void 0&&(D[x.as]=l);continue}if(E==="if"){let a;try{let v=x.cond;a=typeof v=="function"?!!v($,D):!!v;}catch(v){p.push({directiveIndex:A,error:`if cond: ${v}`}),f.errors++;continue}let l=a?x.then:x.else;if(Array.isArray(l)&&l.length>0){let v=Math.min(l.length,C),G=S?R.topLevelIfIndex:T;w.push({dirs:l,i:0,len:v,topLevelIfIndex:G});}continue}let _=x,k=r;if(e)try{let a=processIntercept(await c.beforeDirective(_,r),"beforeDirective");if(a.action===Intercept.SKIP){g++,f.directivesSkipped++;continue}if(a.action===Intercept.ABORT)return B(a.abortReason,m,g,p,I===0?T:I-1,y,f);a.ctx!==void 0&&(k=r.withCtx(a.ctx)),a.directive!==void 0&&(_=a.directive);}catch(a){p.push({directiveIndex:A,error:`Hook beforeDirective: ${a}`}),f.errors++;}if(typeof _.resolve=="function")try{let a=_.resolve(k.ctx,k.scope);_={..._,...a};}catch(a){p.push({directiveIndex:A,error:`Directive resolve: ${a}`}),f.errors++;continue}let M=_[u],F=M?d[M]:void 0;if(!F){p.push({directiveIndex:A,error:`No handler for directive type: ${M??"undefined"}`}),f.errors++;continue}let b;try{let a=await F(_,k,h),l=pe(a);l!==null?b=yield*l:b=a;}catch(a){b={ok:false,error:String(a)};}let H=I;if(b.ok){if(m++,f.directivesApplied++,typeof _.as=="string"&&(D[_.as]=b.data),b.halt)return {success:true,aborted:true,abortedBy:"halt",appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:b.data}}else {if(b.halt)return B("halt",m,g,p,H,y,f,b.data);let a=_.catch;if(Array.isArray(a)&&a.length>0){D.$exception=b.error??"handler failed";let l=await h.runDirectivesAsync(a,k);m+=l.appliedCount;for(let v=0;v<l.errors.length;v++)p.push(l.errors[v]);if(l.aborted)return {success:l.success,aborted:true,abortedBy:l.abortedBy,appliedCount:m,skippedCount:g,errors:p,processedCount:H,totalCount:y,counters:f,data:l.data}}else p.push({directiveIndex:A,error:b.error??"handler failed"}),f.errors++;}if(n)try{if(await c.afterDirective(_,b,k)==="abort")return B("afterDirective",m,g,p,H,y,f)}catch(a){p.push({directiveIndex:A,error:`Hook afterDirective: ${a}`}),f.errors++;}}let P={success:true,aborted:false,appliedCount:m,skippedCount:g,errors:p,processedCount:y,totalCount:y,counters:f};if(i)try{await c.onDirectivesComplete(P);}catch{}return P}}function ee(o,e){return e?Me(o):He(o)}function te(o,e=o.hasAnyAsync){let{filledNames:n}=o,i=h=>n.has(h),s=h=>o.asyncNames.has(h)?"await ":"",t=e?"await ":"",r=[];for(let h of n)r.push(`const ${h} = directiveHooks.${h};`);r.push("const len = Math.min(directives.length, maxDirectives);"),r.push("const errors = []; let appliedCount = 0; let skippedCount = 0;"),r.push("const counters = frame.counters;"),r.push("for (let i = 0; i < len; i++) {"),r.push(" let directive = directives[i];"),i("beforeDirective")?(r.push(" let _df = frame;"),r.push(" try {"),r.push(` const _bd = ${s("beforeDirective")}beforeDirective(directive, frame);`),r.push(' if (_bd === "skip") { skippedCount++; counters.directivesSkipped++; continue; }'),r.push(' if (_bd === "abort") return { success: false, aborted: true, abortedBy: "beforeDirective", appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),r.push(' if (typeof _bd === "object" && _bd !== null) {'),r.push(' if ("abort" in _bd) return { success: false, aborted: true, abortedBy: _bd.abort, appliedCount, skippedCount, errors, processedCount: i, totalCount: len, counters };'),r.push(' if ("ctx" in _bd) _df = frame.withCtx(_bd.ctx);'),r.push(' if ("directive" in _bd) directive = _bd.directive;'),r.push(" }"),r.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook beforeDirective: " + _e }); counters.errors++; }')):r.push(" const _df = frame;"),r.push(' if (typeof directive.resolve === "function") {'),r.push(" try { const _r = directive.resolve(_df.ctx); directive = Object.assign({}, directive, _r); }"),r.push(' catch (_e) { errors.push({ directiveIndex: i, error: "Directive resolve: " + _e }); counters.errors++; continue; }'),r.push(" }"),r.push(" const _type = directive[typeField];"),r.push(" const _handler = _type ? handlers[_type] : undefined;"),r.push(' if (!_handler) { errors.push({ directiveIndex: i, error: "No handler for directive type: " + (_type || "undefined") }); counters.errors++; continue; }'),r.push(" let _result;"),r.push(` try { _result = ${t}_handler(directive, _df, engine); } catch (_e) { errors.push({ directiveIndex: i, error: String(_e) }); counters.errors++; continue; }`),r.push(" if (_result.ok) { appliedCount++; counters.directivesApplied++; }"),r.push(' else { errors.push({ directiveIndex: i, error: _result.error || "handler failed" }); counters.errors++; }'),i("afterDirective")&&(r.push(" try {"),r.push(` const _ad = ${s("afterDirective")}afterDirective(directive, _result, _df);`),r.push(' if (_ad === "abort") return { success: false, aborted: true, abortedBy: "afterDirective", appliedCount, skippedCount, errors, processedCount: i + 1, totalCount: len, counters };'),r.push(' } catch (_e) { errors.push({ directiveIndex: i, error: "Hook afterDirective: " + _e }); counters.errors++; }')),r.push("}"),r.push("const _finalResult = { success: true, aborted: false, appliedCount, skippedCount, errors, processedCount: len, totalCount: len, counters };"),i("onDirectivesComplete")&&r.push(`try { ${s("onDirectivesComplete")}onDirectivesComplete(_finalResult); } catch (_e) {}`),r.push("return _finalResult;");let d=r.join(`
2
+ `),c=e?"async ":"";return {fn:new Function("directives","frame","handlers","directiveHooks","typeField","engine","maxDirectives",`"use strict";
3
+ return (${c}() => {
4
+ ${d}
5
+ })();`),isAsync:e}}function re(o,e,n){return `return{success:false,aborted:true,abortedBy:${o},appliedCount,skippedCount,errors,processedCount:${e},totalCount:${n},counters};`}function Pe(o,e){return `return{success:true,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${e},counters,data:_result.data};`}function Fe(o,e){return `return{success:false,aborted:true,abortedBy:"halt",appliedCount,skippedCount,errors,processedCount:${o},totalCount:${e},counters,data:_result.data};`}function Be(o,e,n,i){let s=JSON.stringify(e.name);typeof e.resolve=="function"?(o.push("try{"),o.push(`scope[${s}]=${n}.resolve(ctx,scope).value;`),o.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Binding resolve: "+_e});counters.errors++;}`)):o.push(`scope[${s}]=${n}.value;`);}function Ge(o,e,n,i,s,t){typeof e.resolve=="function"?(o.push("try{"),o.push(`const _rv=${n}.resolve(ctx,scope);`),o.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:"value" in _rv?_rv.value:"return" in _rv?_rv.return:${n}.value};`),o.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Control resolve: "+_e});counters.errors++;}`)):o.push(`return{success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:${n}.value};`);}function Le(o,e,n,i,s,t){typeof e.resolve=="function"?(o.push("try{"),o.push(`const _rv=${n}.resolve(ctx,scope);`),o.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:"message" in _rv?_rv.message:"throw" in _rv?_rv.throw:${n}.message};`),o.push(`}catch(_e){errors.push({directiveIndex:${i},error:"Control resolve: "+_e});counters.errors++;}`)):o.push(`return{success:false,aborted:true,abortedBy:"throw",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:${n}.message};`);}function Ne(o,e,n,i,s,t){let r=typeof e.as=="string",d=r?JSON.stringify(e.as):"";o.push(`{const _ack=yield{source:"pause",directive:${n},frame,index:${i},payload:{message:${n}.message}};`),o.push(`if(_ack===false||_ack==="abort"||_ack==="cancel")return{success:false,aborted:true,abortedBy:"pause",appliedCount,skippedCount,errors,processedCount:${s},totalCount:${t},counters,data:_ack};`),o.push("appliedCount++;counters.directivesApplied++;"),r&&o.push(`if(_ack!==undefined)scope[${d}]=_ack;`),o.push("}");}function je(o,e,n,i,s){let{L:t,total:r,typeField:d,handlerVars:c,hasBefore:u,hasAfter:h,awBefore:C,awAfter:y,awHandler:p,actionIsAsync:m,actionIsInteractive:g,interactiveHandlerSet:f}=s,D=o[d],$=c.get(D),w=typeof o.resolve=="function",I=typeof o.as=="string",P=Array.isArray(o.catch)&&o.catch.length>0,R=I?JSON.stringify(o.as):"",T=g&&f.has(D),S=s.blockCounter.n++;t.push(`_b${S}:{`);let A=u||w,x=u;A&&t.push(`let _dir=${e};`),x&&t.push("let _df=frame;"),u&&(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")${re('"beforeDirective"',i-1,r)}`),t.push('if(typeof _bd==="object"&&_bd!==null){'),t.push(`if("abort" in _bd)${re("_bd.abort",i-1,r)}`),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:${n},error:"Hook beforeDirective: "+_e});counters.errors++;}`)),u?(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:${n},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:${n},error:"Directive resolve: "+_e});counters.errors++;break _b${S};}`));let E=A?"_dir":e,_=x?"_df":"frame";if(t.push("let _result;"),T?(t.push(`try{_result=yield* ${$}(${E},${_},$.engine);}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")):g?(t.push(`try{_result=${p}${$}(${E},${_},$.engine);if(_result&&_result.iterator)_result=yield* _result.iterator;}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")):(t.push(`try{_result=${p}${$}(${E},${_},$.engine);}`),t.push("catch(_e){_result={ok:false,error:String(_e)};}")),t.push("if(_result.ok){"),t.push("appliedCount++;counters.directivesApplied++;"),I&&t.push(`scope[${R}]=_result.data;`),t.push(`if(_result.halt)${Pe(i,r)}`),t.push("}else{"),t.push(`if(_result.halt)${Fe(i,r)}`),P){t.push('scope.$exception=_result.error||"handler failed";');let k=m?"$.runner":"$.runnerSync";t.push(`const _cr=${p}${k}(${e}.catch,${_});`),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:${r},counters,data:_cr.data};`);}else t.push(`errors.push({directiveIndex:${n},error:_result.error||"handler failed"});counters.errors++;`);t.push("}"),h&&(t.push("try{"),t.push(`const _ad=${y}_hookAfter(${E},_result,${_});`),t.push(`if(_ad==="abort")${re('"afterDirective"',i,r)}`),t.push(`}catch(_e){errors.push({directiveIndex:${n},error:"Hook afterDirective: "+_e});counters.errors++;}`)),t.push("}");}function Oe(o,e,n,i,s,t){let{L:r}=t,d=o.cond,c=typeof d=="boolean";r.push("{"),c?r.push(`if(${d?"true":"false"}){`):(r.push("let _cond=false,_condOk=true;"),r.push(`try{const _c=${e}.cond;_cond=typeof _c==="function"?!!_c(ctx,scope):!!_c;}`),r.push(`catch(_e){errors.push({directiveIndex:${n},error:"if cond: "+_e});counters.errors++;_condOk=false;}`),r.push("if(_condOk){"),r.push("if(_cond){"));let u=o.then;Array.isArray(u)&&u.length>0&&ne(u,`${e}.then`,i,s,t),r.push("}");let h=o.else;Array.isArray(h)&&h.length>0&&(r.push("else{"),ne(h,`${e}.else`,i,s,t),r.push("}")),c||r.push("}"),r.push("}");}function ne(o,e,n,i,s){let t=n!==-1;for(let r=0;r<o.length;r++){let d=o[r],c=`${e}[${r}]`,u=t?n:r,h=t?i:r+1;switch(d[s.typeField]){case "const":case "let":Be(s.L,d,c,u);break;case "return":Ge(s.L,d,c,u,h,s.total);break;case "throw":Le(s.L,d,c,u,h,s.total);break;case "pause":Ne(s.L,d,c,u,h,s.total);break;case "if":{let y=t?n:r,p=t?i:r+1;Oe(d,c,u,y,p,s);break}default:je(d,c,u,h,s);break}}}function ie(o,e,n){for(let i of o){let s=i[e];if(s&&!N.has(s)&&n.add(s),s==="if"){let t=i.then;Array.isArray(t)&&t.length>0&&ie(t,e,n);let r=i.else;Array.isArray(r)&&r.length>0&&ie(r,e,n);}}}var he=new Set;function se(o,e,n,i=he,s,t=false,r=he){let d=[],c=o.length,{filledNames:u,hasAnyAsync:h,asyncNames:C}=e,y=u.has("beforeDirective"),p=u.has("afterDirective"),m=u.has("onDirectivesComplete"),g=s!==void 0?s:Q(o,i,n),f=h||g,D=f?"await ":"",$=C.has("beforeDirective")?"await ":"",w=C.has("afterDirective")?"await ":"",I=C.has("onDirectivesComplete")?"await ":"",P=new Set;ie(o,n,P);let R=new Map,T=0;for(let k of P)R.set(k,`_h${T++}`);d.push("const counters=frame.counters;"),d.push("const ctx=frame.ctx;"),d.push("const errors=[];"),d.push("let appliedCount=0;"),d.push("let skippedCount=0;");for(let[k,M]of R)d.push(`const ${M}=$.h[${JSON.stringify(k)}];`);y&&d.push("const _hookBefore=$.hooks.beforeDirective;"),p&&d.push("const _hookAfter=$.hooks.afterDirective;"),ne(o,"$.d",-1,0,{L:d,total:c,typeField:n,handlerVars:R,hasBefore:y,hasAfter:p,awBefore:$,awAfter:w,awHandler:D,actionIsAsync:f,actionIsInteractive:t,interactiveHandlerSet:r,blockCounter:{n:0}}),d.push(`const _finalResult={success:true,aborted:false,appliedCount,skippedCount,errors,processedCount:${c},totalCount:${c},counters};`),m&&d.push(`try{${I}$.hooks.onDirectivesComplete(_finalResult);}catch(_e){}`),d.push("return _finalResult;");let x=`{
6
+ ${d.join(`
7
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=analyzeSlots(this._directiveHooks,DIRECTIVE_SLOT_NAMES);let o=new Set,t=new Set;for(let[a,d]of this._definitions)(d.async===true||isAsyncFunction(d.execute))&&o.add(a),(d.interactive===true||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=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=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=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)}export{L as RESERVED_TYPES,j as SimpleEmitter,ie as buildActionExecutor,ee as buildDirectiveExecutor,We as createActionEngine,U as createDirectiveInterpreter,Re as drainAsync,Ae as drainSync,N as normalizeDirectives,Ie as replayResponder};
8
+ }`,E;return t?E=`(${f?"async function*()":"function*()"}${x})()`:E=`(${f?"async ()=>":"()=>"}${x})()`,{fn:new Function("frame","scope","$",`"use strict";
9
+ return ${E};`),isAsync:f,isInteractive:t}}function Q(o,e,n){for(let i of o){let s=i[n];if(s&&e.has(s))return true;if(s==="if"){let r=i.then;if(Array.isArray(r)&&r.length>0&&Q(r,e,n))return true;let d=i.else;if(Array.isArray(d)&&d.length>0&&Q(d,e,n))return true}let t=i.catch;if(Array.isArray(t)&&t.length>0&&Q(t,e,n))return true}return false}function oe(o,e,n){return {success:false,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[{directiveIndex:-1,error:e}],counters:o,...n}}function ve(o,e){return oe(e,`Action not found: "${o}"`,{aborted:true,abortedBy:"action-not-found"})}function ye(o,e,n){return oe(n,`Max depth ${e} exceeded invoking "${o}"`,{aborted:true,abortedBy:"maxDepth"})}function xe(o,e){return oe(e,`Action "${o}" is private (sub-action). Can only be invoked from within its parent scope.`)}function X(o,e){return {success:true,aborted:false,appliedCount:0,skippedCount:0,processedCount:0,totalCount:0,errors:[],data:o,counters:e}}function Ke(o){return typeof o=="object"&&o!==null&&"execute"in o}function ge(o){let e=new Map;for(let[n,i]of o){let s=i.subDirectives;if(!s)continue;let t=Object.keys(s);if(t.length===0)continue;let r=null;for(let d=0;d<t.length;d++){let c=t[d];c!=="catch"&&s[c].graph!==false&&(r===null&&(r=[]),r.push(c));}r!==null&&e.set(n,r);}return e}function me(o){let e=new Map;for(let[n,i]of o){let s=i.subDirectives;if(!s)continue;let t=Object.keys(s);if(t.length===0)continue;let r=null;for(let d=0;d<t.length;d++){let c=t[d];c!=="catch"&&(r===null&&(r=[]),r.push(c));}r!==null&&e.set(n,r);}return e}function _e(o){let e=Object.create(null),n=new Map;for(let i of Object.keys(o)){let s=o[i];Ke(s)?(e[i]=s.execute,n.set(i,s)):(e[i]=s,n.set(i,{execute:s}));}return {handlers:e,definitions:n}}function De(o,e){if(o==="*")return true;if(!o.includes("*"))return o===e;let n=o.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)}function Ce(o){return typeof o=="string"?{pattern:o}:o}function be(o,e,n){let i=new Map;if(!e&&!n){for(let s of o)i.set(s,{status:"available"});return i}if(e){let s=e.map(Ce);for(let t of o){let r=s.some(d=>De(d.pattern,t));i.set(t,{status:r?"available":"denied"});}}else {let s=n.map(Ce);for(let t of o){let r=s.find(d=>De(d.pattern,t));r?i.set(t,{status:"denied",reason:r.reason,source:r.source}):i.set(t,{status:"available"});}}return i}function Re(o){let{typeField:e,asyncHandlerSet:n,interactiveHandlerSet:i,subDirectiveFieldsForGraph:s}=o,t=new Map,r=new Set,d=new Set,c=new Set,u=new Set;return {upsert(h,C,y){t.set(h,Ue(C,e,s)),U(C,n,e,s)?r.add(h):r.delete(h),y||z(C,i,e,s)?d.add(h):d.delete(h);},remove(h){t.delete(h),r.delete(h),d.delete(h);},recompute(){c=Ae(t,r),u=Ae(t,d);},isAsync(h){return c.has(h)},isInteractive(h){return u.has(h)},has(h){return t.has(h)}}}var Z=new Map;function Ue(o,e,n=Z){let i=new Set;return K(o,e,n,i),i}function K(o,e,n,i){for(let s of o){let t=s[e];t==="action"&&typeof s.id=="string"&&i.add(s.id);let r=s.catch;if(Array.isArray(r)&&r.length>0&&K(r,e,n,i),t==="if"){let c=s.then;Array.isArray(c)&&c.length>0&&K(c,e,n,i);let u=s.else;Array.isArray(u)&&u.length>0&&K(u,e,n,i);continue}if(t===void 0)continue;let d=n.get(t);if(d!==void 0)for(let c=0;c<d.length;c++){let u=s[d[c]];!Array.isArray(u)||u.length===0||K(u,e,n,i);}}}function U(o,e,n,i=Z){for(let s of o){let t=s[n];if(t!==void 0&&e.has(t))return true;let r=s.catch;if(Array.isArray(r)&&r.length>0&&U(r,e,n,i))return true;if(t==="if"){let c=s.then;if(Array.isArray(c)&&c.length>0&&U(c,e,n,i))return true;let u=s.else;if(Array.isArray(u)&&u.length>0&&U(u,e,n,i))return true;continue}if(t===void 0)continue;let d=i.get(t);if(d!==void 0)for(let c=0;c<d.length;c++){let u=s[d[c]];if(!(!Array.isArray(u)||u.length===0)&&U(u,e,n,i))return true}}return false}function z(o,e,n,i=Z){for(let s of o){let t=s[n];if(t==="pause"||t!==void 0&&e.has(t))return true;let r=s.catch;if(Array.isArray(r)&&r.length>0&&z(r,e,n,i))return true;if(t==="if"){let c=s.then;if(Array.isArray(c)&&c.length>0&&z(c,e,n,i))return true;let u=s.else;if(Array.isArray(u)&&u.length>0&&z(u,e,n,i))return true;continue}if(t===void 0)continue;let d=i.get(t);if(d!==void 0)for(let c=0;c<d.length;c++){let u=s[d[c]];if(!(!Array.isArray(u)||u.length===0)&&z(u,e,n,i))return true}}return false}function j(o,e,n=Z){for(let i of o){let s=i[e];if(s==="pause")return true;let t=i.catch;if(Array.isArray(t)&&t.length>0&&j(t,e,n))return true;if(s==="if"){let d=i.then;if(Array.isArray(d)&&d.length>0&&j(d,e,n))return true;let c=i.else;if(Array.isArray(c)&&c.length>0&&j(c,e,n))return true;continue}if(s===void 0)continue;let r=n.get(s);if(r!==void 0)for(let d=0;d<r.length;d++){let c=i[r[d]];if(!(!Array.isArray(c)||c.length===0)&&j(c,e,n))return true}}return false}function Ae(o,e){let n=new Set(e),i=true;for(;i;){i=false;for(let[s,t]of o)if(!n.has(s)){for(let r of t)if(n.has(r)){n.add(s),i=true;break}}}return n}var Je=8,Ye="type",ae={maxDepth:10,maxRules:1e4,maxDirectives:1e5},ue=class{_directiveExecutor;_mode;_ctx;_requestedMode;_threshold;_limits;_typeField;_handlers;_definitions;_directiveHooks;_directiveAnalysis;_asyncHandlerSet;_interactiveHandlerSet;_isAsync;_isInteractive;_directivePermissions;_subDirectiveFieldsForGraph;_subDirectiveFieldsAll;_miniGraph;_interactiveExecutor;_beforeAction;_afterAction;_registry=new Map;_emitter=new O;_batchDepth=0;_batchErrors=[];_batchWarnings=[];_batchActions=[];_batchRegistered=[];_registeredIds=new Set;_directiveRunner;_directiveRunnerSync;_engineRef;constructor(e){this._requestedMode=e.mode??"auto",this._threshold=e.autoJitThreshold??Je,this._typeField=e.typeField??Ye,this._limits={maxDepth:e.limits?.maxDepth??ae.maxDepth,maxRules:e.limits?.maxRules??ae.maxRules,maxDirectives:e.limits?.maxDirectives??ae.maxDirectives};let{handlers:n,definitions:i}=_e(e.handlers);for(let c of Object.keys(e.handlers))if(N.has(c))throw new Error(`Handler type "${c}" 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=n,this._definitions=i,this._directivePermissions=be(Object.keys(n),e.allowedDirectives,e.blockedDirectives),this._directiveHooks=e.directiveHooks??{},this._beforeAction=e.actionHooks?.beforeAction??null,this._afterAction=e.actionHooks?.afterAction??null,this._directiveAnalysis=analyzeSlots(this._directiveHooks,DIRECTIVE_SLOT_NAMES);let s=new Set,t=new Set;for(let[c,u]of this._definitions)(u.async===true||isAsyncFunction(u.execute))&&s.add(c),(u.interactive===true||isGeneratorFunction(u.execute))&&t.add(c);if(this._asyncHandlerSet=s,this._interactiveHandlerSet=t,this._isInteractive=e.interactive!==void 0,!this._isInteractive&&t.size>0){let c=Array.from(t).join(", ");throw new Error(`Handler(s) [${c}] are interactive but engine has no \`interactive\` config. Add \`interactive: {}\` to enable interactive mode.`)}this._isAsync=this._directiveAnalysis.hasAnyAsync||s.size>0;let r=ge(this._definitions);this._subDirectiveFieldsForGraph=r,this._subDirectiveFieldsAll=me(this._definitions),this._miniGraph=Re({typeField:this._typeField,asyncHandlerSet:s,interactiveHandlerSet:t,subDirectiveFieldsForGraph:r}),this._engineRef={runDirectives:(c,u)=>this._executeDirectives(c,u),runDirectivesAsync:(c,u)=>this._executeDirectivesAsync(c,u),invoke:(c,u,h)=>this._invokeInternal(c,u,h),invokeAsync:(c,u,h)=>this._invokeInternalAsync(c,u,h),isActionAsync:c=>this._miniGraph.has(c)?this._miniGraph.isAsync(c):void 0,isActionInteractive:c=>this._miniGraph.has(c)?this._miniGraph.isInteractive(c):void 0,invokeInteractive:(c,u,h)=>this._invokeInteractiveInternal(c,u,h),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=(c,u)=>this._directiveExecutor(c,u,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);let d=J(this._directiveAnalysis,false);this._directiveRunnerSync=(c,u)=>d(c,u,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=J(this._directiveAnalysis,true),this._mode="interpret"):(this._directiveExecutor=d,this._mode="interpret"),this._interactiveExecutor=this._isInteractive?this._isAsync?ee(this._directiveAnalysis,true):ee(this._directiveAnalysis,false):null;}register(e){let n=[],i=[],s=[],t=[];for(let d of e){if(!d.id){i.push({actionId:"",error:"Action must have an id"});continue}if(!this._isInteractive&&j(d.directives,this._typeField,this._subDirectiveFieldsForGraph)){i.push({actionId:d.id,error:'Action uses directive type:"pause" but engine has no `interactive` config. Add `interactive: {}` to enable.'});continue}let c=le(d,this._handlers,this._definitions,this._typeField);if(c.length>0){for(let u of c)i.push({actionId:d.id,error:u});continue}t.push(d);}for(let d of t){let c=L(d.directives,this._typeField,this._subDirectiveFieldsAll),u={definition:d,directives:c,compiled:null,invokeCount:0};this._registry.set(d.id,u),this._registeredIds.add(d.id),this._miniGraph.upsert(d.id,c,d.interactive===true),n.push(d.id);}if(this._batchDepth>0){this._batchErrors.push(...i),this._batchWarnings.push(...s);for(let d of t)this._batchActions.push(d);return this._batchRegistered.push(...n),{registered:n,errors:i,warnings:s}}t.length>0&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile());let r={registered:n,errors:i,warnings:s};return n.length>0&&this._emitter.emit("register",{actions:t,result:r,registered:n}),r}unregister(e){let n=this._registry.delete(e);n&&(this._registeredIds.delete(e),this._miniGraph.remove(e));let i=e+"/",s=[];for(let t of this._registry.keys())t.startsWith(i)&&(this._registry.delete(t),this._registeredIds.delete(t),this._miniGraph.remove(t),s.push(t));return n&&(this._miniGraph.recompute(),this._invalidateAndMaybeRecompile(),this._emitter.emit("unregister",{id:e,cascaded:s})),n}invoke(e,n,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 s=i!==void 0?i:this._requireCtx(),t=createRootFrame(s,this._limits);return this._invokeInternal(e,n,t)}async invokeAsync(e,n,i){if(this._miniGraph.isInteractive(e))throw new Error(`Cannot call invokeAsync("${e}") \u2014 action is interactive (transitively). Use invokeInteractive() instead.`);let s=i!==void 0?i:this._requireCtx(),t=createRootFrame(s,this._limits);return this._invokeInternalAsync(e,n,t)}setContext(e){this._ctx=e;}context(e,n){let i=this._ctx;this._ctx=e;try{return n()}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,n){return this._emitter.on(e,n)}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,n,i){if(!this._isInteractive||this._interactiveExecutor===null)throw new Error("Cannot call invokeInteractive() \u2014 engine has no `interactive` config. Add `interactive: {}` to enable.");let s=i!==void 0?i:this._requireCtx(),t=createRootFrame(s,this._limits);return this._invokeInteractiveInternal(e,n,t)}_invokeInteractiveInternal(e,n,i){let s=this._prepareInvoke(e,n,i);if("success"in s)return ke(s,this._isAsync);let{stored:t,childFrame:r,childScope:d}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,n,r);if(u?.skip)return ke(X(u.data,r.counters),this._isAsync)}let c;if(t.compiled&&t.compiled.isInteractive)c=t.compiled.fn(r,r.scope,t.compiled.$);else {let u=this._interactiveExecutor;c=u(t.directives,r,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives);}return Qe(c,e,n,r,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,n]of this._registry)n.compiled||(n.compiled=this._compileAction(e,n.directives));}}_invokeInternal(e,n,i){let s=this._prepareInvoke(e,n,i);if("success"in s)return s;let{stored:t,childFrame:r,childScope:d}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,n,r);if(u?.skip)return X(u.data,r.counters)}let c;if(t.compiled?c=t.compiled.fn(r,d,t.compiled.$):this._isAsync&&!this._miniGraph.isAsync(e)?(t.compiled=this._compileAction(e,t.directives),c=t.compiled.fn(r,d,t.compiled.$)):(c=this._directiveRunner(t.directives,r),this._maybeAutoPromote(t)),this._afterAction!==null){let u=this._afterAction(e,n,c,r);u!==void 0&&(c=u);}return c}async _invokeInternalAsync(e,n,i){let s=this._prepareInvoke(e,n,i);if("success"in s)return s;let{stored:t,childFrame:r,childScope:d}=s;if(this._beforeAction!==null){let u=this._beforeAction(e,n,r);if(u?.skip)return X(u.data,r.counters)}let c;if(t.compiled?c=await t.compiled.fn(r,d,t.compiled.$):(c=await this._directiveRunner(t.directives,r),this._maybeAutoPromote(t)),this._afterAction!==null){let u=this._afterAction(e,n,c,r);u!==void 0&&(c=u);}return c}_prepareInvoke(e,n,i){let s=this._registry.get(e);if(!s)return ve(e,i.counters);if(e.includes("/")&&!this._isAccessible(e,i))return xe(e,i.counters);if(i.depth>=i.limits.maxDepth)return ye(e,i.limits.maxDepth,i.counters);let t=Object.create(i.scope);n&&Object.assign(t,n);let r=i.child("action:"+e,0,e).withScope(t);return {stored:s,childFrame:r,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,n){return this._directiveExecutor(e,n,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}async _executeDirectivesAsync(e,n){return this._directiveExecutor(e,n,this._handlers,this._directiveHooks,this._typeField,this._engineRef,this._limits.maxDirectives)}_compileAction(e,n){let i=this._miniGraph.isAsync(e),s=this._miniGraph.isInteractive(e),{fn:t,isAsync:r,isInteractive:d}=se(n,this._directiveAnalysis,this._typeField,this._asyncHandlerSet,i,s,this._interactiveHandlerSet),c={d:n,h:this._handlers,hooks:this._directiveHooks,engine:this._engineRef,runner:this._directiveRunner,runnerSync:this._directiveRunnerSync};return {fn:t,$:c,isAsync:r,isInteractive:d}}_isAccessible(e,n){let s="action:"+e.slice(0,e.lastIndexOf("/"));return n.path.includes(s)}_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}=te(this._directiveAnalysis,this._isAsync);return e}_invalidateAndMaybeRecompile(){for(let e of this._registry.values())e.compiled=null;if(this._requestedMode==="jit")for(let[e,n]of this._registry)n.compiled=this._compileAction(e,n.directives);}};function ke(o,e){return e?{next:()=>Promise.resolve({value:o,done:true}),return:()=>Promise.resolve({value:o,done:true}),throw:s=>Promise.reject(s),[Symbol.asyncIterator](){return this}}:{next:()=>({value:o,done:true}),return:()=>({value:o,done:true}),throw:i=>{throw i},[Symbol.iterator](){return this}}}function Qe(o,e,n,i,s,t){if(t){let c=o;return {async next(h){let C=await c.next(h);if(C.done){let y=C.value;if(s!==null){let p=s(e,n,y,i);p!==void 0&&(y=p);}return {value:y,done:true}}return {value:C.value,done:false}},async return(){let h=await c.return(void 0),C=h.value;if(h.done&&s!==null){let y=s(e,n,C,i);y!==void 0&&(C=y);}return {value:C,done:true}},async throw(h){let C=await c.throw(h);if(C.done){let y=C.value;if(s!==null){let p=s(e,n,y,i);p!==void 0&&(y=p);}return {value:y,done:true}}return {value:C.value,done:false}},[Symbol.asyncIterator](){return this}}}let r=o;return {next(c){let u=r.next(c);if(u.done){let h=u.value;if(s!==null){let C=s(e,n,h,i);C!==void 0&&(h=C);}return {value:h,done:true}}return {value:u.value,done:false}},return(){let c=r.return(void 0),u=c.value;if(c.done&&s!==null){let h=s(e,n,u,i);h!==void 0&&(u=h);}return {value:u,done:true}},throw(c){let u=r.throw(c);if(u.done){let h=u.value;if(s!==null){let C=s(e,n,h,i);C!==void 0&&(h=C);}return {value:h,done:true}}return {value:u.value,done:false}},[Symbol.iterator](){return this}}}function Xe(o){return new ue(o)}export{N as RESERVED_TYPES,O as SimpleEmitter,se as buildActionExecutor,te as buildDirectiveExecutor,Xe as createActionEngine,J as createDirectiveInterpreter,Ee as drainAsync,Ie as drainSync,L as normalizeDirectives,we as replayResponder};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statedelta-actions/actions",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Directive execution engine with JIT compilation and BailHook interception",
5
5
  "keywords": [
6
6
  "statedelta",
@@ -55,6 +55,7 @@
55
55
  "test:coverage": "vitest run --coverage",
56
56
  "lint": "eslint src/",
57
57
  "typecheck": "tsc --noEmit",
58
+ "validate": "pnpm typecheck && pnpm lint",
58
59
  "clean": "rm -rf dist"
59
60
  }
60
61
  }