Repository navigation
Expand file tree
/
Copy pathauthored-source-codemod.ts
More file actions
2265 lines (2114 loc) · 104 KB
/
Copy pathauthored-source-codemod.ts
File metadata and controls
2265 lines (2114 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* `os migrate meta --write` — write the chain's MECHANICAL edits back into the
* authored sources, at the sites it can prove, and list every other one (#9591).
*
* ## What the chain hands over, and why it is not an edit
*
* `applyMetaMigrations` replays the conversions over the LOADED, normalised
* stack in memory. Each `applied` entry names a conversion and a `path` into
* that stack, plus `from` / `to` DISPLAY strings: a token (`mongo` →
* `mongodb`), a removal (`striped` → `(removed)`) or a rendered shape
* (`'previousPeriod'` → `{ kind: 'previousPeriod' }`). The path's anchor also
* differs per conversion — the renamed-to key, the removed key, or the
* container a key was removed from. So an entry alone says WHERE a conversion
* acted, never WHAT bytes to write, and reading `from` / `to` as edits would
* mean a parser per conversion.
*
* The edit is therefore taken from the chain's own two stacks instead: a
* structural diff of the stack the chain started from against the stack it
* produced, which is exactly — and only — what the conversions changed. Every
* diff change is tied back to the `applied` entries whose paths explain it
* (the site itself, a key inside it, the container of it, or a sibling key in
* the same container), and nothing here knows any conversion by name: a
* conversion added to the chain is covered the day it lands.
*
* ## The one thing this may write: a literal it can PROVE is the source
*
* A diff change is a path into a runtime value. It is written only when that
* path leads, through the authored modules' syntax, to ONE object or array
* literal in ONE project file — and the loaded value agrees with that literal:
*
* - the walk starts at the config module's default export and follows the
* path through object and array literals, module-level `const` bindings,
* relative imports and re-exports, `Object.values(<namespace import>)` (the
* barrel shape the example apps use, in the module namespace's sorted
* order) — also when the project wraps it in a one-line forwarding helper
* of its own, as the `create-objectstack` template's `exportsOf(…)` does
* (`authored-source-wrappers.ts` holds the exact shape) — and the
* `@objectstack/spec` `define*` helpers and `.create` factories, which the
* authored-source load hands their argument through;
* - through `composeStacks([…])`, only into an artifact package body:
* `packages[i].manifest.<key>` is read from input i the way composition
* assembles the body (see {@link packageBodyKeys}), and only when every
* input up to i is a stack literal with a `manifest` and no `packages` of
* its own, so entry i is input i's. A key composed from all the inputs at
* once has no one literal as its source;
* - the literal's own statically known values must match the loaded value at
* that site (a helper that parsed, defaulted or rebuilt it fails the match);
* - every binding the walk crossed must have no reference other than the
* walk's own, so the edit cannot change a second use of the same literal.
*
* Anything else — a computed value, a spread, a call to any other helper, a
* shared binding, a file under `node_modules` or outside the project, a key
* the loader injected, a new value with no literal spelling, a layout an edit
* would have to disturb — is REFUSED, by a named {@link CodemodRefusalKind},
* and the site stays on the list for the author. Nothing is guessed: where the
* walk cannot reach a site, `authored-source-site-finder.ts` may still NAME
* the file and line whose literal content matches it, as a pointer for the
* hand edit — never as a site this module writes.
*
* ## Exactness
*
* Edits are text splices at node positions, so every byte outside an edited
* site — comments, formatting, key order — is unchanged. A key rename keeps
* its value's text (and its comments); a removed property takes its own
* line(s) with it, including a comment on those same lines, and nothing else.
* A conversion's edits are written whole or not at all: when one of its sites
* is refused, its other sites are left too (`entangled`), so no source is ever
* left half-converted. Sites a conversion reports apart but that are one move
* (a trigger and its effects) are written together or not at all too: the
* planner asks the chain, in memory, which units cannot stand alone
* (`authored-source-write-units.ts`) and holds such a pair whole when one of its
* sites is refused. The command re-runs the chain over the written sources and
* puts back only the units the re-run disagrees with (`hold`); a disagreement
* no written unit can be tied to restores every file.
*
* ## The one edit no conversion makes: the declared protocol range (#22219)
*
* The load refuses a manifest whose declared protocol range excludes the
* runtime's major, and its refusal names `migrate meta --from N` as the remedy.
* No conversion moves that range, so a write of the chain's edits alone left
* the refusal standing. The command therefore hands the planner one more edit,
* a {@link RangeRewrite}, and the planner treats it as one more applied entry
* with one more change: it is traced, proved, refused, written, re-checked and
* restored exactly like the chain's own edits. It is reported apart
* (`plan.range`), because it is not one of the chain's `applied` entries.
* Which range is owed, and at which key, is the command's question, not this
* module's.
*
* ## What it never writes
*
* The chain's semantic TODOs (`todos`) are judgment calls; nothing here reads
* them. A site a conversion declines (the `compareTo: { offset: '7d' }` case)
* produces no diff, so it is never written either — it stays exactly where the
* schema verdict and the semantic notice already put it.
*/
import { existsSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
import type TS from 'typescript';
import type { MigrationApplication } from '@objectstack/spec/migrations';
import { packageOwnedCollectionKeys } from './stack-collections.js';
import { syntacticDiagnostics } from './emitted-source-parses.js';
import { forwardingWrapper } from './authored-source-wrappers.js';
import { SiteFinder, type FoundSite } from './authored-source-site-finder.js';
import { entryKey, heldPairs, type HeldPair } from './authored-source-write-units.js';
type Ts = typeof TS;
/** One step of a path into a stack: an object key or an array index. */
export type Segment = string | number;
/**
* Why a site was not written. A closed set: the command prints the kind beside
* the reason, and the pins hold each kind to a fixture that produces it.
*/
export type CodemodRefusalKind =
/** The value or its container is produced by an expression, not written as a literal. */
| 'computed'
/** Built by a call that is not an `@objectstack/spec` `define*` helper or `.create` factory. */
| 'helper'
/** A spread supplies the key (or the array element), or may override it. */
| 'spread'
/** The literal is reachable through a binding something else also references. */
| 'shared'
/** The site lives under `node_modules`, in a package, or outside the project. */
| 'outside-project'
/** The loaded value does not match the literal, so the literal is not provably its source. */
| 'mismatch'
/** The key is in the loaded value but not in the literal: the loader or a helper supplied it. */
| 'injected'
/** The converted value has no literal spelling (a function, `undefined`, a class instance). */
| 'unspellable'
/** The text around the site cannot be edited without touching bytes outside it. */
| 'layout'
/** No edit in the migrated stack could be tied to this entry. */
| 'unattributed'
/**
* Another site of the same conversion (or of one sharing an edit with it) was
* refused — or one of the sites it is written together with
* (`authored-source-write-units.ts`) cannot be written.
*/
| 'entangled'
/**
* It was written, and the re-run of the chain over the written sources did
* not agree with it, so its own edits were put back and the rest of the write
* stands.
*/
| 'unverified';
export interface CodemodRefusal {
kind: CodemodRefusalKind;
/** One sentence naming what blocked the write, in the author's terms. */
reason: string;
/**
* For a `helper` refusal (and an `entangled` one it caused): the call that
* builds the value the walk could not follow, as the source spells it
* (`createServiceStack(…)`) — what the author's stack is built by. Human
* output only; the `--json` face carries `kind` and `reason`.
*/
builder?: string;
}
/** A mechanical change written into a source file. */
export interface WrittenSite {
application: MigrationApplication;
/** Project-relative path of the file written. */
file: string;
/** 1-based line of the site in the file as it was before the write. */
line: number;
}
/** A mechanical change left for the author, with the reason it was not written. */
export interface ManualSite {
application: MigrationApplication;
refusal: CodemodRefusal;
/**
* The elements the site's path indexes into, by the name each goes by,
* outermost first: the path names them by position only
* (`packages[6].manifest.permissions[3]…`). Absent when no indexed element
* on the path carries a name.
*/
items?: PathItem[];
/**
* Where the site is found by content when the walk could not prove its
* source (`authored-source-site-finder.ts`): a pointer for the hand edit,
* never a site written. Human output only.
*/
found?: FoundSite;
}
/** An indexed element on a site's path, and the name it goes by. */
export interface PathItem {
/** The indexed segment as the path spells it, e.g. `permissions[3]`. */
at: string;
name: string;
}
/** One file the plan rewrites: its bytes before and after. */
export interface FileRewrite {
/** Absolute path. */
path: string;
/** Project-relative path, for display. */
file: string;
before: string;
after: string;
}
/**
* The manifest's declared protocol range, moved to the major the migrated
* source targets (#22219). The command decides that it is owed and at which
* key; the planner writes it like any other edit.
*/
export interface RangeRewrite {
/** Where the range sits in the stack, spelled like `applied[].path` (`manifest.engines.protocol`). */
path: string;
/** The range as authored. */
from: string;
/** The range written in its place. */
to: string;
/** The protocol major `to` admits. */
major: number;
}
/** What became of a {@link RangeRewrite}: written at a site, or left for the author with the reason. */
export type RangeOutcome =
| { rewrite: RangeRewrite; status: 'written'; file: string; line: number }
| { rewrite: RangeRewrite; status: 'manual'; refusal: CodemodRefusal };
/** One site of a {@link WritePair}. */
export interface PairSite {
application: MigrationApplication;
/** Where the site would be written: absent on a site that cannot be written. */
at?: { file: string; line: number };
/** Why the site cannot be written: present on the site(s) that hold the pair. */
refusal?: CodemodRefusal;
/** The elements the site's path indexes into, by name, as on a {@link ManualSite}. */
items?: PathItem[];
}
/**
* Sites the chain's re-run shows are written together or not at all — a
* conversion's trigger and its effects, which it reports at unrelated sites —
* left whole because one of them cannot be written
* (`authored-source-write-units.ts`). Every site of it is also on `manual`.
*/
export interface WritePair {
/** Every site of the pair, in chain order. */
sites: PairSite[];
}
export interface AuthoredSourceWritePlan {
/** The project directory every written file lies under (the config's directory). */
projectRoot: string;
rewrites: FileRewrite[];
written: WrittenSite[];
manual: ManualSite[];
/**
* Paths the migrated stack changed that no `applied` entry explains. Never
* written. Expected to be empty: a non-empty list means a conversion rewrote
* a site without reporting it.
*/
unexplained: string[];
/** The declared protocol range, when the input carried a {@link RangeRewrite}. */
range?: RangeOutcome;
/** The pairs left whole because one of their sites cannot be written; absent when there is none. */
pairs?: WritePair[];
}
export interface AuthoredSourceWriteInput {
/** Absolute path of the loaded config module. */
configPath: string;
/** The loaded config (`loadConfig(…, { authoredSource: true }).config`). */
config: Record<string, unknown>;
/** The named exports `loadConfig` merged in as top-level keys. */
namedExports: readonly string[];
/** The stack the chain started from (`normalizeStackInput(config, { convert: false })`). */
normalized: Record<string, unknown>;
/** The stack the chain produced (`result.stack`). */
migrated: Record<string, unknown>;
/** The chain's mechanical applications (`result.applied`), in order. */
applied: readonly MigrationApplication[];
/** The declared protocol range the load refuses, when the command owes it an edit (#22219). */
range?: RangeRewrite;
/**
* The chain, re-run over a stack: given, the plan holds the pairs whose
* written half would not match its report (`authored-source-write-units.ts`)
* before anything is written.
*/
rerun?: (stack: Record<string, unknown>) => readonly MigrationApplication[];
/**
* Entries (by `path (conversionId)`) a re-check over written sources disagreed
* with: their units are left, with that refusal, and everything else is
* planned as before.
*/
hold?: ReadonlyMap<string, CodemodRefusal>;
}
/** Thrown inside a walk; caught at the change it was resolving. */
class Refusal extends Error {
constructor(readonly refusal: CodemodRefusal) {
super(refusal.reason);
}
}
function refuse(kind: CodemodRefusalKind, reason: string, builder?: string): never {
throw new Refusal(builder === undefined ? { kind, reason } : { kind, reason, builder });
}
// ── value helpers ────────────────────────────────────────────────────────────
function isPlainObject(value: unknown): value is Record<string, unknown> {
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
const proto: unknown = Object.getPrototypeOf(value);
return proto === null || Object.getPrototypeOf(proto) === null;
}
/** The keys that carry a value: an own key holding `undefined` reads as absent. */
function presentKeys(value: Record<string, unknown>): string[] {
return Object.keys(value).filter((k) => value[k] !== undefined);
}
function deepEqual(a: unknown, b: unknown): boolean {
if (Object.is(a, b)) return true;
if (Array.isArray(a) && Array.isArray(b)) {
return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
}
if (isPlainObject(a) && isPlainObject(b)) {
const ka = presentKeys(a);
const kb = presentKeys(b);
return ka.length === kb.length && ka.every((k) => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k]));
}
return false;
}
/** Render a path the way the chain's `applied[].path` spells one: `a.b[0].c`. */
export function formatPath(path: readonly Segment[]): string {
let out = '';
for (const seg of path) {
if (typeof seg === 'number') out += `[${seg}]`;
else out += out === '' ? seg : `.${seg}`;
}
return out;
}
/**
* The name an element of a collection goes by: its `name`, else its `id`, else
* — for a composition's package entry, `{ manifest: … }` — its manifest's `id`
* or `name`.
*/
function itemName(element: unknown): string | undefined {
if (!isPlainObject(element)) return undefined;
const own = [element.name, element.id];
const manifest = element.manifest;
const candidates = isPlainObject(manifest) ? [...own, manifest.id, manifest.name] : own;
return candidates.find((c): c is string => typeof c === 'string' && c !== '');
}
/** The named elements `path` (an `applied[].path`) indexes into in `stack`, outermost first. */
export function pathItems(stack: unknown, path: string): PathItem[] {
const items: PathItem[] = [];
let node = stack;
let at = '';
for (const seg of parsePath(path)) {
if (typeof seg === 'number') {
if (!Array.isArray(node) || seg >= node.length) break;
node = node[seg];
at = `${at}[${seg}]`;
const name = itemName(node);
if (name !== undefined) items.push({ at, name });
} else {
if (!isPlainObject(node)) break;
node = node[seg];
at = seg;
}
}
return items;
}
/** Parse an `applied[].path` (`a.b[0].c`) into segments. */
export function parsePath(path: string): Segment[] {
const out: Segment[] = [];
for (const part of path.split('.')) {
const m = /^([^[\]]*)((?:\[\d+\])*)$/.exec(part);
if (!m) {
out.push(part);
continue;
}
if (m[1] !== '') out.push(m[1]!);
for (const idx of m[2]!.matchAll(/\[(\d+)\]/g)) out.push(Number(idx[1]));
}
return out;
}
function isPrefix(prefix: readonly Segment[], path: readonly Segment[]): boolean {
return prefix.length <= path.length && prefix.every((s, i) => s === path[i]);
}
function sameParent(a: readonly Segment[], b: readonly Segment[]): boolean {
return a.length === b.length && a.length > 0 && isPrefix(a.slice(0, -1), b);
}
// ── the structural diff ──────────────────────────────────────────────────────
/** One difference between the stack the chain started from and the one it produced. */
export type StackChange =
| { op: 'set'; path: Segment[]; before: unknown; after: unknown }
| { op: 'delete'; path: Segment[]; before: unknown }
| { op: 'add'; path: Segment[]; after: unknown }
/** Elements dropped from an array; `path` is the array, `indices` are into `before`. */
| { op: 'remove'; path: Segment[]; indices: number[]; before: unknown[] };
/** `small` is `big` with some elements taken out, in order — the dropped indices, or null. */
function droppedIndices(big: readonly unknown[], small: readonly unknown[]): number[] | null {
const dropped: number[] = [];
let j = 0;
for (let i = 0; i < big.length; i++) {
if (j < small.length && deepEqual(big[i], small[j])) j++;
else dropped.push(i);
}
return j === small.length ? dropped : null;
}
/**
* The minimal structural difference between two stacks, as the conversions
* made it. Copy-on-write conversions keep every untouched subtree's identity,
* so the walk only descends where something changed.
*/
export function diffStacks(before: unknown, after: unknown, path: Segment[] = [], out: StackChange[] = []): StackChange[] {
if (Object.is(before, after)) return out;
if (isPlainObject(before) && isPlainObject(after)) {
const kb = presentKeys(before);
const ka = presentKeys(after);
for (const k of kb) {
if (!ka.includes(k)) out.push({ op: 'delete', path: [...path, k], before: before[k] });
else diffStacks(before[k], after[k], [...path, k], out);
}
for (const k of ka) {
if (!kb.includes(k)) out.push({ op: 'add', path: [...path, k], after: after[k] });
}
return out;
}
if (Array.isArray(before) && Array.isArray(after)) {
if (before.length === after.length) {
for (let i = 0; i < before.length; i++) diffStacks(before[i], after[i], [...path, i], out);
return out;
}
const dropped = after.length < before.length ? droppedIndices(before, after) : null;
if (dropped) out.push({ op: 'remove', path, indices: dropped, before });
else out.push({ op: 'set', path, before, after });
return out;
}
if (deepEqual(before, after)) return out;
out.push({ op: 'set', path, before, after });
return out;
}
// ── attribution: which applied entries explain which changes ────────────────
/**
* The rules that tie a change to the applied entries explaining it, tried in
* order; a change takes the entries of the FIRST rule that finds any, so a
* looser rule never widens an entry that already has its own edits:
*
* 1. the change is the site, inside it, or a container replaced around it;
* 2. the change is a sibling key of the site — a rename's old key, where the
* entry names the new one;
* 3. a MOVE between two containers of one subject (`node.config.x` →
* `node.waitEventConfig.y`): the entry names the destination, the change is
* the source, and both sit under the subject two steps above the entry.
*/
const ATTRIBUTION_RULES: ReadonlyArray<(applied: readonly Segment[], change: readonly Segment[]) => boolean> = [
(applied, change) => isPrefix(applied, change) || isPrefix(change, applied),
(applied, change) => sameParent(applied, change),
(applied, change) => applied.length >= 3 && isPrefix(applied.slice(0, -2), change),
];
/** The applied entries (by index) that explain a change at `change`, by {@link ATTRIBUTION_RULES}. */
function explainingEntries(appliedPaths: readonly (readonly Segment[])[], change: readonly Segment[]): number[] {
for (const rule of ATTRIBUTION_RULES) {
const hits = appliedPaths.flatMap((p, i) => (rule(p, change) ? [i] : []));
if (hits.length > 0) return hits;
}
return [];
}
// ── the authored module graph, read statically ──────────────────────────────
interface SourceFileRec {
readonly path: string;
readonly text: string;
readonly sf: TS.SourceFile;
}
/** What the walk knows about a value, read from the source rather than run. */
type SNode =
| { k: 'object'; file: SourceFileRec; node: TS.ObjectLiteralExpression }
| { k: 'array'; file: SourceFileRec; node: TS.ArrayLiteralExpression }
/** A sequence the authored code assembles (`Object.values(ns)`, an array with spreads). */
| { k: 'list'; items: Array<(trail: Trail) => SNode>; describe: string }
| { k: 'namespace'; file: SourceFileRec }
| { k: 'scalar'; file: SourceFileRec; node: TS.Expression }
/** A binding imported from `@objectstack/spec` (`name` is the imported name, `*` a namespace). */
| { k: 'spec'; name: string }
| { k: 'specMember'; owner: string; member: string }
/**
* A `composeStacks([…], …)` call, with its input list as read from the
* source. Its artifact's `packages[i].manifest` is input i's assembled body;
* every other key is composed from all the inputs at once.
*/
| { k: 'composed'; describe: string; inputs: Extract<SNode, { k: 'array' } | { k: 'list' }> }
/** The `packages` list of a composition. */
| { k: 'composedPackages'; describe: string; inputs: Extract<SNode, { k: 'array' } | { k: 'list' }> }
/** One entry of it, `{ manifest: <body> }`, and the body itself — both input `input`'s. */
| { k: 'composedEntry'; describe: string; input: Extract<SNode, { k: 'object' }> }
| { k: 'composedBody'; describe: string; input: Extract<SNode, { k: 'object' }> };
/** A module-level binding the walk crossed, and how to tell its references apart. */
interface BindingRef {
readonly file: SourceFileRec;
readonly name: string;
}
/**
* What one walk crossed: every binding it resolved, and every identifier it
* resolved them THROUGH. A binding whose references are not all in `uses` is
* referenced by something the walk did not take, so its literal is shared.
*/
class Trail {
readonly bindings = new Map<string, BindingRef>();
readonly uses = new Set<string>();
}
/**
* The two patterns the authored-source shim (`loadConfig`'s `authoredSource`,
* `utils/config.ts`) wraps by: an `@objectstack/spec` entrypoint, and a
* `define*` export of it. A call the shim makes tolerant hands its argument
* through when the current schema refuses it, so the walk may follow the
* argument; when the schema accepts it, the subset check below catches any
* default or transform the real helper applied.
*
* `<spec export>.create(…)` is followed on the same terms: every `create` an
* `@objectstack/spec` entrypoint exports either validates (and is wrapped by
* the shim's `STRICT_AUTHORING_FACTORIES`) or returns its argument untouched —
* `test/migrate-meta-strict-factories.test.ts` holds that list to the spec
* surface in both directions.
*/
const SPEC_SPECIFIER_RE = /^@objectstack\/spec(?:\/[\w./-]+)?$/;
const DEFINE_HELPER_RE = /^define[A-Z]/;
/** The stack composer, followed into the package bodies it assembles and nowhere else. */
const STACK_COMPOSER = 'composeStacks';
/**
* The keys a package body takes from its input stack rather than from the
* input's `manifest`: composition builds a body as `{ ...input.manifest }` and
* then writes each package-owned collection the input carries over it. So a
* body key is read from the input when it is one of these and the input
* writes it, and from the input's `manifest` otherwise.
*/
let cachedPackageBodyKeys: ReadonlySet<string> | undefined;
function packageBodyKeys(): ReadonlySet<string> {
return (cachedPackageBodyKeys ??= new Set(packageOwnedCollectionKeys()));
}
const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/;
const TS_EXT_FOR_JS: Readonly<Record<string, readonly string[]>> = {
'.js': ['.ts', '.tsx', '.js'],
'.jsx': ['.tsx', '.jsx'],
'.mjs': ['.mts', '.mjs'],
'.cjs': ['.cts', '.cjs'],
};
const PROBE_EXTS = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];
const UNKNOWN = Symbol('unknown');
/** A value read from source, or {@link UNKNOWN} where the source does not say. */
type Readable = unknown;
class SourceGraph {
private readonly files = new Map<string, SourceFileRec>();
private readonly exportNameCache = new Map<string, Set<string>>();
constructor(
private readonly ts: Ts,
readonly projectRoot: string,
) {}
rel(file: SourceFileRec | string): string {
const p = typeof file === 'string' ? file : file.path;
const r = relative(this.projectRoot, p);
return r === '' ? p : r.split(sep).join('/');
}
file(path: string): SourceFileRec {
const hit = this.files.get(path);
if (hit) return hit;
const text = readFileSync(path, 'utf8');
const kind = /\.[cm]?tsx?$/.test(path)
? (path.endsWith('x') ? this.ts.ScriptKind.TSX : this.ts.ScriptKind.TS)
: (path.endsWith('x') ? this.ts.ScriptKind.JSX : this.ts.ScriptKind.JS);
const sf = this.ts.createSourceFile(path, text, this.ts.ScriptTarget.Latest, true, kind);
const rec = { path, text, sf };
this.files.set(path, rec);
return rec;
}
/** Every file this graph has read — the population a reference count looks across. */
loaded(): SourceFileRec[] {
return [...this.files.values()];
}
/** A RELATIVE specifier resolved the way the bundler does; `null` for a package specifier. */
resolveModule(from: SourceFileRec, specifier: string): string | null {
if (!specifier.startsWith('.') && !isAbsolute(specifier)) return null;
const base = resolve(dirname(from.path), specifier);
const ext = /\.[cm]?jsx?$/.exec(base)?.[0];
const candidates: string[] = [];
if (ext && TS_EXT_FOR_JS[ext]) {
const stem = base.slice(0, -ext.length);
for (const e of TS_EXT_FOR_JS[ext]!) candidates.push(stem + e);
} else {
candidates.push(base);
for (const e of PROBE_EXTS) candidates.push(base + e);
for (const e of PROBE_EXTS) candidates.push(resolve(base, `index${e}`));
}
for (const c of candidates) {
if (existsSync(c) && statSync(c).isFile()) return c;
}
return null;
}
/** Read every file reachable from `entry` through relative imports and re-exports. */
crawl(entry: string): void {
const queue = [entry];
const seen = new Set<string>();
while (queue.length > 0) {
const path = queue.shift()!;
if (seen.has(path)) continue;
seen.add(path);
const rec = this.file(path);
for (const stmt of rec.sf.statements) {
const spec = (this.ts.isImportDeclaration(stmt) || this.ts.isExportDeclaration(stmt))
&& stmt.moduleSpecifier && this.ts.isStringLiteral(stmt.moduleSpecifier)
? stmt.moduleSpecifier.text
: undefined;
if (spec === undefined) continue;
const target = this.resolveModule(rec, spec);
if (target) queue.push(target);
}
}
}
// ── reading one expression ──
private unwrap(expr: TS.Expression): TS.Expression {
const ts = this.ts;
let e = expr;
for (;;) {
if (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e)
|| ts.isTypeAssertionExpression(e) || ts.isNonNullExpression(e)) {
e = e.expression;
continue;
}
return e;
}
}
/** The literal node an initializer is, under `as const` / parentheses — or undefined. */
literalNode(expr: TS.Expression): TS.Expression | undefined {
const e = this.unwrap(expr);
return this.isScalar(e) || this.ts.isObjectLiteralExpression(e) || this.ts.isArrayLiteralExpression(e) ? e : undefined;
}
private isScalar(e: TS.Expression): boolean {
const ts = this.ts;
return ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e) || ts.isNumericLiteral(e)
|| e.kind === ts.SyntaxKind.TrueKeyword || e.kind === ts.SyntaxKind.FalseKeyword
|| e.kind === ts.SyntaxKind.NullKeyword
|| (ts.isPrefixUnaryExpression(e) && e.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(e.operand));
}
private scalarValue(e: TS.Expression): unknown {
const ts = this.ts;
if (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e)) return e.text;
if (ts.isNumericLiteral(e)) return Number(e.text.replace(/_/g, ''));
if (e.kind === ts.SyntaxKind.TrueKeyword) return true;
if (e.kind === ts.SyntaxKind.FalseKeyword) return false;
if (e.kind === ts.SyntaxKind.NullKeyword) return null;
if (ts.isPrefixUnaryExpression(e) && ts.isNumericLiteral(e.operand)) return -Number(e.operand.text.replace(/_/g, ''));
return UNKNOWN;
}
/** A property's key as the runtime spells it, or undefined when it is computed. */
propName(name: TS.PropertyName): string | undefined {
const ts = this.ts;
if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name)) return name.text;
if (ts.isNumericLiteral(name)) return String(Number(name.text.replace(/_/g, '')));
if (ts.isComputedPropertyName(name)) {
const e = this.unwrap(name.expression);
if (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e)) return e.text;
}
return undefined;
}
/**
* The value a literal spells, with whatever it cannot know left out: an
* object keeps only the keys written after its last spread with a plain
* name, an array marks an unreadable element UNKNOWN.
*/
partialValue(expr: TS.Expression): Readable {
const ts = this.ts;
const e = this.unwrap(expr);
if (this.isScalar(e)) return this.scalarValue(e);
if (ts.isArrayLiteralExpression(e)) {
if (e.elements.some((el) => ts.isSpreadElement(el) || ts.isOmittedExpression(el))) return UNKNOWN;
return e.elements.map((el) => this.partialValue(el));
}
if (ts.isObjectLiteralExpression(e)) {
const out: Record<string, unknown> = {};
const lastSpread = lastSpreadIndex(ts, e);
e.properties.forEach((p, i) => {
if (i < lastSpread || !ts.isPropertyAssignment(p)) return;
const name = this.propName(p.name);
if (name === undefined) return;
const v = this.partialValue(p.initializer);
if (v !== UNKNOWN) out[name] = v;
});
return out;
}
return UNKNOWN;
}
/** The value a literal spells when every part of it is known, else UNKNOWN. */
exactValue(expr: TS.Expression): Readable {
const ts = this.ts;
const e = this.unwrap(expr);
if (this.isScalar(e)) return this.scalarValue(e);
if (ts.isArrayLiteralExpression(e)) {
const out: unknown[] = [];
for (const el of e.elements) {
if (ts.isSpreadElement(el) || ts.isOmittedExpression(el)) return UNKNOWN;
const v = this.exactValue(el);
if (v === UNKNOWN) return UNKNOWN;
out.push(v);
}
return out;
}
if (ts.isObjectLiteralExpression(e)) {
const out: Record<string, unknown> = {};
for (const p of e.properties) {
if (!ts.isPropertyAssignment(p)) return UNKNOWN;
const name = this.propName(p.name);
if (name === undefined) return UNKNOWN;
const v = this.exactValue(p.initializer);
if (v === UNKNOWN) return UNKNOWN;
out[name] = v;
}
return out;
}
return UNKNOWN;
}
// ── following a value through the authored modules ──
private identifierId(file: SourceFileRec, id: TS.Node): string {
return `${file.path}#${id.getStart(file.sf)}`;
}
/** Resolve an expression to what the walk can know about its value; throws a {@link Refusal}. */
resolveExpr(file: SourceFileRec, expr: TS.Expression, trail: Trail): SNode {
const ts = this.ts;
const e = this.unwrap(expr);
if (ts.isObjectLiteralExpression(e)) return { k: 'object', file, node: e };
if (ts.isArrayLiteralExpression(e)) {
if (!e.elements.some((el) => ts.isSpreadElement(el) || ts.isOmittedExpression(el))) {
return { k: 'array', file, node: e };
}
return this.expandArray(file, e, trail);
}
if (this.isScalar(e)) return { k: 'scalar', file, node: e };
if (ts.isIdentifier(e)) {
trail.uses.add(this.identifierId(file, e));
return this.resolveIdentifier(file, e.text, trail);
}
if (ts.isPropertyAccessExpression(e)) {
const base = this.resolveExpr(file, e.expression, trail);
const member = e.name.text;
if (base.k === 'namespace') return this.resolveExport(base.file, member, trail, new Set());
if (base.k === 'spec') return { k: 'specMember', owner: base.name, member };
if (base.k === 'object') {
const prop = this.findProp(base, member);
return this.resolveExpr(base.file, this.valueOf(prop), trail);
}
refuse('computed', `\`${this.snippet(file, e)}\` reads a member of a value that is not written as a literal`);
}
if (ts.isCallExpression(e)) return this.resolveCall(file, e, trail);
refuse('computed', `the value is the expression \`${this.snippet(file, e)}\`, not a literal`);
}
private resolveCall(file: SourceFileRec, call: TS.CallExpression, trail: Trail): SNode {
const ts = this.ts;
const callee = this.unwrap(call.expression);
const args = call.arguments;
if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression)
&& callee.expression.text === 'Object' && callee.name.text === 'values'
&& args.length === 1 && !ts.isSpreadElement(args[0]!)) {
return this.objectValues(file, args[0]!, trail);
}
// The project's own `Object.values` wrapper (the template's `exportsOf`)
// reads as the call it wraps (`./authored-source-wrappers.ts`).
if (ts.isIdentifier(callee) && args.length === 1 && !ts.isSpreadElement(args[0]!)) {
const wraps = forwardingWrapper(ts, this, file, callee.text);
if (wraps === 'values') return this.objectValues(file, args[0]!, trail, `${callee.text}(${this.snippet(file, args[0]!)})`);
if (wraps === 'identity') return this.resolveExpr(file, args[0]!, trail);
}
let target: SNode | undefined;
try {
target = this.resolveExpr(file, callee, trail);
} catch (error) {
if (!(error instanceof Refusal)) throw error;
}
if (target?.k === 'spec' && target.name === STACK_COMPOSER) {
const describe = `${this.snippet(file, callee)}(…)`;
if (args.length < 1 || ts.isSpreadElement(args[0]!)) {
refuse('helper', `\`${describe}\` is not called with a list of stacks`);
}
const inputs = this.resolveExpr(file, args[0]!, trail);
if (inputs.k !== 'array' && inputs.k !== 'list') {
refuse('computed', `the stacks \`${describe}\` composes are not written as an array`);
}
return { k: 'composed', describe, inputs };
}
const transparent = target !== undefined
&& ((target.k === 'spec' && DEFINE_HELPER_RE.test(target.name))
|| (target.k === 'specMember' && target.member === 'create'));
if (!transparent) {
const builder = `${this.snippet(file, callee)}(…)`;
refuse('helper', `the value is built by \`${builder}\`, not written as a literal`, builder);
}
if (args.length < 1 || ts.isSpreadElement(args[0]!)) {
refuse('helper', `\`${this.snippet(file, callee)}(…)\` is not called with a literal argument`);
}
return this.resolveExpr(file, args[0]!, trail);
}
private objectValues(
file: SourceFileRec,
arg: TS.Expression,
trail: Trail,
describe = `Object.values(${this.snippet(file, arg)})`,
): SNode {
const base = this.resolveExpr(file, arg, trail);
if (base.k === 'namespace') {
// A module namespace enumerates its exports in sorted (code unit) order —
// the order the bundler's namespace object, and the spec, both use.
const names = [...this.exportNames(base.file)].sort();
return {
k: 'list',
describe,
items: names.map((n) => (t: Trail) => this.resolveExport(base.file, n, t, new Set())),
};
}
if (base.k === 'object') {
const ts = this.ts;
const props = base.node.properties;
if (props.some((p) => !ts.isPropertyAssignment(p) && !ts.isShorthandPropertyAssignment(p))) {
refuse('spread', `\`${describe}\` reads an object with a spread or a method`);
}
const named = props.map((p) => ({ p, name: this.propName((p as TS.PropertyAssignment).name) }));
if (named.some((n) => n.name === undefined) || new Set(named.map((n) => n.name)).size !== named.length) {
refuse('computed', `\`${describe}\` reads an object with a computed or repeated key`);
}
// Object.keys order: integer-like keys ascending, then the rest as written.
const isIndex = (k: string) => /^(0|[1-9]\d*)$/.test(k) && Number(k) < 2 ** 32 - 1;
const ordered = [
...named.filter((n) => isIndex(n.name!)).sort((a, b) => Number(a.name) - Number(b.name)),
...named.filter((n) => !isIndex(n.name!)),
];
return {
k: 'list',
describe,
items: ordered.map(({ p }) => (t: Trail) => this.resolveExpr(base.file, this.valueOf(p as TS.ObjectLiteralElementLike), t)),
};
}
refuse('computed', `\`${describe}\` reads a value that is not a module namespace or an object literal`);
}
private expandArray(file: SourceFileRec, node: TS.ArrayLiteralExpression, trail: Trail): SNode {
const ts = this.ts;
const items: Array<(t: Trail) => SNode> = [];
for (const el of node.elements) {
if (ts.isOmittedExpression(el)) {
items.push(() => refuse('computed', 'the array has a hole at this index'));
} else if (ts.isSpreadElement(el)) {
const source = this.resolveExpr(file, el.expression, trail);
if (source.k === 'array') {
for (const inner of source.node.elements) items.push((t) => this.resolveExpr(source.file, inner, t));
} else if (source.k === 'list') {
items.push(...source.items);
} else {
refuse('spread', `\`...${this.snippet(file, el.expression)}\` spreads a value that is not a literal array`);
}
} else {
items.push((t) => this.resolveExpr(file, el, t));
}
}
return { k: 'list', items, describe: 'an array literal with spreads' };
}
private resolveIdentifier(file: SourceFileRec, name: string, trail: Trail): SNode {
const ts = this.ts;
for (const stmt of file.sf.statements) {
if (ts.isVariableStatement(stmt)) {
for (const decl of stmt.declarationList.declarations) {
if (!ts.isIdentifier(decl.name) || decl.name.text !== name) continue;
if (!(stmt.declarationList.flags & ts.NodeFlags.Const)) {
refuse('computed', `\`${name}\` is a \`let\`/\`var\` binding, which can be reassigned`);
}
if (!decl.initializer) refuse('computed', `\`${name}\` has no initializer`);
trail.bindings.set(`${file.path}#${name}`, { file, name });
return this.resolveExpr(file, decl.initializer, trail);
}
} else if (ts.isImportDeclaration(stmt) && stmt.importClause && ts.isStringLiteral(stmt.moduleSpecifier)) {
const clause = stmt.importClause;
const specifier = stmt.moduleSpecifier.text;
let imported: string | undefined;
if (clause.name?.text === name) imported = 'default';
const bindings = clause.namedBindings;
if (bindings && ts.isNamespaceImport(bindings) && bindings.name.text === name) imported = '*';
if (bindings && ts.isNamedImports(bindings)) {
for (const el of bindings.elements) {
if (el.name.text === name) {
if (el.isTypeOnly) refuse('computed', `\`${name}\` is a type-only import`);
imported = (el.propertyName ?? el.name).text;
}
}
}
if (imported === undefined) continue;
if (clause.isTypeOnly) refuse('computed', `\`${name}\` is a type-only import`);
if (SPEC_SPECIFIER_RE.test(specifier)) return { k: 'spec', name: imported };
const target = this.resolveModule(file, specifier);
if (!target) refuse('outside-project', `\`${name}\` is imported through ${unresolved(specifier)}`);
const mod = this.file(target);
if (imported === '*') return { k: 'namespace', file: mod };
return this.resolveExport(mod, imported, trail, new Set());
} else if ((ts.isFunctionDeclaration(stmt) || ts.isClassDeclaration(stmt) || ts.isEnumDeclaration(stmt))
&& stmt.name?.text === name) {
refuse('computed', `\`${name}\` is a ${ts.isFunctionDeclaration(stmt) ? 'function' : ts.isClassDeclaration(stmt) ? 'class' : 'enum'}, not a literal`);
}
}
refuse('computed', `\`${name}\` is not a module-level binding of ${this.rel(file)}`);
}
/** Resolve export `name` of `mod` to the value it carries; throws a {@link Refusal}. */
resolveExport(mod: SourceFileRec, name: string, trail: Trail, visiting: Set<string>): SNode {
const ts = this.ts;
const key = `${mod.path}#${name}`;
if (visiting.has(key)) refuse('computed', `\`${name}\` is re-exported in a cycle`);
visiting.add(key);
const stars: SourceFileRec[] = [];
for (const stmt of mod.sf.statements) {
if (ts.isVariableStatement(stmt) && hasModifier(ts, stmt, ts.SyntaxKind.ExportKeyword)) {
for (const decl of stmt.declarationList.declarations) {
if (ts.isIdentifier(decl.name) && decl.name.text === name) return this.resolveIdentifier(mod, name, trail);
}
} else if (ts.isExportAssignment(stmt) && !stmt.isExportEquals && name === 'default') {
trail.bindings.set(`${mod.path}#default`, { file: mod, name: 'default' });
return this.resolveExpr(mod, stmt.expression, trail);
} else if ((ts.isFunctionDeclaration(stmt) || ts.isClassDeclaration(stmt))
&& hasModifier(ts, stmt, ts.SyntaxKind.ExportKeyword)
&& (hasModifier(ts, stmt, ts.SyntaxKind.DefaultKeyword) ? 'default' : stmt.name?.text) === name) {
refuse('computed', `\`${name}\` exported by ${this.rel(mod)} is a ${ts.isFunctionDeclaration(stmt) ? 'function' : 'class'}, not a literal`);
} else if (ts.isExportDeclaration(stmt) && !stmt.isTypeOnly) {
const specifier = stmt.moduleSpecifier && ts.isStringLiteral(stmt.moduleSpecifier) ? stmt.moduleSpecifier.text : undefined;
const clause = stmt.exportClause;
if (clause && ts.isNamedExports(clause)) {
for (const el of clause.elements) {
if (el.isTypeOnly || el.name.text !== name) continue;
const local = (el.propertyName ?? el.name).text;
if (specifier === undefined) return this.resolveIdentifier(mod, local, trail);
if (SPEC_SPECIFIER_RE.test(specifier)) return { k: 'spec', name: local };
const target = this.resolveModule(mod, specifier);
if (!target) refuse('outside-project', `\`${name}\` is re-exported from ${unresolved(specifier)}`);
return this.resolveExport(this.file(target), local, trail, visiting);
}
} else if (clause && ts.isNamespaceExport(clause) && clause.name.text === name && specifier !== undefined) {
const target = this.resolveModule(mod, specifier);
if (!target) refuse('outside-project', `\`${name}\` re-exports ${unresolved(specifier)}`);
return { k: 'namespace', file: this.file(target) };
} else if (!clause && specifier !== undefined && name !== 'default') {
const target = this.resolveModule(mod, specifier);
if (target) stars.push(this.file(target));
}
}
}
const hits = stars.filter((s) => this.exportNames(s).has(name));
if (hits.length === 1) return this.resolveExport(hits[0]!, name, trail, visiting);
if (hits.length > 1) refuse('computed', `\`${name}\` is exported by more than one \`export *\` of ${this.rel(mod)}`);
refuse('computed', `\`${name}\` is not a runtime export of ${this.rel(mod)}`);
}