deltafold 0.0.0-stage → 0.0.1

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.
Files changed (58) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +280 -2
  3. package/dist/changelog.d.ts +116 -0
  4. package/dist/changelog.d.ts.map +1 -0
  5. package/dist/changelog.js +304 -0
  6. package/dist/changelog.js.map +1 -0
  7. package/dist/document-BZcZo9nr.js +171 -0
  8. package/dist/document-BZcZo9nr.js.map +1 -0
  9. package/dist/document-DWHsgywm.d.ts +257 -0
  10. package/dist/document-DWHsgywm.d.ts.map +1 -0
  11. package/dist/html.d.ts +8 -0
  12. package/dist/html.d.ts.map +1 -0
  13. package/dist/html.js +13 -0
  14. package/dist/html.js.map +1 -0
  15. package/dist/index.d.ts +378 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +2058 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/markdown.d.ts +8 -0
  20. package/dist/markdown.d.ts.map +1 -0
  21. package/dist/markdown.js +16 -0
  22. package/dist/markdown.js.map +1 -0
  23. package/dist/mdast-DiRsYwPU.js +108 -0
  24. package/dist/mdast-DiRsYwPU.js.map +1 -0
  25. package/dist/package-BfBYnaCz.d.ts +1125 -0
  26. package/dist/package-BfBYnaCz.d.ts.map +1 -0
  27. package/dist/rolldown-runtime-D8jQpDG7.js +12 -0
  28. package/package.json +64 -3
  29. package/src/features/documents/changelog.ts +450 -0
  30. package/src/features/documents/document.ts +357 -0
  31. package/src/features/documents/index.ts +4 -0
  32. package/src/features/documents/public-document.ts +31 -0
  33. package/src/features/documents/sections.ts +44 -0
  34. package/src/features/execution/executor.ts +826 -0
  35. package/src/features/execution/handler.ts +257 -0
  36. package/src/features/execution/settlement.ts +49 -0
  37. package/src/features/package.ts +32 -0
  38. package/src/features/planning/guide.ts +56 -0
  39. package/src/features/planning/history.ts +174 -0
  40. package/src/features/planning/identifiers.ts +43 -0
  41. package/src/features/planning/resolve-error.ts +201 -0
  42. package/src/features/planning/resolve.ts +724 -0
  43. package/src/features/planning/rewrite.ts +331 -0
  44. package/src/features/planning/validate.ts +388 -0
  45. package/src/foundation/action.ts +188 -0
  46. package/src/foundation/change.ts +147 -0
  47. package/src/foundation/instruction.ts +110 -0
  48. package/src/foundation/migration.ts +236 -0
  49. package/src/foundation/plan.ts +245 -0
  50. package/src/foundation/rule.ts +74 -0
  51. package/src/foundation/shortcut.ts +79 -0
  52. package/src/foundation/template.ts +28 -0
  53. package/src/foundation/version.ts +78 -0
  54. package/src/index.ts +22 -0
  55. package/src/renderers/html.ts +12 -0
  56. package/src/renderers/markdown.ts +12 -0
  57. package/src/renderers/mdast.ts +120 -0
  58. package/src/types.ts +2 -0
