@lostgradient/weft 0.20.0 → 0.21.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/README.md +2 -2
- package/dist/core/engine/activity-reconciliation.d.ts +2 -2
- package/dist/core/engine/activity-reconciliation.js +12 -8
- package/dist/core/engine/async-activity-completion.js +12 -4
- package/dist/core/engine/async-activity-records.d.ts +11 -1
- package/dist/core/engine/async-activity-records.js +4 -3
- package/dist/core/engine/attributes-tags.d.ts +11 -1
- package/dist/core/engine/attributes-tags.js +4 -3
- package/dist/core/engine/bulk-operations-purge.js +5 -2
- package/dist/core/engine/bulk-operations.js +17 -5
- package/dist/core/engine/callback-creators-bundles.js +1 -1
- package/dist/core/engine/callback-creators-core.js +4 -2
- package/dist/core/engine/checkpoint-io.js +1 -1
- package/dist/core/engine/child-workflow.js +2 -1
- package/dist/core/engine/completed-review-storage.js +1 -1
- package/dist/core/engine/condition-waiters.d.ts +45 -3
- package/dist/core/engine/condition-waiters.js +12 -3
- package/dist/core/engine/disposal.js +6 -0
- package/dist/core/engine/engine-internal-types.d.ts +12 -4
- package/dist/core/engine/fenced-write.d.ts +46 -15
- package/dist/core/engine/fenced-write.js +39 -6
- package/dist/core/engine/finalizer-state.d.ts +3 -1
- package/dist/core/engine/handle-result.d.ts +49 -1
- package/dist/core/engine/handle-result.js +95 -20
- package/dist/core/engine/index.d.ts +13 -5
- package/dist/core/engine/index.js +155 -5
- package/dist/core/engine/inline-launch-queue.js +9 -0
- package/dist/core/engine/internals.d.ts +73 -0
- package/dist/core/engine/invoke-update-handler.d.ts +19 -0
- package/dist/core/engine/invoke-update-handler.js +7 -0
- package/dist/core/engine/lease-deposition.d.ts +132 -0
- package/dist/core/engine/lease-deposition.js +31 -0
- package/dist/core/engine/lease-errors.d.ts +80 -9
- package/dist/core/engine/lease-errors.js +28 -2
- package/dist/core/engine/lifecycle/resume.js +3 -1
- package/dist/core/engine/lifecycle/standalone-claim-acquire.d.ts +33 -0
- package/dist/core/engine/lifecycle/standalone-claim-acquire.js +25 -0
- package/dist/core/engine/lifecycle/start-commit.js +20 -6
- package/dist/core/engine/lifecycle/transition.d.ts +15 -1
- package/dist/core/engine/lifecycle/transition.js +6 -3
- package/dist/core/engine/operations-activity.js +1 -1
- package/dist/core/engine/operations-time.js +21 -7
- package/dist/core/engine/owner-side-signal-poll.d.ts +132 -0
- package/dist/core/engine/owner-side-signal-poll.js +22 -0
- package/dist/core/engine/owner-side-update-poll.d.ts +116 -0
- package/dist/core/engine/owner-side-update-poll.js +22 -0
- package/dist/core/engine/ownership-bootstrap.d.ts +280 -0
- package/dist/core/engine/ownership-bootstrap.js +89 -0
- package/dist/core/engine/ownership-mode-marker.d.ts +82 -0
- package/dist/core/engine/ownership-mode-marker.js +52 -0
- package/dist/core/engine/ownership-options.d.ts +22 -6
- package/dist/core/engine/ownership-options.js +42 -12
- package/dist/core/engine/pending-updates.js +35 -24
- package/dist/core/engine/queries.d.ts +70 -0
- package/dist/core/engine/queries.js +58 -4
- package/dist/core/engine/schedules.js +1 -1
- package/dist/core/engine/signals.d.ts +11 -1
- package/dist/core/engine/signals.js +11 -7
- package/dist/core/engine/sleep-timer-acknowledgements.d.ts +68 -0
- package/dist/core/engine/sleep-timer-acknowledgements.js +19 -0
- package/dist/core/engine/storage-io.d.ts +58 -10
- package/dist/core/engine/storage-io.js +27 -9
- package/dist/core/engine/termination/cleanup.d.ts +5 -4
- package/dist/core/engine/termination/complete.js +23 -4
- package/dist/core/engine/termination/finalizer-claim.js +4 -4
- package/dist/core/engine/termination/state-commit-callbacks.d.ts +15 -0
- package/dist/core/engine/termination/state-commit-callbacks.js +0 -0
- package/dist/core/engine/termination/suspend.js +1 -1
- package/dist/core/engine/update-validation.d.ts +28 -0
- package/dist/core/engine/update-validation.js +37 -0
- package/dist/core/engine/updates.d.ts +17 -16
- package/dist/core/engine/updates.js +24 -47
- package/dist/core/engine/wake-ownership-check.d.ts +86 -0
- package/dist/core/engine/wake-ownership-check.js +19 -0
- package/dist/core/engine/wake-ownership-guard.d.ts +46 -0
- package/dist/core/engine/wake-ownership-guard.js +23 -0
- package/dist/core/engine/workflow-claim-codec.d.ts +64 -0
- package/dist/core/engine/workflow-claim-codec.js +44 -0
- package/dist/core/engine/workflow-claim-cooldown.d.ts +60 -0
- package/dist/core/engine/workflow-claim-cooldown.js +17 -0
- package/dist/core/engine/workflow-claim-fold.d.ts +82 -0
- package/dist/core/engine/workflow-claim-fold.js +53 -0
- package/dist/core/engine/workflow-claim-metrics.d.ts +131 -0
- package/dist/core/engine/workflow-claim-metrics.js +62 -0
- package/dist/core/engine/workflow-claim-reclaim-scan.d.ts +96 -0
- package/dist/core/engine/workflow-claim-reclaim-scan.js +66 -0
- package/dist/core/engine/workflow-claim-reclaim-target.d.ts +107 -0
- package/dist/core/engine/workflow-claim-reclaim-target.js +155 -0
- package/dist/core/engine/workflow-claim-registry.d.ts +227 -0
- package/dist/core/engine/workflow-claim-registry.js +198 -0
- package/dist/core/engine/workflow-claim-renewal-interval.d.ts +50 -0
- package/dist/core/engine/workflow-claim-renewal-interval.js +132 -0
- package/dist/core/engine/workflow-claim-renewal-subpasses.d.ts +265 -0
- package/dist/core/engine/workflow-claim-renewal-subpasses.js +104 -0
- package/dist/core/engine/workflow-claim-renewal-task.d.ts +159 -0
- package/dist/core/engine/workflow-claim-renewal-task.js +65 -0
- package/dist/core/engine/workflow-claim-transitions.d.ts +186 -0
- package/dist/core/engine/workflow-claim-transitions.js +120 -0
- package/dist/core/inline-execution-strategy.d.ts +20 -0
- package/dist/core/inline-execution-strategy.js +15 -4
- package/dist/core/scheduler/scheduler-class.js +3 -3
- package/dist/core/scheduler/timer-sources.d.ts +13 -0
- package/dist/core/scheduler/timer-sources.js +1 -1
- package/dist/core/types/options.d.ts +17 -1
- package/dist/core/weft-error.d.ts +1 -1
- package/dist/core/weft-error.js +2 -1
- package/dist/http.js +2 -2
- package/dist/index.d.ts +2 -1
- package/dist/index.js +8 -0
- package/dist/indexeddb.js +1 -1
- package/dist/json-schema.js +3 -3
- package/dist/observability/index.js +2 -2
- package/dist/storage/auto.js +1 -1
- package/dist/storage/bun-sql.js +113 -0
- package/dist/storage/compressed-storage.js +1 -1
- package/dist/storage/index.d.ts +38 -35
- package/dist/storage/interface.d.ts +87 -125
- package/dist/storage/interface.js +1 -1
- package/dist/storage/key-encoding.d.ts +51 -0
- package/dist/storage/key-encoding.js +13 -0
- package/dist/storage/key-prefixes.d.ts +1 -1
- package/dist/storage/key-prefixes.js +3 -0
- package/dist/storage/lmdb.js +1 -1
- package/dist/storage/memory.js +1 -1
- package/dist/storage/neon.js +2 -2
- package/dist/storage/node-sqlite.js +113 -0
- package/dist/storage/ownership-keys.d.ts +55 -0
- package/dist/storage/ownership-keys.js +6 -0
- package/dist/storage/postgres.js +2 -2
- package/dist/storage/resolve.js +1 -1
- package/dist/storage/scoped-storage.js +1 -1
- package/dist/storage/testing.js +1 -1
- package/dist/storage/turso.js +2 -2
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/web-extension.js +1 -1
- package/dist/worker/protocol.js +1 -1
- package/package.json +1 -1
package/dist/json-schema.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`)}function
|
|
4
|
-
${
|
|
2
|
+
var F=import.meta.require;class K extends Error{code;constructor(j,q,z){super(q,z);this.code=j,this.name=j}}var Y={WorkflowAlreadyExistsError:!0,BulkDeleteRequiresTerminalWorkflowsError:!0,BulkOperationConfirmationError:!0,WorkflowTypeNotRegisteredForRecoveryError:!0,EngineCreateNameMismatchError:!0,EngineDisposedError:!0,EngineDisposalError:!0,WorkflowNotFoundError:!0,WorkflowNotRegisteredError:!0,WorkflowConcurrencyLimitExceededError:!0,WorkflowSuspendNotSupportedError:!0,ActivityResolutionError:!0,BranchTopologyChangedError:!0,PersistedDataIncompatibleError:!0,WorkflowTimeoutError:!0,HttpClientError:!0,WorkerProtocolIncompatibleError:!0,UpdateTimeoutError:!0,UpdateValidationError:!0,WorkflowTerminalError:!0,WorkflowBuilderError:!0,VersionMismatchError:!0,EffectReplayConflictError:!0,ReviewTimeoutError:!0,AtomicStateConflictError:!0,StandardSchemaValidationError:!0,ActivityReconciliationCapabilityError:!0,ActivityReconciliationConflictError:!0,ActivityReconciliationIndeterminateError:!0,DurableActivityScopeError:!0,DurableActivityUnsupportedError:!0,AsyncActivityTokenNotFoundError:!0,ActivityScheduleToCloseTimeoutError:!0,ActivityPerAttemptTimeoutError:!0,PayloadSizeExceededError:!0,StartOrSignalConflictError:!0,WorkflowTeardownPendingError:!0,IdempotencyKeyPurgedError:!0,WorkerManifestBuildError:!0,OwnershipModeMismatchError:!0},M=new Set(Object.keys(Y));class A extends K{fieldName;operation;issues;constructor(j){super("StandardSchemaValidationError",w(j.fieldName,j.operation,j.issues));this.fieldName=j.fieldName,this.operation=j.operation,this.issues=j.issues}}async function X(j,q,z){let G=j["~standard"];if(!Z(G))throw TypeError(`Schema for ${z.fieldName} does not provide runtime validation. Attach a Standard Schema validator (Zod, Valibot, or another vendor) or supply a runtime-validating schema at this boundary.`);let H=await G.validate(q);if(H.issues===void 0)return H.value;throw new A({fieldName:z.fieldName,operation:z.operation,issues:H.issues.map($)})}function Q(j){return j.map((q)=>q.path===""?q.message:`${q.path}: ${q.message}`).join(`
|
|
3
|
+
`)}function Z(j){return typeof j.validate==="function"}function $(j){return{message:j.message,path:B(j.path)}}function B(j){if(j===void 0||j.length===0)return"";let q="";for(let z of j)q+="/",q+=D(z);return q}function D(j){let q=U(j)?j.key:j;return b(String(q))}function U(j){return j!==null&&typeof j==="object"&&"key"in j}function b(j){return j.replace(/~/g,"~0").replace(/\//g,"~1")}function w(j,q,z){return`Validation failed for ${q===void 0?j:`${q} ${j}`}:
|
|
4
|
+
${Q(z)}`}var R=Q,_=A,C=X;export{C as validateStandardSchema,R as formatStandardSchemaIssues,_ as StandardSchemaValidationError};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var Jn=import.meta.require
|
|
2
|
+
var Jn=import.meta.require;var h={traceId:"0".repeat(32),spanId:"0".repeat(16),traceFlags:0},R={setAttribute(){},setStatus(){},recordException(){},end(){},spanContext(){return h}},q={setAttribute:(...n)=>R.setAttribute(...n),setStatus:(...n)=>R.setStatus(...n),recordException:(...n)=>R.recordException(...n),end:(...n)=>R.end(...n)},l={startSpan(){return R}},P={record(){},add(){}},t={createHistogram(){return P},createCounter(){return P},createUpDownCounter(){return P}},r=Symbol("ROOT_CONTEXT"),a={trace:{getTracer(){return l},setSpan(n){return n}},metrics:{getMeter(){return t}},context:{ROOT_CONTEXT:r,with(n,w){return w()}},SpanStatusCode:{OK:1,ERROR:2,UNSET:0}},G;function s(){let n=globalThis.require;if(typeof n==="function")return(w)=>n(w);return()=>{return}}function e(n){return n?.trace?.getTracer!=null&&n.SpanStatusCode!=null}function nn(n=s()){try{let w=n("@opentelemetry/api");if(e(w))return w}catch{}return}function o(n){if(G)return G;let w=nn(n);if(w)return G=w,G;return G=a,G}function H(n){let w=new Uint8Array(n);return crypto.getRandomValues(w),Array.from(w,(i)=>i.toString(16).padStart(2,"0")).join("")}var Y="traceparent",wn=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,Sn="00000000000000000000000000000000",kn="0000000000000000";function Z(n){let w=wn.exec(n);if(!w)return null;let[,i,S,k,v]=w;if(S===Sn)return null;if(k===kn)return null;return{version:i,traceId:S,spanId:k,traceFlags:parseInt(v,16)}}function M(n){let w=n.traceFlags.toString(16).padStart(2,"0");return`${n.version}-${n.traceId}-${n.spanId}-${w}`}function T(n){let w=n.get(Y);if(!w)return null;return Z(w)}function U(n,w){n.set(Y,M(w))}function fn(){return H(16)}function vn(){return H(8)}var O=1024;function K(n,w){let i;try{i=JSON.stringify(n)}catch{i=String(n)}if(i.length>w)return i.slice(0,w)+"...";return i}function yn(n){return n instanceof Error?n.message:String(n)}function Wn(n){return n instanceof Error?n:Error(String(n))}function J(n,w){let i=n.spanContext();U(w,{version:"00",traceId:i.traceId,spanId:i.spanId,traceFlags:i.traceFlags})}function C(n,w,i){let S=n.attributeExtractor;if(!S)return;let k=S(i);for(let[v,y]of Object.entries(k))w.setAttribute(v,y)}function Q(n,w){let i=n.workflowSpans.get(w);return i?n.trace.setSpan(n.api.context.ROOT_CONTEXT,i.span):n.api.context.ROOT_CONTEXT}function V(n,w,i){w.setStatus({code:n.SpanStatusCode.ERROR,message:yn(i)}),w.recordException(Wn(i))}function _(n,w,i,S){try{let k=i();return w.setStatus({code:n.SpanStatusCode.OK}),S?.(k),k}catch(k){throw V(n,w,k),k}finally{w.end()}}async function j(n,w,i,S){try{let k=await i();return w.setStatus({code:n.SpanStatusCode.OK}),S?.(k),k}catch(k){throw V(n,w,k),k}finally{w.end()}}function*x(n,w,i,S){try{let k=yield*i();return w.setStatus({code:n.SpanStatusCode.OK}),S?.(k),k}catch(k){throw V(n,w,k),k}finally{w.end()}}function g(n){return{async execute(w,i){let S=T(w.headers),k=n.api.context.ROOT_CONTEXT;if(S){let y={...q,spanContext(){return{traceId:S.traceId,spanId:S.spanId,traceFlags:S.traceFlags}}};k=n.trace.setSpan(n.api.context.ROOT_CONTEXT,y)}let v=n.tracer.startSpan(`activity:execute:${w.activityName}`,{attributes:{"weft.activity.name":w.activityName,"weft.activity.attempt":w.attempt,...S?{"weft.parent.trace_id":S.traceId}:{}}},k);if(n.recordPayloads&&w.input!==void 0)v.setAttribute("weft.payload.input",K(w.input,n.maxPayloadSize));return j(n,v,()=>i(w))}}}var A={workflowDuration:{name:"weft.workflow.duration",description:"Duration of workflow execution in milliseconds",unit:"ms",type:"histogram"},activityDuration:{name:"weft.activity.duration",description:"Duration of activity execution in milliseconds",unit:"ms",type:"histogram"},activityAttempts:{name:"weft.activity.attempts",description:"Total activity execution attempts",unit:"attempts",type:"counter"},workflowActive:{name:"weft.workflow.active",description:"Number of currently active workflows",unit:"workflows",type:"gauge"},workflowStarted:{name:"weft.workflow.started",description:"Total workflows started",unit:"workflows",type:"counter"},workflowCompleted:{name:"weft.workflow.completed",description:"Total workflows completed",unit:"workflows",type:"counter"},workflowFailed:{name:"weft.workflow.failed",description:"Total workflows failed",unit:"workflows",type:"counter"},promptCacheHits:{name:"weft.prompt_cache.hits",description:"Total prompt prefix cache hits",unit:"hits",type:"counter"},promptCacheMisses:{name:"weft.prompt_cache.misses",description:"Total prompt prefix cache misses",unit:"misses",type:"counter"},dpmoDefects:{name:"weft.dpmo.defects",description:"Total failed workflows (DPMO numerator)",unit:"workflows",type:"counter"},dpmoOperations:{name:"weft.dpmo.operations",description:"Total started workflows (DPMO denominator)",unit:"workflows",type:"counter"},taskBacklog:{name:"weft.task.backlog",description:"Number of queued tasks waiting for workers",unit:"tasks",type:"gauge"},taskQueueLatency:{name:"weft.task.queue_latency",description:"Time tasks spend queued before dispatch in milliseconds",unit:"ms",type:"histogram"},taskExecutionLatency:{name:"weft.task.execution_latency",description:"Time tasks spend executing after worker start in milliseconds",unit:"ms",type:"histogram"},taskRetries:{name:"weft.task.retries",description:"Total task retry attempts after the first dispatch attempt",unit:"retries",type:"counter"},taskRequeues:{name:"weft.task.requeues",description:"Total visibility-timeout or disconnect task requeues",unit:"requeues",type:"counter"},taskStaleHeartbeats:{name:"weft.task.stale_heartbeats",description:"Number of in-flight tasks whose heartbeat age exceeds the diagnostic threshold",unit:"tasks",type:"gauge"},workerCapacitySaturation:{name:"weft.worker.capacity_saturation",description:"Ratio of in-flight worker slots to total worker concurrency",unit:"ratio",type:"gauge"}};var dn=1e4;class z{#n;#i=0;#w=0;constructor(n){this.#n=new Float64Array(n)}push(n){if(this.#n[this.#i]=n,this.#i=(this.#i+1)%this.#n.length,this.#w<this.#n.length)this.#w++}toArray(){if(this.#w<this.#n.length)return Array.from(this.#n.subarray(0,this.#w));let n=Array.from({length:this.#w});for(let w=0;w<this.#w;w++)n[w]=this.#n[(this.#i+w)%this.#n.length];return n}}class B{#n;#i;#w;constructor(){this.#n=new Map,this.#i=new Map,this.#w=new Map}increment(n,w=1){this.#n.set(n,(this.#n.get(n)??0)+w)}record(n,w){let i=this.#i.get(n);if(!i)i=new z(dn),this.#i.set(n,i);i.push(w)}gauge(n,w){this.#w.set(n,w)}snapshot(){let n={};for(let[w,i]of this.#n)n[w]={type:"counter",value:i};for(let[w,i]of this.#i){let S=i.toArray(),k=In(S);n[w]={type:"histogram",count:S.length,sum:Fn(S),p50:k[Math.floor(k.length*0.5)]??0,p99:k[Math.floor(k.length*0.99)]??0,min:k[0]??0,max:k[k.length-1]??0}}for(let[w,i]of this.#w)n[w]={type:"gauge",value:i};return n}reset(){this.#n.clear(),this.#i.clear(),this.#w.clear()}}function pn(n){let w;if(typeof n==="string")w=o().metrics.getMeter(n);else if(n)w=n;else w=o().metrics.getMeter("weft");return{workflowDuration:w.createHistogram("weft.workflow.duration",{unit:"ms"}),activityDuration:w.createHistogram("weft.activity.duration",{unit:"ms"}),activityAttempts:w.createCounter("weft.activity.attempts"),activeWorkflows:w.createUpDownCounter("weft.workflow.active")}}function In(n){let w=[...n];return w.sort((i,S)=>i-S),w}function Fn(n){let w=0;for(let i of n)w+=i;return w}function Ln(n,w){let i=w?.type==="histogram"?w.count:0,S=w?.type==="histogram"?w.sum:0;return[`# TYPE ${n} histogram`,`${n}_count ${i}`,`${n}_sum ${S}`]}function $n(n,w){let i=w?.type==="counter"?w.value:0;return[`# TYPE ${n} counter`,`${n}_total ${i}`]}function Gn(n,w){let i=w?.type==="gauge"?w.value:0;return[`# TYPE ${n} gauge`,`${n} ${i}`]}var on={histogram:Ln,counter:$n,gauge:Gn};function Kn(n,w){let i=n.name.replace(/\./g,"_"),S=w[n.name];return[`# HELP ${i} ${n.description}`,...on[n.type](i,S)]}function Cn(n){let w=n[A.dpmoDefects.name],i=n[A.dpmoOperations.name],S=w?.type==="counter"?w.value:0,k=i?.type==="counter"?i.value:0,v=k===0?0:S*1e6/k,y="weft_dpmo";return["# HELP weft_dpmo Defects per million operations (failed workflows / started workflows * 1e6)","# TYPE weft_dpmo gauge",`weft_dpmo ${v}`]}function b(n){let w=[];for(let i of Object.values(A))w.push(...Kn(i,n));return w.push(...Cn(n)),w.join(`
|
|
3
3
|
`)+`
|
|
4
|
-
`}function An(n){return{serialize(){let w=n?.snapshot()??{};return b(w)}}}class
|
|
4
|
+
`}function An(n){return{serialize(){let w=n?.snapshot()??{};return b(w)}}}class p extends Event{static type="workflow:completed";workflowId;result;duration;constructor(n,w,i){super(p.type);this.workflowId=n,this.result=w,this.duration=i}}class I extends Event{static type="workflow:failed";workflowId;error;constructor(n,w){super(I.type);this.workflowId=n,this.error=w}}class F extends Event{static type="workflow:cancelled";workflowId;constructor(n){super(F.type);this.workflowId=n}}class L extends Event{static type="workflow:timed-out";workflowId;timeoutType;elapsed;reason;constructor(n,w,i,S){super(L.type);if(this.workflowId=n,this.timeoutType=w,this.elapsed=i,S!==void 0)this.reason=S}}var _n=new Set([p.type,I.type,F.type,L.type]);var Xn=3600000,E=1e4,Rn=3600000;function c(n){let w=Date.now();for(let[i,S]of n.workflowSpans)if(w-S.createdAt>Xn)S.span.end(),n.workflowSpans.delete(i);if(n.workflowSpans.size>E){let i=n.workflowSpans.size-E,S=0;for(let[k,v]of n.workflowSpans){if(S>=i)break;v.span.end(),n.workflowSpans.delete(k),S++}}}function N(n,w){let i=n.workflowSpans.get(w);if(i)i.span.end(),n.workflowSpans.delete(w)}function u(n){function w(f,$,W){let d=n.workflowSpans.get(f);if(!d)return;if($==="error")d.span.setStatus({code:n.SpanStatusCode.ERROR,...W?{message:W}:{}});else d.span.setStatus({code:n.SpanStatusCode.OK});d.span.end(),n.workflowSpans.delete(f)}let i=(f)=>{if(!(f instanceof p))return;w(f.workflowId,"ok")},S=(f)=>{if(!(f instanceof I))return;w(f.workflowId,"error",f.error.message),n.metrics.increment("weft.dpmo.defects")},k=(f)=>{if(!(f instanceof F))return;w(f.workflowId,"error","Workflow cancelled")},v=(f)=>{if(!(f instanceof L))return;w(f.workflowId,"error",`Workflow timed out (${f.timeoutType}) after ${f.elapsed}ms`),n.metrics.increment("weft.dpmo.defects")};if(n.eventTarget)n.eventTarget.addEventListener(p.type,i),n.eventTarget.addEventListener(I.type,S),n.eventTarget.addEventListener(F.type,k),n.eventTarget.addEventListener(L.type,v);function y(f=Rn){let $=Date.now()-f,W=0;for(let[d,X]of n.workflowSpans)if(X.createdAt<=$)X.span.setStatus({code:n.SpanStatusCode.ERROR,message:"span evicted (stale)"}),X.span.end(),n.workflowSpans.delete(d),W++;return W}function D(){if(n.eventTarget)n.eventTarget.removeEventListener(p.type,i),n.eventTarget.removeEventListener(I.type,S),n.eventTarget.removeEventListener(F.type,k),n.eventTarget.removeEventListener(L.type,v);for(let f of n.workflowSpans.values())f.span.setStatus({code:n.SpanStatusCode.ERROR,message:"Observability disposed"}),f.span.end();n.workflowSpans.clear()}return{endWorkflowSpan:w,evictStaleSpans:y,dispose:D}}function m(n){return{workflowStart(w,i){c(n);let S=n.workflowSpans.get(w.workflowId);if(S)S.span.setStatus({code:n.SpanStatusCode.OK}),N(n,w.workflowId);let k=n.tracer.startSpan(`workflow:${w.workflowType}`,{attributes:{"weft.workflow.id":w.workflowId,"weft.workflow.type":w.workflowType}});if(n.workflowSpans.set(w.workflowId,{span:k,createdAt:Date.now()}),J(k,w.headers),n.recordPayloads&&w.input!==void 0)k.setAttribute("weft.payload.input",K(w.input,n.maxPayloadSize));C(n,k,w),n.metrics.increment("weft.workflow.started"),n.metrics.increment("weft.dpmo.operations"),i(w)},*activity(w,i){let S=n.tracer.startSpan(`activity:${w.activityName}`,{attributes:{"weft.activity.name":w.activityName,"weft.activity.attempt":w.attempt}},Q(n,w.workflowId));if(J(S,w.headers),n.recordPayloads&&w.input!==void 0)S.setAttribute("weft.payload.input",K(w.input,n.maxPayloadSize));C(n,S,w);let k=Date.now();return yield*x(n,S,()=>i(w),()=>{n.metrics.record("weft.activity.duration",Date.now()-k),n.metrics.increment("weft.activity.attempts")})},*sleep(w,i){let S=n.tracer.startSpan("sleep",{attributes:{"weft.sleep.duration":w.duration}},Q(n,w.workflowId));C(n,S,w),yield*x(n,S,()=>i(w))},*waitForSignal(w,i){let S=n.tracer.startSpan("waitForSignal",{attributes:{"weft.signal.name":w.signalName}},Q(n,w.workflowId));return C(n,S,w),yield*x(n,S,()=>i(w))},async childWorkflow(w,i){let S=[],k=T(w.parentHeaders);if(k)S.push({context:{traceId:k.traceId,spanId:k.spanId,traceFlags:k.traceFlags}});let v=n.tracer.startSpan(`childWorkflow:${w.workflowType}`,{attributes:{"weft.child_workflow.type":w.workflowType,"weft.child_workflow.id":w.childWorkflowId,"weft.child_workflow.parent_id":w.workflowId},links:S},n.api.context.ROOT_CONTEXT);if(J(v,w.headers),n.recordPayloads&&w.input!==void 0)v.setAttribute("weft.payload.input",K(w.input,n.maxPayloadSize));return n.metrics.increment("weft.child_workflow.started"),j(n,v,()=>i(w))},signalReceived(w,i){let S=n.tracer.startSpan(`signal:received:${w.signalName}`,{attributes:{"weft.signal.name":w.signalName,"weft.signal.workflow_id":w.workflowId}});C(n,S,w),_(n,S,()=>i(w))}}}function Tn(n){let{attributeExtractor:w,eventTarget:i,maxPayloadSize:S=O,metrics:k=new B,openTelemetryApi:v=o(),recordPayloads:y=!1,tracerName:D="weft",tracerVersion:f}=n??{},$=v,{trace:W,SpanStatusCode:d}=$,X=W.getTracer(D,f);return{api:$,trace:W,SpanStatusCode:d,tracer:X,recordPayloads:y,maxPayloadSize:S,attributeExtractor:w,eventTarget:i,metrics:k,workflowSpans:new Map}}function sn(n){let w=Tn(n),i=m(w),S=g(w),k={...i,...S},v=u(w);return{interceptor:k,metrics:w.metrics,...v}}export{b as serializeMetricsSnapshotForPrometheus,Z as parseTraceParent,U as injectTraceParent,o as getOpenTelemetryApi,fn as generateTraceId,vn as generateSpanId,M as formatTraceParent,T as extractTraceParent,pn as createOpenTelemetryMetrics,sn as createObservabilityInterceptors,An as createMetricsCollectorExporter,B as MetricsCollector,A as METRICS};
|
package/dist/storage/auto.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
2
|
+
var K=import.meta.require;function X(z){return{hasBun:typeof z.Bun<"u",hasIndexedDB:typeof z.indexedDB<"u",hasNode:z.process!==void 0&&typeof z.process.versions?.node==="string",hasWebExtensionStorage:z.browser?.storage!==void 0||z.chrome?.storage!==void 0}}async function A(z){let{createHash:C}=await import("crypto"),J=z.process?.cwd?.()??"weft-default";return C("sha256").update(J).digest("hex").slice(0,16)}async function H(z){let[{mkdirSync:C},{tmpdir:J},j]=await Promise.all([import("fs"),import("os"),import("path")]),Z=z.process?.env?.WEFT_DEFAULT_STORAGE_PATH,q=Z!==void 0&&Z.length>0?Z:j.join(J(),"weft-default",`${await A(z)}.db`);return C(j.dirname(q),{recursive:!0}),q}function $(z,C){if(C==="Bun")return typeof z.Bun;if(C==="browser.storage")return typeof(z.browser?.storage??z.chrome?.storage);return typeof z.process}function Y(z,C){return import.meta.url.endsWith(".ts")?z:C}async function V(z){return await import(z)}function F(z){if(z.browser?.storage!==void 0)return z.browser;if(z.chrome?.storage!==void 0)return z.chrome;return{}}function P(z){let{indexedDB:C,IDBKeyRange:J}=z;if(C===void 0||J===void 0)throw Error("resolveDefaultStorage: IndexedDB resolution requires both indexedDB and IDBKeyRange.");return{indexedDB:C,IDBKeyRange:J}}function k(z){let C=typeof z.indexedDB,J=typeof z.IDBKeyRange;return`typeof indexedDB=${C}, typeof IDBKeyRange=${J}`}var Q=Y("./bun-sql.ts","./bun-sql.js"),U=Y("./node-sqlite.ts","./node-sqlite.js"),W=Y("./indexeddb.ts","./indexeddb.js"),B=Y("./web-extension.ts","./web-extension.js");async function w(z=globalThis){let C=X(z);if(C.hasBun){let{BunSQLiteStorage:J}=await V(Q);return new J(await H(z))}if(C.hasNode){let{NodeSQLiteStorage:J}=await V(U);return new J(await H(z))}if(C.hasWebExtensionStorage){let{WebExtensionStorage:J}=await V(B);return new J({},F(z))}if(C.hasIndexedDB){let{IndexedDBStorage:J}=await V(W);return new J("weft",P(z))}throw Error(`resolveDefaultStorage: requires Bun, Node, WebExtension storage, or IndexedDB. Detected: typeof Bun=${$(z,"Bun")}, typeof process=${$(z,"process")}, typeof browser.storage=${$(z,"browser.storage")}, ${k(z)}.`)}export{w as resolveDefaultStorage};
|
package/dist/storage/bun-sql.js
CHANGED
|
@@ -9,6 +9,9 @@ function requireStorageCapability(storage, capability, featureName) {
|
|
|
9
9
|
}
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
+
// src/storage/default-scope.ts
|
|
13
|
+
var DEFAULT_SCOPE = "default";
|
|
14
|
+
|
|
12
15
|
// src/storage/derived-operations.ts
|
|
13
16
|
async function storageHasCore(storage, key) {
|
|
14
17
|
return await storage.get(key) !== null;
|
|
@@ -48,6 +51,18 @@ async function storageDeleteRangeCore(storage, prefix, options) {
|
|
|
48
51
|
return operations.length;
|
|
49
52
|
}
|
|
50
53
|
|
|
54
|
+
// src/storage/key-encoding.ts
|
|
55
|
+
function encodeStorageKeyComponent(value) {
|
|
56
|
+
return encodeURIComponent(value);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// src/storage/ownership-keys.ts
|
|
60
|
+
var OWNERSHIP_CLAIM_KEYS = {
|
|
61
|
+
workflowOwnerEpoch: (workflowId) => `wf-owner-epoch:${encodeStorageKeyComponent(workflowId)}`,
|
|
62
|
+
workflowOwnerHolder: (workflowId) => `wf-owner-holder:${encodeStorageKeyComponent(workflowId)}`,
|
|
63
|
+
ownershipModeMarker: () => "ownership-mode-marker"
|
|
64
|
+
};
|
|
65
|
+
|
|
51
66
|
// src/storage/interface.ts
|
|
52
67
|
var MAX_BATCH_OPERATIONS = 1e4;
|
|
53
68
|
class StorageBatchOperationLimitExceededError extends Error {
|
|
@@ -117,6 +132,104 @@ async function storageConditionalBatch(storage, conditions, operations) {
|
|
|
117
132
|
}
|
|
118
133
|
return storage.conditionalBatch(conditions, operations);
|
|
119
134
|
}
|
|
135
|
+
var formatSortableTimestamp = (timestamp) => String(timestamp).padStart(16, "0");
|
|
136
|
+
var SIGNAL_SORT_CLASS_START = "0";
|
|
137
|
+
var SIGNAL_SORT_CLASS_NORMAL = "1";
|
|
138
|
+
var signalStorageKey = (workflowId, name, id, sortClass) => `sig:${encodeStorageKeyComponent(workflowId)}:${encodeStorageKeyComponent(name)}:${sortClass}:${encodeStorageKeyComponent(id)}`;
|
|
139
|
+
var KEYS = {
|
|
140
|
+
workflow: (id) => `wf:${encodeStorageKeyComponent(id)}`,
|
|
141
|
+
checkpoint: (id) => `wf:${encodeStorageKeyComponent(id)}:ckpt`,
|
|
142
|
+
checkpointHistory: (id, step) => `wf:${encodeStorageKeyComponent(id)}:ckpt:${String(step).padStart(10, "0")}`,
|
|
143
|
+
timelinePrefix: (id) => `wf:${encodeStorageKeyComponent(id)}:timeline:`,
|
|
144
|
+
timeline: (id, step) => `wf:${encodeStorageKeyComponent(id)}:timeline:${String(step).padStart(10, "0")}`,
|
|
145
|
+
schedule: (id) => `schedule:${encodeStorageKeyComponent(id)}`,
|
|
146
|
+
scheduleTick: (fireAt, id) => `schedule-due:${String(fireAt).padStart(16, "0")}:${encodeStorageKeyComponent(id)}`,
|
|
147
|
+
scheduleRun: (workflowId) => `schedule-run:${encodeStorageKeyComponent(workflowId)}`,
|
|
148
|
+
scheduleRunLink: (workflowId) => `schedule-run-link:${encodeStorageKeyComponent(workflowId)}`,
|
|
149
|
+
scheduleRunBySchedulePrefix: (scheduleId) => `schedule-run-by-schedule:${encodeStorageKeyComponent(scheduleId)}:`,
|
|
150
|
+
scheduleRunBySchedule: (scheduleId, workflowId) => `schedule-run-by-schedule:${encodeStorageKeyComponent(scheduleId)}:${encodeStorageKeyComponent(workflowId)}`,
|
|
151
|
+
operation: (queue, scheduledAt, id) => `op:${queue}:${formatSortableTimestamp(scheduledAt)}:${id}`,
|
|
152
|
+
operationInflight: (id) => `op:inflight:${id}`,
|
|
153
|
+
operationQueued: (id) => `op:queued:${id}`,
|
|
154
|
+
operationResolved: (id) => `op:resolved:${id}`,
|
|
155
|
+
bulkOperationAuditPrefix: () => "audit:bulk:",
|
|
156
|
+
bulkOperationAudit: (timestamp, requestId, confirmationToken) => `audit:bulk:${formatSortableTimestamp(timestamp)}:${encodeStorageKeyComponent(requestId)}:${encodeStorageKeyComponent(confirmationToken)}`,
|
|
157
|
+
operationResolvedByTimePrefix: () => "op:resolved-by-time:",
|
|
158
|
+
operationResolvedByTime: (resolvedAt, id) => `op:resolved-by-time:${formatSortableTimestamp(resolvedAt)}:${encodeStorageKeyComponent(id)}`,
|
|
159
|
+
asyncActivity: (workflowId, token) => `async-act:v1:${encodeStorageKeyComponent(workflowId)}:${encodeStorageKeyComponent(token)}`,
|
|
160
|
+
asyncActivityResolution: (workflowId, token) => `async-act:v1:${encodeStorageKeyComponent(workflowId)}:${encodeStorageKeyComponent(token)}:resolution`,
|
|
161
|
+
activityReconciliationPrefix: (workflowId) => `actrec:v1:${encodeStorageKeyComponent(workflowId)}:`,
|
|
162
|
+
activityReconciliation: (workflowId, activityName, idempotencyKeyDigest) => `actrec:v1:${encodeStorageKeyComponent(workflowId)}:${encodeStorageKeyComponent(activityName)}:${idempotencyKeyDigest}`,
|
|
163
|
+
eventPrefix: (workflowId) => `ev:${encodeStorageKeyComponent(workflowId)}:`,
|
|
164
|
+
event: (workflowId, sequence) => `ev:${encodeStorageKeyComponent(workflowId)}:${String(sequence).padStart(10, "0")}`,
|
|
165
|
+
eventHead: (workflowId) => `ev:${encodeStorageKeyComponent(workflowId)}:head`,
|
|
166
|
+
eventWatermark: (workflowId) => `ev:${encodeStorageKeyComponent(workflowId)}:watermark`,
|
|
167
|
+
fleetEventPrefix: () => "fleet-event:",
|
|
168
|
+
fleetEvent: (sequence) => `fleet-event:${String(sequence).padStart(10, "0")}`,
|
|
169
|
+
fleetEventTail: () => "fleet-event-tail",
|
|
170
|
+
fleetEventByWorkflowPrefix: (workflowId) => `fleet-event-by-workflow:${encodeStorageKeyComponent(workflowId)}:`,
|
|
171
|
+
fleetEventByWorkflow: (workflowId, sequence) => `fleet-event-by-workflow:${encodeStorageKeyComponent(workflowId)}:${String(sequence).padStart(10, "0")}`,
|
|
172
|
+
signal: (workflowId, name, id) => signalStorageKey(workflowId, name, id, SIGNAL_SORT_CLASS_NORMAL),
|
|
173
|
+
startSignal: (workflowId, name, id) => signalStorageKey(workflowId, name, id, SIGNAL_SORT_CLASS_START),
|
|
174
|
+
signalSequence: (workflowId) => `sigseq:v1:${encodeStorageKeyComponent(workflowId)}`,
|
|
175
|
+
signalAcceptedResponsePrefix: (workflowId) => `sigres:v1:${encodeStorageKeyComponent(workflowId)}:`,
|
|
176
|
+
signalAcceptedResponse: (workflowId, name, signalId) => `sigres:v1:${encodeStorageKeyComponent(workflowId)}:${encodeStorageKeyComponent(name)}:${encodeStorageKeyComponent(signalId)}`,
|
|
177
|
+
deadline: (deadline, workflowId) => `wf-deadline:${formatSortableTimestamp(deadline)}:${encodeStorageKeyComponent(workflowId)}`,
|
|
178
|
+
terminalCleanup: (fireAt, timerId) => `wf-cleanup:${formatSortableTimestamp(fireAt)}:${encodeStorageKeyComponent(timerId)}`,
|
|
179
|
+
teardownTimer: (fireAt, timerId) => `wf-teardown:${formatSortableTimestamp(fireAt)}:${encodeStorageKeyComponent(timerId)}`,
|
|
180
|
+
delayedStart: (startAt, workflowId) => `wf-delayed:${formatSortableTimestamp(startAt)}:${encodeStorageKeyComponent(workflowId)}`,
|
|
181
|
+
terminalWorkflowPrefix: () => "wf-terminal:",
|
|
182
|
+
terminalWorkflow: (updatedAt, workflowId) => `wf-terminal:${formatSortableTimestamp(updatedAt)}:${encodeStorageKeyComponent(workflowId)}`,
|
|
183
|
+
attribute: (workflowId) => `attr:${encodeStorageKeyComponent(workflowId)}`,
|
|
184
|
+
attributeIndex: (attributeName, encodedValue, workflowId) => `idx:${attributeName}:${encodedValue}:${encodeStorageKeyComponent(workflowId)}`,
|
|
185
|
+
tagIndex: (tag, workflowId) => `tag:${encodeStorageKeyComponent(tag)}:${encodeStorageKeyComponent(workflowId)}`,
|
|
186
|
+
updatePrefix: (workflowId) => `upd:${encodeStorageKeyComponent(workflowId)}:`,
|
|
187
|
+
update: (workflowId, updateId) => `upd:${encodeStorageKeyComponent(workflowId)}:${updateId}`,
|
|
188
|
+
updateResponse: (updateId) => `upr:${updateId}`,
|
|
189
|
+
updateIdempotency: (workflowId, key) => `upk:${encodeStorageKeyComponent(workflowId)}:${key}`,
|
|
190
|
+
startIdempotency: (key) => `start-idem:${encodeStorageKeyComponent(key)}`,
|
|
191
|
+
startIdempotencySignalId: (key) => `start-idem:${key}`,
|
|
192
|
+
livenessPrefix: () => "liveness:",
|
|
193
|
+
liveness: (instanceId) => `liveness:${encodeStorageKeyComponent(instanceId)}`,
|
|
194
|
+
leasePrefix: () => "lease:",
|
|
195
|
+
leaseEpoch: () => "lease:epoch",
|
|
196
|
+
leaseHolder: () => "lease:holder",
|
|
197
|
+
...OWNERSHIP_CLAIM_KEYS,
|
|
198
|
+
budget: (namespace, period, date) => `budget:${namespace}:${period}:${date}`,
|
|
199
|
+
review: (workflowId, reviewId) => `review:${encodeStorageKeyComponent(workflowId)}:${reviewId}`,
|
|
200
|
+
workflowHeaders: (workflowId) => `wf-headers:${encodeStorageKeyComponent(workflowId)}`,
|
|
201
|
+
childCancellationPrefix: (workflowId) => `child-cancel:${encodeStorageKeyComponent(workflowId)}:`,
|
|
202
|
+
childCancellation: (workflowId, childWorkflowId) => `child-cancel:${encodeStorageKeyComponent(workflowId)}:${encodeStorageKeyComponent(childWorkflowId)}`,
|
|
203
|
+
childWorkflowByParentPrefix: (parentWorkflowId, parentWorkflowExecutionToken) => `child-by-parent:${encodeStorageKeyComponent(parentWorkflowId)}:${parentWorkflowExecutionToken === undefined ? "" : `${encodeStorageKeyComponent(parentWorkflowExecutionToken)}:`}`,
|
|
204
|
+
childWorkflowByParent: (parentWorkflowId, parentWorkflowExecutionToken, childWorkflowId) => `child-by-parent:${encodeStorageKeyComponent(parentWorkflowId)}:${parentWorkflowExecutionToken === undefined ? "" : `${encodeStorageKeyComponent(parentWorkflowExecutionToken)}:`}${encodeStorageKeyComponent(childWorkflowId)}`,
|
|
205
|
+
terminalCleanupNeeded: (workflowId) => `wf-cleanup-needed:${encodeStorageKeyComponent(workflowId)}`,
|
|
206
|
+
workflowConcurrency: (workflowType, partitionKey) => `wf-concurrency:${encodeStorageKeyComponent(workflowType)}:${encodeStorageKeyComponent(partitionKey)}`,
|
|
207
|
+
workflowConcurrencyHolder: (workflowId) => `wf-concurrency-holder:${encodeStorageKeyComponent(workflowId)}`,
|
|
208
|
+
workflowHasServices: (workflowId) => `wf-has-services:${encodeStorageKeyComponent(workflowId)}`,
|
|
209
|
+
finalizerState: (workflowId) => `wf-finalizer-state:${encodeStorageKeyComponent(workflowId)}`,
|
|
210
|
+
teardownOwed: (workflowId) => `wf-teardown-needed:${encodeStorageKeyComponent(workflowId)}`,
|
|
211
|
+
teardownSucceeded: (workflowId) => `wf-teardown-succeeded:${encodeStorageKeyComponent(workflowId)}`,
|
|
212
|
+
teardownDeadLetter: (workflowId) => `wf-teardown-deadletter:${encodeStorageKeyComponent(workflowId)}`,
|
|
213
|
+
offload: (workflowId, key) => `offload:${encodeStorageKeyComponent(workflowId)}:${key}`,
|
|
214
|
+
archive: (workflowId, key) => `archive:${encodeStorageKeyComponent(workflowId)}:${key}`,
|
|
215
|
+
stateExecution: (ownerWorkflowId, key) => `state:execution:${encodeStorageKeyComponent(ownerWorkflowId)}:${encodeStorageKeyComponent(key)}`,
|
|
216
|
+
stateWorkflow: (workflowType, key) => `state:workflow-scope:${DEFAULT_SCOPE}:${encodeStorageKeyComponent(workflowType)}:${encodeStorageKeyComponent(key)}`,
|
|
217
|
+
streamChunkPrefix: (workflowId, key) => `blob:${encodeStorageKeyComponent(workflowId)}:${key}:chunk:`,
|
|
218
|
+
streamChunk: (workflowId, key, chunkIndex) => `blob:${encodeStorageKeyComponent(workflowId)}:${key}:chunk:${String(chunkIndex).padStart(10, "0")}`,
|
|
219
|
+
streamTail: (workflowId, key) => `blob:${encodeStorageKeyComponent(workflowId)}:${key}:tail`,
|
|
220
|
+
streamMetadata: (workflowId, key) => `blob:${encodeStorageKeyComponent(workflowId)}:${key}:meta`,
|
|
221
|
+
budgetCharged: (operationId) => `budget-charged:${operationId}`,
|
|
222
|
+
toolEffect: (workflowId, agentId, semanticHash) => `tool-effect:${encodeStorageKeyComponent(workflowId)}:${agentId}:${semanticHash}`,
|
|
223
|
+
workflowVisibilityStatus: (status, workflowId) => `wf-idx-status:${encodeStorageKeyComponent(status)}:${encodeStorageKeyComponent(workflowId)}`,
|
|
224
|
+
workflowVisibilityType: (type, workflowId) => `wf-idx-type:${encodeStorageKeyComponent(type)}:${encodeStorageKeyComponent(workflowId)}`,
|
|
225
|
+
workflowVisibilityCreated: (createdAt, workflowId) => `wf-idx-created:${formatSortableTimestamp(createdAt)}:${encodeStorageKeyComponent(workflowId)}`,
|
|
226
|
+
workflowVisibilityUpdated: (updatedAt, workflowId) => `wf-idx-updated:${formatSortableTimestamp(updatedAt)}:${encodeStorageKeyComponent(workflowId)}`,
|
|
227
|
+
workflowVisibilityDeadline: (deadline, workflowId) => `wf-idx-deadline:${formatSortableTimestamp(deadline)}:${encodeStorageKeyComponent(workflowId)}`,
|
|
228
|
+
workflowVisibilityManifest: (workflowId) => `wf-idx-manifest:${encodeStorageKeyComponent(workflowId)}`,
|
|
229
|
+
workflowVisibilityMetaVersion: () => "wf-idx-meta:version",
|
|
230
|
+
workflowVisibilityMetaBuiltAt: () => "wf-idx-meta:built-at",
|
|
231
|
+
workflowVisibilityMetaCursor: () => "wf-idx-meta:cursor"
|
|
232
|
+
};
|
|
120
233
|
|
|
121
234
|
// src/storage/conditional-batch-body.ts
|
|
122
235
|
function runConditionalBatchBody(conditions, operations, handlers) {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var i=import.meta.require,t=(F,X,Y)=>{if(X!=null){if(typeof X!=="object"&&typeof X!=="function")throw TypeError('Object expected to be assigned to "using" declaration');let $;if(Y)$=X[Symbol.asyncDispose];if($===void 0)$=X[Symbol.dispose];if(typeof $!=="function")throw TypeError("Object not disposable");F.push([Y,$,X])}else if(Y)F.push([Y]);return X},r=(F,X,Y)=>{let $=(j)=>X=Y?new SuppressedError(j,X,"An error was suppressed during disposal"):(Y=!0,j),V=(j)=>{while(j=F.pop())try{var K=j[1]&&j[1].call(j[2]);if(j[0])return Promise.resolve(K).then(V,(C)=>($(C),V()))}catch(C){$(C)}if(Y)throw X};return V()};function D(F,X,Y){if(!F.capabilities()[X])throw Error(`Feature "${Y}" requires storage capability "${X}", but this storage backend does not provide it.`)}function g(F){let X=F.capabilities(),Y=[];if(X.persistence!=="local"&&X.persistence!=="remote")Y.push(`persistence must be "local" or "remote" (got "${X.persistence}")`);if(X.readAfterWrite!=="linearizable")Y.push(`readAfterWrite must be "linearizable" (got "${X.readAfterWrite}")`);if(X.scanConsistency!=="snapshot")Y.push(`scanConsistency must be "snapshot" (got "${X.scanConsistency}")`);if(!X.atomicBatch)Y.push("atomicBatch must be true");if(!X.conditionalBatch)Y.push("conditionalBatch must be true");if(Y.length>0)throw Error(`Storage is not durable enough for recovery: ${Y.join("; ")}.`)}var G="default";async function M(F,X){return await F.get(X)!==null}async function*q(F,X,Y){for await(let[$]of F.scan(X,Y))yield $}async function N(F,X){let Y=0;for await(let $ of q(F,X))Y++;return Y}async function H(F,X){let Y=[];for await(let $ of q(F,X))Y.push({type:"delete",key:$});if(Y.length===0)return 0;return await F.batch(Y),Y.length}async function XF(F,X,Y){let $=[];for await(let V of q(F,X,Y))$.push({type:"delete",key:V});if($.length===0)return 0;return await F.batch($),$.length}var u=["actrec:","archive:","async-act:","attr:","audit:bulk:","blob:","budget:","budget-charged:","child-by-parent:","ev:","fleet-event-by-workflow:","fleet-event:","fleet-event-tail","idx:","lease:","liveness:","offload:","op:","review:","schedule:","schedule-due:","schedule-run-by-schedule:","schedule-run-link:","schedule-run:","sig:","sigres:","sigseq:","start-idem:","state:","tag:","tool-effect:","upd:","upk:","upr:","wf:","wf-cleanup:","wf-cleanup-needed:","wf-concurrency:","wf-concurrency-holder:","wf-deadline:","wf-delayed:","wf-finalizer-state:","wf-has-services:","wf-headers:","wf-idx-","wf-teardown:","wf-teardown-deadletter:","wf-teardown-needed:","wf-teardown-succeeded:","wf-terminal:"];var L=1e4,QF=1e4;class v extends Error{code="StorageBatchOperationLimitExceededError";cap=L;count;target;constructor(F,X){super(`${F} count ${X} exceeds MAX_BATCH_OPERATIONS (${L}).`);this.name="StorageBatchOperationLimitExceededError",this.target=F,this.count=X}}function z(F,X){if(X>L)throw new v(F,X)}function UF(F){return F.length>0?F.slice(0,-1)+String.fromCharCode(F.charCodeAt(F.length-1)+1):"\xFF"}function VF(F,X={}){if(X.gt!==void 0&&F<=X.gt)return!1;if(X.gte!==void 0&&F<X.gte)return!1;if(X.lt!==void 0&&F>=X.lt)return!1;if(X.lte!==void 0&&F>X.lte)return!1;return!0}function PF(F,X){if(F===null||X===null)return F===X;if(F.byteLength!==X.byteLength)return!1;for(let Y=0;Y<F.byteLength;Y++)if(F[Y]!==X[Y])return!1;return!0}async function qF(F,X){if(F.has)return F.has(X);return M(F,X)}function zF(F,X,Y){if(F.keys)return F.keys(X,Y);return q(F,X,Y)}async function WF(F,X){if(F.count)return F.count(X);return N(F,X)}async function CF(F,X){if(F.deletePrefix)return F.deletePrefix(X);return H(F,X)}async function DF(F,X){z("batch operations",X.length),await F.batch(X)}async function GF(F,X,Y){if(z("conditionalBatch conditions",X.length),z("conditionalBatch operations",Y.length),D(F,"conditionalBatch","storageConditionalBatch"),!F.conditionalBatch)throw Error("This storage backend reports conditionalBatch capability but does not implement the conditionalBatch() method.");return F.conditionalBatch(X,Y)}function J(F){return encodeURIComponent(F)}function LF(F){return decodeURIComponent(F)}function SF(F){try{return decodeURIComponent(F)}catch{return null}}var Q=(F)=>String(F).padStart(16,"0"),f="0",p="1",B=(F,X,Y,$)=>`sig:${J(F)}:${J(X)}:${$}:${J(Y)}`,ZF={workflow:(F)=>`wf:${J(F)}`,checkpoint:(F)=>`wf:${J(F)}:ckpt`,checkpointHistory:(F,X)=>`wf:${J(F)}:ckpt:${String(X).padStart(10,"0")}`,timelinePrefix:(F)=>`wf:${J(F)}:timeline:`,timeline:(F,X)=>`wf:${J(F)}:timeline:${String(X).padStart(10,"0")}`,schedule:(F)=>`schedule:${J(F)}`,scheduleTick:(F,X)=>`schedule-due:${String(F).padStart(16,"0")}:${J(X)}`,scheduleRun:(F)=>`schedule-run:${J(F)}`,scheduleRunLink:(F)=>`schedule-run-link:${J(F)}`,scheduleRunBySchedulePrefix:(F)=>`schedule-run-by-schedule:${J(F)}:`,scheduleRunBySchedule:(F,X)=>`schedule-run-by-schedule:${J(F)}:${J(X)}`,operation:(F,X,Y)=>`op:${F}:${Q(X)}:${Y}`,operationInflight:(F)=>`op:inflight:${F}`,operationQueued:(F)=>`op:queued:${F}`,operationResolved:(F)=>`op:resolved:${F}`,bulkOperationAuditPrefix:()=>"audit:bulk:",bulkOperationAudit:(F,X,Y)=>`audit:bulk:${Q(F)}:${J(X)}:${J(Y)}`,operationResolvedByTimePrefix:()=>"op:resolved-by-time:",operationResolvedByTime:(F,X)=>`op:resolved-by-time:${Q(F)}:${J(X)}`,asyncActivity:(F,X)=>`async-act:v1:${J(F)}:${J(X)}`,asyncActivityResolution:(F,X)=>`async-act:v1:${J(F)}:${J(X)}:resolution`,activityReconciliationPrefix:(F)=>`actrec:v1:${J(F)}:`,activityReconciliation:(F,X,Y)=>`actrec:v1:${J(F)}:${J(X)}:${Y}`,eventPrefix:(F)=>`ev:${J(F)}:`,event:(F,X)=>`ev:${J(F)}:${String(X).padStart(10,"0")}`,eventHead:(F)=>`ev:${J(F)}:head`,eventWatermark:(F)=>`ev:${J(F)}:watermark`,fleetEventPrefix:()=>"fleet-event:",fleetEvent:(F)=>`fleet-event:${String(F).padStart(10,"0")}`,fleetEventTail:()=>"fleet-event-tail",fleetEventByWorkflowPrefix:(F)=>`fleet-event-by-workflow:${J(F)}:`,fleetEventByWorkflow:(F,X)=>`fleet-event-by-workflow:${J(F)}:${String(X).padStart(10,"0")}`,signal:(F,X,Y)=>B(F,X,Y,p),startSignal:(F,X,Y)=>B(F,X,Y,f),signalSequence:(F)=>`sigseq:v1:${J(F)}`,signalAcceptedResponsePrefix:(F)=>`sigres:v1:${J(F)}:`,signalAcceptedResponse:(F,X,Y)=>`sigres:v1:${J(F)}:${J(X)}:${J(Y)}`,deadline:(F,X)=>`wf-deadline:${Q(F)}:${J(X)}`,terminalCleanup:(F,X)=>`wf-cleanup:${Q(F)}:${J(X)}`,teardownTimer:(F,X)=>`wf-teardown:${Q(F)}:${J(X)}`,delayedStart:(F,X)=>`wf-delayed:${Q(F)}:${J(X)}`,terminalWorkflowPrefix:()=>"wf-terminal:",terminalWorkflow:(F,X)=>`wf-terminal:${Q(F)}:${J(X)}`,attribute:(F)=>`attr:${J(F)}`,attributeIndex:(F,X,Y)=>`idx:${F}:${X}:${J(Y)}`,tagIndex:(F,X)=>`tag:${J(F)}:${J(X)}`,updatePrefix:(F)=>`upd:${J(F)}:`,update:(F,X)=>`upd:${J(F)}:${X}`,updateResponse:(F)=>`upr:${F}`,updateIdempotency:(F,X)=>`upk:${J(F)}:${X}`,startIdempotency:(F)=>`start-idem:${J(F)}`,startIdempotencySignalId:(F)=>`start-idem:${F}`,livenessPrefix:()=>"liveness:",liveness:(F)=>`liveness:${J(F)}`,leasePrefix:()=>"lease:",leaseEpoch:()=>"lease:epoch",leaseHolder:()=>"lease:holder",budget:(F,X,Y)=>`budget:${F}:${X}:${Y}`,review:(F,X)=>`review:${J(F)}:${X}`,workflowHeaders:(F)=>`wf-headers:${J(F)}`,childCancellationPrefix:(F)=>`child-cancel:${J(F)}:`,childCancellation:(F,X)=>`child-cancel:${J(F)}:${J(X)}`,childWorkflowByParentPrefix:(F,X)=>`child-by-parent:${J(F)}:${X===void 0?"":`${J(X)}:`}`,childWorkflowByParent:(F,X,Y)=>`child-by-parent:${J(F)}:${X===void 0?"":`${J(X)}:`}${J(Y)}`,terminalCleanupNeeded:(F)=>`wf-cleanup-needed:${J(F)}`,workflowConcurrency:(F,X)=>`wf-concurrency:${J(F)}:${J(X)}`,workflowConcurrencyHolder:(F)=>`wf-concurrency-holder:${J(F)}`,workflowHasServices:(F)=>`wf-has-services:${J(F)}`,finalizerState:(F)=>`wf-finalizer-state:${J(F)}`,teardownOwed:(F)=>`wf-teardown-needed:${J(F)}`,teardownSucceeded:(F)=>`wf-teardown-succeeded:${J(F)}`,teardownDeadLetter:(F)=>`wf-teardown-deadletter:${J(F)}`,offload:(F,X)=>`offload:${J(F)}:${X}`,archive:(F,X)=>`archive:${J(F)}:${X}`,stateExecution:(F,X)=>`state:execution:${J(F)}:${J(X)}`,stateWorkflow:(F,X)=>`state:workflow-scope:${G}:${J(F)}:${J(X)}`,streamChunkPrefix:(F,X)=>`blob:${J(F)}:${X}:chunk:`,streamChunk:(F,X,Y)=>`blob:${J(F)}:${X}:chunk:${String(Y).padStart(10,"0")}`,streamTail:(F,X)=>`blob:${J(F)}:${X}:tail`,streamMetadata:(F,X)=>`blob:${J(F)}:${X}:meta`,budgetCharged:(F)=>`budget-charged:${F}`,toolEffect:(F,X,Y)=>`tool-effect:${J(F)}:${X}:${Y}`,workflowVisibilityStatus:(F,X)=>`wf-idx-status:${J(F)}:${J(X)}`,workflowVisibilityType:(F,X)=>`wf-idx-type:${J(F)}:${J(X)}`,workflowVisibilityCreated:(F,X)=>`wf-idx-created:${Q(F)}:${J(X)}`,workflowVisibilityUpdated:(F,X)=>`wf-idx-updated:${Q(F)}:${J(X)}`,workflowVisibilityDeadline:(F,X)=>`wf-idx-deadline:${Q(F)}:${J(X)}`,workflowVisibilityManifest:(F)=>`wf-idx-manifest:${J(F)}`,workflowVisibilityMetaVersion:()=>"wf-idx-meta:version",workflowVisibilityMetaBuiltAt:()=>"wf-idx-meta:built-at",workflowVisibilityMetaCursor:()=>"wf-idx-meta:cursor"};var P;function I(){if(P&&"bun"in P)return P.bun;return globalThis.Bun}function E(){return typeof I()<"u"}function k(){if(P&&"process"in P)return P.process;return globalThis.process}function O(F){let Y=k()?.getBuiltinModule;if(typeof Y!=="function")return;return Y(F)}function x(){let F=O("node:zlib");if(!F)throw Error("gzip/gunzip require Bun or Node 22.5+ (process.getBuiltinModule). "+"Not available in browser or edge runtimes \u2014 use CompressionStream directly.");return F}function A(F){if(E())return new Uint8Array(Bun.gzipSync(new Uint8Array(F)));return new Uint8Array(x().gzipSync(F))}function h(F){if(E())return new Uint8Array(Bun.gunzipSync(new Uint8Array(F)));return new Uint8Array(x().gunzipSync(F))}function T(){return O("node:zlib")}function R(){let F=T();if(!F)throw Error("Brotli compression requires Bun or Node 22.5+ with process.getBuiltinModule support. Use gzip compression for browser/edge runtimes.");return F}function w(F){return new Uint8Array(R().brotliCompressSync(F))}function n(F){return new Uint8Array(R().brotliDecompressSync(F))}var W=193,S=0,b=1,c=2,U=2;function y(F){return l(F)}function l(F){switch(F){case"gzip":return{algorithm:"gzip",compress(X){return A(X)}};case"brotli":return{algorithm:"brotli",compress(X){return w(X)}};case"none":return{algorithm:"none",compress(X){return X}}}}async function Z(F,X,Y){if(F.length<Y||X.algorithm==="none"){let K=new Uint8Array(F.length+U);return K[0]=W,K[1]=S,K.set(F,U),K}let $=await X.compress(F);if($.length+U>=F.length+U){let K=new Uint8Array(F.length+U);return K[0]=W,K[1]=S,K.set(F,U),K}let V=X.algorithm==="gzip"?b:c,j=new Uint8Array($.length+U);return j[0]=W,j[1]=V,j.set($,U),j}async function _(F){if(F.length<U)throw Error("Compression payload missing 2-byte header.");if(F[0]!==W)throw Error("Compression payload missing magic byte 0xC1.");let X=F[1],Y=F.slice(U);switch(X){case S:return Y;case b:return h(Y);case c:return n(Y);default:throw Error(`Compression payload uses unsupported algorithm byte 0x${X.toString(16).padStart(2,"0")}.`)}}var s=4096,d="gzip";function m(F){return{threshold:F?.threshold??s,algorithm:F?.algorithm??d}}class a{#F;#X;#J;constructor(F,X){this.#F=F;let Y=m(X);if(this.#X=y(Y.algorithm),this.#J=Y.threshold,F.query){let $=F.query.bind(F);Object.defineProperty(this,"query",{value:$,enumerable:!0,configurable:!0})}}capabilities(){let F=this.#F.capabilities();return{persistence:F.persistence,readAfterWrite:F.readAfterWrite,scanConsistency:F.scanConsistency,atomicBatch:F.atomicBatch,conditionalBatch:!1,boundedRangeDelete:!1}}async get(F){let X=await this.#F.get(F);if(!X)return null;return _(X)}async put(F,X){let Y=await Z(X,this.#X,this.#J);return this.#F.put(F,Y)}async delete(F){return this.#F.delete(F)}async*scan(F,X){for await(let[Y,$]of this.#F.scan(F,X))yield[Y,await _($)]}async batch(F){z("batch operations",F.length);let X=await Promise.all(F.map(async(Y)=>{if(Y.type==="put")return{type:"put",key:Y.key,value:await Z(Y.value,this.#X,this.#J)};return Y}));return this.#F.batch(X)}[Symbol.dispose](){this.#F[Symbol.dispose]()}}export{a as CompressedStorage};
|
|
2
|
+
var r=import.meta.require;function L(F,X,$){if(!F.capabilities()[X])throw Error(`Feature "${$}" requires storage capability "${X}", but this storage backend does not provide it.`)}function g(F){let X=F.capabilities(),$=[];if(X.persistence!=="local"&&X.persistence!=="remote")$.push(`persistence must be "local" or "remote" (got "${X.persistence}")`);if(X.readAfterWrite!=="linearizable")$.push(`readAfterWrite must be "linearizable" (got "${X.readAfterWrite}")`);if(X.scanConsistency!=="snapshot")$.push(`scanConsistency must be "snapshot" (got "${X.scanConsistency}")`);if(!X.atomicBatch)$.push("atomicBatch must be true");if(!X.conditionalBatch)$.push("conditionalBatch must be true");if($.length>0)throw Error(`Storage is not durable enough for recovery: ${$.join("; ")}.`)}var Z="default";async function C(F,X){return await F.get(X)!==null}async function*P(F,X,$){for await(let[j]of F.scan(X,$))yield j}async function H(F,X){let $=0;for await(let j of P(F,X))$++;return $}async function N(F,X){let $=[];for await(let j of P(F,X))$.push({type:"delete",key:j});if($.length===0)return 0;return await F.batch($),$.length}async function XF(F,X,$){let j=[];for await(let W of P(F,X,$))j.push({type:"delete",key:W});if(j.length===0)return 0;return await F.batch(j),j.length}function Y(F){return encodeURIComponent(F)}function u(F){return decodeURIComponent(F)}function f(F){try{return decodeURIComponent(F)}catch{return null}}var S={workflowOwnerEpoch:(F)=>`wf-owner-epoch:${Y(F)}`,workflowOwnerHolder:(F)=>`wf-owner-holder:${Y(F)}`,ownershipModeMarker:()=>"ownership-mode-marker"};var I=["actrec:","archive:","async-act:","attr:","audit:bulk:","blob:","budget:","budget-charged:","child-by-parent:","ev:","fleet-event-by-workflow:","fleet-event:","fleet-event-tail","idx:","lease:","liveness:","offload:","ownership-mode-marker","op:","review:","schedule:","schedule-due:","schedule-run-by-schedule:","schedule-run-link:","schedule-run:","sig:","sigres:","sigseq:","start-idem:","state:","tag:","tool-effect:","upd:","upk:","upr:","wf:","wf-cleanup:","wf-cleanup-needed:","wf-concurrency:","wf-concurrency-holder:","wf-deadline:","wf-delayed:","wf-finalizer-state:","wf-has-services:","wf-headers:","wf-idx-","wf-owner-epoch:","wf-owner-holder:","wf-teardown:","wf-teardown-deadletter:","wf-teardown-needed:","wf-teardown-succeeded:","wf-terminal:"];var _=1e4,zF=1e4;class E extends Error{code="StorageBatchOperationLimitExceededError";cap=_;count;target;constructor(F,X){super(`${F} count ${X} exceeds MAX_BATCH_OPERATIONS (${_}).`);this.name="StorageBatchOperationLimitExceededError",this.target=F,this.count=X}}function K(F,X){if(X>_)throw new E(F,X)}function WF(F){return F.length>0?F.slice(0,-1)+String.fromCharCode(F.charCodeAt(F.length-1)+1):"\xFF"}function LF(F,X={}){if(X.gt!==void 0&&F<=X.gt)return!1;if(X.gte!==void 0&&F<X.gte)return!1;if(X.lt!==void 0&&F>=X.lt)return!1;if(X.lte!==void 0&&F>X.lte)return!1;return!0}function ZF(F,X){if(F===null||X===null)return F===X;if(F.byteLength!==X.byteLength)return!1;for(let $=0;$<F.byteLength;$++)if(F[$]!==X[$])return!1;return!0}async function _F(F,X){if(F.has)return F.has(X);return C(F,X)}function GF(F,X,$){if(F.keys)return F.keys(X,$);return P(F,X,$)}async function MF(F,X){if(F.count)return F.count(X);return H(F,X)}async function DF(F,X){if(F.deletePrefix)return F.deletePrefix(X);return N(F,X)}async function CF(F,X){K("batch operations",X.length),await F.batch(X)}async function HF(F,X,$){if(K("conditionalBatch conditions",X.length),K("conditionalBatch operations",$.length),L(F,"conditionalBatch","storageConditionalBatch"),!F.conditionalBatch)throw Error("This storage backend reports conditionalBatch capability but does not implement the conditionalBatch() method.");return F.conditionalBatch(X,$)}var J=(F)=>String(F).padStart(16,"0"),p="0",k="1",B=(F,X,$,j)=>`sig:${Y(F)}:${Y(X)}:${j}:${Y($)}`,NF={workflow:(F)=>`wf:${Y(F)}`,checkpoint:(F)=>`wf:${Y(F)}:ckpt`,checkpointHistory:(F,X)=>`wf:${Y(F)}:ckpt:${String(X).padStart(10,"0")}`,timelinePrefix:(F)=>`wf:${Y(F)}:timeline:`,timeline:(F,X)=>`wf:${Y(F)}:timeline:${String(X).padStart(10,"0")}`,schedule:(F)=>`schedule:${Y(F)}`,scheduleTick:(F,X)=>`schedule-due:${String(F).padStart(16,"0")}:${Y(X)}`,scheduleRun:(F)=>`schedule-run:${Y(F)}`,scheduleRunLink:(F)=>`schedule-run-link:${Y(F)}`,scheduleRunBySchedulePrefix:(F)=>`schedule-run-by-schedule:${Y(F)}:`,scheduleRunBySchedule:(F,X)=>`schedule-run-by-schedule:${Y(F)}:${Y(X)}`,operation:(F,X,$)=>`op:${F}:${J(X)}:${$}`,operationInflight:(F)=>`op:inflight:${F}`,operationQueued:(F)=>`op:queued:${F}`,operationResolved:(F)=>`op:resolved:${F}`,bulkOperationAuditPrefix:()=>"audit:bulk:",bulkOperationAudit:(F,X,$)=>`audit:bulk:${J(F)}:${Y(X)}:${Y($)}`,operationResolvedByTimePrefix:()=>"op:resolved-by-time:",operationResolvedByTime:(F,X)=>`op:resolved-by-time:${J(F)}:${Y(X)}`,asyncActivity:(F,X)=>`async-act:v1:${Y(F)}:${Y(X)}`,asyncActivityResolution:(F,X)=>`async-act:v1:${Y(F)}:${Y(X)}:resolution`,activityReconciliationPrefix:(F)=>`actrec:v1:${Y(F)}:`,activityReconciliation:(F,X,$)=>`actrec:v1:${Y(F)}:${Y(X)}:${$}`,eventPrefix:(F)=>`ev:${Y(F)}:`,event:(F,X)=>`ev:${Y(F)}:${String(X).padStart(10,"0")}`,eventHead:(F)=>`ev:${Y(F)}:head`,eventWatermark:(F)=>`ev:${Y(F)}:watermark`,fleetEventPrefix:()=>"fleet-event:",fleetEvent:(F)=>`fleet-event:${String(F).padStart(10,"0")}`,fleetEventTail:()=>"fleet-event-tail",fleetEventByWorkflowPrefix:(F)=>`fleet-event-by-workflow:${Y(F)}:`,fleetEventByWorkflow:(F,X)=>`fleet-event-by-workflow:${Y(F)}:${String(X).padStart(10,"0")}`,signal:(F,X,$)=>B(F,X,$,k),startSignal:(F,X,$)=>B(F,X,$,p),signalSequence:(F)=>`sigseq:v1:${Y(F)}`,signalAcceptedResponsePrefix:(F)=>`sigres:v1:${Y(F)}:`,signalAcceptedResponse:(F,X,$)=>`sigres:v1:${Y(F)}:${Y(X)}:${Y($)}`,deadline:(F,X)=>`wf-deadline:${J(F)}:${Y(X)}`,terminalCleanup:(F,X)=>`wf-cleanup:${J(F)}:${Y(X)}`,teardownTimer:(F,X)=>`wf-teardown:${J(F)}:${Y(X)}`,delayedStart:(F,X)=>`wf-delayed:${J(F)}:${Y(X)}`,terminalWorkflowPrefix:()=>"wf-terminal:",terminalWorkflow:(F,X)=>`wf-terminal:${J(F)}:${Y(X)}`,attribute:(F)=>`attr:${Y(F)}`,attributeIndex:(F,X,$)=>`idx:${F}:${X}:${Y($)}`,tagIndex:(F,X)=>`tag:${Y(F)}:${Y(X)}`,updatePrefix:(F)=>`upd:${Y(F)}:`,update:(F,X)=>`upd:${Y(F)}:${X}`,updateResponse:(F)=>`upr:${F}`,updateIdempotency:(F,X)=>`upk:${Y(F)}:${X}`,startIdempotency:(F)=>`start-idem:${Y(F)}`,startIdempotencySignalId:(F)=>`start-idem:${F}`,livenessPrefix:()=>"liveness:",liveness:(F)=>`liveness:${Y(F)}`,leasePrefix:()=>"lease:",leaseEpoch:()=>"lease:epoch",leaseHolder:()=>"lease:holder",...S,budget:(F,X,$)=>`budget:${F}:${X}:${$}`,review:(F,X)=>`review:${Y(F)}:${X}`,workflowHeaders:(F)=>`wf-headers:${Y(F)}`,childCancellationPrefix:(F)=>`child-cancel:${Y(F)}:`,childCancellation:(F,X)=>`child-cancel:${Y(F)}:${Y(X)}`,childWorkflowByParentPrefix:(F,X)=>`child-by-parent:${Y(F)}:${X===void 0?"":`${Y(X)}:`}`,childWorkflowByParent:(F,X,$)=>`child-by-parent:${Y(F)}:${X===void 0?"":`${Y(X)}:`}${Y($)}`,terminalCleanupNeeded:(F)=>`wf-cleanup-needed:${Y(F)}`,workflowConcurrency:(F,X)=>`wf-concurrency:${Y(F)}:${Y(X)}`,workflowConcurrencyHolder:(F)=>`wf-concurrency-holder:${Y(F)}`,workflowHasServices:(F)=>`wf-has-services:${Y(F)}`,finalizerState:(F)=>`wf-finalizer-state:${Y(F)}`,teardownOwed:(F)=>`wf-teardown-needed:${Y(F)}`,teardownSucceeded:(F)=>`wf-teardown-succeeded:${Y(F)}`,teardownDeadLetter:(F)=>`wf-teardown-deadletter:${Y(F)}`,offload:(F,X)=>`offload:${Y(F)}:${X}`,archive:(F,X)=>`archive:${Y(F)}:${X}`,stateExecution:(F,X)=>`state:execution:${Y(F)}:${Y(X)}`,stateWorkflow:(F,X)=>`state:workflow-scope:${Z}:${Y(F)}:${Y(X)}`,streamChunkPrefix:(F,X)=>`blob:${Y(F)}:${X}:chunk:`,streamChunk:(F,X,$)=>`blob:${Y(F)}:${X}:chunk:${String($).padStart(10,"0")}`,streamTail:(F,X)=>`blob:${Y(F)}:${X}:tail`,streamMetadata:(F,X)=>`blob:${Y(F)}:${X}:meta`,budgetCharged:(F)=>`budget-charged:${F}`,toolEffect:(F,X,$)=>`tool-effect:${Y(F)}:${X}:${$}`,workflowVisibilityStatus:(F,X)=>`wf-idx-status:${Y(F)}:${Y(X)}`,workflowVisibilityType:(F,X)=>`wf-idx-type:${Y(F)}:${Y(X)}`,workflowVisibilityCreated:(F,X)=>`wf-idx-created:${J(F)}:${Y(X)}`,workflowVisibilityUpdated:(F,X)=>`wf-idx-updated:${J(F)}:${Y(X)}`,workflowVisibilityDeadline:(F,X)=>`wf-idx-deadline:${J(F)}:${Y(X)}`,workflowVisibilityManifest:(F)=>`wf-idx-manifest:${Y(F)}`,workflowVisibilityMetaVersion:()=>"wf-idx-meta:version",workflowVisibilityMetaBuiltAt:()=>"wf-idx-meta:built-at",workflowVisibilityMetaCursor:()=>"wf-idx-meta:cursor"};var V;function w(){if(V&&"bun"in V)return V.bun;return globalThis.Bun}function v(){return typeof w()<"u"}function l(){if(V&&"process"in V)return V.process;return globalThis.process}function O(F){let $=l()?.getBuiltinModule;if(typeof $!=="function")return;return $(F)}function x(){let F=O("node:zlib");if(!F)throw Error("gzip/gunzip require Bun or Node 22.5+ (process.getBuiltinModule). "+"Not available in browser or edge runtimes \u2014 use CompressionStream directly.");return F}function A(F){if(v())return new Uint8Array(Bun.gzipSync(new Uint8Array(F)));return new Uint8Array(x().gzipSync(F))}function T(F){if(v())return new Uint8Array(Bun.gunzipSync(new Uint8Array(F)));return new Uint8Array(x().gunzipSync(F))}function R(){return O("node:zlib")}function b(){let F=R();if(!F)throw Error("Brotli compression requires Bun or Node 22.5+ with process.getBuiltinModule support. Use gzip compression for browser/edge runtimes.");return F}function n(F){return new Uint8Array(b().brotliCompressSync(F))}function s(F){return new Uint8Array(b().brotliDecompressSync(F))}var z=193,G=0,h=1,c=2,Q=2;function y(F){return d(F)}function d(F){switch(F){case"gzip":return{algorithm:"gzip",compress(X){return A(X)}};case"brotli":return{algorithm:"brotli",compress(X){return n(X)}};case"none":return{algorithm:"none",compress(X){return X}}}}async function M(F,X,$){if(F.length<$||X.algorithm==="none"){let U=new Uint8Array(F.length+Q);return U[0]=z,U[1]=G,U.set(F,Q),U}let j=await X.compress(F);if(j.length+Q>=F.length+Q){let U=new Uint8Array(F.length+Q);return U[0]=z,U[1]=G,U.set(F,Q),U}let W=X.algorithm==="gzip"?h:c,q=new Uint8Array(j.length+Q);return q[0]=z,q[1]=W,q.set(j,Q),q}async function D(F){if(F.length<Q)throw Error("Compression payload missing 2-byte header.");if(F[0]!==z)throw Error("Compression payload missing magic byte 0xC1.");let X=F[1],$=F.slice(Q);switch(X){case G:return $;case h:return T($);case c:return s($);default:throw Error(`Compression payload uses unsupported algorithm byte 0x${X.toString(16).padStart(2,"0")}.`)}}var a=4096,i="gzip";function m(F){return{threshold:F?.threshold??a,algorithm:F?.algorithm??i}}class t{#F;#X;#Y;constructor(F,X){this.#F=F;let $=m(X);if(this.#X=y($.algorithm),this.#Y=$.threshold,F.query){let j=F.query.bind(F);Object.defineProperty(this,"query",{value:j,enumerable:!0,configurable:!0})}}capabilities(){let F=this.#F.capabilities();return{persistence:F.persistence,readAfterWrite:F.readAfterWrite,scanConsistency:F.scanConsistency,atomicBatch:F.atomicBatch,conditionalBatch:!1,boundedRangeDelete:!1}}async get(F){let X=await this.#F.get(F);if(!X)return null;return D(X)}async put(F,X){let $=await M(X,this.#X,this.#Y);return this.#F.put(F,$)}async delete(F){return this.#F.delete(F)}async*scan(F,X){for await(let[$,j]of this.#F.scan(F,X))yield[$,await D(j)]}async batch(F){K("batch operations",F.length);let X=await Promise.all(F.map(async($)=>{if($.type==="put")return{type:"put",key:$.key,value:await M($.value,this.#X,this.#Y)};return $}));return this.#F.batch(X)}[Symbol.dispose](){this.#F[Symbol.dispose]()}}export{t as CompressedStorage};
|
package/dist/storage/index.d.ts
CHANGED
|
@@ -82,6 +82,43 @@ declare const exportedCopyTextKeyValueRowsToStorage: typeof copyTextKeyValueRows
|
|
|
82
82
|
* ```
|
|
83
83
|
*/
|
|
84
84
|
declare const exportedKeys: {
|
|
85
|
+
readonly budget: (namespace: string, period: string, date: string) => string;
|
|
86
|
+
readonly review: (workflowId: string, reviewId: string) => string;
|
|
87
|
+
readonly workflowHeaders: (workflowId: string) => string;
|
|
88
|
+
readonly childCancellationPrefix: (workflowId: string) => string;
|
|
89
|
+
readonly childCancellation: (workflowId: string, childWorkflowId: string) => string;
|
|
90
|
+
readonly childWorkflowByParentPrefix: (parentWorkflowId: string, parentWorkflowExecutionToken?: string) => string;
|
|
91
|
+
readonly childWorkflowByParent: (parentWorkflowId: string, parentWorkflowExecutionToken: string | undefined, childWorkflowId: string) => string;
|
|
92
|
+
readonly terminalCleanupNeeded: (workflowId: string) => string;
|
|
93
|
+
readonly workflowConcurrency: (workflowType: string, partitionKey: string) => string;
|
|
94
|
+
readonly workflowConcurrencyHolder: (workflowId: string) => string;
|
|
95
|
+
readonly workflowHasServices: (workflowId: string) => string;
|
|
96
|
+
readonly finalizerState: (workflowId: string) => string;
|
|
97
|
+
readonly teardownOwed: (workflowId: string) => string;
|
|
98
|
+
readonly teardownSucceeded: (workflowId: string) => string;
|
|
99
|
+
readonly teardownDeadLetter: (workflowId: string) => string;
|
|
100
|
+
readonly offload: (workflowId: string, key: string) => string;
|
|
101
|
+
readonly archive: (workflowId: string, key: string) => string;
|
|
102
|
+
readonly stateExecution: (ownerWorkflowId: string, key: string) => string;
|
|
103
|
+
readonly stateWorkflow: (workflowType: string, key: string) => string;
|
|
104
|
+
readonly streamChunkPrefix: (workflowId: string, key: string) => string;
|
|
105
|
+
readonly streamChunk: (workflowId: string, key: string, chunkIndex: number) => string;
|
|
106
|
+
readonly streamTail: (workflowId: string, key: string) => string;
|
|
107
|
+
readonly streamMetadata: (workflowId: string, key: string) => string;
|
|
108
|
+
readonly budgetCharged: (operationId: string) => string;
|
|
109
|
+
readonly toolEffect: (workflowId: string, agentId: string, semanticHash: string) => string;
|
|
110
|
+
readonly workflowVisibilityStatus: (status: string, workflowId: string) => string;
|
|
111
|
+
readonly workflowVisibilityType: (type: string, workflowId: string) => string;
|
|
112
|
+
readonly workflowVisibilityCreated: (createdAt: number, workflowId: string) => string;
|
|
113
|
+
readonly workflowVisibilityUpdated: (updatedAt: number, workflowId: string) => string;
|
|
114
|
+
readonly workflowVisibilityDeadline: (deadline: number, workflowId: string) => string;
|
|
115
|
+
readonly workflowVisibilityManifest: (workflowId: string) => string;
|
|
116
|
+
readonly workflowVisibilityMetaVersion: () => string;
|
|
117
|
+
readonly workflowVisibilityMetaBuiltAt: () => string;
|
|
118
|
+
readonly workflowVisibilityMetaCursor: () => string;
|
|
119
|
+
readonly workflowOwnerEpoch: (workflowId: string) => string;
|
|
120
|
+
readonly workflowOwnerHolder: (workflowId: string) => string;
|
|
121
|
+
readonly ownershipModeMarker: () => string;
|
|
85
122
|
readonly workflow: (id: string) => string;
|
|
86
123
|
readonly checkpoint: (id: string) => string;
|
|
87
124
|
readonly checkpointHistory: (id: string, step: number) => string;
|
|
@@ -139,40 +176,6 @@ declare const exportedKeys: {
|
|
|
139
176
|
readonly leasePrefix: () => string;
|
|
140
177
|
readonly leaseEpoch: () => string;
|
|
141
178
|
readonly leaseHolder: () => string;
|
|
142
|
-
readonly budget: (namespace: string, period: string, date: string) => string;
|
|
143
|
-
readonly review: (workflowId: string, reviewId: string) => string;
|
|
144
|
-
readonly workflowHeaders: (workflowId: string) => string;
|
|
145
|
-
readonly childCancellationPrefix: (workflowId: string) => string;
|
|
146
|
-
readonly childCancellation: (workflowId: string, childWorkflowId: string) => string;
|
|
147
|
-
readonly childWorkflowByParentPrefix: (parentWorkflowId: string, parentWorkflowExecutionToken?: string) => string;
|
|
148
|
-
readonly childWorkflowByParent: (parentWorkflowId: string, parentWorkflowExecutionToken: string | undefined, childWorkflowId: string) => string;
|
|
149
|
-
readonly terminalCleanupNeeded: (workflowId: string) => string;
|
|
150
|
-
readonly workflowConcurrency: (workflowType: string, partitionKey: string) => string;
|
|
151
|
-
readonly workflowConcurrencyHolder: (workflowId: string) => string;
|
|
152
|
-
readonly workflowHasServices: (workflowId: string) => string;
|
|
153
|
-
readonly finalizerState: (workflowId: string) => string;
|
|
154
|
-
readonly teardownOwed: (workflowId: string) => string;
|
|
155
|
-
readonly teardownSucceeded: (workflowId: string) => string;
|
|
156
|
-
readonly teardownDeadLetter: (workflowId: string) => string;
|
|
157
|
-
readonly offload: (workflowId: string, key: string) => string;
|
|
158
|
-
readonly archive: (workflowId: string, key: string) => string;
|
|
159
|
-
readonly stateExecution: (ownerWorkflowId: string, key: string) => string;
|
|
160
|
-
readonly stateWorkflow: (workflowType: string, key: string) => string;
|
|
161
|
-
readonly streamChunkPrefix: (workflowId: string, key: string) => string;
|
|
162
|
-
readonly streamChunk: (workflowId: string, key: string, chunkIndex: number) => string;
|
|
163
|
-
readonly streamTail: (workflowId: string, key: string) => string;
|
|
164
|
-
readonly streamMetadata: (workflowId: string, key: string) => string;
|
|
165
|
-
readonly budgetCharged: (operationId: string) => string;
|
|
166
|
-
readonly toolEffect: (workflowId: string, agentId: string, semanticHash: string) => string;
|
|
167
|
-
readonly workflowVisibilityStatus: (status: string, workflowId: string) => string;
|
|
168
|
-
readonly workflowVisibilityType: (type: string, workflowId: string) => string;
|
|
169
|
-
readonly workflowVisibilityCreated: (createdAt: number, workflowId: string) => string;
|
|
170
|
-
readonly workflowVisibilityUpdated: (updatedAt: number, workflowId: string) => string;
|
|
171
|
-
readonly workflowVisibilityDeadline: (deadline: number, workflowId: string) => string;
|
|
172
|
-
readonly workflowVisibilityManifest: (workflowId: string) => string;
|
|
173
|
-
readonly workflowVisibilityMetaVersion: () => string;
|
|
174
|
-
readonly workflowVisibilityMetaBuiltAt: () => string;
|
|
175
|
-
readonly workflowVisibilityMetaCursor: () => string;
|
|
176
179
|
};
|
|
177
180
|
/**
|
|
178
181
|
* Re-exported {@link MAX_BATCH_OPERATIONS}. See the original declaration for full docs.
|
|
@@ -353,7 +356,7 @@ declare const exportedTextValueStore: typeof textValueStore;
|
|
|
353
356
|
* void isWeftKey;
|
|
354
357
|
* ```
|
|
355
358
|
*/
|
|
356
|
-
declare const exportedWeftReservedKeyPrefixes: readonly ["actrec:", "archive:", "async-act:", "attr:", "audit:bulk:", "blob:", "budget:", "budget-charged:", "child-by-parent:", "ev:", "fleet-event-by-workflow:", "fleet-event:", "fleet-event-tail", "idx:", "lease:", "liveness:", "offload:", "op:", "review:", "schedule:", "schedule-due:", "schedule-run-by-schedule:", "schedule-run-link:", "schedule-run:", "sig:", "sigres:", "sigseq:", "start-idem:", "state:", "tag:", "tool-effect:", "upd:", "upk:", "upr:", "wf:", "wf-cleanup:", "wf-cleanup-needed:", "wf-concurrency:", "wf-concurrency-holder:", "wf-deadline:", "wf-delayed:", "wf-finalizer-state:", "wf-has-services:", "wf-headers:", "wf-idx-", "wf-teardown:", "wf-teardown-deadletter:", "wf-teardown-needed:", "wf-teardown-succeeded:", "wf-terminal:"];
|
|
359
|
+
declare const exportedWeftReservedKeyPrefixes: readonly ["actrec:", "archive:", "async-act:", "attr:", "audit:bulk:", "blob:", "budget:", "budget-charged:", "child-by-parent:", "ev:", "fleet-event-by-workflow:", "fleet-event:", "fleet-event-tail", "idx:", "lease:", "liveness:", "offload:", "ownership-mode-marker", "op:", "review:", "schedule:", "schedule-due:", "schedule-run-by-schedule:", "schedule-run-link:", "schedule-run:", "sig:", "sigres:", "sigseq:", "start-idem:", "state:", "tag:", "tool-effect:", "upd:", "upk:", "upr:", "wf:", "wf-cleanup:", "wf-cleanup-needed:", "wf-concurrency:", "wf-concurrency-holder:", "wf-deadline:", "wf-delayed:", "wf-finalizer-state:", "wf-has-services:", "wf-headers:", "wf-idx-", "wf-owner-epoch:", "wf-owner-holder:", "wf-teardown:", "wf-teardown-deadletter:", "wf-teardown-needed:", "wf-teardown-succeeded:", "wf-terminal:"];
|
|
357
360
|
/**
|
|
358
361
|
* Re-exported {@link withCodec}. See the original declaration for full docs.
|
|
359
362
|
*
|