yaml-flow 6.0.0 → 7.1.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/board-live-cards-cli.js +4 -4
- package/browser/asset-integrity.json +3 -3
- package/browser/board-livecards-client.js +2 -0
- package/browser/board-livecards-client.js.map +1 -0
- package/browser/board-livecards-localstorage.js +10 -0
- package/browser/board-livecards-localstorage.js.map +1 -0
- package/browser/board-livegraph-engine.js +2 -2
- package/browser/board-livegraph-engine.js.map +1 -1
- package/browser/card-compute.js +28 -28
- package/browser/compute-jsonata.js +5 -0
- package/browser/compute-jsonata.js.map +1 -0
- package/browser/live-cards.js +264 -151
- package/card-store.js +4 -4
- package/dist/{board-live-cards-public-CltXYgaY.d.cts → board-live-cards-public-5n1-syA3.d.cts} +8 -5
- package/dist/{board-live-cards-public-f-E-FAyp.d.ts → board-live-cards-public-CK_J8uv0.d.ts} +8 -5
- package/dist/board-livegraph-runtime/index.cjs +2 -2
- package/dist/board-livegraph-runtime/index.cjs.map +1 -1
- package/dist/board-livegraph-runtime/index.d.cts +11 -9
- package/dist/board-livegraph-runtime/index.d.ts +11 -9
- package/dist/board-livegraph-runtime/index.js +2 -2
- package/dist/board-livegraph-runtime/index.js.map +1 -1
- package/dist/board-livegraph-runtime/jsonata-sync.cjs +37 -1
- package/dist/card-compute/index.cjs +4 -4
- package/dist/card-compute/index.cjs.map +1 -1
- package/dist/card-compute/index.d.cts +5 -1
- package/dist/card-compute/index.d.ts +5 -1
- package/dist/card-compute/index.js +4 -4
- package/dist/card-compute/index.js.map +1 -1
- package/dist/card-compute/jsonata-sync.cjs +37 -1
- package/dist/cli/browser-api/board-live-cards-browser-adapter.cjs +2 -1
- package/dist/cli/browser-api/board-live-cards-browser-adapter.cjs.map +1 -1
- package/dist/cli/browser-api/board-live-cards-browser-adapter.d.cts +27 -14
- package/dist/cli/browser-api/board-live-cards-browser-adapter.d.ts +27 -14
- package/dist/cli/browser-api/board-live-cards-browser-adapter.js +2 -1
- package/dist/cli/browser-api/board-live-cards-browser-adapter.js.map +1 -1
- package/dist/cli/browser-api/card-store-browser-api.cjs +1 -1
- package/dist/cli/browser-api/card-store-browser-api.cjs.map +1 -1
- package/dist/cli/browser-api/card-store-browser-api.js +1 -1
- package/dist/cli/browser-api/card-store-browser-api.js.map +1 -1
- package/dist/cli/browser-api/jsonata-sync.cjs +37 -1
- package/dist/cli/node/artifacts-store-cli.cjs +8 -8
- package/dist/cli/node/artifacts-store-cli.cjs.map +1 -1
- package/dist/cli/node/artifacts-store-cli.js +8 -8
- package/dist/cli/node/artifacts-store-cli.js.map +1 -1
- package/dist/cli/node/board-live-cards-cli.cjs +7 -7
- package/dist/cli/node/board-live-cards-cli.cjs.map +1 -1
- package/dist/cli/node/board-live-cards-cli.js +7 -7
- package/dist/cli/node/board-live-cards-cli.js.map +1 -1
- package/dist/cli/node/card-store-cli.cjs +5 -5
- package/dist/cli/node/card-store-cli.cjs.map +1 -1
- package/dist/cli/node/card-store-cli.js +5 -5
- package/dist/cli/node/card-store-cli.js.map +1 -1
- package/dist/cli/node/execution-adapter.cjs +3 -0
- package/dist/cli/node/execution-adapter.cjs.map +1 -0
- package/dist/cli/node/execution-adapter.d.cts +174 -0
- package/dist/cli/node/execution-adapter.d.ts +174 -0
- package/dist/cli/node/execution-adapter.js +3 -0
- package/dist/cli/node/execution-adapter.js.map +1 -0
- package/dist/cli/node/fs-board-adapter.cjs +7 -7
- package/dist/cli/node/fs-board-adapter.cjs.map +1 -1
- package/dist/cli/node/fs-board-adapter.d.cts +2 -2
- package/dist/cli/node/fs-board-adapter.d.ts +2 -2
- package/dist/cli/node/fs-board-adapter.js +7 -7
- package/dist/cli/node/fs-board-adapter.js.map +1 -1
- package/dist/cli/node/jsonata-sync.cjs +37 -1
- package/dist/cli/node/source-cli-task-executor.cjs +4 -4
- package/dist/cli/node/source-cli-task-executor.cjs.map +1 -1
- package/dist/cli/node/source-cli-task-executor.js +4 -4
- package/dist/cli/node/source-cli-task-executor.js.map +1 -1
- package/dist/continuous-event-graph/index.cjs +2 -2
- package/dist/continuous-event-graph/index.cjs.map +1 -1
- package/dist/continuous-event-graph/index.js +2 -2
- package/dist/continuous-event-graph/index.js.map +1 -1
- package/dist/continuous-event-graph/jsonata-sync.cjs +37 -1
- package/dist/execution-refs.cjs +2 -1
- package/dist/execution-refs.cjs.map +1 -1
- package/dist/execution-refs.d.cts +55 -12
- package/dist/execution-refs.d.ts +55 -12
- package/dist/execution-refs.js +2 -1
- package/dist/execution-refs.js.map +1 -1
- package/dist/index.cjs +10 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +10 -10
- package/dist/index.js.map +1 -1
- package/dist/jsonata-sync.cjs +37 -1
- package/dist/server-runtime/index.cjs +9 -0
- package/dist/server-runtime/index.cjs.map +1 -0
- package/dist/server-runtime/index.d.cts +31 -0
- package/dist/server-runtime/index.d.ts +31 -0
- package/dist/server-runtime/index.js +9 -0
- package/dist/server-runtime/index.js.map +1 -0
- package/dist/server-runtime/jsonata-sync.cjs +7623 -0
- package/dist/step-machine-public/index.cjs +3 -0
- package/dist/step-machine-public/index.cjs.map +1 -0
- package/dist/step-machine-public/index.d.cts +166 -0
- package/dist/step-machine-public/index.d.ts +166 -0
- package/dist/step-machine-public/index.js +3 -0
- package/dist/step-machine-public/index.js.map +1 -0
- package/dist/step-machine-public/jsonata-sync.cjs +7623 -0
- package/dist/storage-refs.cjs +2 -2
- package/dist/storage-refs.cjs.map +1 -1
- package/dist/storage-refs.d.cts +6 -6
- package/dist/storage-refs.d.ts +6 -6
- package/dist/storage-refs.js +2 -2
- package/dist/storage-refs.js.map +1 -1
- package/dist/types-CU3DjTKL.d.cts +147 -0
- package/dist/types-HGDTWIun.d.ts +147 -0
- package/examples/browser/boards/portfolio-tracker/portfolio-t4.js +9 -10
- package/examples/browser/boards/portfolio-tracker/portfolio-tracker-http-test.js +370 -0
- package/examples/browser/boards/portfolio-tracker/portfolio-tracker-http-test.py +398 -0
- package/examples/browser/boards/portfolio-tracker/portfolio-tracker-public.js +9 -10
- package/examples/browser/boards/portfolio-tracker/portfolio-tracker-server.js +300 -0
- package/examples/browser/boards/portfolio-tracker/portfolio-tracker-server.py +617 -0
- package/examples/browser/boards/portfolio-tracker/portfolio-tracker-sse-worker.js +48 -0
- package/examples/browser/boards/portfolio-tracker/portfolio-tracker.py +11 -10
- package/examples/cli/step-machine-cli/portfolio-tracker/handlers/_board-cli.js +19 -4
- package/examples/cli/step-machine-cli/portfolio-tracker/handlers/add-cards-cli.js +4 -8
- package/examples/cli/step-machine-cli/portfolio-tracker/handlers/init-board-cli.js +6 -10
- package/examples/cli/step-machine-cli/portfolio-tracker/handlers/poll-status-cli.js +8 -16
- package/examples/cli/step-machine-cli/portfolio-tracker/handlers/reset-board-dir-cli.js +2 -6
- package/examples/cli/step-machine-cli/portfolio-tracker/handlers/retrigger-cli.js +4 -8
- package/examples/cli/step-machine-cli/portfolio-tracker/handlers/status-cli.js +3 -7
- package/examples/cli/step-machine-cli/portfolio-tracker/handlers/update-holdings-cli.js +4 -8
- package/examples/cli/step-machine-cli/portfolio-tracker/handlers/wait-completed-cli.js +7 -16
- package/examples/cli/step-machine-cli/portfolio-tracker/handlers/write-prices-cli.js +2 -6
- package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/_board_pycli.py +13 -3
- package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/add-cards.py +2 -1
- package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/init-board.py +2 -1
- package/examples/cli/step-machine-cli/portfolio-tracker/handlers-py/poll-status.py +2 -1
- package/examples/cli/step-machine-cli/portfolio-tracker/portfolio-tracker.flow.yaml +20 -24
- package/examples/cli/step-machine-cli/portfolio-tracker/run-inline-python-demo-pycli.py +0 -3
- package/examples/cli/step-machine-demo/jsonata-init-board-cli.js +8 -13
- package/examples/cli/step-machine-demo/jsonata-init-board.flow.yaml +33 -9
- package/examples/cli/step-machine-demo/one-step-cli-only.flow.yaml +3 -1
- package/examples/cli/step-machine-demo/step2-double-cli.js +6 -12
- package/examples/cli/step-machine-demo/two-step-math.flow.yaml +66 -4
- package/examples/cli/step-machine-demo/two-step-mixed.flow.yaml +13 -5
- package/examples/example-board/agent-instructions.md +1 -1
- package/examples/example-board/cards/card-my-identity.json +30 -6
- package/examples/example-board/cards/card-portfolio-action.json +24 -6
- package/examples/example-board/cards/card-portfolio-intelligence.json +97 -0
- package/examples/example-board/cards/card-portfolio-risks.json +24 -6
- package/examples/example-board/cards/card-rebalance-impact.json +22 -6
- package/examples/example-board/cards/card-rebalance-sim.json +66 -15
- package/examples/example-board/cards/cardT-market-prices.json +80 -0
- package/examples/example-board/cards/{card-portfolio-value.json → cardT-portfolio-value.json} +38 -10
- package/examples/example-board/cards/cardT-portfolio.json +78 -0
- package/examples/example-board/demo-server-config.json +1 -1
- package/examples/example-board/demo-server.js +383 -69
- package/examples/example-board/demo-shell-localstorage.html +774 -0
- package/examples/example-board/demo-shell-with-server.html +18 -36
- package/examples/example-board/demo-shell.html +5 -4
- package/examples/example-board/demo-task-executor.js +213 -265
- package/package.json +15 -13
- package/step-machine-cli.js +43 -310
- package/board-livecards-server-runtime.js +0 -1513
- package/browser/board-livecards-runtime-client.js +0 -263
- package/dist/pycli/quickjs-board-runtime.global.js +0 -9
- package/dist/pycli/quickjs-board-runtime.global.js.map +0 -1
- package/dist/pycli/quickjs-step-machine-runtime.global.js +0 -5
- package/dist/pycli/quickjs-step-machine-runtime.global.js.map +0 -1
- package/examples/cli/step-machine-demo/two-step-math-handlers.js +0 -32
- package/examples/cli/step-machine-demo/two-step-mixed-handlers.js +0 -24
- package/examples/example-board/cards/card-market-prices.json +0 -56
- package/examples/example-board/cards/card-portfolio.json +0 -44
- package/examples/example-board/demo-shell-browser.html +0 -675
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.
|
|
1
|
+
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsonataSync = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
|
|
2
2
|
/**
|
|
3
3
|
* © Copyright IBM Corp. 2018 All Rights Reserved
|
|
4
4
|
* Project name: JSONata
|
|
@@ -2839,6 +2839,10 @@ const functions = (() => {
|
|
|
2839
2839
|
}
|
|
2840
2840
|
|
|
2841
2841
|
var result = createSequence();
|
|
2842
|
+
// PATCH: $map must always return an array (never collapse to scalar),
|
|
2843
|
+
// even when the input has exactly 1 item. keepSingleton prevents the
|
|
2844
|
+
// length===1 → result[0] collapse in evaluate().
|
|
2845
|
+
result.keepSingleton = true;
|
|
2842
2846
|
// do the map - iterate over the arrays, and invoke func
|
|
2843
2847
|
for (var i = 0; i < arr.length; i++) {
|
|
2844
2848
|
var func_args = hofFuncArgs(func, arr[i], i, arr);
|
|
@@ -2865,6 +2869,8 @@ const functions = (() => {
|
|
|
2865
2869
|
}
|
|
2866
2870
|
|
|
2867
2871
|
var result = createSequence();
|
|
2872
|
+
// PATCH: $filter must always return an array (never scalar)
|
|
2873
|
+
result.keepSingleton = true;
|
|
2868
2874
|
|
|
2869
2875
|
for (var i = 0; i < arr.length; i++) {
|
|
2870
2876
|
var entry = arr[i];
|
|
@@ -3022,6 +3028,8 @@ const functions = (() => {
|
|
|
3022
3028
|
} else if (arg !== null && typeof arg === 'object' && !isFunction(arg)) {
|
|
3023
3029
|
Object.keys(arg).forEach(key => result.push(key));
|
|
3024
3030
|
}
|
|
3031
|
+
// PATCH: $keys must always return an array (never scalar)
|
|
3032
|
+
result.keepSingleton = true;
|
|
3025
3033
|
return result;
|
|
3026
3034
|
}
|
|
3027
3035
|
|
|
@@ -3096,6 +3104,8 @@ const functions = (() => {
|
|
|
3096
3104
|
*/
|
|
3097
3105
|
function spread(arg) {
|
|
3098
3106
|
var result = createSequence();
|
|
3107
|
+
// PATCH: $spread must always return an array (never scalar)
|
|
3108
|
+
result.keepSingleton = true;
|
|
3099
3109
|
|
|
3100
3110
|
if (Array.isArray(arg)) {
|
|
3101
3111
|
// spread all of the items in the array
|
|
@@ -3168,6 +3178,8 @@ const functions = (() => {
|
|
|
3168
3178
|
*/
|
|
3169
3179
|
function each(obj, func) {
|
|
3170
3180
|
var result = createSequence();
|
|
3181
|
+
// PATCH: $each must always return an array (never scalar)
|
|
3182
|
+
result.keepSingleton = true;
|
|
3171
3183
|
|
|
3172
3184
|
for (var key in obj) {
|
|
3173
3185
|
var func_args = hofFuncArgs(func, obj[key], key, obj);
|
|
@@ -3600,6 +3612,7 @@ var jsonata = (function() {
|
|
|
3600
3612
|
var resultSequence;
|
|
3601
3613
|
var isTupleStream = false;
|
|
3602
3614
|
var tupleBindings = undefined;
|
|
3615
|
+
var traversedArray = false; // PATCH: track if any step iterated over an array
|
|
3603
3616
|
|
|
3604
3617
|
// evaluate each step in turn
|
|
3605
3618
|
for(var ii = 0; ii < expr.steps.length; ii++) {
|
|
@@ -3624,6 +3637,11 @@ var jsonata = (function() {
|
|
|
3624
3637
|
break;
|
|
3625
3638
|
}
|
|
3626
3639
|
|
|
3640
|
+
// PATCH: detect array traversal from the step result
|
|
3641
|
+
if (!isTupleStream && Array.isArray(resultSequence) && resultSequence._fromArrayField) {
|
|
3642
|
+
traversedArray = true;
|
|
3643
|
+
}
|
|
3644
|
+
|
|
3627
3645
|
if(typeof step.focus === 'undefined') {
|
|
3628
3646
|
inputSequence = resultSequence;
|
|
3629
3647
|
}
|
|
@@ -3650,6 +3668,12 @@ var jsonata = (function() {
|
|
|
3650
3668
|
resultSequence.keepSingleton = true;
|
|
3651
3669
|
}
|
|
3652
3670
|
|
|
3671
|
+
// PATCH: Always preserve array results from path expressions that traversed
|
|
3672
|
+
// through an array. Ensures predictable array output regardless of input cardinality.
|
|
3673
|
+
if (traversedArray && Array.isArray(resultSequence) && resultSequence.sequence) {
|
|
3674
|
+
Object.defineProperty(resultSequence, 'keepSingleton', { value: true, enumerable: false, configurable: true });
|
|
3675
|
+
}
|
|
3676
|
+
|
|
3653
3677
|
if (expr.hasOwnProperty('group')) {
|
|
3654
3678
|
resultSequence = evaluateGroupExpression(expr.group, isTupleStream ? tupleBindings : resultSequence, environment)
|
|
3655
3679
|
}
|
|
@@ -3698,8 +3722,10 @@ var jsonata = (function() {
|
|
|
3698
3722
|
}
|
|
3699
3723
|
|
|
3700
3724
|
var resultSequence = createSequence();
|
|
3725
|
+
var _flattenedArray = false; // PATCH: track if we flattened a real array
|
|
3701
3726
|
if(lastStep && result.length === 1 && Array.isArray(result[0]) && !isSequence(result[0])) {
|
|
3702
3727
|
resultSequence = result[0];
|
|
3728
|
+
_flattenedArray = true;
|
|
3703
3729
|
} else {
|
|
3704
3730
|
// flatten the sequence
|
|
3705
3731
|
result.forEach(function(res) {
|
|
@@ -3709,10 +3735,20 @@ var jsonata = (function() {
|
|
|
3709
3735
|
} else {
|
|
3710
3736
|
// res is a sequence - flatten it into the parent sequence
|
|
3711
3737
|
res.forEach(val => resultSequence.push(val));
|
|
3738
|
+
// PATCH: only mark as flattened array if res is a genuine data array,
|
|
3739
|
+
// not an intermediate sequence (from filter results, etc.)
|
|
3740
|
+
if (!isSequence(res)) {
|
|
3741
|
+
_flattenedArray = true;
|
|
3742
|
+
}
|
|
3712
3743
|
}
|
|
3713
3744
|
});
|
|
3714
3745
|
}
|
|
3715
3746
|
|
|
3747
|
+
// PATCH: Mark sequences that came from flattening array fields
|
|
3748
|
+
if (_flattenedArray && Array.isArray(resultSequence)) {
|
|
3749
|
+
Object.defineProperty(resultSequence, '_fromArrayField', { value: true, enumerable: false, configurable: true });
|
|
3750
|
+
}
|
|
3751
|
+
|
|
3716
3752
|
return resultSequence;
|
|
3717
3753
|
}
|
|
3718
3754
|
|
package/dist/execution-refs.cjs
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
'use strict';function
|
|
1
|
+
'use strict';var s="b64:";function l(e){let r=new TextEncoder().encode(e),t=globalThis.Buffer,n;if(t)n=t.from(r).toString("base64");else if(typeof btoa=="function"){let o="";for(let a of r)o+=String.fromCharCode(a);n=btoa(o);}else throw new Error("No base64 encoder available in this runtime");return n.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function i(e){return `${s}${l(JSON.stringify(e))}`}function c(e,r){let t;return /\.m?js$/i.test(e)?t="local-node":/\.py$/i.test(e)?t="local-python":t="local-process",{meta:"task-executor",howToRun:t,whatToRun:i({kind:"fs-path",value:e}),...r?{extra:r}:{}}}function f(e){return JSON.stringify(e)}function d(e){let r;try{r=JSON.parse(e);}catch{throw new Error(`parseExecutionRef: invalid JSON \u2014 ${e}`)}if(typeof r!="object"||r===null||typeof r.howToRun!="string"||typeof r.whatToRun!="string")throw new Error(`parseExecutionRef: missing required fields howToRun/whatToRun \u2014 ${e}`);return r}
|
|
2
|
+
exports.executionRefFromScriptPath=c;exports.parseExecutionRef=d;exports.serializeExecutionRef=f;//# sourceMappingURL=execution-refs.cjs.map
|
|
2
3
|
//# sourceMappingURL=execution-refs.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli/common/execution-interface.ts"],"names":["executionRefFromScriptPath","scriptPath","extra","howToRun","serializeExecutionRef","ref","parseExecutionRef","s","parsed"],"mappings":"aA6OO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CACc,CACd,IAAIC,CAAAA,CACJ,OAAI,WAAW,IAAA,CAAKF,CAAU,EAAGE,CAAAA,CAAW,YAAA,CACnC,SAAS,IAAA,CAAKF,CAAU,EAAGE,CAAAA,CAAW,cAAA,CAC1CA,EAAW,eAAA,CACT,CACL,KAAM,eAAA,CACN,QAAA,CAAAA,EACA,SAAA,CAAW,CAAA,WAAA,EAAcF,CAAU,CAAA,CAAA,CACnC,GAAIC,EAAQ,CAAE,KAAA,CAAAA,CAAM,CAAA,CAAI,EAC1B,CACF,CAUO,SAASE,CAAAA,CAAsBC,CAAAA,CAA2B,CAC/D,OAAO,IAAA,CAAK,SAAA,CAAUA,CAAG,CAC3B,CAMO,SAASC,CAAAA,CAAkBC,CAAAA,CAAyB,CACzD,IAAIC,CAAAA,CACJ,GAAI,CACFA,CAAAA,CAAS,KAAK,KAAA,CAAMD,CAAC,EACvB,CAAA,KAAQ,CACN,MAAM,IAAI,KAAA,CAAM,CAAA,uCAAA,EAAqCA,CAAC,CAAA,CAAE,CAC1D,CACA,GACE,OAAOC,GAAW,QAAA,EAClBA,CAAAA,GAAW,MACX,OAAQA,CAAAA,CAAmC,UAAa,QAAA,EACxD,OAAQA,EAAmC,SAAA,EAAc,QAAA,CAEzD,MAAM,IAAI,KAAA,CAAM,wEAAmED,CAAC,CAAA,CAAE,CAAA,CAExF,OAAOC,CACT","file":"execution-refs.cjs","sourcesContent":["/**\n * execution-interface.ts\n *\n * Pure module — no Node/platform imports. Safe for any runtime.\n *\n * Defines the portable descriptor types for invoking any executable target,\n * regardless of transport (local process, HTTP endpoint, cloud function, etc.).\n *\n * Parallel to storage-interface.ts (which describes WHERE data lives), this\n * module describes HOW to invoke a piece of logic.\n *\n * ────────────────────────────────────────────────────────────────────────────\n * CORE CONCEPTS\n * ────────────────────────────────────────────────────────────────────────────\n *\n * ExecutionRef — self-contained, serializable JSON descriptor for one invocation target.\n * • howToRun — transport / runtime kind (discriminator)\n * • whatToRun — address of the artifact (KindValueRef wire form: ::kind::value)\n * • argsMassaging — optional JSONata expressions that map logical args → physical call shape\n * • meta — optional human-readable label (e.g. 'task-executor', 'chat-handler')\n *\n * ExecutionResult — standardized envelope returned by any invocation.\n * • status: 'success' | 'fail' | 'error'\n * • data — KindValueRef wire form pointing to output blob (on success)\n * • error — human-readable message (on fail/error)\n *\n * ────────────────────────────────────────────────────────────────────────────\n * howToRun VALUES\n * ────────────────────────────────────────────────────────────────────────────\n *\n * 'local-node' node <whatToRun> [argv...]\n * 'local-python' python <whatToRun> [argv...]\n * 'local-process' execute <whatToRun> directly (shebang / pre-resolved binary)\n * 'http:post' HTTP POST to <whatToRun>\n * 'http:get' HTTP GET to <whatToRun>\n * 'built-in' resolved by the adapter to a well-known internal implementation\n *\n * ────────────────────────────────────────────────────────────────────────────\n * argsMassaging\n * ────────────────────────────────────────────────────────────────────────────\n *\n * Each field is a JSONata expression evaluated against the caller's logical args object.\n * If argsMassaging is omitted, the adapter uses its default mapping for the howToRun kind.\n *\n * cmdTemplate — array of JSONata exprs, each producing one argv string (local transports)\n * urlTemplate — JSONata expr producing the final URL string (http transports)\n * bodyTemplate — JSONata expr producing the request body object (http transports)\n *\n * ────────────────────────────────────────────────────────────────────────────\n * SERIALIZATION\n * ────────────────────────────────────────────────────────────────────────────\n *\n * ExecutionRef is a plain JSON object — store it as-is on disk, in Cosmos, or any DB.\n * No special encoding needed. parseExecutionRef / serializeExecutionRef are thin\n * JSON wrappers provided for symmetry with storage-interface.\n *\n * ────────────────────────────────────────────────────────────────────────────\n * USAGE EXAMPLES\n * ────────────────────────────────────────────────────────────────────────────\n *\n * // Built-in source-cli task executor (resolved by adapter from cliDir):\n * const builtIn: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'built-in',\n * whatToRun: '::built-in::source-cli-task-executor',\n * };\n *\n * // External local-node task executor with default protocol args:\n * const local: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'local-node',\n * whatToRun: '::fs-path::/path/to/my-executor.js',\n * };\n *\n * // Azure Function task executor with custom arg mapping:\n * const azureFn: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'http:post',\n * whatToRun: '::http-url::https://myfn.azurewebsites.net/api/task-executor',\n * argsMassaging: {\n * urlTemplate: \"whatToRun & '?op=' & subcommand\",\n * bodyTemplate: \"{ 'inRef': inRef, 'outRef': outRef, 'token': token }\",\n * },\n * };\n *\n * // Chat handler over HTTP with a different logical args shape:\n * const chatHandler: ExecutionRef = {\n * meta: 'chat-handler',\n * howToRun: 'http:post',\n * whatToRun: '::http-url::https://myfn.azurewebsites.net/api/chat',\n * argsMassaging: {\n * bodyTemplate: \"{ 'message': message, 'context': context, 'sessionId': sessionId }\",\n * },\n * };\n */\n\n// ============================================================================\n// ArgsMassaging\n// ============================================================================\n\n/**\n * Optional JSONata-based mapping from logical args → physical invocation shape.\n *\n * Each field is a JSONata expression string evaluated against the caller's\n * logical args object (e.g. `{ inRef, outRef, errRef }` for a task-executor).\n *\n * If argsMassaging is omitted entirely, the execution adapter uses its default\n * mapping for the given howToRun kind.\n */\nexport interface ArgsMassaging {\n /**\n * For local transports ('local-node', 'local-python', 'local-process').\n * Array of JSONata expressions — each evaluates to one argv string.\n * The resolved strings are appended after the base command.\n *\n * @example\n * // Standard task-executor protocol:\n * cmdTemplate: [\n * \"'run-source-fetch'\",\n * \"'--in-ref'\", \"inRef\",\n * \"'--out-ref'\", \"outRef\",\n * \"'--err-ref'\", \"errRef\",\n * ]\n */\n cmdTemplate?: string[];\n\n /**\n * For http transports ('http:post', 'http:get').\n * JSONata expression that produces the final URL string.\n * The input context includes 'whatToRun' (the base URL from the ref)\n * plus all logical args.\n *\n * @example\n * urlTemplate: \"whatToRun & '?op=' & subcommand\"\n */\n urlTemplate?: string;\n\n /**\n * For http transports.\n * JSONata expression that produces the request body object.\n * Evaluated against the logical args object.\n *\n * @example\n * bodyTemplate: \"{ 'inRef': inRef, 'outRef': outRef, 'token': token }\"\n */\n bodyTemplate?: string;\n}\n\n// ============================================================================\n// ExecutionRef\n// ============================================================================\n\n/**\n * Self-contained, serializable descriptor for invoking a target.\n *\n * Stores everything needed to make the physical call — transport kind,\n * artifact address, and optional arg-mapping expressions.\n * Serialize as plain JSON; no special wire encoding required.\n */\nexport interface ExecutionRef {\n /**\n * Optional human-readable label identifying the role of this invocation.\n * Not used for dispatch — purely for logging and diagnostics.\n * @example 'task-executor', 'chat-handler', 'board-live-cards'\n */\n meta?: string;\n\n /**\n * Transport and runtime kind — determines how whatToRun is invoked.\n * @see module JSDoc for the full list of supported values.\n */\n howToRun: 'local-node' | 'local-python' | 'local-process' | 'http:post' | 'http:get' | 'built-in';\n\n /**\n * Address of the artifact to run, in KindValueRef wire form (::kind::value).\n * @example '::fs-path::/dist/cli/source-cli-task-executor.js'\n * @example '::http-url::https://fn.example.com/api/executor'\n * @example '::built-in::source-cli-task-executor'\n */\n whatToRun: string;\n\n /**\n * Optional JSONata-based mapping from logical args → physical call shape.\n * When omitted, the adapter applies its default protocol for the howToRun kind.\n */\n argsMassaging?: ArgsMassaging;\n\n /**\n * Opaque executor-specific configuration.\n * For local transports, base64-encoded and passed as --extra <base64-json> in the argv.\n * For HTTP transports, available in argsMassaging.bodyTemplate as the `extra` binding.\n * Stored with the ref so it travels as a single unit with the invocation descriptor.\n */\n extra?: Record<string, unknown>;\n}\n\n// ============================================================================\n// ExecutionResult\n// ============================================================================\n\n/**\n * Standardized result envelope returned by any execution.\n *\n * Replaces the implicit \"file-exists = success, absent = failure\" protocol\n * with an explicit status field. The data ref points to the output blob.\n */\nexport interface ExecutionResult {\n /** Outcome of the execution. */\n status: 'success' | 'fail' | 'error';\n\n /**\n * KindValueRef wire form pointing to the output blob.\n * Present only when status === 'success'.\n */\n data?: string;\n\n /**\n * Human-readable error or failure message.\n * Present when status === 'fail' or 'error'.\n */\n error?: string;\n}\n\n// ============================================================================\n// ExecutionRef factory helpers\n// ============================================================================\n\n/**\n * Create an ExecutionRef from a script path string (e.g. from a --task-executor CLI arg).\n * File extension determines howToRun:\n * .js / .mjs → 'local-node'\n * .py → 'local-python'\n * other → 'local-process'\n *\n * @param scriptPath Absolute or relative path to the script / binary.\n * @param extra Optional opaque executor config stored on the ref.\n */\nexport function executionRefFromScriptPath(\n scriptPath: string,\n extra?: Record<string, unknown>,\n): ExecutionRef {\n let howToRun: ExecutionRef['howToRun'];\n if (/\\.m?js$/i.test(scriptPath)) howToRun = 'local-node';\n else if (/\\.py$/i.test(scriptPath)) howToRun = 'local-python';\n else howToRun = 'local-process';\n return {\n meta: 'task-executor',\n howToRun,\n whatToRun: `::fs-path::${scriptPath}`,\n ...(extra ? { extra } : {}),\n };\n}\n\n// ============================================================================\n// Serialization helpers\n// ============================================================================\n\n/**\n * Serialize an ExecutionRef to a JSON string for storage.\n * Plain JSON.stringify — no special encoding.\n */\nexport function serializeExecutionRef(ref: ExecutionRef): string {\n return JSON.stringify(ref);\n}\n\n/**\n * Parse a JSON string back into an ExecutionRef.\n * Throws if the string is not valid JSON or is missing required fields.\n */\nexport function parseExecutionRef(s: string): ExecutionRef {\n let parsed: unknown;\n try {\n parsed = JSON.parse(s);\n } catch {\n throw new Error(`parseExecutionRef: invalid JSON — ${s}`);\n }\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n typeof (parsed as Record<string, unknown>).howToRun !== 'string' ||\n typeof (parsed as Record<string, unknown>).whatToRun !== 'string'\n ) {\n throw new Error(`parseExecutionRef: missing required fields howToRun/whatToRun — ${s}`);\n }\n return parsed as ExecutionRef;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli/common/storage-interface.ts","../src/cli/common/execution-interface.ts"],"names":["REF_PREFIX","toBase64Url","raw","utf8","buf","base64","binary","byte","serializeRef","ref","executionRefFromScriptPath","scriptPath","extra","howToRun","serializeExecutionRef","parseExecutionRef","s","parsed"],"mappings":"aAqFA,IAAMA,EAAa,MAAA,CAEnB,SAASC,EAAYC,CAAAA,CAAqB,CACxC,IAAMC,CAAAA,CAAO,IAAI,aAAY,CAAE,MAAA,CAAOD,CAAG,CAAA,CACnCE,CAAAA,CAAO,WAA0F,MAAA,CACnGC,CAAAA,CACJ,GAAID,CAAAA,CACFC,CAAAA,CAASD,EAAI,IAAA,CAAKD,CAAI,EAAE,QAAA,CAAS,QAAQ,UAChC,OAAO,IAAA,EAAS,WAAY,CACrC,IAAIG,EAAS,EAAA,CACb,IAAA,IAAWC,KAAQJ,CAAAA,CAAMG,CAAAA,EAAU,OAAO,YAAA,CAAaC,CAAI,EAC3DF,CAAAA,CAAS,IAAA,CAAKC,CAAM,EACtB,MACE,MAAM,IAAI,MAAM,6CAA6C,CAAA,CAE/D,OAAOD,CAAAA,CAAO,OAAA,CAAQ,MAAO,GAAG,CAAA,CAAE,QAAQ,KAAA,CAAO,GAAG,EAAE,OAAA,CAAQ,MAAA,CAAQ,EAAE,CAC1E,CAiBO,SAASG,CAAAA,CAAaC,CAAAA,CAA2B,CACtD,OAAO,CAAA,EAAGT,CAAU,CAAA,EAAGC,CAAAA,CAAY,KAAK,SAAA,CAAUQ,CAAG,CAAC,CAAC,CAAA,CACzD,CCuKO,SAASC,CAAAA,CACdC,EACAC,CAAAA,CACc,CACd,IAAIC,CAAAA,CACJ,OAAI,UAAA,CAAW,IAAA,CAAKF,CAAU,CAAA,CAAGE,CAAAA,CAAW,aACnC,QAAA,CAAS,IAAA,CAAKF,CAAU,CAAA,CAAGE,CAAAA,CAAW,eAC1CA,CAAAA,CAAW,eAAA,CACT,CACL,IAAA,CAAM,eAAA,CACN,SAAAA,CAAAA,CACA,SAAA,CAAWL,EAAa,CAAE,IAAA,CAAM,UAAW,KAAA,CAAOG,CAAW,CAAC,CAAA,CAC9D,GAAIC,EAAQ,CAAE,KAAA,CAAAA,CAAM,CAAA,CAAI,EAC1B,CACF,CAUO,SAASE,CAAAA,CAAsBL,CAAAA,CAA2B,CAC/D,OAAO,IAAA,CAAK,UAAUA,CAAG,CAC3B,CAMO,SAASM,CAAAA,CAAkBC,EAAyB,CACzD,IAAIC,EACJ,GAAI,CACFA,EAAS,IAAA,CAAK,KAAA,CAAMD,CAAC,EACvB,CAAA,KAAQ,CACN,MAAM,IAAI,MAAM,CAAA,uCAAA,EAAqCA,CAAC,EAAE,CAC1D,CACA,GACE,OAAOC,CAAAA,EAAW,UAClBA,CAAAA,GAAW,IAAA,EACX,OAAQA,CAAAA,CAAmC,QAAA,EAAa,UACxD,OAAQA,CAAAA,CAAmC,WAAc,QAAA,CAEzD,MAAM,IAAI,KAAA,CAAM,CAAA,qEAAA,EAAmED,CAAC,CAAA,CAAE,CAAA,CAExF,OAAOC,CACT","file":"execution-refs.cjs","sourcesContent":["/**\n * storage-interface.ts\n *\n * Three minimal storage primitives that together cover all persistence needs\n * of the board-live-cards system. Any backend (Node fs, CosmosDB, Azure Blob,\n * browser localStorage, in-memory test double) implements these three interfaces.\n *\n * The pure-logic stores in board-live-cards-all-stores.ts depend only on these\n * interfaces — never on Node built-ins.\n *\n * Blob — raw string content at a logical, backend-neutral key\n * Journal — append-only log with cursor-based reads\n * KV — key-value store with list/delete\n *\n * Mapping to existing storage adapters:\n *\n * CardStorageAdapter\n * inventory (cardId → { blobRef, checksum, fileMetadata? }) → KV\n * card JSON files → Blob\n * source output files → Blob\n *\n * JournalStorageAdapter → Journal (board-journal.jsonl)\n *\n * ExecutionRequestStore → KV (keyed by journalId, via createFsKvStorage)\n *\n * StateSnapshotStorageAdapter\n * board-graph.json (packed single JSON, written atomically) → Blob\n * per-card sidecars (cards/<id>/runtime, fetched-sources-manifest) → KV\n */\n\n// ============================================================================\n// Blob — raw content at an opaque key\n//\n// The key is backend-specific (file path, blob name, storage key).\n// Text helpers are always available. Binary helpers are optional so existing\n// backends can adopt incrementally.\n// ============================================================================\n\nexport interface BlobStat {\n key: string;\n size: number;\n updatedAt?: string;\n contentType?: string;\n}\n\nexport interface BlobStorage {\n /** Returns raw content string, or null if the blob does not exist. */\n read(key: string): string | null;\n\n /** Write content at key. Implementations should be atomic (write-rename). */\n write(key: string, content: string): void;\n\n /** Returns true if a blob exists at key. */\n exists(key: string): boolean;\n\n /** Delete the blob at key. No-op if it does not exist. */\n remove(key: string): void;\n\n /** Optional binary read for file-like artifacts. */\n readBytes?(key: string): Uint8Array | null;\n\n /** Optional binary write for file-like artifacts. */\n writeBytes?(key: string, content: Uint8Array): void;\n\n /** Optional key listing by prefix. */\n listKeys?(prefix?: string): string[];\n\n /** Optional metadata lookup. */\n stat?(key: string): BlobStat | null;\n}\n\n// ============================================================================\n// KindValueRef — backend-neutral typed reference\n//\n// A ref describes WHERE content lives without carrying the bytes.\n// Serialized on the CLI wire as: b64:<base64url({\"kind\":\"...\",\"value\":\"...\"})>\n// kind = 'fs-path': value is an absolute file path\n// Additional kinds (e.g. 'cosmos') are added in public-storage-adapter.ts as new backends are supported.\n// ============================================================================\n\nexport interface KindValueRef {\n readonly kind: string;\n readonly value: string;\n}\n\nconst REF_PREFIX = 'b64:';\n\nfunction toBase64Url(raw: string): string {\n const utf8 = new TextEncoder().encode(raw);\n const buf = (globalThis as { Buffer?: { from(data: Uint8Array): { toString(enc: string): string } } }).Buffer;\n let base64: string;\n if (buf) {\n base64 = buf.from(utf8).toString('base64');\n } else if (typeof btoa === 'function') {\n let binary = '';\n for (const byte of utf8) binary += String.fromCharCode(byte);\n base64 = btoa(binary);\n } else {\n throw new Error('No base64 encoder available in this runtime');\n }\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/g, '');\n}\n\nfunction fromBase64Url(input: string): string {\n const base64 = input.replace(/-/g, '+').replace(/_/g, '/')\n + '='.repeat((4 - (input.length % 4)) % 4);\n const buf = (globalThis as { Buffer?: { from(data: string, enc: string): { toString(enc: string): string } } }).Buffer;\n if (buf) return buf.from(base64, 'base64').toString('utf8');\n if (typeof atob === 'function') {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder().decode(bytes);\n }\n throw new Error('No base64 decoder available in this runtime');\n}\n\n/** Serialize a KindValueRef to the wire format: b64:<base64url(json)> */\nexport function serializeRef(ref: KindValueRef): string {\n return `${REF_PREFIX}${toBase64Url(JSON.stringify(ref))}`;\n}\n\n/** Parse a wire-format ref string (b64:<base64url(json)>) into a KindValueRef. */\nexport function parseRef(s: string): KindValueRef {\n if (!s.startsWith(REF_PREFIX)) throw new Error(`Invalid ref format (expected ${REF_PREFIX}<base64url(json)>): ${s}`);\n let parsed: unknown;\n try {\n parsed = JSON.parse(fromBase64Url(s.slice(REF_PREFIX.length)));\n } catch {\n throw new Error(`Invalid ref format (malformed base64url/json): ${s}`);\n }\n if (!parsed || typeof parsed !== 'object') {\n throw new Error(`Invalid ref format (expected object payload): ${s}`);\n }\n const candidate = parsed as { kind?: unknown; value?: unknown };\n if (typeof candidate.kind !== 'string' || typeof candidate.value !== 'string') {\n throw new Error(`Invalid ref format (payload must contain string kind/value): ${s}`);\n }\n return { kind: candidate.kind, value: candidate.value };\n}\n\n// ============================================================================\n// Journal — append-only log, cursor-based reads\n//\n// Each entry has a string id (UUID or monotonic token) and an opaque payload.\n// Cursors are entry ids — readAfter returns entries strictly after that id.\n// A null/empty cursor means \"read from the beginning\".\n// ============================================================================\n\nexport interface JournalEntry {\n id: string;\n payload: unknown;\n}\n\nexport interface JournalReadResult {\n entries: JournalEntry[];\n /** The id of the last entry returned, suitable for use as the next cursor. */\n newCursor: string | null;\n}\n\nexport interface JournalStorage {\n /** Append an entry. The storage layer assigns the id. */\n append(payload: unknown): JournalEntry;\n\n /** Read ALL entries (for index rebuilds, full replay). */\n readAll(): JournalEntry[];\n\n /**\n * Read entries appended after the given cursor id.\n * If cursor is null/empty, returns all entries from the beginning.\n */\n readAfter(cursor: string | null): JournalReadResult;\n}\n\n// ============================================================================\n// KV — key-value store with list and delete\n//\n// Values are opaque unknown — callers own serialisation.\n// Keys are scoped by the adapter factory (e.g. a boardDir prefix is closed\n// over in the adapter, not passed per-call).\n// ============================================================================\n\nexport interface KVStorage {\n /** Returns the stored value, or null if the key does not exist. */\n read(key: string): unknown | null;\n\n /** Write value at key. Overwrites any existing value. */\n write(key: string, value: unknown): void;\n\n /** Delete the key. No-op if it does not exist. */\n delete(key: string): void;\n\n /**\n * List all keys, optionally filtered to those starting with prefix.\n * Order is implementation-defined.\n */\n listKeys(prefix?: string): string[];\n}\n\n// ============================================================================\n// JSONStorage — KV store with JSON-aware merge operations\n//\n// Backed by KVStorage under the hood. Adds deepMerge and shallowMerge so\n// callers never need to read-modify-write manually for partial updates.\n// ============================================================================\n\nexport interface JSONStorage {\n /** Returns the stored JSON value, or null if the key does not exist. */\n read(key: string): unknown | null;\n\n /**\n * Read a nested value inside the stored object using a dot-notation path.\n * e.g. get('myKey', 'a.b.c') returns the value at { a: { b: { c: ... } } }.\n * Returns null if the key does not exist or the path cannot be traversed.\n */\n get(key: string, jsonPath: string): unknown | null;\n\n /** Write value at key. Overwrites any existing value. */\n write(key: string, value: unknown): void;\n\n /** Delete the key. No-op if it does not exist. */\n delete(key: string): void;\n\n /** List all keys, optionally filtered by prefix. */\n listKeys(prefix?: string): string[];\n\n /**\n * Shallow-merge patch into the existing object at key.\n * Equivalent to: write(key, { ...read(key), ...patch })\n * Creates the key if it does not exist.\n */\n shallowMerge(key: string, patch: Record<string, unknown>): void;\n\n /**\n * Deep-merge patch into the existing object at key.\n * Recursively merges nested plain objects; arrays and primitives are replaced.\n * Creates the key if it does not exist.\n */\n deepMerge(key: string, patch: Record<string, unknown>): void;\n\n /**\n * Set a nested value inside the stored object using a dot-notation path.\n * e.g. patch('myKey', 'a.b.c', 42) sets { a: { b: { c: 42 } } } into the stored object.\n * Intermediate objects are created if absent. Arrays are not traversed — use integer\n * segments to index into them (e.g. 'items.0.name').\n * Creates the top-level key if it does not exist.\n */\n patch(key: string, jsonPath: string, value: unknown): void;\n}\n\n// ============================================================================\n// StorageProvider — aggregate of all three primitives\n//\n// Adapter factories receive a StorageProvider and close over any scope (e.g.\n// boardDir) themselves. This is the single injection point for swapping\n// backends (Node fs → CosmosDB, browser localStorage, test doubles, etc.).\n// ============================================================================\n\nexport interface StorageProvider {\n blob: BlobStorage;\n journal: JournalStorage;\n kv: KVStorage;\n}\n\n// ============================================================================\n// AtomicRelayLock — non-blocking try-acquire lock with relay-on-busy semantics\n//\n// This interface serves TWO tightly coupled purposes which are intentionally\n// unified into a single primitive:\n//\n// 1. ATOMICITY — ensures that a read-mutate-save cycle is executed by at\n// most one actor at a time, preventing concurrent actors from racing on\n// stale state and writing conflicting snapshots.\n//\n// 2. RELAY SIGNAL — when tryAcquire() returns null, the caller knows the\n// cycle is already in progress. Because the holder always reads fresh\n// state upon entry, it will pick up every change appended by the skipping\n// caller before the lock was attempted. The caller can therefore safely\n// exit — its work will be completed by the holder. This is the\n// \"relay baton\" pattern: the lock being held IS the in-progress signal.\n//\n// These two purposes are not an accidental overload — they are the same\n// invariant expressed at different scopes. Any backend implementation\n// (FS lockfile, Cosmos document lease, Azure entity lock, in-memory flag)\n// that satisfies \"at most one holder at a time\" automatically satisfies both.\n//\n// Contract:\n// - tryAcquire() is non-blocking. It never waits.\n// - Returns a release function on success, or null if already held.\n// - The release function must be called exactly once (use try/finally).\n// - Behaviour after calling release() more than once is undefined.\n// ============================================================================\n\nexport interface AtomicRelayLock {\n /**\n * Attempt to acquire the lock without blocking.\n * Returns a `release` function if successful, or `null` if the lock is\n * already held by another actor (relay: that actor will complete the work).\n */\n tryAcquire(): (() => void) | null;\n}\n\n/**\n * Execute `work` under an `AtomicRelayLock`.\n *\n * - If the lock is busy, returns false immediately (relay: the holder will\n * complete the work on behalf of this caller).\n * - If acquired, runs `work` exclusively, releases the lock, then calls\n * `continuation` if provided — allowing the caller to schedule the next\n * cycle (e.g. spawn a detached process) after the lock is free.\n * - Returns true if work ran.\n */\nexport async function withRelayLock(\n lock: AtomicRelayLock,\n work: () => Promise<void>,\n continuation?: () => void,\n): Promise<boolean> {\n const release = lock.tryAcquire();\n if (!release) return false; // relay: holder is already doing the work\n try {\n await work();\n } finally {\n release(); // release before continuation so it can immediately re-acquire\n }\n continuation?.();\n return true;\n}\n","/**\n * execution-interface.ts\n *\n * Pure module — no Node/platform imports. Safe for any runtime.\n *\n * Defines the portable descriptor types for invoking any executable target,\n * regardless of transport (local process, HTTP endpoint, cloud function, etc.).\n *\n * Parallel to storage-interface.ts (which describes WHERE data lives), this\n * module describes HOW to invoke a piece of logic.\n *\n * ────────────────────────────────────────────────────────────────────────────\n * CORE CONCEPTS\n * ────────────────────────────────────────────────────────────────────────────\n *\n * ExecutionRef — self-contained, serializable JSON descriptor for one invocation target.\n * • howToRun — transport / runtime kind (discriminator)\n * • whatToRun — address of the artifact (KindValueRef wire form: b64:<base64url(json)>)\n * • argsMassaging — optional JSONata expressions that map logical args → physical call shape\n * • meta — optional human-readable label (e.g. 'task-executor', 'chat-handler')\n *\n * ExecutionResult — standardized envelope returned by any invocation.\n * • status: 'success' | 'fail' | 'error'\n * • data — KindValueRef wire form pointing to output blob (on success)\n * • error — human-readable message (on fail/error)\n *\n * ────────────────────────────────────────────────────────────────────────────\n * howToRun VALUES\n * ────────────────────────────────────────────────────────────────────────────\n *\n * 'local-node' node <whatToRun> [argv...]\n * 'local-python' python <whatToRun> [argv...]\n * 'local-process' execute <whatToRun> directly (shebang / pre-resolved binary)\n * 'http:post' HTTP POST to <whatToRun>\n * 'http:get' HTTP GET to <whatToRun>\n * 'built-in' resolved by the adapter to a well-known internal implementation\n *\n * ────────────────────────────────────────────────────────────────────────────\n * argsMassaging\n * ────────────────────────────────────────────────────────────────────────────\n *\n * Each field is a JSONata expression evaluated against the caller's logical args object.\n * If argsMassaging is omitted, the adapter uses its default mapping for the howToRun kind.\n *\n * cmdTemplate — array of JSONata exprs, each producing one argv string (local transports)\n * urlTemplate — JSONata expr producing the final URL string (http transports)\n * bodyTemplate — JSONata expr producing the request body object (http transports)\n *\n * ────────────────────────────────────────────────────────────────────────────\n * SERIALIZATION\n * ────────────────────────────────────────────────────────────────────────────\n *\n * ExecutionRef is a plain JSON object — store it as-is on disk, in Cosmos, or any DB.\n * No special encoding needed. parseExecutionRef / serializeExecutionRef are thin\n * JSON wrappers provided for symmetry with storage-interface.\n *\n * ────────────────────────────────────────────────────────────────────────────\n * USAGE EXAMPLES\n * ────────────────────────────────────────────────────────────────────────────\n *\n * // Built-in source-cli task executor (resolved by adapter from cliDir):\n * const builtIn: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'built-in',\n * whatToRun: 'b64:<base64url({\"kind\":\"built-in\",\"value\":\"source-cli-task-executor\"})>',\n * };\n *\n * // External local-node task executor with default protocol args:\n * const local: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'local-node',\n * whatToRun: 'b64:<base64url({\"kind\":\"fs-path\",\"value\":\"/path/to/my-executor.js\"})>',\n * };\n *\n * // Azure Function task executor with custom arg mapping:\n * const azureFn: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'http:post',\n * whatToRun: 'b64:<base64url({\"kind\":\"http-url\",\"value\":\"https://myfn.azurewebsites.net/api/task-executor\"})>',\n * argsMassaging: {\n * urlTemplate: \"whatToRun & '?op=' & subcommand\",\n * bodyTemplate: \"{ 'inRef': inRef, 'outRef': outRef, 'token': token }\",\n * },\n * };\n *\n * // Chat handler over HTTP with a different logical args shape:\n * const chatHandler: ExecutionRef = {\n * meta: 'chat-handler',\n * howToRun: 'http:post',\n * whatToRun: 'b64:<base64url({\"kind\":\"http-url\",\"value\":\"https://myfn.azurewebsites.net/api/chat\"})>',\n * argsMassaging: {\n * bodyTemplate: \"{ 'message': message, 'context': context, 'sessionId': sessionId }\",\n * },\n * };\n */\n\n// ============================================================================\n// OutputTransforms\n// ============================================================================\n\nimport { serializeRef } from './storage-interface.js';\n\n/**\n * Optional JSONata-based transforms applied to the raw invoke result.\n * Context for all expressions: `{ output: { result, data, error? } }`.\n * All fields are optional.\n */\nexport interface OutputTransforms {\n /**\n * JSONata expression that produces the transition name string.\n * @example \"output.code = 200 ? 'success' : 'failure'\"\n */\n resultExpr?: string;\n\n /**\n * JSONata expression that produces the data object.\n * @example \"{ 'value': output.body.value }\"\n */\n dataTemplate?: string;\n\n /**\n * JSONata expression that produces the error string, or $undefined() to clear it.\n * @example \"output.code != 200 ? output.error_message : $undefined()\"\n */\n errorExpr?: string;\n}\n\n// ============================================================================\n// ArgsMassaging\n// ============================================================================\n\n/**\n * Optional JSONata-based mapping from logical args → physical invocation shape.\n *\n * Each field is a JSONata expression string evaluated against the caller's\n * logical args object (e.g. `{ inRef, outRef, errRef }` for a task-executor).\n *\n * If argsMassaging is omitted entirely, the execution adapter uses its default\n * mapping for the given howToRun kind.\n */\nexport interface ArgsMassaging {\n /**\n * For local transports ('local-node', 'local-python', 'local-process').\n * Array of JSONata expressions — each evaluates to one argv string.\n * The resolved strings are appended after the base command.\n *\n * @example\n * // Standard task-executor protocol:\n * cmdTemplate: [\n * \"'run-source-fetch'\",\n * \"'--in-ref'\", \"inRef\",\n * \"'--out-ref'\", \"outRef\",\n * \"'--err-ref'\", \"errRef\",\n * ]\n */\n cmdTemplate?: string[];\n\n /**\n * For http transports ('http:post', 'http:get').\n * JSONata expression that produces the final URL string.\n * The input context includes 'whatToRun' (the base URL from the ref)\n * plus all logical args.\n *\n * @example\n * urlTemplate: \"whatToRun & '?op=' & subcommand\"\n */\n urlTemplate?: string;\n\n /**\n * For http transports.\n * JSONata expression that produces the request body object.\n * Evaluated against the logical args object.\n *\n * @example\n * bodyTemplate: \"{ 'inRef': inRef, 'outRef': outRef, 'token': token }\"\n */\n bodyTemplate?: string;\n}\n\n// ============================================================================\n// ExecutionRef\n// ============================================================================\n\n/**\n * Self-contained, serializable descriptor for invoking a target.\n *\n * Stores everything needed to make the physical call — transport kind,\n * artifact address, and optional arg-mapping expressions.\n * Serialize as plain JSON; no special wire encoding required.\n */\nexport interface ExecutionRef {\n /**\n * Optional human-readable label identifying the role of this invocation.\n * Not used for dispatch — purely for logging and diagnostics.\n * @example 'task-executor', 'chat-handler', 'board-live-cards'\n */\n meta?: string;\n\n /**\n * Transport and runtime kind — determines how whatToRun is invoked.\n * @see module JSDoc for the full list of supported values.\n */\n howToRun: 'local-node' | 'local-python' | 'local-process' | 'http:post' | 'http:get' | 'built-in' | 'in-browser';\n\n /**\n * Address of the artifact to run. Two valid forms:\n * - string: must be KindValueRef wire form `b64:<base64url(json)>` (programmatically generated via serializeRef)\n * - object: `{ kind: string; value: string }` plain object (human-authored flow files — normalized by the handler factory)\n * @example 'b64:<base64url({\"kind\":\"fs-path\",\"value\":\"/dist/cli/source-cli-task-executor.js\"})>'\n * @example { kind: 'http-url', value: '/api/workiq/ask' }\n * @example { kind: 'fs-path', value: './my-handler.js' }\n */\n whatToRun: string | { kind: string; value: string };\n\n /**\n * Optional JSONata-based mapping from logical args → physical call shape.\n * When omitted, the adapter applies its default protocol for the howToRun kind.\n */\n argsMassaging?: ArgsMassaging;\n\n /**\n * Optional JSONata-based transforms applied to the raw invoke result\n * before it reaches the step-machine engine.\n *\n * Context for all expressions: `{ output: { result, data, error? } }`\n * where `output` is the raw { result, data, error? } returned by invokeRefSync.\n *\n * All fields are optional — only defined ones override the raw value.\n *\n * @example\n * outputTransforms:\n * resultExpr: \"output.code = 200 ? 'success' : 'failure'\"\n * dataTemplate: \"{ 'value': output.body.value }\"\n * errorExpr: \"output.code != 200 ? output.error_message : $undefined()\"\n */\n outputTransforms?: OutputTransforms;\n\n /**\n * Opaque executor-specific configuration.\n * For local transports, base64-encoded and passed as --extra <base64-json> in the argv.\n * For HTTP transports, available in argsMassaging.bodyTemplate as the `extra` binding.\n * Stored with the ref so it travels as a single unit with the invocation descriptor.\n */\n extra?: Record<string, unknown>;\n}\n\n// ============================================================================\n// ExecutionResult\n// ============================================================================\n\n/**\n * Standardized result envelope returned by any execution.\n *\n * Replaces the implicit \"file-exists = success, absent = failure\" protocol\n * with an explicit status field. The data ref points to the output blob.\n */\nexport interface ExecutionResult {\n /** Outcome of the execution. */\n status: 'success' | 'fail' | 'error';\n\n /**\n * KindValueRef wire form pointing to the output blob.\n * Present only when status === 'success'.\n */\n data?: string;\n\n /**\n * Human-readable error or failure message.\n * Present when status === 'fail' or 'error'.\n */\n error?: string;\n}\n\n// ============================================================================\n// ExecutionRef factory helpers\n// ============================================================================\n\n/**\n * Create an ExecutionRef from a script path string (e.g. from a --task-executor CLI arg).\n * File extension determines howToRun:\n * .js / .mjs → 'local-node'\n * .py → 'local-python'\n * other → 'local-process'\n *\n * @param scriptPath Absolute or relative path to the script / binary.\n * @param extra Optional opaque executor config stored on the ref.\n */\nexport function executionRefFromScriptPath(\n scriptPath: string,\n extra?: Record<string, unknown>,\n): ExecutionRef {\n let howToRun: ExecutionRef['howToRun'];\n if (/\\.m?js$/i.test(scriptPath)) howToRun = 'local-node';\n else if (/\\.py$/i.test(scriptPath)) howToRun = 'local-python';\n else howToRun = 'local-process';\n return {\n meta: 'task-executor',\n howToRun,\n whatToRun: serializeRef({ kind: 'fs-path', value: scriptPath }),\n ...(extra ? { extra } : {}),\n };\n}\n\n// ============================================================================\n// Serialization helpers\n// ============================================================================\n\n/**\n * Serialize an ExecutionRef to a JSON string for storage.\n * Plain JSON.stringify — no special encoding.\n */\nexport function serializeExecutionRef(ref: ExecutionRef): string {\n return JSON.stringify(ref);\n}\n\n/**\n * Parse a JSON string back into an ExecutionRef.\n * Throws if the string is not valid JSON or is missing required fields.\n */\nexport function parseExecutionRef(s: string): ExecutionRef {\n let parsed: unknown;\n try {\n parsed = JSON.parse(s);\n } catch {\n throw new Error(`parseExecutionRef: invalid JSON — ${s}`);\n }\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n typeof (parsed as Record<string, unknown>).howToRun !== 'string' ||\n typeof (parsed as Record<string, unknown>).whatToRun !== 'string'\n ) {\n throw new Error(`parseExecutionRef: missing required fields howToRun/whatToRun — ${s}`);\n }\n return parsed as ExecutionRef;\n}\n"]}
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
*
|
|
16
16
|
* ExecutionRef — self-contained, serializable JSON descriptor for one invocation target.
|
|
17
17
|
* • howToRun — transport / runtime kind (discriminator)
|
|
18
|
-
* • whatToRun — address of the artifact (KindValueRef wire form:
|
|
18
|
+
* • whatToRun — address of the artifact (KindValueRef wire form: b64:<base64url(json)>)
|
|
19
19
|
* • argsMassaging — optional JSONata expressions that map logical args → physical call shape
|
|
20
20
|
* • meta — optional human-readable label (e.g. 'task-executor', 'chat-handler')
|
|
21
21
|
*
|
|
@@ -62,21 +62,21 @@
|
|
|
62
62
|
* const builtIn: ExecutionRef = {
|
|
63
63
|
* meta: 'task-executor',
|
|
64
64
|
* howToRun: 'built-in',
|
|
65
|
-
* whatToRun: '
|
|
65
|
+
* whatToRun: 'b64:<base64url({"kind":"built-in","value":"source-cli-task-executor"})>',
|
|
66
66
|
* };
|
|
67
67
|
*
|
|
68
68
|
* // External local-node task executor with default protocol args:
|
|
69
69
|
* const local: ExecutionRef = {
|
|
70
70
|
* meta: 'task-executor',
|
|
71
71
|
* howToRun: 'local-node',
|
|
72
|
-
* whatToRun: '
|
|
72
|
+
* whatToRun: 'b64:<base64url({"kind":"fs-path","value":"/path/to/my-executor.js"})>',
|
|
73
73
|
* };
|
|
74
74
|
*
|
|
75
75
|
* // Azure Function task executor with custom arg mapping:
|
|
76
76
|
* const azureFn: ExecutionRef = {
|
|
77
77
|
* meta: 'task-executor',
|
|
78
78
|
* howToRun: 'http:post',
|
|
79
|
-
* whatToRun: '
|
|
79
|
+
* whatToRun: 'b64:<base64url({"kind":"http-url","value":"https://myfn.azurewebsites.net/api/task-executor"})>',
|
|
80
80
|
* argsMassaging: {
|
|
81
81
|
* urlTemplate: "whatToRun & '?op=' & subcommand",
|
|
82
82
|
* bodyTemplate: "{ 'inRef': inRef, 'outRef': outRef, 'token': token }",
|
|
@@ -87,12 +87,34 @@
|
|
|
87
87
|
* const chatHandler: ExecutionRef = {
|
|
88
88
|
* meta: 'chat-handler',
|
|
89
89
|
* howToRun: 'http:post',
|
|
90
|
-
* whatToRun: '
|
|
90
|
+
* whatToRun: 'b64:<base64url({"kind":"http-url","value":"https://myfn.azurewebsites.net/api/chat"})>',
|
|
91
91
|
* argsMassaging: {
|
|
92
92
|
* bodyTemplate: "{ 'message': message, 'context': context, 'sessionId': sessionId }",
|
|
93
93
|
* },
|
|
94
94
|
* };
|
|
95
95
|
*/
|
|
96
|
+
/**
|
|
97
|
+
* Optional JSONata-based transforms applied to the raw invoke result.
|
|
98
|
+
* Context for all expressions: `{ output: { result, data, error? } }`.
|
|
99
|
+
* All fields are optional.
|
|
100
|
+
*/
|
|
101
|
+
interface OutputTransforms {
|
|
102
|
+
/**
|
|
103
|
+
* JSONata expression that produces the transition name string.
|
|
104
|
+
* @example "output.code = 200 ? 'success' : 'failure'"
|
|
105
|
+
*/
|
|
106
|
+
resultExpr?: string;
|
|
107
|
+
/**
|
|
108
|
+
* JSONata expression that produces the data object.
|
|
109
|
+
* @example "{ 'value': output.body.value }"
|
|
110
|
+
*/
|
|
111
|
+
dataTemplate?: string;
|
|
112
|
+
/**
|
|
113
|
+
* JSONata expression that produces the error string, or $undefined() to clear it.
|
|
114
|
+
* @example "output.code != 200 ? output.error_message : $undefined()"
|
|
115
|
+
*/
|
|
116
|
+
errorExpr?: string;
|
|
117
|
+
}
|
|
96
118
|
/**
|
|
97
119
|
* Optional JSONata-based mapping from logical args → physical invocation shape.
|
|
98
120
|
*
|
|
@@ -156,19 +178,40 @@ interface ExecutionRef {
|
|
|
156
178
|
* Transport and runtime kind — determines how whatToRun is invoked.
|
|
157
179
|
* @see module JSDoc for the full list of supported values.
|
|
158
180
|
*/
|
|
159
|
-
howToRun: 'local-node' | 'local-python' | 'local-process' | 'http:post' | 'http:get' | 'built-in';
|
|
181
|
+
howToRun: 'local-node' | 'local-python' | 'local-process' | 'http:post' | 'http:get' | 'built-in' | 'in-browser';
|
|
160
182
|
/**
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
183
|
+
* Address of the artifact to run. Two valid forms:
|
|
184
|
+
* - string: must be KindValueRef wire form `b64:<base64url(json)>` (programmatically generated via serializeRef)
|
|
185
|
+
* - object: `{ kind: string; value: string }` plain object (human-authored flow files — normalized by the handler factory)
|
|
186
|
+
* @example 'b64:<base64url({"kind":"fs-path","value":"/dist/cli/source-cli-task-executor.js"})>'
|
|
187
|
+
* @example { kind: 'http-url', value: '/api/workiq/ask' }
|
|
188
|
+
* @example { kind: 'fs-path', value: './my-handler.js' }
|
|
165
189
|
*/
|
|
166
|
-
whatToRun: string
|
|
190
|
+
whatToRun: string | {
|
|
191
|
+
kind: string;
|
|
192
|
+
value: string;
|
|
193
|
+
};
|
|
167
194
|
/**
|
|
168
195
|
* Optional JSONata-based mapping from logical args → physical call shape.
|
|
169
196
|
* When omitted, the adapter applies its default protocol for the howToRun kind.
|
|
170
197
|
*/
|
|
171
198
|
argsMassaging?: ArgsMassaging;
|
|
199
|
+
/**
|
|
200
|
+
* Optional JSONata-based transforms applied to the raw invoke result
|
|
201
|
+
* before it reaches the step-machine engine.
|
|
202
|
+
*
|
|
203
|
+
* Context for all expressions: `{ output: { result, data, error? } }`
|
|
204
|
+
* where `output` is the raw { result, data, error? } returned by invokeRefSync.
|
|
205
|
+
*
|
|
206
|
+
* All fields are optional — only defined ones override the raw value.
|
|
207
|
+
*
|
|
208
|
+
* @example
|
|
209
|
+
* outputTransforms:
|
|
210
|
+
* resultExpr: "output.code = 200 ? 'success' : 'failure'"
|
|
211
|
+
* dataTemplate: "{ 'value': output.body.value }"
|
|
212
|
+
* errorExpr: "output.code != 200 ? output.error_message : $undefined()"
|
|
213
|
+
*/
|
|
214
|
+
outputTransforms?: OutputTransforms;
|
|
172
215
|
/**
|
|
173
216
|
* Opaque executor-specific configuration.
|
|
174
217
|
* For local transports, base64-encoded and passed as --extra <base64-json> in the argv.
|
|
@@ -219,4 +262,4 @@ declare function serializeExecutionRef(ref: ExecutionRef): string;
|
|
|
219
262
|
*/
|
|
220
263
|
declare function parseExecutionRef(s: string): ExecutionRef;
|
|
221
264
|
|
|
222
|
-
export { type ArgsMassaging, type ExecutionRef, type ExecutionResult, executionRefFromScriptPath, parseExecutionRef, serializeExecutionRef };
|
|
265
|
+
export { type ArgsMassaging, type ExecutionRef, type ExecutionResult, type OutputTransforms, executionRefFromScriptPath, parseExecutionRef, serializeExecutionRef };
|
package/dist/execution-refs.d.ts
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
*
|
|
16
16
|
* ExecutionRef — self-contained, serializable JSON descriptor for one invocation target.
|
|
17
17
|
* • howToRun — transport / runtime kind (discriminator)
|
|
18
|
-
* • whatToRun — address of the artifact (KindValueRef wire form:
|
|
18
|
+
* • whatToRun — address of the artifact (KindValueRef wire form: b64:<base64url(json)>)
|
|
19
19
|
* • argsMassaging — optional JSONata expressions that map logical args → physical call shape
|
|
20
20
|
* • meta — optional human-readable label (e.g. 'task-executor', 'chat-handler')
|
|
21
21
|
*
|
|
@@ -62,21 +62,21 @@
|
|
|
62
62
|
* const builtIn: ExecutionRef = {
|
|
63
63
|
* meta: 'task-executor',
|
|
64
64
|
* howToRun: 'built-in',
|
|
65
|
-
* whatToRun: '
|
|
65
|
+
* whatToRun: 'b64:<base64url({"kind":"built-in","value":"source-cli-task-executor"})>',
|
|
66
66
|
* };
|
|
67
67
|
*
|
|
68
68
|
* // External local-node task executor with default protocol args:
|
|
69
69
|
* const local: ExecutionRef = {
|
|
70
70
|
* meta: 'task-executor',
|
|
71
71
|
* howToRun: 'local-node',
|
|
72
|
-
* whatToRun: '
|
|
72
|
+
* whatToRun: 'b64:<base64url({"kind":"fs-path","value":"/path/to/my-executor.js"})>',
|
|
73
73
|
* };
|
|
74
74
|
*
|
|
75
75
|
* // Azure Function task executor with custom arg mapping:
|
|
76
76
|
* const azureFn: ExecutionRef = {
|
|
77
77
|
* meta: 'task-executor',
|
|
78
78
|
* howToRun: 'http:post',
|
|
79
|
-
* whatToRun: '
|
|
79
|
+
* whatToRun: 'b64:<base64url({"kind":"http-url","value":"https://myfn.azurewebsites.net/api/task-executor"})>',
|
|
80
80
|
* argsMassaging: {
|
|
81
81
|
* urlTemplate: "whatToRun & '?op=' & subcommand",
|
|
82
82
|
* bodyTemplate: "{ 'inRef': inRef, 'outRef': outRef, 'token': token }",
|
|
@@ -87,12 +87,34 @@
|
|
|
87
87
|
* const chatHandler: ExecutionRef = {
|
|
88
88
|
* meta: 'chat-handler',
|
|
89
89
|
* howToRun: 'http:post',
|
|
90
|
-
* whatToRun: '
|
|
90
|
+
* whatToRun: 'b64:<base64url({"kind":"http-url","value":"https://myfn.azurewebsites.net/api/chat"})>',
|
|
91
91
|
* argsMassaging: {
|
|
92
92
|
* bodyTemplate: "{ 'message': message, 'context': context, 'sessionId': sessionId }",
|
|
93
93
|
* },
|
|
94
94
|
* };
|
|
95
95
|
*/
|
|
96
|
+
/**
|
|
97
|
+
* Optional JSONata-based transforms applied to the raw invoke result.
|
|
98
|
+
* Context for all expressions: `{ output: { result, data, error? } }`.
|
|
99
|
+
* All fields are optional.
|
|
100
|
+
*/
|
|
101
|
+
interface OutputTransforms {
|
|
102
|
+
/**
|
|
103
|
+
* JSONata expression that produces the transition name string.
|
|
104
|
+
* @example "output.code = 200 ? 'success' : 'failure'"
|
|
105
|
+
*/
|
|
106
|
+
resultExpr?: string;
|
|
107
|
+
/**
|
|
108
|
+
* JSONata expression that produces the data object.
|
|
109
|
+
* @example "{ 'value': output.body.value }"
|
|
110
|
+
*/
|
|
111
|
+
dataTemplate?: string;
|
|
112
|
+
/**
|
|
113
|
+
* JSONata expression that produces the error string, or $undefined() to clear it.
|
|
114
|
+
* @example "output.code != 200 ? output.error_message : $undefined()"
|
|
115
|
+
*/
|
|
116
|
+
errorExpr?: string;
|
|
117
|
+
}
|
|
96
118
|
/**
|
|
97
119
|
* Optional JSONata-based mapping from logical args → physical invocation shape.
|
|
98
120
|
*
|
|
@@ -156,19 +178,40 @@ interface ExecutionRef {
|
|
|
156
178
|
* Transport and runtime kind — determines how whatToRun is invoked.
|
|
157
179
|
* @see module JSDoc for the full list of supported values.
|
|
158
180
|
*/
|
|
159
|
-
howToRun: 'local-node' | 'local-python' | 'local-process' | 'http:post' | 'http:get' | 'built-in';
|
|
181
|
+
howToRun: 'local-node' | 'local-python' | 'local-process' | 'http:post' | 'http:get' | 'built-in' | 'in-browser';
|
|
160
182
|
/**
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
183
|
+
* Address of the artifact to run. Two valid forms:
|
|
184
|
+
* - string: must be KindValueRef wire form `b64:<base64url(json)>` (programmatically generated via serializeRef)
|
|
185
|
+
* - object: `{ kind: string; value: string }` plain object (human-authored flow files — normalized by the handler factory)
|
|
186
|
+
* @example 'b64:<base64url({"kind":"fs-path","value":"/dist/cli/source-cli-task-executor.js"})>'
|
|
187
|
+
* @example { kind: 'http-url', value: '/api/workiq/ask' }
|
|
188
|
+
* @example { kind: 'fs-path', value: './my-handler.js' }
|
|
165
189
|
*/
|
|
166
|
-
whatToRun: string
|
|
190
|
+
whatToRun: string | {
|
|
191
|
+
kind: string;
|
|
192
|
+
value: string;
|
|
193
|
+
};
|
|
167
194
|
/**
|
|
168
195
|
* Optional JSONata-based mapping from logical args → physical call shape.
|
|
169
196
|
* When omitted, the adapter applies its default protocol for the howToRun kind.
|
|
170
197
|
*/
|
|
171
198
|
argsMassaging?: ArgsMassaging;
|
|
199
|
+
/**
|
|
200
|
+
* Optional JSONata-based transforms applied to the raw invoke result
|
|
201
|
+
* before it reaches the step-machine engine.
|
|
202
|
+
*
|
|
203
|
+
* Context for all expressions: `{ output: { result, data, error? } }`
|
|
204
|
+
* where `output` is the raw { result, data, error? } returned by invokeRefSync.
|
|
205
|
+
*
|
|
206
|
+
* All fields are optional — only defined ones override the raw value.
|
|
207
|
+
*
|
|
208
|
+
* @example
|
|
209
|
+
* outputTransforms:
|
|
210
|
+
* resultExpr: "output.code = 200 ? 'success' : 'failure'"
|
|
211
|
+
* dataTemplate: "{ 'value': output.body.value }"
|
|
212
|
+
* errorExpr: "output.code != 200 ? output.error_message : $undefined()"
|
|
213
|
+
*/
|
|
214
|
+
outputTransforms?: OutputTransforms;
|
|
172
215
|
/**
|
|
173
216
|
* Opaque executor-specific configuration.
|
|
174
217
|
* For local transports, base64-encoded and passed as --extra <base64-json> in the argv.
|
|
@@ -219,4 +262,4 @@ declare function serializeExecutionRef(ref: ExecutionRef): string;
|
|
|
219
262
|
*/
|
|
220
263
|
declare function parseExecutionRef(s: string): ExecutionRef;
|
|
221
264
|
|
|
222
|
-
export { type ArgsMassaging, type ExecutionRef, type ExecutionResult, executionRefFromScriptPath, parseExecutionRef, serializeExecutionRef };
|
|
265
|
+
export { type ArgsMassaging, type ExecutionRef, type ExecutionResult, type OutputTransforms, executionRefFromScriptPath, parseExecutionRef, serializeExecutionRef };
|
package/dist/execution-refs.js
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
function
|
|
1
|
+
var s="b64:";function l(e){let r=new TextEncoder().encode(e),t=globalThis.Buffer,n;if(t)n=t.from(r).toString("base64");else if(typeof btoa=="function"){let o="";for(let a of r)o+=String.fromCharCode(a);n=btoa(o);}else throw new Error("No base64 encoder available in this runtime");return n.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function i(e){return `${s}${l(JSON.stringify(e))}`}function c(e,r){let t;return /\.m?js$/i.test(e)?t="local-node":/\.py$/i.test(e)?t="local-python":t="local-process",{meta:"task-executor",howToRun:t,whatToRun:i({kind:"fs-path",value:e}),...r?{extra:r}:{}}}function f(e){return JSON.stringify(e)}function d(e){let r;try{r=JSON.parse(e);}catch{throw new Error(`parseExecutionRef: invalid JSON \u2014 ${e}`)}if(typeof r!="object"||r===null||typeof r.howToRun!="string"||typeof r.whatToRun!="string")throw new Error(`parseExecutionRef: missing required fields howToRun/whatToRun \u2014 ${e}`);return r}
|
|
2
|
+
export{c as executionRefFromScriptPath,d as parseExecutionRef,f as serializeExecutionRef};//# sourceMappingURL=execution-refs.js.map
|
|
2
3
|
//# sourceMappingURL=execution-refs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli/common/execution-interface.ts"],"names":["executionRefFromScriptPath","scriptPath","extra","howToRun","serializeExecutionRef","ref","parseExecutionRef","s","parsed"],"mappings":"AA6OO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CACc,CACd,IAAIC,CAAAA,CACJ,OAAI,WAAW,IAAA,CAAKF,CAAU,EAAGE,CAAAA,CAAW,YAAA,CACnC,SAAS,IAAA,CAAKF,CAAU,EAAGE,CAAAA,CAAW,cAAA,CAC1CA,EAAW,eAAA,CACT,CACL,KAAM,eAAA,CACN,QAAA,CAAAA,EACA,SAAA,CAAW,CAAA,WAAA,EAAcF,CAAU,CAAA,CAAA,CACnC,GAAIC,EAAQ,CAAE,KAAA,CAAAA,CAAM,CAAA,CAAI,EAC1B,CACF,CAUO,SAASE,CAAAA,CAAsBC,CAAAA,CAA2B,CAC/D,OAAO,IAAA,CAAK,SAAA,CAAUA,CAAG,CAC3B,CAMO,SAASC,CAAAA,CAAkBC,CAAAA,CAAyB,CACzD,IAAIC,CAAAA,CACJ,GAAI,CACFA,CAAAA,CAAS,KAAK,KAAA,CAAMD,CAAC,EACvB,CAAA,KAAQ,CACN,MAAM,IAAI,KAAA,CAAM,CAAA,uCAAA,EAAqCA,CAAC,CAAA,CAAE,CAC1D,CACA,GACE,OAAOC,GAAW,QAAA,EAClBA,CAAAA,GAAW,MACX,OAAQA,CAAAA,CAAmC,UAAa,QAAA,EACxD,OAAQA,EAAmC,SAAA,EAAc,QAAA,CAEzD,MAAM,IAAI,KAAA,CAAM,wEAAmED,CAAC,CAAA,CAAE,CAAA,CAExF,OAAOC,CACT","file":"execution-refs.js","sourcesContent":["/**\n * execution-interface.ts\n *\n * Pure module — no Node/platform imports. Safe for any runtime.\n *\n * Defines the portable descriptor types for invoking any executable target,\n * regardless of transport (local process, HTTP endpoint, cloud function, etc.).\n *\n * Parallel to storage-interface.ts (which describes WHERE data lives), this\n * module describes HOW to invoke a piece of logic.\n *\n * ────────────────────────────────────────────────────────────────────────────\n * CORE CONCEPTS\n * ────────────────────────────────────────────────────────────────────────────\n *\n * ExecutionRef — self-contained, serializable JSON descriptor for one invocation target.\n * • howToRun — transport / runtime kind (discriminator)\n * • whatToRun — address of the artifact (KindValueRef wire form: ::kind::value)\n * • argsMassaging — optional JSONata expressions that map logical args → physical call shape\n * • meta — optional human-readable label (e.g. 'task-executor', 'chat-handler')\n *\n * ExecutionResult — standardized envelope returned by any invocation.\n * • status: 'success' | 'fail' | 'error'\n * • data — KindValueRef wire form pointing to output blob (on success)\n * • error — human-readable message (on fail/error)\n *\n * ────────────────────────────────────────────────────────────────────────────\n * howToRun VALUES\n * ────────────────────────────────────────────────────────────────────────────\n *\n * 'local-node' node <whatToRun> [argv...]\n * 'local-python' python <whatToRun> [argv...]\n * 'local-process' execute <whatToRun> directly (shebang / pre-resolved binary)\n * 'http:post' HTTP POST to <whatToRun>\n * 'http:get' HTTP GET to <whatToRun>\n * 'built-in' resolved by the adapter to a well-known internal implementation\n *\n * ────────────────────────────────────────────────────────────────────────────\n * argsMassaging\n * ────────────────────────────────────────────────────────────────────────────\n *\n * Each field is a JSONata expression evaluated against the caller's logical args object.\n * If argsMassaging is omitted, the adapter uses its default mapping for the howToRun kind.\n *\n * cmdTemplate — array of JSONata exprs, each producing one argv string (local transports)\n * urlTemplate — JSONata expr producing the final URL string (http transports)\n * bodyTemplate — JSONata expr producing the request body object (http transports)\n *\n * ────────────────────────────────────────────────────────────────────────────\n * SERIALIZATION\n * ────────────────────────────────────────────────────────────────────────────\n *\n * ExecutionRef is a plain JSON object — store it as-is on disk, in Cosmos, or any DB.\n * No special encoding needed. parseExecutionRef / serializeExecutionRef are thin\n * JSON wrappers provided for symmetry with storage-interface.\n *\n * ────────────────────────────────────────────────────────────────────────────\n * USAGE EXAMPLES\n * ────────────────────────────────────────────────────────────────────────────\n *\n * // Built-in source-cli task executor (resolved by adapter from cliDir):\n * const builtIn: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'built-in',\n * whatToRun: '::built-in::source-cli-task-executor',\n * };\n *\n * // External local-node task executor with default protocol args:\n * const local: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'local-node',\n * whatToRun: '::fs-path::/path/to/my-executor.js',\n * };\n *\n * // Azure Function task executor with custom arg mapping:\n * const azureFn: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'http:post',\n * whatToRun: '::http-url::https://myfn.azurewebsites.net/api/task-executor',\n * argsMassaging: {\n * urlTemplate: \"whatToRun & '?op=' & subcommand\",\n * bodyTemplate: \"{ 'inRef': inRef, 'outRef': outRef, 'token': token }\",\n * },\n * };\n *\n * // Chat handler over HTTP with a different logical args shape:\n * const chatHandler: ExecutionRef = {\n * meta: 'chat-handler',\n * howToRun: 'http:post',\n * whatToRun: '::http-url::https://myfn.azurewebsites.net/api/chat',\n * argsMassaging: {\n * bodyTemplate: \"{ 'message': message, 'context': context, 'sessionId': sessionId }\",\n * },\n * };\n */\n\n// ============================================================================\n// ArgsMassaging\n// ============================================================================\n\n/**\n * Optional JSONata-based mapping from logical args → physical invocation shape.\n *\n * Each field is a JSONata expression string evaluated against the caller's\n * logical args object (e.g. `{ inRef, outRef, errRef }` for a task-executor).\n *\n * If argsMassaging is omitted entirely, the execution adapter uses its default\n * mapping for the given howToRun kind.\n */\nexport interface ArgsMassaging {\n /**\n * For local transports ('local-node', 'local-python', 'local-process').\n * Array of JSONata expressions — each evaluates to one argv string.\n * The resolved strings are appended after the base command.\n *\n * @example\n * // Standard task-executor protocol:\n * cmdTemplate: [\n * \"'run-source-fetch'\",\n * \"'--in-ref'\", \"inRef\",\n * \"'--out-ref'\", \"outRef\",\n * \"'--err-ref'\", \"errRef\",\n * ]\n */\n cmdTemplate?: string[];\n\n /**\n * For http transports ('http:post', 'http:get').\n * JSONata expression that produces the final URL string.\n * The input context includes 'whatToRun' (the base URL from the ref)\n * plus all logical args.\n *\n * @example\n * urlTemplate: \"whatToRun & '?op=' & subcommand\"\n */\n urlTemplate?: string;\n\n /**\n * For http transports.\n * JSONata expression that produces the request body object.\n * Evaluated against the logical args object.\n *\n * @example\n * bodyTemplate: \"{ 'inRef': inRef, 'outRef': outRef, 'token': token }\"\n */\n bodyTemplate?: string;\n}\n\n// ============================================================================\n// ExecutionRef\n// ============================================================================\n\n/**\n * Self-contained, serializable descriptor for invoking a target.\n *\n * Stores everything needed to make the physical call — transport kind,\n * artifact address, and optional arg-mapping expressions.\n * Serialize as plain JSON; no special wire encoding required.\n */\nexport interface ExecutionRef {\n /**\n * Optional human-readable label identifying the role of this invocation.\n * Not used for dispatch — purely for logging and diagnostics.\n * @example 'task-executor', 'chat-handler', 'board-live-cards'\n */\n meta?: string;\n\n /**\n * Transport and runtime kind — determines how whatToRun is invoked.\n * @see module JSDoc for the full list of supported values.\n */\n howToRun: 'local-node' | 'local-python' | 'local-process' | 'http:post' | 'http:get' | 'built-in';\n\n /**\n * Address of the artifact to run, in KindValueRef wire form (::kind::value).\n * @example '::fs-path::/dist/cli/source-cli-task-executor.js'\n * @example '::http-url::https://fn.example.com/api/executor'\n * @example '::built-in::source-cli-task-executor'\n */\n whatToRun: string;\n\n /**\n * Optional JSONata-based mapping from logical args → physical call shape.\n * When omitted, the adapter applies its default protocol for the howToRun kind.\n */\n argsMassaging?: ArgsMassaging;\n\n /**\n * Opaque executor-specific configuration.\n * For local transports, base64-encoded and passed as --extra <base64-json> in the argv.\n * For HTTP transports, available in argsMassaging.bodyTemplate as the `extra` binding.\n * Stored with the ref so it travels as a single unit with the invocation descriptor.\n */\n extra?: Record<string, unknown>;\n}\n\n// ============================================================================\n// ExecutionResult\n// ============================================================================\n\n/**\n * Standardized result envelope returned by any execution.\n *\n * Replaces the implicit \"file-exists = success, absent = failure\" protocol\n * with an explicit status field. The data ref points to the output blob.\n */\nexport interface ExecutionResult {\n /** Outcome of the execution. */\n status: 'success' | 'fail' | 'error';\n\n /**\n * KindValueRef wire form pointing to the output blob.\n * Present only when status === 'success'.\n */\n data?: string;\n\n /**\n * Human-readable error or failure message.\n * Present when status === 'fail' or 'error'.\n */\n error?: string;\n}\n\n// ============================================================================\n// ExecutionRef factory helpers\n// ============================================================================\n\n/**\n * Create an ExecutionRef from a script path string (e.g. from a --task-executor CLI arg).\n * File extension determines howToRun:\n * .js / .mjs → 'local-node'\n * .py → 'local-python'\n * other → 'local-process'\n *\n * @param scriptPath Absolute or relative path to the script / binary.\n * @param extra Optional opaque executor config stored on the ref.\n */\nexport function executionRefFromScriptPath(\n scriptPath: string,\n extra?: Record<string, unknown>,\n): ExecutionRef {\n let howToRun: ExecutionRef['howToRun'];\n if (/\\.m?js$/i.test(scriptPath)) howToRun = 'local-node';\n else if (/\\.py$/i.test(scriptPath)) howToRun = 'local-python';\n else howToRun = 'local-process';\n return {\n meta: 'task-executor',\n howToRun,\n whatToRun: `::fs-path::${scriptPath}`,\n ...(extra ? { extra } : {}),\n };\n}\n\n// ============================================================================\n// Serialization helpers\n// ============================================================================\n\n/**\n * Serialize an ExecutionRef to a JSON string for storage.\n * Plain JSON.stringify — no special encoding.\n */\nexport function serializeExecutionRef(ref: ExecutionRef): string {\n return JSON.stringify(ref);\n}\n\n/**\n * Parse a JSON string back into an ExecutionRef.\n * Throws if the string is not valid JSON or is missing required fields.\n */\nexport function parseExecutionRef(s: string): ExecutionRef {\n let parsed: unknown;\n try {\n parsed = JSON.parse(s);\n } catch {\n throw new Error(`parseExecutionRef: invalid JSON — ${s}`);\n }\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n typeof (parsed as Record<string, unknown>).howToRun !== 'string' ||\n typeof (parsed as Record<string, unknown>).whatToRun !== 'string'\n ) {\n throw new Error(`parseExecutionRef: missing required fields howToRun/whatToRun — ${s}`);\n }\n return parsed as ExecutionRef;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli/common/storage-interface.ts","../src/cli/common/execution-interface.ts"],"names":["REF_PREFIX","toBase64Url","raw","utf8","buf","base64","binary","byte","serializeRef","ref","executionRefFromScriptPath","scriptPath","extra","howToRun","serializeExecutionRef","parseExecutionRef","s","parsed"],"mappings":"AAqFA,IAAMA,EAAa,MAAA,CAEnB,SAASC,EAAYC,CAAAA,CAAqB,CACxC,IAAMC,CAAAA,CAAO,IAAI,aAAY,CAAE,MAAA,CAAOD,CAAG,CAAA,CACnCE,CAAAA,CAAO,WAA0F,MAAA,CACnGC,CAAAA,CACJ,GAAID,CAAAA,CACFC,CAAAA,CAASD,EAAI,IAAA,CAAKD,CAAI,EAAE,QAAA,CAAS,QAAQ,UAChC,OAAO,IAAA,EAAS,WAAY,CACrC,IAAIG,EAAS,EAAA,CACb,IAAA,IAAWC,KAAQJ,CAAAA,CAAMG,CAAAA,EAAU,OAAO,YAAA,CAAaC,CAAI,EAC3DF,CAAAA,CAAS,IAAA,CAAKC,CAAM,EACtB,MACE,MAAM,IAAI,MAAM,6CAA6C,CAAA,CAE/D,OAAOD,CAAAA,CAAO,OAAA,CAAQ,MAAO,GAAG,CAAA,CAAE,QAAQ,KAAA,CAAO,GAAG,EAAE,OAAA,CAAQ,MAAA,CAAQ,EAAE,CAC1E,CAiBO,SAASG,CAAAA,CAAaC,CAAAA,CAA2B,CACtD,OAAO,CAAA,EAAGT,CAAU,CAAA,EAAGC,CAAAA,CAAY,KAAK,SAAA,CAAUQ,CAAG,CAAC,CAAC,CAAA,CACzD,CCuKO,SAASC,CAAAA,CACdC,EACAC,CAAAA,CACc,CACd,IAAIC,CAAAA,CACJ,OAAI,UAAA,CAAW,IAAA,CAAKF,CAAU,CAAA,CAAGE,CAAAA,CAAW,aACnC,QAAA,CAAS,IAAA,CAAKF,CAAU,CAAA,CAAGE,CAAAA,CAAW,eAC1CA,CAAAA,CAAW,eAAA,CACT,CACL,IAAA,CAAM,eAAA,CACN,SAAAA,CAAAA,CACA,SAAA,CAAWL,EAAa,CAAE,IAAA,CAAM,UAAW,KAAA,CAAOG,CAAW,CAAC,CAAA,CAC9D,GAAIC,EAAQ,CAAE,KAAA,CAAAA,CAAM,CAAA,CAAI,EAC1B,CACF,CAUO,SAASE,CAAAA,CAAsBL,CAAAA,CAA2B,CAC/D,OAAO,IAAA,CAAK,UAAUA,CAAG,CAC3B,CAMO,SAASM,CAAAA,CAAkBC,EAAyB,CACzD,IAAIC,EACJ,GAAI,CACFA,EAAS,IAAA,CAAK,KAAA,CAAMD,CAAC,EACvB,CAAA,KAAQ,CACN,MAAM,IAAI,MAAM,CAAA,uCAAA,EAAqCA,CAAC,EAAE,CAC1D,CACA,GACE,OAAOC,CAAAA,EAAW,UAClBA,CAAAA,GAAW,IAAA,EACX,OAAQA,CAAAA,CAAmC,QAAA,EAAa,UACxD,OAAQA,CAAAA,CAAmC,WAAc,QAAA,CAEzD,MAAM,IAAI,KAAA,CAAM,CAAA,qEAAA,EAAmED,CAAC,CAAA,CAAE,CAAA,CAExF,OAAOC,CACT","file":"execution-refs.js","sourcesContent":["/**\n * storage-interface.ts\n *\n * Three minimal storage primitives that together cover all persistence needs\n * of the board-live-cards system. Any backend (Node fs, CosmosDB, Azure Blob,\n * browser localStorage, in-memory test double) implements these three interfaces.\n *\n * The pure-logic stores in board-live-cards-all-stores.ts depend only on these\n * interfaces — never on Node built-ins.\n *\n * Blob — raw string content at a logical, backend-neutral key\n * Journal — append-only log with cursor-based reads\n * KV — key-value store with list/delete\n *\n * Mapping to existing storage adapters:\n *\n * CardStorageAdapter\n * inventory (cardId → { blobRef, checksum, fileMetadata? }) → KV\n * card JSON files → Blob\n * source output files → Blob\n *\n * JournalStorageAdapter → Journal (board-journal.jsonl)\n *\n * ExecutionRequestStore → KV (keyed by journalId, via createFsKvStorage)\n *\n * StateSnapshotStorageAdapter\n * board-graph.json (packed single JSON, written atomically) → Blob\n * per-card sidecars (cards/<id>/runtime, fetched-sources-manifest) → KV\n */\n\n// ============================================================================\n// Blob — raw content at an opaque key\n//\n// The key is backend-specific (file path, blob name, storage key).\n// Text helpers are always available. Binary helpers are optional so existing\n// backends can adopt incrementally.\n// ============================================================================\n\nexport interface BlobStat {\n key: string;\n size: number;\n updatedAt?: string;\n contentType?: string;\n}\n\nexport interface BlobStorage {\n /** Returns raw content string, or null if the blob does not exist. */\n read(key: string): string | null;\n\n /** Write content at key. Implementations should be atomic (write-rename). */\n write(key: string, content: string): void;\n\n /** Returns true if a blob exists at key. */\n exists(key: string): boolean;\n\n /** Delete the blob at key. No-op if it does not exist. */\n remove(key: string): void;\n\n /** Optional binary read for file-like artifacts. */\n readBytes?(key: string): Uint8Array | null;\n\n /** Optional binary write for file-like artifacts. */\n writeBytes?(key: string, content: Uint8Array): void;\n\n /** Optional key listing by prefix. */\n listKeys?(prefix?: string): string[];\n\n /** Optional metadata lookup. */\n stat?(key: string): BlobStat | null;\n}\n\n// ============================================================================\n// KindValueRef — backend-neutral typed reference\n//\n// A ref describes WHERE content lives without carrying the bytes.\n// Serialized on the CLI wire as: b64:<base64url({\"kind\":\"...\",\"value\":\"...\"})>\n// kind = 'fs-path': value is an absolute file path\n// Additional kinds (e.g. 'cosmos') are added in public-storage-adapter.ts as new backends are supported.\n// ============================================================================\n\nexport interface KindValueRef {\n readonly kind: string;\n readonly value: string;\n}\n\nconst REF_PREFIX = 'b64:';\n\nfunction toBase64Url(raw: string): string {\n const utf8 = new TextEncoder().encode(raw);\n const buf = (globalThis as { Buffer?: { from(data: Uint8Array): { toString(enc: string): string } } }).Buffer;\n let base64: string;\n if (buf) {\n base64 = buf.from(utf8).toString('base64');\n } else if (typeof btoa === 'function') {\n let binary = '';\n for (const byte of utf8) binary += String.fromCharCode(byte);\n base64 = btoa(binary);\n } else {\n throw new Error('No base64 encoder available in this runtime');\n }\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/g, '');\n}\n\nfunction fromBase64Url(input: string): string {\n const base64 = input.replace(/-/g, '+').replace(/_/g, '/')\n + '='.repeat((4 - (input.length % 4)) % 4);\n const buf = (globalThis as { Buffer?: { from(data: string, enc: string): { toString(enc: string): string } } }).Buffer;\n if (buf) return buf.from(base64, 'base64').toString('utf8');\n if (typeof atob === 'function') {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder().decode(bytes);\n }\n throw new Error('No base64 decoder available in this runtime');\n}\n\n/** Serialize a KindValueRef to the wire format: b64:<base64url(json)> */\nexport function serializeRef(ref: KindValueRef): string {\n return `${REF_PREFIX}${toBase64Url(JSON.stringify(ref))}`;\n}\n\n/** Parse a wire-format ref string (b64:<base64url(json)>) into a KindValueRef. */\nexport function parseRef(s: string): KindValueRef {\n if (!s.startsWith(REF_PREFIX)) throw new Error(`Invalid ref format (expected ${REF_PREFIX}<base64url(json)>): ${s}`);\n let parsed: unknown;\n try {\n parsed = JSON.parse(fromBase64Url(s.slice(REF_PREFIX.length)));\n } catch {\n throw new Error(`Invalid ref format (malformed base64url/json): ${s}`);\n }\n if (!parsed || typeof parsed !== 'object') {\n throw new Error(`Invalid ref format (expected object payload): ${s}`);\n }\n const candidate = parsed as { kind?: unknown; value?: unknown };\n if (typeof candidate.kind !== 'string' || typeof candidate.value !== 'string') {\n throw new Error(`Invalid ref format (payload must contain string kind/value): ${s}`);\n }\n return { kind: candidate.kind, value: candidate.value };\n}\n\n// ============================================================================\n// Journal — append-only log, cursor-based reads\n//\n// Each entry has a string id (UUID or monotonic token) and an opaque payload.\n// Cursors are entry ids — readAfter returns entries strictly after that id.\n// A null/empty cursor means \"read from the beginning\".\n// ============================================================================\n\nexport interface JournalEntry {\n id: string;\n payload: unknown;\n}\n\nexport interface JournalReadResult {\n entries: JournalEntry[];\n /** The id of the last entry returned, suitable for use as the next cursor. */\n newCursor: string | null;\n}\n\nexport interface JournalStorage {\n /** Append an entry. The storage layer assigns the id. */\n append(payload: unknown): JournalEntry;\n\n /** Read ALL entries (for index rebuilds, full replay). */\n readAll(): JournalEntry[];\n\n /**\n * Read entries appended after the given cursor id.\n * If cursor is null/empty, returns all entries from the beginning.\n */\n readAfter(cursor: string | null): JournalReadResult;\n}\n\n// ============================================================================\n// KV — key-value store with list and delete\n//\n// Values are opaque unknown — callers own serialisation.\n// Keys are scoped by the adapter factory (e.g. a boardDir prefix is closed\n// over in the adapter, not passed per-call).\n// ============================================================================\n\nexport interface KVStorage {\n /** Returns the stored value, or null if the key does not exist. */\n read(key: string): unknown | null;\n\n /** Write value at key. Overwrites any existing value. */\n write(key: string, value: unknown): void;\n\n /** Delete the key. No-op if it does not exist. */\n delete(key: string): void;\n\n /**\n * List all keys, optionally filtered to those starting with prefix.\n * Order is implementation-defined.\n */\n listKeys(prefix?: string): string[];\n}\n\n// ============================================================================\n// JSONStorage — KV store with JSON-aware merge operations\n//\n// Backed by KVStorage under the hood. Adds deepMerge and shallowMerge so\n// callers never need to read-modify-write manually for partial updates.\n// ============================================================================\n\nexport interface JSONStorage {\n /** Returns the stored JSON value, or null if the key does not exist. */\n read(key: string): unknown | null;\n\n /**\n * Read a nested value inside the stored object using a dot-notation path.\n * e.g. get('myKey', 'a.b.c') returns the value at { a: { b: { c: ... } } }.\n * Returns null if the key does not exist or the path cannot be traversed.\n */\n get(key: string, jsonPath: string): unknown | null;\n\n /** Write value at key. Overwrites any existing value. */\n write(key: string, value: unknown): void;\n\n /** Delete the key. No-op if it does not exist. */\n delete(key: string): void;\n\n /** List all keys, optionally filtered by prefix. */\n listKeys(prefix?: string): string[];\n\n /**\n * Shallow-merge patch into the existing object at key.\n * Equivalent to: write(key, { ...read(key), ...patch })\n * Creates the key if it does not exist.\n */\n shallowMerge(key: string, patch: Record<string, unknown>): void;\n\n /**\n * Deep-merge patch into the existing object at key.\n * Recursively merges nested plain objects; arrays and primitives are replaced.\n * Creates the key if it does not exist.\n */\n deepMerge(key: string, patch: Record<string, unknown>): void;\n\n /**\n * Set a nested value inside the stored object using a dot-notation path.\n * e.g. patch('myKey', 'a.b.c', 42) sets { a: { b: { c: 42 } } } into the stored object.\n * Intermediate objects are created if absent. Arrays are not traversed — use integer\n * segments to index into them (e.g. 'items.0.name').\n * Creates the top-level key if it does not exist.\n */\n patch(key: string, jsonPath: string, value: unknown): void;\n}\n\n// ============================================================================\n// StorageProvider — aggregate of all three primitives\n//\n// Adapter factories receive a StorageProvider and close over any scope (e.g.\n// boardDir) themselves. This is the single injection point for swapping\n// backends (Node fs → CosmosDB, browser localStorage, test doubles, etc.).\n// ============================================================================\n\nexport interface StorageProvider {\n blob: BlobStorage;\n journal: JournalStorage;\n kv: KVStorage;\n}\n\n// ============================================================================\n// AtomicRelayLock — non-blocking try-acquire lock with relay-on-busy semantics\n//\n// This interface serves TWO tightly coupled purposes which are intentionally\n// unified into a single primitive:\n//\n// 1. ATOMICITY — ensures that a read-mutate-save cycle is executed by at\n// most one actor at a time, preventing concurrent actors from racing on\n// stale state and writing conflicting snapshots.\n//\n// 2. RELAY SIGNAL — when tryAcquire() returns null, the caller knows the\n// cycle is already in progress. Because the holder always reads fresh\n// state upon entry, it will pick up every change appended by the skipping\n// caller before the lock was attempted. The caller can therefore safely\n// exit — its work will be completed by the holder. This is the\n// \"relay baton\" pattern: the lock being held IS the in-progress signal.\n//\n// These two purposes are not an accidental overload — they are the same\n// invariant expressed at different scopes. Any backend implementation\n// (FS lockfile, Cosmos document lease, Azure entity lock, in-memory flag)\n// that satisfies \"at most one holder at a time\" automatically satisfies both.\n//\n// Contract:\n// - tryAcquire() is non-blocking. It never waits.\n// - Returns a release function on success, or null if already held.\n// - The release function must be called exactly once (use try/finally).\n// - Behaviour after calling release() more than once is undefined.\n// ============================================================================\n\nexport interface AtomicRelayLock {\n /**\n * Attempt to acquire the lock without blocking.\n * Returns a `release` function if successful, or `null` if the lock is\n * already held by another actor (relay: that actor will complete the work).\n */\n tryAcquire(): (() => void) | null;\n}\n\n/**\n * Execute `work` under an `AtomicRelayLock`.\n *\n * - If the lock is busy, returns false immediately (relay: the holder will\n * complete the work on behalf of this caller).\n * - If acquired, runs `work` exclusively, releases the lock, then calls\n * `continuation` if provided — allowing the caller to schedule the next\n * cycle (e.g. spawn a detached process) after the lock is free.\n * - Returns true if work ran.\n */\nexport async function withRelayLock(\n lock: AtomicRelayLock,\n work: () => Promise<void>,\n continuation?: () => void,\n): Promise<boolean> {\n const release = lock.tryAcquire();\n if (!release) return false; // relay: holder is already doing the work\n try {\n await work();\n } finally {\n release(); // release before continuation so it can immediately re-acquire\n }\n continuation?.();\n return true;\n}\n","/**\n * execution-interface.ts\n *\n * Pure module — no Node/platform imports. Safe for any runtime.\n *\n * Defines the portable descriptor types for invoking any executable target,\n * regardless of transport (local process, HTTP endpoint, cloud function, etc.).\n *\n * Parallel to storage-interface.ts (which describes WHERE data lives), this\n * module describes HOW to invoke a piece of logic.\n *\n * ────────────────────────────────────────────────────────────────────────────\n * CORE CONCEPTS\n * ────────────────────────────────────────────────────────────────────────────\n *\n * ExecutionRef — self-contained, serializable JSON descriptor for one invocation target.\n * • howToRun — transport / runtime kind (discriminator)\n * • whatToRun — address of the artifact (KindValueRef wire form: b64:<base64url(json)>)\n * • argsMassaging — optional JSONata expressions that map logical args → physical call shape\n * • meta — optional human-readable label (e.g. 'task-executor', 'chat-handler')\n *\n * ExecutionResult — standardized envelope returned by any invocation.\n * • status: 'success' | 'fail' | 'error'\n * • data — KindValueRef wire form pointing to output blob (on success)\n * • error — human-readable message (on fail/error)\n *\n * ────────────────────────────────────────────────────────────────────────────\n * howToRun VALUES\n * ────────────────────────────────────────────────────────────────────────────\n *\n * 'local-node' node <whatToRun> [argv...]\n * 'local-python' python <whatToRun> [argv...]\n * 'local-process' execute <whatToRun> directly (shebang / pre-resolved binary)\n * 'http:post' HTTP POST to <whatToRun>\n * 'http:get' HTTP GET to <whatToRun>\n * 'built-in' resolved by the adapter to a well-known internal implementation\n *\n * ────────────────────────────────────────────────────────────────────────────\n * argsMassaging\n * ────────────────────────────────────────────────────────────────────────────\n *\n * Each field is a JSONata expression evaluated against the caller's logical args object.\n * If argsMassaging is omitted, the adapter uses its default mapping for the howToRun kind.\n *\n * cmdTemplate — array of JSONata exprs, each producing one argv string (local transports)\n * urlTemplate — JSONata expr producing the final URL string (http transports)\n * bodyTemplate — JSONata expr producing the request body object (http transports)\n *\n * ────────────────────────────────────────────────────────────────────────────\n * SERIALIZATION\n * ────────────────────────────────────────────────────────────────────────────\n *\n * ExecutionRef is a plain JSON object — store it as-is on disk, in Cosmos, or any DB.\n * No special encoding needed. parseExecutionRef / serializeExecutionRef are thin\n * JSON wrappers provided for symmetry with storage-interface.\n *\n * ────────────────────────────────────────────────────────────────────────────\n * USAGE EXAMPLES\n * ────────────────────────────────────────────────────────────────────────────\n *\n * // Built-in source-cli task executor (resolved by adapter from cliDir):\n * const builtIn: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'built-in',\n * whatToRun: 'b64:<base64url({\"kind\":\"built-in\",\"value\":\"source-cli-task-executor\"})>',\n * };\n *\n * // External local-node task executor with default protocol args:\n * const local: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'local-node',\n * whatToRun: 'b64:<base64url({\"kind\":\"fs-path\",\"value\":\"/path/to/my-executor.js\"})>',\n * };\n *\n * // Azure Function task executor with custom arg mapping:\n * const azureFn: ExecutionRef = {\n * meta: 'task-executor',\n * howToRun: 'http:post',\n * whatToRun: 'b64:<base64url({\"kind\":\"http-url\",\"value\":\"https://myfn.azurewebsites.net/api/task-executor\"})>',\n * argsMassaging: {\n * urlTemplate: \"whatToRun & '?op=' & subcommand\",\n * bodyTemplate: \"{ 'inRef': inRef, 'outRef': outRef, 'token': token }\",\n * },\n * };\n *\n * // Chat handler over HTTP with a different logical args shape:\n * const chatHandler: ExecutionRef = {\n * meta: 'chat-handler',\n * howToRun: 'http:post',\n * whatToRun: 'b64:<base64url({\"kind\":\"http-url\",\"value\":\"https://myfn.azurewebsites.net/api/chat\"})>',\n * argsMassaging: {\n * bodyTemplate: \"{ 'message': message, 'context': context, 'sessionId': sessionId }\",\n * },\n * };\n */\n\n// ============================================================================\n// OutputTransforms\n// ============================================================================\n\nimport { serializeRef } from './storage-interface.js';\n\n/**\n * Optional JSONata-based transforms applied to the raw invoke result.\n * Context for all expressions: `{ output: { result, data, error? } }`.\n * All fields are optional.\n */\nexport interface OutputTransforms {\n /**\n * JSONata expression that produces the transition name string.\n * @example \"output.code = 200 ? 'success' : 'failure'\"\n */\n resultExpr?: string;\n\n /**\n * JSONata expression that produces the data object.\n * @example \"{ 'value': output.body.value }\"\n */\n dataTemplate?: string;\n\n /**\n * JSONata expression that produces the error string, or $undefined() to clear it.\n * @example \"output.code != 200 ? output.error_message : $undefined()\"\n */\n errorExpr?: string;\n}\n\n// ============================================================================\n// ArgsMassaging\n// ============================================================================\n\n/**\n * Optional JSONata-based mapping from logical args → physical invocation shape.\n *\n * Each field is a JSONata expression string evaluated against the caller's\n * logical args object (e.g. `{ inRef, outRef, errRef }` for a task-executor).\n *\n * If argsMassaging is omitted entirely, the execution adapter uses its default\n * mapping for the given howToRun kind.\n */\nexport interface ArgsMassaging {\n /**\n * For local transports ('local-node', 'local-python', 'local-process').\n * Array of JSONata expressions — each evaluates to one argv string.\n * The resolved strings are appended after the base command.\n *\n * @example\n * // Standard task-executor protocol:\n * cmdTemplate: [\n * \"'run-source-fetch'\",\n * \"'--in-ref'\", \"inRef\",\n * \"'--out-ref'\", \"outRef\",\n * \"'--err-ref'\", \"errRef\",\n * ]\n */\n cmdTemplate?: string[];\n\n /**\n * For http transports ('http:post', 'http:get').\n * JSONata expression that produces the final URL string.\n * The input context includes 'whatToRun' (the base URL from the ref)\n * plus all logical args.\n *\n * @example\n * urlTemplate: \"whatToRun & '?op=' & subcommand\"\n */\n urlTemplate?: string;\n\n /**\n * For http transports.\n * JSONata expression that produces the request body object.\n * Evaluated against the logical args object.\n *\n * @example\n * bodyTemplate: \"{ 'inRef': inRef, 'outRef': outRef, 'token': token }\"\n */\n bodyTemplate?: string;\n}\n\n// ============================================================================\n// ExecutionRef\n// ============================================================================\n\n/**\n * Self-contained, serializable descriptor for invoking a target.\n *\n * Stores everything needed to make the physical call — transport kind,\n * artifact address, and optional arg-mapping expressions.\n * Serialize as plain JSON; no special wire encoding required.\n */\nexport interface ExecutionRef {\n /**\n * Optional human-readable label identifying the role of this invocation.\n * Not used for dispatch — purely for logging and diagnostics.\n * @example 'task-executor', 'chat-handler', 'board-live-cards'\n */\n meta?: string;\n\n /**\n * Transport and runtime kind — determines how whatToRun is invoked.\n * @see module JSDoc for the full list of supported values.\n */\n howToRun: 'local-node' | 'local-python' | 'local-process' | 'http:post' | 'http:get' | 'built-in' | 'in-browser';\n\n /**\n * Address of the artifact to run. Two valid forms:\n * - string: must be KindValueRef wire form `b64:<base64url(json)>` (programmatically generated via serializeRef)\n * - object: `{ kind: string; value: string }` plain object (human-authored flow files — normalized by the handler factory)\n * @example 'b64:<base64url({\"kind\":\"fs-path\",\"value\":\"/dist/cli/source-cli-task-executor.js\"})>'\n * @example { kind: 'http-url', value: '/api/workiq/ask' }\n * @example { kind: 'fs-path', value: './my-handler.js' }\n */\n whatToRun: string | { kind: string; value: string };\n\n /**\n * Optional JSONata-based mapping from logical args → physical call shape.\n * When omitted, the adapter applies its default protocol for the howToRun kind.\n */\n argsMassaging?: ArgsMassaging;\n\n /**\n * Optional JSONata-based transforms applied to the raw invoke result\n * before it reaches the step-machine engine.\n *\n * Context for all expressions: `{ output: { result, data, error? } }`\n * where `output` is the raw { result, data, error? } returned by invokeRefSync.\n *\n * All fields are optional — only defined ones override the raw value.\n *\n * @example\n * outputTransforms:\n * resultExpr: \"output.code = 200 ? 'success' : 'failure'\"\n * dataTemplate: \"{ 'value': output.body.value }\"\n * errorExpr: \"output.code != 200 ? output.error_message : $undefined()\"\n */\n outputTransforms?: OutputTransforms;\n\n /**\n * Opaque executor-specific configuration.\n * For local transports, base64-encoded and passed as --extra <base64-json> in the argv.\n * For HTTP transports, available in argsMassaging.bodyTemplate as the `extra` binding.\n * Stored with the ref so it travels as a single unit with the invocation descriptor.\n */\n extra?: Record<string, unknown>;\n}\n\n// ============================================================================\n// ExecutionResult\n// ============================================================================\n\n/**\n * Standardized result envelope returned by any execution.\n *\n * Replaces the implicit \"file-exists = success, absent = failure\" protocol\n * with an explicit status field. The data ref points to the output blob.\n */\nexport interface ExecutionResult {\n /** Outcome of the execution. */\n status: 'success' | 'fail' | 'error';\n\n /**\n * KindValueRef wire form pointing to the output blob.\n * Present only when status === 'success'.\n */\n data?: string;\n\n /**\n * Human-readable error or failure message.\n * Present when status === 'fail' or 'error'.\n */\n error?: string;\n}\n\n// ============================================================================\n// ExecutionRef factory helpers\n// ============================================================================\n\n/**\n * Create an ExecutionRef from a script path string (e.g. from a --task-executor CLI arg).\n * File extension determines howToRun:\n * .js / .mjs → 'local-node'\n * .py → 'local-python'\n * other → 'local-process'\n *\n * @param scriptPath Absolute or relative path to the script / binary.\n * @param extra Optional opaque executor config stored on the ref.\n */\nexport function executionRefFromScriptPath(\n scriptPath: string,\n extra?: Record<string, unknown>,\n): ExecutionRef {\n let howToRun: ExecutionRef['howToRun'];\n if (/\\.m?js$/i.test(scriptPath)) howToRun = 'local-node';\n else if (/\\.py$/i.test(scriptPath)) howToRun = 'local-python';\n else howToRun = 'local-process';\n return {\n meta: 'task-executor',\n howToRun,\n whatToRun: serializeRef({ kind: 'fs-path', value: scriptPath }),\n ...(extra ? { extra } : {}),\n };\n}\n\n// ============================================================================\n// Serialization helpers\n// ============================================================================\n\n/**\n * Serialize an ExecutionRef to a JSON string for storage.\n * Plain JSON.stringify — no special encoding.\n */\nexport function serializeExecutionRef(ref: ExecutionRef): string {\n return JSON.stringify(ref);\n}\n\n/**\n * Parse a JSON string back into an ExecutionRef.\n * Throws if the string is not valid JSON or is missing required fields.\n */\nexport function parseExecutionRef(s: string): ExecutionRef {\n let parsed: unknown;\n try {\n parsed = JSON.parse(s);\n } catch {\n throw new Error(`parseExecutionRef: invalid JSON — ${s}`);\n }\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n typeof (parsed as Record<string, unknown>).howToRun !== 'string' ||\n typeof (parsed as Record<string, unknown>).whatToRun !== 'string'\n ) {\n throw new Error(`parseExecutionRef: missing required fields howToRun/whatToRun — ${s}`);\n }\n return parsed as ExecutionRef;\n}\n"]}
|