Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/petrinaut-website/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
src/examples/generated/
styled-system
5 changes: 4 additions & 1 deletion apps/petrinaut-website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
"brunch:fixture": "node --experimental-strip-types scripts/brunch-sse-fixture.ts",
"build": "vite build",
"codegen": "node --experimental-strip-types scripts/generate-route-tree.ts",
"dev": "vite",
"dev": "yarn examples:generate && vite",
"dev:optimization": "node scripts/optimization-dev.mjs",
"examples:generate": "node --experimental-strip-types scripts/generate-example-artifacts.ts",
"fix:eslint": "oxlint --fix --type-aware --report-unused-disable-directives-severity=error .",
"generate:icons": "node scripts/generate-favicons.mjs",
"lint:eslint": "oxlint --type-aware --report-unused-disable-directives-severity=error .",
Expand Down Expand Up @@ -36,13 +37,15 @@
"zod": "4.4.3"
},
"devDependencies": {
"@fast-check/vitest": "0.4.1",
"@tanstack/router-generator": "1.167.32",
"@tanstack/router-plugin": "1.168.34",
"@types/react": "19.2.14",
"@types/react-dom": "19.2.3",
"@typescript/native-preview": "7.0.0-dev.20260511.1",
"@vitejs/plugin-react": "6.1.0",
"@whatwg-node/server": "0.10.18",
"fast-check": "4.9.0",
"oxc-transform-react": "0.145.0",
"oxlint": "1.63.0",
"oxlint-tsgolint": "0.22.1",
Expand Down
86 changes: 86 additions & 0 deletions apps/petrinaut-website/scripts/generate-example-artifacts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { readFile, mkdir, writeFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";

import {
compileScenario,
parseSDCPNFile,
type SDCPN,
} from "@hashintel/petrinaut-core";
import {
compileHirArtifacts,
lowerScenarioToHir,
type ScenarioHir,
} from "@hashintel/petrinaut-core/hir";

import {
exampleSlugs,
type ExampleSlug,
} from "../src/examples/catalog-metadata.ts";
import { normalizeExampleDefinition } from "../src/examples/normalize-example.ts";

const scriptDirectory = dirname(fileURLToPath(import.meta.url));
const examplesDirectory = resolve(scriptDirectory, "../src/examples");
const modelsDirectory = resolve(examplesDirectory, "models");
const generatedDirectory = resolve(examplesDirectory, "generated");

const parseDefinition = async (slug: ExampleSlug): Promise<SDCPN> => {
const input = JSON.parse(
await readFile(resolve(modelsDirectory, `${slug}.json`), "utf8"),
) as unknown;
const parsed = parseSDCPNFile(input);
if (!parsed.ok) {
throw new Error(`${slug}: ${parsed.error}`);
}
const { title: _title, ...rawDefinition } = parsed.sdcpn;
return normalizeExampleDefinition(slug, rawDefinition);
};

const generateRuntime = async (slug: ExampleSlug) => {
const definition = await parseDefinition(slug);
const { artifacts, failures } = compileHirArtifacts(definition);
if (failures.length > 0) {
throw new Error(
`${slug}: model HIR compilation failed:\n${failures
.map(
(failure) => `${failure.kind}:${failure.itemId}: ${failure.message}`,
)
.join("\n")}`,
);
}

const scenarioHirById: Record<string, ScenarioHir> = Object.create(
null,
) as Record<string, ScenarioHir>;
for (const scenario of definition.scenarios ?? []) {
const hir = lowerScenarioToHir({
parameterOverrides: scenario.parameterOverrides,
initialState: scenario.initialState,
});
const outcome = compileScenario(
scenario,
hir,
definition.parameters,
definition.places,
definition.types,
);
if (!outcome.ok) {
throw new Error(
`${slug}/${scenario.id}: scenario compilation failed:\n${outcome.errors
.map((error) => error.message)
.join("\n")}`,
);
}
scenarioHirById[scenario.id] = hir;
}

return `${JSON.stringify({ hirArtifacts: artifacts, scenarioHirById }, null, 2)}\n`;
};

await mkdir(generatedDirectory, { recursive: true });

for (const slug of exampleSlugs) {
const outputPath = resolve(generatedDirectory, `${slug}.json`);
await writeFile(outputPath, await generateRuntime(slug), "utf8");
process.stdout.write(`generated ${outputPath}\n`);
}
111 changes: 111 additions & 0 deletions apps/petrinaut-website/src/examples/catalog-metadata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/**
* Static example metadata shared by the browser catalog and server endpoints.
*
* Keep this module free of Petrinaut runtime imports and model loaders: Vercel
* functions that only need to validate a public URL should not bundle every
* example model and generated simulation artifact.
*/
export const exampleSlugs = [
"gases-1-pn-consumption-trigger",
"gases-1-pn",
"gases-2-spn",
"gases-3-cpn",
"gases-4-dcpn",
"semiconductor-fab-drift",
"truck-fleet-predictive-maintenance",
] as const;

export type ExampleSlug = (typeof exampleSlugs)[number];

export type ExampleSimulationParameterBounds = Readonly<{
min: number;
max: number;
step: number;
}>;

export type ExampleCatalogEntry = Readonly<{
slug: ExampleSlug;
title: string;
/** Safe UI ranges for scenario parameters, keyed by identifier. */
parameterBounds: Readonly<Record<string, ExampleSimulationParameterBounds>>;
}>;

const catalog = [
{
slug: "gases-1-pn-consumption-trigger",
title: "Gases 1 β€” Consumption Trigger",
parameterBounds: {
draw_enabled: { min: 0, max: 1, step: 1 },
},
},
{
slug: "gases-1-pn",
title: "Gases 1 β€” One Customer",
parameterBounds: {
draw_enabled: { min: 0, max: 1, step: 1 },
},
},
{
slug: "gases-2-spn",
title: "Gases 2 β€” Shared Tanker",
parameterBounds: {
draw_enabled: { min: 0, max: 1, step: 1 },
route_scale: { min: 0.5, max: 2, step: 0.1 },
},
},
{
slug: "gases-3-cpn",
title: "Gases 3 β€” Mixed Fleet",
parameterBounds: {
route_scale: { min: 0.5, max: 2, step: 0.1 },
},
},
{
slug: "gases-4-dcpn",
title: "Gases 4 β€” Dynamic Coloured Net",
parameterBounds: {
hire_enabled: { min: 0, max: 1, step: 1 },
route_scale: { min: 0.5, max: 2, step: 0.1 },
slow_draw: { min: 0, max: 0.1, step: 0.005 },
},
},
{
slug: "semiconductor-fab-drift",
title: "Semiconductor Fab Drift",
parameterBounds: {
demand_rate: { min: 0.02, max: 0.3, step: 0.01 },
maintenance_threshold: { min: 0.4, max: 0.99, step: 0.01 },
wip_cap: { min: 10, max: 100, step: 5 },
},
},
{
slug: "truck-fleet-predictive-maintenance",
title: "Truck Fleet Predictive Maintenance",
parameterBounds: {
base_severity_mean: { min: 0.5, max: 2, step: 0.05 },
base_speed_mean: { min: 0.5, max: 1.5, step: 0.05 },
bays: { min: 1, max: 4, step: 1 },
drivers: { min: 1, max: 16, step: 1 },
motorway_rate: { min: 0.01, max: 0.3, step: 0.005 },
mountain_rate: { min: 0.01, max: 0.3, step: 0.005 },
parts_lead_time: { min: 12, max: 168, step: 12 },
recovery_units: { min: 0, max: 4, step: 1 },
service_wear_limit: { min: 0.1, max: 10, step: 0.05 },
severe_route_wear_limit: { min: 0.1, max: 1, step: 0.05 },
spares: { min: 0, max: 30, step: 1 },
technicians: { min: 1, max: 8, step: 1 },
trucks: { min: 1, max: 20, step: 1 },
urban_rate: { min: 0.01, max: 0.3, step: 0.005 },
},
},
] as const satisfies readonly ExampleCatalogEntry[];

export const exampleCatalog: readonly ExampleCatalogEntry[] = catalog;

export const isExampleSlug = (value: string): value is ExampleSlug =>
exampleSlugs.some((slug) => slug === value);

export const getExampleCatalogEntry = (
slug: string,
): ExampleCatalogEntry | null =>
catalog.find((entry) => entry.slug === slug) ?? null;
57 changes: 57 additions & 0 deletions apps/petrinaut-website/src/examples/catalog.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { describe, expect, it } from "vitest";

import {
exampleCatalog,
exampleSlugs,
loadExample,
loadExampleRuntime,
} from "./catalog";

describe("example catalog", () => {
it("has a catalog entry for every slug", () => {
// isExampleSlug gates the routes on exampleSlugs while loadExample
// resolves the entry with a non-null assertion; this pins the two lists
// to each other so a slug without an entry fails here, not at render.
expect(exampleCatalog.map((entry) => entry.slug).toSorted()).toEqual(
[...exampleSlugs].toSorted(),
);
});

it.each(exampleCatalog)(
"loads $slug with bounded scenario parameters and matching generated HIR",
async (entry) => {
const [example, runtime] = await Promise.all([
loadExample(entry.slug),
loadExampleRuntime(entry.slug),
]);

expect(example.catalog).toBe(entry);

for (const scenario of example.definition.scenarios ?? []) {
expect(runtime.scenarioHirById).toHaveProperty(scenario.id);

for (const parameter of scenario.scenarioParameters) {
const bounds = entry.parameterBounds[parameter.identifier];
expect(bounds, parameter.identifier).toBeDefined();
expect(bounds!.min).toBeLessThanOrEqual(parameter.default);
expect(bounds!.max).toBeGreaterThanOrEqual(parameter.default);
expect(bounds!.step).toBeGreaterThan(0);
}
}
},
);

it("caches one model/runtime load per example", async () => {
const entry = exampleCatalog[0]!;
const [firstExample, secondExample, firstRuntime, secondRuntime] =
await Promise.all([
loadExample(entry.slug),
loadExample(entry.slug),
loadExampleRuntime(entry.slug),
loadExampleRuntime(entry.slug),
]);

expect(secondExample).toBe(firstExample);
expect(secondRuntime).toBe(firstRuntime);
});
});
112 changes: 112 additions & 0 deletions apps/petrinaut-website/src/examples/catalog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import {
parseSDCPNFile,
type HirArtifacts,
type ScenarioHir,
type SDCPN,
} from "@hashintel/petrinaut-core";

import {
getExampleCatalogEntry,
type ExampleCatalogEntry,
type ExampleSlug,
} from "./catalog-metadata";
import { normalizeExampleDefinition } from "./normalize-example";

export {
exampleCatalog,
exampleSlugs,
getExampleCatalogEntry,
isExampleSlug,
} from "./catalog-metadata";
export type {
ExampleCatalogEntry,
ExampleSimulationParameterBounds,
ExampleSlug,
} from "./catalog-metadata";

export type LoadedExample = Readonly<{
catalog: ExampleCatalogEntry;
definition: SDCPN;
}>;

export type GeneratedExampleRuntime = Readonly<{
hirArtifacts: HirArtifacts;
scenarioHirById: Readonly<Record<string, ScenarioHir>>;
}>;

const modelLoaders: Record<ExampleSlug, () => Promise<{ default: unknown }>> = {
"gases-1-pn-consumption-trigger": () =>
import("./models/gases-1-pn-consumption-trigger.json"),
"gases-1-pn": () => import("./models/gases-1-pn.json"),
"gases-2-spn": () => import("./models/gases-2-spn.json"),
"gases-3-cpn": () => import("./models/gases-3-cpn.json"),
"gases-4-dcpn": () => import("./models/gases-4-dcpn.json"),
"semiconductor-fab-drift": () =>
import("./models/semiconductor-fab-drift.json"),
"truck-fleet-predictive-maintenance": () =>
import("./models/truck-fleet-predictive-maintenance.json"),
};

const runtimeLoaders: Record<ExampleSlug, () => Promise<{ default: unknown }>> =
{
"gases-1-pn-consumption-trigger": () =>
import("./generated/gases-1-pn-consumption-trigger.json"),
"gases-1-pn": () => import("./generated/gases-1-pn.json"),
"gases-2-spn": () => import("./generated/gases-2-spn.json"),
"gases-3-cpn": () => import("./generated/gases-3-cpn.json"),
"gases-4-dcpn": () => import("./generated/gases-4-dcpn.json"),
"semiconductor-fab-drift": () =>
import("./generated/semiconductor-fab-drift.json"),
"truck-fleet-predictive-maintenance": () =>
import("./generated/truck-fleet-predictive-maintenance.json"),
};

const loadedExamples = new Map<ExampleSlug, Promise<LoadedExample>>();
const loadedRuntimes = new Map<ExampleSlug, Promise<GeneratedExampleRuntime>>();

export const loadExample = async (
slug: ExampleSlug,
): Promise<LoadedExample> => {
const existing = loadedExamples.get(slug);
if (existing) {
return existing;
}

const loaded = modelLoaders[slug]().then((module) => {
const parsed = parseSDCPNFile(module.default);
if (!parsed.ok) {
throw new Error(parsed.error);
}

const { title: _title, ...rawDefinition } = parsed.sdcpn;
return {
catalog: getExampleCatalogEntry(slug)!,
definition: normalizeExampleDefinition(slug, rawDefinition),
};
});
// A rejected import (a transient network failure, a stale chunk after a
// redeploy) must not poison the cache: evict so the next navigation retries.
loaded.catch(() => {
loadedExamples.delete(slug);
});
loadedExamples.set(slug, loaded);
return loaded;
};

export const loadExampleRuntime = async (
slug: ExampleSlug,
): Promise<GeneratedExampleRuntime> => {
const existing = loadedRuntimes.get(slug);
if (existing) {
return existing;
}

const loaded = runtimeLoaders[slug]().then(
(module) => module.default as GeneratedExampleRuntime,
);
loaded.catch(() => {
loadedRuntimes.delete(slug);
});
loadedRuntimes.set(slug, loaded);
return loaded;
Comment thread
cursor[bot] marked this conversation as resolved.
};
Loading
Loading