topotopo 0.3.0 → 0.5.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/NOTICE +40 -10
- package/README.md +475 -111
- package/dist/cli.js +328 -133
- package/dist/config.d.ts +48 -0
- package/dist/config.js +170 -0
- package/dist/core/analysis.d.ts +5 -1
- package/dist/core/analysis.js +8 -3
- package/dist/core/bake.d.ts +16 -8
- package/dist/core/bake.js +165 -29
- package/dist/core/bevel.d.ts +3 -1
- package/dist/core/bevel.js +238 -97
- package/dist/core/decimate.d.ts +65 -0
- package/dist/core/decimate.js +409 -3
- package/dist/core/erosion.d.ts +37 -0
- package/dist/core/erosion.js +41 -1
- package/dist/core/geometry.d.ts +5 -1
- package/dist/core/geometry.js +204 -4
- package/dist/core/heightfield.d.ts +27 -4
- package/dist/core/heightfield.js +54 -16
- package/dist/core/imageops.d.ts +6 -0
- package/dist/core/imageops.js +51 -0
- package/dist/core/intrinsics.d.ts +7 -0
- package/dist/core/intrinsics.js +94 -0
- package/dist/core/manifold.d.ts +12 -1
- package/dist/core/manifold.js +78 -6
- package/dist/core/materials.d.ts +11 -0
- package/dist/core/materials.js +56 -0
- package/dist/core/noise.d.ts +9 -0
- package/dist/core/noise.js +10 -1
- package/dist/core/packed.js +11 -0
- package/dist/core/particles.d.ts +1 -1
- package/dist/core/particles.js +1 -1
- package/dist/core/polymerge.d.ts +21 -0
- package/dist/core/polymerge.js +327 -0
- package/dist/core/rbd.js +13 -1
- package/dist/core/repair.d.ts +2 -0
- package/dist/core/repair.js +2 -0
- package/dist/core/report.d.ts +70 -0
- package/dist/core/report.js +275 -0
- package/dist/core/scatter.d.ts +1 -1
- package/dist/core/scatter.js +1 -1
- package/dist/core/scene.d.ts +20 -0
- package/dist/core/scene.js +72 -0
- package/dist/core/sha256.d.ts +4 -0
- package/dist/core/sha256.js +69 -0
- package/dist/core/shapes.d.ts +3 -0
- package/dist/core/shapes.js +34 -0
- package/dist/core/snippet-lib.d.ts +15 -2
- package/dist/core/snippet-lib.js +40 -14
- package/dist/core/solidify.d.ts +38 -0
- package/dist/core/solidify.js +356 -0
- package/dist/core/tangents.d.ts +54 -0
- package/dist/core/tangents.js +218 -0
- package/dist/core/texcoord.d.ts +4 -0
- package/dist/core/texcoord.js +14 -0
- package/dist/core/texnoise.d.ts +6 -1
- package/dist/core/texnoise.js +6 -2
- package/dist/core/texsdf.d.ts +131 -0
- package/dist/core/texsdf.js +637 -0
- package/dist/core/texture.d.ts +163 -9
- package/dist/core/texture.js +844 -20
- package/dist/core/topology.d.ts +32 -0
- package/dist/core/topology.js +238 -7
- package/dist/core/traceimage.d.ts +7 -0
- package/dist/core/traceimage.js +221 -0
- package/dist/core/tritri.d.ts +5 -0
- package/dist/core/tritri.js +120 -0
- package/dist/core/unwrap.d.ts +72 -0
- package/dist/core/unwrap.js +800 -0
- package/dist/core/usercode.d.ts +27 -0
- package/dist/core/usercode.js +87 -0
- package/dist/core/uv.d.ts +15 -16
- package/dist/core/uv.js +36 -189
- package/dist/core/uvislands.d.ts +62 -0
- package/dist/core/uvislands.js +574 -0
- package/dist/core/uvoverlap.d.ts +58 -0
- package/dist/core/uvoverlap.js +220 -0
- package/dist/core/uvpack.d.ts +64 -0
- package/dist/core/uvpack.js +628 -0
- package/dist/core/uvreport.d.ts +127 -0
- package/dist/core/uvreport.js +372 -0
- package/dist/core/wrangle.d.ts +6 -1
- package/dist/core/wrangle.js +27 -16
- package/dist/core/xatlas.d.ts +16 -1
- package/dist/core/xatlas.js +95 -61
- package/dist/engines.d.ts +63 -0
- package/dist/engines.js +180 -0
- package/dist/explain.d.ts +4 -3
- package/dist/explain.js +129 -12
- package/dist/graph/engine.d.ts +92 -29
- package/dist/graph/engine.js +298 -148
- package/dist/graph/expr.d.ts +6 -3
- package/dist/graph/expr.js +18 -8
- package/dist/graph/outputs.d.ts +23 -0
- package/dist/graph/outputs.js +41 -0
- package/dist/graph/packages.d.ts +72 -0
- package/dist/graph/packages.js +261 -0
- package/dist/graph/parallel.d.ts +3 -1
- package/dist/graph/parallel.js +4 -1
- package/dist/graph/params.d.ts +6 -0
- package/dist/graph/params.js +34 -7
- package/dist/graph/scope.d.ts +55 -0
- package/dist/graph/scope.js +14 -0
- package/dist/graph/types.d.ts +75 -12
- package/dist/graph/types.js +4 -2
- package/dist/graph/vars.d.ts +16 -0
- package/dist/graph/vars.js +80 -0
- package/dist/host/artifacts.d.ts +10 -1
- package/dist/host/artifacts.js +37 -6
- package/dist/host/cook.d.ts +241 -0
- package/dist/host/cook.js +844 -0
- package/dist/host/export-targets.d.ts +42 -5
- package/dist/host/export-targets.js +72 -13
- package/dist/host/godot-commands.d.ts +4 -0
- package/dist/host/godot-commands.js +21 -0
- package/dist/host/godot.d.ts +183 -0
- package/dist/host/godot.js +916 -0
- package/dist/host/node.d.ts +12 -7
- package/dist/host/node.js +27 -9
- package/dist/host/pool.js +51 -2
- package/dist/host/sidecars.d.ts +8 -0
- package/dist/host/sidecars.js +50 -0
- package/dist/host/types.d.ts +19 -6
- package/dist/host/version.d.ts +1 -0
- package/dist/host/version.js +3 -0
- package/dist/host/worker.js +5 -2
- package/dist/index.d.ts +5 -3
- package/dist/index.js +3 -2
- package/dist/inspect.d.ts +84 -1
- package/dist/inspect.js +271 -24
- package/dist/io/common.d.ts +33 -5
- package/dist/io/export.js +2 -1
- package/dist/io/files.d.ts +23 -4
- package/dist/io/files.js +60 -8
- package/dist/io/gltf.js +355 -51
- package/dist/io/heightmap.d.ts +3 -0
- package/dist/io/heightmap.js +1 -0
- package/dist/io/import.js +10 -0
- package/dist/io/inspect-scene.d.ts +55 -0
- package/dist/io/inspect-scene.js +155 -0
- package/dist/io/kinds.d.ts +81 -0
- package/dist/io/kinds.js +163 -0
- package/dist/io/points.d.ts +2 -1
- package/dist/io/points.js +3 -1
- package/dist/io/sidecars.d.ts +24 -0
- package/dist/io/sidecars.js +57 -0
- package/dist/io/source.d.ts +65 -0
- package/dist/io/source.js +112 -0
- package/dist/io/targets.d.ts +47 -3
- package/dist/io/targets.js +149 -14
- package/dist/io/textures.js +21 -1
- package/dist/io/unreal.js +5 -1
- package/dist/mcp/docs.d.ts +10 -1
- package/dist/mcp/docs.js +816 -119
- package/dist/mcp/inputs.d.ts +12 -5
- package/dist/mcp/inputs.js +50 -13
- package/dist/mcp/server.js +70 -24
- package/dist/mcp/tools.d.ts +14 -7
- package/dist/mcp/tools.js +207 -108
- package/dist/mcp/verify.d.ts +2 -2
- package/dist/mcp/verify.js +1 -1
- package/dist/mcp/workspace.d.ts +15 -0
- package/dist/mcp/workspace.js +349 -0
- package/dist/nodes/attributes.js +198 -1
- package/dist/nodes/bake.js +207 -83
- package/dist/nodes/beam.d.ts +1 -0
- package/dist/nodes/beam.js +201 -0
- package/dist/nodes/bevel.js +54 -5
- package/dist/nodes/cloth.js +2 -0
- package/dist/nodes/code.js +22 -10
- package/dist/nodes/curves.js +440 -93
- package/dist/nodes/flow.js +53 -33
- package/dist/nodes/generate.js +13 -39
- package/dist/nodes/heightfield.js +248 -77
- package/dist/nodes/imageops.d.ts +1 -0
- package/dist/nodes/imageops.js +203 -0
- package/dist/nodes/index.d.ts +4 -0
- package/dist/nodes/index.js +4 -0
- package/dist/nodes/material.js +91 -23
- package/dist/nodes/measure.js +45 -18
- package/dist/nodes/particles.js +2 -0
- package/dist/nodes/pcg.js +6 -5
- package/dist/nodes/procedural.js +4 -3
- package/dist/nodes/rbd.js +1 -1
- package/dist/nodes/remesh.js +71 -15
- package/dist/nodes/scene.d.ts +1 -0
- package/dist/nodes/scene.js +55 -0
- package/dist/nodes/sdf.js +10 -5
- package/dist/nodes/solid.js +20 -5
- package/dist/nodes/solidify.d.ts +1 -0
- package/dist/nodes/solidify.js +52 -0
- package/dist/nodes/splines.d.ts +15 -1
- package/dist/nodes/splines.js +112 -105
- package/dist/nodes/texture.d.ts +21 -6
- package/dist/nodes/texture.js +1318 -185
- package/dist/nodes/topology.d.ts +7 -0
- package/dist/nodes/topology.js +133 -6
- package/dist/nodes/transform.js +11 -3
- package/dist/nodes/util.d.ts +1 -1
- package/dist/nodes/uv.js +192 -174
- package/dist/nodes/wasmcall.js +6 -2
- package/dist/open.d.ts +19 -0
- package/dist/open.js +12 -0
- package/dist/package.d.ts +288 -0
- package/dist/package.js +772 -0
- package/dist/packages/check.d.ts +32 -0
- package/dist/packages/check.js +169 -0
- package/dist/packages/commands.d.ts +57 -0
- package/dist/packages/commands.js +537 -0
- package/dist/packages/registry.d.ts +796 -0
- package/dist/packages/registry.js +2998 -0
- package/dist/packages/update.d.ts +124 -0
- package/dist/packages/update.js +476 -0
- package/dist/render/options.d.ts +2 -0
- package/dist/render/options.js +44 -5
- package/dist/render/pbr.d.ts +28 -0
- package/dist/render/pbr.js +378 -0
- package/dist/render/preview.d.ts +69 -0
- package/dist/render/preview.js +26 -0
- package/dist/render/raster.d.ts +78 -7
- package/dist/render/raster.js +600 -145
- package/dist/render/texview.d.ts +7 -1
- package/dist/render/texview.js +34 -2
- package/dist/scan.d.ts +61 -0
- package/dist/scan.js +228 -0
- package/dist/session.d.ts +311 -0
- package/dist/session.js +849 -0
- package/dist/viewer/app/api.js +48 -6
- package/dist/viewer/app/camera.js +1 -1
- package/dist/viewer/app/cooking.js +78 -0
- package/dist/viewer/app/embed.js +100 -0
- package/dist/viewer/app/export-popover.js +118 -16
- package/dist/viewer/app/grid.js +6 -2
- package/dist/viewer/app/guides.js +123 -1
- package/dist/viewer/app/keymap.js +7 -4
- package/dist/viewer/app/layers.js +5 -5
- package/dist/viewer/app/main.js +186 -53
- package/dist/viewer/app/markers.js +61 -1
- package/dist/viewer/app/outliner.js +72 -27
- package/dist/viewer/app/output-info.js +45 -0
- package/dist/viewer/app/outputs.css +147 -8
- package/dist/viewer/app/outputs.js +168 -54
- package/dist/viewer/app/packages.js +614 -0
- package/dist/viewer/app/props.js +177 -53
- package/dist/viewer/app/scene.js +35 -6
- package/dist/viewer/app/select.js +5 -4
- package/dist/viewer/app/selection.js +1 -1
- package/dist/viewer/app/status.js +12 -15
- package/dist/viewer/app/style.css +66 -8
- package/dist/viewer/app/units.js +1 -1
- package/dist/viewer/app/vars.js +48 -1
- package/dist/viewer/app/welcome.js +72 -0
- package/dist/viewer/graph-file.d.ts +62 -0
- package/dist/viewer/graph-file.js +175 -0
- package/dist/viewer/index.html +24 -11
- package/dist/viewer/json-edit.d.ts +13 -0
- package/dist/viewer/json-edit.js +274 -0
- package/dist/viewer/outputs.d.ts +49 -5
- package/dist/viewer/outputs.js +264 -56
- package/dist/viewer/packages.d.ts +121 -0
- package/dist/viewer/packages.js +584 -0
- package/dist/viewer/server.d.ts +24 -7
- package/dist/viewer/server.js +289 -31
- package/dist/web/app/web.css +419 -0
- package/dist/web/app/web.js +188 -0
- package/dist/web/bake.d.ts +34 -0
- package/dist/web/bake.js +153 -0
- package/dist/web/folder-page.d.ts +101 -0
- package/dist/web/folder-page.js +146 -0
- package/dist/web/folders.d.ts +280 -0
- package/dist/web/folders.js +970 -0
- package/dist/web/library.d.ts +91 -0
- package/dist/web/library.js +228 -0
- package/dist/web/markdown.d.ts +45 -0
- package/dist/web/markdown.js +677 -0
- package/dist/web/pages.d.ts +258 -0
- package/dist/web/pages.js +301 -0
- package/dist/web/server.d.ts +24 -0
- package/dist/web/server.js +1068 -0
- package/dist/workspace.d.ts +88 -105
- package/dist/workspace.js +359 -375
- package/integrations/godot/addons/topotopo/LICENSE +202 -0
- package/integrations/godot/addons/topotopo/README.md +57 -0
- package/integrations/godot/addons/topotopo/context_menu.gd +43 -0
- package/integrations/godot/addons/topotopo/dock.gd +266 -0
- package/integrations/godot/addons/topotopo/dock.tscn +72 -0
- package/integrations/godot/addons/topotopo/export_filter.gd +72 -0
- package/integrations/godot/addons/topotopo/gltf_instancing.gd +131 -0
- package/integrations/godot/addons/topotopo/icons/topotopo.svg +1 -0
- package/integrations/godot/addons/topotopo/inspector.gd +38 -0
- package/integrations/godot/addons/topotopo/instances_post_import.gd +111 -0
- package/integrations/godot/addons/topotopo/package.gd +23 -0
- package/integrations/godot/addons/topotopo/package_importer.gd +187 -0
- package/integrations/godot/addons/topotopo/plugin.cfg +7 -0
- package/integrations/godot/addons/topotopo/plugin.gd +970 -0
- package/integrations/godot/addons/topotopo/record.gd +435 -0
- package/integrations/godot/addons/topotopo/runner.gd +458 -0
- package/integrations/godot/addons/topotopo/tools/check.gd +42 -0
- package/integrations/godot/addons/topotopo/watcher.gd +199 -0
- package/kernels/pkg/README.md +23 -29
- package/kernels/pkg-simd/README.md +23 -29
- package/library/architecture/versions/1.0/architecture.topo +12 -0
- package/{shelf → library/architecture/versions/1.0/graphs}/arch.json +3 -3
- package/{shelf → library/architecture/versions/1.0/graphs}/beam_truss.json +6 -6
- package/{shelf → library/architecture/versions/1.0/graphs}/brick_wall.json +8 -8
- package/{shelf → library/architecture/versions/1.0/graphs}/door_frame.json +3 -3
- package/{shelf → library/architecture/versions/1.0/graphs}/hex_grid_floor.json +3 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/house.json +8 -8
- package/library/architecture/versions/1.0/graphs/lineup.json +42 -0
- package/{shelf → library/architecture/versions/1.0/graphs}/pillar.json +3 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/railing.json +5 -5
- package/{shelf → library/architecture/versions/1.0/graphs}/roof_gable.json +2 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/roof_hip.json +2 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/roof_skeleton.json +2 -1
- package/{shelf → library/architecture/versions/1.0/graphs}/scaffold.json +4 -4
- package/{shelf → library/architecture/versions/1.0/graphs}/spiral_stairs.json +3 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/stairs.json +6 -6
- package/{shelf → library/architecture/versions/1.0/graphs}/tile_floor.json +3 -2
- package/{shelf → library/architecture/versions/1.0/graphs}/wall_segment.json +10 -10
- package/{shelf → library/architecture/versions/1.0/graphs}/window_frame.json +2 -2
- package/library/architecture/versions/1.0/version.json +1119 -0
- package/{shelf → library/nature/versions/1.0/graphs}/bush.json +2 -2
- package/{shelf → library/nature/versions/1.0/graphs}/cliff_block.json +4 -3
- package/{shelf → library/nature/versions/1.0/graphs}/forest_patch.json +5 -5
- package/{shelf → library/nature/versions/1.0/graphs}/grass_clumps.json +2 -2
- package/library/nature/versions/1.0/graphs/lineup.json +24 -0
- package/{shelf → library/nature/versions/1.0/graphs}/log.json +6 -6
- package/{shelf → library/nature/versions/1.0/graphs}/rock.json +5 -4
- package/{shelf → library/nature/versions/1.0/graphs}/scatter_rocks.json +5 -5
- package/{shelf → library/nature/versions/1.0/graphs}/tree_lowpoly.json +3 -2
- package/library/nature/versions/1.0/nature.topo +12 -0
- package/library/nature/versions/1.0/version.json +534 -0
- package/{shelf → library/props/versions/1.0/graphs}/barrel.json +5 -4
- package/{shelf → library/props/versions/1.0/graphs}/crate.json +3 -3
- package/library/props/versions/1.0/graphs/lineup.json +18 -0
- package/{shelf → library/props/versions/1.0/graphs}/pallet.json +4 -3
- package/{shelf → library/props/versions/1.0/graphs}/pipe_run.json +3 -3
- package/{shelf → library/props/versions/1.0/graphs}/sandbag_wall.json +5 -5
- package/library/props/versions/1.0/props.topo +12 -0
- package/library/props/versions/1.0/version.json +336 -0
- package/{shelf → library/street/versions/1.0/graphs}/bench.json +5 -5
- package/{shelf → library/street/versions/1.0/graphs}/bollard.json +2 -1
- package/{shelf → library/street/versions/1.0/graphs}/cable.json +4 -4
- package/{shelf → library/street/versions/1.0/graphs}/fence.json +7 -7
- package/{shelf → library/street/versions/1.0/graphs}/lamp_post.json +2 -2
- package/library/street/versions/1.0/graphs/lineup.json +22 -0
- package/{shelf → library/street/versions/1.0/graphs}/road_strip.json +2 -2
- package/{shelf → library/street/versions/1.0/graphs}/sign_post.json +1 -1
- package/library/street/versions/1.0/street.topo +12 -0
- package/library/street/versions/1.0/version.json +421 -0
- package/package.json +23 -8
- package/dist/graph/migrate.d.ts +0 -23
- package/dist/graph/migrate.js +0 -58
- package/shelf/index.json +0 -190
package/dist/package.js
ADDED
|
@@ -0,0 +1,772 @@
|
|
|
1
|
+
// A package: a folder holding one <id>.topo file, its manifest, whose name is the package id, with the folders TopoTopo
|
|
2
|
+
// works with (graphs/ assets/ inputs/ exports/) and, when it publishes versions or uses packages, its published versions/
|
|
3
|
+
// and the copies in packages/ (src/packages/). Reading and writing the manifest, finding the package a folder belongs to
|
|
4
|
+
// and the places it finds packages in (its workspace and the libraries the workspace lists, else the registered
|
|
5
|
+
// libraries), making a folder a package (init, and the MCP server's rule when it starts), and the lock its package
|
|
6
|
+
// commands hold while they write.
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { ID_RE, parsePackageName } from './graph/scope.js';
|
|
10
|
+
import { MANIFEST_EXT, NAME_RE, PACKAGE_FOLDERS, graphFiles, topoFiles } from './session.js';
|
|
11
|
+
import { BUILTIN_LIBRARY, loadConfig } from './config.js';
|
|
12
|
+
import { engineFile, readWorkspace, writeWorkspace } from './workspace.js';
|
|
13
|
+
import { folderKey, forgetScans, unscanned } from './scan.js';
|
|
14
|
+
/** a package version: big.small, from 1.0 */
|
|
15
|
+
export const VERSION_RE = /^[1-9]\d*\.(0|[1-9]\d*)$/;
|
|
16
|
+
let PROGRAM = 'topotopo';
|
|
17
|
+
/**
|
|
18
|
+
* The command a person runs TopoTopo with, as hints name it: "topotopo" installed, "node src/cli.ts" from a clone. The
|
|
19
|
+
* CLI and the MCP server set it from how they were started.
|
|
20
|
+
*/
|
|
21
|
+
export const program = () => PROGRAM;
|
|
22
|
+
export const setProgram = (p) => { PROGRAM = p; };
|
|
23
|
+
/** Wait `ms` without giving up the thread (a short retry between file operations). */
|
|
24
|
+
const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
25
|
+
/**
|
|
26
|
+
* Rename a file or folder into place. On Windows a file watcher, an editor or a virus scanner holding a file in it
|
|
27
|
+
* makes the rename fail for a moment (EPERM, EBUSY, EACCES): it is tried again for about two seconds, and then fails
|
|
28
|
+
* with a plain message.
|
|
29
|
+
*/
|
|
30
|
+
export function renameInto(from, to) {
|
|
31
|
+
for (let i = 0;; i++) {
|
|
32
|
+
try {
|
|
33
|
+
fs.renameSync(from, to);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
catch (e) {
|
|
37
|
+
if (!['EPERM', 'EBUSY', 'EACCES'].includes(e?.code))
|
|
38
|
+
throw e;
|
|
39
|
+
if (i >= 8)
|
|
40
|
+
throw new Error(`could not move ${from} to ${to}: another program (a file watcher, an editor, a virus scanner) holds a file there; close it or wait a moment, then try again`);
|
|
41
|
+
pause(Math.min(400, 25 * 2 ** i));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** How long a package's lock may be held before another process takes it as left behind by one that ended. */
|
|
46
|
+
const STALE_LOCK_MS = 120_000;
|
|
47
|
+
/**
|
|
48
|
+
* Run `f` holding the package's lock, .lock in the folder of its copies (copiesFor: packages/, or the workspace's
|
|
49
|
+
* topotopo-packages/ for a package that shares the workspace's copies), a file only one process can create at a time:
|
|
50
|
+
* the CLI, the MCP server and the viewer read, change and write the manifest, the uses and the lock under it, so that
|
|
51
|
+
* none loses another's change. Waits up to about ten seconds for another holder; a lock older than two minutes, or
|
|
52
|
+
* whose process has ended, is taken over. Held again by the same process (a nested call), it just runs `f`.
|
|
53
|
+
*/
|
|
54
|
+
export function withPackageLock(dir, f) {
|
|
55
|
+
return withStoreLock(copiesFor(dir), f);
|
|
56
|
+
}
|
|
57
|
+
/** Run `f` holding the lock of a store of copies (withPackageLock). */
|
|
58
|
+
export function withStoreLock(store, f) {
|
|
59
|
+
return withLockFile(path.join(store.packages, '.lock'), f);
|
|
60
|
+
}
|
|
61
|
+
const heldLocks = new Set();
|
|
62
|
+
function withLockFile(file, f) {
|
|
63
|
+
if (heldLocks.has(file))
|
|
64
|
+
return f();
|
|
65
|
+
const release = takeLock(file, {
|
|
66
|
+
held: () => `${file} is held by another TopoTopo process (the viewer, an MCP server or a command) changing the packages this one uses; try again when it is done, or delete the file if no such process runs`,
|
|
67
|
+
});
|
|
68
|
+
heldLocks.add(file);
|
|
69
|
+
try {
|
|
70
|
+
return f();
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
heldLocks.delete(file);
|
|
74
|
+
release();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** Is the process `pid` running? (A process of another user counts as running.) */
|
|
78
|
+
export function processAlive(pid) {
|
|
79
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
80
|
+
return false;
|
|
81
|
+
try {
|
|
82
|
+
process.kill(pid, 0);
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
catch (k) {
|
|
86
|
+
return k?.code === 'EPERM';
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Take a lock file: a file only one process can create at a time, holding the taker's pid. Waits for its holder, up to
|
|
91
|
+
* `waitMs` (default about ten seconds), then throws with `held()`'s message. A lock whose process has ended, or that
|
|
92
|
+
* this process left, is taken over; one older than two minutes too, unless `pidOnly` (a cook can hold its lock for
|
|
93
|
+
* longer: only an ended process makes it stale). Returns the function that releases it.
|
|
94
|
+
*/
|
|
95
|
+
export function takeLock(file, o = {}) {
|
|
96
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
97
|
+
const limit = o.waitMs ?? 10_000;
|
|
98
|
+
for (let waited = 0;;) {
|
|
99
|
+
try {
|
|
100
|
+
fs.writeFileSync(file, `${process.pid} ${new Date().toISOString()}\n`, { flag: 'wx' });
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
catch (e) {
|
|
104
|
+
if (e?.code !== 'EEXIST')
|
|
105
|
+
throw e;
|
|
106
|
+
let stale = false, pid = 0;
|
|
107
|
+
try {
|
|
108
|
+
pid = Number(fs.readFileSync(file, 'utf8').trim().split(/\s+/)[0]);
|
|
109
|
+
const age = Date.now() - fs.statSync(file).mtimeMs;
|
|
110
|
+
// no pid yet: its taker is writing it (a moment), or it ended before it could
|
|
111
|
+
stale = !pid ? age > 2000 : (!o.pidOnly && age > STALE_LOCK_MS) || !processAlive(pid) || pid === process.pid;
|
|
112
|
+
}
|
|
113
|
+
catch { /* removed meanwhile: try again */ }
|
|
114
|
+
if (stale) {
|
|
115
|
+
fs.rmSync(file, { force: true });
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (waited > limit)
|
|
119
|
+
throw new Error(o.held ? o.held(pid) : `${file} is held by process ${pid}`);
|
|
120
|
+
pause(50);
|
|
121
|
+
waited += 50;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return () => fs.rmSync(file, { force: true });
|
|
125
|
+
}
|
|
126
|
+
export const slugify = (s) => s.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^[-_]+|[-_]+$/g, '').slice(0, 64);
|
|
127
|
+
// ------------------------------------------------------------------------------------------------------- manifests
|
|
128
|
+
const str = (v, key, def = '') => {
|
|
129
|
+
if (v === undefined || v === null)
|
|
130
|
+
return def;
|
|
131
|
+
if (typeof v !== 'string')
|
|
132
|
+
throw new Error(`"${key}" must be a string`);
|
|
133
|
+
return v;
|
|
134
|
+
};
|
|
135
|
+
/** "owner/name": a package name (no output). */
|
|
136
|
+
export const isPackageName = (s) => { const n = parsePackageName(s); return typeof n !== 'string' && n.output === null; };
|
|
137
|
+
/**
|
|
138
|
+
* A "uses" map checked ({"owner/name": "1.3"}), sorted by name; throws naming the entry that is wrong (`where`: the file
|
|
139
|
+
* it is in, when it is not the manifest).
|
|
140
|
+
*/
|
|
141
|
+
export function parseUses(v, where = '') {
|
|
142
|
+
const at = where ? `${where}: ` : '';
|
|
143
|
+
if (v === undefined || v === null)
|
|
144
|
+
return {};
|
|
145
|
+
if (typeof v !== 'object' || Array.isArray(v))
|
|
146
|
+
throw new Error(`${at}"uses" must be {"owner/name": "1.3"}`);
|
|
147
|
+
for (const [k, x] of Object.entries(v)) {
|
|
148
|
+
if (!isPackageName(k))
|
|
149
|
+
throw new Error(`${at}"uses": "${k}" is not a package name (owner/name)`);
|
|
150
|
+
if (typeof x !== 'string' || !VERSION_RE.test(x))
|
|
151
|
+
throw new Error(`${at}"uses": "${k}" needs a version such as "1.3", got ${JSON.stringify(x)}`);
|
|
152
|
+
}
|
|
153
|
+
return Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* A manifest checked and normalised; throws naming the problem. `id`: the package id, its file's name (the default
|
|
157
|
+
* title); `dir`: the package's folder, when the manifest is read from one (what a manifest that still lists
|
|
158
|
+
* "libraries" is told depends on where it is).
|
|
159
|
+
*/
|
|
160
|
+
export function parseManifest(raw, id, dir) {
|
|
161
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
162
|
+
throw new Error('a package manifest must be an object');
|
|
163
|
+
if (Object.hasOwn(raw, 'id'))
|
|
164
|
+
throw new Error('"id": the file\'s name is the package id; remove "id"');
|
|
165
|
+
if (Object.hasOwn(raw, 'package'))
|
|
166
|
+
throw new Error('"package" is "name" now: rename it');
|
|
167
|
+
const graph = str(raw.graph, 'graph', 'main');
|
|
168
|
+
if (!NAME_RE.test(graph))
|
|
169
|
+
throw new Error(`"graph" "${graph}" must be a graph name (${NAME_RE})`);
|
|
170
|
+
const tags = raw.tags ?? [];
|
|
171
|
+
if (!Array.isArray(tags) || tags.some((t) => typeof t !== 'string'))
|
|
172
|
+
throw new Error('"tags" must be a list of strings');
|
|
173
|
+
const links = raw.links ?? [];
|
|
174
|
+
if (!Array.isArray(links) || links.some((l) => !l || typeof l.url !== 'string'))
|
|
175
|
+
throw new Error('"links" must be a list of {"label", "url"}');
|
|
176
|
+
const b = raw.bake ?? {};
|
|
177
|
+
if (typeof b !== 'object' || Array.isArray(b))
|
|
178
|
+
throw new Error('"bake" must be {graph?, node?, frame?}');
|
|
179
|
+
const bake = {};
|
|
180
|
+
if (b.graph !== undefined) {
|
|
181
|
+
bake.graph = str(b.graph, 'bake.graph');
|
|
182
|
+
if (!NAME_RE.test(bake.graph))
|
|
183
|
+
throw new Error(`"bake.graph" must be a graph name`);
|
|
184
|
+
}
|
|
185
|
+
if (b.node !== undefined)
|
|
186
|
+
bake.node = str(b.node, 'bake.node');
|
|
187
|
+
if (b.frame !== undefined) {
|
|
188
|
+
if (!Number.isFinite(b.frame))
|
|
189
|
+
throw new Error('"bake.frame" must be a number');
|
|
190
|
+
bake.frame = b.frame;
|
|
191
|
+
}
|
|
192
|
+
const name = raw.name === undefined ? undefined : str(raw.name, 'name');
|
|
193
|
+
if (name !== undefined && !isPackageName(name))
|
|
194
|
+
throw new Error(`"name" "${name}" must be "owner/name": each part lower-case letters, digits, - and _, starting with a letter or digit`);
|
|
195
|
+
const uses = parseUses(raw.uses);
|
|
196
|
+
// a package lists no libraries: its workspace does (an empty list is dropped)
|
|
197
|
+
if (raw.libraries !== undefined && !(Array.isArray(raw.libraries) && !raw.libraries.length))
|
|
198
|
+
throw new Error(librariesGone(raw.libraries, dir));
|
|
199
|
+
return {
|
|
200
|
+
graph, bake,
|
|
201
|
+
title: str(raw.title, 'title', id),
|
|
202
|
+
description: str(raw.description, 'description'),
|
|
203
|
+
tags: [...new Set(tags.map((t) => t.trim()).filter(Boolean))],
|
|
204
|
+
links: links.map((l) => ({ label: typeof l.label === 'string' && l.label ? l.label : l.url, url: l.url })),
|
|
205
|
+
created: str(raw.created, 'created'),
|
|
206
|
+
...(name !== undefined ? { name } : {}),
|
|
207
|
+
uses,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* What a manifest that still lists "libraries" is told: where each entry goes now, for the package in `dir` (its
|
|
212
|
+
* entries' paths were written from it). In a workspace, the workspace lists the shared libraries its packages use:
|
|
213
|
+
* the command that lists each (a path entry by its folder; one inside the workspace needs nothing, its packages are
|
|
214
|
+
* found by themselves). Outside a workspace every registered library counts: the command that registers one.
|
|
215
|
+
*/
|
|
216
|
+
function librariesGone(v, dir) {
|
|
217
|
+
if (!dir)
|
|
218
|
+
return `"libraries" is gone from the package manifest: a workspace lists the shared libraries its packages use (${program()} workspace library add <name or folder>); outside a workspace every registered library counts; remove "libraries"`;
|
|
219
|
+
const entries = Array.isArray(v) ? v.filter((e) => typeof e === 'string' && !!e.trim()) : [];
|
|
220
|
+
const q = (s) => (/[\s"]/.test(s) ? JSON.stringify(s) : s);
|
|
221
|
+
const ws = locate(dir).workspace;
|
|
222
|
+
let registered = [];
|
|
223
|
+
try {
|
|
224
|
+
registered = loadConfig().libraries;
|
|
225
|
+
}
|
|
226
|
+
catch { /* none to name */ }
|
|
227
|
+
const said = entries.map((e) => {
|
|
228
|
+
const k = libraryEntry(e);
|
|
229
|
+
if ('error' in k)
|
|
230
|
+
return `"${e}" is no library: ${k.error}`;
|
|
231
|
+
const abs = 'path' in k ? path.resolve(dir, k.path) : null;
|
|
232
|
+
const reg = abs ? registered.find((l) => folderKey(l.path) === folderKey(abs)) : registered.find((l) => l.name === e);
|
|
233
|
+
if (ws) {
|
|
234
|
+
if (abs && within(abs, ws))
|
|
235
|
+
return `"${e}" (${abs}) is inside the workspace, whose packages are found by themselves: nothing to list`;
|
|
236
|
+
return `${program()} workspace library add ${reg ? reg.name : q(abs ?? e)}${workspaceFlag(ws)}`;
|
|
237
|
+
}
|
|
238
|
+
if (reg)
|
|
239
|
+
return `"${e}" is the registered library "${reg.name}", which counts already`;
|
|
240
|
+
return abs ? `${program()} library add ${libraryName(abs) ?? (slugify(path.basename(abs)) || 'library')} ${q(abs)}` : `${program()} library add ${e} <its folder>`;
|
|
241
|
+
});
|
|
242
|
+
const how = said.length ? said.join('; ') : ws ? `${program()} workspace library add <name or folder>${workspaceFlag(ws)}` : `${program()} library add <name> <folder>`;
|
|
243
|
+
return `"libraries" is gone from the package manifest: ${ws ? `the workspace lists the shared libraries its packages use (${how})` : `outside a workspace every registered library counts (${how})`}; remove "libraries"`;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* The manifest of the package whose folder is `dir`: its file and the package id, the file's name; null for a folder
|
|
247
|
+
* that holds no .topo file (one that holds project.json instead is none either: oldManifest says what to do). Throws
|
|
248
|
+
* for a folder with more than one, naming them, and for a file name that is no package id.
|
|
249
|
+
*/
|
|
250
|
+
export function manifestAt(dir) {
|
|
251
|
+
const found = topoFiles(dir);
|
|
252
|
+
if (!found.length)
|
|
253
|
+
return null;
|
|
254
|
+
if (found.length > 1)
|
|
255
|
+
throw new Error(`${dir} holds ${found.slice(0, -1).join(', ')} and ${found.at(-1)}: a package has one ${MANIFEST_EXT} file, whose name is its id`);
|
|
256
|
+
const id = found[0].slice(0, -MANIFEST_EXT.length);
|
|
257
|
+
if (!ID_RE.test(id))
|
|
258
|
+
throw new Error(`${path.join(dir, found[0])}: the file's name is the package id: lower-case letters, digits, - and _, starting with a letter or digit ("${slugify(id) || 'package'}${MANIFEST_EXT}")`);
|
|
259
|
+
return { file: path.join(dir, found[0]), id };
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* What a folder that holds project.json and no .topo file is told: a package's manifest is <id>.topo, named after the
|
|
263
|
+
* id it had (else after the folder). null for any other folder.
|
|
264
|
+
*/
|
|
265
|
+
export function oldManifest(dir) {
|
|
266
|
+
const file = path.join(dir, 'project.json');
|
|
267
|
+
if (topoFiles(dir).length || !fs.statSync(file, { throwIfNoEntry: false })?.isFile())
|
|
268
|
+
return null;
|
|
269
|
+
let raw = null;
|
|
270
|
+
try {
|
|
271
|
+
raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
272
|
+
}
|
|
273
|
+
catch { /* not JSON: named after its folder */ }
|
|
274
|
+
const id = typeof raw?.id === 'string' && ID_RE.test(raw.id) ? raw.id : slugify(path.basename(dir)) || 'package';
|
|
275
|
+
const inside = [raw?.package !== undefined ? '"package" to "name"' : '', raw?.id !== undefined ? 'remove "id"' : ''].filter(Boolean);
|
|
276
|
+
return `${dir} holds project.json, which TopoTopo no longer reads: rename it to ${id}${MANIFEST_EXT}${inside.length ? ` and, in it, ${inside.join(' and ')}` : ''}`;
|
|
277
|
+
}
|
|
278
|
+
/** oldManifest for the nearest folder at or above `start` it speaks of, as the end of a message ("; …"); '' for none. */
|
|
279
|
+
export function oldManifestAbove(start) {
|
|
280
|
+
for (let d = path.resolve(start);;) {
|
|
281
|
+
const said = oldManifest(d);
|
|
282
|
+
if (said)
|
|
283
|
+
return `; ${said}`;
|
|
284
|
+
const up = path.dirname(d);
|
|
285
|
+
if (up === d)
|
|
286
|
+
return '';
|
|
287
|
+
d = up;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/** The manifest of a package folder (manifestAt); throws for a folder that is no package. */
|
|
291
|
+
function needManifest(dir) {
|
|
292
|
+
const at = manifestAt(dir);
|
|
293
|
+
if (!at)
|
|
294
|
+
throw new Error(oldManifest(dir) ?? `${dir} is no package: it holds no ${MANIFEST_EXT} file`);
|
|
295
|
+
return at;
|
|
296
|
+
}
|
|
297
|
+
/** A package folder's manifest file, <id>.topo; throws for a folder that is no package. */
|
|
298
|
+
export const manifestFile = (dir) => needManifest(dir).file;
|
|
299
|
+
/** A package folder's id, the name of its .topo file; throws for a folder that is no package. */
|
|
300
|
+
export const packageId = (dir) => needManifest(dir).id;
|
|
301
|
+
export function readManifest(dir) {
|
|
302
|
+
const { file, id } = needManifest(dir);
|
|
303
|
+
return readManifestFile(file, id);
|
|
304
|
+
}
|
|
305
|
+
/** A manifest file read and checked (`id`: its name, the package id); throws naming the file. */
|
|
306
|
+
export function readManifestFile(file, id) {
|
|
307
|
+
let raw;
|
|
308
|
+
try {
|
|
309
|
+
raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
310
|
+
}
|
|
311
|
+
catch (e) {
|
|
312
|
+
throw new Error(`${file}: ${e.message}`);
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
return parseManifest(raw, id, path.dirname(file));
|
|
316
|
+
}
|
|
317
|
+
catch (e) {
|
|
318
|
+
throw new Error(`${file}: ${e.message}`);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Write a manifest (atomically), keeping keys of the file this version does not know: the folder's .topo file, or a new
|
|
323
|
+
* <id>.topo in a folder that holds none.
|
|
324
|
+
*/
|
|
325
|
+
export function writeManifest(dir, m, id) {
|
|
326
|
+
const file = manifestAt(dir)?.file ?? (id === undefined ? manifestFile(dir) : path.join(dir, `${id}${MANIFEST_EXT}`));
|
|
327
|
+
let raw = {};
|
|
328
|
+
try {
|
|
329
|
+
raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
330
|
+
}
|
|
331
|
+
catch { /* new or unreadable: replaced */ }
|
|
332
|
+
const out = { ...raw, ...m };
|
|
333
|
+
// "uses" appears once it holds something (or when the file had it already); an empty "libraries" goes
|
|
334
|
+
if (!Object.keys(m.uses).length && !Object.hasOwn(raw, 'uses'))
|
|
335
|
+
delete out.uses;
|
|
336
|
+
if (Array.isArray(out.libraries) && !out.libraries.length)
|
|
337
|
+
delete out.libraries;
|
|
338
|
+
writeAtomic(file, JSON.stringify(out, null, 2) + '\n');
|
|
339
|
+
forgetScans();
|
|
340
|
+
}
|
|
341
|
+
/** Written as a dot-file next to the target and renamed, so readers never see half a file. */
|
|
342
|
+
export function writeAtomic(file, data) {
|
|
343
|
+
const part = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}-${Date.now().toString(36)}.part`);
|
|
344
|
+
try {
|
|
345
|
+
fs.writeFileSync(part, data);
|
|
346
|
+
renameInto(part, file);
|
|
347
|
+
}
|
|
348
|
+
catch (e) {
|
|
349
|
+
fs.rmSync(part, { force: true });
|
|
350
|
+
throw e;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* The package a folder belongs to: the folder itself, or the nearest one above, that holds a .topo file (manifestAt);
|
|
355
|
+
* null for none. Throws for a folder on the way that holds several.
|
|
356
|
+
*/
|
|
357
|
+
export function packageDirOf(start) {
|
|
358
|
+
let d = path.resolve(start);
|
|
359
|
+
for (;;) {
|
|
360
|
+
if (manifestAt(d))
|
|
361
|
+
return d;
|
|
362
|
+
const up = path.dirname(d);
|
|
363
|
+
if (up === d)
|
|
364
|
+
return null;
|
|
365
|
+
d = up;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* What a package's .gitignore holds: files derived from it (previews, caches, the hashes of its copies' files) and the
|
|
370
|
+
* lock its package commands hold while they write.
|
|
371
|
+
*/
|
|
372
|
+
const IGNORED = ['.web/', '.cache/', 'packages/.cache.json', 'packages/.lock'];
|
|
373
|
+
/**
|
|
374
|
+
* What a package's .gitattributes holds: its published versions and its package copies are kept byte for byte, their
|
|
375
|
+
* line ends never changed by a checkout (their hashes read text with LF line ends anyway, src/packages/registry.ts).
|
|
376
|
+
*/
|
|
377
|
+
const ATTRIBUTES = ['versions/** -text', 'packages/** -text'];
|
|
378
|
+
/** Add to a text file the lines it does not hold yet, at its end (a new file holds just them). */
|
|
379
|
+
function addLines(file, lines) {
|
|
380
|
+
let text = '';
|
|
381
|
+
try {
|
|
382
|
+
text = fs.readFileSync(file, 'utf8');
|
|
383
|
+
}
|
|
384
|
+
catch { /* new */ }
|
|
385
|
+
const have = new Set(text.split(/\r?\n/).map((l) => l.trim()));
|
|
386
|
+
const missing = lines.filter((l) => !have.has(l));
|
|
387
|
+
if (!missing.length)
|
|
388
|
+
return;
|
|
389
|
+
fs.writeFileSync(file, `${text}${text && !text.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`);
|
|
390
|
+
}
|
|
391
|
+
/** A package's .gitignore and .gitattributes, made or completed. */
|
|
392
|
+
export function packageRepoFiles(dir) {
|
|
393
|
+
addLines(path.join(dir, '.gitignore'), IGNORED);
|
|
394
|
+
addLines(path.join(dir, '.gitattributes'), ATTRIBUTES);
|
|
395
|
+
}
|
|
396
|
+
/** A workspace's .gitignore and .gitattributes, made or completed: its shared copies as a package's own are kept. */
|
|
397
|
+
export function workspaceRepoFiles(dir) {
|
|
398
|
+
addLines(path.join(dir, '.gitignore'), [`${WORKSPACE_PACKAGES}/.cache.json`, `${WORKSPACE_PACKAGES}/.lock`]);
|
|
399
|
+
addLines(path.join(dir, '.gitattributes'), [`${WORKSPACE_PACKAGES}/** -text`]);
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* A package name a person gives their package ("owner/name"): checked, and the owner "topotopo", which TopoTopo's own
|
|
403
|
+
* packages have, refused.
|
|
404
|
+
*/
|
|
405
|
+
export function ownPackageName(pkg) {
|
|
406
|
+
const n = parsePackageName(pkg);
|
|
407
|
+
if (typeof n === 'string' || n.output !== null)
|
|
408
|
+
throw new Error(`"${pkg}" is not a package name: write "owner/name", each part lower-case letters, digits, - and _, starting with a letter or digit`);
|
|
409
|
+
if (pkg.split('/')[0] === BUILTIN_LIBRARY.name)
|
|
410
|
+
throw new Error(`the owner "${BUILTIN_LIBRARY.name}" is reserved for TopoTopo's own packages: name the package after its owner, you or your studio ("studio/${pkg.split('/')[1]}")`);
|
|
411
|
+
return pkg;
|
|
412
|
+
}
|
|
413
|
+
/** The graph a new package starts with (graphs/main.json): a box, so that the graph its manifest shows cooks. */
|
|
414
|
+
const STARTER = { description: 'A starting point: replace it with the package\'s graph.', nodes: { box: { type: 'box' } }, output: 'box' };
|
|
415
|
+
/**
|
|
416
|
+
* Make a folder a package (`topotopo init`), in a workspace, a library or anywhere: <id>.topo (the id and title from the
|
|
417
|
+
* folder's name, or from `title`; the graph it shows; and the name it publishes under, `name`, "owner/name"), graphs/
|
|
418
|
+
* with a starter graph when it holds none (so that
|
|
419
|
+
* the graph the manifest shows is there: graphs/main.json, a box), a .gitignore for the derived files and a
|
|
420
|
+
* .gitattributes that keeps its versions and package copies byte for byte (both completed when they exist). In a folder
|
|
421
|
+
* that is a package already, `name` sets the name it publishes under (when it has none yet); without it, that is an
|
|
422
|
+
* error. Fails for a folder inside another package, and for one that holds project.json (oldManifest).
|
|
423
|
+
*/
|
|
424
|
+
export function initPackage(dir, o = {}) {
|
|
425
|
+
const abs = path.resolve(dir);
|
|
426
|
+
if (o.name !== undefined)
|
|
427
|
+
ownPackageName(o.name);
|
|
428
|
+
const at = manifestAt(abs);
|
|
429
|
+
if (at) {
|
|
430
|
+
if (o.name === undefined)
|
|
431
|
+
throw new Error(`${abs} is a package already (${at.file}); --name owner/name sets the name it publishes under`);
|
|
432
|
+
const m = readManifest(abs);
|
|
433
|
+
if (m.name === o.name)
|
|
434
|
+
return { dir: abs, id: at.id, manifest: m, said: `package ${at.id} → ${abs} publishes as ${m.name} already` };
|
|
435
|
+
if (m.name)
|
|
436
|
+
throw new Error(`package ${at.id} publishes as ${m.name} already: a package keeps its name (to publish it under another name, change "name" in ${at.file} yourself)`);
|
|
437
|
+
m.name = o.name;
|
|
438
|
+
writeManifest(abs, m);
|
|
439
|
+
packageRepoFiles(abs);
|
|
440
|
+
return { dir: abs, id: at.id, manifest: m, said: `package ${at.id} → ${abs} publishes as ${m.name} now` };
|
|
441
|
+
}
|
|
442
|
+
const old = oldManifest(abs);
|
|
443
|
+
if (old)
|
|
444
|
+
throw new Error(old);
|
|
445
|
+
const outer = packageDirOf(path.dirname(abs));
|
|
446
|
+
if (outer)
|
|
447
|
+
throw new Error(`${abs} is inside the package ${outer}: a package cannot hold another`);
|
|
448
|
+
const title = o.title ?? path.basename(abs);
|
|
449
|
+
const id = slugify(title);
|
|
450
|
+
if (!ID_RE.test(id))
|
|
451
|
+
throw new Error(`"${title}" gives no usable package id: name the folder with letters or digits`);
|
|
452
|
+
// the graph it shows: main, unless graphs/ holds others and no main
|
|
453
|
+
const graphs = path.join(abs, 'graphs');
|
|
454
|
+
fs.mkdirSync(graphs, { recursive: true });
|
|
455
|
+
const held = [...graphFiles(abs).keys()];
|
|
456
|
+
const graph = held.length && !held.includes('main') ? held[0] : 'main';
|
|
457
|
+
if (!held.length)
|
|
458
|
+
fs.writeFileSync(path.join(graphs, 'main.json'), JSON.stringify(STARTER, null, 2) + '\n');
|
|
459
|
+
const raw = { title, graph, created: new Date().toISOString().slice(0, 10), ...(o.name !== undefined ? { name: o.name } : {}) };
|
|
460
|
+
const manifest = parseManifest(raw, id);
|
|
461
|
+
writeAtomic(path.join(abs, `${id}${MANIFEST_EXT}`), JSON.stringify(raw, null, 2) + '\n');
|
|
462
|
+
forgetScans();
|
|
463
|
+
packageRepoFiles(abs);
|
|
464
|
+
return { dir: abs, id, manifest, said: `package ${id} → ${abs}${manifest.name ? ` (publishes as ${manifest.name})` : ''}` };
|
|
465
|
+
}
|
|
466
|
+
/** Files an operating system leaves in folders, which say nothing about what a folder holds. */
|
|
467
|
+
const SYSTEM_FILES = new Set(['.DS_Store', 'Thumbs.db', 'desktop.ini']);
|
|
468
|
+
/**
|
|
469
|
+
* What a folder holds that TopoTopo does not make itself (its folders graphs/, assets/, exports/, inputs/), by name,
|
|
470
|
+
* a folder's with a slash: none for a folder that holds nothing else, nothing at all, or does not exist yet. Files an
|
|
471
|
+
* operating system leaves in folders do not count.
|
|
472
|
+
*/
|
|
473
|
+
export function notPackageFiles(dir) {
|
|
474
|
+
if (!fs.existsSync(dir))
|
|
475
|
+
return [];
|
|
476
|
+
return fs.readdirSync(dir, { withFileTypes: true })
|
|
477
|
+
.filter((e) => !(e.isDirectory() && PACKAGE_FOLDERS.includes(e.name)) && !SYSTEM_FILES.has(e.name))
|
|
478
|
+
.map((e) => (e.isDirectory() ? `${e.name}/` : e.name)).sort();
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* The MCP server's rule for its folder when it starts, named or not (scripts/preview.ts applies it too). A folder in
|
|
482
|
+
* a package works in that package's root, which holds its graphs, assets and packages. A folder in no package that holds
|
|
483
|
+
* nothing but what TopoTopo makes itself (graphs/, assets/, exports/, inputs/), or nothing at all, becomes a package
|
|
484
|
+
* (initPackage; `title`: its title and id, else the folder's name), so that its graphs use packages, TopoTopo's own
|
|
485
|
+
* among them, as they come. A folder with anything else in it (a repository, a folder of the person's) stays as it is:
|
|
486
|
+
* workspace {action:"init"} makes it a package when the person says so.
|
|
487
|
+
*/
|
|
488
|
+
export function startPackage(dir, o = {}) {
|
|
489
|
+
const abs = path.resolve(dir);
|
|
490
|
+
const outer = packageDirOf(abs);
|
|
491
|
+
if (outer === abs)
|
|
492
|
+
return { dir: abs, log: `the folder ${abs} is a package`, note: null };
|
|
493
|
+
if (outer)
|
|
494
|
+
return {
|
|
495
|
+
dir: outer, log: `the folder ${abs} is in the package ${outer}: working in the package's folder`,
|
|
496
|
+
note: `The server works in the package ${outer}, the package that holds the folder it was given (${abs}): a package's graphs, assets, inputs and packages are those of its own folder.`,
|
|
497
|
+
};
|
|
498
|
+
const other = notPackageFiles(abs);
|
|
499
|
+
if (other.length) {
|
|
500
|
+
const held = `${other.slice(0, 3).join(', ')}${other.length > 3 ? ` and ${other.length - 3} more` : ''}`;
|
|
501
|
+
return {
|
|
502
|
+
dir: abs, log: `the folder ${abs} is in no package and holds ${held}, which TopoTopo does not make: left as it is${oldManifestAbove(abs)}`,
|
|
503
|
+
note: `The folder ${abs} is in no package, so its graphs cannot use packages, TopoTopo's own packages ("topotopo/nature/rock" …) among them: it holds ${held}, which TopoTopo does not make (it makes graphs/, assets/, exports/, inputs/), so the server left it as it is${oldManifestAbove(abs)}. Ask the person before making it a package; workspace {action:"init"} then does it (<id>${MANIFEST_EXT}, graphs/, .gitignore, .gitattributes).`,
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
let made;
|
|
507
|
+
try {
|
|
508
|
+
made = initPackage(abs, { title: o.title });
|
|
509
|
+
}
|
|
510
|
+
catch (e) {
|
|
511
|
+
return { dir: abs, log: `the folder ${abs} could not be made a package: ${e.message}`, note: `The folder ${abs} could not be made a package, so its graphs cannot use packages: ${e.message}` };
|
|
512
|
+
}
|
|
513
|
+
const file = `${made.id}${MANIFEST_EXT}`;
|
|
514
|
+
return {
|
|
515
|
+
dir: abs, log: `made the folder ${abs} a package (${file}): it held nothing but what TopoTopo makes itself`,
|
|
516
|
+
note: `The folder ${abs} became a package, "${made.id}", when the server started (${file}, graphs/${made.manifest.graph}.json): it held nothing but TopoTopo's own folders. Its graphs use packages as they come, TopoTopo's own packages ("topotopo/nature/rock" …) among them. Next: build into graph "${made.manifest.graph}"; to publish versions of it, workspace {action:"set", name:"<owner>/${made.id}"} names it. It finds packages in its workspace and the libraries the workspace lists (workspace {action:"libraries"} shows them), or outside a workspace in every registered library.`,
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
// -------------------------------------------------------------------------------- where a package looks for packages
|
|
520
|
+
/** The file at a game's root that makes it a workspace: the libraries every package inside it looks in. */
|
|
521
|
+
export const WORKSPACE_FILE = 'topotopo-workspace.json';
|
|
522
|
+
/** A library's own file: its name, the same whatever path or registered name reaches the library. */
|
|
523
|
+
export const LIBRARY_FILE = 'library.json';
|
|
524
|
+
/**
|
|
525
|
+
* Where a folder sits: the package it belongs to and the workspace (the game) around it. A package is the workspace's
|
|
526
|
+
* when the workspace's scan finds it: one the scan never reaches (in another engine project inside the workspace, a dot
|
|
527
|
+
* folder, deeper than the scan looks) is in no workspace, and keeps its own copies.
|
|
528
|
+
*/
|
|
529
|
+
export function locate(start) {
|
|
530
|
+
const inside = packageDirOf(start);
|
|
531
|
+
for (let d = path.resolve(inside ?? start);;) {
|
|
532
|
+
if (fs.existsSync(path.join(d, WORKSPACE_FILE))) {
|
|
533
|
+
let engine;
|
|
534
|
+
// a workspace file that cannot be read: said where the packages are looked up
|
|
535
|
+
try {
|
|
536
|
+
engine = engineFile(d, readWorkspace(d));
|
|
537
|
+
}
|
|
538
|
+
catch {
|
|
539
|
+
return { package: inside, workspace: d };
|
|
540
|
+
}
|
|
541
|
+
const why = unscanned(d, inside ?? start, { engine });
|
|
542
|
+
return why ? { package: inside, workspace: null, outside: { workspace: d, why } } : { package: inside, workspace: d };
|
|
543
|
+
}
|
|
544
|
+
const up = path.dirname(d);
|
|
545
|
+
if (up === d)
|
|
546
|
+
return { package: inside, workspace: null };
|
|
547
|
+
d = up;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
/** A library's own name (library.json "name"), or null when it has none. */
|
|
551
|
+
export function libraryName(root) {
|
|
552
|
+
try {
|
|
553
|
+
const n = JSON.parse(fs.readFileSync(path.join(root, LIBRARY_FILE), 'utf8'))?.name;
|
|
554
|
+
return typeof n === 'string' && ID_RE.test(n) ? n : null;
|
|
555
|
+
}
|
|
556
|
+
catch {
|
|
557
|
+
return null;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
/** A place as messages name it: the workspace "my-game", library "props". */
|
|
561
|
+
export const placeText = (l) => (l.workspace ? `the workspace "${l.name}"` : `library "${l.name}"`);
|
|
562
|
+
/** TopoTopo's built-in library as messages name it. */
|
|
563
|
+
export const BUILTIN_TEXT = 'TopoTopo\'s built-in library';
|
|
564
|
+
/** `inner` is `outer` or a folder inside it. */
|
|
565
|
+
export const within = (inner, outer) => { const r = path.relative(path.resolve(outer), path.resolve(inner)); return !r.startsWith('..') && !path.isAbsolute(r); };
|
|
566
|
+
const isDir = (p) => !!fs.statSync(p, { throwIfNoEntry: false })?.isDirectory();
|
|
567
|
+
/**
|
|
568
|
+
* What a `workspace library` command a hint names needs to act on the workspace `ws`: " --workspace <folder>" (its path
|
|
569
|
+
* from `cwd`) when `cwd` is outside it, for the command acts on the workspace around the current folder; else ''.
|
|
570
|
+
*/
|
|
571
|
+
export function workspaceFlag(ws, cwd = process.cwd()) {
|
|
572
|
+
if (within(cwd, ws))
|
|
573
|
+
return '';
|
|
574
|
+
const r = path.relative(path.resolve(cwd), path.resolve(ws));
|
|
575
|
+
const p = !r || path.isAbsolute(r) ? path.resolve(ws) : r;
|
|
576
|
+
return ` --workspace ${/[\s"]/.test(p) ? JSON.stringify(p) : p}`;
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* What an entry of a workspace's "libraries" names: a registered library's name ("props"), or a path written from the
|
|
580
|
+
* workspace, "../shared/props" (a library in the same repository, so every checkout and worktree reads its own).
|
|
581
|
+
* Anything else says how to write it.
|
|
582
|
+
*/
|
|
583
|
+
export function libraryEntry(entry) {
|
|
584
|
+
const e = entry.trim();
|
|
585
|
+
if (path.isAbsolute(e) || /^[A-Za-z]:/.test(e))
|
|
586
|
+
return { error: `"${entry}" is an absolute path: register the library (${program()} library add <name> ${e}) and list it by its name, or list it by its path from the workspace ("../shared/props")` };
|
|
587
|
+
if (e === '.' || e === '..' || /^\.\.?[\\/]/.test(e))
|
|
588
|
+
return { path: e };
|
|
589
|
+
if (ID_RE.test(e))
|
|
590
|
+
return { name: e };
|
|
591
|
+
return { error: `"${entry}" is neither a path written from the workspace ("../${e.replace(/\\/g, '/')}") nor a registered library's name (lower-case letters, digits, - and _)` };
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* The places a folder's package finds packages in, in order (TopoTopo's built-in library comes after them, and only it
|
|
595
|
+
* has the packages named "topotopo/…"):
|
|
596
|
+
* in a workspace: the workspace itself (its scan), then the shared libraries its file lists, in order;
|
|
597
|
+
* outside a workspace, in a library (a registered library's root at or above the folder, or a library.json): that
|
|
598
|
+
* library, scanned from the package's own checkout so its siblings come from the same worktree, then every other
|
|
599
|
+
* registered library;
|
|
600
|
+
* outside both: every registered library.
|
|
601
|
+
* A workspace file that cannot be read is a problem, and only the built-in library is looked in until it is fixed.
|
|
602
|
+
*/
|
|
603
|
+
export function librariesFor(start) {
|
|
604
|
+
const { package: pkg, workspace: ws } = locate(start);
|
|
605
|
+
const out = { libs: [], problems: [], workspace: ws, self: null };
|
|
606
|
+
if (ws) {
|
|
607
|
+
let m;
|
|
608
|
+
try {
|
|
609
|
+
m = readWorkspace(ws);
|
|
610
|
+
}
|
|
611
|
+
catch (e) {
|
|
612
|
+
out.problems.push(`${e.message}; until it is fixed, packages are found in ${BUILTIN_TEXT} only`);
|
|
613
|
+
return out;
|
|
614
|
+
}
|
|
615
|
+
out.self = { from: 'self', entry: '.', root: ws, name: m.name, workspace: true, byPath: true };
|
|
616
|
+
const listed = resolveListed(ws, m.libraries);
|
|
617
|
+
out.libs.push(out.self, ...listed.libs);
|
|
618
|
+
out.problems.push(...listed.problems);
|
|
619
|
+
return out;
|
|
620
|
+
}
|
|
621
|
+
let cfg = null;
|
|
622
|
+
try {
|
|
623
|
+
cfg = loadConfig();
|
|
624
|
+
}
|
|
625
|
+
catch (e) {
|
|
626
|
+
out.problems.push(e.message);
|
|
627
|
+
}
|
|
628
|
+
const registered = cfg?.libraries ?? [];
|
|
629
|
+
out.self = libraryAround(pkg ?? start, registered);
|
|
630
|
+
if (out.self)
|
|
631
|
+
out.libs.push(out.self);
|
|
632
|
+
const seen = new Set(out.libs.map((l) => folderKey(l.root)));
|
|
633
|
+
for (const l of registered) {
|
|
634
|
+
// the library the package is in, reached from another checkout under its registered name, counts once
|
|
635
|
+
if (seen.has(folderKey(l.path)) || l.name === out.self?.name)
|
|
636
|
+
continue;
|
|
637
|
+
seen.add(folderKey(l.path));
|
|
638
|
+
out.libs.push({ from: 'registered', entry: l.name, root: l.path, name: l.name, byPath: false });
|
|
639
|
+
}
|
|
640
|
+
return out;
|
|
641
|
+
}
|
|
642
|
+
/** The library a folder outside a workspace is in: the nearest registered library's root or library.json at or above it. */
|
|
643
|
+
function libraryAround(start, registered) {
|
|
644
|
+
for (let d = path.resolve(start);;) {
|
|
645
|
+
const reg = registered.find((l) => folderKey(l.path) === folderKey(d));
|
|
646
|
+
if (reg)
|
|
647
|
+
return { from: 'self', entry: reg.name, root: reg.path, name: reg.name, byPath: false };
|
|
648
|
+
if (fs.existsSync(path.join(d, LIBRARY_FILE))) {
|
|
649
|
+
const name = libraryName(d) ?? (slugify(path.basename(d)) || 'library');
|
|
650
|
+
return { from: 'self', entry: name, root: d, name, byPath: true };
|
|
651
|
+
}
|
|
652
|
+
const up = path.dirname(d);
|
|
653
|
+
if (up === d)
|
|
654
|
+
return null;
|
|
655
|
+
d = up;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* The shared libraries a workspace's file lists, in order, each once; what is wrong with an entry is a problem and the
|
|
660
|
+
* others still count: a name not registered on this machine, a folder that is not there, a package's folder, an entry
|
|
661
|
+
* of neither form, a library inside the workspace (its packages are found by themselves) or holding it. TopoTopo's
|
|
662
|
+
* built-in library is none of them (listing it changes nothing).
|
|
663
|
+
*/
|
|
664
|
+
export function resolveListed(ws, entries) {
|
|
665
|
+
const out = { libs: [], problems: [] };
|
|
666
|
+
const file = path.join(ws, WORKSPACE_FILE);
|
|
667
|
+
let cfg;
|
|
668
|
+
const said = (entry, why) => out.problems.push(`${file} "libraries": "${entry}" ${why}; the other libraries still count`);
|
|
669
|
+
const seen = new Set();
|
|
670
|
+
for (const entry of entries) {
|
|
671
|
+
if (entry === BUILTIN_LIBRARY.name)
|
|
672
|
+
continue;
|
|
673
|
+
const k = libraryEntry(entry);
|
|
674
|
+
if ('error' in k) {
|
|
675
|
+
out.problems.push(`${file} "libraries": ${k.error}; the other libraries still count`);
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
let root, name;
|
|
679
|
+
if ('name' in k) {
|
|
680
|
+
if (cfg === undefined) {
|
|
681
|
+
try {
|
|
682
|
+
cfg = loadConfig();
|
|
683
|
+
}
|
|
684
|
+
catch (e) {
|
|
685
|
+
cfg = null;
|
|
686
|
+
out.problems.push(e.message);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
const lib = cfg?.libraries.find((l) => l.name === entry);
|
|
690
|
+
if (!lib) {
|
|
691
|
+
said(entry, cfg?.workspaces.some((w) => w.name === entry)
|
|
692
|
+
? 'is a registered workspace, not a library: a workspace\'s packages are found from inside it ("libraries" holds shared libraries only)'
|
|
693
|
+
: `is not registered on this machine${cfg ? ` (${cfg.file} has ${cfg.libraries.map((l) => l.name).join(', ') || 'none'})` : ''}: ${program()} library add ${entry} <folder> registers it`);
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
root = path.resolve(lib.path);
|
|
697
|
+
name = entry;
|
|
698
|
+
}
|
|
699
|
+
else {
|
|
700
|
+
root = path.resolve(ws, k.path);
|
|
701
|
+
if (!isDir(root)) {
|
|
702
|
+
said(entry, `is no folder (${root})`);
|
|
703
|
+
continue;
|
|
704
|
+
}
|
|
705
|
+
let at = null;
|
|
706
|
+
try {
|
|
707
|
+
at = manifestAt(root);
|
|
708
|
+
}
|
|
709
|
+
catch (e) {
|
|
710
|
+
said(entry, `is a package's folder that cannot be read: ${e.message}`);
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
if (at) {
|
|
714
|
+
said(entry, `is a package's folder (${path.basename(at.file)}), not a library: list the folder of the library that holds it`);
|
|
715
|
+
continue;
|
|
716
|
+
}
|
|
717
|
+
name = libraryName(root) ?? entry;
|
|
718
|
+
}
|
|
719
|
+
if (within(root, ws)) {
|
|
720
|
+
said(entry, `is inside the workspace (${root}): its packages are found by themselves; remove it from "libraries"`);
|
|
721
|
+
continue;
|
|
722
|
+
}
|
|
723
|
+
if (within(ws, root)) {
|
|
724
|
+
said(entry, `(${root}) holds the workspace: list a shared library outside it; the workspace's own packages are found by themselves`);
|
|
725
|
+
continue;
|
|
726
|
+
}
|
|
727
|
+
if (seen.has(folderKey(root)))
|
|
728
|
+
continue;
|
|
729
|
+
seen.add(folderKey(root));
|
|
730
|
+
out.libs.push({ from: 'listed', entry, root, name, byPath: !('name' in k) });
|
|
731
|
+
}
|
|
732
|
+
return out;
|
|
733
|
+
}
|
|
734
|
+
// -------------------------------------------------------------------------------- where a package keeps its copies
|
|
735
|
+
/** The folder beside topotopo-workspace.json that holds the workspace's one shared copy of each package version. */
|
|
736
|
+
export const WORKSPACE_PACKAGES = 'topotopo-packages';
|
|
737
|
+
/**
|
|
738
|
+
* Where a package keeps the copies of the packages it uses: in a workspace, the workspace's one shared copy for every package in it
|
|
739
|
+
* (topotopo-packages/ beside topotopo-workspace.json, whose "uses" name one version of each package for the whole
|
|
740
|
+
* game); else, and for a package that publishes versions (its uses are published with it), its own packages/ beside its
|
|
741
|
+
* manifest.
|
|
742
|
+
*/
|
|
743
|
+
export function copiesFor(folder) {
|
|
744
|
+
const dir = path.resolve(folder);
|
|
745
|
+
let at = null;
|
|
746
|
+
try {
|
|
747
|
+
at = manifestAt(dir);
|
|
748
|
+
}
|
|
749
|
+
catch { /* two manifests: said where the package is read */ }
|
|
750
|
+
const own = { root: dir, packages: path.join(dir, 'packages'), usesFile: at?.file ?? path.join(dir, `${slugify(path.basename(dir)) || 'package'}${MANIFEST_EXT}`), workspace: null };
|
|
751
|
+
let pkg;
|
|
752
|
+
try {
|
|
753
|
+
pkg = readManifest(dir).name;
|
|
754
|
+
}
|
|
755
|
+
catch { /* not a package, or its manifest is not valid: its own folder */ }
|
|
756
|
+
if (pkg)
|
|
757
|
+
return own;
|
|
758
|
+
const ws = locate(dir).workspace;
|
|
759
|
+
return ws ? { root: ws, packages: path.join(ws, WORKSPACE_PACKAGES), usesFile: path.join(ws, WORKSPACE_FILE), workspace: ws } : own;
|
|
760
|
+
}
|
|
761
|
+
/** The versions the packages of a store use: the "uses" of the package's manifest, or of the workspace's file. */
|
|
762
|
+
export function readUses(store) {
|
|
763
|
+
return store.workspace ? readWorkspace(store.workspace).uses : readManifest(store.root).uses;
|
|
764
|
+
}
|
|
765
|
+
/** Write the uses of a store (hold its lock: withStoreLock). */
|
|
766
|
+
export function writeUses(store, uses) {
|
|
767
|
+
const sorted = Object.fromEntries(Object.entries(uses).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
|
|
768
|
+
if (store.workspace)
|
|
769
|
+
writeWorkspace(store.workspace, { ...readWorkspace(store.workspace), uses: sorted });
|
|
770
|
+
else
|
|
771
|
+
writeManifest(store.root, { ...readManifest(store.root), uses: sorted });
|
|
772
|
+
}
|