@@ -0,0 +1,724 @@
1
+ import { Array as Arr, Graph, Order, Result, SemVer } from "effect";
2
+
3
+ import type * as Change from "../../foundation/change.ts";
4
+ import type * as Migration from "../../foundation/migration.ts";
5
+ import type {
6
+ Direction,
7
+ Explanation,
8
+ Hop,
9
+ Node,
10
+ Plan,
11
+ RequestDirection,
12
+ Route,
13
+ Step,
14
+ } from "../../foundation/plan.ts";
15
+ import type * as Shortcut from "../../foundation/shortcut.ts";
16
+ import type { Version } from "../../foundation/version.ts";
17
+ import { resolveGuide } from "./guide.ts";
18
+ import { declaredOccurrenceId, routeHop, routeShortcut, routeStart } from "./identifiers.ts";
19
+ import {
20
+ AmbiguousRoute,
21
+ ConflictingRewrites,
22
+ RewriteCycle,
23
+ RewriteLimitExceeded,
24
+ TooManyRoutes,
25
+ UnknownRoute,
26
+ UnknownVersion,
27
+ UnsupportedRoute,
28
+ type Blocker,
29
+ type ResolveError,
30
+ type RewriteError,
31
+ type RouteSummary,
32
+ } from "./resolve-error.ts";
33
+ import { itemsOf, occurrencesOf, rewrite, type Item, type MakeOccurrence } from "./rewrite.ts";
34
+ import { actionsOfSteps, hasProse, stepsOf, type Declarations } from "./validate.ts";
35
+
36
+ /**
37
+ * Route policies for choosing between candidate routes. Each one is opt-in, and a policy
38
+ * that leaves a tie still fails as ambiguous.
39
+ *
40
+ * - `fewest-actions`: the fewest action occurrences after optimization.
41
+ * - `fewest-migrations`: the fewest migration steps.
42
+ * - `lowest-cost`: the lowest total cost. A migration costs 1 unless it declares
43
+ * `cost`; a shortcut costs its declared `cost` or the total of its migrations.
44
+ * - `prefer-shortcuts`: a route through a shortcut over the route the shortcut replaces.
45
+ *
46
+ * @since @next
47
+ */
48
+ export type RoutePolicy =
49
+ | "fewest-actions"
50
+ | "fewest-migrations"
51
+ | "lowest-cost"
52
+ | "prefer-shortcuts";
53
+
54
+ /** The largest number of candidate routes enumerated between two versions. */
55
+ export const routeLimit = 100;
56
+
57
+ type Member = { readonly migration: Migration.Any; readonly direction: Direction };
58
+
59
+ type Edge = {
60
+ readonly from: Version;
61
+ readonly to: Version;
62
+ readonly members: ReadonlyArray<Member>;
63
+ readonly shortcut: Shortcut.Any | undefined;
64
+ readonly cost: number;
65
+ readonly class: "up" | "down" | "cross";
66
+ };
67
+
68
+ type Candidate = {
69
+ readonly route: Route;
70
+ readonly edges: ReadonlyArray<Edge>;
71
+ readonly plan: Result.Result<Plan, RewriteError>;
72
+ readonly cost: number;
73
+ };
74
+
75
+ export type Context = {
76
+ readonly declarations: Declarations;
77
+ readonly versions: ReadonlyMap<string, Version>;
78
+ /** Strict ancestors of each version, by identifier. */
79
+ readonly ancestors: ReadonlyMap<string, ReadonlySet<string>>;
80
+ readonly edges: ReadonlyArray<Edge>;
81
+ };
82
+
83
+ const memberCost = (migration: Migration.Any) => migration.cost ?? 1;
84
+
85
+ export const makeContext = (declarations: Declarations): Context => {
86
+ const versions = new Map(declarations.versions.map((version) => [version.id, version]));
87
+ const ancestors = new Map<string, ReadonlySet<string>>();
88
+ const ancestorsOf = (id: string): ReadonlySet<string> => {
89
+ const known = ancestors.get(id);
90
+ if (known !== undefined) return known;
91
+
92
+ const result = new Set<string>();
93
+ let current = versions.get(id)?.previous;
94
+ while (current !== undefined && !result.has(current.id)) {
95
+ result.add(current.id);
96
+ current = versions.get(current.id)?.previous;
97
+ }
98
+ ancestors.set(id, result);
99
+
100
+ return result;
101
+ };
102
+ for (const id of versions.keys()) ancestorsOf(id);
103
+
104
+ const classOf = (from: string, to: string): Edge["class"] => {
105
+ if (ancestorsOf(to).has(from)) return "up";
106
+ if (ancestorsOf(from).has(to)) return "down";
107
+
108
+ return "cross";
109
+ };
110
+
111
+ // Validation guarantees at most one migration side per pair of versions.
112
+ const edges: Array<Edge> = declarations.migrations.flatMap((migration): Array<Edge> => {
113
+ const forward: Edge = {
114
+ from: migration.from,
115
+ to: migration.to,
116
+ members: [{ migration, direction: "forward" }],
117
+ shortcut: undefined,
118
+ cost: memberCost(migration),
119
+ class: classOf(migration.from.id, migration.to.id),
120
+ };
121
+ if (migration.revert === undefined) return [forward];
122
+
123
+ return [
124
+ forward,
125
+ {
126
+ from: migration.to,
127
+ to: migration.from,
128
+ members: [{ migration, direction: "revert" }],
129
+ shortcut: undefined,
130
+ cost: memberCost(migration),
131
+ class: classOf(migration.to.id, migration.from.id),
132
+ },
133
+ ];
134
+ });
135
+ for (const shortcut of declarations.shortcuts) {
136
+ edges.push({
137
+ from: shortcut.from,
138
+ to: shortcut.to,
139
+ members: shortcut.migrations.map((migration) => ({ migration, direction: "forward" })),
140
+ shortcut,
141
+ cost:
142
+ shortcut.cost ??
143
+ shortcut.migrations.reduce((total, migration) => total + memberCost(migration), 0),
144
+ class: classOf(shortcut.from.id, shortcut.to.id),
145
+ });
146
+ }
147
+
148
+ return { declarations, versions, ancestors, edges };
149
+ };
150
+
151
+ const requestDirection = (context: Context, from: string, to: string): RequestDirection => {
152
+ if (from === to) return "none";
153
+ if (context.ancestors.get(to)?.has(from)) return "upgrade";
154
+ if (context.ancestors.get(from)?.has(to)) return "downgrade";
155
+
156
+ return "cross-branch";
157
+ };
158
+
159
+ /**
160
+ * Edge classes allowed together in one route. A route never mixes moves toward
161
+ * ancestors with moves toward descendants, so sharing an ancestor does not authorize a
162
+ * downgrade-and-upgrade detour. Explicit cross-branch migrations fit either family.
163
+ */
164
+ const families: ReadonlyArray<ReadonlySet<Edge["class"]>> = [
165
+ new Set(["up", "cross"]),
166
+ new Set(["down", "cross"]),
167
+ ];
168
+
169
+ const routeCost = (edges: ReadonlyArray<Edge>) =>
170
+ edges.reduce((total, edge) => total + edge.cost, 0);
171
+
172
+ const routeOf = (from: Version, edges: ReadonlyArray<Edge>): Route => {
173
+ let id = routeStart(from.id);
174
+ const hops: Array<Hop> = [];
175
+ for (const edge of edges) {
176
+ if (edge.shortcut === undefined) {
177
+ id += routeHop(edge.to.id);
178
+ hops.push({
179
+ _tag: "Migrations",
180
+ from: edge.from,
181
+ to: edge.to,
182
+ migrations: edge.members,
183
+ });
184
+ continue;
185
+ }
186
+ id += routeShortcut(edge.shortcut.id, edge.to.id);
187
+ hops.push({ _tag: "Shortcut", from: edge.from, to: edge.to, shortcut: edge.shortcut });
188
+ }
189
+
190
+ return { id, hops };
191
+ };
192
+
193
+ const graphOf = (context: Context, family: ReadonlySet<Edge["class"]>) => {
194
+ const nodes = new Map<string, Graph.NodeIndex>();
195
+ const graph = Graph.directed<string, Edge>((mutable) => {
196
+ for (const id of context.versions.keys()) nodes.set(id, Graph.addNode(mutable, id));
197
+ for (const edge of context.edges) {
198
+ if (!family.has(edge.class)) continue;
199
+
200
+ const source = nodes.get(edge.from.id);
201
+ const target = nodes.get(edge.to.id);
202
+ if (source !== undefined && target !== undefined)
203
+ Graph.addEdge(mutable, source, target, edge);
204
+ }
205
+ });
206
+
207
+ return { graph, nodes };
208
+ };
209
+
210
+ type Enumerated = {
211
+ /** At most `routeLimit` routes, in search order. */
212
+ readonly routes: ReadonlyArray<ReadonlyArray<Edge>>;
213
+ /** Whether the search stopped because more routes exist. */
214
+ readonly overLimit: boolean;
215
+ };
216
+
217
+ const enumerateRoutes = (context: Context, from: Version, to: Version): Enumerated => {
218
+ const routes = new Map<string, ReadonlyArray<Edge>>();
219
+ for (const family of families) {
220
+ const { graph, nodes } = graphOf(context, family);
221
+ const source = nodes.get(from.id);
222
+ const target = nodes.get(to.id);
223
+ if (source === undefined || target === undefined) continue;
224
+
225
+ for (const path of Graph.simplePaths(graph, { source, target, limit: routeLimit + 1 })) {
226
+ routes.set(routeOf(from, path.costs).id, path.costs);
227
+ }
228
+ }
229
+ const found = [...routes.values()];
230
+
231
+ return { routes: found.slice(0, routeLimit), overLimit: found.length > routeLimit };
232
+ };
233
+
234
+ const toNode = (items: ReadonlyArray<Item>): ReadonlyArray<Node> =>
235
+ items.flatMap((item): ReadonlyArray<Node> => {
236
+ if (item._tag === "Occ") return [item.occurrence];
237
+ if (item._tag === "Barrier") return [];
238
+
239
+ return [
240
+ {
241
+ _tag: "Parallel",
242
+ branches: item.branches.map((branch) => {
243
+ const children = toNode(branch);
244
+ const [only] = children;
245
+
246
+ return children.length === 1 && only !== undefined
247
+ ? only
248
+ : { _tag: "Sequence", children };
249
+ }),
250
+ concurrency: item.concurrency,
251
+ },
252
+ ];
253
+ });
254
+
255
+ const contentOf = (member: Member): Migration.Content =>
256
+ (member.direction === "forward" ? member.migration.content : member.migration.revert) ?? [];
257
+
258
+ const buildPlan = (
259
+ context: Context,
260
+ from: Version,
261
+ to: Version,
262
+ direction: RequestDirection,
263
+ edges: ReadonlyArray<Edge>,
264
+ ): Result.Result<Plan, RewriteError> => {
265
+ const route = routeOf(from, edges);
266
+ const members = edges.flatMap((edge) => edge.members);
267
+
268
+ const items = members.flatMap((member, index): ReadonlyArray<Item> => {
269
+ const content = contentOf(member);
270
+ const make: MakeOccurrence = (action, instruction) => ({
271
+ _tag: "Occurrence",
272
+ id: declaredOccurrenceId(member.migration, member.direction, action),
273
+ action,
274
+ migration: member.migration,
275
+ direction: member.direction,
276
+ instruction,
277
+ origin: { _tag: "Declared" },
278
+ });
279
+ const declared = itemsOf(stepsOf(content), make, index);
280
+ if (declared.length === 0 && hasProse(content)) return [{ _tag: "Barrier", step: index }];
281
+
282
+ return declared;
283
+ });
284
+
285
+ const rewritten = rewrite(items, context.declarations.rules);
286
+ if (rewritten._tag === "Failure") {
287
+ const failure = rewritten.failure;
288
+ switch (failure._tag) {
289
+ case "RewriteCycle":
290
+ return Result.fail(
291
+ new RewriteCycle({
292
+ route: route.id,
293
+ rules: failure.rules,
294
+ actions: failure.actions,
295
+ }),
296
+ );
297
+ case "ConflictingRewrites":
298
+ return Result.fail(
299
+ new ConflictingRewrites({ route: route.id, outcomes: failure.outcomes }),
300
+ );
301
+ }
302
+
303
+ return Result.fail(
304
+ new RewriteLimitExceeded({
305
+ route: route.id,
306
+ limit: failure.limit,
307
+ value: failure.value,
308
+ }),
309
+ );
310
+ }
311
+ const { items: optimized, trace } = rewritten.outcome;
312
+
313
+ const explanations: Array<Explanation> = trace.map((application) => ({
314
+ _tag: "Rewrite",
315
+ rule: application.rule,
316
+ removed: application.removed,
317
+ produced: application.produced,
318
+ }));
319
+
320
+ const steps = members.map((member, index): Step => {
321
+ const stepItems = optimized.filter((item) => item.step === index);
322
+ const content = contentOf(member);
323
+ const declaredCount = actionsOfSteps(stepsOf(content)).length;
324
+ const retained = occurrencesOf(stepItems);
325
+ const guide = resolveGuide(content, retained, (action) =>
326
+ declaredOccurrenceId(member.migration, member.direction, action),
327
+ );
328
+ const allRemoved = declaredCount > 0 && retained.length === 0;
329
+ // `noop` describes the zero-work sides. A revert added to a noop migration is work.
330
+ const noop = member.migration.noop && content.length === 0;
331
+ const omitted = noop || allRemoved;
332
+ if (omitted) {
333
+ explanations.push({
334
+ _tag: "OmittedStep",
335
+ migration: member.migration,
336
+ direction: member.direction,
337
+ reason: noop ? "noop" : "all-actions-removed",
338
+ });
339
+ }
340
+ const [stepFrom, stepTo] =
341
+ member.direction === "forward"
342
+ ? [member.migration.from, member.migration.to]
343
+ : [member.migration.to, member.migration.from];
344
+
345
+ return {
346
+ _tag: "Step",
347
+ migration: member.migration,
348
+ direction: member.direction,
349
+ from: stepFrom,
350
+ to: stepTo,
351
+ node: { _tag: "Sequence", children: toNode(stepItems) },
352
+ guide: omitted ? [] : guide,
353
+ omitted,
354
+ };
355
+ });
356
+
357
+ const changes: Array<Change.Any> = [];
358
+ for (const member of members) {
359
+ for (const change of member.migration.addresses) {
360
+ if (!changes.some((known) => known.id === change.id)) changes.push(change);
361
+ }
362
+ }
363
+
364
+ return Result.succeed({
365
+ _tag: "Plan",
366
+ from,
367
+ to,
368
+ direction,
369
+ route,
370
+ steps,
371
+ occurrences: occurrencesOf(optimized),
372
+ changes,
373
+ explanations,
374
+ coverage: "static",
375
+ });
376
+ };
377
+
378
+ const summaryOf = (candidate: Candidate): RouteSummary => ({
379
+ id: candidate.route.id,
380
+ migrations: candidate.edges.flatMap((edge) =>
381
+ edge.members.map((member) => member.migration.id),
382
+ ),
383
+ shortcuts: candidate.edges.flatMap((edge) =>
384
+ edge.shortcut === undefined ? [] : [edge.shortcut.id],
385
+ ),
386
+ actions: Result.isSuccess(candidate.plan)
387
+ ? candidate.plan.success.occurrences.length
388
+ : undefined,
389
+ cost: candidate.cost,
390
+ failure: Result.isFailure(candidate.plan) ? candidate.plan.failure.message : undefined,
391
+ });
392
+
393
+ /** Migration tokens of a route, with shortcut hops expanded to the route they replace. */
394
+ const canonicalTokens = (candidate: Candidate) =>
395
+ JSON.stringify(
396
+ candidate.edges.flatMap((edge) =>
397
+ edge.shortcut === undefined
398
+ ? edge.members.map((member) => [member.direction, member.migration.id])
399
+ : edge.shortcut.replaces.map((migration) => ["forward", migration.id]),
400
+ ),
401
+ );
402
+
403
+ const shortcutCount = (candidate: Candidate) =>
404
+ candidate.edges.filter((edge) => edge.shortcut !== undefined).length;
405
+
406
+ const minimal = (
407
+ candidates: ReadonlyArray<Candidate>,
408
+ measure: (candidate: Candidate) => number | undefined,
409
+ ): ReadonlyArray<Candidate> => {
410
+ const measured = candidates.flatMap((candidate) => {
411
+ const value = measure(candidate);
412
+
413
+ return value === undefined ? [] : [{ candidate, value }];
414
+ });
415
+ const best = Math.min(...measured.map((entry) => entry.value));
416
+
417
+ return measured.filter((entry) => entry.value === best).map((entry) => entry.candidate);
418
+ };
419
+
420
+ const applyPolicy = (
421
+ policy: RoutePolicy,
422
+ candidates: ReadonlyArray<Candidate>,
423
+ ): ReadonlyArray<Candidate> => {
424
+ switch (policy) {
425
+ case "fewest-actions":
426
+ return minimal(candidates, (candidate) =>
427
+ Result.isSuccess(candidate.plan)
428
+ ? candidate.plan.success.occurrences.length
429
+ : undefined,
430
+ );
431
+ case "fewest-migrations":
432
+ return minimal(candidates, (candidate) =>
433
+ candidate.edges.reduce((total, edge) => total + edge.members.length, 0),
434
+ );
435
+ case "lowest-cost":
436
+ return minimal(candidates, (candidate) => candidate.cost);
437
+ }
438
+
439
+ // prefer-shortcuts: drop a route when another candidate is the same canonical route
440
+ // with more of it replaced by shortcuts. Unrelated routes stay ambiguous.
441
+ return candidates.filter(
442
+ (candidate) =>
443
+ !candidates.some(
444
+ (other) =>
445
+ other !== candidate &&
446
+ canonicalTokens(other) === canonicalTokens(candidate) &&
447
+ shortcutCount(other) > shortcutCount(candidate),
448
+ ),
449
+ );
450
+ };
451
+
452
+ const depthOf = (context: Context, id: string) => context.ancestors.get(id)?.size ?? 0;
453
+
454
+ /** Distance between two versions in the release ancestry tree. */
455
+ const ancestryDistance = (context: Context, self: string, that: string): number => {
456
+ const selfLine = [self, ...ancestorsInOrder(context, self)];
457
+ const thatLine = new Set([that, ...ancestorsInOrder(context, that)]);
458
+ const common = selfLine.find((id) => thatLine.has(id));
459
+ if (common === undefined) return Number.POSITIVE_INFINITY;
460
+
461
+ return depthOf(context, self) + depthOf(context, that) - 2 * depthOf(context, common);
462
+ };
463
+
464
+ const ancestorsInOrder = (context: Context, id: string): ReadonlyArray<string> => {
465
+ const result: Array<string> = [];
466
+ let current = context.versions.get(id)?.previous;
467
+ while (current !== undefined && !result.includes(current.id)) {
468
+ result.push(current.id);
469
+ current = context.versions.get(current.id)?.previous;
470
+ }
471
+
472
+ return result;
473
+ };
474
+
475
+ /** The ancestry path between two versions, through their closest common ancestor. */
476
+ const ancestryPath = (context: Context, from: string, to: string): ReadonlyArray<string> => {
477
+ const fromLine = [from, ...ancestorsInOrder(context, from)];
478
+ const toLine = [to, ...ancestorsInOrder(context, to)];
479
+ const common = fromLine.find((id) => toLine.includes(id));
480
+ if (common === undefined) return [];
481
+
482
+ return [
483
+ ...fromLine.slice(0, fromLine.indexOf(common) + 1),
484
+ ...Arr.reverse(toLine.slice(0, toLine.indexOf(common))),
485
+ ];
486
+ };
487
+
488
+ export const reachable = (
489
+ context: Context,
490
+ from: string,
491
+ family: ReadonlySet<Edge["class"]>,
492
+ ): ReadonlyArray<string> => {
493
+ const seen = new Set([from]);
494
+ const queue = [from];
495
+ for (let current = queue.shift(); current !== undefined; current = queue.shift()) {
496
+ for (const edge of context.edges) {
497
+ if (edge.from.id !== current || !family.has(edge.class) || seen.has(edge.to.id))
498
+ continue;
499
+
500
+ seen.add(edge.to.id);
501
+ queue.push(edge.to.id);
502
+ }
503
+ }
504
+ seen.delete(from);
505
+
506
+ return [...seen];
507
+ };
508
+
509
+ const familiesFor = (direction: RequestDirection) => {
510
+ if (direction === "upgrade") return [families[0]];
511
+ if (direction === "downgrade") return [families[1]];
512
+
513
+ return families;
514
+ };
515
+
516
+ const unsupported = (context: Context, from: string, to: string, direction: RequestDirection) => {
517
+ const allowed = familiesFor(direction).flatMap((family) =>
518
+ family === undefined ? [] : [family],
519
+ );
520
+ const reachableIds = Arr.sort(
521
+ new Set(allowed.flatMap((family) => reachable(context, from, family))),
522
+ Order.String,
523
+ );
524
+ const distances = reachableIds.map((id) => ({
525
+ id,
526
+ distance: ancestryDistance(context, id, to),
527
+ }));
528
+ const best = Math.min(...distances.map((entry) => entry.distance));
529
+ const closest = Number.isFinite(best)
530
+ ? distances.filter((entry) => entry.distance === best).map((entry) => entry.id)
531
+ : [];
532
+
533
+ const path = ancestryPath(context, from, to);
534
+ const blockers: Array<Blocker> = [];
535
+ for (let index = 0; index + 1 < path.length; index++) {
536
+ const hopFrom = path[index];
537
+ const hopTo = path[index + 1];
538
+ if (hopFrom === undefined || hopTo === undefined) continue;
539
+ if (context.edges.some((edge) => edge.from.id === hopFrom && edge.to.id === hopTo))
540
+ continue;
541
+
542
+ blockers.push({
543
+ from: hopFrom,
544
+ to: hopTo,
545
+ reason: `No migration is declared from "${hopFrom}" to "${hopTo}".`,
546
+ });
547
+ }
548
+
549
+ // The common ancestor where an ancestry path turns from moving down to moving up.
550
+ const turn = path.find(
551
+ (id) =>
552
+ context.ancestors.get(from)?.has(id) === true &&
553
+ context.ancestors.get(to)?.has(id) === true,
554
+ );
555
+ if (blockers.length === 0 && turn !== undefined) {
556
+ blockers.push({
557
+ from,
558
+ to,
559
+ reason: `A route through "${turn}" would combine a downgrade with an upgrade. Declare a migration from "${from}" to "${to}".`,
560
+ });
561
+ }
562
+
563
+ return new UnsupportedRoute({
564
+ from,
565
+ to,
566
+ direction,
567
+ reachable: reachableIds,
568
+ closest,
569
+ blockers,
570
+ });
571
+ };
572
+
573
+ /** @since @next */
574
+ export type ResolveOptions = {
575
+ readonly from: Version | string;
576
+ readonly to: Version | string;
577
+ /** Selects a candidate route by identifier. */
578
+ readonly route?: string;
579
+ /** Chooses between candidate routes. Ties still fail as ambiguous. */
580
+ readonly policy?: RoutePolicy;
581
+ };
582
+
583
+ export const lookup = (context: Context, reference: Version | string) => {
584
+ const id = typeof reference === "string" ? reference : reference.id;
585
+ const version = context.versions.get(id);
586
+
587
+ return version === undefined
588
+ ? Result.fail(new UnknownVersion({ version: id, known: [...context.versions.keys()] }))
589
+ : Result.succeed(version);
590
+ };
591
+
592
+ export const candidatesBetween = (
593
+ context: Context,
594
+ from: Version,
595
+ to: Version,
596
+ ): Result.Result<ReadonlyArray<Candidate>, TooManyRoutes> => {
597
+ const direction = requestDirection(context, from.id, to.id);
598
+ const { routes, overLimit } = enumerateRoutes(context, from, to);
599
+ if (overLimit) {
600
+ return Result.fail(new TooManyRoutes({ from: from.id, to: to.id, limit: routeLimit }));
601
+ }
602
+
603
+ return Result.succeed(
604
+ routes.map((edges) => ({
605
+ route: routeOf(from, edges),
606
+ edges,
607
+ plan: buildPlan(context, from, to, direction, edges),
608
+ cost: routeCost(edges),
609
+ })),
610
+ );
611
+ };
612
+
613
+ export const resolve = (
614
+ context: Context,
615
+ options: ResolveOptions,
616
+ ): Result.Result<Plan, ResolveError> =>
617
+ Result.gen(function* () {
618
+ const from = yield* lookup(context, options.from);
619
+ const to = yield* lookup(context, options.to);
620
+ const direction = requestDirection(context, from.id, to.id);
621
+ if (direction === "none") {
622
+ return yield* buildPlan(context, from, to, direction, []);
623
+ }
624
+
625
+ const candidates = yield* candidatesBetween(context, from, to);
626
+ if (candidates.length === 0)
627
+ return yield* Result.fail(unsupported(context, from.id, to.id, direction));
628
+
629
+ if (options.route !== undefined) {
630
+ const selected = candidates.find((candidate) => candidate.route.id === options.route);
631
+ if (selected === undefined) {
632
+ return yield* Result.fail(
633
+ new UnknownRoute({
634
+ route: options.route,
635
+ candidates: candidates.map(summaryOf),
636
+ }),
637
+ );
638
+ }
639
+
640
+ return yield* selected.plan;
641
+ }
642
+
643
+ const chosen =
644
+ options.policy === undefined ? candidates : applyPolicy(options.policy, candidates);
645
+ const [only] = chosen;
646
+ if (chosen.length === 1 && only !== undefined) return yield* only.plan;
647
+
648
+ return yield* Result.fail(
649
+ new AmbiguousRoute({
650
+ from: from.id,
651
+ to: to.id,
652
+ candidates: (chosen.length === 0 ? candidates : chosen).map(summaryOf),
653
+ policy: options.policy,
654
+ }),
655
+ );
656
+ });
657
+
658
+ /**
659
+ * A reachable destination and the identifiers of its candidate routes.
660
+ *
661
+ * @since @next
662
+ */
663
+ export type Destination = {
664
+ readonly version: Version;
665
+ readonly routes: ReadonlyArray<string>;
666
+ /**
667
+ * Present when more routes exist than route search explores. `routes` then lists the
668
+ * routes found, cheapest first, and `History.resolve` to this destination fails with
669
+ * `TooManyRoutes`.
670
+ */
671
+ readonly overLimit?: true;
672
+ };
673
+
674
+ const semverOrder = (self: string, that: string): number | undefined => {
675
+ const parsedSelf = SemVer.parse(self);
676
+ const parsedThat = SemVer.parse(that);
677
+ if (Result.isFailure(parsedSelf) || Result.isFailure(parsedThat)) return undefined;
678
+
679
+ return SemVer.Order(parsedSelf.success, parsedThat.success);
680
+ };
681
+
682
+ /**
683
+ * Destinations reachable from a version. Cross-branch destinations are classified by
684
+ * semver order when both identifiers parse, and listed in both directions otherwise.
685
+ * Classification is presentation only; it does not change routing.
686
+ */
687
+ export const destinations = (
688
+ context: Context,
689
+ from: Version,
690
+ kind: "upgrade" | "downgrade",
691
+ ): ReadonlyArray<Destination> => {
692
+ const family = kind === "upgrade" ? families[0] : families[1];
693
+ if (family === undefined) return [];
694
+
695
+ return reachable(context, from.id, family).flatMap((id) => {
696
+ const version = context.versions.get(id);
697
+ if (version === undefined) return [];
698
+
699
+ const direction = requestDirection(context, from.id, id);
700
+ if (direction === "cross-branch") {
701
+ const order = semverOrder(id, from.id);
702
+ if (order !== undefined && (kind === "upgrade" ? order < 0 : order > 0)) return [];
703
+ } else if (direction !== kind) {
704
+ return [];
705
+ }
706
+
707
+ const { routes, overLimit } = enumerateRoutes(context, from, version);
708
+ if (!overLimit) {
709
+ return [{ version, routes: routes.map((edges) => routeOf(from, edges).id) }];
710
+ }
711
+ const cheapest = Arr.sort(
712
+ routes,
713
+ Order.mapInput(Order.Number, (edges: ReadonlyArray<Edge>) => routeCost(edges)),
714
+ );
715
+
716
+ return [
717
+ {
718
+ version,
719
+ routes: cheapest.map((edges) => routeOf(from, edges).id),
720
+ overLimit: true as const,
721
+ },
722
+ ];
723
+ });
724
+ };