@selvajs/compute 5.0.0-beta.4 → 5.0.0-beta.6
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/dist/core-BPYXUtfq.js +3 -0
- package/dist/core-BPYXUtfq.js.map +1 -0
- package/dist/core-DF0VYOve.cjs +3 -0
- package/dist/core-DF0VYOve.cjs.map +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.d.cts +1 -1
- package/dist/core.d.ts +1 -1
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.cjs.map +1 -1
- package/dist/grasshopper.d.cts +1 -35
- package/dist/grasshopper.d.ts +1 -35
- package/dist/grasshopper.js +1 -1
- package/dist/grasshopper.js.map +1 -1
- package/dist/{index-cMvSohkf.d.ts → index-DDmprCht.d.cts} +11 -26
- package/dist/{index-cMvSohkf.d.cts → index-DDmprCht.d.ts} +11 -26
- package/package.json +4 -4
- package/dist/core-CFlbOj2M.js +0 -3
- package/dist/core-CFlbOj2M.js.map +0 -1
- package/dist/core-UUSszGkB.cjs +0 -3
- package/dist/core-UUSszGkB.cjs.map +0 -1
package/dist/grasshopper.d.cts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { D as ComputeAuth, M as ComputeError, O as ComputeConfig, _ as SolveDefinition, j as ServerTiming, k as RetryPolicy, s as FileBaseInfo } from "./index-
|
|
2
|
-
//#region src/grasshopper/server/compute-server-stats.d.ts
|
|
1
|
+
import { D as ComputeAuth, M as ComputeError, O as ComputeConfig, _ as SolveDefinition, j as ServerTiming, k as RetryPolicy, s as FileBaseInfo } from "./index-DDmprCht.cjs";
|
|
3
2
|
interface ServerVersion {
|
|
4
3
|
rhino: string;
|
|
5
4
|
compute: string;
|
|
@@ -314,8 +313,6 @@ declare class ComputeServerStats {
|
|
|
314
313
|
dispose(): Promise<void>;
|
|
315
314
|
private ensureNotDisposed;
|
|
316
315
|
}
|
|
317
|
-
//#endregion
|
|
318
|
-
//#region src/grasshopper/types/inputs.d.ts
|
|
319
316
|
type DataTreePath = `{${string}}`;
|
|
320
317
|
interface DataItem {
|
|
321
318
|
type: string;
|
|
@@ -425,8 +422,6 @@ interface ColorInputType extends BaseInputType {
|
|
|
425
422
|
* Discriminated union of all input parameter types
|
|
426
423
|
*/
|
|
427
424
|
type InputParam = NumericInputType | BooleanInputType | TextInputType | ValueListInputType | GeometryInputType | FileInputType | ColorInputType;
|
|
428
|
-
//#endregion
|
|
429
|
-
//#region src/grasshopper/types/schema.d.ts
|
|
430
425
|
type RhinoModelUnit = 'None' | 'Microns' | 'Millimeters' | 'Centimeters' | 'Decimeters' | 'Meters' | 'Kilometers' | 'Mils' | 'Inches' | 'Feet' | 'Yards' | 'Miles' | 'CustomUnits' | 'Unset';
|
|
431
426
|
/**
|
|
432
427
|
* Base Grasshopper schema properties shared by config, args, and response
|
|
@@ -561,8 +556,6 @@ interface InputParamSchema {
|
|
|
561
556
|
acceptedFormats?: string[];
|
|
562
557
|
groupName?: string | null;
|
|
563
558
|
}
|
|
564
|
-
//#endregion
|
|
565
|
-
//#region src/grasshopper/types/outputs.d.ts
|
|
566
559
|
/** Input/output schemas as the `/io` endpoint reports them, keys canonicalized. */
|
|
567
560
|
interface GrasshopperParsedIORaw {
|
|
568
561
|
inputs: InputParamSchema[];
|
|
@@ -603,8 +596,6 @@ interface GrasshopperParsedIO extends Omit<GrasshopperParsedIORaw, 'inputs'> {
|
|
|
603
596
|
*/
|
|
604
597
|
parseErrors?: InputParseError[];
|
|
605
598
|
}
|
|
606
|
-
//#endregion
|
|
607
|
-
//#region src/grasshopper/scheduler/types.d.ts
|
|
608
599
|
/**
|
|
609
600
|
* How concurrent `solve()` calls interact.
|
|
610
601
|
*
|
|
@@ -748,8 +739,6 @@ interface SolveDetail {
|
|
|
748
739
|
/** Executor wall time; `0` for a `fromCache` hit. */
|
|
749
740
|
durationMs: number;
|
|
750
741
|
}
|
|
751
|
-
//#endregion
|
|
752
|
-
//#region src/grasshopper/scheduler/solve-scheduler.d.ts
|
|
753
742
|
/**
|
|
754
743
|
* Adds to a plain solve call:
|
|
755
744
|
* - Scheduling (latest-wins for sliders, queue for jobs)
|
|
@@ -919,8 +908,6 @@ export declare class SolveScheduler {
|
|
|
919
908
|
dispose(): void;
|
|
920
909
|
private runHook;
|
|
921
910
|
}
|
|
922
|
-
//#endregion
|
|
923
|
-
//#region src/grasshopper/client/grasshopper-client.d.ts
|
|
924
911
|
/**
|
|
925
912
|
* Per-call options that override the client's default ComputeConfig values.
|
|
926
913
|
*
|
|
@@ -1049,8 +1036,6 @@ declare class GrasshopperClient {
|
|
|
1049
1036
|
dispose(): Promise<void>;
|
|
1050
1037
|
private ensureNotDisposed;
|
|
1051
1038
|
}
|
|
1052
|
-
//#endregion
|
|
1053
|
-
//#region src/grasshopper/io/output/response-processors.d.ts
|
|
1054
1039
|
interface ParsedContext {
|
|
1055
1040
|
[key: string]: any;
|
|
1056
1041
|
}
|
|
@@ -1074,8 +1059,6 @@ interface GetValuesResult<T = ParsedContext> {
|
|
|
1074
1059
|
*/
|
|
1075
1060
|
dispose: () => void;
|
|
1076
1061
|
}
|
|
1077
|
-
//#endregion
|
|
1078
|
-
//#region src/grasshopper/client/grasshopper-response-processor.d.ts
|
|
1079
1062
|
/** Reads parsed values and produced files out of one compute response. */
|
|
1080
1063
|
declare class GrasshopperResponseProcessor {
|
|
1081
1064
|
/** Hand it to a mesh parser such as `@selvajs/visualization/parse`. */
|
|
@@ -1141,8 +1124,6 @@ declare class GrasshopperResponseProcessor {
|
|
|
1141
1124
|
*/
|
|
1142
1125
|
getAndDownloadFiles(folderName: string, additionalFiles?: FileBaseInfo[] | FileBaseInfo | null): Promise<void>;
|
|
1143
1126
|
}
|
|
1144
|
-
//#endregion
|
|
1145
|
-
//#region src/grasshopper/scheduler/stable-hash.d.ts
|
|
1146
1127
|
/**
|
|
1147
1128
|
* Deterministic stringify with sorted keys. {a:1,b:2} and {b:2,a:1} produce
|
|
1148
1129
|
* the same string. Safely handles circular references and non-finite numbers.
|
|
@@ -1161,8 +1142,6 @@ export declare function hashSolveInput(definition: SolveDefinition, dataTree: un
|
|
|
1161
1142
|
* content; a `DefinitionRef` uses its `key`.
|
|
1162
1143
|
*/
|
|
1163
1144
|
export declare function hashDefinition(definition: SolveDefinition): string;
|
|
1164
|
-
//#endregion
|
|
1165
|
-
//#region src/grasshopper/solve.d.ts
|
|
1166
1145
|
/**
|
|
1167
1146
|
* Run one solve. `GrasshopperClient.solve()` adds input validation and throws on solver errors.
|
|
1168
1147
|
*
|
|
@@ -1175,8 +1154,6 @@ export declare function hashDefinition(definition: SolveDefinition): string;
|
|
|
1175
1154
|
* await solveGrasshopperDefinition(trees, new Uint8Array(await readFile('model.gh')), config);
|
|
1176
1155
|
*/
|
|
1177
1156
|
export declare function solveGrasshopperDefinition(dataTree: DataTree[], definition: SolveDefinition, config: GrasshopperComputeConfig): Promise<GrasshopperComputeResponse>;
|
|
1178
|
-
//#endregion
|
|
1179
|
-
//#region src/grasshopper/io/definition-io.d.ts
|
|
1180
1157
|
/**
|
|
1181
1158
|
* Fetches a definition's input/output schemas without per-type parsing.
|
|
1182
1159
|
*
|
|
@@ -1213,8 +1190,6 @@ export declare function fetchDefinitionIO(definition: string | Uint8Array, confi
|
|
|
1213
1190
|
* ```
|
|
1214
1191
|
*/
|
|
1215
1192
|
export declare function fetchParsedDefinitionIO(definition: string | Uint8Array, config: ComputeConfig): Promise<GrasshopperParsedIO>;
|
|
1216
|
-
//#endregion
|
|
1217
|
-
//#region src/grasshopper/io/schema-endpoint.d.ts
|
|
1218
1193
|
/** One entry of the schema endpoint's response, after wrapper-key normalization. */
|
|
1219
1194
|
interface SchemaEndpointResult<TSchema = unknown> {
|
|
1220
1195
|
/** Schemas embedded in that file. Absent when the file yielded none. */
|
|
@@ -1233,8 +1208,6 @@ interface SchemaEndpointResult<TSchema = unknown> {
|
|
|
1233
1208
|
* @typeParam TSchema - Your schema type (e.g. `UISchema`). Not inspected.
|
|
1234
1209
|
*/
|
|
1235
1210
|
export declare function readSchemaResults<TSchema = unknown>(raw: unknown): SchemaEndpointResult<TSchema>[];
|
|
1236
|
-
//#endregion
|
|
1237
|
-
//#region src/grasshopper/io/normalize-ui-schema.d.ts
|
|
1238
1211
|
/**
|
|
1239
1212
|
* Canonicalize a `/grasshopper/schema` body's key casing.
|
|
1240
1213
|
*
|
|
@@ -1255,15 +1228,11 @@ export declare function readSchemaResults<TSchema = unknown>(raw: unknown): Sche
|
|
|
1255
1228
|
* returned as-is.
|
|
1256
1229
|
*/
|
|
1257
1230
|
export declare function normalizeUISchemaCasing<T>(raw: T): T;
|
|
1258
|
-
//#endregion
|
|
1259
|
-
//#region src/grasshopper/io/input/input-processors.d.ts
|
|
1260
1231
|
/**
|
|
1261
1232
|
* Parse one raw Grasshopper input schema into a typed {@link InputParam}.
|
|
1262
1233
|
* A validation failure is swallowed and replaced with a safe default.
|
|
1263
1234
|
*/
|
|
1264
1235
|
export declare function processInput(rawInput: InputParamSchema): InputParam;
|
|
1265
|
-
//#endregion
|
|
1266
|
-
//#region src/grasshopper/io/output/rhino-objects.d.ts
|
|
1267
1236
|
/**
|
|
1268
1237
|
* Sentinel a Rhino geometry decode returns when a decode was attempted
|
|
1269
1238
|
* and failed hard (a registered decoder or `CommonObject.decode` threw). Carries
|
|
@@ -1292,8 +1261,6 @@ export declare function isRhinoDecodeError(value: unknown): value is RhinoDecode
|
|
|
1292
1261
|
* Safe to call more than once and on values containing no WASM objects.
|
|
1293
1262
|
*/
|
|
1294
1263
|
export declare function disposeRhinoObjects(value: unknown): void;
|
|
1295
|
-
//#endregion
|
|
1296
|
-
//#region src/grasshopper/data-tree/data-tree.d.ts
|
|
1297
1264
|
type DataTreeValue = string | number | boolean | object | null;
|
|
1298
1265
|
/** One input's value for {@link TreeBuilder.fromValues}. */
|
|
1299
1266
|
interface TreeValueEntry {
|
|
@@ -1384,6 +1351,5 @@ export declare class TreeBuilder {
|
|
|
1384
1351
|
private static hasValidValue;
|
|
1385
1352
|
private static clampValue;
|
|
1386
1353
|
}
|
|
1387
|
-
//#endregion
|
|
1388
1354
|
export { type BooleanInputType, type CacheOptions, type ColorInputType, ComputeServerStats, type CreateClientOptions, type DataItem, type DataTree, type DataTreeDefault, type DataTreePath, type DataTreeValue, type DefaultValue, type FileInputType, type GeometryInputType, type GetValuesOptions, type GetValuesResult, GrasshopperClient, type GrasshopperComputeConfig, type GrasshopperComputeResponse, type GrasshopperParsedIO, type GrasshopperParsedIORaw, GrasshopperResponseProcessor, type InnerTreeData, type InputParam, type InputParamSchema, type InputParseError, type NumericInputType, type OutputParamSchema, type ParsedContext, type RhinoDecodeError, type RhinoModelUnit, type SchedulerMode, type SchedulerSolveOptions, type SchemaEndpointResult, type SelvaEventTarget, type SelvaResponseBlock, type ServerStats, type ServerVersion, type SolveContext, type SolveDetail, type SolveExecutor, type SolveOptions, type SolveResult, type SolveSchedulerOptions, type TextInputType, type TreeValueEntry, type ValueListInputType };
|
|
1389
1355
|
//# sourceMappingURL=grasshopper.d.cts.map
|
package/dist/grasshopper.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { D as ComputeAuth, M as ComputeError, O as ComputeConfig, _ as SolveDefinition, j as ServerTiming, k as RetryPolicy, s as FileBaseInfo } from "./index-
|
|
2
|
-
//#region src/grasshopper/server/compute-server-stats.d.ts
|
|
1
|
+
import { D as ComputeAuth, M as ComputeError, O as ComputeConfig, _ as SolveDefinition, j as ServerTiming, k as RetryPolicy, s as FileBaseInfo } from "./index-DDmprCht.js";
|
|
3
2
|
interface ServerVersion {
|
|
4
3
|
rhino: string;
|
|
5
4
|
compute: string;
|
|
@@ -314,8 +313,6 @@ declare class ComputeServerStats {
|
|
|
314
313
|
dispose(): Promise<void>;
|
|
315
314
|
private ensureNotDisposed;
|
|
316
315
|
}
|
|
317
|
-
//#endregion
|
|
318
|
-
//#region src/grasshopper/types/inputs.d.ts
|
|
319
316
|
type DataTreePath = `{${string}}`;
|
|
320
317
|
interface DataItem {
|
|
321
318
|
type: string;
|
|
@@ -425,8 +422,6 @@ interface ColorInputType extends BaseInputType {
|
|
|
425
422
|
* Discriminated union of all input parameter types
|
|
426
423
|
*/
|
|
427
424
|
type InputParam = NumericInputType | BooleanInputType | TextInputType | ValueListInputType | GeometryInputType | FileInputType | ColorInputType;
|
|
428
|
-
//#endregion
|
|
429
|
-
//#region src/grasshopper/types/schema.d.ts
|
|
430
425
|
type RhinoModelUnit = 'None' | 'Microns' | 'Millimeters' | 'Centimeters' | 'Decimeters' | 'Meters' | 'Kilometers' | 'Mils' | 'Inches' | 'Feet' | 'Yards' | 'Miles' | 'CustomUnits' | 'Unset';
|
|
431
426
|
/**
|
|
432
427
|
* Base Grasshopper schema properties shared by config, args, and response
|
|
@@ -561,8 +556,6 @@ interface InputParamSchema {
|
|
|
561
556
|
acceptedFormats?: string[];
|
|
562
557
|
groupName?: string | null;
|
|
563
558
|
}
|
|
564
|
-
//#endregion
|
|
565
|
-
//#region src/grasshopper/types/outputs.d.ts
|
|
566
559
|
/** Input/output schemas as the `/io` endpoint reports them, keys canonicalized. */
|
|
567
560
|
interface GrasshopperParsedIORaw {
|
|
568
561
|
inputs: InputParamSchema[];
|
|
@@ -603,8 +596,6 @@ interface GrasshopperParsedIO extends Omit<GrasshopperParsedIORaw, 'inputs'> {
|
|
|
603
596
|
*/
|
|
604
597
|
parseErrors?: InputParseError[];
|
|
605
598
|
}
|
|
606
|
-
//#endregion
|
|
607
|
-
//#region src/grasshopper/scheduler/types.d.ts
|
|
608
599
|
/**
|
|
609
600
|
* How concurrent `solve()` calls interact.
|
|
610
601
|
*
|
|
@@ -748,8 +739,6 @@ interface SolveDetail {
|
|
|
748
739
|
/** Executor wall time; `0` for a `fromCache` hit. */
|
|
749
740
|
durationMs: number;
|
|
750
741
|
}
|
|
751
|
-
//#endregion
|
|
752
|
-
//#region src/grasshopper/scheduler/solve-scheduler.d.ts
|
|
753
742
|
/**
|
|
754
743
|
* Adds to a plain solve call:
|
|
755
744
|
* - Scheduling (latest-wins for sliders, queue for jobs)
|
|
@@ -919,8 +908,6 @@ export declare class SolveScheduler {
|
|
|
919
908
|
dispose(): void;
|
|
920
909
|
private runHook;
|
|
921
910
|
}
|
|
922
|
-
//#endregion
|
|
923
|
-
//#region src/grasshopper/client/grasshopper-client.d.ts
|
|
924
911
|
/**
|
|
925
912
|
* Per-call options that override the client's default ComputeConfig values.
|
|
926
913
|
*
|
|
@@ -1049,8 +1036,6 @@ declare class GrasshopperClient {
|
|
|
1049
1036
|
dispose(): Promise<void>;
|
|
1050
1037
|
private ensureNotDisposed;
|
|
1051
1038
|
}
|
|
1052
|
-
//#endregion
|
|
1053
|
-
//#region src/grasshopper/io/output/response-processors.d.ts
|
|
1054
1039
|
interface ParsedContext {
|
|
1055
1040
|
[key: string]: any;
|
|
1056
1041
|
}
|
|
@@ -1074,8 +1059,6 @@ interface GetValuesResult<T = ParsedContext> {
|
|
|
1074
1059
|
*/
|
|
1075
1060
|
dispose: () => void;
|
|
1076
1061
|
}
|
|
1077
|
-
//#endregion
|
|
1078
|
-
//#region src/grasshopper/client/grasshopper-response-processor.d.ts
|
|
1079
1062
|
/** Reads parsed values and produced files out of one compute response. */
|
|
1080
1063
|
declare class GrasshopperResponseProcessor {
|
|
1081
1064
|
/** Hand it to a mesh parser such as `@selvajs/visualization/parse`. */
|
|
@@ -1141,8 +1124,6 @@ declare class GrasshopperResponseProcessor {
|
|
|
1141
1124
|
*/
|
|
1142
1125
|
getAndDownloadFiles(folderName: string, additionalFiles?: FileBaseInfo[] | FileBaseInfo | null): Promise<void>;
|
|
1143
1126
|
}
|
|
1144
|
-
//#endregion
|
|
1145
|
-
//#region src/grasshopper/scheduler/stable-hash.d.ts
|
|
1146
1127
|
/**
|
|
1147
1128
|
* Deterministic stringify with sorted keys. {a:1,b:2} and {b:2,a:1} produce
|
|
1148
1129
|
* the same string. Safely handles circular references and non-finite numbers.
|
|
@@ -1161,8 +1142,6 @@ export declare function hashSolveInput(definition: SolveDefinition, dataTree: un
|
|
|
1161
1142
|
* content; a `DefinitionRef` uses its `key`.
|
|
1162
1143
|
*/
|
|
1163
1144
|
export declare function hashDefinition(definition: SolveDefinition): string;
|
|
1164
|
-
//#endregion
|
|
1165
|
-
//#region src/grasshopper/solve.d.ts
|
|
1166
1145
|
/**
|
|
1167
1146
|
* Run one solve. `GrasshopperClient.solve()` adds input validation and throws on solver errors.
|
|
1168
1147
|
*
|
|
@@ -1175,8 +1154,6 @@ export declare function hashDefinition(definition: SolveDefinition): string;
|
|
|
1175
1154
|
* await solveGrasshopperDefinition(trees, new Uint8Array(await readFile('model.gh')), config);
|
|
1176
1155
|
*/
|
|
1177
1156
|
export declare function solveGrasshopperDefinition(dataTree: DataTree[], definition: SolveDefinition, config: GrasshopperComputeConfig): Promise<GrasshopperComputeResponse>;
|
|
1178
|
-
//#endregion
|
|
1179
|
-
//#region src/grasshopper/io/definition-io.d.ts
|
|
1180
1157
|
/**
|
|
1181
1158
|
* Fetches a definition's input/output schemas without per-type parsing.
|
|
1182
1159
|
*
|
|
@@ -1213,8 +1190,6 @@ export declare function fetchDefinitionIO(definition: string | Uint8Array, confi
|
|
|
1213
1190
|
* ```
|
|
1214
1191
|
*/
|
|
1215
1192
|
export declare function fetchParsedDefinitionIO(definition: string | Uint8Array, config: ComputeConfig): Promise<GrasshopperParsedIO>;
|
|
1216
|
-
//#endregion
|
|
1217
|
-
//#region src/grasshopper/io/schema-endpoint.d.ts
|
|
1218
1193
|
/** One entry of the schema endpoint's response, after wrapper-key normalization. */
|
|
1219
1194
|
interface SchemaEndpointResult<TSchema = unknown> {
|
|
1220
1195
|
/** Schemas embedded in that file. Absent when the file yielded none. */
|
|
@@ -1233,8 +1208,6 @@ interface SchemaEndpointResult<TSchema = unknown> {
|
|
|
1233
1208
|
* @typeParam TSchema - Your schema type (e.g. `UISchema`). Not inspected.
|
|
1234
1209
|
*/
|
|
1235
1210
|
export declare function readSchemaResults<TSchema = unknown>(raw: unknown): SchemaEndpointResult<TSchema>[];
|
|
1236
|
-
//#endregion
|
|
1237
|
-
//#region src/grasshopper/io/normalize-ui-schema.d.ts
|
|
1238
1211
|
/**
|
|
1239
1212
|
* Canonicalize a `/grasshopper/schema` body's key casing.
|
|
1240
1213
|
*
|
|
@@ -1255,15 +1228,11 @@ export declare function readSchemaResults<TSchema = unknown>(raw: unknown): Sche
|
|
|
1255
1228
|
* returned as-is.
|
|
1256
1229
|
*/
|
|
1257
1230
|
export declare function normalizeUISchemaCasing<T>(raw: T): T;
|
|
1258
|
-
//#endregion
|
|
1259
|
-
//#region src/grasshopper/io/input/input-processors.d.ts
|
|
1260
1231
|
/**
|
|
1261
1232
|
* Parse one raw Grasshopper input schema into a typed {@link InputParam}.
|
|
1262
1233
|
* A validation failure is swallowed and replaced with a safe default.
|
|
1263
1234
|
*/
|
|
1264
1235
|
export declare function processInput(rawInput: InputParamSchema): InputParam;
|
|
1265
|
-
//#endregion
|
|
1266
|
-
//#region src/grasshopper/io/output/rhino-objects.d.ts
|
|
1267
1236
|
/**
|
|
1268
1237
|
* Sentinel a Rhino geometry decode returns when a decode was attempted
|
|
1269
1238
|
* and failed hard (a registered decoder or `CommonObject.decode` threw). Carries
|
|
@@ -1292,8 +1261,6 @@ export declare function isRhinoDecodeError(value: unknown): value is RhinoDecode
|
|
|
1292
1261
|
* Safe to call more than once and on values containing no WASM objects.
|
|
1293
1262
|
*/
|
|
1294
1263
|
export declare function disposeRhinoObjects(value: unknown): void;
|
|
1295
|
-
//#endregion
|
|
1296
|
-
//#region src/grasshopper/data-tree/data-tree.d.ts
|
|
1297
1264
|
type DataTreeValue = string | number | boolean | object | null;
|
|
1298
1265
|
/** One input's value for {@link TreeBuilder.fromValues}. */
|
|
1299
1266
|
interface TreeValueEntry {
|
|
@@ -1384,6 +1351,5 @@ export declare class TreeBuilder {
|
|
|
1384
1351
|
private static hasValidValue;
|
|
1385
1352
|
private static clampValue;
|
|
1386
1353
|
}
|
|
1387
|
-
//#endregion
|
|
1388
1354
|
export { type BooleanInputType, type CacheOptions, type ColorInputType, ComputeServerStats, type CreateClientOptions, type DataItem, type DataTree, type DataTreeDefault, type DataTreePath, type DataTreeValue, type DefaultValue, type FileInputType, type GeometryInputType, type GetValuesOptions, type GetValuesResult, GrasshopperClient, type GrasshopperComputeConfig, type GrasshopperComputeResponse, type GrasshopperParsedIO, type GrasshopperParsedIORaw, GrasshopperResponseProcessor, type InnerTreeData, type InputParam, type InputParamSchema, type InputParseError, type NumericInputType, type OutputParamSchema, type ParsedContext, type RhinoDecodeError, type RhinoModelUnit, type SchedulerMode, type SchedulerSolveOptions, type SchemaEndpointResult, type SelvaEventTarget, type SelvaResponseBlock, type ServerStats, type ServerVersion, type SolveContext, type SolveDetail, type SolveExecutor, type SolveOptions, type SolveResult, type SolveSchedulerOptions, type TextInputType, type TreeValueEntry, type ValueListInputType };
|
|
1389
1355
|
//# sourceMappingURL=grasshopper.d.ts.map
|
package/dist/grasshopper.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{C as e,D as t,O as n,S as r,T as i,_ as a,c as o,d as s,f as c,h as l,i as u,l as d,m as f,p,s as m,t as ee,u as te,v as ne,x as h,y as re}from"./core-CFlbOj2M.js";var g=class e{serverUrl;headers;disposed=!1;activeMonitors=new Set;static DEFAULT_TIMEOUT_MS=5e3;static LIFECYCLE_TIMEOUT_MS=6e4;static MIN_MONITOR_INTERVAL_MS=100;static MAX_BODY_BYTES=1<<20;constructor(e,t){this.serverUrl=h(e),this.headers={...re(typeof t==`string`?{apiKey:t}:t??{}),"Content-Type":`application/json`}}fetchWithTimeout(t,n={},r=e.DEFAULT_TIMEOUT_MS){let i={...n,headers:this.headers,redirect:`manual`};return r>0&&!i.signal&&(i.signal=AbortSignal.timeout(r)),fetch(t,i)}async getText(t,n={},r=e.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let a=`${n.method??`GET`} ${t}`;try{let o=await this.fetchWithTimeout(`${this.serverUrl}${t}`,n,r);if(!o.ok)return i().warn(`[ComputeServerStats] ${a} failed:`,o.status),await o.body?.cancel().catch(()=>{}),null;let{text:s,truncated:c}=await f(o,e.MAX_BODY_BYTES);return c?(i().warn(`[ComputeServerStats] ${a} answered with an oversized body`),null):s}catch(e){return i().warn(`[ComputeServerStats] ${a} errored:`,e),null}}async isServerOnline(t=e.DEFAULT_TIMEOUT_MS){return(await this.probeServer(t)).online}async probeServer(t=e.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let n=`${this.serverUrl}/`;try{let e=await this.fetchWithTimeout(n,{method:`GET`},t);return await e.body?.cancel().catch(()=>{}),{online:e.ok||s(e),status:e.status}}catch(e){return i().debug(`[ComputeServerStats] Fetch error:`,e),{online:!1,error:e instanceof Error?`${e.name}: ${e.message}`:String(e)}}}async getActiveChildren(t={}){let{initialize:n=!0}=t,r=n?await this.getText(`/activechildren`,{},e.LIFECYCLE_TIMEOUT_MS):await this.getText(`/activechildren?initialize=false`);if(r===null)return null;let a=r.trim();return/^\d+$/.test(a)?parseInt(a,10):(i().warn(`[ComputeServerStats] /activechildren answered with a non-numeric body`),null)}async getVersion(){let e=await this.getText(`/version`);if(e===null)return null;let t=_(e);return t==null?{rhino:e,compute:``,git_sha:null}:{rhino:t.rhino??``,compute:t.compute??``,git_sha:t.git_sha??null}}async getInstalledPlugins(e=`gh`){let t=await this.getText(`/plugins/${e}/installed`),n=t===null?void 0:_(t);return n&&typeof n==`object`?n:null}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[e,t]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...e&&{version:e},...t!==null&&{activeChildren:t}}}async purgeCache(){let e=await this.getText(`/cache/purge`,{method:`POST`}),t=(e===null?void 0:_(e))?.purged;return typeof t==`number`?t:null}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return i().warn(`[ComputeServerStats] purgeAllChildren: could not read child count`),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let t=e*2,n=0;for(let e=0;e<t;e++){let e=await this.purgeCache();e!==null&&(n+=e)}return{totalPurged:n,calls:t,children:e,confident:e===1}}async getServerTime(){let e=await this.getText(`/servertime`);if(e===null)return null;let t=new Date(e.trim().replace(/^"|"$/g,``));return isNaN(t.getTime())?null:t}async getIdleSpan(){let e=await this.getText(`/idlespan`);if(e===null)return null;let t=parseFloat(e.trim());return isNaN(t)?null:t}async launchChildren(){return this.postJson(`/launch-children`)}async launchChild(e){let t=e===void 0?`/launch-child`:`/launch-child?port=${e}`;return this.postJson(t)}async shutdownChildren(e){let t=e===void 0?`/shutdown-children`:`/shutdown-children?port=${e}`;return this.postJson(t)}async recycleChildren(e){let t=e===void 0?`/recycle-children`:`/recycle-children?port=${e}`;return this.postJson(t)}async postJson(t){let n=await this.getText(t,{method:`POST`},e.LIFECYCLE_TIMEOUT_MS);return n===null?null:_(n)??null}monitor(r,a=5e3){if(this.ensureNotDisposed(),!Number.isFinite(a)||a<e.MIN_MONITOR_INTERVAL_MS)throw new t(`monitor() intervalMs must be a finite number >= ${e.MIN_MONITOR_INTERVAL_MS}ms, got ${a}. Sub-${e.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`,n.INVALID_CONFIG,{context:{intervalMs:a}});let o=!0,s=null;i().info(`🔄 Starting server stats monitoring every ${a}ms`);let c=async()=>{if(s=null,o&&!this.disposed){try{let e=await this.getServerStats();if(!o||this.disposed)return;try{r(e)}catch(e){i().error(`[ComputeServerStats] Monitor callback threw:`,e)}}catch(e){!o||this.disposed?i().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,e):i().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,e)}o&&!this.disposed&&(s=setTimeout(()=>void c(),a))}},l=()=>{o=!1,s!==null&&(clearTimeout(s),s=null),this.activeMonitors.delete(l)};return this.activeMonitors.add(l),c(),l}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear()}}ensureNotDisposed(){if(this.disposed)throw new t(`ComputeServerStats has been disposed and cannot be used`,n.INVALID_STATE)}};function _(e){try{return JSON.parse(e)}catch{return}}const v=new Set;function ie(){if(typeof window>`u`||globalThis.process?.versions?.node!=null)return!1;let e=globalThis.navigator,t=typeof e?.userAgent==`string`?e.userAgent:``;return!/jsdom/i.test(t)}function y(e,t){t||ie()&&!v.has(e)&&(v.add(e),i().warn(`Warning: ${e} is running on the client side. For better performance and security, consider running this on the server side.`))}const ae={definition_not_cached:n.DEFINITION_NOT_CACHED};function oe(e){return{...e,serverErrorCodes:{...ae,...e.serverErrorCodes}}}function se(e){return e instanceof t?e.code===n.DEFINITION_NOT_CACHED||e.message.includes(`Unable to load grasshopper definition`):!1}function ce(t,n){if(!n)return;let r=e(t,`values`);if(!Array.isArray(r)||r.length===0)return;let a=[];for(let t of r){let n=e(t,`innerTree`);(!n||Object.keys(n).length===0)&&a.push(e(t,`paramName`)??`<unnamed>`)}if(a.length===0)return;let o=a.length===r.length?`all`:`${a.length}/${r.length}`;i().warn(`Solve returned empty output(s) (${o}): ${a.join(`, `)}. These parameters produced no data — check the definition's inputs and the branch feeding each.`)}async function le(e,t,n){return y(`solveGrasshopperDefinition`,n.suppressBrowserWarning),(await de(e,t,n)).response}async function ue(e,t,n,r){if(y(`solveWithServerCacheKey`,r.suppressBrowserWarning),t!==null)try{return{...await pe({algo:null,pointer:t,values:e},r),missed:!1}}catch(e){if(!se(e))throw e}return{...await de(e,n,r),missed:!0}}async function de(e,t,n){return pe(b(await fe(t),e),n)}async function fe(e){if(!m(e))return e;try{return await e.load()}catch(r){throw new t(`Failed to load definition bytes for ref '${e.key}'`,n.INVALID_INPUT,{context:{definitionKey:e.key},originalError:r})}}async function pe(e,t){h(t.serverUrl),me(e,t);let{maxResponseBytes:n}=t,r=await d(`grasshopper`,e,oe({...t,maxResponseBytes:n!==void 0&&e.algo?n+e.algo.length:n})),{pointer:i,algo:a,...o}=r,s=o,l=c(r);if(l!==void 0){let e=typeof a==`string`?a.length:0;p(s,Math.max(0,l-e))}return ce(s,t.debug),{response:s,cacheKey:typeof i==`string`?i:null}}function b(e,t){let n={algo:null,pointer:null,values:t};return e instanceof Uint8Array?n.algo=l(e):o(e)?n.pointer=e:n.algo=a(e)??ne(e),n}function me(e,t){t.cachesolve!=null&&(e.cachesolve=t.cachesolve),t.cacheerroredsolves!=null&&(e.cacheerroredsolves=t.cacheerroredsolves),t.modelunits!=null&&(e.modelunits=t.modelunits),t.angletolerance!=null&&(e.angletolerance=t.angletolerance),t.absolutetolerance!=null&&(e.absolutetolerance=t.absolutetolerance),t.dataversion!=null&&(e.dataversion=t.dataversion),t.selvaevents!=null&&(e.selvaevents=t.selvaevents)}function x(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}const S=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function C(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>S.test(e)&&Array.isArray(t))}function w(e,t,n){if(e==null)return e;if(Array.isArray(e)){let n=e.map(t).filter(e=>e!==null);return n.length>0?n:void 0}let r=t(e);return r===null?n?void 0:e:r}const T=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=e.trim();if(t===``||/^[+-]?0[xbo]/i.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}return null},E=e=>{if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}return null},he=e=>typeof e==`string`?e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e.startsWith(`"`)?e.slice(1):e:null,ge=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function D(e){return t=>{if(typeof t==`object`&&t)return t;if(typeof t==`string`&&t.trim()!==``)try{let n=JSON.parse(t);return typeof n==`object`&&n?n:(i().warn(`Parsed value for input ${e} is not an object`),null)}catch(n){return i().warn(`Failed to parse object value "${t}" for input ${e}`,n),null}return null}}const _e=new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),ve=new Set([`System.Int32`,`System.Int64`]);function O(e,t){return i().warn(t),{schema:{...e,default:null},warning:{code:n.MALFORMED_DEFAULT,message:t}}}function ye(t,a){if(typeof t.default!=`object`||t.default===null||Array.isArray(t.default)||C(t.default))return{schema:t};if(!r(t.default,`innerTree`))return O(t,`Input "${a}" default had an unrecognized shape (no innerTree key); the default was dropped.`);let o=e(t.default,`innerTree`)??{};if(Object.keys(o).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let r={},s=[];for(let[n,i]of Object.entries(o)){if(!Array.isArray(i))return O(t,`Input "${a}" default had a non-array innerTree branch ("${n}"); the default was dropped.`);let o=[];for(let t of i){let n=e(t,`data`),r=e(t,`type`);if(r&&_e.has(r)){if(typeof n==`string`&&n.trim()===``)continue;let e=T(n);if(e===null){s.push(`"${String(n)}" (${r})`);continue}o.push(ve.has(r)?Math.round(e):e);continue}if(r===`System.Boolean`){let e=E(n);if(e===null){s.push(`"${String(n)}" (${r})`);continue}o.push(e);continue}if(typeof n==`string`&&r?.startsWith(`Rhino.Geometry`)){try{o.push(JSON.parse(n))}catch{o.push(n)}continue}o.push(n)}x(r,n,o)}if(s.length>0){let e=`Input "${a}" default contained ${s.length} tree value(s) that could not be parsed and were dropped: ${s.join(`, `)}.`;return i().warn(e),{schema:{...t,default:r},warning:{code:n.MALFORMED_DEFAULT,message:e}}}return{schema:{...t,default:r}}}let s=[];for(let t of Object.values(o))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&r(n,`data`)&&s.push(e(n,`data`));return{schema:{...t,default:s.length>1?s:s[0]}}}function be(e,t){let n=Number(e.toFixed(t));return Math.abs(e-n)<1e-8?n:e}function k(e){if(!Number.isFinite(e))return 0;let[t,n]=String(Math.abs(e)).split(`e`),r=n===void 0?Math.abs(e).toFixed(12).replace(/0+$/,``).split(`.`)[1]?.length??0:(t.split(`.`)[1]?.length??0)-Number(n);return Math.min(Math.max(r,0),12)}function xe(e){if(!Number.isFinite(e)||e===0)return .1;let t=k(e);return t===0?Math.abs(e)>=1?1:.1:Number((10**-t).toFixed(t))}function A(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}const j=(e,t)=>(e.atMost??1)>1?[t]:t,M=e=>A(e)??(e.paramType===`Integer`?1:.1),N=(e,t)=>Array.isArray(e)?e.map(e=>typeof e==`number`?t(e):e):typeof e==`number`?t(e):e;function Se(e){if(C(e.default))return{default:e.default,stepSize:M(e)};if(typeof e.default==`string`&&e.default.trim()!==``&&T(e.default)===null)throw new t(`Invalid numeric default "${e.default}" for input "${e.name||`unknown`}"`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});let r=w(e.default,T,!0);if(e.paramType===`Integer`)return{default:N(r,Math.round),stepSize:M(e)};let i=Array.isArray(r)?r[0]:r,a=[i,e.minimum,e.maximum].find(e=>typeof e==`number`&&Number.isFinite(e)&&e!==0),o=A(e)??(a===void 0?.1:xe(a)),s=k(o);if(s===0&&typeof i==`number`&&i!==0&&Math.abs(i)<1){let e=Math.ceil(-Math.log10(Math.abs(i)));Number.isFinite(e)&&e>0&&(s=e)}return s=Math.min(Math.max(s,0),12),{default:N(r,e=>be(e,s)),stepSize:o}}const P={parse(e,t){let{default:n,stepSize:r}=Se(e);return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:r,default:n}},fallback(e,t){let n=typeof e.minimum==`number`&&Number.isFinite(e.minimum)&&e.minimum>0?e.minimum:0;return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:M(e),default:j(e,n)}}},Ce={parse(e,r){if(C(e.default))return{...r,paramType:`Boolean`,default:e.default};let i=w(e.default,E,!1);if(i!=null&&typeof i!=`boolean`&&!Array.isArray(i))throw new t(`Invalid boolean default "${String(i)}" for input "${e.name||`unknown`}"`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});return{...r,paramType:`Boolean`,default:i}},fallback(e,t){return{...t,paramType:`Boolean`,default:j(e,!1)}}},we={parse(e,t){let n=w(e.default,he,!1);return{...t,paramType:`Text`,default:n}}},Te={parse(e,r,a){if(!e.values||typeof e.values!=`object`||Object.keys(e.values).length===0){let r=e.nickname||`unnamed`;throw new t(`Input "${r}" has no values defined (expected ValueList)`,n.INVALID_INPUT,{context:{inputName:r,expectedType:`ValueList`}})}let o=e.default;if(e.default!==void 0&&e.default!==null){if(typeof e.default==`object`)throw new t(`ValueList input "${e.nickname||`unnamed`}" default is not a string-able value`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});let r=String(e.default).toLowerCase(),s=Object.keys(e.values).find(e=>e.toLowerCase()===r);if(s!==void 0)o=s;else{let t=`ValueList input "${e.nickname||`unnamed`}" default value "${e.default}" is not in available values`;i().warn(t),a?.({code:n.VALIDATION_ERROR,message:t})}}return{...r,paramType:`ValueList`,values:e.values,default:o}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}};function F(e,t){return{...t,paramType:`Geometry`,default:j(e,null)}}const I=new Map([[`Number`,P],[`Integer`,P],[`Boolean`,Ce],[`Text`,we],[`ValueList`,Te],[`Geometry`,{parse(e,t){let n=w(e.default,D(e.nickname||`unnamed`),!0);return{...t,paramType:`Geometry`,default:n}},fallback:F}],[`File`,{parse(e,t){let n=w(e.default,D(e.nickname||`unnamed`),!0);return{...t,paramType:`File`,acceptedFormats:e.acceptedFormats,default:n}}}],[`Color`,{parse(e,t){let n=w(e.default,ge,!1);return{...t,paramType:`Color`,default:n}}}]]),Ee=F,De=new Map([...I.keys()].map(e=>[e.toLowerCase(),e]));function Oe(e){return De.get(e?.toLowerCase())??e}function ke(e){return L(e).input}function L(e){let r=e.name||`unknown`,a=[],o=({code:t,message:n})=>{a.push({inputName:r,paramType:e.paramType,message:n,code:t})},s={description:e.description,name:e.name,nickname:e.nickname,treeAccess:e.treeAccess,groupName:e.groupName??void 0,id:e.id},c=Oe(e.paramType),l={...e,paramType:c};try{let{schema:e,warning:t}=ye(l,r);l=e,t&&o(t)}catch(e){l={...l,default:null},o({code:n.MALFORMED_DEFAULT,message:`Input "${r}" default could not be normalized and was dropped: ${e instanceof Error?e.message:String(e)}`})}let u=I.get(c);try{if(!u)throw new t(`Unknown paramType: ${c}`,n.VALIDATION_ERROR,{context:{receivedParamType:c,paramName:e.name}});return{input:u.parse(l,s,o),errors:a}}catch(d){if(!(d instanceof t))throw new t(d instanceof Error?d.message:String(d),n.VALIDATION_ERROR,{context:{paramName:e.name,paramType:c},originalError:d});return i().error(`Validation error for input ${r}:`,d.message),o(d),{input:(u?.fallback??Ee)(l,s),errors:a}}}function Ae(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=L(r);t.push(e),n.push(...i)}return{inputs:t,parseErrors:n}}function je(t){let n=e(t,`stepSize`);return{id:e(t,`id`)??``,name:e(t,`name`)??``,nickname:e(t,`nickname`)??null,description:e(t,`description`)??``,paramType:e(t,`paramType`)??``,treeAccess:e(t,`treeAccess`)??!1,minimum:e(t,`minimum`)??null,maximum:e(t,`maximum`)??null,atLeast:e(t,`atLeast`)??1,atMost:e(t,`atMost`)??1,stepSize:typeof n==`number`&&Number.isFinite(n)?n:void 0,default:e(t,`default`),values:e(t,`values`),acceptedFormats:e(t,`acceptedFormats`),groupName:e(t,`groupName`)??null}}function Me(t){return{name:e(t,`name`)??``,nickname:e(t,`nickname`)??null,paramType:e(t,`paramType`)??``,id:e(t,`id`)??``}}async function R(r,i){y(`fetchDefinitionIO`,i.suppressBrowserWarning),h(i.serverUrl);let{algo:a,pointer:o}=b(r,[]);if(!a&&!o)throw new t(`Definition must resolve to either a URL pointer or base64 algo`,n.INVALID_INPUT);let s=await d(`io`,a?{algo:a}:{pointer:o},oe(i));if(!s||typeof s!=`object`)throw new t(`Invalid IO response structure`,n.INVALID_INPUT,{context:{response:s}});let c=z(e(s,`warnings`)),l=z(e(s,`errors`)),u=e(s,`inputs`),f=e(s,`outputs`);return{inputs:Array.isArray(u)?u.map(je):[],outputs:Array.isArray(f)?f.map(Me):[],...c&&{loadWarnings:c},...l&&{loadErrors:l}}}function z(e){if(!Array.isArray(e))return;let t=e.map(Ne).filter(e=>e!==void 0);return t.length>0?t:void 0}function Ne(t){if(t==null)return;let n;if(typeof t==`string`)n=t;else if(typeof t==`object`){let r=e(t,`message`);if(typeof r==`string`&&r.trim().length>0)n=r;else try{n=JSON.stringify(t)??String(t)}catch{n=String(t)}}else n=String(t);return n.trim().length>0?n:void 0}async function B(e,t){let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await R(e,t),{inputs:o,parseErrors:s}=Ae(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}const V=globalThis.process?.getBuiltinModule?.(`node:crypto`);function H(e){if(V){let t=V.createHash(`sha256`);return typeof e==`string`?t.update(e,`utf16le`):t.update(e),t.digest(`hex`)}return Fe(e)}const Pe=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Fe(e){let t=new Ie;return typeof e==`string`?t.updateString(e):t.update(e),t.digestHex()}var Ie=class{h=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);w=new Int32Array(64);pending=new Uint8Array(64);pendingLength=0;totalBytes=0;update(e){this.totalBytes+=e.length;let t=0;if(this.pendingLength>0){let n=Math.min(64-this.pendingLength,e.length);if(this.pending.set(e.subarray(0,n),this.pendingLength),this.pendingLength+=n,t=n,this.pendingLength<64)return;this.compressBytes(this.pending,0),this.pendingLength=0}for(;t+64<=e.length;t+=64)this.compressBytes(e,t);this.pending.set(e.subarray(t),0),this.pendingLength=e.length-t}updateString(e){let t=this.w,n=e.length-e.length%32;for(let r=0;r<n;r+=32){for(let n=0;n<16;n++){let i=e.charCodeAt(r+2*n),a=e.charCodeAt(r+2*n+1);t[n]=(i&255)<<24|i>>>8<<16|(a&255)<<8|a>>>8}this.compress()}this.totalBytes+=n*2;let r=new Uint8Array((e.length-n)*2);for(let t=n,i=0;t<e.length;t++){let n=e.charCodeAt(t);r[i++]=n&255,r[i++]=n>>>8}this.update(r)}digestHex(){let e=this.totalBytes*8,t=new Uint8Array(this.pendingLength<56?64:128);t.set(this.pending.subarray(0,this.pendingLength)),t[this.pendingLength]=128;let n=new DataView(t.buffer);n.setUint32(t.length-8,Math.floor(e/4294967296)),n.setUint32(t.length-4,e>>>0);for(let e=0;e<t.length;e+=64)this.compressBytes(t,e);let r=``;for(let e of this.h)r+=(e>>>0).toString(16).padStart(8,`0`);return r}compressBytes(e,t){let n=this.w;for(let r=0;r<16;r++){let i=t+r*4;n[r]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}this.compress()}compress(){let e=this.w;for(let t=16;t<64;t++){let n=e[t-15],r=e[t-2],i=(n>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,a=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10;e[t]=e[t-16]+i+e[t-7]+a|0}let t=this.h,n=t[0],r=t[1],i=t[2],a=t[3],o=t[4],s=t[5],c=t[6],l=t[7];for(let t=0;t<64;t++){let u=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),d=o&s^~o&c,f=l+u+d+Pe[t]+e[t]|0,p=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&r^n&i^r&i)|0;l=c,c=s,s=o,o=a+f|0,a=i,i=r,r=n,n=f+p|0}t[0]=t[0]+n|0,t[1]=t[1]+r|0,t[2]=t[2]+i|0,t[3]=t[3]+a|0,t[4]=t[4]+o|0,t[5]=t[5]+s|0,t[6]=t[6]+c|0,t[7]=t[7]+l|0}};function U(e){let t=new WeakSet,n=e=>{if(e===null)return`null`;if(typeof e==`number`)return Number.isFinite(e)?String(e):`null`;if(typeof e==`string`||typeof e==`boolean`)return JSON.stringify(e);if(typeof e==`bigint`)return`${e}n`;if(typeof e!=`object`)return`undefined`;if(e instanceof Uint8Array)return`{u8:${H(e)}}`;if(t.has(e))return`[Circular]`;t.add(e);let r;if(Array.isArray(e)){let t=[];for(let r=0;r<e.length;r++)t.push(n(e[r]));r=`[${t.join(`,`)}]`}else r=typeof e.toJSON==`function`?n(e.toJSON()):e instanceof Map?`{map:[${[...e.entries()].map(([e,t])=>`[${n(e)},${n(t)}]`).sort().join(`,`)}]}`:e instanceof Set?`{set:[${[...e.values()].map(n).sort().join(`,`)}]}`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${n(e[t])}`).join(`,`)}}`;return t.delete(e),r};return n(e)}function Le(e,t){return W(G(e),t)}function W(e,t){return`${e}|t:${H(U(t))}`}function G(e){return m(e)?`r:${e.key}`:typeof e==`string`?`s:${H(e)}`:`u8:${H(e)}`}const K=new WeakMap;function Re(e){if(!(e instanceof Uint8Array))return G(e);let t=K.get(e);return t===void 0&&(t=G(e),K.set(e,t)),t}var ze=class{hashDefinition;dataTree;definitionMemo;keyMemo;constructor(e,t){this.hashDefinition=e,this.dataTree=t}get definitionHash(){return this.definitionMemo??=this.hashDefinition()}get key(){return this.keyMemo??=W(this.definitionHash,this.dataTree)}},Be=class{items=[];head=0;live=new Set;get size(){return this.live.size}push(e){this.items.push(e),this.live.add(e)}remove(e){this.live.delete(e)&&this.compact()}shift(){for(;this.head<this.items.length;){let e=this.items[this.head];if(this.items[this.head++]=void 0,e&&this.live.delete(e))return this.compact(),e}}compact(){if(this.live.size===0){this.items=[],this.head=0;return}let e=this.items.length-this.live.size;e<=64||e<=this.live.size||(this.items=this.items.filter(e=>e!==void 0&&this.live.has(e)),this.head=0)}};function Ve(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var He=class{executor;baseConfig;mode;maxConcurrent;maxQueueDepth;queueWaitMs;timeoutMs;retry;cacheEnabled;cacheMaxBytes;cacheTtl;cacheErroredSolves;cache=new Map;cacheBytes=0;cacheHits=0;cacheMisses=0;cacheEvictions=0;reuseServerDefinitionCache;serverCacheKeys=new Map;lastStringDefinition=null;onStart;onSettle;onSuperseded;subscribers=new Set;inFlight=new Set;pendingForLatestWins=null;fifo=new Be;_lastResult=null;_lastError=null;_lastDurationMs=null;solveSeq=0;lastStateSeq=0;disposed=!1;constructor(e,r,i={}){if(this.executor=e,this.baseConfig=r,this.mode=i.mode??`latest-wins`,this.mode!==`latest-wins`&&this.mode!==`queue`)throw new t(`Unknown scheduler mode '${String(this.mode)}'. For concurrent solves use { mode: 'queue', maxConcurrent: 4 }.`,n.INVALID_CONFIG,{context:{mode:this.mode}});this.maxConcurrent=Math.max(1,i.maxConcurrent??1),this.maxQueueDepth=i.maxQueueDepth!==void 0&&i.maxQueueDepth>0?Math.floor(i.maxQueueDepth):void 0,this.queueWaitMs=i.queueWaitMs!==void 0&&i.queueWaitMs>0?i.queueWaitMs:void 0,this.timeoutMs=i.timeoutMs,this.retry=i.retry;let a=i.cache,o=typeof a==`object`?a:null;this.cacheMaxBytes=Math.max(0,o?.maxBytes??0),this.cacheEnabled=this.cacheMaxBytes>0,this.cacheTtl=o?.ttlMs??0,this.cacheErroredSolves=o?.cacheErroredSolves??!0,this.reuseServerDefinitionCache=i.reuseServerDefinitionCache??!0,this.onStart=i.onStart,this.onSettle=i.onSettle,this.onSuperseded=i.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifo.size>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifo.size+ +!!this.pendingForLatestWins}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}setMaxConcurrent(e){let t=Math.max(1,Math.floor(e));if(t===this.maxConcurrent)return;let n=t>this.maxConcurrent;this.maxConcurrent=t,n&&this.drainNext()}getMaxConcurrent(){return this.maxConcurrent}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(e){i().error(`[SolveScheduler] subscriber threw:`,e)}}solve(e,t,n){return this.solveDetailed(e,t,n).then(e=>e.response)}solveDetailed(e,r,i){if(this.disposed)return Promise.reject(new t(`SolveScheduler has been disposed and cannot be used`,n.INVALID_STATE));let a=new ze(()=>this.hashDefinitionMemo(e),r),o=``;if(this.cacheEnabled||this.onStart||this.onSettle||this.onSuperseded)try{o=a.key}catch(e){return Promise.reject(new t(`Solve input could not be hashed`,n.INVALID_INPUT,{originalError:e}))}let s=++this.solveSeq,c={key:o,enqueuedAt:Date.now(),startedAt:null};if(i?.signal?.aborted)return Promise.reject(this.makeAbortError(c));let l=this.readCache(o);if(l){this.mode===`latest-wins`&&this.supersedeCurrent();let e={status:`success`,response:l,durationMs:0,fromCache:!0};return this.writeLastState(s,{result:l,durationMs:0}),this.runHook(this.onStart,c),this.runHook(this.onSettle,c,e),this.notify(),Promise.resolve({response:l,fromCache:!0,durationMs:0})}return new Promise((t,n)=>{let o={definition:e,dataTree:r,hashes:a,ctx:c,seq:s,resolve:t,reject:n,externalSignal:i?.signal,selvaevents:i?.selvaevents,onServerTiming:i?.onServerTiming};o.externalSignal&&(o.queuedAbortHandler=()=>this.abortQueuedItem(o),o.externalSignal.addEventListener(`abort`,o.queuedAbortHandler,{once:!0})),this.enqueue(o)})}writeLastState(e,t){e<this.lastStateSeq||(this.lastStateSeq=e,`result`in t?(this._lastResult=t.result,this._lastError=null):this._lastError=t.error,this._lastDurationMs=t.durationMs)}supersedeCurrent(){this.pendingForLatestWins&&=(this.supersede(this.pendingForLatestWins),null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}dequeue(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null),this.fifo.remove(e)}abortQueuedItem(e){this.dequeue(e),this.fail(e,this.makeAbortError(e.ctx)),this.notify()}shedAsQueueFull(e){let r=new t(`Solve queue is full; request rejected (backpressure)`,n.QUEUE_FULL,{statusCode:503,context:{queueDepth:this.fifo.size,maxQueueDepth:this.maxQueueDepth}});this.fail(e,r),this.notify()}armQueueWaitTimer(e){if(this.queueWaitMs===void 0)return;let r=this.queueWaitMs;e.queueWaitTimer=setTimeout(()=>{if(e.settled)return;this.dequeue(e);let i=new t(`Solve waited longer than ${r}ms in queue; rejected (backpressure)`,n.QUEUE_TIMEOUT,{statusCode:503,context:{waitedMs:Date.now()-e.ctx.enqueuedAt,queueWaitMs:r}});this.fail(e,i),this.notify()},r)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case`latest-wins`:this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break;case`queue`:this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifo.size>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifo.push(e))}this.notify()}async execute(e){let t=new AbortController,n=e;n.controller=t,this.inFlight.add(n),e.ctx.startedAt=Date.now(),this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e);let r=()=>t.abort();e.externalSignal?.addEventListener(`abort`,r,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let i=performance.now();try{let n={...this.baseConfig,signal:t.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry},...e.selvaevents!==void 0&&{selvaevents:e.selvaevents}},r=e.onServerTiming;if(r){let e=this.baseConfig.onServerTiming;n.onServerTiming=(t,n)=>{try{e?.(t,n)}finally{r(t,n)}}}let{response:a,definitionReuploaded:o}=await this.runExecutor(e,n),s=performance.now()-i;if(this.writeCache(e.ctx.key,a),!this.settleSuccess(e,{response:a,fromCache:!1,definitionReuploaded:o,durationMs:s}))return;this.writeLastState(e.seq,{result:a,durationMs:s}),this.runHook(this.onSettle,e.ctx,{status:`success`,response:a,durationMs:s,fromCache:!1,definitionReuploaded:o})}catch(t){let r=performance.now()-i,a=this.normalizeExecutionError(t,n);this.writeLastState(e.seq,{error:a,durationMs:r}),this.fail(e,a,r)}finally{e.externalSignal?.removeEventListener(`abort`,r),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,t){let{definition:n,dataTree:r}=e;if(!this.reuseServerDefinitionCache||o(n)){let{response:e}=await this.executor(n,r,null,t);return{response:e}}let i=e.hashes.definitionHash,a=this.serverCacheKeys.get(i)??null,s=await this.executor(n,r,a,t);return this.serverCacheKeys.delete(i),s.cacheKey&&(this.serverCacheKeys.set(i,s.cacheKey),this.serverCacheKeys.size>100&&this.serverCacheKeys.delete(this.serverCacheKeys.keys().next().value)),{response:s.response,definitionReuploaded:s.missed}}hashDefinitionMemo(e){return typeof e==`string`?(this.lastStringDefinition?.value!==e&&(this.lastStringDefinition={value:e,hash:G(e)}),this.lastStringDefinition.hash):Re(e)}drainNext(){if(!this.disposed){if(this.mode===`latest-wins`){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}return}for(;this.fifo.size>0&&this.inFlight.size<this.maxConcurrent;)this.execute(this.fifo.shift())}}supersede(e){let r=new t(`Superseded by newer solve`,n.SUPERSEDED,{context:{enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new t(`Request aborted by caller`,n.ABORTED,{context:{enqueuedAt:e.enqueuedAt}})}settleError(e,t){return!e.settled&&(e.settled={error:t},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(t),!0)}fail(e,t,n=0){this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:n})}settleSuccess(e,t){return!e.settled&&(e.settled={ok:!0},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.resolve(t),!0)}removeQueuedAbortHandler(e){e.queuedAbortHandler&&e.externalSignal&&e.externalSignal.removeEventListener(`abort`,e.queuedAbortHandler),e.queuedAbortHandler=void 0}normalizeExecutionError(e,r){return r.settled&&`error`in r.settled?r.settled.error:e instanceof t?e:e instanceof Error&&e.name===`AbortError`?this.makeAbortError(r.ctx):new t(e instanceof Error?e.message:String(e),n.UNKNOWN_ERROR,{originalError:e})}cancelAll(){this.pendingForLatestWins&&=(this.fail(this.pendingForLatestWins,this.makeAbortError(this.pendingForLatestWins.ctx)),null);for(let e=this.fifo.shift();e;e=this.fifo.shift())this.fail(e,this.makeAbortError(e.ctx));for(let e of this.inFlight){let t=e.ctx.startedAt?Date.now()-e.ctx.startedAt:0;this.fail(e,this.makeAbortError(e.ctx),t),e.controller.abort()}this.notify()}readCache(e){if(!this.cacheEnabled)return null;let t=this.cache.get(e);return t?this.cacheTtl>0&&Date.now()-t.insertedAt>this.cacheTtl?(this.dropCacheEntry(e),this.cacheMisses+=1,null):(this.cache.delete(e),this.cache.set(e,t),this.cacheHits+=1,t.response):(this.cacheMisses+=1,null)}writeCache(t,n){if(!this.cacheEnabled)return;let r=e(n,`errors`);if(!this.cacheErroredSolves&&Array.isArray(r)&&r.length>0)return;let i=c(n)??Ve(n);if(!(i>this.cacheMaxBytes))for(this.dropCacheEntry(t),this.cache.set(t,{response:n,insertedAt:Date.now(),sizeBytes:i}),this.cacheBytes+=i;this.cacheBytes>this.cacheMaxBytes&&this.cache.size>0;){let e=this.cache.keys().next().value;if(e===void 0)break;this.dropCacheEntry(e),this.cacheEvictions+=1}}dropCacheEntry(e){let t=this.cache.get(e);t&&(this.cache.delete(e),this.cacheBytes-=t.sizeBytes)}clearCache(){this.cache.clear(),this.cacheBytes=0}cacheStats(){return{entries:this.cache.size,bytes:this.cacheBytes,hits:this.cacheHits,misses:this.cacheMisses,evictions:this.cacheEvictions}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(e,...t){if(e)try{e(...t)}catch(e){i().error(`[SolveScheduler] hook threw:`,e)}}};function Ue(e){return m(e)?`ref:${e.key}`:typeof e==`string`&&e.length<200?e:`...content...`}function We(t){return Array.isArray(t)?t.map(t=>{let n=0,r=0,i=e(t,`innerTree`);if(i&&typeof i==`object`){for(let e of Object.values(i))if(Array.isArray(e)){n+=e.length;for(let t of e){let e=t?.data;typeof e==`string`&&(r+=e.length)}}}return{param:e(t,`paramName`)??`<unnamed>`,items:n,bytes:r}}):[]}var Ge=class r{config;serverStats;disposed=!1;static CREATE_PROBE_TIMEOUT_MS=2e3;constructor(e){this.config={...e,serverUrl:h(e.serverUrl),debug:e.debug??!1},this.serverStats=new g(this.config.serverUrl,this.config)}static async create(e,i={}){let a=new r(e),o=Math.max(1,(i.probe?.attempts??2)+1),s=i.probe?.baseDelayMs??250,c=i.probe?.maxDelayMs??1e3,l,u=null,d=0;for(let e=0;e<o;e++){if(d=e+1,l=await a.serverStats.probeServer(r.CREATE_PROBE_TIMEOUT_MS),l.online)return a;if(u=te(l),u&&!u.retryable)break;if(e<o-1){let t=Math.min(s*2**e,c);await new Promise(e=>setTimeout(e,t))}}await a.dispose();let f=l?.status,p=u?`Rhino Compute server is not available. ${u.summary}`:`Rhino Compute server is not online`;throw new t(p,n.NETWORK_ERROR,{...f!==void 0&&{statusCode:f},context:{serverUrl:a.config.serverUrl,attempts:d,maxAttempts:o,...u&&{probeVerdict:u.verdict,probeRetryable:u.retryable},...f!==void 0&&{lastProbeStatus:f},...l?.error!==void 0&&{lastProbeError:l.error}}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),B(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),R(e,this.config)}async solve(r,a,o){this.ensureNotDisposed();try{if(typeof r==`string`&&!r.trim())throw new t(`Definition URL/content is required`,n.INVALID_INPUT,{context:{receivedUrl:r}});if(r instanceof Uint8Array&&r.length===0)throw new t(`Definition content is empty`,n.INVALID_INPUT);if(m(r)&&!r.key.trim())throw new t(`DefinitionRef key is empty`,n.INVALID_INPUT);let i=await le(a,r,{...this.config,...o?.signal!==void 0&&{signal:o.signal},...o?.timeoutMs!==void 0&&{timeoutMs:o.timeoutMs},...o?.retry!==void 0&&{retry:o.retry},...o?.selvaevents!==void 0&&{selvaevents:o.selvaevents}}),s=e(i,`errors`);if(Array.isArray(s)&&s.length>0)throw new t(s.map(String).join(`; `)||`Computation failed`,n.COMPUTATION_ERROR,{context:{definition:Ue(r),inputSummary:We(a),errors:s,warnings:e(i,`warnings`),values:i.values}});return i}catch(e){throw this.config.debug&&i().error(`Compute failed:`,e),e instanceof t?e:new t(e instanceof Error?e.message:String(e),n.COMPUTATION_ERROR,{context:{definition:Ue(r),inputSummary:We(a)},originalError:e})}}createScheduler(e){return this.ensureNotDisposed(),new He((e,t,n,r)=>ue(t,n,e,r),this.config,e)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new t(`GrasshopperClient has been disposed and cannot be used`,n.INVALID_STATE)}};function Ke(e){return typeof e==`object`&&!!e&&e.__decodeError===!0}function qe(e,t){return{__decodeError:!0,type:e,raw:t}}function Je(e){let t=new WeakSet,n=e=>{if(!e||typeof e!=`object`||t.has(e))return;t.add(e);let r=e.delete;if(typeof r==`function`){let t=e.isDeleted;(typeof t!=`function`||!t.call(e))&&r.call(e);return}if(Array.isArray(e)){for(let t of e)n(t);return}let i=Object.getPrototypeOf(e);if(i===Object.prototype||i===null)for(let t of Object.values(e))n(t)};n(e)}const q=new Map([[`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}],[`Rhino.Geometry.Line`,(e,t)=>{let n=t;return!n||!n.From||!n.To?null:new e.Line([n.From.X,n.From.Y,n.From.Z],[n.To.X,n.To.Y,n.To.Z])}]]);function Ye(e){if(q.has(e))return q.get(e);for(let[t,n]of q)if(e.startsWith(t))return n}function Xe(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function Ze(e,t,n){let r=Ye(t),a=!1;if(r)try{let t=r(n,e);if(t!=null)return t}catch(e){i().warn(`Failed to decode Rhino type ${t}:`,e),a=!0}try{if(Xe(e))return n.CommonObject.decode(e)}catch(n){return i().warn(`Failed to decode ${t} with CommonObject:`,n),qe(t,e)}return a?qe(t,e):e}const J={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},Qe=`FileData`;function $e(e,t){return e.includes(`WebDisplay`)||t&&e!==J.STRING}function et(e){if(typeof e!=`string`)return e;let t=e.trim();if(!(t.startsWith(`{`)||t.startsWith(`[`)||t.startsWith(`"`)))return e;try{let e=JSON.parse(t);if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}catch{return e}}function tt(e,t,n){switch(t){case J.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case J.INT:return Number.parseInt(String(e),10);case J.DOUBLE:return Number.parseFloat(String(e));case J.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?Ze(e,t,n):e}}function Y(e,t,n,r){if(typeof e.data!=`string`)return e.data;let i=n?et(e.data):e.data;return n&&t.includes(Qe)?nt(i)??i:tt(i,t,r)}function nt(t){if(!t||typeof t!=`object`)return null;let n=e(t,`fileName`),i=e(t,`fileType`),a=e(t,`subFolder`),o=e(t,`isBase64Encoded`);if(typeof n!=`string`||typeof i!=`string`||typeof a!=`string`||!r(t,`data`)||typeof o!=`boolean`&&typeof o!=`string`)return null;let s=e(t,`metadata`);return{fileName:n,fileType:i,data:e(t,`data`),isBase64Encoded:u(o),subFolder:a,...s?{metadata:s}:{}}}function X(t){let n=e(t,`values`);return Array.isArray(n)?n:[]}function Z(e){return typeof e.type==`string`?e.type:``}function Q(e,t){if(e&&typeof e==`object`){for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)e&&typeof e==`object`&&t(e)}}function rt(t,n=!1,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r,s={},c=new Set;for(let r of X(t)){let t=e(r,`paramName`);Q(e(r,`innerTree`),e=>{let r=Z(e);if($e(r,o))return;let l=n?e.id:t;if(!l)return;let u=Y(e,r,i,a);Object.prototype.hasOwnProperty.call(s,l)?c.has(l)?s[l].push(u):(s[l]=[s[l],u],c.add(l)):x(s,l,u)})}return{values:s,dispose:()=>Je(s)}}function it(t){let n=[];for(let r of X(t))Q(e(r,`innerTree`),e=>{if(!Z(e).includes(Qe))return;let t=nt(et(e.data));t&&n.push(t)});return n}function at(t,n,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r;for(let r of X(t)){let t=e(r,`innerTree`),s=!1;if(`byName`in n){if(e(r,`paramName`)!==n.byName)continue;s=!0}let c=[];if(Q(t,e=>{if(`byId`in n){if(e.id!==n.byId)return;s=!0}let t=Z(e);$e(t,o)||c.push(Y(e,t,i,a))}),s)return c.length===0?void 0:c.length===1?c[0]:c}}var ot=class{response;constructor(e){this.response=e}getValues(e=!1,t={}){return rt(this.response,e,t)}getValue(e,t){return at(this.response,e,t)}async getAndDownloadFiles(e,t){await ee(it(this.response),e,t)}};function st(t){return(Array.isArray(t)?t:[t]).map(t=>({schemas:e(t,`schemas`),error:e(t,`error`)}))}const ct=new Set([`options`,`defaultOptions`,`values`]),lt=new Set([`optionMedia`,`assets`]),ut=e=>e>=`A`&&e<=`Z`;function dt(e){if(e.length===0||!ut(e[0]))return e;let t=0;for(;t<e.length&&ut(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function ft(e){return $(e)}function $(e){if(Array.isArray(e))return e.map($);if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e)){let e=dt(n);x(t,e,ct.has(e)?r:lt.has(e)?pt(r):$(r))}return t}function pt(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t={};for(let[n,r]of Object.entries(e))x(t,n,$(r));return t}var mt=class r{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(e,t){let n=this.innerTree[r.formatPathString(e)]??=[];for(let e of t)n.push({data:r.serializeValue(e)});return this}fromDataTreeDefault(e){this.innerTree={};for(let[t,n]of Object.entries(e)){if(!Array.isArray(n))continue;let e=r.parsePathString(t);this.append(e,n)}return this}appendFlat(e){let t=Array.isArray(e)?e:[e];return this.append([0],t)}flatten(){let e=[];for(let t of Object.values(this.innerTree))if(Array.isArray(t))for(let n of t)e.push(r.deserializeValue(n.data));return e}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getParamName(){return this.paramName}static fromInputParams(e){return r.fromValues(e.map(e=>({paramName:e.nickname||`unnamed`,paramType:e.paramType,value:e.default,...`minimum`in e&&{minimum:e.minimum,maximum:e.maximum}})))}static fromValues(e){let t=[];for(let n of e){let e=new r(n.paramName),a=r.itemCoercer(n);for(let[t,o]of r.branchesOf(n.value)){let r=[];for(let e of o){if(e==null)continue;let t=a(e);t===null?i().warn(`${n.paramName}: dropped an item that is not a valid ${n.paramType}`):r.push(t)}r.length>0&&e.append(t,r)}Object.keys(e.innerTree).length>0&&t.push(e.toComputeFormat())}return t}static branchesOf(e){return r.hasValidValue(e)?C(e)?Object.entries(e).map(([e,t])=>[r.parsePathString(e),t]):[[[0],Array.isArray(e)?e:[e]]]:[]}static itemCoercer(e){let{paramName:t,minimum:n,maximum:i}=e,a=e.paramType.toLowerCase();return a===`number`||a===`integer`?e=>{let o=T(e);if(o===null)return null;let s=a===`integer`?Math.round(o):o;return r.clampValue(s,n,i,t)}:a===`boolean`?E:e=>e}static replaceTreeValue(e,t,n){let i=r.buildFromValue(t,n).toComputeFormat(),a=e.slice(),o=a.findIndex(e=>r.paramNameOf(e)===t);return o===-1?a.push(i):a[o]=i,a}static buildFromValue(e,t){let n=new r(e);return C(t)?n.fromDataTreeDefault(t):n.appendFlat(t),n}static getTree(t,n){let i=t.find(e=>r.paramNameOf(e)===n);if(!i)return null;let a=new Map,o=e(i,`InnerTree`);if(!o||typeof o!=`object`)return a;for(let[e,t]of Object.entries(o))Array.isArray(t)&&a.set(e,t.map(e=>e?.data===void 0?null:r.deserializeValue(e.data)));return a}static getTreeValue(e,i){let a=r.getTree(e,i);if(!a||a.size===0)return null;if(a.size>1)throw new t(`"${i}" has ${a.size} branches; read it with TreeBuilder.getTree`,n.INVALID_INPUT,{context:{paramName:i,branchCount:a.size}});let[o]=a.values();return o.length===0?null:o.length===1?o[0]:o}static paramNameOf(t){return e(t,`ParamName`)}static parsePathString(e){let r=e.match(S);if(!r)throw new t(`Invalid Grasshopper tree path: "${e}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`,n.INVALID_INPUT,{context:{pathStr:e}});return r[1]?r[1].split(`;`).map(Number):[]}static formatPathString(e){return`{${e.join(`;`)}}`}static serializeValue(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`?e:typeof e==`object`&&e?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e!=`string`)return e;if(e.startsWith(`{`)||e.startsWith(`[`))try{return JSON.parse(e)}catch{return e}let t=Number(e);return Number.isFinite(t)&&String(t)===e?t:e===`true`||e!==`false`&&e}static hasValidValue(e){return e==null?!1:typeof e==`string`||!(Array.isArray(e)&&e.length===0||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0)}static clampValue(e,t,n,r){let a=e;return t!=null&&a<t&&(i().warn(`${r}: ${e} below min ${t}, clamping`),a=t),n!=null&&a>n&&(i().warn(`${r}: ${e} above max ${n}, clamping`),a=n),a}};export{g as ComputeServerStats,Ge as GrasshopperClient,ot as GrasshopperResponseProcessor,He as SolveScheduler,mt as TreeBuilder,Je as disposeRhinoObjects,R as fetchDefinitionIO,B as fetchParsedDefinitionIO,G as hashDefinition,Le as hashSolveInput,Ke as isRhinoDecodeError,ft as normalizeUISchemaCasing,ke as processInput,st as readSchemaResults,le as solveGrasshopperDefinition,U as stableStringify};
|
|
1
|
+
import{C as e,D as t,O as n,S as r,T as i,_ as a,c as o,d as s,f as c,h as l,i as u,l as d,m as f,p,s as m,t as ee,u as te,v as ne,x as h,y as re}from"./core-BPYXUtfq.js";var g=class e{serverUrl;headers;disposed=!1;activeMonitors=/* @__PURE__ */ new Set;static DEFAULT_TIMEOUT_MS=5e3;static LIFECYCLE_TIMEOUT_MS=6e4;static MIN_MONITOR_INTERVAL_MS=100;static MAX_BODY_BYTES=1<<20;constructor(e,t){this.serverUrl=h(e),this.headers={...re(typeof t==`string`?{apiKey:t}:t??{}),"Content-Type":`application/json`}}fetchWithTimeout(t,n={},r=e.DEFAULT_TIMEOUT_MS){let i={...n,headers:this.headers,redirect:`manual`};return r>0&&!i.signal&&(i.signal=AbortSignal.timeout(r)),fetch(t,i)}async getText(t,n={},r=e.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let a=`${n.method??`GET`} ${t}`;try{let o=await this.fetchWithTimeout(`${this.serverUrl}${t}`,n,r);if(!o.ok)return i().warn(`[ComputeServerStats] ${a} failed:`,o.status),await o.body?.cancel().catch(()=>{}),null;let{text:s,truncated:c}=await f(o,e.MAX_BODY_BYTES);return c?(i().warn(`[ComputeServerStats] ${a} answered with an oversized body`),null):s}catch(e){return i().warn(`[ComputeServerStats] ${a} errored:`,e),null}}async isServerOnline(t=e.DEFAULT_TIMEOUT_MS){return(await this.probeServer(t)).online}async probeServer(t=e.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let n=`${this.serverUrl}/`;try{let e=await this.fetchWithTimeout(n,{method:`GET`},t);return await e.body?.cancel().catch(()=>{}),{online:e.ok||s(e),status:e.status}}catch(e){return i().debug(`[ComputeServerStats] Fetch error:`,e),{online:!1,error:e instanceof Error?`${e.name}: ${e.message}`:String(e)}}}async getActiveChildren(t={}){let{initialize:n=!0}=t,r=n?await this.getText(`/activechildren`,{},e.LIFECYCLE_TIMEOUT_MS):await this.getText(`/activechildren?initialize=false`);if(r===null)return null;let a=r.trim();return/^\d+$/.test(a)?parseInt(a,10):(i().warn(`[ComputeServerStats] /activechildren answered with a non-numeric body`),null)}async getVersion(){let e=await this.getText(`/version`);if(e===null)return null;let t=_(e);return t==null?{rhino:e,compute:``,git_sha:null}:{rhino:t.rhino??``,compute:t.compute??``,git_sha:t.git_sha??null}}async getInstalledPlugins(e=`gh`){let t=await this.getText(`/plugins/${e}/installed`),n=t===null?void 0:_(t);return n&&typeof n==`object`?n:null}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[e,t]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...e&&{version:e},...t!==null&&{activeChildren:t}}}async purgeCache(){let e=await this.getText(`/cache/purge`,{method:`POST`}),t=(e===null?void 0:_(e))?.purged;return typeof t==`number`?t:null}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return i().warn(`[ComputeServerStats] purgeAllChildren: could not read child count`),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let t=e*2,n=0;for(let e=0;e<t;e++){let e=await this.purgeCache();e!==null&&(n+=e)}return{totalPurged:n,calls:t,children:e,confident:e===1}}async getServerTime(){let e=await this.getText(`/servertime`);if(e===null)return null;let t=new Date(e.trim().replace(/^"|"$/g,``));return isNaN(t.getTime())?null:t}async getIdleSpan(){let e=await this.getText(`/idlespan`);if(e===null)return null;let t=parseFloat(e.trim());return isNaN(t)?null:t}async launchChildren(){return this.postJson(`/launch-children`)}async launchChild(e){let t=e===void 0?`/launch-child`:`/launch-child?port=${e}`;return this.postJson(t)}async shutdownChildren(e){let t=e===void 0?`/shutdown-children`:`/shutdown-children?port=${e}`;return this.postJson(t)}async recycleChildren(e){let t=e===void 0?`/recycle-children`:`/recycle-children?port=${e}`;return this.postJson(t)}async postJson(t){let n=await this.getText(t,{method:`POST`},e.LIFECYCLE_TIMEOUT_MS);return n===null?null:_(n)??null}monitor(r,a=5e3){if(this.ensureNotDisposed(),!Number.isFinite(a)||a<e.MIN_MONITOR_INTERVAL_MS)throw new t(`monitor() intervalMs must be a finite number >= ${e.MIN_MONITOR_INTERVAL_MS}ms, got ${a}. Sub-${e.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`,n.INVALID_CONFIG,{context:{intervalMs:a}});let o=!0,s=null;i().info(`🔄 Starting server stats monitoring every ${a}ms`);let c=async()=>{if(s=null,o&&!this.disposed){try{let e=await this.getServerStats();if(!o||this.disposed)return;try{r(e)}catch(e){i().error(`[ComputeServerStats] Monitor callback threw:`,e)}}catch(e){!o||this.disposed?i().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,e):i().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,e)}o&&!this.disposed&&(s=setTimeout(()=>void c(),a))}},l=()=>{o=!1,s!==null&&(clearTimeout(s),s=null),this.activeMonitors.delete(l)};return this.activeMonitors.add(l),c(),l}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear()}}ensureNotDisposed(){if(this.disposed)throw new t(`ComputeServerStats has been disposed and cannot be used`,n.INVALID_STATE)}};function _(e){try{return JSON.parse(e)}catch{return}}const v=/* @__PURE__ */ new Set;function ie(){if(typeof window>`u`||globalThis.process?.versions?.node!=null)return!1;let e=globalThis.navigator,t=typeof e?.userAgent==`string`?e.userAgent:``;return!/jsdom/i.test(t)}function y(e,t){t||ie()&&!v.has(e)&&(v.add(e),i().warn(`Warning: ${e} is running on the client side. For better performance and security, consider running this on the server side.`))}const ae={definition_not_cached:n.DEFINITION_NOT_CACHED};function oe(e){return{...e,serverErrorCodes:{...ae,...e.serverErrorCodes}}}function se(e){return e instanceof t?e.code===n.DEFINITION_NOT_CACHED||e.message.includes(`Unable to load grasshopper definition`):!1}function ce(t,n){if(!n)return;let r=e(t,`values`);if(!Array.isArray(r)||r.length===0)return;let a=[];for(let t of r){let n=e(t,`innerTree`);n&&Object.keys(n).length!==0||a.push(e(t,`paramName`)??`<unnamed>`)}if(a.length===0)return;let o=a.length===r.length?`all`:`${a.length}/${r.length}`;i().warn(`Solve returned empty output(s) (${o}): ${a.join(`, `)}. These parameters produced no data — check the definition's inputs and the branch feeding each.`)}async function le(e,t,n){return y(`solveGrasshopperDefinition`,n.suppressBrowserWarning),(await de(e,t,n)).response}async function ue(e,t,n,r){if(y(`solveWithServerCacheKey`,r.suppressBrowserWarning),t!==null)try{return{...await pe({algo:null,pointer:t,values:e},r),missed:!1}}catch(e){if(!se(e))throw e}return{...await de(e,n,r),missed:!0}}async function de(e,t,n){return pe(b(await fe(t),e),n)}async function fe(e){if(!m(e))return e;try{return await e.load()}catch(r){throw new t(`Failed to load definition bytes for ref '${e.key}'`,n.INVALID_INPUT,{context:{definitionKey:e.key},originalError:r})}}async function pe(e,t){h(t.serverUrl),me(e,t);let{maxResponseBytes:n}=t,r=await d(`grasshopper`,e,oe({...t,maxResponseBytes:n!==void 0&&e.algo?n+e.algo.length:n})),{pointer:i,algo:a,...o}=r,s=o,l=c(r);if(l!==void 0){let e=typeof a==`string`?a.length:0;p(s,Math.max(0,l-e))}return ce(s,t.debug),{response:s,cacheKey:typeof i==`string`?i:null}}function b(e,t){let n={algo:null,pointer:null,values:t};return e instanceof Uint8Array?n.algo=l(e):o(e)?n.pointer=e:n.algo=a(e)??ne(e),n}function me(e,t){t.cachesolve!=null&&(e.cachesolve=t.cachesolve),t.cacheerroredsolves!=null&&(e.cacheerroredsolves=t.cacheerroredsolves),t.modelunits!=null&&(e.modelunits=t.modelunits),t.angletolerance!=null&&(e.angletolerance=t.angletolerance),t.absolutetolerance!=null&&(e.absolutetolerance=t.absolutetolerance),t.dataversion!=null&&(e.dataversion=t.dataversion),t.selvaevents!=null&&(e.selvaevents=t.selvaevents)}function x(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}const S=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function C(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>S.test(e)&&Array.isArray(t))}function w(e,t,n){if(e==null)return e;if(Array.isArray(e)){let n=e.map(t).filter(e=>e!==null);return n.length>0?n:void 0}let r=t(e);return r===null?n?void 0:e:r}const T=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=e.trim();if(t===``||/^[+-]?0[xbo]/i.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}return null},E=e=>{if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}return null},he=e=>typeof e==`string`?e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e.startsWith(`"`)?e.slice(1):e:null,ge=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function D(e){return t=>{if(typeof t==`object`&&t)return t;if(typeof t==`string`&&t.trim()!==``)try{let n=JSON.parse(t);return typeof n==`object`&&n?n:(i().warn(`Parsed value for input ${e} is not an object`),null)}catch(n){return i().warn(`Failed to parse object value "${t}" for input ${e}`,n),null}return null}}const _e=/* @__PURE__ */ new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),ve=/* @__PURE__ */ new Set([`System.Int32`,`System.Int64`]);function O(e,t){return i().warn(t),{schema:{...e,default:null},warning:{code:n.MALFORMED_DEFAULT,message:t}}}function ye(t,a){if(typeof t.default!=`object`||t.default===null||Array.isArray(t.default)||C(t.default))return{schema:t};if(!r(t.default,`innerTree`))return O(t,`Input "${a}" default had an unrecognized shape (no innerTree key); the default was dropped.`);let o=e(t.default,`innerTree`)??{};if(Object.keys(o).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let r={},s=[];for(let[n,i]of Object.entries(o)){if(!Array.isArray(i))return O(t,`Input "${a}" default had a non-array innerTree branch ("${n}"); the default was dropped.`);let o=[];for(let t of i){let n=e(t,`data`),r=e(t,`type`);if(r&&_e.has(r)){if(typeof n==`string`&&n.trim()===``)continue;let e=T(n);if(e===null){s.push(`"${String(n)}" (${r})`);continue}o.push(ve.has(r)?Math.round(e):e)}else if(r===`System.Boolean`){let e=E(n);if(e===null){s.push(`"${String(n)}" (${r})`);continue}o.push(e)}else if(typeof n==`string`&&r?.startsWith(`Rhino.Geometry`))try{o.push(JSON.parse(n))}catch{o.push(n)}else o.push(n)}x(r,n,o)}if(s.length>0){let e=`Input "${a}" default contained ${s.length} tree value(s) that could not be parsed and were dropped: ${s.join(`, `)}.`;return i().warn(e),{schema:{...t,default:r},warning:{code:n.MALFORMED_DEFAULT,message:e}}}return{schema:{...t,default:r}}}let s=[];for(let t of Object.values(o))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&r(n,`data`)&&s.push(e(n,`data`));return{schema:{...t,default:s.length>1?s:s[0]}}}function be(e,t){let n=Number(e.toFixed(t));return Math.abs(e-n)<1e-8?n:e}function k(e){if(!Number.isFinite(e))return 0;let[t,n]=String(Math.abs(e)).split(`e`),r=n===void 0?Math.abs(e).toFixed(12).replace(/0+$/,``).split(`.`)[1]?.length??0:(t.split(`.`)[1]?.length??0)-Number(n);return Math.min(Math.max(r,0),12)}function xe(e){if(!Number.isFinite(e)||e===0)return .1;let t=k(e);return t===0?Math.abs(e)>=1?1:.1:Number((10**-t).toFixed(t))}function A(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}const j=(e,t)=>(e.atMost??1)>1?[t]:t,M=e=>A(e)??(e.paramType===`Integer`?1:.1),N=(e,t)=>Array.isArray(e)?e.map(e=>typeof e==`number`?t(e):e):typeof e==`number`?t(e):e;function Se(e){if(C(e.default))return{default:e.default,stepSize:M(e)};if(typeof e.default==`string`&&e.default.trim()!==``&&T(e.default)===null)throw new t(`Invalid numeric default "${e.default}" for input "${e.name||`unknown`}"`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});let r=w(e.default,T,!0);if(e.paramType===`Integer`)return{default:N(r,Math.round),stepSize:M(e)};let i=Array.isArray(r)?r[0]:r,a=[i,e.minimum,e.maximum].find(e=>typeof e==`number`&&Number.isFinite(e)&&e!==0),o=A(e)??(a===void 0?.1:xe(a)),s=k(o);if(s===0&&typeof i==`number`&&i!==0&&Math.abs(i)<1){let e=Math.ceil(-Math.log10(Math.abs(i)));Number.isFinite(e)&&e>0&&(s=e)}return s=Math.min(Math.max(s,0),12),{default:N(r,e=>be(e,s)),stepSize:o}}const P={parse(e,t){let{default:n,stepSize:r}=Se(e);return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:r,default:n}},fallback(e,t){let n=typeof e.minimum==`number`&&Number.isFinite(e.minimum)&&e.minimum>0?e.minimum:0;return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:M(e),default:j(e,n)}}},Ce={parse(e,r){if(C(e.default))return{...r,paramType:`Boolean`,default:e.default};let i=w(e.default,E,!1);if(i!=null&&typeof i!=`boolean`&&!Array.isArray(i))throw new t(`Invalid boolean default "${String(i)}" for input "${e.name||`unknown`}"`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});return{...r,paramType:`Boolean`,default:i}},fallback(e,t){return{...t,paramType:`Boolean`,default:j(e,!1)}}},we={parse(e,t){let n=w(e.default,he,!1);return{...t,paramType:`Text`,default:n}}},Te={parse(e,r,a){if(!e.values||typeof e.values!=`object`||Object.keys(e.values).length===0){let r=e.nickname||`unnamed`;throw new t(`Input "${r}" has no values defined (expected ValueList)`,n.INVALID_INPUT,{context:{inputName:r,expectedType:`ValueList`}})}let o=e.default;if(e.default!==void 0&&e.default!==null){if(typeof e.default==`object`)throw new t(`ValueList input "${e.nickname||`unnamed`}" default is not a string-able value`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});let r=String(e.default).toLowerCase(),s=Object.keys(e.values).find(e=>e.toLowerCase()===r);if(s!==void 0)o=s;else{let t=`ValueList input "${e.nickname||`unnamed`}" default value "${e.default}" is not in available values`;i().warn(t),a?.({code:n.VALIDATION_ERROR,message:t})}}return{...r,paramType:`ValueList`,values:e.values,default:o}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}};function F(e,t){return{...t,paramType:`Geometry`,default:j(e,null)}}const I=/* @__PURE__ */ new Map([[`Number`,P],[`Integer`,P],[`Boolean`,Ce],[`Text`,we],[`ValueList`,Te],[`Geometry`,{parse(e,t){let n=w(e.default,D(e.nickname||`unnamed`),!0);return{...t,paramType:`Geometry`,default:n}},fallback:F}],[`File`,{parse(e,t){let n=w(e.default,D(e.nickname||`unnamed`),!0);return{...t,paramType:`File`,acceptedFormats:e.acceptedFormats,default:n}}}],[`Color`,{parse(e,t){let n=w(e.default,ge,!1);return{...t,paramType:`Color`,default:n}}}]]),Ee=F,De=new Map([...I.keys()].map(e=>[e.toLowerCase(),e]));function Oe(e){return De.get(e?.toLowerCase())??e}function ke(e){return L(e).input}function L(e){let r=e.name||`unknown`,a=[],o=({code:t,message:n})=>{a.push({inputName:r,paramType:e.paramType,message:n,code:t})},s={description:e.description,name:e.name,nickname:e.nickname,treeAccess:e.treeAccess,groupName:e.groupName??void 0,id:e.id},c=Oe(e.paramType),l={...e,paramType:c};try{let{schema:e,warning:t}=ye(l,r);l=e,t&&o(t)}catch(e){l={...l,default:null},o({code:n.MALFORMED_DEFAULT,message:`Input "${r}" default could not be normalized and was dropped: ${e instanceof Error?e.message:String(e)}`})}let u=I.get(c);try{if(!u)throw new t(`Unknown paramType: ${c}`,n.VALIDATION_ERROR,{context:{receivedParamType:c,paramName:e.name}});return{input:u.parse(l,s,o),errors:a}}catch(d){if(!(d instanceof t))throw new t(d instanceof Error?d.message:String(d),n.VALIDATION_ERROR,{context:{paramName:e.name,paramType:c},originalError:d});return i().error(`Validation error for input ${r}:`,d.message),o(d),{input:(u?.fallback??Ee)(l,s),errors:a}}}function Ae(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=L(r);t.push(e),n.push(...i)}return{inputs:t,parseErrors:n}}function je(t){let n=e(t,`stepSize`);return{id:e(t,`id`)??``,name:e(t,`name`)??``,nickname:e(t,`nickname`)??null,description:e(t,`description`)??``,paramType:e(t,`paramType`)??``,treeAccess:e(t,`treeAccess`)??!1,minimum:e(t,`minimum`)??null,maximum:e(t,`maximum`)??null,atLeast:e(t,`atLeast`)??1,atMost:e(t,`atMost`)??1,stepSize:typeof n==`number`&&Number.isFinite(n)?n:void 0,default:e(t,`default`),values:e(t,`values`),acceptedFormats:e(t,`acceptedFormats`),groupName:e(t,`groupName`)??null}}function Me(t){return{name:e(t,`name`)??``,nickname:e(t,`nickname`)??null,paramType:e(t,`paramType`)??``,id:e(t,`id`)??``}}async function R(r,i){y(`fetchDefinitionIO`,i.suppressBrowserWarning),h(i.serverUrl);let{algo:a,pointer:o}=b(r,[]);if(!a&&!o)throw new t(`Definition must resolve to either a URL pointer or base64 algo`,n.INVALID_INPUT);let s=await d(`io`,a?{algo:a}:{pointer:o},oe(i));if(!s||typeof s!=`object`)throw new t(`Invalid IO response structure`,n.INVALID_INPUT,{context:{response:s}});let c=z(e(s,`warnings`)),l=z(e(s,`errors`)),u=e(s,`inputs`),f=e(s,`outputs`);return{inputs:Array.isArray(u)?u.map(je):[],outputs:Array.isArray(f)?f.map(Me):[],...c&&{loadWarnings:c},...l&&{loadErrors:l}}}function z(e){if(!Array.isArray(e))return;let t=e.map(Ne).filter(e=>e!==void 0);return t.length>0?t:void 0}function Ne(t){if(t==null)return;let n;if(typeof t==`string`)n=t;else if(typeof t==`object`){let r=e(t,`message`);if(typeof r==`string`&&r.trim().length>0)n=r;else try{n=JSON.stringify(t)??String(t)}catch{n=String(t)}}else n=String(t);return n.trim().length>0?n:void 0}async function B(e,t){let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await R(e,t),{inputs:o,parseErrors:s}=Ae(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}const V=globalThis.process?.getBuiltinModule?.(`node:crypto`);function H(e){if(V){let t=V.createHash(`sha256`);return typeof e==`string`?t.update(e,`utf16le`):t.update(e),t.digest(`hex`)}return Fe(e)}const Pe=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Fe(e){let t=new Ie;return typeof e==`string`?t.updateString(e):t.update(e),t.digestHex()}var Ie=class{h=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);w=/* @__PURE__ */ new Int32Array(64);pending=/* @__PURE__ */ new Uint8Array(64);pendingLength=0;totalBytes=0;update(e){this.totalBytes+=e.length;let t=0;if(this.pendingLength>0){let n=Math.min(64-this.pendingLength,e.length);if(this.pending.set(e.subarray(0,n),this.pendingLength),this.pendingLength+=n,t=n,this.pendingLength<64)return;this.compressBytes(this.pending,0),this.pendingLength=0}for(;t+64<=e.length;t+=64)this.compressBytes(e,t);this.pending.set(e.subarray(t),0),this.pendingLength=e.length-t}updateString(e){let t=this.w,n=e.length-e.length%32;for(let r=0;r<n;r+=32){for(let n=0;n<16;n++){let i=e.charCodeAt(r+2*n),a=e.charCodeAt(r+2*n+1);t[n]=(i&255)<<24|i>>>8<<16|(a&255)<<8|a>>>8}this.compress()}this.totalBytes+=n*2;let r=new Uint8Array((e.length-n)*2);for(let t=n,i=0;t<e.length;t++){let n=e.charCodeAt(t);r[i++]=n&255,r[i++]=n>>>8}this.update(r)}digestHex(){let e=this.totalBytes*8,t=new Uint8Array(this.pendingLength<56?64:128);t.set(this.pending.subarray(0,this.pendingLength)),t[this.pendingLength]=128;let n=new DataView(t.buffer);n.setUint32(t.length-8,Math.floor(e/4294967296)),n.setUint32(t.length-4,e>>>0);for(let e=0;e<t.length;e+=64)this.compressBytes(t,e);let r=``;for(let e of this.h)r+=(e>>>0).toString(16).padStart(8,`0`);return r}compressBytes(e,t){let n=this.w;for(let r=0;r<16;r++){let i=t+r*4;n[r]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}this.compress()}compress(){let e=this.w;for(let t=16;t<64;t++){let n=e[t-15],r=e[t-2],i=(n>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,a=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10;e[t]=e[t-16]+i+e[t-7]+a|0}let t=this.h,n=t[0],r=t[1],i=t[2],a=t[3],o=t[4],s=t[5],c=t[6],l=t[7];for(let t=0;t<64;t++){let u=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),d=o&s^~o&c,f=l+u+d+Pe[t]+e[t]|0,p=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&r^n&i^r&i)|0;l=c,c=s,s=o,o=a+f|0,a=i,i=r,r=n,n=f+p|0}t[0]=t[0]+n|0,t[1]=t[1]+r|0,t[2]=t[2]+i|0,t[3]=t[3]+a|0,t[4]=t[4]+o|0,t[5]=t[5]+s|0,t[6]=t[6]+c|0,t[7]=t[7]+l|0}};function U(e){let t=/* @__PURE__ */ new WeakSet,n=e=>{if(e===null)return`null`;if(typeof e==`number`)return Number.isFinite(e)?String(e):`null`;if(typeof e==`string`||typeof e==`boolean`)return JSON.stringify(e);if(typeof e==`bigint`)return`${e}n`;if(typeof e!=`object`)return`undefined`;if(e instanceof Uint8Array)return`{u8:${H(e)}}`;if(t.has(e))return`[Circular]`;t.add(e);let r;if(Array.isArray(e)){let t=[];for(let r=0;r<e.length;r++)t.push(n(e[r]));r=`[${t.join(`,`)}]`}else r=typeof e.toJSON==`function`?n(e.toJSON()):e instanceof Map?`{map:[${[...e.entries()].map(([e,t])=>`[${n(e)},${n(t)}]`).sort().join(`,`)}]}`:e instanceof Set?`{set:[${[...e.values()].map(n).sort().join(`,`)}]}`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${n(e[t])}`).join(`,`)}}`;return t.delete(e),r};return n(e)}function Le(e,t){return W(G(e),t)}function W(e,t){return`${e}|t:${H(U(t))}`}function G(e){return m(e)?`r:${e.key}`:typeof e==`string`?`s:${H(e)}`:`u8:${H(e)}`}const K=/* @__PURE__ */ new WeakMap;function Re(e){if(!(e instanceof Uint8Array))return G(e);let t=K.get(e);return t===void 0&&(t=G(e),K.set(e,t)),t}var ze=class{hashDefinition;dataTree;definitionMemo;keyMemo;constructor(e,t){this.hashDefinition=e,this.dataTree=t}get definitionHash(){return this.definitionMemo??=this.hashDefinition()}get key(){return this.keyMemo??=W(this.definitionHash,this.dataTree)}},Be=class{items=[];head=0;live=/* @__PURE__ */ new Set;get size(){return this.live.size}push(e){this.items.push(e),this.live.add(e)}remove(e){this.live.delete(e)&&this.compact()}shift(){for(;this.head<this.items.length;){let e=this.items[this.head];if(this.items[this.head++]=void 0,e&&this.live.delete(e))return this.compact(),e}}compact(){if(this.live.size===0){this.items=[],this.head=0;return}let e=this.items.length-this.live.size;e<=64||e<=this.live.size||(this.items=this.items.filter(e=>e!==void 0&&this.live.has(e)),this.head=0)}};function Ve(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var He=class{executor;baseConfig;mode;maxConcurrent;maxQueueDepth;queueWaitMs;timeoutMs;retry;cacheEnabled;cacheMaxBytes;cacheTtl;cacheErroredSolves;cache=/* @__PURE__ */ new Map;cacheBytes=0;cacheHits=0;cacheMisses=0;cacheEvictions=0;reuseServerDefinitionCache;serverCacheKeys=/* @__PURE__ */ new Map;lastStringDefinition=null;onStart;onSettle;onSuperseded;subscribers=/* @__PURE__ */ new Set;inFlight=/* @__PURE__ */ new Set;pendingForLatestWins=null;fifo=new Be;_lastResult=null;_lastError=null;_lastDurationMs=null;solveSeq=0;lastStateSeq=0;disposed=!1;constructor(e,r,i={}){if(this.executor=e,this.baseConfig=r,this.mode=i.mode??`latest-wins`,this.mode!==`latest-wins`&&this.mode!==`queue`)throw new t(`Unknown scheduler mode '${String(this.mode)}'. For concurrent solves use { mode: 'queue', maxConcurrent: 4 }.`,n.INVALID_CONFIG,{context:{mode:this.mode}});this.maxConcurrent=Math.max(1,i.maxConcurrent??1),this.maxQueueDepth=i.maxQueueDepth!==void 0&&i.maxQueueDepth>0?Math.floor(i.maxQueueDepth):void 0,this.queueWaitMs=i.queueWaitMs!==void 0&&i.queueWaitMs>0?i.queueWaitMs:void 0,this.timeoutMs=i.timeoutMs,this.retry=i.retry;let a=i.cache,o=typeof a==`object`?a:null;this.cacheMaxBytes=Math.max(0,o?.maxBytes??0),this.cacheEnabled=this.cacheMaxBytes>0,this.cacheTtl=o?.ttlMs??0,this.cacheErroredSolves=o?.cacheErroredSolves??!0,this.reuseServerDefinitionCache=i.reuseServerDefinitionCache??!0,this.onStart=i.onStart,this.onSettle=i.onSettle,this.onSuperseded=i.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifo.size>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifo.size+ +!!this.pendingForLatestWins}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}setMaxConcurrent(e){let t=Math.max(1,Math.floor(e));if(t===this.maxConcurrent)return;let n=t>this.maxConcurrent;this.maxConcurrent=t,n&&this.drainNext()}getMaxConcurrent(){return this.maxConcurrent}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(e){i().error(`[SolveScheduler] subscriber threw:`,e)}}solve(e,t,n){return this.solveDetailed(e,t,n).then(e=>e.response)}solveDetailed(e,r,i){if(this.disposed)return Promise.reject(new t(`SolveScheduler has been disposed and cannot be used`,n.INVALID_STATE));let a=new ze(()=>this.hashDefinitionMemo(e),r),o=``;if(this.cacheEnabled||this.onStart||this.onSettle||this.onSuperseded)try{o=a.key}catch(e){return Promise.reject(new t(`Solve input could not be hashed`,n.INVALID_INPUT,{originalError:e}))}let s=++this.solveSeq,c={key:o,enqueuedAt:Date.now(),startedAt:null};if(i?.signal?.aborted)return Promise.reject(this.makeAbortError(c));let l=this.readCache(o);if(l){this.mode===`latest-wins`&&this.supersedeCurrent();let e={status:`success`,response:l,durationMs:0,fromCache:!0};return this.writeLastState(s,{result:l,durationMs:0}),this.runHook(this.onStart,c),this.runHook(this.onSettle,c,e),this.notify(),Promise.resolve({response:l,fromCache:!0,durationMs:0})}return new Promise((t,n)=>{let o={definition:e,dataTree:r,hashes:a,ctx:c,seq:s,resolve:t,reject:n,externalSignal:i?.signal,selvaevents:i?.selvaevents,onServerTiming:i?.onServerTiming};o.externalSignal&&(o.queuedAbortHandler=()=>this.abortQueuedItem(o),o.externalSignal.addEventListener(`abort`,o.queuedAbortHandler,{once:!0})),this.enqueue(o)})}writeLastState(e,t){e<this.lastStateSeq||(this.lastStateSeq=e,`result`in t?(this._lastResult=t.result,this._lastError=null):this._lastError=t.error,this._lastDurationMs=t.durationMs)}supersedeCurrent(){this.pendingForLatestWins&&=(this.supersede(this.pendingForLatestWins),null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}dequeue(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null),this.fifo.remove(e)}abortQueuedItem(e){this.dequeue(e),this.fail(e,this.makeAbortError(e.ctx)),this.notify()}shedAsQueueFull(e){let r=new t(`Solve queue is full; request rejected (backpressure)`,n.QUEUE_FULL,{statusCode:503,context:{queueDepth:this.fifo.size,maxQueueDepth:this.maxQueueDepth}});this.fail(e,r),this.notify()}armQueueWaitTimer(e){if(this.queueWaitMs===void 0)return;let r=this.queueWaitMs;e.queueWaitTimer=setTimeout(()=>{if(e.settled)return;this.dequeue(e);let i=new t(`Solve waited longer than ${r}ms in queue; rejected (backpressure)`,n.QUEUE_TIMEOUT,{statusCode:503,context:{waitedMs:Date.now()-e.ctx.enqueuedAt,queueWaitMs:r}});this.fail(e,i),this.notify()},r)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case`latest-wins`:this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break;case`queue`:this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifo.size>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifo.push(e))}this.notify()}async execute(e){let t=new AbortController,n=e;n.controller=t,this.inFlight.add(n),e.ctx.startedAt=Date.now(),this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e);let r=()=>t.abort();e.externalSignal?.addEventListener(`abort`,r,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let i=performance.now();try{let n={...this.baseConfig,signal:t.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry},...e.selvaevents!==void 0&&{selvaevents:e.selvaevents}},r=e.onServerTiming;if(r){let e=this.baseConfig.onServerTiming;n.onServerTiming=(t,n)=>{try{e?.(t,n)}finally{r(t,n)}}}let{response:a,definitionReuploaded:o}=await this.runExecutor(e,n),s=performance.now()-i;if(this.writeCache(e.ctx.key,a),!this.settleSuccess(e,{response:a,fromCache:!1,definitionReuploaded:o,durationMs:s}))return;this.writeLastState(e.seq,{result:a,durationMs:s}),this.runHook(this.onSettle,e.ctx,{status:`success`,response:a,durationMs:s,fromCache:!1,definitionReuploaded:o})}catch(t){let r=performance.now()-i,a=this.normalizeExecutionError(t,n);this.writeLastState(e.seq,{error:a,durationMs:r}),this.fail(e,a,r)}finally{e.externalSignal?.removeEventListener(`abort`,r),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,t){let{definition:n,dataTree:r}=e;if(!this.reuseServerDefinitionCache||o(n)){let{response:e}=await this.executor(n,r,null,t);return{response:e}}let i=e.hashes.definitionHash,a=this.serverCacheKeys.get(i)??null,s=await this.executor(n,r,a,t);return this.serverCacheKeys.delete(i),s.cacheKey&&(this.serverCacheKeys.set(i,s.cacheKey),this.serverCacheKeys.size>100&&this.serverCacheKeys.delete(this.serverCacheKeys.keys().next().value)),{response:s.response,definitionReuploaded:s.missed}}hashDefinitionMemo(e){return typeof e==`string`?(this.lastStringDefinition?.value!==e&&(this.lastStringDefinition={value:e,hash:G(e)}),this.lastStringDefinition.hash):Re(e)}drainNext(){if(!this.disposed){if(this.mode===`latest-wins`){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}}else for(;this.fifo.size>0&&this.inFlight.size<this.maxConcurrent;)this.execute(this.fifo.shift())}}supersede(e){let r=new t(`Superseded by newer solve`,n.SUPERSEDED,{context:{enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new t(`Request aborted by caller`,n.ABORTED,{context:{enqueuedAt:e.enqueuedAt}})}settleError(e,t){return!e.settled&&(e.settled={error:t},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(t),!0)}fail(e,t,n=0){this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:n})}settleSuccess(e,t){return!e.settled&&(e.settled={ok:!0},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.resolve(t),!0)}removeQueuedAbortHandler(e){e.queuedAbortHandler&&e.externalSignal&&e.externalSignal.removeEventListener(`abort`,e.queuedAbortHandler),e.queuedAbortHandler=void 0}normalizeExecutionError(e,r){return r.settled&&`error`in r.settled?r.settled.error:e instanceof t?e:e instanceof Error&&e.name===`AbortError`?this.makeAbortError(r.ctx):new t(e instanceof Error?e.message:String(e),n.UNKNOWN_ERROR,{originalError:e})}cancelAll(){this.pendingForLatestWins&&=(this.fail(this.pendingForLatestWins,this.makeAbortError(this.pendingForLatestWins.ctx)),null);for(let e=this.fifo.shift();e;e=this.fifo.shift())this.fail(e,this.makeAbortError(e.ctx));for(let e of this.inFlight){let t=e.ctx.startedAt?Date.now()-e.ctx.startedAt:0;this.fail(e,this.makeAbortError(e.ctx),t),e.controller.abort()}this.notify()}readCache(e){if(!this.cacheEnabled)return null;let t=this.cache.get(e);return t?this.cacheTtl>0&&Date.now()-t.insertedAt>this.cacheTtl?(this.dropCacheEntry(e),this.cacheMisses+=1,null):(this.cache.delete(e),this.cache.set(e,t),this.cacheHits+=1,t.response):(this.cacheMisses+=1,null)}writeCache(t,n){if(!this.cacheEnabled)return;let r=e(n,`errors`);if(!this.cacheErroredSolves&&Array.isArray(r)&&r.length>0)return;let i=c(n)??Ve(n);if(!(i>this.cacheMaxBytes))for(this.dropCacheEntry(t),this.cache.set(t,{response:n,insertedAt:Date.now(),sizeBytes:i}),this.cacheBytes+=i;this.cacheBytes>this.cacheMaxBytes&&this.cache.size>0;){let e=this.cache.keys().next().value;if(e===void 0)break;this.dropCacheEntry(e),this.cacheEvictions+=1}}dropCacheEntry(e){let t=this.cache.get(e);t&&(this.cache.delete(e),this.cacheBytes-=t.sizeBytes)}clearCache(){this.cache.clear(),this.cacheBytes=0}cacheStats(){return{entries:this.cache.size,bytes:this.cacheBytes,hits:this.cacheHits,misses:this.cacheMisses,evictions:this.cacheEvictions}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(e,...t){if(e)try{e(...t)}catch(e){i().error(`[SolveScheduler] hook threw:`,e)}}};function Ue(e){return m(e)?`ref:${e.key}`:typeof e==`string`&&e.length<200?e:`...content...`}function We(t){return Array.isArray(t)?t.map(t=>{let n=0,r=0,i=e(t,`innerTree`);if(i&&typeof i==`object`){for(let e of Object.values(i))if(Array.isArray(e)){n+=e.length;for(let t of e){let e=t?.data;typeof e==`string`&&(r+=e.length)}}}return{param:e(t,`paramName`)??`<unnamed>`,items:n,bytes:r}}):[]}var Ge=class r{config;serverStats;disposed=!1;static CREATE_PROBE_TIMEOUT_MS=2e3;constructor(e){this.config={...e,serverUrl:h(e.serverUrl),debug:e.debug??!1},this.serverStats=new g(this.config.serverUrl,this.config)}static async create(e,i={}){let a=new r(e),o=Math.max(1,(i.probe?.attempts??2)+1),s=i.probe?.baseDelayMs??250,c=i.probe?.maxDelayMs??1e3,l,u=null,d=0;for(let e=0;e<o;e++){if(d=e+1,l=await a.serverStats.probeServer(r.CREATE_PROBE_TIMEOUT_MS),l.online)return a;if(u=te(l),u&&!u.retryable)break;if(e<o-1){let t=Math.min(s*2**e,c);await new Promise(e=>setTimeout(e,t))}}await a.dispose();let f=l?.status,p=u?`Rhino Compute server is not available. ${u.summary}`:`Rhino Compute server is not online`;throw new t(p,n.NETWORK_ERROR,{...f!==void 0&&{statusCode:f},context:{serverUrl:a.config.serverUrl,attempts:d,maxAttempts:o,...u&&{probeVerdict:u.verdict,probeRetryable:u.retryable},...f!==void 0&&{lastProbeStatus:f},...l?.error!==void 0&&{lastProbeError:l.error}}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),B(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),R(e,this.config)}async solve(r,a,o){this.ensureNotDisposed();try{if(typeof r==`string`&&!r.trim())throw new t(`Definition URL/content is required`,n.INVALID_INPUT,{context:{receivedUrl:r}});if(r instanceof Uint8Array&&r.length===0)throw new t(`Definition content is empty`,n.INVALID_INPUT);if(m(r)&&!r.key.trim())throw new t(`DefinitionRef key is empty`,n.INVALID_INPUT);let i=await le(a,r,{...this.config,...o?.signal!==void 0&&{signal:o.signal},...o?.timeoutMs!==void 0&&{timeoutMs:o.timeoutMs},...o?.retry!==void 0&&{retry:o.retry},...o?.selvaevents!==void 0&&{selvaevents:o.selvaevents}}),s=e(i,`errors`);if(Array.isArray(s)&&s.length>0)throw new t(s.map(String).join(`; `)||`Computation failed`,n.COMPUTATION_ERROR,{context:{definition:Ue(r),inputSummary:We(a),errors:s,warnings:e(i,`warnings`),values:i.values}});return i}catch(e){throw this.config.debug&&i().error(`Compute failed:`,e),e instanceof t?e:new t(e instanceof Error?e.message:String(e),n.COMPUTATION_ERROR,{context:{definition:Ue(r),inputSummary:We(a)},originalError:e})}}createScheduler(e){return this.ensureNotDisposed(),new He((e,t,n,r)=>ue(t,n,e,r),this.config,e)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new t(`GrasshopperClient has been disposed and cannot be used`,n.INVALID_STATE)}};function Ke(e){return typeof e==`object`&&!!e&&e.__decodeError===!0}function qe(e,t){return{__decodeError:!0,type:e,raw:t}}function Je(e){let t=/* @__PURE__ */ new WeakSet,n=e=>{if(!e||typeof e!=`object`||t.has(e))return;t.add(e);let r=e.delete;if(typeof r==`function`){let t=e.isDeleted;typeof t==`function`&&t.call(e)||r.call(e);return}if(Array.isArray(e)){for(let t of e)n(t);return}let i=Object.getPrototypeOf(e);if(i===Object.prototype||i===null)for(let t of Object.values(e))n(t)};n(e)}const q=/* @__PURE__ */ new Map([[`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}],[`Rhino.Geometry.Line`,(e,t)=>{let n=t;return!n||!n.From||!n.To?null:new e.Line([n.From.X,n.From.Y,n.From.Z],[n.To.X,n.To.Y,n.To.Z])}]]);function Ye(e){if(q.has(e))return q.get(e);for(let[t,n]of q)if(e.startsWith(t))return n}function Xe(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function Ze(e,t,n){let r=Ye(t),a=!1;if(r)try{let t=r(n,e);if(t!=null)return t}catch(e){i().warn(`Failed to decode Rhino type ${t}:`,e),a=!0}try{if(Xe(e))return n.CommonObject.decode(e)}catch(n){return i().warn(`Failed to decode ${t} with CommonObject:`,n),qe(t,e)}return a?qe(t,e):e}const J={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},Qe=`FileData`;function $e(e,t){return e.includes(`WebDisplay`)||t&&e!==J.STRING}function et(e){if(typeof e!=`string`)return e;let t=e.trim();if(!(t.startsWith(`{`)||t.startsWith(`[`)||t.startsWith(`"`)))return e;try{let e=JSON.parse(t);if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}catch{return e}}function tt(e,t,n){switch(t){case J.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case J.INT:return Number.parseInt(String(e),10);case J.DOUBLE:return Number.parseFloat(String(e));case J.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?Ze(e,t,n):e}}function Y(e,t,n,r){if(typeof e.data!=`string`)return e.data;let i=n?et(e.data):e.data;return n&&t.includes(Qe)?nt(i)??i:tt(i,t,r)}function nt(t){if(!t||typeof t!=`object`)return null;let n=e(t,`fileName`),i=e(t,`fileType`),a=e(t,`subFolder`),o=e(t,`isBase64Encoded`);if(typeof n!=`string`||typeof i!=`string`||typeof a!=`string`||!r(t,`data`)||typeof o!=`boolean`&&typeof o!=`string`)return null;let s=e(t,`metadata`);return{fileName:n,fileType:i,data:e(t,`data`),isBase64Encoded:u(o),subFolder:a,...s?{metadata:s}:{}}}function X(t){let n=e(t,`values`);return Array.isArray(n)?n:[]}function Z(e){return typeof e.type==`string`?e.type:``}function Q(e,t){if(e&&typeof e==`object`){for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)e&&typeof e==`object`&&t(e)}}function rt(t,n=!1,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r,s={},c=/* @__PURE__ */ new Set;for(let r of X(t)){let t=e(r,`paramName`);Q(e(r,`innerTree`),e=>{let r=Z(e);if($e(r,o))return;let l=n?e.id:t;if(!l)return;let u=Y(e,r,i,a);Object.prototype.hasOwnProperty.call(s,l)?c.has(l)?s[l].push(u):(s[l]=[s[l],u],c.add(l)):x(s,l,u)})}return{values:s,dispose:()=>Je(s)}}function it(t){let n=[];for(let r of X(t))Q(e(r,`innerTree`),e=>{if(!Z(e).includes(Qe))return;let t=nt(et(e.data));t&&n.push(t)});return n}function at(t,n,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r;for(let r of X(t)){let t=e(r,`innerTree`),s=!1;if(`byName`in n){if(e(r,`paramName`)!==n.byName)continue;s=!0}let c=[];if(Q(t,e=>{if(`byId`in n){if(e.id!==n.byId)return;s=!0}let t=Z(e);$e(t,o)||c.push(Y(e,t,i,a))}),s)return c.length===0?void 0:c.length===1?c[0]:c}}var ot=class{response;constructor(e){this.response=e}getValues(e=!1,t={}){return rt(this.response,e,t)}getValue(e,t){return at(this.response,e,t)}async getAndDownloadFiles(e,t){await ee(it(this.response),e,t)}};function st(t){return(Array.isArray(t)?t:[t]).map(t=>({schemas:e(t,`schemas`),error:e(t,`error`)}))}const ct=/* @__PURE__ */ new Set([`options`,`defaultOptions`,`values`]),lt=/* @__PURE__ */ new Set([`optionMedia`,`assets`]),ut=e=>e>=`A`&&e<=`Z`;function dt(e){if(e.length===0||!ut(e[0]))return e;let t=0;for(;t<e.length&&ut(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function ft(e){return $(e)}function $(e){if(Array.isArray(e))return e.map($);if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e)){let e=dt(n);x(t,e,ct.has(e)?r:lt.has(e)?pt(r):$(r))}return t}function pt(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t={};for(let[n,r]of Object.entries(e))x(t,n,$(r));return t}var mt=class r{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(e,t){let n=this.innerTree[r.formatPathString(e)]??=[];for(let e of t)n.push({data:r.serializeValue(e)});return this}fromDataTreeDefault(e){this.innerTree={};for(let[t,n]of Object.entries(e)){if(!Array.isArray(n))continue;let e=r.parsePathString(t);this.append(e,n)}return this}appendFlat(e){let t=Array.isArray(e)?e:[e];return this.append([0],t)}flatten(){let e=[];for(let t of Object.values(this.innerTree))if(Array.isArray(t))for(let n of t)e.push(r.deserializeValue(n.data));return e}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getParamName(){return this.paramName}static fromInputParams(e){return r.fromValues(e.map(e=>({paramName:e.nickname||`unnamed`,paramType:e.paramType,value:e.default,...`minimum`in e&&{minimum:e.minimum,maximum:e.maximum}})))}static fromValues(e){let t=[];for(let n of e){let e=new r(n.paramName),a=r.itemCoercer(n);for(let[t,o]of r.branchesOf(n.value)){let r=[];for(let e of o){if(e==null)continue;let t=a(e);t===null?i().warn(`${n.paramName}: dropped an item that is not a valid ${n.paramType}`):r.push(t)}r.length>0&&e.append(t,r)}Object.keys(e.innerTree).length>0&&t.push(e.toComputeFormat())}return t}static branchesOf(e){return r.hasValidValue(e)?C(e)?Object.entries(e).map(([e,t])=>[r.parsePathString(e),t]):[[[0],Array.isArray(e)?e:[e]]]:[]}static itemCoercer(e){let{paramName:t,minimum:n,maximum:i}=e,a=e.paramType.toLowerCase();return a===`number`||a===`integer`?e=>{let o=T(e);if(o===null)return null;let s=a===`integer`?Math.round(o):o;return r.clampValue(s,n,i,t)}:a===`boolean`?E:e=>e}static replaceTreeValue(e,t,n){let i=r.buildFromValue(t,n).toComputeFormat(),a=e.slice(),o=a.findIndex(e=>r.paramNameOf(e)===t);return o===-1?a.push(i):a[o]=i,a}static buildFromValue(e,t){let n=new r(e);return C(t)?n.fromDataTreeDefault(t):n.appendFlat(t),n}static getTree(t,n){let i=t.find(e=>r.paramNameOf(e)===n);if(!i)return null;let a=/* @__PURE__ */ new Map,o=e(i,`InnerTree`);if(!o||typeof o!=`object`)return a;for(let[e,t]of Object.entries(o))Array.isArray(t)&&a.set(e,t.map(e=>e?.data===void 0?null:r.deserializeValue(e.data)));return a}static getTreeValue(e,i){let a=r.getTree(e,i);if(!a||a.size===0)return null;if(a.size>1)throw new t(`"${i}" has ${a.size} branches; read it with TreeBuilder.getTree`,n.INVALID_INPUT,{context:{paramName:i,branchCount:a.size}});let[o]=a.values();return o.length===0?null:o.length===1?o[0]:o}static paramNameOf(t){return e(t,`ParamName`)}static parsePathString(e){let r=e.match(S);if(!r)throw new t(`Invalid Grasshopper tree path: "${e}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`,n.INVALID_INPUT,{context:{pathStr:e}});return r[1]?r[1].split(`;`).map(Number):[]}static formatPathString(e){return`{${e.join(`;`)}}`}static serializeValue(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`?e:typeof e==`object`&&e?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e!=`string`)return e;if(e.startsWith(`{`)||e.startsWith(`[`))try{return JSON.parse(e)}catch{return e}let t=Number(e);return Number.isFinite(t)&&String(t)===e?t:e===`true`||e!==`false`&&e}static hasValidValue(e){return e==null?!1:typeof e==`string`||!(Array.isArray(e)&&e.length===0||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0)}static clampValue(e,t,n,r){let a=e;return t!=null&&a<t&&(i().warn(`${r}: ${e} below min ${t}, clamping`),a=t),n!=null&&a>n&&(i().warn(`${r}: ${e} above max ${n}, clamping`),a=n),a}};export{g as ComputeServerStats,Ge as GrasshopperClient,ot as GrasshopperResponseProcessor,He as SolveScheduler,mt as TreeBuilder,Je as disposeRhinoObjects,R as fetchDefinitionIO,B as fetchParsedDefinitionIO,G as hashDefinition,Le as hashSolveInput,Ke as isRhinoDecodeError,ft as normalizeUISchemaCasing,ke as processInput,st as readSchemaResults,le as solveGrasshopperDefinition,U as stableStringify};
|
|
2
2
|
//# sourceMappingURL=grasshopper.js.map
|