@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
package/README.md
CHANGED
|
@@ -1,3 +1,71 @@
|
|
|
1
1
|
# @timefoldai/viz-platform
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The data layer of a Timefold model visualization: `VisualizationProvider` loads a dataset from the Models
|
|
4
|
+
API, demo data or a file, and keeps it live while the model solves.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
pnpm add @timefoldai/viz-platform react
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
The peer is React 19.
|
|
13
|
+
It supports Chrome and Edge 124, Firefox 128 and Safari 17.5 or later, and ships no polyfills.
|
|
14
|
+
You need no registry token and no `.npmrc`.
|
|
15
|
+
|
|
16
|
+
## Example
|
|
17
|
+
|
|
18
|
+
`VisualizationProvider` loads the dataset, and `useDataSet` reads it in any component below it.
|
|
19
|
+
The two paths name the dataset and demo data resources of your model on the Models API.
|
|
20
|
+
|
|
21
|
+
```tsx
|
|
22
|
+
import { useDataSet, VisualizationProvider } from "@timefoldai/viz-platform";
|
|
23
|
+
|
|
24
|
+
type Plan = { visits: { id: string }[] };
|
|
25
|
+
|
|
26
|
+
function VisitCount() {
|
|
27
|
+
const { mergedData } = useDataSet<Plan, Plan>();
|
|
28
|
+
return <p>{mergedData?.visits.length ?? 0} visits</p>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function App() {
|
|
32
|
+
return (
|
|
33
|
+
<VisualizationProvider
|
|
34
|
+
config={{ dataSetPath: "/route-plans", demoDataSetPath: "/demo-data" }}
|
|
35
|
+
>
|
|
36
|
+
<VisitCount />
|
|
37
|
+
</VisualizationProvider>
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Trusted hosts
|
|
43
|
+
|
|
44
|
+
`allowedApiHosts` in the `VisualizationProvider` config lists the hosts that receive the API key. The
|
|
45
|
+
same list names the parent pages whose messages the embed accepts. With no list (`[]`, the default), only the
|
|
46
|
+
page's own origin is trusted.
|
|
47
|
+
|
|
48
|
+
- An entry is a bare host name, with no scheme, port or path: `"api.example.com"`, not `"https://api.example.com"`.
|
|
49
|
+
The provider throws on an entry in another form, and on a one-label entry other than `localhost`, such as `"com"`.
|
|
50
|
+
- An entry also trusts its subdomains: `"example.com"` trusts `api.example.com` on any port.
|
|
51
|
+
- A listed host is trusted over `https:` only. `localhost` and `127.0.0.1` are also trusted over `http:`.
|
|
52
|
+
- The list gates the `apiUrl` query parameter. A `host` in the config is the app's own choice: the list does not
|
|
53
|
+
gate it, and it receives the API key.
|
|
54
|
+
|
|
55
|
+
```tsx
|
|
56
|
+
<VisualizationProvider config={{ ...config, allowedApiHosts: ["example.com"] }}>
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## TypeScript
|
|
60
|
+
|
|
61
|
+
The types support TypeScript 7 and later. CI type-checks the package with TypeScript 7.
|
|
62
|
+
|
|
63
|
+
## Support
|
|
64
|
+
|
|
65
|
+
- To report a security vulnerability, email security@timefold.ai. Don't post the details in public.
|
|
66
|
+
- To report a bug or to get help with this package, email support@timefold.ai.
|
|
67
|
+
|
|
68
|
+
## License
|
|
69
|
+
|
|
70
|
+
Apache License 2.0: the `LICENSE` file of this package holds the text.
|
|
71
|
+
The license grants no right to use the Timefold name, logo, or brand colors, except to describe where the package comes from.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useDataSetProviderState } from "../dataset-context/DataSetContext.mjs";
|
|
3
|
+
import { postToParent } from "../iframe-bridge/iframe-bridge.mjs";
|
|
4
|
+
import { useCallback } from "react";
|
|
5
|
+
// src/analytics/use-analytics-bridge.ts
|
|
6
|
+
/**
|
|
7
|
+
* A `track(event, properties)` that posts an `analytics` message to the embedding host while on platform.
|
|
8
|
+
*
|
|
9
|
+
* @category Hooks
|
|
10
|
+
*/
|
|
11
|
+
function useAnalyticsBridge() {
|
|
12
|
+
const { isOnPlatform } = useDataSetProviderState();
|
|
13
|
+
return useCallback((event, properties) => {
|
|
14
|
+
if (!isOnPlatform) return;
|
|
15
|
+
postToParent("analytics", {
|
|
16
|
+
event,
|
|
17
|
+
properties
|
|
18
|
+
}, window.location.origin);
|
|
19
|
+
}, [isOnPlatform]);
|
|
20
|
+
}
|
|
21
|
+
export { useAnalyticsBridge };
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { VisualizationConfig } from "../dataset-context/DataSetContext.mjs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
declare const summarySchema: z.ZodObject<{
|
|
4
|
+
entityId: z.ZodString;
|
|
5
|
+
validAssignments: z.ZodNumber;
|
|
6
|
+
totalValues: z.ZodNumber;
|
|
7
|
+
}, z.core.$strip>;
|
|
8
|
+
declare const reportSchema: z.ZodPipe<z.ZodObject<{
|
|
9
|
+
totalAnalyzed: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
10
|
+
totalUnassignable: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
11
|
+
totalAssignable: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
12
|
+
unassignable: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
|
|
13
|
+
entityId: z.ZodString;
|
|
14
|
+
validAssignments: z.ZodNumber;
|
|
15
|
+
totalValues: z.ZodNumber;
|
|
16
|
+
}, z.core.$strip>>>>;
|
|
17
|
+
assignable: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
|
|
18
|
+
entityId: z.ZodString;
|
|
19
|
+
validAssignments: z.ZodNumber;
|
|
20
|
+
totalValues: z.ZodNumber;
|
|
21
|
+
}, z.core.$strip>>>>;
|
|
22
|
+
}, z.core.$strip>, z.ZodTransform<{
|
|
23
|
+
totalAnalyzed: number | null;
|
|
24
|
+
totalUnassignable: number | null;
|
|
25
|
+
totalAssignable: number | null;
|
|
26
|
+
unassignable: {
|
|
27
|
+
entityId: string;
|
|
28
|
+
validAssignments: number;
|
|
29
|
+
totalValues: number;
|
|
30
|
+
}[];
|
|
31
|
+
assignable: {
|
|
32
|
+
entityId: string;
|
|
33
|
+
validAssignments: number;
|
|
34
|
+
totalValues: number;
|
|
35
|
+
}[];
|
|
36
|
+
}, {
|
|
37
|
+
totalAnalyzed?: number | null | undefined;
|
|
38
|
+
totalUnassignable?: number | null | undefined;
|
|
39
|
+
totalAssignable?: number | null | undefined;
|
|
40
|
+
unassignable?: {
|
|
41
|
+
entityId: string;
|
|
42
|
+
validAssignments: number;
|
|
43
|
+
totalValues: number;
|
|
44
|
+
}[] | null | undefined;
|
|
45
|
+
assignable?: {
|
|
46
|
+
entityId: string;
|
|
47
|
+
validAssignments: number;
|
|
48
|
+
totalValues: number;
|
|
49
|
+
}[] | null | undefined;
|
|
50
|
+
}>>;
|
|
51
|
+
declare const detailSchema: z.ZodPipe<z.ZodObject<{
|
|
52
|
+
shift: z.ZodString;
|
|
53
|
+
validAssignments: z.ZodNumber;
|
|
54
|
+
totalValues: z.ZodNumber;
|
|
55
|
+
assignments: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
|
|
56
|
+
value: z.ZodString;
|
|
57
|
+
assignmentFailures: z.ZodArray<z.ZodString>;
|
|
58
|
+
}, z.core.$strip>>>>;
|
|
59
|
+
}, z.core.$strip>, z.ZodTransform<{
|
|
60
|
+
assignments: {
|
|
61
|
+
value: string;
|
|
62
|
+
assignmentFailures: string[];
|
|
63
|
+
}[];
|
|
64
|
+
shift: string;
|
|
65
|
+
validAssignments: number;
|
|
66
|
+
totalValues: number;
|
|
67
|
+
}, {
|
|
68
|
+
shift: string;
|
|
69
|
+
validAssignments: number;
|
|
70
|
+
totalValues: number;
|
|
71
|
+
assignments?: {
|
|
72
|
+
value: string;
|
|
73
|
+
assignmentFailures: string[];
|
|
74
|
+
}[] | null | undefined;
|
|
75
|
+
}>>;
|
|
76
|
+
/** One analysed entity: how many values could be assigned to it, out of how many. */
|
|
77
|
+
export type AssignabilitySummary = z.infer<typeof summarySchema>;
|
|
78
|
+
/** The dataset-wide analysis: totals plus the two entity lists. */
|
|
79
|
+
export type AssignabilityReport = z.infer<typeof reportSchema>;
|
|
80
|
+
/** One value's verdict for an entity: assignable when `assignmentFailures` is empty. */
|
|
81
|
+
export type AssignmentAnalysis = AssignabilityDetail["assignments"][number];
|
|
82
|
+
/** One entity's per-value analysis. */
|
|
83
|
+
export type AssignabilityDetail = z.infer<typeof detailSchema>;
|
|
84
|
+
/**
|
|
85
|
+
* Fetches the run's assignability report
|
|
86
|
+
* (`GET {dataSetPath}/{id}/assignability-analysis`).
|
|
87
|
+
*/
|
|
88
|
+
export declare function fetchAssignabilityReport<InputType, OutputType, MergedType>(config: VisualizationConfig<InputType, OutputType, MergedType>, dataSetId: string, unassignedOnly: boolean, apiKey?: string, signal?: AbortSignal): Promise<AssignabilityReport>;
|
|
89
|
+
/**
|
|
90
|
+
* Fetches one entity's assignability detail
|
|
91
|
+
* (`GET {dataSetPath}/{id}/assignability-analysis/details/{entityId}`).
|
|
92
|
+
*
|
|
93
|
+
* @remarks
|
|
94
|
+
* `entityId` is percent-encoded, so an id with spaces or slashes keeps the path intact.
|
|
95
|
+
*/
|
|
96
|
+
export declare function fetchAssignabilityDetail<InputType, OutputType, MergedType>(config: VisualizationConfig<InputType, OutputType, MergedType>, dataSetId: string, entityId: string, apiKey?: string, signal?: AbortSignal): Promise<AssignabilityDetail>;
|
|
97
|
+
export {};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { fetchDataSetResource } from "../dataset-context/DataSetLoader.mjs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
// src/assignability/assignability.ts
|
|
4
|
+
const summarySchema = z.object({
|
|
5
|
+
entityId: z.string(),
|
|
6
|
+
validAssignments: z.number(),
|
|
7
|
+
totalValues: z.number()
|
|
8
|
+
});
|
|
9
|
+
const reportSchema = z.object({
|
|
10
|
+
totalAnalyzed: z.number().nullish(),
|
|
11
|
+
totalUnassignable: z.number().nullish(),
|
|
12
|
+
totalAssignable: z.number().nullish(),
|
|
13
|
+
unassignable: z.array(summarySchema).nullish(),
|
|
14
|
+
assignable: z.array(summarySchema).nullish()
|
|
15
|
+
}).transform((report) => ({
|
|
16
|
+
totalAnalyzed: report.totalAnalyzed ?? null,
|
|
17
|
+
totalUnassignable: report.totalUnassignable ?? null,
|
|
18
|
+
totalAssignable: report.totalAssignable ?? null,
|
|
19
|
+
unassignable: report.unassignable ?? [],
|
|
20
|
+
assignable: report.assignable ?? []
|
|
21
|
+
}));
|
|
22
|
+
const detailSchema = z.object({
|
|
23
|
+
shift: z.string(),
|
|
24
|
+
validAssignments: z.number(),
|
|
25
|
+
totalValues: z.number(),
|
|
26
|
+
assignments: z.array(z.object({
|
|
27
|
+
value: z.string(),
|
|
28
|
+
assignmentFailures: z.array(z.string())
|
|
29
|
+
})).nullish()
|
|
30
|
+
}).transform((detail) => ({
|
|
31
|
+
...detail,
|
|
32
|
+
assignments: detail.assignments ?? []
|
|
33
|
+
}));
|
|
34
|
+
/**
|
|
35
|
+
* Fetches the run's assignability report
|
|
36
|
+
* (`GET {dataSetPath}/{id}/assignability-analysis`).
|
|
37
|
+
*/
|
|
38
|
+
function fetchAssignabilityReport(config, dataSetId, unassignedOnly, apiKey, signal) {
|
|
39
|
+
return fetchDataSetResource(config, dataSetId, `assignability-analysis?unassignedOnly=${String(unassignedOnly)}`, reportSchema, apiKey, signal);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Fetches one entity's assignability detail
|
|
43
|
+
* (`GET {dataSetPath}/{id}/assignability-analysis/details/{entityId}`).
|
|
44
|
+
*
|
|
45
|
+
* @remarks
|
|
46
|
+
* `entityId` is percent-encoded, so an id with spaces or slashes keeps the path intact.
|
|
47
|
+
*/
|
|
48
|
+
function fetchAssignabilityDetail(config, dataSetId, entityId, apiKey, signal) {
|
|
49
|
+
return fetchDataSetResource(config, dataSetId, `assignability-analysis/details/${encodeURIComponent(entityId)}`, detailSchema, apiKey, signal);
|
|
50
|
+
}
|
|
51
|
+
export { fetchAssignabilityDetail, fetchAssignabilityReport };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { AssignabilityDetail, AssignabilityReport } from "./assignability.mjs";
|
|
2
|
+
/** Request parameters for {@link useAssignabilityReport}. */
|
|
3
|
+
export interface UseAssignabilityReportOptions {
|
|
4
|
+
unassignedOnly: boolean;
|
|
5
|
+
}
|
|
6
|
+
/** What {@link useAssignabilityReport} exposes to the consuming view. */
|
|
7
|
+
export interface UseAssignabilityReportResult {
|
|
8
|
+
report: AssignabilityReport | null;
|
|
9
|
+
loading: boolean;
|
|
10
|
+
error: string | null;
|
|
11
|
+
hasRun: boolean;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Loads the current run's assignability report once its input has arrived;
|
|
15
|
+
* refetches on run/option/settled-outcome change, never on raw output identity.
|
|
16
|
+
*/
|
|
17
|
+
export declare function useAssignabilityReport({ unassignedOnly }: UseAssignabilityReportOptions): UseAssignabilityReportResult;
|
|
18
|
+
/** What {@link useAssignabilityDetail} exposes to the consuming view. */
|
|
19
|
+
export interface UseAssignabilityDetailResult {
|
|
20
|
+
detail: AssignabilityDetail | null;
|
|
21
|
+
loading: boolean;
|
|
22
|
+
error: string | null;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Loads one entity's assignability detail, caching per entity id.
|
|
26
|
+
*
|
|
27
|
+
* @remarks
|
|
28
|
+
* The cache is dropped whenever the run changes, a solve starts, or a solve
|
|
29
|
+
* settles: a detail computed before a solve describes a schedule that no
|
|
30
|
+
* longer exists.
|
|
31
|
+
*/
|
|
32
|
+
export declare function useAssignabilityDetail(entityId: string | null): UseAssignabilityDetailResult;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useDataSetProviderState } from "../dataset-context/DataSetContext.mjs";
|
|
3
|
+
import { fetchAssignabilityDetail, fetchAssignabilityReport } from "./assignability.mjs";
|
|
4
|
+
import { useEffect, useRef, useState } from "react";
|
|
5
|
+
// src/assignability/use-assignability.ts
|
|
6
|
+
function useSettledToken() {
|
|
7
|
+
const { status } = useDataSetProviderState();
|
|
8
|
+
return status.phase === "solving" ? "solving" : "settled";
|
|
9
|
+
}
|
|
10
|
+
function useInputGate() {
|
|
11
|
+
const { inputData, status } = useDataSetProviderState();
|
|
12
|
+
const hasInput = inputData !== void 0;
|
|
13
|
+
return {
|
|
14
|
+
hasInput,
|
|
15
|
+
inputError: !hasInput && status.phase === "error" ? status.error : null
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Loads the current run's assignability report once its input has arrived;
|
|
20
|
+
* refetches on run/option/settled-outcome change, never on raw output identity.
|
|
21
|
+
*/
|
|
22
|
+
function useAssignabilityReport({ unassignedOnly }) {
|
|
23
|
+
const { config, dataSetId, apiKey } = useDataSetProviderState();
|
|
24
|
+
const [report, setReport] = useState(null);
|
|
25
|
+
const [loading, setLoading] = useState(false);
|
|
26
|
+
const [error, setError] = useState(null);
|
|
27
|
+
const settled = useSettledToken();
|
|
28
|
+
const { hasInput, inputError } = useInputGate();
|
|
29
|
+
useEffect(() => {
|
|
30
|
+
if (!dataSetId) {
|
|
31
|
+
setReport(null);
|
|
32
|
+
setLoading(false);
|
|
33
|
+
setError(null);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (!hasInput) {
|
|
37
|
+
setLoading(inputError === null);
|
|
38
|
+
setError(inputError);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
let cancelled = false;
|
|
42
|
+
const controller = new AbortController();
|
|
43
|
+
setLoading(true);
|
|
44
|
+
setError(null);
|
|
45
|
+
fetchAssignabilityReport(config, dataSetId, unassignedOnly, apiKey, controller.signal).then((next) => {
|
|
46
|
+
if (cancelled) return;
|
|
47
|
+
setReport(next);
|
|
48
|
+
setLoading(false);
|
|
49
|
+
}).catch((cause) => {
|
|
50
|
+
if (cancelled) return;
|
|
51
|
+
setReport(null);
|
|
52
|
+
setError(cause.message);
|
|
53
|
+
setLoading(false);
|
|
54
|
+
});
|
|
55
|
+
return () => {
|
|
56
|
+
cancelled = true;
|
|
57
|
+
controller.abort();
|
|
58
|
+
};
|
|
59
|
+
}, [
|
|
60
|
+
config,
|
|
61
|
+
dataSetId,
|
|
62
|
+
apiKey,
|
|
63
|
+
unassignedOnly,
|
|
64
|
+
settled,
|
|
65
|
+
hasInput,
|
|
66
|
+
inputError
|
|
67
|
+
]);
|
|
68
|
+
return {
|
|
69
|
+
report,
|
|
70
|
+
loading,
|
|
71
|
+
error,
|
|
72
|
+
hasRun: Boolean(dataSetId)
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Loads one entity's assignability detail, caching per entity id.
|
|
77
|
+
*
|
|
78
|
+
* @remarks
|
|
79
|
+
* The cache is dropped whenever the run changes, a solve starts, or a solve
|
|
80
|
+
* settles: a detail computed before a solve describes a schedule that no
|
|
81
|
+
* longer exists.
|
|
82
|
+
*/
|
|
83
|
+
function useAssignabilityDetail(entityId) {
|
|
84
|
+
const { config, dataSetId, apiKey } = useDataSetProviderState();
|
|
85
|
+
const settled = useSettledToken();
|
|
86
|
+
const { hasInput, inputError } = useInputGate();
|
|
87
|
+
const cache = useRef(/* @__PURE__ */ new Map());
|
|
88
|
+
const cacheKey = useRef(void 0);
|
|
89
|
+
const [detail, setDetail] = useState(null);
|
|
90
|
+
const [loading, setLoading] = useState(false);
|
|
91
|
+
const [error, setError] = useState(null);
|
|
92
|
+
useEffect(() => {
|
|
93
|
+
const nextCacheKey = `${dataSetId ?? ""}|${settled}`;
|
|
94
|
+
if (cacheKey.current !== nextCacheKey) {
|
|
95
|
+
cacheKey.current = nextCacheKey;
|
|
96
|
+
cache.current = /* @__PURE__ */ new Map();
|
|
97
|
+
}
|
|
98
|
+
if (!dataSetId || !entityId) {
|
|
99
|
+
setDetail(null);
|
|
100
|
+
setLoading(false);
|
|
101
|
+
setError(null);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (!hasInput) {
|
|
105
|
+
setDetail(null);
|
|
106
|
+
setLoading(inputError === null);
|
|
107
|
+
setError(inputError);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const cached = cache.current.get(entityId);
|
|
111
|
+
if (cached) {
|
|
112
|
+
setDetail(cached);
|
|
113
|
+
setLoading(false);
|
|
114
|
+
setError(null);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
let cancelled = false;
|
|
118
|
+
const controller = new AbortController();
|
|
119
|
+
setLoading(true);
|
|
120
|
+
setError(null);
|
|
121
|
+
fetchAssignabilityDetail(config, dataSetId, entityId, apiKey, controller.signal).then((next) => {
|
|
122
|
+
if (cancelled) return;
|
|
123
|
+
cache.current.set(entityId, next);
|
|
124
|
+
setDetail(next);
|
|
125
|
+
setLoading(false);
|
|
126
|
+
}).catch((cause) => {
|
|
127
|
+
if (cancelled) return;
|
|
128
|
+
setDetail(null);
|
|
129
|
+
setError(cause.message);
|
|
130
|
+
setLoading(false);
|
|
131
|
+
});
|
|
132
|
+
return () => {
|
|
133
|
+
cancelled = true;
|
|
134
|
+
controller.abort();
|
|
135
|
+
};
|
|
136
|
+
}, [
|
|
137
|
+
config,
|
|
138
|
+
dataSetId,
|
|
139
|
+
apiKey,
|
|
140
|
+
entityId,
|
|
141
|
+
settled,
|
|
142
|
+
hasInput,
|
|
143
|
+
inputError
|
|
144
|
+
]);
|
|
145
|
+
return {
|
|
146
|
+
detail,
|
|
147
|
+
loading,
|
|
148
|
+
error
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
export { useAssignabilityDetail, useAssignabilityReport };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export type UseCredentialChannelOptions = {
|
|
2
|
+
allowlist: readonly string[];
|
|
3
|
+
/** @defaultValue true */
|
|
4
|
+
enabled?: boolean;
|
|
5
|
+
onCredential: (apiKey: string) => void;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Listens for an inbound credential handshake from the embedding parent, and
|
|
9
|
+
* no-ops entirely when the parent never sends one.
|
|
10
|
+
*
|
|
11
|
+
* @category Hooks
|
|
12
|
+
*/
|
|
13
|
+
export declare function useCredentialChannel({ allowlist, enabled, onCredential }: UseCredentialChannelOptions): void;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { isTrustedMessageOrigin } from "../iframe-bridge/iframe-bridge.mjs";
|
|
3
|
+
import { useEffect, useRef } from "react";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
// src/config/credential-channel.ts
|
|
6
|
+
const credentialMessageSchema = z.object({
|
|
7
|
+
type: z.literal("timefold:credential"),
|
|
8
|
+
apiKey: z.string().min(1)
|
|
9
|
+
});
|
|
10
|
+
/**
|
|
11
|
+
* Listens for an inbound credential handshake from the embedding parent, and
|
|
12
|
+
* no-ops entirely when the parent never sends one.
|
|
13
|
+
*
|
|
14
|
+
* @category Hooks
|
|
15
|
+
*/
|
|
16
|
+
function useCredentialChannel({ allowlist, enabled = true, onCredential }) {
|
|
17
|
+
const onCredentialRef = useRef(onCredential);
|
|
18
|
+
useEffect(() => {
|
|
19
|
+
onCredentialRef.current = onCredential;
|
|
20
|
+
}, [onCredential]);
|
|
21
|
+
useEffect(() => {
|
|
22
|
+
if (!enabled) return;
|
|
23
|
+
function handleMessage(event) {
|
|
24
|
+
if (!isTrustedMessageOrigin(event, allowlist)) return;
|
|
25
|
+
const result = credentialMessageSchema.safeParse(event.data);
|
|
26
|
+
if (!result.success) return;
|
|
27
|
+
onCredentialRef.current(result.data.apiKey);
|
|
28
|
+
}
|
|
29
|
+
window.addEventListener("message", handleMessage);
|
|
30
|
+
return () => window.removeEventListener("message", handleMessage);
|
|
31
|
+
}, [enabled, allowlist]);
|
|
32
|
+
}
|
|
33
|
+
export { useCredentialChannel };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { DevEmbeddingParams } from "../dataset-context/DataSetContext.mjs";
|
|
2
|
+
import { DistanceUnitSystem } from "@timefoldai/viz-core";
|
|
3
|
+
export type ResolvedEmbeddingParams = {
|
|
4
|
+
apiUrl?: string;
|
|
5
|
+
apiVersion?: string;
|
|
6
|
+
runId?: string;
|
|
7
|
+
tenantId?: string;
|
|
8
|
+
featureFlags: Set<string>;
|
|
9
|
+
apiKey?: string;
|
|
10
|
+
onPlatform: boolean;
|
|
11
|
+
isDevelopment: boolean;
|
|
12
|
+
platformChrome: boolean;
|
|
13
|
+
unitSystem: DistanceUnitSystem;
|
|
14
|
+
};
|
|
15
|
+
/** Reads a host-sent unit system; anything but `"imperial"` renders metric, the default for standalone use. */
|
|
16
|
+
export declare function parseDistanceUnitSystem(raw: string | null | undefined): DistanceUnitSystem;
|
|
17
|
+
/**
|
|
18
|
+
* Resolves every embedding param as `queryParam ?? devDefaults[param]`.
|
|
19
|
+
* Query params always win; `devDefaults` applies only when `isDevBuild`.
|
|
20
|
+
*
|
|
21
|
+
* @param hostname - `window.location.hostname`, read as one half of the
|
|
22
|
+
* `isDevelopment` inference.
|
|
23
|
+
*/
|
|
24
|
+
export declare function resolveEmbeddingParams({ queryParams, devDefaults, isDevBuild, hostname, knownFlagParams }: {
|
|
25
|
+
queryParams: URLSearchParams;
|
|
26
|
+
devDefaults: DevEmbeddingParams;
|
|
27
|
+
isDevBuild: boolean;
|
|
28
|
+
hostname: string;
|
|
29
|
+
knownFlagParams?: readonly string[];
|
|
30
|
+
}): ResolvedEmbeddingParams;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { parseBooleanParam, resolveFeatureFlags } from "../feature-flags/feature-flags.mjs";
|
|
2
|
+
import "@timefoldai/viz-core";
|
|
3
|
+
// src/config/embedding-params.ts
|
|
4
|
+
function resolveStringParam(queryParams, key, fallback) {
|
|
5
|
+
const queryValue = queryParams.get(key);
|
|
6
|
+
return queryValue !== null ? queryValue : fallback;
|
|
7
|
+
}
|
|
8
|
+
function isLoopbackHost(hostname) {
|
|
9
|
+
const host = hostname.toLowerCase().replace(/^\[|]$/g, "");
|
|
10
|
+
return host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "::1";
|
|
11
|
+
}
|
|
12
|
+
/** Reads a host-sent unit system; anything but `"imperial"` renders metric, the default for standalone use. */
|
|
13
|
+
function parseDistanceUnitSystem(raw) {
|
|
14
|
+
return raw === "imperial" ? "imperial" : "metric";
|
|
15
|
+
}
|
|
16
|
+
function isOnPlatformParam(raw) {
|
|
17
|
+
return raw !== null && raw !== "0" && raw !== "false";
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Resolves every embedding param as `queryParam ?? devDefaults[param]`.
|
|
21
|
+
* Query params always win; `devDefaults` applies only when `isDevBuild`.
|
|
22
|
+
*
|
|
23
|
+
* @param hostname - `window.location.hostname`, read as one half of the
|
|
24
|
+
* `isDevelopment` inference.
|
|
25
|
+
*/
|
|
26
|
+
function resolveEmbeddingParams({ queryParams, devDefaults, isDevBuild, hostname, knownFlagParams }) {
|
|
27
|
+
const fallback = isDevBuild ? devDefaults : {};
|
|
28
|
+
const apiUrl = resolveStringParam(queryParams, "apiUrl", fallback.apiUrl);
|
|
29
|
+
const apiVersion = queryParams.get("apiVersion") ?? void 0;
|
|
30
|
+
const runId = resolveStringParam(queryParams, "runId", fallback.runId);
|
|
31
|
+
const tenantId = resolveStringParam(queryParams, "tenantId", fallback.tenantId);
|
|
32
|
+
const apiKey = resolveStringParam(queryParams, "apiKey", fallback.apiKey);
|
|
33
|
+
const onPlatform = isOnPlatformParam(queryParams.get("onPlatform"));
|
|
34
|
+
const platformChrome = parseBooleanParam(queryParams.get("platformChrome"));
|
|
35
|
+
const isDevelopment = isDevBuild || isLoopbackHost(hostname) || !onPlatform;
|
|
36
|
+
return {
|
|
37
|
+
apiUrl,
|
|
38
|
+
apiVersion,
|
|
39
|
+
runId,
|
|
40
|
+
tenantId,
|
|
41
|
+
featureFlags: resolveFeatureFlags({
|
|
42
|
+
queryParams,
|
|
43
|
+
fallbackFlags: fallback.featureFlags,
|
|
44
|
+
isDevelopment,
|
|
45
|
+
knownFlagParams
|
|
46
|
+
}),
|
|
47
|
+
apiKey,
|
|
48
|
+
onPlatform,
|
|
49
|
+
platformChrome,
|
|
50
|
+
isDevelopment,
|
|
51
|
+
unitSystem: parseDistanceUnitSystem(queryParams.get("unitSystem"))
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
export { parseDistanceUnitSystem, resolveEmbeddingParams };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** The allowlist when an app names none: only the page's own origin is trusted. */
|
|
2
|
+
export declare const SAME_ORIGIN_ONLY: readonly string[];
|
|
3
|
+
/**
|
|
4
|
+
* Checks the `allowedApiHosts` of a config once, where the provider reads it: it trims, lower-cases and drops blanks.
|
|
5
|
+
* It throws on an entry that is not a bare host name, because such an entry can never match a host.
|
|
6
|
+
*/
|
|
7
|
+
export declare function resolveAllowedApiHosts(entries?: readonly string[]): readonly string[];
|
|
8
|
+
/**
|
|
9
|
+
* True iff `origin` matches a host of `allowlist` exactly or as a dot-suffix, over `https:` only (`http:` for
|
|
10
|
+
* localhost); default-deny otherwise.
|
|
11
|
+
*/
|
|
12
|
+
export declare function isAllowedOrigin(origin: string, allowlist: readonly string[]): boolean;
|
|
13
|
+
/**
|
|
14
|
+
* Resolves the API fetch host, gating any `apiUrl` override through the allowlist. A rejected `apiUrl` keeps the
|
|
15
|
+
* page's own origin and returns `embeddingError`, so the host is never a disallowed origin (default-deny).
|
|
16
|
+
*/
|
|
17
|
+
export declare function resolveApiHost({ configHost, apiUrlParam, currentOrigin, allowlist }: {
|
|
18
|
+
configHost?: string;
|
|
19
|
+
apiUrlParam?: string | null;
|
|
20
|
+
currentOrigin: string;
|
|
21
|
+
allowlist: readonly string[];
|
|
22
|
+
}): {
|
|
23
|
+
host: string;
|
|
24
|
+
embeddingError?: string;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Resolves the Models API version: the host's when the platform catalog accepts it, else the app's own.
|
|
28
|
+
* An app without `configVersion` keeps the version in its paths; a malformed host value returns `embeddingError`.
|
|
29
|
+
*/
|
|
30
|
+
export declare function resolveApiVersion({ configVersion, hostVersion }: {
|
|
31
|
+
configVersion?: string;
|
|
32
|
+
hostVersion?: string;
|
|
33
|
+
}): {
|
|
34
|
+
apiVersion?: string;
|
|
35
|
+
embeddingError?: string;
|
|
36
|
+
};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// src/config/security.ts
|
|
2
|
+
/** The allowlist when an app names none: only the page's own origin is trusted. */
|
|
3
|
+
const SAME_ORIGIN_ONLY = [];
|
|
4
|
+
const BARE_HOST_NAME = /^(?:localhost|[a-z0-9-]+(?:\.[a-z0-9-]+)+)$/;
|
|
5
|
+
const ONE_LABEL = /^[a-z0-9-]+$/;
|
|
6
|
+
/**
|
|
7
|
+
* Checks the `allowedApiHosts` of a config once, where the provider reads it: it trims, lower-cases and drops blanks.
|
|
8
|
+
* It throws on an entry that is not a bare host name, because such an entry can never match a host.
|
|
9
|
+
*/
|
|
10
|
+
function resolveAllowedApiHosts(entries = SAME_ORIGIN_ONLY) {
|
|
11
|
+
const hosts = entries.map((entry) => entry.trim()).filter((entry) => entry !== "");
|
|
12
|
+
const invalid = hosts.find((host) => !BARE_HOST_NAME.test(host.toLowerCase()));
|
|
13
|
+
if (invalid !== void 0) throw new Error(ONE_LABEL.test(invalid.toLowerCase()) ? `allowedApiHosts: "${invalid}" has one label, so it would trust a whole top-level domain. List a host such as "api.example.com".` : `allowedApiHosts: "${invalid}" is not a host name. List a host such as "api.example.com", with no scheme, port or path.`);
|
|
14
|
+
return hosts.map((host) => host.toLowerCase());
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* True iff `origin` matches a host of `allowlist` exactly or as a dot-suffix, over `https:` only (`http:` for
|
|
18
|
+
* localhost); default-deny otherwise.
|
|
19
|
+
*/
|
|
20
|
+
function isAllowedOrigin(origin, allowlist) {
|
|
21
|
+
if (!origin || allowlist.length === 0) return false;
|
|
22
|
+
let url;
|
|
23
|
+
try {
|
|
24
|
+
url = new URL(origin);
|
|
25
|
+
} catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
const { hostname, protocol } = url;
|
|
29
|
+
if (!allowlist.some((base) => hostname === base || hostname.endsWith(`.${base}`))) return false;
|
|
30
|
+
if (protocol === "https:") return true;
|
|
31
|
+
return protocol === "http:" && (hostname === "localhost" || hostname === "127.0.0.1");
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Resolves the API fetch host, gating any `apiUrl` override through the allowlist. A rejected `apiUrl` keeps the
|
|
35
|
+
* page's own origin and returns `embeddingError`, so the host is never a disallowed origin (default-deny).
|
|
36
|
+
*/
|
|
37
|
+
function resolveApiHost({ configHost, apiUrlParam, currentOrigin, allowlist }) {
|
|
38
|
+
if (configHost) return { host: configHost };
|
|
39
|
+
const trimmed = apiUrlParam?.endsWith("/") ? apiUrlParam.slice(0, -1) : apiUrlParam;
|
|
40
|
+
if (!trimmed) return { host: currentOrigin };
|
|
41
|
+
if (URL.canParse(trimmed, currentOrigin)) {
|
|
42
|
+
const resolved = new URL(trimmed, currentOrigin);
|
|
43
|
+
if (resolved.origin === currentOrigin || isAllowedOrigin(resolved.origin, allowlist)) return { host: trimmed };
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
host: currentOrigin,
|
|
47
|
+
embeddingError: `The API URL "${apiUrlParam}" is not an allowed host. The data loads from this page's own host.`
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
const API_VERSION_PATTERN = /^(?:v[0-9]+|[0-9a-f]{1,40}|SNAPSHOT)$/;
|
|
51
|
+
/**
|
|
52
|
+
* Resolves the Models API version: the host's when the platform catalog accepts it, else the app's own.
|
|
53
|
+
* An app without `configVersion` keeps the version in its paths; a malformed host value returns `embeddingError`.
|
|
54
|
+
*/
|
|
55
|
+
function resolveApiVersion({ configVersion, hostVersion }) {
|
|
56
|
+
if (configVersion === void 0) return {};
|
|
57
|
+
if (hostVersion === void 0) return { apiVersion: configVersion };
|
|
58
|
+
if (API_VERSION_PATTERN.test(hostVersion)) return { apiVersion: hostVersion };
|
|
59
|
+
return {
|
|
60
|
+
apiVersion: configVersion,
|
|
61
|
+
embeddingError: `The API version "${hostVersion}" is not valid. Using the default API version (${configVersion}).`
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export { SAME_ORIGIN_ONLY, isAllowedOrigin, resolveAllowedApiHosts, resolveApiHost, resolveApiVersion };
|