@timefoldai/viz-platform 0.0.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -1
- package/dist/analytics/use-analytics-bridge.d.mts +6 -0
- package/dist/analytics/use-analytics-bridge.mjs +21 -0
- package/dist/assignability/assignability.d.mts +97 -0
- package/dist/assignability/assignability.mjs +51 -0
- package/dist/assignability/use-assignability.d.mts +32 -0
- package/dist/assignability/use-assignability.mjs +151 -0
- package/dist/config/credential-channel.d.mts +13 -0
- package/dist/config/credential-channel.mjs +33 -0
- package/dist/config/embedding-params.d.mts +30 -0
- package/dist/config/embedding-params.mjs +54 -0
- package/dist/config/security.d.mts +36 -0
- package/dist/config/security.mjs +64 -0
- package/dist/dataset-context/DataSetContext.d.mts +215 -0
- package/dist/dataset-context/DataSetContext.mjs +170 -0
- package/dist/dataset-context/DataSetContextProvider.d.mts +19 -0
- package/dist/dataset-context/DataSetContextProvider.mjs +627 -0
- package/dist/dataset-context/DataSetLoader.d.mts +68 -0
- package/dist/dataset-context/DataSetLoader.mjs +130 -0
- package/dist/dataset-context/data-set-key.d.mts +2 -0
- package/dist/dataset-context/data-set-key.mjs +14 -0
- package/dist/dataset-context/model-api-url.d.mts +13 -0
- package/dist/dataset-context/model-api-url.mjs +27 -0
- package/dist/dataset-context/use-data-set-load-state.d.mts +26 -0
- package/dist/dataset-context/use-data-set-load-state.mjs +29 -0
- package/dist/dataset-context/use-fetch-dataset-resource.d.mts +8 -0
- package/dist/dataset-context/use-fetch-dataset-resource.mjs +20 -0
- package/dist/dataset-context/use-fetch-waypoints.d.mts +8 -0
- package/dist/dataset-context/use-fetch-waypoints.mjs +20 -0
- package/dist/dataset-context/use-run-events.d.mts +34 -0
- package/dist/dataset-context/use-run-events.mjs +138 -0
- package/dist/demo-data/use-demo-data.d.mts +42 -0
- package/dist/demo-data/use-demo-data.mjs +187 -0
- package/dist/env.d.mts +2 -0
- package/dist/env.mjs +4 -0
- package/dist/feature-flags/feature-flags.d.mts +34 -0
- package/dist/feature-flags/feature-flags.mjs +51 -0
- package/dist/feature-flags/use-feature-flag.d.mts +11 -0
- package/dist/feature-flags/use-feature-flag.mjs +17 -0
- package/dist/http/describe-response.d.mts +9 -0
- package/dist/http/describe-response.mjs +13 -0
- package/dist/http/models-api-request.d.mts +3 -0
- package/dist/http/models-api-request.mjs +20 -0
- package/dist/iframe-bridge/iframe-bridge.d.mts +10 -0
- package/dist/iframe-bridge/iframe-bridge.mjs +24 -0
- package/dist/iframe-bridge/use-iframe-bridge.d.mts +32 -0
- package/dist/iframe-bridge/use-iframe-bridge.mjs +200 -0
- package/dist/index.d.mts +16 -0
- package/dist/index.mjs +14 -0
- package/dist/solve-control/use-solve-control.d.mts +16 -0
- package/dist/solve-control/use-solve-control.mjs +46 -0
- package/dist/theme/prefers-dark.d.mts +11 -0
- package/dist/theme/prefers-dark.mjs +43 -0
- package/dist/view-channel/view-channel.d.mts +17 -0
- package/dist/view-channel/view-channel.mjs +67 -0
- package/dist/visualization-provider/VisualizationProvider.d.mts +20 -0
- package/dist/visualization-provider/VisualizationProvider.mjs +26 -0
- package/package.json +36 -5
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { describeResponse } from "../http/describe-response.mjs";
|
|
2
|
+
import { modelsApiRequest } from "../http/models-api-request.mjs";
|
|
3
|
+
import { dataSetUrl, resourceUrl, subResourceUrl } from "./model-api-url.mjs";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
// src/dataset-context/DataSetLoader.ts
|
|
6
|
+
const solvingStatusSchema = z.enum([
|
|
7
|
+
"DATASET_CREATED",
|
|
8
|
+
"DATASET_VALIDATED",
|
|
9
|
+
"DATASET_INVALID",
|
|
10
|
+
"DATASET_COMPUTED",
|
|
11
|
+
"SOLVING_SCHEDULED",
|
|
12
|
+
"SOLVING_STARTED",
|
|
13
|
+
"SOLVING_ACTIVE",
|
|
14
|
+
"SOLVING_COMPLETED",
|
|
15
|
+
"SOLVING_INCOMPLETE",
|
|
16
|
+
"SOLVING_FAILED",
|
|
17
|
+
"SOLVING_STOPPED"
|
|
18
|
+
]);
|
|
19
|
+
const validationResultSchema = z.object({ errors: z.array(z.string()).nullish() });
|
|
20
|
+
const metadataSchema = z.object({
|
|
21
|
+
name: z.string().nullish(),
|
|
22
|
+
score: z.string().nullish(),
|
|
23
|
+
solverStatus: solvingStatusSchema.nullish(),
|
|
24
|
+
validationResult: validationResultSchema.nullish()
|
|
25
|
+
});
|
|
26
|
+
const outputEnvelopeSchema = z.object({
|
|
27
|
+
metadata: metadataSchema.nullish(),
|
|
28
|
+
run: metadataSchema.nullish(),
|
|
29
|
+
modelOutput: z.unknown().optional(),
|
|
30
|
+
kpis: z.unknown().nullish()
|
|
31
|
+
});
|
|
32
|
+
/** The dataset's metadata, from whichever of the two aliases the API served. */
|
|
33
|
+
function readDataSetMetadata(envelope) {
|
|
34
|
+
return envelope.metadata ?? envelope.run ?? void 0;
|
|
35
|
+
}
|
|
36
|
+
async function fetchOutputData(config, dataSetId, apiKey, signal) {
|
|
37
|
+
return fetchModelsApiJson(resourceUrl(dataSetUrl(config), dataSetId), "output dataset", outputEnvelopeSchema, apiKey, signal);
|
|
38
|
+
}
|
|
39
|
+
const jsonObjectSchema = z.record(z.string(), z.unknown());
|
|
40
|
+
async function fetchInputData(config, dataSetId, apiKey, signal) {
|
|
41
|
+
return fetchModelsApiJson(`${resourceUrl(dataSetUrl(config), dataSetId)}/input`, "input dataset", jsonObjectSchema, apiKey, signal);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Authenticated GET of a dataset sub-resource, reusing the same
|
|
45
|
+
* origin-allowlisted host + API key as {@link fetchOutputData}.
|
|
46
|
+
*/
|
|
47
|
+
async function fetchDataSetResource(config, dataSetId, subpath, schema, apiKey, signal) {
|
|
48
|
+
return fetchModelsApiJson(subResourceUrl(dataSetUrl(config), dataSetId, subpath), subpath, schema, apiKey, signal);
|
|
49
|
+
}
|
|
50
|
+
async function fetchModelsApiJson(url, resource, schema, apiKey, signal) {
|
|
51
|
+
try {
|
|
52
|
+
return await parseModelsApiJson(await modelsApiRequest(url, apiKey, { signal }), resource, schema);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
logUnlessAborted(resource, error);
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async function parseModelsApiJson(response, resource, schema) {
|
|
59
|
+
if (!response.ok) throw new Error(`Failed to fetch ${resource}: ${describeResponse(response)}`);
|
|
60
|
+
const json = await response.json();
|
|
61
|
+
return schema.parse(json);
|
|
62
|
+
}
|
|
63
|
+
function logUnlessAborted(resource, error) {
|
|
64
|
+
if (error.name !== "AbortError") console.error(`Error fetching ${resource}:`, error);
|
|
65
|
+
}
|
|
66
|
+
const waypointsEntrySchema = z.object({
|
|
67
|
+
id: z.string().nullish(),
|
|
68
|
+
waypoints: z.array(z.array(z.number())).nullish()
|
|
69
|
+
});
|
|
70
|
+
const waypointsSchema = z.union([z.array(waypointsEntrySchema), waypointsEntrySchema.transform((entry) => [entry])]);
|
|
71
|
+
/**
|
|
72
|
+
* Fetches the computed road-geometry waypoints for a run — the polylines the map draws instead of straight lines.
|
|
73
|
+
* Resolves empty on a 404, which the Models API answers for every run without a stored solution.
|
|
74
|
+
*/
|
|
75
|
+
async function fetchWaypoints(config, dataSetId, apiKey, signal) {
|
|
76
|
+
try {
|
|
77
|
+
const response = await modelsApiRequest(subResourceUrl(dataSetUrl(config), dataSetId, "waypoints"), apiKey, { signal });
|
|
78
|
+
if (response.status === 404) {
|
|
79
|
+
await response.text();
|
|
80
|
+
return [];
|
|
81
|
+
}
|
|
82
|
+
return await parseModelsApiJson(response, "waypoints", waypointsSchema);
|
|
83
|
+
} catch (error) {
|
|
84
|
+
logUnlessAborted("waypoints", error);
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const scheduleResponseSchema = z.object({
|
|
89
|
+
id: z.string().nullish(),
|
|
90
|
+
solverStatus: solvingStatusSchema.nullish(),
|
|
91
|
+
validationResult: validationResultSchema.nullish()
|
|
92
|
+
});
|
|
93
|
+
/**
|
|
94
|
+
* @param inputData - `null` before any dataset has been loaded/imported is a
|
|
95
|
+
* legitimate value here, not a type escape hatch — the caller doesn't guard
|
|
96
|
+
* against it.
|
|
97
|
+
*/
|
|
98
|
+
function scheduleDataset(config, inputData, apiKey) {
|
|
99
|
+
return postSolveRequest(dataSetUrl(config), apiKey, JSON.stringify(inputData));
|
|
100
|
+
}
|
|
101
|
+
const runMetadataSchema = z.object({
|
|
102
|
+
solverStatus: solvingStatusSchema.nullish(),
|
|
103
|
+
tags: z.array(z.string()).nullish()
|
|
104
|
+
});
|
|
105
|
+
const FROM_PATCH_TAG = "system.type:from-patch";
|
|
106
|
+
/**
|
|
107
|
+
* Starts a solve the way the platform's run actions do: without a run it creates one from `activeDataSet`,
|
|
108
|
+
* a computed run is solved in place, and any other run is re-run from its input as a child run.
|
|
109
|
+
*/
|
|
110
|
+
async function requestSolve(config, dataSetId, activeDataSet, apiKey) {
|
|
111
|
+
if (!dataSetId) return scheduleDataset(config, activeDataSet, apiKey);
|
|
112
|
+
const run = await fetchDataSetResource(config, dataSetId, "metadata", runMetadataSchema, apiKey);
|
|
113
|
+
const runUrl = resourceUrl(dataSetUrl(config), dataSetId);
|
|
114
|
+
if (run.solverStatus === "DATASET_COMPUTED") return postSolveRequest(runUrl, apiKey);
|
|
115
|
+
return postSolveRequest(`${runUrl}/from-input?operation=SOLVE&select=${run.tags?.includes(FROM_PATCH_TAG) ? "SOLVED" : "UNSOLVED"}`, apiKey);
|
|
116
|
+
}
|
|
117
|
+
async function postSolveRequest(url, apiKey, body) {
|
|
118
|
+
const response = await modelsApiRequest(url, apiKey, {
|
|
119
|
+
method: "POST",
|
|
120
|
+
body
|
|
121
|
+
});
|
|
122
|
+
if (!response.ok) throw new Error(`Failed to schedule dataset: ${describeResponse(response)}`);
|
|
123
|
+
const json = await response.json();
|
|
124
|
+
return scheduleResponseSchema.parse(json);
|
|
125
|
+
}
|
|
126
|
+
/** Stops (terminates) an in-flight solve. Returns false on any non-OK response. */
|
|
127
|
+
async function stopSolvingDataset(config, id, apiKey) {
|
|
128
|
+
return (await modelsApiRequest(resourceUrl(dataSetUrl(config), id), apiKey, { method: "DELETE" })).ok;
|
|
129
|
+
}
|
|
130
|
+
export { fetchDataSetResource, fetchInputData, fetchOutputData, fetchWaypoints, readDataSetMetadata, requestSolve, stopSolvingDataset };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// src/dataset-context/data-set-key.ts
|
|
2
|
+
const keys = /* @__PURE__ */ new WeakMap();
|
|
3
|
+
let keyCount = 0;
|
|
4
|
+
/** A key that changes when a new dataset loads and holds while a solve updates it; pass the context's `inputData`. */
|
|
5
|
+
function dataSetKey(inputData) {
|
|
6
|
+
if (!inputData) return "";
|
|
7
|
+
const known = keys.get(inputData);
|
|
8
|
+
if (known !== void 0) return known;
|
|
9
|
+
keyCount += 1;
|
|
10
|
+
const key = String(keyCount);
|
|
11
|
+
keys.set(inputData, key);
|
|
12
|
+
return key;
|
|
13
|
+
}
|
|
14
|
+
export { dataSetKey };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { VisualizationConfig } from "./DataSetContext.mjs";
|
|
2
|
+
type ModelApiConfig = Pick<VisualizationConfig<unknown, unknown>, "host" | "apiVersion" | "dataSetPath" | "demoDataSetPath">;
|
|
3
|
+
export declare function dataSetUrl(config: ModelApiConfig): string;
|
|
4
|
+
export declare function demoDataSetUrl(config: ModelApiConfig): string;
|
|
5
|
+
/** Checks a run id from the query or the init message: a dot segment or an ill-formed string loads no run. */
|
|
6
|
+
export declare function resolveRunId(runId: string | undefined): {
|
|
7
|
+
runId?: string;
|
|
8
|
+
embeddingError?: string;
|
|
9
|
+
};
|
|
10
|
+
export declare function resourceUrl(collectionUrl: string, id: string): string;
|
|
11
|
+
/** Appends a dataset sub-resource path, rejecting a `.`/`..` segment in the page-supplied subpath (invariant 7). */
|
|
12
|
+
export declare function subResourceUrl(collectionUrl: string, id: string, subpath: string): string;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// src/dataset-context/model-api-url.ts
|
|
2
|
+
function versionedHost(config) {
|
|
3
|
+
return config.apiVersion === void 0 ? `${config.host}` : `${config.host}/${config.apiVersion}`;
|
|
4
|
+
}
|
|
5
|
+
function dataSetUrl(config) {
|
|
6
|
+
return `${versionedHost(config)}${config.dataSetPath}`;
|
|
7
|
+
}
|
|
8
|
+
function demoDataSetUrl(config) {
|
|
9
|
+
return `${versionedHost(config)}${config.demoDataSetPath}`;
|
|
10
|
+
}
|
|
11
|
+
const DOT_SEGMENT = /^\.{1,2}$/;
|
|
12
|
+
/** Checks a run id from the query or the init message: a dot segment or an ill-formed string loads no run. */
|
|
13
|
+
function resolveRunId(runId) {
|
|
14
|
+
if (runId !== void 0 && (DOT_SEGMENT.test(runId) || !runId.isWellFormed())) return { embeddingError: `The dataset ID "${runId}" is not valid, so no dataset loads.` };
|
|
15
|
+
return { runId };
|
|
16
|
+
}
|
|
17
|
+
function resourceUrl(collectionUrl, id) {
|
|
18
|
+
if (DOT_SEGMENT.test(id)) throw new Error(`"${id}" is not a valid dataset id.`);
|
|
19
|
+
return `${collectionUrl}/${encodeURIComponent(id)}`;
|
|
20
|
+
}
|
|
21
|
+
/** Appends a dataset sub-resource path, rejecting a `.`/`..` segment in the page-supplied subpath (invariant 7). */
|
|
22
|
+
function subResourceUrl(collectionUrl, id, subpath) {
|
|
23
|
+
const [path = ""] = subpath.split(/[?#]/);
|
|
24
|
+
for (const segment of path.split("/")) if (DOT_SEGMENT.test(segment)) throw new Error(`"${subpath}" is not a valid dataset subpath.`);
|
|
25
|
+
return `${resourceUrl(collectionUrl, id)}/${subpath}`;
|
|
26
|
+
}
|
|
27
|
+
export { dataSetUrl, demoDataSetUrl, resolveRunId, resourceUrl, subResourceUrl };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { DemoDataError } from "../demo-data/use-demo-data.mjs";
|
|
2
|
+
/** Options for {@link useDataSetLoadState}. */
|
|
3
|
+
export interface UseDataSetLoadStateOptions {
|
|
4
|
+
importError?: DemoDataError | null;
|
|
5
|
+
}
|
|
6
|
+
/** The load and solve state of the dataset that {@link useDataSetLoadState} returns. */
|
|
7
|
+
export interface DataSetLoadState {
|
|
8
|
+
dataError: string | null;
|
|
9
|
+
loadError: string | null;
|
|
10
|
+
embeddingError: string | null;
|
|
11
|
+
isSolving: boolean;
|
|
12
|
+
isAwaitingSolution: boolean;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Derives the terminal data error and the awaiting-solution flag that an app's
|
|
16
|
+
* data gates need, from the dataset context's own status.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```tsx
|
|
20
|
+
* const demo = useDemoData({ enabled: !data.isOnPlatform });
|
|
21
|
+
* const { dataError, isAwaitingSolution } = useDataSetLoadState({
|
|
22
|
+
* importError: demo.importError,
|
|
23
|
+
* });
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export declare function useDataSetLoadState(options?: UseDataSetLoadStateOptions): DataSetLoadState;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { isSolveAtWork, useDataSetProviderState } from "./DataSetContext.mjs";
|
|
3
|
+
// src/dataset-context/use-data-set-load-state.ts
|
|
4
|
+
/**
|
|
5
|
+
* Derives the terminal data error and the awaiting-solution flag that an app's
|
|
6
|
+
* data gates need, from the dataset context's own status.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```tsx
|
|
10
|
+
* const demo = useDemoData({ enabled: !data.isOnPlatform });
|
|
11
|
+
* const { dataError, isAwaitingSolution } = useDataSetLoadState({
|
|
12
|
+
* importError: demo.importError,
|
|
13
|
+
* });
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
function useDataSetLoadState(options = {}) {
|
|
17
|
+
const importError = options.importError ?? null;
|
|
18
|
+
const { status, inAppSolveActive, outputData, embeddingError } = useDataSetProviderState();
|
|
19
|
+
const loadError = status.phase === "error" ? status.error : null;
|
|
20
|
+
const isSolving = isSolveAtWork(status, inAppSolveActive);
|
|
21
|
+
return {
|
|
22
|
+
dataError: loadError ?? importError?.message ?? null,
|
|
23
|
+
loadError,
|
|
24
|
+
embeddingError: embeddingError ?? null,
|
|
25
|
+
isSolving,
|
|
26
|
+
isAwaitingSolution: isSolving && outputData === void 0
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export { useDataSetLoadState };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* A function that runs an authenticated GET of a dataset sub-resource (such as `score-analysis`) with the provider's
|
|
4
|
+
* API key, through the library's origin-gated, redirect-refusing request. With no run loaded, the call rejects.
|
|
5
|
+
*
|
|
6
|
+
* @category Hooks
|
|
7
|
+
*/
|
|
8
|
+
export declare function useFetchDataSetResource(): <T>(subpath: string, schema: z.ZodType<T>, signal?: AbortSignal) => Promise<T>;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useDataSetProviderState } from "./DataSetContext.mjs";
|
|
3
|
+
import { fetchDataSetResource } from "./DataSetLoader.mjs";
|
|
4
|
+
import { useCallback } from "react";
|
|
5
|
+
// src/dataset-context/use-fetch-dataset-resource.ts
|
|
6
|
+
/**
|
|
7
|
+
* A function that runs an authenticated GET of a dataset sub-resource (such as `score-analysis`) with the provider's
|
|
8
|
+
* API key, through the library's origin-gated, redirect-refusing request. With no run loaded, the call rejects.
|
|
9
|
+
*
|
|
10
|
+
* @category Hooks
|
|
11
|
+
*/
|
|
12
|
+
function useFetchDataSetResource() {
|
|
13
|
+
const { config, dataSetId, apiKey } = useDataSetProviderState();
|
|
14
|
+
return useCallback((subpath, schema, signal) => dataSetId ? fetchDataSetResource(config, dataSetId, subpath, schema, apiKey, signal) : Promise.reject(/* @__PURE__ */ new Error("No run is loaded, so it has no sub-resources.")), [
|
|
15
|
+
config,
|
|
16
|
+
dataSetId,
|
|
17
|
+
apiKey
|
|
18
|
+
]);
|
|
19
|
+
}
|
|
20
|
+
export { useFetchDataSetResource };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Waypoints } from "./DataSetLoader.mjs";
|
|
2
|
+
/**
|
|
3
|
+
* A function that fetches the road-geometry waypoints of the loaded run with the provider's API key. Its identity
|
|
4
|
+
* changes only with the run, the API host, the API version or the key. With no run loaded, the call rejects.
|
|
5
|
+
*
|
|
6
|
+
* @category Hooks
|
|
7
|
+
*/
|
|
8
|
+
export declare function useFetchWaypoints(): (signal?: AbortSignal) => Promise<Waypoints>;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useDataSetProviderState } from "./DataSetContext.mjs";
|
|
3
|
+
import { fetchWaypoints } from "./DataSetLoader.mjs";
|
|
4
|
+
import { useCallback } from "react";
|
|
5
|
+
// src/dataset-context/use-fetch-waypoints.ts
|
|
6
|
+
/**
|
|
7
|
+
* A function that fetches the road-geometry waypoints of the loaded run with the provider's API key. Its identity
|
|
8
|
+
* changes only with the run, the API host, the API version or the key. With no run loaded, the call rejects.
|
|
9
|
+
*
|
|
10
|
+
* @category Hooks
|
|
11
|
+
*/
|
|
12
|
+
function useFetchWaypoints() {
|
|
13
|
+
const { config, dataSetId, apiKey } = useDataSetProviderState();
|
|
14
|
+
return useCallback((signal) => dataSetId ? fetchWaypoints(config, dataSetId, apiKey, signal) : Promise.reject(/* @__PURE__ */ new Error("No run is loaded, so it has no waypoints.")), [
|
|
15
|
+
config,
|
|
16
|
+
dataSetId,
|
|
17
|
+
apiKey
|
|
18
|
+
]);
|
|
19
|
+
}
|
|
20
|
+
export { useFetchWaypoints };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Shared poll cadence for the in-app solve loop and the polling fallback below. */
|
|
2
|
+
export declare const SOLVE_POLL_INTERVAL_MS = 2000;
|
|
3
|
+
/**
|
|
4
|
+
* Stops the polling fallback after this many consecutive failed refetches —
|
|
5
|
+
* a persistent failure won't recover by retrying.
|
|
6
|
+
*/
|
|
7
|
+
export declare const MAX_CONSECUTIVE_POLL_ERRORS = 3;
|
|
8
|
+
/**
|
|
9
|
+
* Outcome `onOutput` reports back, so the polling fallback knows whether to
|
|
10
|
+
* keep going.
|
|
11
|
+
*/
|
|
12
|
+
export type RunUpdateOutcome = {
|
|
13
|
+
ok: boolean;
|
|
14
|
+
solving: boolean;
|
|
15
|
+
};
|
|
16
|
+
export type UseRunEventsOptions = {
|
|
17
|
+
dataSetUrl: string;
|
|
18
|
+
runId?: string;
|
|
19
|
+
apiKey?: string;
|
|
20
|
+
isActivelySolving: boolean;
|
|
21
|
+
runSolving: boolean;
|
|
22
|
+
onOutput: () => void | RunUpdateOutcome | Promise<void | RunUpdateOutcome>;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Live-updates a runId-loaded dataset that this app did not start solving,
|
|
26
|
+
* over SSE with a polling fallback.
|
|
27
|
+
*
|
|
28
|
+
* @category Hooks
|
|
29
|
+
*/
|
|
30
|
+
export declare function useRunEvents({ dataSetUrl, runId, apiKey, isActivelySolving, runSolving, onOutput }: UseRunEventsOptions): void;
|
|
31
|
+
/**
|
|
32
|
+
* The status and score of an SSE message body, flat or in a `{ run: {...} }` envelope; `undefined` on any other shape.
|
|
33
|
+
*/
|
|
34
|
+
export declare function extractRunProgress(raw: string): string | undefined;
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { resourceUrl } from "./model-api-url.mjs";
|
|
3
|
+
import { useEffect, useRef } from "react";
|
|
4
|
+
// src/dataset-context/use-run-events.ts
|
|
5
|
+
/** Shared poll cadence for the in-app solve loop and the polling fallback below. */
|
|
6
|
+
const SOLVE_POLL_INTERVAL_MS = 2e3;
|
|
7
|
+
/**
|
|
8
|
+
* Stops the polling fallback after this many consecutive failed refetches —
|
|
9
|
+
* a persistent failure won't recover by retrying.
|
|
10
|
+
*/
|
|
11
|
+
const MAX_CONSECUTIVE_POLL_ERRORS = 3;
|
|
12
|
+
/**
|
|
13
|
+
* Live-updates a runId-loaded dataset that this app did not start solving,
|
|
14
|
+
* over SSE with a polling fallback.
|
|
15
|
+
*
|
|
16
|
+
* @category Hooks
|
|
17
|
+
*/
|
|
18
|
+
function useRunEvents({ dataSetUrl, runId, apiKey, isActivelySolving, runSolving, onOutput }) {
|
|
19
|
+
const onOutputRef = useRef(onOutput);
|
|
20
|
+
useEffect(() => {
|
|
21
|
+
onOutputRef.current = onOutput;
|
|
22
|
+
}, [onOutput]);
|
|
23
|
+
useEffect(() => {
|
|
24
|
+
if (!runId || isActivelySolving || !runSolving) return;
|
|
25
|
+
let cancelled = false;
|
|
26
|
+
let pollTimer = null;
|
|
27
|
+
let polling = false;
|
|
28
|
+
let source = null;
|
|
29
|
+
let lastProgress;
|
|
30
|
+
let busy = false;
|
|
31
|
+
let eventFolded = false;
|
|
32
|
+
let trailingFetchOwed = false;
|
|
33
|
+
let busyTimer = null;
|
|
34
|
+
const releaseBusy = () => {
|
|
35
|
+
busy = false;
|
|
36
|
+
if (eventFolded) {
|
|
37
|
+
eventFolded = false;
|
|
38
|
+
fetchOutput({ owesTrailingFetch: true });
|
|
39
|
+
} else if (trailingFetchOwed) {
|
|
40
|
+
trailingFetchOwed = false;
|
|
41
|
+
fetchOutput({ owesTrailingFetch: false });
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
const fetchOutput = async ({ owesTrailingFetch }) => {
|
|
45
|
+
busy = true;
|
|
46
|
+
trailingFetchOwed = owesTrailingFetch;
|
|
47
|
+
try {
|
|
48
|
+
await onOutputRef.current();
|
|
49
|
+
} catch {
|
|
50
|
+
trailingFetchOwed = true;
|
|
51
|
+
}
|
|
52
|
+
if (!cancelled) busyTimer = setTimeout(releaseBusy, SOLVE_POLL_INTERVAL_MS);
|
|
53
|
+
};
|
|
54
|
+
const fetchForEvent = () => {
|
|
55
|
+
if (busy) {
|
|
56
|
+
eventFolded = true;
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
fetchOutput({ owesTrailingFetch: true });
|
|
60
|
+
};
|
|
61
|
+
const startPolling = () => {
|
|
62
|
+
if (polling) return;
|
|
63
|
+
polling = true;
|
|
64
|
+
let consecutiveErrors = 0;
|
|
65
|
+
const tick = async () => {
|
|
66
|
+
if (cancelled) return;
|
|
67
|
+
let outcome;
|
|
68
|
+
try {
|
|
69
|
+
outcome = await onOutputRef.current();
|
|
70
|
+
} catch {
|
|
71
|
+
outcome = {
|
|
72
|
+
ok: false,
|
|
73
|
+
solving: false
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
if (cancelled) return;
|
|
77
|
+
if (outcome && !outcome.ok) {
|
|
78
|
+
consecutiveErrors += 1;
|
|
79
|
+
if (consecutiveErrors >= 3) return;
|
|
80
|
+
} else {
|
|
81
|
+
consecutiveErrors = 0;
|
|
82
|
+
if (outcome && !outcome.solving) return;
|
|
83
|
+
}
|
|
84
|
+
pollTimer = setTimeout(() => void tick(), SOLVE_POLL_INTERVAL_MS);
|
|
85
|
+
};
|
|
86
|
+
pollTimer = setTimeout(() => void tick(), SOLVE_POLL_INTERVAL_MS);
|
|
87
|
+
};
|
|
88
|
+
if (!apiKey && typeof EventSource !== "undefined") {
|
|
89
|
+
source = new EventSource(`${resourceUrl(dataSetUrl, runId)}/events`);
|
|
90
|
+
source.onmessage = (event) => {
|
|
91
|
+
if (cancelled) return;
|
|
92
|
+
const progress = extractRunProgress(event.data);
|
|
93
|
+
if (progress !== void 0 && progress === lastProgress) return;
|
|
94
|
+
lastProgress = progress;
|
|
95
|
+
fetchForEvent();
|
|
96
|
+
};
|
|
97
|
+
source.onerror = () => {
|
|
98
|
+
if (cancelled) return;
|
|
99
|
+
source?.close();
|
|
100
|
+
source = null;
|
|
101
|
+
startPolling();
|
|
102
|
+
};
|
|
103
|
+
} else startPolling();
|
|
104
|
+
return () => {
|
|
105
|
+
cancelled = true;
|
|
106
|
+
source?.close();
|
|
107
|
+
if (pollTimer !== null) clearTimeout(pollTimer);
|
|
108
|
+
if (busyTimer !== null) clearTimeout(busyTimer);
|
|
109
|
+
};
|
|
110
|
+
}, [
|
|
111
|
+
dataSetUrl,
|
|
112
|
+
runId,
|
|
113
|
+
apiKey,
|
|
114
|
+
isActivelySolving,
|
|
115
|
+
runSolving
|
|
116
|
+
]);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The status and score of an SSE message body, flat or in a `{ run: {...} }` envelope; `undefined` on any other shape.
|
|
120
|
+
*/
|
|
121
|
+
function extractRunProgress(raw) {
|
|
122
|
+
const status = readRunField(raw, "solverStatus");
|
|
123
|
+
return status === void 0 ? void 0 : `${status} ${readRunField(raw, "score") ?? ""}`;
|
|
124
|
+
}
|
|
125
|
+
function readRunField(raw, field) {
|
|
126
|
+
let parsed;
|
|
127
|
+
try {
|
|
128
|
+
parsed = JSON.parse(raw);
|
|
129
|
+
} catch {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (!parsed || typeof parsed !== "object") return void 0;
|
|
133
|
+
const envelope = parsed;
|
|
134
|
+
const run = envelope.run;
|
|
135
|
+
const value = envelope[field] ?? (run && typeof run === "object" ? run[field] : void 0);
|
|
136
|
+
return typeof value === "string" ? value : void 0;
|
|
137
|
+
}
|
|
138
|
+
export { MAX_CONSECUTIVE_POLL_ERRORS, SOLVE_POLL_INTERVAL_MS, extractRunProgress, useRunEvents };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { DemoDataSetSummary } from "../dataset-context/DataSetContext.mjs";
|
|
2
|
+
/**
|
|
3
|
+
* A failed import/load attempt, reported as data so callers decide how to
|
|
4
|
+
* surface it. A fresh object per failure, so watchers see every attempt.
|
|
5
|
+
*/
|
|
6
|
+
export interface DemoDataError {
|
|
7
|
+
message: string;
|
|
8
|
+
}
|
|
9
|
+
/** Options for {@link useDemoData}. */
|
|
10
|
+
export interface UseDemoDataOptions {
|
|
11
|
+
/** @defaultValue true */
|
|
12
|
+
enabled?: boolean;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Owns the demo-data lifecycle: fetching the list, loading one by id,
|
|
16
|
+
* auto-loading on mount, and validating + applying a file import.
|
|
17
|
+
*/
|
|
18
|
+
export declare function useDemoData<InputType = unknown>({ enabled }?: UseDemoDataOptions): {
|
|
19
|
+
demoDataSets: DemoDataSetSummary[] | null;
|
|
20
|
+
label: string;
|
|
21
|
+
importError: DemoDataError | null;
|
|
22
|
+
loadDataSet: (id: string) => Promise<void>;
|
|
23
|
+
importFile: (file: File) => void;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* What the data picker calls the dataset on screen.
|
|
27
|
+
*
|
|
28
|
+
* @param isLoadingDataSet - A demo dataset is being fetched right now, so no
|
|
29
|
+
* label yet describes what the reader is about to see.
|
|
30
|
+
* @param pickedLabel - The label a demo choice or a file import wrote, which
|
|
31
|
+
* outranks the loaded dataset's own name.
|
|
32
|
+
* @param dataSetName - `undefined` while the loaded dataset's metadata is
|
|
33
|
+
* still coming, `""` once it arrived without a name.
|
|
34
|
+
*/
|
|
35
|
+
export declare function resolveDataLabel({ isLoadingDataSet, pickedLabel, dataSetId, dataSetName, demoDataSets, hasImportError }: {
|
|
36
|
+
isLoadingDataSet: boolean;
|
|
37
|
+
pickedLabel: string | null;
|
|
38
|
+
dataSetId?: string;
|
|
39
|
+
dataSetName?: string;
|
|
40
|
+
demoDataSets: DemoDataSetSummary[] | null;
|
|
41
|
+
hasImportError: boolean;
|
|
42
|
+
}): string;
|