@selvajs/solve 0.2.0-beta.2 → 1.0.0-beta.5
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 +10 -14
- package/dist/client.cjs +1 -1
- package/dist/client.d.cts +119 -88
- package/dist/client.d.ts +119 -88
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/server.cjs +1 -1
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +98 -160
- package/dist/server.d.ts +98 -160
- package/dist/server.js +1 -1
- package/dist/server.js.map +1 -1
- package/dist/shared.d.cts +1 -1
- package/dist/shared.d.ts +1 -1
- package/dist/solve-fn-DrRgaPZ5.d.cts +46 -0
- package/dist/solve-fn-DrRgaPZ5.d.ts +46 -0
- package/package.json +1 -1
- package/dist/solve-fn-DGzPCsDu.d.cts +0 -22
- package/dist/solve-fn-DGzPCsDu.d.ts +0 -22
package/dist/client.d.ts
CHANGED
|
@@ -1,40 +1,124 @@
|
|
|
1
1
|
import { UISchema } from '@selvajs/schemas';
|
|
2
|
-
import { a as SolveResult, S as SolveFn } from './solve-fn-
|
|
2
|
+
import { a as SolveResult, S as SolveFn } from './solve-fn-DrRgaPZ5.js';
|
|
3
3
|
import { GrasshopperComputeResponse } from '@selvajs/compute';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* mesh frames on its own schedule) satisfy the same interface as
|
|
6
|
+
* Transport behind a solve session. `solve()` never returns outputs directly — results
|
|
7
|
+
* go through the session's `report()` instead, so a push transport (e.g. a WebSocket
|
|
8
|
+
* streaming mesh frames on its own schedule) can satisfy the same interface as
|
|
9
|
+
* request/response HTTP.
|
|
10
|
+
*
|
|
11
|
+
* **Stamping `SolveResult.values` is the driver's job, and only some drivers can do it.** A
|
|
12
|
+
* driver that owns a request/response pair must stamp the input set it solved onto the
|
|
13
|
+
* result it reports — the session retains that pair, and a consumer committing what is on
|
|
14
|
+
* screen relies on it being atomic. A push driver that cannot attribute an incoming frame to
|
|
15
|
+
* a request it made must leave `values` absent rather than attach the last set it sent:
|
|
16
|
+
* frames that arrive unsolicited (a replay on connect, a recompute triggered outside the web
|
|
17
|
+
* UI) would otherwise be stamped with an unrelated input set, which is precisely the stale
|
|
18
|
+
* pairing the field exists to prevent.
|
|
9
19
|
*/
|
|
10
20
|
interface SolveDriver {
|
|
11
21
|
solve(values: Record<string, unknown>): void;
|
|
12
22
|
cancel(): void;
|
|
13
23
|
readonly isSolving: boolean;
|
|
14
24
|
/**
|
|
15
|
-
* Drops
|
|
16
|
-
* client-side memo
|
|
17
|
-
*
|
|
25
|
+
* Drops cached solve results. Optional — only the request/response driver has a
|
|
26
|
+
* client-side memo to clear. Call on rebuild: a definition swap must not serve a
|
|
27
|
+
* stale result from the prior definition's input space.
|
|
18
28
|
*/
|
|
19
29
|
clearCache?(): void;
|
|
20
30
|
}
|
|
21
|
-
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* `TMesh` defaults to `unknown` because nothing in this package inspects meshes; a host that
|
|
25
|
-
* knows its concrete mesh type (a three.js viewer) narrows it at its own seam.
|
|
26
|
-
*/
|
|
31
|
+
/** `TMesh` defaults to `unknown`: nothing here inspects meshes. A host with a concrete
|
|
32
|
+
* mesh type (e.g. a three.js viewer) narrows it at its own seam. */
|
|
27
33
|
interface SolveReporter<TMesh = unknown> {
|
|
28
34
|
report(result: SolveResult<TMesh>): void;
|
|
29
35
|
reportError(message: string): void;
|
|
30
36
|
}
|
|
31
37
|
|
|
38
|
+
interface ExternalValueRef {
|
|
39
|
+
scopeKey: string;
|
|
40
|
+
inputId: string;
|
|
41
|
+
}
|
|
42
|
+
declare function writeExternalValue(args: ExternalValueRef & {
|
|
43
|
+
value: unknown;
|
|
44
|
+
}): void;
|
|
45
|
+
declare function readExternalValue(ref: ExternalValueRef): unknown | undefined;
|
|
46
|
+
declare function clearExternalValue(ref: ExternalValueRef): void;
|
|
47
|
+
interface ExternalInput {
|
|
48
|
+
paramId: string;
|
|
49
|
+
displayName: string;
|
|
50
|
+
}
|
|
51
|
+
declare function getExternalInputs(schema: UISchema): ExternalInput[];
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The slice of a reported result the session keeps addressable, so a host can commit exactly
|
|
55
|
+
* what the viewer is showing — `source` and `values` included, already memo-correct.
|
|
56
|
+
*
|
|
57
|
+
* Mesh-free by construction. `SolveResult.meshes` are GPU-backed and the viewer disposes what
|
|
58
|
+
* it renders on the next scene update, which is why the memo carries a `MeshPolicy`
|
|
59
|
+
* clone/release contract at all. Retaining them here would hand out disposed instances after
|
|
60
|
+
* the next solve, with no policy governing them and no owner. Everything left is inert JSON;
|
|
61
|
+
* live meshes stay on `session.meshes`.
|
|
62
|
+
*/
|
|
63
|
+
type RetainedSolveResult<TSource = unknown> = Omit<SolveResult<never, TSource>, 'meshes'>;
|
|
64
|
+
interface SolveSessionState {
|
|
65
|
+
values: Record<string, unknown>;
|
|
66
|
+
error: string;
|
|
67
|
+
computeErrors: string[];
|
|
68
|
+
computeWarnings: string[];
|
|
69
|
+
meshes: unknown[];
|
|
70
|
+
/** Values changed since the last solve, in manual (instanceSolve === false) mode. */
|
|
71
|
+
pendingValues: Record<string, unknown>;
|
|
72
|
+
hasPendingChanges: boolean;
|
|
73
|
+
hasNeverSolved: boolean;
|
|
74
|
+
/**
|
|
75
|
+
* The last result reported, minus its meshes. Null before the first solve.
|
|
76
|
+
*
|
|
77
|
+
* Lags `values` by design: nothing updates it on `setValue` or `loadValues`, so between a
|
|
78
|
+
* value change and the next report it describes the *previous* input set. That is what a
|
|
79
|
+
* commit gate wants — what is on screen, not what is pending — so `lastResult.values`
|
|
80
|
+
* disagreeing with `state.values` mid-scrub is the feature, not a bug.
|
|
81
|
+
*/
|
|
82
|
+
lastResult: RetainedSolveResult | null;
|
|
83
|
+
}
|
|
84
|
+
type ExternalReader = (ref: ExternalValueRef) => unknown | undefined;
|
|
85
|
+
/**
|
|
86
|
+
* Client-sourced inputs are hydrated from `read` and left absent when no stored value
|
|
87
|
+
* exists, so the missing-inputs panel can detect them. Other inputs fall back to their
|
|
88
|
+
* declared default, then the paramType default.
|
|
89
|
+
*/
|
|
90
|
+
declare function buildInitialValues(schema: UISchema, scopeKey: string, read: ExternalReader): Record<string, unknown>;
|
|
91
|
+
/** Manual-solve schemas (instanceSolve === false) start dirty; auto-solve schemas start clean. */
|
|
92
|
+
declare function makeInitialFlags(instanceSolve: boolean | undefined): {
|
|
93
|
+
hasPendingChanges: boolean;
|
|
94
|
+
hasNeverSolved: boolean;
|
|
95
|
+
};
|
|
96
|
+
/** Manual mode defers (records the pending value, raises the dirty flag) instead of solving. */
|
|
97
|
+
declare function applyValueChange(state: SolveSessionState, id: string, value: unknown, instanceSolve: boolean | undefined): {
|
|
98
|
+
state: SolveSessionState;
|
|
99
|
+
shouldSolve: boolean;
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* Solve outputs live in the same `values` map as inputs (so widgets like dynamic value
|
|
103
|
+
* lists can read them) but must not be echoed back to the driver: a measured 6.4 MB
|
|
104
|
+
* options-list output showed this can re-upload a multi-MB payload no backend reads.
|
|
105
|
+
*/
|
|
106
|
+
declare function pickInputValues(schema: UISchema | undefined, values: Record<string, unknown>): Record<string, unknown>;
|
|
107
|
+
declare function applySolveResult(state: SolveSessionState, result: SolveResult): SolveSessionState;
|
|
108
|
+
|
|
32
109
|
interface SolveSession {
|
|
33
110
|
readonly values: Record<string, unknown>;
|
|
34
111
|
readonly error: string;
|
|
35
112
|
readonly computeErrors: string[];
|
|
36
113
|
readonly computeWarnings: string[];
|
|
37
114
|
readonly meshes: unknown[];
|
|
115
|
+
/**
|
|
116
|
+
* The last reported result without its meshes — what the viewer is currently showing,
|
|
117
|
+
* including the `source`/`values` pair a commit path needs. Null before the first solve,
|
|
118
|
+
* and again after `rebuild()`. Survives `reportError`: a failed solve leaves the last good
|
|
119
|
+
* geometry on screen, so a host committing what it sees should still see what produced it.
|
|
120
|
+
*/
|
|
121
|
+
readonly lastResult: RetainedSolveResult | null;
|
|
38
122
|
readonly hasPendingChanges: boolean;
|
|
39
123
|
readonly hasNeverSolved: boolean;
|
|
40
124
|
readonly isSolving: boolean;
|
|
@@ -59,45 +143,36 @@ interface SolveSessionArgs {
|
|
|
59
143
|
declare function createSolveSession(args: SolveSessionArgs): SolveSession;
|
|
60
144
|
|
|
61
145
|
/**
|
|
62
|
-
* Deterministic string key for a set of input values.
|
|
63
|
-
*
|
|
64
|
-
* server's stable-input keying intent. Values are plain JSON — the projected solve inputs
|
|
65
|
-
* never contain functions or cycles.
|
|
146
|
+
* Deterministic string key for a set of input values. Sorts object keys at every level so
|
|
147
|
+
* two logically-equal inputs built in different key order collide.
|
|
66
148
|
*/
|
|
67
149
|
declare function stableInputKey(values: Record<string, unknown>): string;
|
|
68
150
|
/**
|
|
69
|
-
* Omit
|
|
70
|
-
* stores and serves them by reference, which is
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
* @property clone - Called on the way in AND on every hit, so neither the stored entry nor
|
|
74
|
-
* a previously served one can be disposed by the other's owner.
|
|
75
|
-
* @property release - Must NOT free anything shared with live content — see
|
|
76
|
-
* `releaseSceneObjects` in `@selvajs/visualization/parse`, which skips materials for
|
|
77
|
-
* exactly that reason.
|
|
151
|
+
* Omit when results are mesh-free or nothing takes ownership of the meshes — the memo then
|
|
152
|
+
* stores and serves them by reference, which is safe only because nothing frees them behind
|
|
153
|
+
* its back.
|
|
78
154
|
*/
|
|
79
155
|
interface MeshPolicy<TMesh> {
|
|
156
|
+
/** Called on the way in and on every hit, so the stored entry and a served copy are never the same instance. */
|
|
80
157
|
clone(meshes: TMesh[]): TMesh[];
|
|
158
|
+
/** Must not free anything shared with live content (e.g. materials another object still uses). */
|
|
81
159
|
release(meshes: TMesh[]): void;
|
|
82
160
|
}
|
|
83
161
|
interface SolveMemoOptions<TMesh> {
|
|
84
|
-
/**
|
|
85
|
-
* Entry cap (entries, not bytes). Solve results can be large, so the default is
|
|
86
|
-
* deliberately small — this targets the tight slider-scrub loop, not a durable cache.
|
|
87
|
-
*/
|
|
162
|
+
/** Entry cap, not a byte cap. Kept small on purpose: this targets the slider-scrub loop, not a durable cache. */
|
|
88
163
|
max?: number;
|
|
89
164
|
meshPolicy?: MeshPolicy<TMesh>;
|
|
90
165
|
}
|
|
91
166
|
interface SolveMemo<TMesh = unknown> {
|
|
92
167
|
get(values: Record<string, unknown>): SolveResult<TMesh> | undefined;
|
|
93
|
-
/** Evicts the LRU tail if `set` pushes the map past its cap. */
|
|
94
168
|
set(values: Record<string, unknown>, result: SolveResult<TMesh>): void;
|
|
95
169
|
clear(): void;
|
|
96
170
|
}
|
|
97
171
|
declare function createSolveMemo<TMesh = unknown>(options?: SolveMemoOptions<TMesh>): SolveMemo<TMesh>;
|
|
98
172
|
|
|
99
173
|
interface RequestResponseDriverOptions<TMesh> {
|
|
100
|
-
|
|
174
|
+
/** How long one solve may take before the client aborts it (ms). Pass the server's `COMPUTE_SOLVE_DEADLINE_MS` so the two agree. */
|
|
175
|
+
solveDeadlineMs: number;
|
|
101
176
|
onChange?: () => void;
|
|
102
177
|
/** Mesh ownership policy for the result memo — see `MeshPolicy` (solve-memo.ts). */
|
|
103
178
|
meshPolicy?: MeshPolicy<TMesh>;
|
|
@@ -106,58 +181,7 @@ interface RequestResponseDriverOptions<TMesh> {
|
|
|
106
181
|
* `getReporter` is lazy (`() => session`) because the session and driver reference each
|
|
107
182
|
* other — the host builds the driver first, then the session, then can hand this back.
|
|
108
183
|
*/
|
|
109
|
-
declare function createRequestResponseDriver<TMesh = unknown>(onSolve: SolveFn<TMesh>, getReporter: () => SolveReporter<TMesh>, options
|
|
110
|
-
|
|
111
|
-
interface ExternalValueRef {
|
|
112
|
-
scopeKey: string;
|
|
113
|
-
inputId: string;
|
|
114
|
-
}
|
|
115
|
-
declare function writeExternalValue(args: ExternalValueRef & {
|
|
116
|
-
value: unknown;
|
|
117
|
-
}): void;
|
|
118
|
-
declare function readExternalValue(ref: ExternalValueRef): unknown | undefined;
|
|
119
|
-
declare function clearExternalValue(ref: ExternalValueRef): void;
|
|
120
|
-
interface ExternalInput {
|
|
121
|
-
paramId: string;
|
|
122
|
-
displayName: string;
|
|
123
|
-
}
|
|
124
|
-
declare function getExternalInputs(schema: UISchema): ExternalInput[];
|
|
125
|
-
|
|
126
|
-
interface SolveSessionState {
|
|
127
|
-
values: Record<string, unknown>;
|
|
128
|
-
error: string;
|
|
129
|
-
computeErrors: string[];
|
|
130
|
-
computeWarnings: string[];
|
|
131
|
-
meshes: unknown[];
|
|
132
|
-
/** Values changed since the last solve, in manual (instanceSolve === false) mode. */
|
|
133
|
-
pendingValues: Record<string, unknown>;
|
|
134
|
-
hasPendingChanges: boolean;
|
|
135
|
-
hasNeverSolved: boolean;
|
|
136
|
-
}
|
|
137
|
-
type ExternalReader = (ref: ExternalValueRef) => unknown | undefined;
|
|
138
|
-
/**
|
|
139
|
-
* Client-sourced inputs are hydrated from `read` and left absent when no stored value
|
|
140
|
-
* exists, so the missing-inputs panel can detect them. Other inputs fall back to their
|
|
141
|
-
* declared default, then the paramType default.
|
|
142
|
-
*/
|
|
143
|
-
declare function buildInitialValues(schema: UISchema, scopeKey: string, read: ExternalReader): Record<string, unknown>;
|
|
144
|
-
/** Manual-solve schemas (instanceSolve === false) start dirty; auto-solve schemas start clean. */
|
|
145
|
-
declare function makeInitialFlags(instanceSolve: boolean | undefined): {
|
|
146
|
-
hasPendingChanges: boolean;
|
|
147
|
-
hasNeverSolved: boolean;
|
|
148
|
-
};
|
|
149
|
-
/** Manual mode defers (records the pending value, raises the dirty flag) instead of solving. */
|
|
150
|
-
declare function applyValueChange(state: SolveSessionState, id: string, value: unknown, instanceSolve: boolean | undefined): {
|
|
151
|
-
state: SolveSessionState;
|
|
152
|
-
shouldSolve: boolean;
|
|
153
|
-
};
|
|
154
|
-
/**
|
|
155
|
-
* Solve outputs live in the same `values` map as inputs (so widgets like dynamic value
|
|
156
|
-
* lists can read them) but must not be echoed back to the driver: a measured 6.4 MB
|
|
157
|
-
* options-list output showed this can re-upload a multi-MB payload no backend reads.
|
|
158
|
-
*/
|
|
159
|
-
declare function pickInputValues(schema: UISchema | undefined, values: Record<string, unknown>): Record<string, unknown>;
|
|
160
|
-
declare function applySolveResult(state: SolveSessionState, result: SolveResult): SolveSessionState;
|
|
184
|
+
declare function createRequestResponseDriver<TMesh = unknown>(onSolve: SolveFn<TMesh>, getReporter: () => SolveReporter<TMesh>, options: RequestResponseDriverOptions<TMesh>): SolveDriver;
|
|
161
185
|
|
|
162
186
|
/**
|
|
163
187
|
* Single-in-flight, latest-wins throttle for any async operation: only one run at a
|
|
@@ -169,7 +193,14 @@ declare function applySolveResult(state: SolveSessionState, result: SolveResult)
|
|
|
169
193
|
* directly reads correct values but won't trigger a re-render.
|
|
170
194
|
*/
|
|
171
195
|
interface AsyncThrottleOptions {
|
|
172
|
-
|
|
196
|
+
/**
|
|
197
|
+
* How long one run may take before it is aborted (ms). Required and deliberately
|
|
198
|
+
* undefaulted: this is a generic throttle, so it has no basis for guessing what
|
|
199
|
+
* the caller's work costs. Callers driving a Selva solve pass the deadline the
|
|
200
|
+
* server enforces (`COMPUTE_SOLVE_DEADLINE_MS`) — a shorter local guess would abort
|
|
201
|
+
* solves the server would have finished.
|
|
202
|
+
*/
|
|
203
|
+
runDeadlineMs: number;
|
|
173
204
|
onChange?: () => void;
|
|
174
205
|
}
|
|
175
206
|
interface AsyncThrottle<T> {
|
|
@@ -178,7 +209,7 @@ interface AsyncThrottle<T> {
|
|
|
178
209
|
readonly hasPending: boolean;
|
|
179
210
|
cancel: () => void;
|
|
180
211
|
}
|
|
181
|
-
declare function createAsyncThrottle<T>(run: (values: T, signal: AbortSignal) => Promise<void>, options
|
|
212
|
+
declare function createAsyncThrottle<T>(run: (values: T, signal: AbortSignal) => Promise<void>, options: AsyncThrottleOptions): AsyncThrottle<T>;
|
|
182
213
|
|
|
183
214
|
/**
|
|
184
215
|
* `createComputeFetchSolveFn` — a ready-made `SolveFn` that POSTs to a
|
|
@@ -229,6 +260,6 @@ interface ComputeFetchSolveFnOptions<TMesh = unknown, TRhino = unknown> {
|
|
|
229
260
|
/** Called on a 401 or a login-page redirect. Default: throws an actionable "reload to sign in again" Error. */
|
|
230
261
|
onSessionExpired?: () => void;
|
|
231
262
|
}
|
|
232
|
-
declare function createComputeFetchSolveFn<TMesh = unknown, TRhino = unknown>(opts: ComputeFetchSolveFnOptions<TMesh, TRhino>): SolveFn<TMesh>;
|
|
263
|
+
declare function createComputeFetchSolveFn<TMesh = unknown, TRhino = unknown>(opts: ComputeFetchSolveFnOptions<TMesh, TRhino>): SolveFn<TMesh, GrasshopperComputeResponse>;
|
|
233
264
|
|
|
234
|
-
export { type AsyncThrottle, type ComputeFetchSolveFnOptions, type ExternalInput, type ExternalReader, type ExternalValueRef, type MeshPolicy, type RequestResponseDriverOptions, type SolveDriver, SolveFn, type SolveMemo, type SolveMemoOptions, type SolveReporter, SolveResult, type SolveSession, type SolveSessionArgs, type SolveSessionState, applySolveResult, applyValueChange, buildInitialValues, clearExternalValue, createAsyncThrottle, createComputeFetchSolveFn, createRequestResponseDriver, createSolveMemo, createSolveSession, getExternalInputs, makeInitialFlags, pickInputValues, readExternalValue, stableInputKey, writeExternalValue };
|
|
265
|
+
export { type AsyncThrottle, type ComputeFetchSolveFnOptions, type ExternalInput, type ExternalReader, type ExternalValueRef, type MeshPolicy, type RequestResponseDriverOptions, type RetainedSolveResult, type SolveDriver, SolveFn, type SolveMemo, type SolveMemoOptions, type SolveReporter, SolveResult, type SolveSession, type SolveSessionArgs, type SolveSessionState, applySolveResult, applyValueChange, buildInitialValues, clearExternalValue, createAsyncThrottle, createComputeFetchSolveFn, createRequestResponseDriver, createSolveMemo, createSolveSession, getExternalInputs, makeInitialFlags, pickInputValues, readExternalValue, stableInputKey, writeExternalValue };
|
package/dist/client.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getInputItems as
|
|
1
|
+
import{getInputItems as L}from"@selvajs/schemas";var _="external";function E(e,r){return`${_}:${e}:${r}`}function X(e){let{scopeKey:r,inputId:t,value:n}=e;!r||!t||typeof sessionStorage>"u"||sessionStorage.setItem(E(r,t),JSON.stringify(n))}function x(e){let{scopeKey:r,inputId:t}=e;if(!r||!t||typeof sessionStorage>"u")return;let n=sessionStorage.getItem(E(r,t));if(n!==null)try{return JSON.parse(n)}catch{return}}function Y(e){let{scopeKey:r,inputId:t}=e;!r||!t||typeof sessionStorage>"u"||sessionStorage.removeItem(E(r,t))}function I(e){return L(e).filter(r=>r.source?.kind==="client").map(r=>({paramId:r.paramId,displayName:r.displayName??r.paramId}))}import{getDefaultValue as Q}from"@selvajs/schemas";function b(e,r,t){let n=new Set(I(e).map(s=>s.paramId)),l={};for(let s of e.inputs){if(n.has(s.id)){let i=t({scopeKey:r,inputId:s.id});i!==void 0&&(l[s.id]=i);continue}l[s.id]=s.default??Q(s.paramType)}for(let s of e.outputs)l[s.id]=null;return l}function w(e){let r=e===!1;return{hasPendingChanges:r,hasNeverSolved:r}}function C(e,r,t,n){return e.values[r]=t,n===!1?(e.pendingValues[r]=t,e.hasPendingChanges=!0,{state:e,shouldSolve:!1}):{state:e,shouldSolve:!0}}function P(e,r){if(!e?.inputs)return r;let t={};for(let n of e.inputs)n.id in r&&(t[n.id]=r[n.id]);return t}function V(e,r){e.error="",e.computeErrors=r.errors??[],e.computeWarnings=r.warnings??[],e.meshes=r.meshes??[];let{meshes:t,...n}=r;return e.lastResult=n,Object.assign(e.values,r.outputs),e.pendingValues={},e.hasPendingChanges=!1,e.hasNeverSolved=!1,e}function Z(e){let r=e.schema,t=w(r?.instanceSolve),n={values:b(r,e.scopeKey,x),error:"",computeErrors:[],computeWarnings:[],meshes:[],pendingValues:{},hasPendingChanges:t.hasPendingChanges,hasNeverSolved:t.hasNeverSolved,lastResult:null},l=new Set,s=()=>l.forEach(o=>o());function i(){e.driver.solve({...P(r,n.values)}),s()}return{get values(){return n.values},get error(){return n.error},get computeErrors(){return n.computeErrors},get computeWarnings(){return n.computeWarnings},get meshes(){return n.meshes},get lastResult(){return n.lastResult},get hasPendingChanges(){return n.hasPendingChanges},get hasNeverSolved(){return n.hasNeverSolved},get isSolving(){return e.driver.isSolving},setValue(o,a,u=!1){let{shouldSolve:p}=C(n,o,a,r?.instanceSolve);p||u?(u&&!p&&(n.pendingValues={},n.hasPendingChanges=!1),i()):s()},solve(){i()},loadValues(o){Object.assign(n.values,o),r?.instanceSolve!==!1?i():(n.hasPendingChanges=!0,s())},rebuild(o,a){r=o,e.driver.clearCache?.(),n.meshes=[],n.lastResult=null,n.error="",n.computeErrors=[],n.computeWarnings=[],n.pendingValues={},n.values=b(o,a,x);let u=w(o?.instanceSolve);n.hasPendingChanges=u.hasPendingChanges,n.hasNeverSolved=u.hasNeverSolved,o&&Object.keys(n.values).length>0&&o.instanceSolve!==!1?i():s()},report(o){V(n,o),s()},reportError(o){n.error=o,s()},subscribe(o){return l.add(o),()=>l.delete(o)},notify:s}}function F(e,r){let{runDeadlineMs:t,onChange:n}=r,l=!1,s=null,i=null;function o(m){l!==m&&(l=m,n?.())}function a(){i?.abort(),i=null}async function u(m){a(),i=new AbortController;let{signal:S}=i,y=setTimeout(()=>{console.warn(`[Solve/throttle] run exceeded ${t}ms \u2014 aborting`),i?.abort()},t);o(!0);try{await e(m,S)}catch(h){(!(h instanceof Error)||h.name!=="AbortError"&&h.name!=="TimeoutError")&&console.error("[Solve/throttle] unhandled error in run:",h)}finally{if(clearTimeout(y),o(!1),i=null,s!==null){let h=s;s=null,u(h)}}}function p(m){l?(s!==null&&console.debug("[Solve/throttle] superseded pending run (latest-wins)"),s=m):u(m)}function f(){s=null,a()}return{trigger:p,get isRunning(){return l},get hasPending(){return s!==null},cancel:f}}function O(e){return $(e)}function $(e){if(e===null||typeof e!="object")return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map($).join(",")}]`;let r=e;return`{${Object.keys(r).sort().map(n=>`${JSON.stringify(n)}:${$(r[n])}`).join(",")}}`}function j(e={}){let{max:r=16,meshPolicy:t}=e,n=new Map;function l(o){o.meshes?.length&&t?.release(o.meshes)}function s(o){return!t||!o.meshes?.length?o:{...o,meshes:t.clone(o.meshes)}}function i(o){let a=n.get(o);a!==void 0&&(n.delete(o),l(a))}return{get(o){let a=O(o),u=n.get(a);if(u!==void 0)return n.delete(a),n.set(a,u),console.info(`[Solve/memo] HIT \u2014 served from client memo (${n.size}/${r})`),s(u)},set(o,a){let u=O(o);for(i(u),n.set(u,s(a));n.size>r;){let p=n.keys().next().value;if(p===void 0)break;i(p),console.info(`[Solve/memo] evicted LRU entry (cap ${r})`)}},clear(){n.size>0&&console.info(`[Solve/memo] cleared ${n.size} entries (definition changed)`),n.forEach(l),n.clear()}}}function ee(e,r,t){let{meshPolicy:n,solveDeadlineMs:l,onChange:s}=t,i=j({meshPolicy:n}),o=F(async(a,u)=>{let p=i.get(a);if(p!==void 0){if(u.aborted)return;r().report(p);return}try{let f=await e(a,u);if(u.aborted){console.debug("[Solve/driver] solve completed after abort \u2014 result discarded");return}let m={...f,values:a};i.set(a,m),r().report(m)}catch(f){if(u.aborted){console.debug("[Solve/driver] solve aborted (superseded, cancelled, or timed out)");return}console.warn("[Solve/driver] solve failed:",f),r().reportError(f instanceof Error?f.message:String(f))}},{runDeadlineMs:l,onChange:s});return{solve(a){o.trigger(a)},cancel(){o.cancel()},get isSolving(){return o.isRunning},clearCache(){i.clear()}}}import{GrasshopperResponseProcessor as ne}from"@selvajs/compute";function re(e){let r={};if(!e)return r;for(let t of e.split(",")){let[n,...l]=t.split(";").map(o=>o.trim()),s=l.find(o=>o.startsWith("dur="));if(!n||!s)continue;let i=Number(s.slice(4));Number.isFinite(i)&&(r[n]=i)}return r}var oe=e=>{throw new Error(`Rate limit reached. Try again in ${Math.ceil(e)}s.`)},te=()=>{throw new Error("Your session has expired. Sign in again in a new tab, then re-run \u2014 your inputs are preserved.")};function se(e){let r=e.debug??!1,t=(...i)=>{r&&console.info(...i)},n=null;function l(){if(!e.meshes)throw new Error("createComputeFetchSolveFn: meshes option not configured.");return n||(n=e.meshes.loadRhino()),n}let s=0;return async(i,o)=>{let a=s-Date.now();if(a>0)throw new Error(`Rate limit reached. Try again in ${Math.ceil(a/1e3)}s.`);let u=performance.now(),p=e.inputs(),f=e.outputs(),m=e.channel?.(),S=e.versionId?.(),y=JSON.stringify({inputs:p,values:i,definitionUrl:e.definitionUrl(),...S?{versionId:S}:m==="draft"?{channel:"draft"}:{}}),h=JSON.stringify(i).length,d;try{d=await fetch(e.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:y,signal:o})}catch(c){if(o.aborted)return t("[Compute] solve aborted during fetch \u2014 empty result discarded"),{outputs:{}};throw new Error("Request blocked \u2014 your session may have expired. Reload the page to sign in again.",{cause:c})}if(o.aborted)return t("[Compute] solve aborted after headers \u2014 empty result discarded"),{outputs:{}};let J=d.redirected&&new URL(d.url).pathname==="/login";if((d.status===401||J)&&(e.onSessionExpired??te)(),!d.ok){if(d.status===503)throw new Error("Compute server is offline or unreachable. Please try again later.");let c=await d.text().catch(()=>""),v={};try{v=JSON.parse(c)}catch{c&&console.warn(`[Compute] non-JSON error body (HTTP ${d.status}):`,c.slice(0,300))}if(d.status===429){let R=Number(d.headers.get("Retry-After"))||Number(v.retryAfter)||5;s=Date.now()+R*1e3,(e.onRateLimited??oe)(R)}throw new Error(v.message||`Compute error (HTTP ${d.status})`)}let N=performance.now()-u,B=performance.now(),A=await d.text();if(o.aborted)return t("[Compute] solve aborted mid-download \u2014 empty result discarded"),{outputs:{}};let T=performance.now()-B,D=A.length,g;try{g=JSON.parse(A)}catch(c){throw new Error("Received an invalid response from the server. Reload the page and try again.",{cause:c})}let M=new ne(g,!1),z=e.meshes?await e.meshes.extract(M.response,{debug:r,rhino:await l()}):[],U={};for(let c of f){let v=M.getValue({byId:c.id},{parseValues:!0});U[c.id]=v??(c.nickname?M.getValue({byName:c.nickname},{parseValues:!0}):void 0)}if(r){let c=re(d.headers.get("Server-Timing")),v=c.total??0,R=Math.max(0,N-v),k=D/(1024*1024),q=k>=1?`${k.toFixed(2)} MB`:`${(D/1024).toFixed(0)} KB`,W=T>0?(k/(T/1e3)).toFixed(1):"\u221E",K=performance.memory?.usedJSHeapSize,G=K!==void 0?` | heap=${(K/(1024*1024)).toFixed(0)} MB`:"";if(t(`[Compute] req=${(y.length/1024).toFixed(0)}KB (values ${(h/1024).toFixed(0)}KB) | ttfb=${N.toFixed(0)}ms (network\u2248${R.toFixed(0)} + server ${v.toFixed(0)}) | download=${T.toFixed(0)}ms (${q} @ ${W} MB/s)${G}`),c.selva_cache!==void 0){let H=c.selva_cache?"HIT \u2014 served without calling compute":"miss \u2014 solved on Rhino.Compute";t(`[Compute] \u2514\u2500 cache: ${H}`)}}return{outputs:U,meshes:z,errors:g.errors??[],warnings:g.warnings??[],source:g}}}export{V as applySolveResult,C as applyValueChange,b as buildInitialValues,Y as clearExternalValue,F as createAsyncThrottle,se as createComputeFetchSolveFn,ee as createRequestResponseDriver,j as createSolveMemo,Z as createSolveSession,I as getExternalInputs,w as makeInitialFlags,P as pickInputValues,x as readExternalValue,O as stableInputKey,X as writeExternalValue};
|
|
2
2
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/external-storage.ts","../src/client/solve-session-core.ts","../src/client/solve-session.ts","../src/client/async-throttle.ts","../src/client/solve-memo.ts","../src/client/drivers/request-response.ts","../src/client/compute-fetch-solve-fn.ts"],"sourcesContent":["// Transit storage for inputs with source.kind === 'client': a producer route writes the\n// value here, the solver route reads it back. Keyed by (scopeKey, inputId) so values\n// don't bleed across solver contexts — scopeKey is whatever uniquely identifies one\n// (sessionId in plugin-ui/preview, definition guid in selva/library).\n\nimport type { UISchema } from '@selvajs/schemas';\nimport { getInputItems } from '@selvajs/schemas';\n\nconst STORAGE_PREFIX = 'external';\n\nfunction makeKey(scopeKey: string, inputId: string): string {\n\treturn `${STORAGE_PREFIX}:${scopeKey}:${inputId}`;\n}\n\nexport interface ExternalValueRef {\n\tscopeKey: string;\n\tinputId: string;\n}\n\nexport function writeExternalValue(args: ExternalValueRef & { value: unknown }): void {\n\tconst { scopeKey, inputId, value } = args;\n\tif (!scopeKey || !inputId) return;\n\tif (typeof sessionStorage === 'undefined') return;\n\tsessionStorage.setItem(makeKey(scopeKey, inputId), JSON.stringify(value));\n}\n\nexport function readExternalValue(ref: ExternalValueRef): unknown | undefined {\n\tconst { scopeKey, inputId } = ref;\n\tif (!scopeKey || !inputId) return undefined;\n\tif (typeof sessionStorage === 'undefined') return undefined;\n\tconst raw = sessionStorage.getItem(makeKey(scopeKey, inputId));\n\tif (raw === null) return undefined;\n\ttry {\n\t\treturn JSON.parse(raw);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function clearExternalValue(ref: ExternalValueRef): void {\n\tconst { scopeKey, inputId } = ref;\n\tif (!scopeKey || !inputId) return;\n\tif (typeof sessionStorage === 'undefined') return;\n\tsessionStorage.removeItem(makeKey(scopeKey, inputId));\n}\n\nexport interface ExternalInput {\n\tparamId: string;\n\tdisplayName: string;\n}\n\nexport function getExternalInputs(schema: UISchema): ExternalInput[] {\n\treturn getInputItems(schema)\n\t\t.filter((item) => item.source?.kind === 'client')\n\t\t.map((item) => ({\n\t\t\tparamId: item.paramId,\n\t\t\tdisplayName: item.displayName ?? item.paramId\n\t\t}));\n}\n","// Pure transition logic for a Solve Session.\n//\n// This module holds the value/lifecycle state machine with no transport and no state\n// ownership: how values are seeded (including client-sourced hydration), when a value\n// change should dispatch a solve vs. defer it, and what a reported solve result does to\n// the flags. `solve-session.ts` is a thin shell that owns the state object and the\n// subscriber set; every decision lives here, which is what makes it directly testable.\n\nimport type { UISchema } from '@selvajs/schemas';\nimport { getDefaultValue } from '@selvajs/schemas';\nimport { getExternalInputs, type ExternalValueRef } from './external-storage.js';\nimport type { SolveResult } from '../shared/solve-fn.js';\n\nexport interface SolveSessionState {\n\tvalues: Record<string, unknown>;\n\terror: string;\n\tcomputeErrors: string[];\n\tcomputeWarnings: string[];\n\tmeshes: unknown[];\n\t/** Values changed since the last solve, in manual (instanceSolve === false) mode. */\n\tpendingValues: Record<string, unknown>;\n\thasPendingChanges: boolean;\n\thasNeverSolved: boolean;\n}\n\nexport type ExternalReader = (ref: ExternalValueRef) => unknown | undefined;\n\n/**\n * Client-sourced inputs are hydrated from `read` and left absent when no stored value\n * exists, so the missing-inputs panel can detect them. Other inputs fall back to their\n * declared default, then the paramType default.\n */\nexport function buildInitialValues(\n\tschema: UISchema,\n\tscopeKey: string,\n\tread: ExternalReader\n): Record<string, unknown> {\n\tconst clientSet = new Set(getExternalInputs(schema).map((e) => e.paramId));\n\tconst values: Record<string, unknown> = {};\n\tfor (const input of schema.inputs) {\n\t\tif (clientSet.has(input.id)) {\n\t\t\tconst stored = read({ scopeKey, inputId: input.id });\n\t\t\tif (stored !== undefined) values[input.id] = stored;\n\t\t\tcontinue;\n\t\t}\n\t\tvalues[input.id] = input.default ?? getDefaultValue(input.paramType);\n\t}\n\tfor (const output of schema.outputs) {\n\t\tvalues[output.id] = null;\n\t}\n\treturn values;\n}\n\n/** Manual-solve schemas (instanceSolve === false) start dirty; auto-solve schemas start clean. */\nexport function makeInitialFlags(instanceSolve: boolean | undefined): {\n\thasPendingChanges: boolean;\n\thasNeverSolved: boolean;\n} {\n\tconst manual = instanceSolve === false;\n\treturn { hasPendingChanges: manual, hasNeverSolved: manual };\n}\n\n/** Manual mode defers (records the pending value, raises the dirty flag) instead of solving. */\nexport function applyValueChange(\n\tstate: SolveSessionState,\n\tid: string,\n\tvalue: unknown,\n\tinstanceSolve: boolean | undefined\n): { state: SolveSessionState; shouldSolve: boolean } {\n\tstate.values[id] = value;\n\tif (instanceSolve === false) {\n\t\tstate.pendingValues[id] = value;\n\t\tstate.hasPendingChanges = true;\n\t\treturn { state, shouldSolve: false };\n\t}\n\treturn { state, shouldSolve: true };\n}\n\n/**\n * Solve outputs live in the same `values` map as inputs (so widgets like dynamic value\n * lists can read them) but must not be echoed back to the driver: a measured 6.4 MB\n * options-list output showed this can re-upload a multi-MB payload no backend reads.\n */\nexport function pickInputValues(\n\tschema: UISchema | undefined,\n\tvalues: Record<string, unknown>\n): Record<string, unknown> {\n\tif (!schema?.inputs) return values;\n\tconst picked: Record<string, unknown> = {};\n\tfor (const input of schema.inputs) {\n\t\tif (input.id in values) picked[input.id] = values[input.id];\n\t}\n\treturn picked;\n}\n\nexport function applySolveResult(state: SolveSessionState, result: SolveResult): SolveSessionState {\n\tstate.error = '';\n\tstate.computeErrors = result.errors ?? [];\n\tstate.computeWarnings = result.warnings ?? [];\n\tstate.meshes = result.meshes ?? [];\n\tObject.assign(state.values, result.outputs);\n\tstate.pendingValues = {};\n\tstate.hasPendingChanges = false;\n\tstate.hasNeverSolved = false;\n\treturn state;\n}\n","// A framework-free shell over the pure transition logic in solve-session-core.ts: owns the\n// live values/flags, delegates every transition to the core, and drives solves through a\n// transport-agnostic SolveDriver.\n//\n// State is exposed as plain getters; it carries no framework reactivity of its own, so a\n// Svelte host must wrap it — see `useSolveSession.svelte.ts` in `@selvajs/ui`, which\n// republishes these getters as $state. Reading a getter without subscribing gives a\n// correct value but will not re-render.\n\nimport type { UISchema } from '@selvajs/schemas';\nimport { readExternalValue } from './external-storage.js';\nimport type { SolveResult } from '../shared/solve-fn.js';\nimport type { SolveDriver } from './drivers/driver.js';\nimport {\n\tbuildInitialValues,\n\tmakeInitialFlags,\n\tapplyValueChange,\n\tapplySolveResult,\n\tpickInputValues,\n\ttype SolveSessionState\n} from './solve-session-core.js';\n\nexport interface SolveSession {\n\treadonly values: Record<string, unknown>;\n\treadonly error: string;\n\treadonly computeErrors: string[];\n\treadonly computeWarnings: string[];\n\treadonly meshes: unknown[];\n\treadonly hasPendingChanges: boolean;\n\treadonly hasNeverSolved: boolean;\n\treadonly isSolving: boolean;\n\t/** `forceSolve` overrides manual mode for system-initiated reconciliation (e.g. a dynamic value list pruning a vanished selection), so the output can't lag behind the new value. */\n\tsetValue(id: string, value: unknown, forceSolve?: boolean): void;\n\tsolve(): void;\n\t/** Merges incoming values, then solves (auto) or marks dirty (manual). */\n\tloadValues(incoming: Record<string, unknown>): void;\n\trebuild(schema: UISchema, scopeKey: string): void;\n\treport(result: SolveResult): void;\n\treportError(message: string): void;\n\t/** Fires after any mutation of the getters above, including driver-reported `isSolving` transitions. */\n\tsubscribe(listener: () => void): () => void;\n\t/** For driver-owned state the session only forwards: `isSolving` lives on the driver, so wire this to its `onChange`. */\n\tnotify(): void;\n}\n\nexport interface SolveSessionArgs {\n\tschema: UISchema;\n\tscopeKey: string;\n\tdriver: SolveDriver;\n}\n\nexport function createSolveSession(args: SolveSessionArgs): SolveSession {\n\tlet currentSchema = args.schema;\n\n\tconst flags = makeInitialFlags(currentSchema?.instanceSolve);\n\tconst state: SolveSessionState = {\n\t\tvalues: buildInitialValues(currentSchema, args.scopeKey, readExternalValue),\n\t\terror: '',\n\t\tcomputeErrors: [],\n\t\tcomputeWarnings: [],\n\t\tmeshes: [],\n\t\tpendingValues: {},\n\t\thasPendingChanges: flags.hasPendingChanges,\n\t\thasNeverSolved: flags.hasNeverSolved\n\t};\n\n\tconst listeners = new Set<() => void>();\n\tconst emit = () => listeners.forEach((l) => l());\n\n\tfunction dispatch() {\n\t\t// Copy: state.values is the live map, and a driver may hold the payload across an\n\t\t// async solve — a later setValue must not mutate what's already in flight.\n\t\targs.driver.solve({ ...pickInputValues(currentSchema, state.values) });\n\t\temit();\n\t}\n\n\treturn {\n\t\tget values() {\n\t\t\treturn state.values;\n\t\t},\n\t\tget error() {\n\t\t\treturn state.error;\n\t\t},\n\t\tget computeErrors() {\n\t\t\treturn state.computeErrors;\n\t\t},\n\t\tget computeWarnings() {\n\t\t\treturn state.computeWarnings;\n\t\t},\n\t\tget meshes() {\n\t\t\treturn state.meshes;\n\t\t},\n\t\tget hasPendingChanges() {\n\t\t\treturn state.hasPendingChanges;\n\t\t},\n\t\tget hasNeverSolved() {\n\t\t\treturn state.hasNeverSolved;\n\t\t},\n\t\tget isSolving() {\n\t\t\treturn args.driver.isSolving;\n\t\t},\n\n\t\tsetValue(id, value, forceSolve = false) {\n\t\t\tconst { shouldSolve } = applyValueChange(state, id, value, currentSchema?.instanceSolve);\n\t\t\tif (shouldSolve || forceSolve) {\n\t\t\t\tif (forceSolve && !shouldSolve) {\n\t\t\t\t\tstate.pendingValues = {};\n\t\t\t\t\tstate.hasPendingChanges = false;\n\t\t\t\t}\n\t\t\t\tdispatch();\n\t\t\t} else {\n\t\t\t\temit();\n\t\t\t}\n\t\t},\n\n\t\tsolve() {\n\t\t\tdispatch();\n\t\t},\n\n\t\tloadValues(incoming) {\n\t\t\tObject.assign(state.values, incoming);\n\t\t\tif (currentSchema?.instanceSolve !== false) {\n\t\t\t\tdispatch();\n\t\t\t} else {\n\t\t\t\tstate.hasPendingChanges = true;\n\t\t\t\temit();\n\t\t\t}\n\t\t},\n\n\t\trebuild(schema, scopeKey) {\n\t\t\tcurrentSchema = schema;\n\t\t\t// The new definition has its own input space; a matching input key from the prior\n\t\t\t// one must not serve that definition's cached result.\n\t\t\targs.driver.clearCache?.();\n\t\t\tstate.meshes = [];\n\t\t\tstate.error = '';\n\t\t\tstate.computeErrors = [];\n\t\t\tstate.computeWarnings = [];\n\t\t\tstate.pendingValues = {};\n\t\t\tstate.values = buildInitialValues(schema, scopeKey, readExternalValue);\n\t\t\tconst f = makeInitialFlags(schema?.instanceSolve);\n\t\t\tstate.hasPendingChanges = f.hasPendingChanges;\n\t\t\tstate.hasNeverSolved = f.hasNeverSolved;\n\t\t\tif (schema && Object.keys(state.values).length > 0 && schema.instanceSolve !== false) {\n\t\t\t\tdispatch();\n\t\t\t} else {\n\t\t\t\temit();\n\t\t\t}\n\t\t},\n\n\t\treport(result) {\n\t\t\tapplySolveResult(state, result);\n\t\t\temit();\n\t\t},\n\n\t\treportError(message) {\n\t\t\tstate.error = message;\n\t\t\temit();\n\t\t},\n\n\t\tsubscribe(listener) {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => listeners.delete(listener);\n\t\t},\n\n\t\tnotify: emit\n\t};\n}\n","/**\n * Single-in-flight, latest-wins throttle for any async operation: only one run at a\n * time, a newly triggered value overwrites the single pending slot (no queue), and a\n * stale run can be aborted via `AbortController` or timeout.\n *\n * Framework-free: `isRunning` is a plain getter, not a store. A reactive host must\n * subscribe via `onChange` (see `@selvajs/ui`'s rune adapter) — polling the getter\n * directly reads correct values but won't trigger a re-render.\n */\ninterface AsyncThrottleOptions {\n\ttimeout?: number;\n\tonChange?: () => void;\n}\n\nexport interface AsyncThrottle<T> {\n\ttrigger: (values: T) => void;\n\treadonly isRunning: boolean;\n\treadonly hasPending: boolean;\n\tcancel: () => void;\n}\n\n/** Fallback per-run abort timeout (ms) when the caller doesn't pass one. */\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\nexport function createAsyncThrottle<T>(\n\trun: (values: T, signal: AbortSignal) => Promise<void>,\n\toptions: AsyncThrottleOptions = {}\n): AsyncThrottle<T> {\n\tconst { timeout = DEFAULT_TIMEOUT_MS, onChange } = options;\n\n\tlet isRunning = false;\n\tlet pendingValues: T | null = null;\n\tlet currentAbortController: AbortController | null = null;\n\n\tfunction setRunning(next: boolean) {\n\t\tif (isRunning === next) return;\n\t\tisRunning = next;\n\t\tonChange?.();\n\t}\n\n\tfunction abortCurrent() {\n\t\tcurrentAbortController?.abort();\n\t\tcurrentAbortController = null;\n\t}\n\n\tasync function execute(values: T) {\n\t\tabortCurrent();\n\n\t\tcurrentAbortController = new AbortController();\n\t\tconst { signal } = currentAbortController;\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\t// Cleared in `finally` on every other path, so firing means a genuine\n\t\t\t// timeout — the only signal for it (the abort itself is swallowed below).\n\t\t\tconsole.warn(`[Solve/throttle] run exceeded ${timeout}ms — aborting`);\n\t\t\tcurrentAbortController?.abort();\n\t\t}, timeout);\n\n\t\tsetRunning(true);\n\t\ttry {\n\t\t\tawait run(values, signal);\n\t\t} catch (err) {\n\t\t\t// AbortError is expected (timeout or cancel). Non-abort errors must be\n\t\t\t// handled inside `run` — re-throwing here would produce an unhandled\n\t\t\t// rejection because `execute` is always called fire-and-forget.\n\t\t\tif (!(err instanceof Error) || (err.name !== 'AbortError' && err.name !== 'TimeoutError')) {\n\t\t\t\tconsole.error('[Solve/throttle] unhandled error in run:', err);\n\t\t\t}\n\t\t} finally {\n\t\t\tclearTimeout(timeoutId);\n\t\t\tsetRunning(false);\n\t\t\tcurrentAbortController = null;\n\n\t\t\tif (pendingValues !== null) {\n\t\t\t\tconst next = pendingValues;\n\t\t\t\tpendingValues = null;\n\t\t\t\texecute(next);\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction trigger(values: T) {\n\t\tif (isRunning) {\n\t\t\tif (pendingValues !== null) {\n\t\t\t\t// Latest-wins: the previously-queued values are dropped, not run.\n\t\t\t\t// `debug`, not `info`: a slider scrub fires this per frame, and it is a trace of\n\t\t\t\t// normal operation. Promoting it would spam a host's console on every drag.\n\t\t\t\t// eslint-disable-next-line no-console -- see above\n\t\t\t\tconsole.debug('[Solve/throttle] superseded pending run (latest-wins)');\n\t\t\t}\n\t\t\tpendingValues = values;\n\t\t} else {\n\t\t\texecute(values);\n\t\t}\n\t}\n\n\tfunction cancel() {\n\t\tpendingValues = null;\n\t\tabortCurrent();\n\t}\n\n\treturn {\n\t\ttrigger,\n\t\tget isRunning() {\n\t\t\treturn isRunning;\n\t\t},\n\t\tget hasPending() {\n\t\t\treturn pendingValues !== null;\n\t\t},\n\t\tcancel\n\t};\n}\n","// A small LRU keyed on a stable serialization of the solve inputs, sitting in front of the\n// request/response driver: re-solving inputs already seen this session (e.g. dragging a\n// slider back) returns instantly instead of round-tripping. A hit is always a complete\n// result, since only fully-solved values are ever stored.\n//\n// A SolveResult can carry live renderer objects, and a viewer typically takes ownership of\n// every mesh array it renders — disposing the previous content on the next update. So the\n// memo can neither hand out its own instances (they'd be disposed under it, then re-added\n// dead on the next hit) nor drop entries silently (their GPU buffers would leak). It\n// therefore keeps private copies, serves a fresh copy per hit, and releases an entry\n// whenever it leaves the map — but it does not know what a mesh is: `TMesh` is opaque and\n// the clone/release policy is injected, which keeps `three` out of this package entirely.\n\nimport type { SolveResult } from '../shared/solve-fn.js';\n\n/**\n * Deterministic string key for a set of input values. Object keys are sorted at every\n * level so two logically-equal inputs (built in different key order) collide, matching the\n * server's stable-input keying intent. Values are plain JSON — the projected solve inputs\n * never contain functions or cycles.\n */\nexport function stableInputKey(values: Record<string, unknown>): string {\n\treturn serialize(values);\n}\n\nfunction serialize(value: unknown): string {\n\tif (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';\n\tif (Array.isArray(value)) return `[${value.map(serialize).join(',')}]`;\n\tconst obj = value as Record<string, unknown>;\n\tconst keys = Object.keys(obj).sort();\n\treturn `{${keys.map((k) => `${JSON.stringify(k)}:${serialize(obj[k])}`).join(',')}}`;\n}\n\n/**\n * Omit for mesh-free results, or for meshes no consumer takes ownership of: the memo then\n * stores and serves them by reference, which is correct precisely because nothing frees\n * them behind its back.\n *\n * @property clone - Called on the way in AND on every hit, so neither the stored entry nor\n * a previously served one can be disposed by the other's owner.\n * @property release - Must NOT free anything shared with live content — see\n * `releaseSceneObjects` in `@selvajs/visualization/parse`, which skips materials for\n * exactly that reason.\n */\nexport interface MeshPolicy<TMesh> {\n\tclone(meshes: TMesh[]): TMesh[];\n\trelease(meshes: TMesh[]): void;\n}\n\nexport interface SolveMemoOptions<TMesh> {\n\t/**\n\t * Entry cap (entries, not bytes). Solve results can be large, so the default is\n\t * deliberately small — this targets the tight slider-scrub loop, not a durable cache.\n\t */\n\tmax?: number;\n\tmeshPolicy?: MeshPolicy<TMesh>;\n}\n\nexport interface SolveMemo<TMesh = unknown> {\n\tget(values: Record<string, unknown>): SolveResult<TMesh> | undefined;\n\t/** Evicts the LRU tail if `set` pushes the map past its cap. */\n\tset(values: Record<string, unknown>, result: SolveResult<TMesh>): void;\n\tclear(): void;\n}\n\nexport function createSolveMemo<TMesh = unknown>(\n\toptions: SolveMemoOptions<TMesh> = {}\n): SolveMemo<TMesh> {\n\tconst { max = 16, meshPolicy } = options;\n\tconst entries = new Map<string, SolveResult<TMesh>>();\n\n\tfunction release(result: SolveResult<TMesh>): void {\n\t\tif (result.meshes?.length) meshPolicy?.release(result.meshes);\n\t}\n\n\tfunction copy(result: SolveResult<TMesh>): SolveResult<TMesh> {\n\t\tif (!meshPolicy || !result.meshes?.length) return result;\n\t\treturn { ...result, meshes: meshPolicy.clone(result.meshes) };\n\t}\n\n\tfunction evict(key: string): void {\n\t\tconst entry = entries.get(key);\n\t\tif (entry === undefined) return;\n\t\tentries.delete(key);\n\t\trelease(entry);\n\t}\n\n\treturn {\n\t\tget(values) {\n\t\t\tconst key = stableInputKey(values);\n\t\t\tconst hit = entries.get(key);\n\t\t\tif (hit === undefined) return undefined;\n\t\t\t// Refresh recency: re-insert at the tail.\n\t\t\tentries.delete(key);\n\t\t\tentries.set(key, hit);\n\t\t\t// A memo hit skips the transport entirely, so no other log line fires —\n\t\t\t// this line is the only trace it wasn't a fresh solve.\n\t\t\tconsole.info(`[Solve/memo] HIT — served from client memo (${entries.size}/${max})`);\n\t\t\t// The consumer disposes what it renders, so the retained entry must never be\n\t\t\t// the same instance handed out twice.\n\t\t\treturn copy(hit);\n\t\t},\n\t\tset(values, result) {\n\t\t\tconst key = stableInputKey(values);\n\t\t\t// Overwriting a key strands the old value's resources unless it's released first.\n\t\t\tevict(key);\n\t\t\tentries.set(key, copy(result));\n\t\t\twhile (entries.size > max) {\n\t\t\t\tconst oldest = entries.keys().next().value;\n\t\t\t\tif (oldest === undefined) break;\n\t\t\t\tevict(oldest);\n\t\t\t\tconsole.info(`[Solve/memo] evicted LRU entry (cap ${max})`);\n\t\t\t}\n\t\t},\n\t\tclear() {\n\t\t\tif (entries.size > 0) {\n\t\t\t\tconsole.info(`[Solve/memo] cleared ${entries.size} entries (definition changed)`);\n\t\t\t}\n\t\t\tentries.forEach(release);\n\t\t\tentries.clear();\n\t\t}\n\t};\n}\n","import { createAsyncThrottle } from '../async-throttle.js';\nimport { createSolveMemo, type MeshPolicy } from '../solve-memo.js';\nimport type { SolveFn } from '../../shared/solve-fn.js';\nimport type { SolveDriver, SolveReporter } from './driver.js';\n\nexport interface RequestResponseDriverOptions<TMesh> {\n\ttimeout?: number;\n\tonChange?: () => void;\n\t/** Mesh ownership policy for the result memo — see `MeshPolicy` (solve-memo.ts). */\n\tmeshPolicy?: MeshPolicy<TMesh>;\n}\n\n/**\n * `getReporter` is lazy (`() => session`) because the session and driver reference each\n * other — the host builds the driver first, then the session, then can hand this back.\n */\nexport function createRequestResponseDriver<TMesh = unknown>(\n\tonSolve: SolveFn<TMesh>,\n\tgetReporter: () => SolveReporter<TMesh>,\n\toptions: RequestResponseDriverOptions<TMesh> = {}\n): SolveDriver {\n\tconst { meshPolicy, ...throttleOptions } = options;\n\n\t// Checked inside the throttled run, not before triggering it, so a hit only serves\n\t// after the throttle's latest-wins ordering has picked these values to run.\n\tconst memo = createSolveMemo<TMesh>({ meshPolicy });\n\n\tconst throttle = createAsyncThrottle<Record<string, unknown>>(async (values, signal) => {\n\t\tconst cached = memo.get(values);\n\t\tif (cached !== undefined) {\n\t\t\tif (signal.aborted) return;\n\t\t\tgetReporter().report(cached);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tconst result = await onSolve(values, signal);\n\t\t\tif (signal.aborted) {\n\t\t\t\t// eslint-disable-next-line no-console -- normal during a slider scrub; not a warning\n\t\t\t\tconsole.debug('[Solve/driver] solve completed after abort — result discarded');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tmemo.set(values, result);\n\t\t\tgetReporter().report(result);\n\t\t} catch (err) {\n\t\t\tif (signal.aborted) {\n\t\t\t\t// eslint-disable-next-line no-console -- normal during a slider scrub; not a warning\n\t\t\t\tconsole.debug('[Solve/driver] solve aborted (superseded, cancelled, or timed out)');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconsole.warn('[Solve/driver] solve failed:', err);\n\t\t\tgetReporter().reportError(err instanceof Error ? err.message : String(err));\n\t\t}\n\t}, throttleOptions);\n\n\treturn {\n\t\tsolve(values) {\n\t\t\tthrottle.trigger(values);\n\t\t},\n\t\tcancel() {\n\t\t\tthrottle.cancel();\n\t\t},\n\t\tget isSolving() {\n\t\t\treturn throttle.isRunning;\n\t\t},\n\t\tclearCache() {\n\t\t\tmemo.clear();\n\t\t}\n\t};\n}\n","/**\n * `createComputeFetchSolveFn` — a ready-made `SolveFn` that POSTs to a\n * `/api/compute`-shaped HTTP endpoint (the wire contract `runSolvePipeline` +\n * `SolveEngine` produce server-side) and unpacks the result.\n *\n * Ports the resilience behavior an interactive solve endpoint needs regardless\n * of app — 429 cooldown, session-expiry/redirect detection, non-JSON-response\n * guarding, and abort handling at every await point — so a new consumer gets it\n * for free instead of re-deriving it by hand. Mesh decoding is NOT built in:\n * this package stays renderer-agnostic (see `shared/solve-fn.ts`), so a\n * viewer-enabled consumer supplies its own `meshes.extract` hook (typically\n * `getThreeMeshesFromComputeResponse` from `@selvajs/visualization/parse`).\n */\n\nimport { GrasshopperResponseProcessor, type GrasshopperComputeResponse } from '@selvajs/compute';\nimport type { SolveFn, SolveResult } from '../shared/solve-fn.js';\n\nexport interface ComputeFetchSolveFnOptions<TMesh = unknown, TRhino = unknown> {\n\t/** The compute endpoint to POST to, e.g. `/api/compute`. */\n\tendpoint: string;\n\t/** Definition URL (or `local:<guid>`) to solve — read per-solve so it can track a route param. */\n\tdefinitionUrl: () => string;\n\t/** Schema input params, sent as the request body's `inputs`. */\n\tinputs: () => Array<{ id: string }>;\n\t/** Schema output params — drives byId/byName output extraction after a solve. */\n\toutputs: () => Array<{ id: string; nickname?: string }>;\n\tchannel?: () => 'live' | 'draft' | undefined;\n\tversionId?: () => string | null | undefined;\n\t/**\n\t * Omit entirely for a non-viewer consumer — `meshes` on the result stays `[]`\n\t * and no rhino3dm module is ever loaded. `loadRhino` is called lazily on the\n\t * first solve that needs meshes and cached for the lifetime of this `SolveFn`.\n\t */\n\tmeshes?: {\n\t\tloadRhino: () => Promise<TRhino>;\n\t\textract: (\n\t\t\tresponse: GrasshopperComputeResponse,\n\t\t\topts: { debug: boolean; rhino: TRhino }\n\t\t) => TMesh[] | Promise<TMesh[]>;\n\t};\n\t/** Gates ALL console telemetry (timing, cache verdicts, whales, heap). Default `false`. */\n\tdebug?: boolean;\n\t/** Called on a 429. Default: throws a cooldown-aware Error; the cooldown itself is tracked either way. */\n\tonRateLimited?: (retryAfterSeconds: number) => void;\n\t/** Called on a 401 or a login-page redirect. Default: throws an actionable \"reload to sign in again\" Error. */\n\tonSessionExpired?: () => void;\n}\n\nfunction parseServerTiming(header: string | null): Record<string, number> {\n\tconst out: Record<string, number> = {};\n\tif (!header) return out;\n\tfor (const part of header.split(',')) {\n\t\tconst [name, ...params] = part.split(';').map((s) => s.trim());\n\t\tconst dur = params.find((p) => p.startsWith('dur='));\n\t\tif (!name || !dur) continue;\n\t\tconst ms = Number(dur.slice(4));\n\t\tif (Number.isFinite(ms)) out[name] = ms;\n\t}\n\treturn out;\n}\n\nconst defaultOnRateLimited = (retryAfterSeconds: number): never => {\n\tthrow new Error(`Rate limit reached. Try again in ${Math.ceil(retryAfterSeconds)}s.`);\n};\n\nconst defaultOnSessionExpired = (): never => {\n\tthrow new Error(\n\t\t'Your session has expired. Sign in again in a new tab, then re-run — your inputs are preserved.'\n\t);\n};\n\nexport function createComputeFetchSolveFn<TMesh = unknown, TRhino = unknown>(\n\topts: ComputeFetchSolveFnOptions<TMesh, TRhino>\n): SolveFn<TMesh> {\n\tconst debug = opts.debug ?? false;\n\tconst log = (...args: unknown[]) => {\n\t\tif (debug) console.info(...args);\n\t};\n\n\tlet rhinoPromise: Promise<TRhino> | null = null;\n\tfunction getRhino(): Promise<TRhino> {\n\t\tif (!opts.meshes) throw new Error('createComputeFetchSolveFn: meshes option not configured.');\n\t\tif (!rhinoPromise) rhinoPromise = opts.meshes.loadRhino();\n\t\treturn rhinoPromise;\n\t}\n\n\tlet cooldownUntil = 0;\n\n\treturn async (values, signal): Promise<SolveResult<TMesh>> => {\n\t\tconst remainingMs = cooldownUntil - Date.now();\n\t\tif (remainingMs > 0) {\n\t\t\tthrow new Error(`Rate limit reached. Try again in ${Math.ceil(remainingMs / 1000)}s.`);\n\t\t}\n\n\t\tconst solveStart = performance.now();\n\t\tconst inputs = opts.inputs();\n\t\tconst outputs = opts.outputs();\n\t\tconst channel = opts.channel?.();\n\t\tconst versionId = opts.versionId?.();\n\n\t\tconst payload = JSON.stringify({\n\t\t\tinputs,\n\t\t\tvalues,\n\t\t\tdefinitionUrl: opts.definitionUrl(),\n\t\t\t...(versionId ? { versionId } : channel === 'draft' ? { channel: 'draft' } : {})\n\t\t});\n\t\tconst valuesBytes = JSON.stringify(values).length;\n\n\t\tlet res: Response;\n\t\ttry {\n\t\t\tres = await fetch(opts.endpoint, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\t\tbody: payload,\n\t\t\t\tsignal\n\t\t\t});\n\t\t} catch (err) {\n\t\t\tif (signal.aborted) {\n\t\t\t\tlog('[Compute] solve aborted during fetch — empty result discarded');\n\t\t\t\treturn { outputs: {} };\n\t\t\t}\n\t\t\tthrow new Error(\n\t\t\t\t'Request blocked — your session may have expired. Reload the page to sign in again.',\n\t\t\t\t{ cause: err }\n\t\t\t);\n\t\t}\n\n\t\tif (signal.aborted) {\n\t\t\tlog('[Compute] solve aborted after headers — empty result discarded');\n\t\t\treturn { outputs: {} };\n\t\t}\n\n\t\tconst redirectedToLogin = res.redirected && new URL(res.url).pathname === '/login';\n\t\tif (res.status === 401 || redirectedToLogin) {\n\t\t\t(opts.onSessionExpired ?? defaultOnSessionExpired)();\n\t\t}\n\n\t\tif (!res.ok) {\n\t\t\tif (res.status === 503) {\n\t\t\t\tthrow new Error('Compute server is offline or unreachable. Please try again later.');\n\t\t\t}\n\t\t\tconst errorBody = await res.text().catch(() => '');\n\t\t\tlet d: { message?: string; retryAfter?: number } = {};\n\t\t\ttry {\n\t\t\t\td = JSON.parse(errorBody);\n\t\t\t} catch {\n\t\t\t\tif (errorBody) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Compute] non-JSON error body (HTTP ${res.status}):`,\n\t\t\t\t\t\terrorBody.slice(0, 300)\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (res.status === 429) {\n\t\t\t\tconst retryAfter = Number(res.headers.get('Retry-After')) || Number(d.retryAfter) || 5;\n\t\t\t\tcooldownUntil = Date.now() + retryAfter * 1000;\n\t\t\t\t(opts.onRateLimited ?? defaultOnRateLimited)(retryAfter);\n\t\t\t}\n\t\t\tthrow new Error(d.message || `Compute error (HTTP ${res.status})`);\n\t\t}\n\n\t\tconst ttfbMs = performance.now() - solveStart;\n\n\t\tconst downloadStart = performance.now();\n\t\tconst bodyText = await res.text();\n\t\tif (signal.aborted) {\n\t\t\tlog('[Compute] solve aborted mid-download — empty result discarded');\n\t\t\treturn { outputs: {} };\n\t\t}\n\t\tconst downloadMs = performance.now() - downloadStart;\n\t\tconst bytes = bodyText.length;\n\n\t\tlet solved: GrasshopperComputeResponse;\n\t\ttry {\n\t\t\tsolved = JSON.parse(bodyText);\n\t\t} catch (err) {\n\t\t\tthrow new Error(\n\t\t\t\t'Received an invalid response from the server. Reload the page and try again.',\n\t\t\t\t{\n\t\t\t\t\tcause: err\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t\tconst processor = new GrasshopperResponseProcessor(solved, false);\n\n\t\tconst rhino = opts.meshes ? await getRhino() : null;\n\t\tconst meshes =\n\t\t\trhino !== null && opts.meshes\n\t\t\t\t? await opts.meshes.extract(processor.response, { debug, rhino })\n\t\t\t\t: [];\n\n\t\tconst resultOutputs: Record<string, unknown> = {};\n\t\tfor (const o of outputs) {\n\t\t\tconst byId = processor.getValue({ byId: o.id }, { parseValues: true });\n\t\t\tresultOutputs[o.id] =\n\t\t\t\tbyId ??\n\t\t\t\t(o.nickname\n\t\t\t\t\t? processor.getValue({ byName: o.nickname }, { parseValues: true })\n\t\t\t\t\t: undefined);\n\t\t}\n\n\t\tif (debug) {\n\t\t\tconst serverTiming = parseServerTiming(res.headers.get('Server-Timing'));\n\t\t\tconst serverTotal = serverTiming.total ?? 0;\n\t\t\tconst networkMs = Math.max(0, ttfbMs - serverTotal);\n\t\t\tconst sizeMB = bytes / (1024 * 1024);\n\t\t\tconst size = sizeMB >= 1 ? `${sizeMB.toFixed(2)} MB` : `${(bytes / 1024).toFixed(0)} KB`;\n\t\t\tconst mbps = downloadMs > 0 ? (sizeMB / (downloadMs / 1000)).toFixed(1) : '∞';\n\t\t\tconst heapMB = (performance as Performance & { memory?: { usedJSHeapSize: number } }).memory\n\t\t\t\t?.usedJSHeapSize;\n\t\t\tconst heap = heapMB !== undefined ? ` | heap=${(heapMB / (1024 * 1024)).toFixed(0)} MB` : '';\n\t\t\tlog(\n\t\t\t\t`[Compute] req=${(payload.length / 1024).toFixed(0)}KB (values ${(valuesBytes / 1024).toFixed(0)}KB) | ` +\n\t\t\t\t\t`ttfb=${ttfbMs.toFixed(0)}ms (network≈${networkMs.toFixed(0)} + server ${serverTotal.toFixed(0)}) | ` +\n\t\t\t\t\t`download=${downloadMs.toFixed(0)}ms (${size} @ ${mbps} MB/s)${heap}`\n\t\t\t);\n\t\t\tif (serverTiming.selva_cache !== undefined) {\n\t\t\t\tconst cacheMsg = serverTiming.selva_cache\n\t\t\t\t\t? 'HIT — served without calling compute'\n\t\t\t\t\t: 'miss — solved on Rhino.Compute';\n\t\t\t\tlog(`[Compute] └─ cache: ${cacheMsg}`);\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\toutputs: resultOutputs,\n\t\t\tmeshes,\n\t\t\terrors: solved.errors ?? [],\n\t\t\twarnings: solved.warnings ?? []\n\t\t};\n\t};\n}\n"],"mappings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R,EAAa,YAC3B,4CACA,sCACHjC,EAAI,mCAAyByC,CAAQ,EAAE,CACxC,CACD,CAEA,MAAO,CACN,QAASX,EACT,OAAAD,EACA,OAAQH,EAAO,QAAU,CAAC,EAC1B,SAAUA,EAAO,UAAY,CAAC,CAC/B,CACD,CACD","names":["getInputItems","STORAGE_PREFIX","makeKey","scopeKey","inputId","writeExternalValue","args","value","readExternalValue","ref","raw","clearExternalValue","getExternalInputs","schema","item","getDefaultValue","buildInitialValues","schema","scopeKey","read","clientSet","getExternalInputs","e","values","input","stored","getDefaultValue","output","makeInitialFlags","instanceSolve","manual","applyValueChange","state","id","value","pickInputValues","picked","applySolveResult","result","createSolveSession","args","currentSchema","flags","makeInitialFlags","state","buildInitialValues","readExternalValue","listeners","emit","l","dispatch","pickInputValues","id","value","forceSolve","shouldSolve","applyValueChange","incoming","schema","scopeKey","f","result","applySolveResult","message","listener","createAsyncThrottle","run","options","timeout","onChange","isRunning","pendingValues","currentAbortController","setRunning","next","abortCurrent","execute","values","signal","timeoutId","err","trigger","cancel","stableInputKey","values","serialize","value","obj","k","createSolveMemo","options","max","meshPolicy","entries","release","result","copy","evict","key","entry","hit","oldest","createRequestResponseDriver","onSolve","getReporter","options","meshPolicy","throttleOptions","memo","createSolveMemo","throttle","createAsyncThrottle","values","signal","cached","result","err","GrasshopperResponseProcessor","parseServerTiming","header","out","part","name","params","s","dur","p","ms","defaultOnRateLimited","retryAfterSeconds","defaultOnSessionExpired","createComputeFetchSolveFn","opts","debug","log","args","rhinoPromise","getRhino","cooldownUntil","values","signal","remainingMs","solveStart","inputs","outputs","channel","versionId","payload","valuesBytes","res","err","redirectedToLogin","errorBody","d","retryAfter","ttfbMs","downloadStart","bodyText","downloadMs","bytes","solved","processor","rhino","meshes","resultOutputs","o","byId","serverTiming","serverTotal","networkMs","sizeMB","size","mbps","heapMB","heap","cacheMsg"]}
|
|
1
|
+
{"version":3,"sources":["../src/client/external-storage.ts","../src/client/solve-session-core.ts","../src/client/solve-session.ts","../src/client/async-throttle.ts","../src/client/solve-memo.ts","../src/client/drivers/request-response.ts","../src/client/compute-fetch-solve-fn.ts"],"sourcesContent":["// Transit storage for inputs with source.kind === 'client': a producer route writes the\n// value here, the solver route reads it back. Keyed by (scopeKey, inputId) so values\n// don't bleed across solver contexts — scopeKey is whatever uniquely identifies one\n// (sessionId in plugin-ui/preview, definition guid in selva/library).\n\nimport type { UISchema } from '@selvajs/schemas';\nimport { getInputItems } from '@selvajs/schemas';\n\nconst STORAGE_PREFIX = 'external';\n\nfunction makeKey(scopeKey: string, inputId: string): string {\n\treturn `${STORAGE_PREFIX}:${scopeKey}:${inputId}`;\n}\n\nexport interface ExternalValueRef {\n\tscopeKey: string;\n\tinputId: string;\n}\n\nexport function writeExternalValue(args: ExternalValueRef & { value: unknown }): void {\n\tconst { scopeKey, inputId, value } = args;\n\tif (!scopeKey || !inputId) return;\n\tif (typeof sessionStorage === 'undefined') return;\n\tsessionStorage.setItem(makeKey(scopeKey, inputId), JSON.stringify(value));\n}\n\nexport function readExternalValue(ref: ExternalValueRef): unknown | undefined {\n\tconst { scopeKey, inputId } = ref;\n\tif (!scopeKey || !inputId) return undefined;\n\tif (typeof sessionStorage === 'undefined') return undefined;\n\tconst raw = sessionStorage.getItem(makeKey(scopeKey, inputId));\n\tif (raw === null) return undefined;\n\ttry {\n\t\treturn JSON.parse(raw);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function clearExternalValue(ref: ExternalValueRef): void {\n\tconst { scopeKey, inputId } = ref;\n\tif (!scopeKey || !inputId) return;\n\tif (typeof sessionStorage === 'undefined') return;\n\tsessionStorage.removeItem(makeKey(scopeKey, inputId));\n}\n\nexport interface ExternalInput {\n\tparamId: string;\n\tdisplayName: string;\n}\n\nexport function getExternalInputs(schema: UISchema): ExternalInput[] {\n\treturn getInputItems(schema)\n\t\t.filter((item) => item.source?.kind === 'client')\n\t\t.map((item) => ({\n\t\t\tparamId: item.paramId,\n\t\t\tdisplayName: item.displayName ?? item.paramId\n\t\t}));\n}\n","// Pure transition logic for a Solve Session.\n//\n// This module holds the value/lifecycle state machine with no transport and no state\n// ownership: how values are seeded (including client-sourced hydration), when a value\n// change should dispatch a solve vs. defer it, and what a reported solve result does to\n// the flags. `solve-session.ts` is a thin shell that owns the state object and the\n// subscriber set; every decision lives here, which is what makes it directly testable.\n\nimport type { UISchema } from '@selvajs/schemas';\nimport { getDefaultValue } from '@selvajs/schemas';\nimport { getExternalInputs, type ExternalValueRef } from './external-storage.js';\nimport type { SolveResult } from '../shared/solve-fn.js';\n\n/**\n * The slice of a reported result the session keeps addressable, so a host can commit exactly\n * what the viewer is showing — `source` and `values` included, already memo-correct.\n *\n * Mesh-free by construction. `SolveResult.meshes` are GPU-backed and the viewer disposes what\n * it renders on the next scene update, which is why the memo carries a `MeshPolicy`\n * clone/release contract at all. Retaining them here would hand out disposed instances after\n * the next solve, with no policy governing them and no owner. Everything left is inert JSON;\n * live meshes stay on `session.meshes`.\n */\nexport type RetainedSolveResult<TSource = unknown> = Omit<SolveResult<never, TSource>, 'meshes'>;\n\nexport interface SolveSessionState {\n\tvalues: Record<string, unknown>;\n\terror: string;\n\tcomputeErrors: string[];\n\tcomputeWarnings: string[];\n\tmeshes: unknown[];\n\t/** Values changed since the last solve, in manual (instanceSolve === false) mode. */\n\tpendingValues: Record<string, unknown>;\n\thasPendingChanges: boolean;\n\thasNeverSolved: boolean;\n\t/**\n\t * The last result reported, minus its meshes. Null before the first solve.\n\t *\n\t * Lags `values` by design: nothing updates it on `setValue` or `loadValues`, so between a\n\t * value change and the next report it describes the *previous* input set. That is what a\n\t * commit gate wants — what is on screen, not what is pending — so `lastResult.values`\n\t * disagreeing with `state.values` mid-scrub is the feature, not a bug.\n\t */\n\tlastResult: RetainedSolveResult | null;\n}\n\nexport type ExternalReader = (ref: ExternalValueRef) => unknown | undefined;\n\n/**\n * Client-sourced inputs are hydrated from `read` and left absent when no stored value\n * exists, so the missing-inputs panel can detect them. Other inputs fall back to their\n * declared default, then the paramType default.\n */\nexport function buildInitialValues(\n\tschema: UISchema,\n\tscopeKey: string,\n\tread: ExternalReader\n): Record<string, unknown> {\n\tconst clientSet = new Set(getExternalInputs(schema).map((e) => e.paramId));\n\tconst values: Record<string, unknown> = {};\n\tfor (const input of schema.inputs) {\n\t\tif (clientSet.has(input.id)) {\n\t\t\tconst stored = read({ scopeKey, inputId: input.id });\n\t\t\tif (stored !== undefined) values[input.id] = stored;\n\t\t\tcontinue;\n\t\t}\n\t\tvalues[input.id] = input.default ?? getDefaultValue(input.paramType);\n\t}\n\tfor (const output of schema.outputs) {\n\t\tvalues[output.id] = null;\n\t}\n\treturn values;\n}\n\n/** Manual-solve schemas (instanceSolve === false) start dirty; auto-solve schemas start clean. */\nexport function makeInitialFlags(instanceSolve: boolean | undefined): {\n\thasPendingChanges: boolean;\n\thasNeverSolved: boolean;\n} {\n\tconst manual = instanceSolve === false;\n\treturn { hasPendingChanges: manual, hasNeverSolved: manual };\n}\n\n/** Manual mode defers (records the pending value, raises the dirty flag) instead of solving. */\nexport function applyValueChange(\n\tstate: SolveSessionState,\n\tid: string,\n\tvalue: unknown,\n\tinstanceSolve: boolean | undefined\n): { state: SolveSessionState; shouldSolve: boolean } {\n\tstate.values[id] = value;\n\tif (instanceSolve === false) {\n\t\tstate.pendingValues[id] = value;\n\t\tstate.hasPendingChanges = true;\n\t\treturn { state, shouldSolve: false };\n\t}\n\treturn { state, shouldSolve: true };\n}\n\n/**\n * Solve outputs live in the same `values` map as inputs (so widgets like dynamic value\n * lists can read them) but must not be echoed back to the driver: a measured 6.4 MB\n * options-list output showed this can re-upload a multi-MB payload no backend reads.\n */\nexport function pickInputValues(\n\tschema: UISchema | undefined,\n\tvalues: Record<string, unknown>\n): Record<string, unknown> {\n\tif (!schema?.inputs) return values;\n\tconst picked: Record<string, unknown> = {};\n\tfor (const input of schema.inputs) {\n\t\tif (input.id in values) picked[input.id] = values[input.id];\n\t}\n\treturn picked;\n}\n\nexport function applySolveResult(state: SolveSessionState, result: SolveResult): SolveSessionState {\n\tstate.error = '';\n\tstate.computeErrors = result.errors ?? [];\n\tstate.computeWarnings = result.warnings ?? [];\n\tstate.meshes = result.meshes ?? [];\n\tconst { meshes: _meshes, ...retained } = result;\n\tstate.lastResult = retained;\n\tObject.assign(state.values, result.outputs);\n\tstate.pendingValues = {};\n\tstate.hasPendingChanges = false;\n\tstate.hasNeverSolved = false;\n\treturn state;\n}\n","// A framework-free shell over the pure transition logic in solve-session-core.ts: owns the\n// live values/flags, delegates every transition to the core, and drives solves through a\n// transport-agnostic SolveDriver.\n//\n// State is exposed as plain getters; it carries no framework reactivity of its own, so a\n// Svelte host must wrap it — see `useSolveSession.svelte.ts` in `@selvajs/ui`, which\n// republishes these getters as $state. Reading a getter without subscribing gives a\n// correct value but will not re-render.\n\nimport type { UISchema } from '@selvajs/schemas';\nimport { readExternalValue } from './external-storage.js';\nimport type { SolveResult } from '../shared/solve-fn.js';\nimport type { SolveDriver } from './drivers/driver.js';\nimport {\n\tbuildInitialValues,\n\tmakeInitialFlags,\n\tapplyValueChange,\n\tapplySolveResult,\n\tpickInputValues,\n\ttype SolveSessionState,\n\ttype RetainedSolveResult\n} from './solve-session-core.js';\n\nexport interface SolveSession {\n\treadonly values: Record<string, unknown>;\n\treadonly error: string;\n\treadonly computeErrors: string[];\n\treadonly computeWarnings: string[];\n\treadonly meshes: unknown[];\n\t/**\n\t * The last reported result without its meshes — what the viewer is currently showing,\n\t * including the `source`/`values` pair a commit path needs. Null before the first solve,\n\t * and again after `rebuild()`. Survives `reportError`: a failed solve leaves the last good\n\t * geometry on screen, so a host committing what it sees should still see what produced it.\n\t */\n\treadonly lastResult: RetainedSolveResult | null;\n\treadonly hasPendingChanges: boolean;\n\treadonly hasNeverSolved: boolean;\n\treadonly isSolving: boolean;\n\t/** `forceSolve` overrides manual mode for system-initiated reconciliation (e.g. a dynamic value list pruning a vanished selection), so the output can't lag behind the new value. */\n\tsetValue(id: string, value: unknown, forceSolve?: boolean): void;\n\tsolve(): void;\n\t/** Merges incoming values, then solves (auto) or marks dirty (manual). */\n\tloadValues(incoming: Record<string, unknown>): void;\n\trebuild(schema: UISchema, scopeKey: string): void;\n\treport(result: SolveResult): void;\n\treportError(message: string): void;\n\t/** Fires after any mutation of the getters above, including driver-reported `isSolving` transitions. */\n\tsubscribe(listener: () => void): () => void;\n\t/** For driver-owned state the session only forwards: `isSolving` lives on the driver, so wire this to its `onChange`. */\n\tnotify(): void;\n}\n\nexport interface SolveSessionArgs {\n\tschema: UISchema;\n\tscopeKey: string;\n\tdriver: SolveDriver;\n}\n\nexport function createSolveSession(args: SolveSessionArgs): SolveSession {\n\tlet currentSchema = args.schema;\n\n\tconst flags = makeInitialFlags(currentSchema?.instanceSolve);\n\tconst state: SolveSessionState = {\n\t\tvalues: buildInitialValues(currentSchema, args.scopeKey, readExternalValue),\n\t\terror: '',\n\t\tcomputeErrors: [],\n\t\tcomputeWarnings: [],\n\t\tmeshes: [],\n\t\tpendingValues: {},\n\t\thasPendingChanges: flags.hasPendingChanges,\n\t\thasNeverSolved: flags.hasNeverSolved,\n\t\tlastResult: null\n\t};\n\n\tconst listeners = new Set<() => void>();\n\tconst emit = () => listeners.forEach((l) => l());\n\n\tfunction dispatch() {\n\t\t// Copy: state.values is the live map, and a driver may hold the payload across an\n\t\t// async solve — a later setValue must not mutate what's already in flight.\n\t\targs.driver.solve({ ...pickInputValues(currentSchema, state.values) });\n\t\temit();\n\t}\n\n\treturn {\n\t\tget values() {\n\t\t\treturn state.values;\n\t\t},\n\t\tget error() {\n\t\t\treturn state.error;\n\t\t},\n\t\tget computeErrors() {\n\t\t\treturn state.computeErrors;\n\t\t},\n\t\tget computeWarnings() {\n\t\t\treturn state.computeWarnings;\n\t\t},\n\t\tget meshes() {\n\t\t\treturn state.meshes;\n\t\t},\n\t\tget lastResult() {\n\t\t\treturn state.lastResult;\n\t\t},\n\t\tget hasPendingChanges() {\n\t\t\treturn state.hasPendingChanges;\n\t\t},\n\t\tget hasNeverSolved() {\n\t\t\treturn state.hasNeverSolved;\n\t\t},\n\t\tget isSolving() {\n\t\t\treturn args.driver.isSolving;\n\t\t},\n\n\t\tsetValue(id, value, forceSolve = false) {\n\t\t\tconst { shouldSolve } = applyValueChange(state, id, value, currentSchema?.instanceSolve);\n\t\t\tif (shouldSolve || forceSolve) {\n\t\t\t\tif (forceSolve && !shouldSolve) {\n\t\t\t\t\tstate.pendingValues = {};\n\t\t\t\t\tstate.hasPendingChanges = false;\n\t\t\t\t}\n\t\t\t\tdispatch();\n\t\t\t} else {\n\t\t\t\temit();\n\t\t\t}\n\t\t},\n\n\t\tsolve() {\n\t\t\tdispatch();\n\t\t},\n\n\t\tloadValues(incoming) {\n\t\t\tObject.assign(state.values, incoming);\n\t\t\tif (currentSchema?.instanceSolve !== false) {\n\t\t\t\tdispatch();\n\t\t\t} else {\n\t\t\t\tstate.hasPendingChanges = true;\n\t\t\t\temit();\n\t\t\t}\n\t\t},\n\n\t\trebuild(schema, scopeKey) {\n\t\t\tcurrentSchema = schema;\n\t\t\t// The new definition has its own input space; a matching input key from the prior\n\t\t\t// one must not serve that definition's cached result.\n\t\t\targs.driver.clearCache?.();\n\t\t\tstate.meshes = [];\n\t\t\t// Same reason as clearCache: a retained result belongs to the previous definition.\n\t\t\tstate.lastResult = null;\n\t\t\tstate.error = '';\n\t\t\tstate.computeErrors = [];\n\t\t\tstate.computeWarnings = [];\n\t\t\tstate.pendingValues = {};\n\t\t\tstate.values = buildInitialValues(schema, scopeKey, readExternalValue);\n\t\t\tconst f = makeInitialFlags(schema?.instanceSolve);\n\t\t\tstate.hasPendingChanges = f.hasPendingChanges;\n\t\t\tstate.hasNeverSolved = f.hasNeverSolved;\n\t\t\tif (schema && Object.keys(state.values).length > 0 && schema.instanceSolve !== false) {\n\t\t\t\tdispatch();\n\t\t\t} else {\n\t\t\t\temit();\n\t\t\t}\n\t\t},\n\n\t\treport(result) {\n\t\t\tapplySolveResult(state, result);\n\t\t\temit();\n\t\t},\n\n\t\treportError(message) {\n\t\t\tstate.error = message;\n\t\t\temit();\n\t\t},\n\n\t\tsubscribe(listener) {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => listeners.delete(listener);\n\t\t},\n\n\t\tnotify: emit\n\t};\n}\n","/**\n * Single-in-flight, latest-wins throttle for any async operation: only one run at a\n * time, a newly triggered value overwrites the single pending slot (no queue), and a\n * stale run can be aborted via `AbortController` or timeout.\n *\n * Framework-free: `isRunning` is a plain getter, not a store. A reactive host must\n * subscribe via `onChange` (see `@selvajs/ui`'s rune adapter) — polling the getter\n * directly reads correct values but won't trigger a re-render.\n */\ninterface AsyncThrottleOptions {\n\t/**\n\t * How long one run may take before it is aborted (ms). Required and deliberately\n\t * undefaulted: this is a generic throttle, so it has no basis for guessing what\n\t * the caller's work costs. Callers driving a Selva solve pass the deadline the\n\t * server enforces (`COMPUTE_SOLVE_DEADLINE_MS`) — a shorter local guess would abort\n\t * solves the server would have finished.\n\t */\n\trunDeadlineMs: number;\n\tonChange?: () => void;\n}\n\nexport interface AsyncThrottle<T> {\n\ttrigger: (values: T) => void;\n\treadonly isRunning: boolean;\n\treadonly hasPending: boolean;\n\tcancel: () => void;\n}\n\nexport function createAsyncThrottle<T>(\n\trun: (values: T, signal: AbortSignal) => Promise<void>,\n\toptions: AsyncThrottleOptions\n): AsyncThrottle<T> {\n\tconst { runDeadlineMs, onChange } = options;\n\n\tlet isRunning = false;\n\tlet pendingValues: T | null = null;\n\tlet currentAbortController: AbortController | null = null;\n\n\tfunction setRunning(next: boolean) {\n\t\tif (isRunning === next) return;\n\t\tisRunning = next;\n\t\tonChange?.();\n\t}\n\n\tfunction abortCurrent() {\n\t\tcurrentAbortController?.abort();\n\t\tcurrentAbortController = null;\n\t}\n\n\tasync function execute(values: T) {\n\t\tabortCurrent();\n\n\t\tcurrentAbortController = new AbortController();\n\t\tconst { signal } = currentAbortController;\n\t\tconst deadlineId = setTimeout(() => {\n\t\t\t// Cleared in `finally` on every other path, so firing means a genuine\n\t\t\t// timeout — the only signal for it (the abort itself is swallowed below).\n\t\t\tconsole.warn(`[Solve/throttle] run exceeded ${runDeadlineMs}ms — aborting`);\n\t\t\tcurrentAbortController?.abort();\n\t\t}, runDeadlineMs);\n\n\t\tsetRunning(true);\n\t\ttry {\n\t\t\tawait run(values, signal);\n\t\t} catch (err) {\n\t\t\t// AbortError is expected (timeout or cancel). Non-abort errors must be\n\t\t\t// handled inside `run` — re-throwing here would produce an unhandled\n\t\t\t// rejection because `execute` is always called fire-and-forget.\n\t\t\tif (!(err instanceof Error) || (err.name !== 'AbortError' && err.name !== 'TimeoutError')) {\n\t\t\t\tconsole.error('[Solve/throttle] unhandled error in run:', err);\n\t\t\t}\n\t\t} finally {\n\t\t\tclearTimeout(deadlineId);\n\t\t\tsetRunning(false);\n\t\t\tcurrentAbortController = null;\n\n\t\t\tif (pendingValues !== null) {\n\t\t\t\tconst next = pendingValues;\n\t\t\t\tpendingValues = null;\n\t\t\t\texecute(next);\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction trigger(values: T) {\n\t\tif (isRunning) {\n\t\t\tif (pendingValues !== null) {\n\t\t\t\t// Latest-wins: the previously-queued values are dropped, not run.\n\t\t\t\t// `debug`, not `info`: a slider scrub fires this per frame, and it is a trace of\n\t\t\t\t// normal operation. Promoting it would spam a host's console on every drag.\n\t\t\t\t// eslint-disable-next-line no-console -- see above\n\t\t\t\tconsole.debug('[Solve/throttle] superseded pending run (latest-wins)');\n\t\t\t}\n\t\t\tpendingValues = values;\n\t\t} else {\n\t\t\texecute(values);\n\t\t}\n\t}\n\n\tfunction cancel() {\n\t\tpendingValues = null;\n\t\tabortCurrent();\n\t}\n\n\treturn {\n\t\ttrigger,\n\t\tget isRunning() {\n\t\t\treturn isRunning;\n\t\t},\n\t\tget hasPending() {\n\t\t\treturn pendingValues !== null;\n\t\t},\n\t\tcancel\n\t};\n}\n","// LRU cache of solve results keyed on a stable serialization of the inputs, so re-solving\n// something already seen this session (e.g. dragging a slider back) returns instantly\n// instead of round-tripping.\n//\n// A viewer typically takes ownership of every mesh it renders, disposing the previous\n// content on the next update. So the memo can't hand out its own stored instances (they'd\n// get disposed under it) or drop entries silently (their GPU buffers would leak): it keeps\n// private copies via an injected clone/release policy, which also keeps `three` out of this\n// package — `TMesh` stays opaque here.\n\nimport type { SolveResult } from '../shared/solve-fn.js';\n\n/**\n * Deterministic string key for a set of input values. Sorts object keys at every level so\n * two logically-equal inputs built in different key order collide.\n */\nexport function stableInputKey(values: Record<string, unknown>): string {\n\treturn serialize(values);\n}\n\nfunction serialize(value: unknown): string {\n\tif (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';\n\tif (Array.isArray(value)) return `[${value.map(serialize).join(',')}]`;\n\tconst obj = value as Record<string, unknown>;\n\tconst keys = Object.keys(obj).sort();\n\treturn `{${keys.map((k) => `${JSON.stringify(k)}:${serialize(obj[k])}`).join(',')}}`;\n}\n\n/**\n * Omit when results are mesh-free or nothing takes ownership of the meshes — the memo then\n * stores and serves them by reference, which is safe only because nothing frees them behind\n * its back.\n */\nexport interface MeshPolicy<TMesh> {\n\t/** Called on the way in and on every hit, so the stored entry and a served copy are never the same instance. */\n\tclone(meshes: TMesh[]): TMesh[];\n\t/** Must not free anything shared with live content (e.g. materials another object still uses). */\n\trelease(meshes: TMesh[]): void;\n}\n\nexport interface SolveMemoOptions<TMesh> {\n\t/** Entry cap, not a byte cap. Kept small on purpose: this targets the slider-scrub loop, not a durable cache. */\n\tmax?: number;\n\tmeshPolicy?: MeshPolicy<TMesh>;\n}\n\nexport interface SolveMemo<TMesh = unknown> {\n\tget(values: Record<string, unknown>): SolveResult<TMesh> | undefined;\n\tset(values: Record<string, unknown>, result: SolveResult<TMesh>): void;\n\tclear(): void;\n}\n\nexport function createSolveMemo<TMesh = unknown>(\n\toptions: SolveMemoOptions<TMesh> = {}\n): SolveMemo<TMesh> {\n\tconst { max = 16, meshPolicy } = options;\n\tconst entries = new Map<string, SolveResult<TMesh>>();\n\n\tfunction release(result: SolveResult<TMesh>): void {\n\t\tif (result.meshes?.length) meshPolicy?.release(result.meshes);\n\t}\n\n\tfunction copy(result: SolveResult<TMesh>): SolveResult<TMesh> {\n\t\tif (!meshPolicy || !result.meshes?.length) return result;\n\t\treturn { ...result, meshes: meshPolicy.clone(result.meshes) };\n\t}\n\n\tfunction evict(key: string): void {\n\t\tconst entry = entries.get(key);\n\t\tif (entry === undefined) return;\n\t\tentries.delete(key);\n\t\trelease(entry);\n\t}\n\n\treturn {\n\t\tget(values) {\n\t\t\tconst key = stableInputKey(values);\n\t\t\tconst hit = entries.get(key);\n\t\t\tif (hit === undefined) return undefined;\n\t\t\tentries.delete(key);\n\t\t\tentries.set(key, hit);\n\t\t\tconsole.info(`[Solve/memo] HIT — served from client memo (${entries.size}/${max})`);\n\t\t\treturn copy(hit);\n\t\t},\n\t\tset(values, result) {\n\t\t\tconst key = stableInputKey(values);\n\t\t\tevict(key);\n\t\t\tentries.set(key, copy(result));\n\t\t\twhile (entries.size > max) {\n\t\t\t\tconst oldest = entries.keys().next().value;\n\t\t\t\tif (oldest === undefined) break;\n\t\t\t\tevict(oldest);\n\t\t\t\tconsole.info(`[Solve/memo] evicted LRU entry (cap ${max})`);\n\t\t\t}\n\t\t},\n\t\tclear() {\n\t\t\tif (entries.size > 0) {\n\t\t\t\tconsole.info(`[Solve/memo] cleared ${entries.size} entries (definition changed)`);\n\t\t\t}\n\t\t\tentries.forEach(release);\n\t\t\tentries.clear();\n\t\t}\n\t};\n}\n","import { createAsyncThrottle } from '../async-throttle.js';\nimport { createSolveMemo, type MeshPolicy } from '../solve-memo.js';\nimport type { SolveFn } from '../../shared/solve-fn.js';\nimport type { SolveDriver, SolveReporter } from './driver.js';\n\nexport interface RequestResponseDriverOptions<TMesh> {\n\t/** How long one solve may take before the client aborts it (ms). Pass the server's `COMPUTE_SOLVE_DEADLINE_MS` so the two agree. */\n\tsolveDeadlineMs: number;\n\tonChange?: () => void;\n\t/** Mesh ownership policy for the result memo — see `MeshPolicy` (solve-memo.ts). */\n\tmeshPolicy?: MeshPolicy<TMesh>;\n}\n\n/**\n * `getReporter` is lazy (`() => session`) because the session and driver reference each\n * other — the host builds the driver first, then the session, then can hand this back.\n */\nexport function createRequestResponseDriver<TMesh = unknown>(\n\tonSolve: SolveFn<TMesh>,\n\tgetReporter: () => SolveReporter<TMesh>,\n\toptions: RequestResponseDriverOptions<TMesh>\n): SolveDriver {\n\tconst { meshPolicy, solveDeadlineMs, onChange } = options;\n\n\t// Checked inside the throttled run, not before triggering it, so a hit only serves\n\t// after the throttle's latest-wins ordering has picked these values to run.\n\tconst memo = createSolveMemo<TMesh>({ meshPolicy });\n\n\tconst throttle = createAsyncThrottle<Record<string, unknown>>(\n\t\tasync (values, signal) => {\n\t\t\tconst cached = memo.get(values);\n\t\t\tif (cached !== undefined) {\n\t\t\t\tif (signal.aborted) return;\n\t\t\t\tgetReporter().report(cached);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await onSolve(values, signal);\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\t// eslint-disable-next-line no-console -- normal during a slider scrub; not a warning\n\t\t\t\t\tconsole.debug('[Solve/driver] solve completed after abort — result discarded');\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// Stamped here rather than in the SolveFn: a memo hit never calls it, so values\n\t\t\t\t// captured inside would pair the served result with whatever solved last.\n\t\t\t\tconst stamped = { ...result, values };\n\t\t\t\tmemo.set(values, stamped);\n\t\t\t\tgetReporter().report(stamped);\n\t\t\t} catch (err) {\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\t// eslint-disable-next-line no-console -- normal during a slider scrub; not a warning\n\t\t\t\t\tconsole.debug('[Solve/driver] solve aborted (superseded, cancelled, or timed out)');\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconsole.warn('[Solve/driver] solve failed:', err);\n\t\t\t\tgetReporter().reportError(err instanceof Error ? err.message : String(err));\n\t\t\t}\n\t\t},\n\t\t// The throttle is generic, so the solve deadline is what bounds one of its runs.\n\t\t{ runDeadlineMs: solveDeadlineMs, onChange }\n\t);\n\n\treturn {\n\t\tsolve(values) {\n\t\t\tthrottle.trigger(values);\n\t\t},\n\t\tcancel() {\n\t\t\tthrottle.cancel();\n\t\t},\n\t\tget isSolving() {\n\t\t\treturn throttle.isRunning;\n\t\t},\n\t\tclearCache() {\n\t\t\tmemo.clear();\n\t\t}\n\t};\n}\n","/**\n * `createComputeFetchSolveFn` — a ready-made `SolveFn` that POSTs to a\n * `/api/compute`-shaped HTTP endpoint (the wire contract `runSolvePipeline` +\n * `SolveEngine` produce server-side) and unpacks the result.\n *\n * Ports the resilience behavior an interactive solve endpoint needs regardless\n * of app — 429 cooldown, session-expiry/redirect detection, non-JSON-response\n * guarding, and abort handling at every await point — so a new consumer gets it\n * for free instead of re-deriving it by hand. Mesh decoding is NOT built in:\n * this package stays renderer-agnostic (see `shared/solve-fn.ts`), so a\n * viewer-enabled consumer supplies its own `meshes.extract` hook (typically\n * `getThreeMeshesFromComputeResponse` from `@selvajs/visualization/parse`).\n */\n\nimport { GrasshopperResponseProcessor, type GrasshopperComputeResponse } from '@selvajs/compute';\nimport type { SolveFn, SolveResult } from '../shared/solve-fn.js';\n\nexport interface ComputeFetchSolveFnOptions<TMesh = unknown, TRhino = unknown> {\n\t/** The compute endpoint to POST to, e.g. `/api/compute`. */\n\tendpoint: string;\n\t/** Definition URL (or `local:<guid>`) to solve — read per-solve so it can track a route param. */\n\tdefinitionUrl: () => string;\n\t/** Schema input params, sent as the request body's `inputs`. */\n\tinputs: () => Array<{ id: string }>;\n\t/** Schema output params — drives byId/byName output extraction after a solve. */\n\toutputs: () => Array<{ id: string; nickname?: string }>;\n\tchannel?: () => 'live' | 'draft' | undefined;\n\tversionId?: () => string | null | undefined;\n\t/**\n\t * Omit entirely for a non-viewer consumer — `meshes` on the result stays `[]`\n\t * and no rhino3dm module is ever loaded. `loadRhino` is called lazily on the\n\t * first solve that needs meshes and cached for the lifetime of this `SolveFn`.\n\t */\n\tmeshes?: {\n\t\tloadRhino: () => Promise<TRhino>;\n\t\textract: (\n\t\t\tresponse: GrasshopperComputeResponse,\n\t\t\topts: { debug: boolean; rhino: TRhino }\n\t\t) => TMesh[] | Promise<TMesh[]>;\n\t};\n\t/** Gates ALL console telemetry (timing, cache verdicts, whales, heap). Default `false`. */\n\tdebug?: boolean;\n\t/** Called on a 429. Default: throws a cooldown-aware Error; the cooldown itself is tracked either way. */\n\tonRateLimited?: (retryAfterSeconds: number) => void;\n\t/** Called on a 401 or a login-page redirect. Default: throws an actionable \"reload to sign in again\" Error. */\n\tonSessionExpired?: () => void;\n}\n\nfunction parseServerTiming(header: string | null): Record<string, number> {\n\tconst out: Record<string, number> = {};\n\tif (!header) return out;\n\tfor (const part of header.split(',')) {\n\t\tconst [name, ...params] = part.split(';').map((s) => s.trim());\n\t\tconst dur = params.find((p) => p.startsWith('dur='));\n\t\tif (!name || !dur) continue;\n\t\tconst ms = Number(dur.slice(4));\n\t\tif (Number.isFinite(ms)) out[name] = ms;\n\t}\n\treturn out;\n}\n\nconst defaultOnRateLimited = (retryAfterSeconds: number): never => {\n\tthrow new Error(`Rate limit reached. Try again in ${Math.ceil(retryAfterSeconds)}s.`);\n};\n\nconst defaultOnSessionExpired = (): never => {\n\tthrow new Error(\n\t\t'Your session has expired. Sign in again in a new tab, then re-run — your inputs are preserved.'\n\t);\n};\n\nexport function createComputeFetchSolveFn<TMesh = unknown, TRhino = unknown>(\n\topts: ComputeFetchSolveFnOptions<TMesh, TRhino>\n): SolveFn<TMesh, GrasshopperComputeResponse> {\n\tconst debug = opts.debug ?? false;\n\tconst log = (...args: unknown[]) => {\n\t\tif (debug) console.info(...args);\n\t};\n\n\tlet rhinoPromise: Promise<TRhino> | null = null;\n\tfunction getRhino(): Promise<TRhino> {\n\t\tif (!opts.meshes) throw new Error('createComputeFetchSolveFn: meshes option not configured.');\n\t\tif (!rhinoPromise) rhinoPromise = opts.meshes.loadRhino();\n\t\treturn rhinoPromise;\n\t}\n\n\tlet cooldownUntil = 0;\n\n\treturn async (values, signal): Promise<SolveResult<TMesh, GrasshopperComputeResponse>> => {\n\t\tconst remainingMs = cooldownUntil - Date.now();\n\t\tif (remainingMs > 0) {\n\t\t\tthrow new Error(`Rate limit reached. Try again in ${Math.ceil(remainingMs / 1000)}s.`);\n\t\t}\n\n\t\tconst solveStart = performance.now();\n\t\tconst inputs = opts.inputs();\n\t\tconst outputs = opts.outputs();\n\t\tconst channel = opts.channel?.();\n\t\tconst versionId = opts.versionId?.();\n\n\t\tconst payload = JSON.stringify({\n\t\t\tinputs,\n\t\t\tvalues,\n\t\t\tdefinitionUrl: opts.definitionUrl(),\n\t\t\t...(versionId ? { versionId } : channel === 'draft' ? { channel: 'draft' } : {})\n\t\t});\n\t\tconst valuesBytes = JSON.stringify(values).length;\n\n\t\tlet res: Response;\n\t\ttry {\n\t\t\tres = await fetch(opts.endpoint, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\t\tbody: payload,\n\t\t\t\tsignal\n\t\t\t});\n\t\t} catch (err) {\n\t\t\tif (signal.aborted) {\n\t\t\t\tlog('[Compute] solve aborted during fetch — empty result discarded');\n\t\t\t\treturn { outputs: {} };\n\t\t\t}\n\t\t\tthrow new Error(\n\t\t\t\t'Request blocked — your session may have expired. Reload the page to sign in again.',\n\t\t\t\t{ cause: err }\n\t\t\t);\n\t\t}\n\n\t\tif (signal.aborted) {\n\t\t\tlog('[Compute] solve aborted after headers — empty result discarded');\n\t\t\treturn { outputs: {} };\n\t\t}\n\n\t\tconst redirectedToLogin = res.redirected && new URL(res.url).pathname === '/login';\n\t\tif (res.status === 401 || redirectedToLogin) {\n\t\t\t(opts.onSessionExpired ?? defaultOnSessionExpired)();\n\t\t}\n\n\t\tif (!res.ok) {\n\t\t\tif (res.status === 503) {\n\t\t\t\tthrow new Error('Compute server is offline or unreachable. Please try again later.');\n\t\t\t}\n\t\t\tconst errorBody = await res.text().catch(() => '');\n\t\t\tlet d: { message?: string; retryAfter?: number } = {};\n\t\t\ttry {\n\t\t\t\td = JSON.parse(errorBody);\n\t\t\t} catch {\n\t\t\t\tif (errorBody) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[Compute] non-JSON error body (HTTP ${res.status}):`,\n\t\t\t\t\t\terrorBody.slice(0, 300)\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (res.status === 429) {\n\t\t\t\tconst retryAfter = Number(res.headers.get('Retry-After')) || Number(d.retryAfter) || 5;\n\t\t\t\tcooldownUntil = Date.now() + retryAfter * 1000;\n\t\t\t\t(opts.onRateLimited ?? defaultOnRateLimited)(retryAfter);\n\t\t\t}\n\t\t\tthrow new Error(d.message || `Compute error (HTTP ${res.status})`);\n\t\t}\n\n\t\tconst ttfbMs = performance.now() - solveStart;\n\n\t\tconst downloadStart = performance.now();\n\t\tconst bodyText = await res.text();\n\t\tif (signal.aborted) {\n\t\t\tlog('[Compute] solve aborted mid-download — empty result discarded');\n\t\t\treturn { outputs: {} };\n\t\t}\n\t\tconst downloadMs = performance.now() - downloadStart;\n\t\tconst bytes = bodyText.length;\n\n\t\tlet solved: GrasshopperComputeResponse;\n\t\ttry {\n\t\t\tsolved = JSON.parse(bodyText);\n\t\t} catch (err) {\n\t\t\tthrow new Error(\n\t\t\t\t'Received an invalid response from the server. Reload the page and try again.',\n\t\t\t\t{\n\t\t\t\t\tcause: err\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t\tconst processor = new GrasshopperResponseProcessor(solved, false);\n\n\t\tconst meshes = opts.meshes\n\t\t\t? await opts.meshes.extract(processor.response, { debug, rhino: await getRhino() })\n\t\t\t: [];\n\n\t\tconst resultOutputs: Record<string, unknown> = {};\n\t\tfor (const o of outputs) {\n\t\t\tconst byId = processor.getValue({ byId: o.id }, { parseValues: true });\n\t\t\tresultOutputs[o.id] =\n\t\t\t\tbyId ??\n\t\t\t\t(o.nickname\n\t\t\t\t\t? processor.getValue({ byName: o.nickname }, { parseValues: true })\n\t\t\t\t\t: undefined);\n\t\t}\n\n\t\tif (debug) {\n\t\t\tconst serverTiming = parseServerTiming(res.headers.get('Server-Timing'));\n\t\t\tconst serverTotal = serverTiming.total ?? 0;\n\t\t\tconst networkMs = Math.max(0, ttfbMs - serverTotal);\n\t\t\tconst sizeMB = bytes / (1024 * 1024);\n\t\t\tconst size = sizeMB >= 1 ? `${sizeMB.toFixed(2)} MB` : `${(bytes / 1024).toFixed(0)} KB`;\n\t\t\tconst mbps = downloadMs > 0 ? (sizeMB / (downloadMs / 1000)).toFixed(1) : '∞';\n\t\t\tconst heapMB = (performance as Performance & { memory?: { usedJSHeapSize: number } }).memory\n\t\t\t\t?.usedJSHeapSize;\n\t\t\tconst heap = heapMB !== undefined ? ` | heap=${(heapMB / (1024 * 1024)).toFixed(0)} MB` : '';\n\t\t\tlog(\n\t\t\t\t`[Compute] req=${(payload.length / 1024).toFixed(0)}KB (values ${(valuesBytes / 1024).toFixed(0)}KB) | ` +\n\t\t\t\t\t`ttfb=${ttfbMs.toFixed(0)}ms (network≈${networkMs.toFixed(0)} + server ${serverTotal.toFixed(0)}) | ` +\n\t\t\t\t\t`download=${downloadMs.toFixed(0)}ms (${size} @ ${mbps} MB/s)${heap}`\n\t\t\t);\n\t\t\tif (serverTiming.selva_cache !== undefined) {\n\t\t\t\tconst cacheMsg = serverTiming.selva_cache\n\t\t\t\t\t? 'HIT — served without calling compute'\n\t\t\t\t\t: 'miss — solved on Rhino.Compute';\n\t\t\t\tlog(`[Compute] └─ cache: ${cacheMsg}`);\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\toutputs: resultOutputs,\n\t\t\tmeshes,\n\t\t\terrors: solved.errors ?? [],\n\t\t\twarnings: solved.warnings ?? [],\n\t\t\tsource: solved\n\t\t};\n\t};\n}\n"],"mappings":"AAMA,OAAS,iBAAAA,MAAqB,mBAE9B,IAAMC,EAA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AW,QAAQ,CAAC,CAAC,OAAOY,CAAI,MAAMC,CAAI,SAASE,CAAI,EACrE,EACIP,EAAa,cAAgB,OAAW,CAC3C,IAAMQ,EAAWR,EAAa,YAC3B,4CACA,sCACHhC,EAAI,mCAAyBwC,CAAQ,EAAE,CACxC,CACD,CAEA,MAAO,CACN,QAASX,EACT,OAAAD,EACA,OAAQF,EAAO,QAAU,CAAC,EAC1B,SAAUA,EAAO,UAAY,CAAC,EAC9B,OAAQA,CACT,CACD,CACD","names":["getInputItems","STORAGE_PREFIX","makeKey","scopeKey","inputId","writeExternalValue","args","value","readExternalValue","ref","raw","clearExternalValue","getExternalInputs","schema","item","getDefaultValue","buildInitialValues","schema","scopeKey","read","clientSet","getExternalInputs","e","values","input","stored","getDefaultValue","output","makeInitialFlags","instanceSolve","manual","applyValueChange","state","id","value","pickInputValues","picked","applySolveResult","result","_meshes","retained","createSolveSession","args","currentSchema","flags","makeInitialFlags","state","buildInitialValues","readExternalValue","listeners","emit","l","dispatch","pickInputValues","id","value","forceSolve","shouldSolve","applyValueChange","incoming","schema","scopeKey","f","result","applySolveResult","message","listener","createAsyncThrottle","run","options","runDeadlineMs","onChange","isRunning","pendingValues","currentAbortController","setRunning","next","abortCurrent","execute","values","signal","deadlineId","err","trigger","cancel","stableInputKey","values","serialize","value","obj","k","createSolveMemo","options","max","meshPolicy","entries","release","result","copy","evict","key","entry","hit","oldest","createRequestResponseDriver","onSolve","getReporter","options","meshPolicy","solveDeadlineMs","onChange","memo","createSolveMemo","throttle","createAsyncThrottle","values","signal","cached","result","stamped","err","GrasshopperResponseProcessor","parseServerTiming","header","out","part","name","params","s","dur","p","ms","defaultOnRateLimited","retryAfterSeconds","defaultOnSessionExpired","createComputeFetchSolveFn","opts","debug","log","args","rhinoPromise","getRhino","cooldownUntil","values","signal","remainingMs","solveStart","inputs","outputs","channel","versionId","payload","valuesBytes","res","err","redirectedToLogin","errorBody","d","retryAfter","ttfbMs","downloadStart","bodyText","downloadMs","bytes","solved","processor","meshes","resultOutputs","o","byId","serverTiming","serverTotal","networkMs","sizeMB","size","mbps","heapMB","heap","cacheMsg"]}
|