@hamur/adapter-angular 0.0.2 → 0.0.4

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.
@@ -152,6 +152,7 @@ function selectorOf(selectors) {
152
152
  // packages/adapter-angular/src/compile.ts
153
153
  var COMPILE_ID = /^(?!.*[\\/]node_modules[\\/]).*\.[cm]?ts$/;
154
154
  var LINK_ID = /[\\/]node_modules[\\/](?:.+\.m?js|(?:.+[\\/])?@hamur[\\/][^\\/]+[\\/]src[\\/].+\.ts)$/;
155
+ var INSTALLED = /[\\/]node_modules[\\/]/;
155
156
  var SCRIPT = /\.[cm]?ts$/;
156
157
  var DECORATED = /^\s*@(?:Component|Directive|Pipe|NgModule|Injectable)\s*\(/m;
157
158
  var ENTRY = /^(?:(pages|layouts)\/.+|(app|error))\.[cm]?ts$/;
@@ -247,9 +248,18 @@ function workspaceRoot(rootDir, base) {
247
248
  const root = [...modulePackages(rootDir), real(dirname(import.meta.dir + "/../../src"))].reduce(commonDir, real(rootDir));
248
249
  return { rootDir: root, ...base.rootDirs ? { rootDirs: [...base.rootDirs, root] } : {} };
249
250
  }
250
- function rootNames(rootDir) {
251
+ function generatedTypes(buildDir) {
252
+ const file = join(buildDir, "types/hamur.d.ts");
253
+ return existsSync(file) ? [file] : [];
254
+ }
255
+ function rootNames({ rootDir, buildDir }) {
251
256
  const app = join(rootDir, "app");
252
- return [...existsSync(app) ? scripts(app) : [], ...ownComponents(), ...moduleComponents(rootDir)];
257
+ return [
258
+ ...existsSync(app) ? scripts(app) : [],
259
+ ...ownComponents(),
260
+ ...moduleComponents(rootDir),
261
+ ...generatedTypes(buildDir)
262
+ ];
253
263
  }
254
264
  var shown = (rootDir, file) => relative(rootDir, file).split(sep).join("/");
255
265
  function diagnosticProblem(typescript, diagnostic, rootDir) {
@@ -363,16 +373,8 @@ function compilerHost(ng, options, setup) {
363
373
  };
364
374
  return host;
365
375
  }
366
- function problemsOf(ng, program, rootDir, check) {
367
- const problems = [
368
- ...program.getNgOptionDiagnostics(),
369
- ...program.getNgStructuralDiagnostics(),
370
- ...program.getNgSemanticDiagnostics()
371
- ].filter((diagnostic) => diagnostic.category === ng.ts.DiagnosticCategory.Error).map((diagnostic) => diagnosticProblem(ng.ts, diagnostic, rootDir));
372
- if (check)
373
- problems.push(...check(program.getTsProgram()));
374
- return problems;
375
- }
376
+ var errorsOf = (ng, diagnostics, rootDir) => diagnostics.filter((diagnostic) => diagnostic.category === ng.ts.DiagnosticCategory.Error).map((diagnostic) => diagnosticProblem(ng.ts, diagnostic, rootDir));
377
+ var programErrors = (ng, program, rootDir) => errorsOf(ng, [...program.getNgOptionDiagnostics(), ...program.getNgStructuralDiagnostics()], rootDir);
376
378
  function emitOnly(program, emits) {
377
379
  program.emit({
378
380
  emitCallback: ({
@@ -385,11 +387,43 @@ function emitOnly(program, emits) {
385
387
  }) => targetSourceFile && !emits(real(targetSourceFile.fileName)) ? { emitSkipped: true, diagnostics: [] } : tsProgram.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)
386
388
  });
387
389
  }
388
- async function emitProgram(ng, rootDir, roots, options, preprocessStyle, emits, check) {
390
+ function reuseSourceFiles(host, parsed, stampOfFile) {
391
+ const read = host.getSourceFile.bind(host);
392
+ host.getSourceFile = (fileName, language, onError, fresh) => {
393
+ const stamp = stampOfFile(fileName);
394
+ const hit = parsed.get(fileName);
395
+ if (hit && hit.stamp === stamp && !fresh)
396
+ return hit.file;
397
+ const file = read(fileName, language, onError, fresh);
398
+ if (!file)
399
+ return file;
400
+ const same = hit && !fresh && hit.file.text === file.text;
401
+ parsed.set(fileName, { stamp, file: same ? hit.file : file });
402
+ return same ? hit.file : file;
403
+ };
404
+ }
405
+ var buildSources = new WeakMap;
406
+ function releaseBuildSources() {
407
+ buildSources = new WeakMap;
408
+ }
409
+ function sourcesOf(ng) {
410
+ let parsed = buildSources.get(ng);
411
+ if (!parsed)
412
+ buildSources.set(ng, parsed = new Map);
413
+ return parsed;
414
+ }
415
+ async function emitProgram(ng, rootDir, roots, options, preprocessStyle, emits, parsed, check) {
389
416
  const files = new Map;
390
- const program = new ng.cli.NgtscProgram(roots, options, compilerHost(ng, options, { rootDir, preprocessStyle, files }));
417
+ const host = compilerHost(ng, options, { rootDir, preprocessStyle, files });
418
+ if (parsed)
419
+ reuseSourceFiles(host, parsed, stampOf);
420
+ const program = new ng.cli.NgtscProgram(roots, options, host);
391
421
  await program.loadNgStructureAsync();
392
- const problems = problemsOf(ng, program, rootDir, check);
422
+ const problems = [
423
+ ...programErrors(ng, program, rootDir),
424
+ ...errorsOf(ng, program.getNgSemanticDiagnostics(), rootDir),
425
+ ...check?.(program.getTsProgram()) ?? []
426
+ ];
393
427
  if (problems.length)
394
428
  throw new Error(problems.map((problem) => problem.line).join(`
395
429
  `));
@@ -437,7 +471,7 @@ function compilerOptions(typescript, ctx) {
437
471
  }
438
472
  var programs = new Map;
439
473
  function angularProgram(ctx) {
440
- const roots = rootNames(ctx.rootDir);
474
+ const roots = rootNames(ctx);
441
475
  const stamp = roots.map((file) => {
442
476
  const stat = statSync(file);
443
477
  return `${file}:${stat.size}:${stat.mtimeMs}`;
@@ -449,7 +483,7 @@ function angularProgram(ctx) {
449
483
  return hit.files;
450
484
  const app = `${real(ctx.rootDir)}${sep}`;
451
485
  const own = new Set([...ownComponents(), ...moduleComponents(ctx.rootDir)].map(real));
452
- const files = loadAngular(ctx.rootDir).then((ng) => emitProgram(ng, ctx.rootDir, roots, compilerOptions(ng.ts, ctx), ctx.preprocessStyle, (path) => path.startsWith(app) || own.has(path), (program) => defaultExportErrors(ng.ts, program, ctx.rootDir, roots)));
486
+ const files = loadAngular(ctx.rootDir).then((ng) => emitProgram(ng, ctx.rootDir, roots, compilerOptions(ng.ts, ctx), ctx.preprocessStyle, (path) => path.startsWith(app) && !INSTALLED.test(path) || own.has(path), ctx.dev ? undefined : sourcesOf(ng), (program) => defaultExportErrors(ng.ts, program, ctx.rootDir, roots)));
453
487
  programs.set(key, { stamp, files });
454
488
  return files;
455
489
  }
@@ -500,10 +534,12 @@ class AngularDevProgram {
500
534
  own;
501
535
  files = new Map;
502
536
  texts = new Map;
537
+ fileNames = new Map;
503
538
  resources = new Map;
504
539
  importers = new Map;
505
540
  sourceFiles = new Map;
506
541
  resourcesOf = new Map;
542
+ checked = new Map;
507
543
  broken = new Set;
508
544
  options;
509
545
  program;
@@ -519,7 +555,7 @@ class AngularDevProgram {
519
555
  this.own = new Set([...ownComponents(), ...moduleComponents(ctx.rootDir)].map(real));
520
556
  }
521
557
  emits(path) {
522
- return path.startsWith(this.root) && !path.startsWith(this.server) || this.own.has(path);
558
+ return path.startsWith(this.root) && !path.startsWith(this.server) && !INSTALLED.test(path) || this.own.has(path);
523
559
  }
524
560
  async load(path) {
525
561
  if (!this.emits(path))
@@ -537,12 +573,24 @@ class AngularDevProgram {
537
573
  throw this.failure;
538
574
  if (!this.texts.has(path))
539
575
  return;
540
- const problems = this.problems.filter((problem) => problem.file === undefined || problem.file === path || this.reads(path, problem.file));
576
+ const problems = await this.problemsOf(path);
541
577
  if (problems.length)
542
578
  throw new Error(problems.map((problem) => problem.line).join(`
543
579
  `));
544
580
  return this.files.get(path);
545
581
  }
582
+ async problemsOf(path) {
583
+ const { program } = this;
584
+ const fileName = this.fileNames.get(path);
585
+ let own = this.checked.get(path);
586
+ if (!own && program && fileName !== undefined) {
587
+ const ng = await loadAngular(this.ctx.rootDir);
588
+ own = errorsOf(ng, program.getNgSemanticDiagnostics(fileName), this.ctx.rootDir);
589
+ if (program === this.program)
590
+ this.checked.set(path, own);
591
+ }
592
+ return [...this.problems.filter((problem) => problem.file === undefined || problem.file === path), ...own ?? []];
593
+ }
546
594
  stale(path, text) {
547
595
  const compiled = this.texts.get(path);
548
596
  if (compiled !== undefined)
@@ -574,7 +622,10 @@ class AngularDevProgram {
574
622
  await next;
575
623
  const components = this.dependentsOf(path);
576
624
  const program = this.program;
577
- const failing = this.failure || !program ? components : components.filter((component) => this.problems.some((problem) => problem.file === component || !!problem.file && this.reads(component, problem.file)));
625
+ const failing = [];
626
+ for (const component of components)
627
+ if (this.failure || !program || (await this.problemsOf(component)).length)
628
+ failing.push(component);
578
629
  if (failing.length || !program) {
579
630
  for (const component of failing)
580
631
  this.broken.add(component);
@@ -628,7 +679,7 @@ class AngularDevProgram {
628
679
  async build(modified) {
629
680
  const ng = await loadAngular(this.ctx.rootDir);
630
681
  const options = this.options ??= compilerOptions(ng.ts, this.ctx);
631
- const roots = rootNames(this.ctx.rootDir);
682
+ const roots = rootNames(this.ctx);
632
683
  const written = new Map;
633
684
  const host = compilerHost(ng, options, {
634
685
  rootDir: this.ctx.rootDir,
@@ -643,17 +694,7 @@ class AngularDevProgram {
643
694
  }
644
695
  });
645
696
  host.getModifiedResourceFiles = () => new Set(modified);
646
- const read = host.getSourceFile.bind(host);
647
- host.getSourceFile = (fileName, language, onError, fresh) => {
648
- const stamp = /[\\/]node_modules[\\/]/.test(fileName) ? "" : stampOf(fileName);
649
- const hit = this.sourceFiles.get(fileName);
650
- if (hit && hit.stamp === stamp && !fresh)
651
- return hit.file;
652
- const file = read(fileName, language, onError, fresh);
653
- if (file)
654
- this.sourceFiles.set(fileName, { stamp, file });
655
- return file;
656
- };
697
+ reuseSourceFiles(host, this.sourceFiles, (file) => INSTALLED.test(file) ? "" : stampOf(file));
657
698
  for (const file of modified)
658
699
  this.resources.set(file, stampOf(file));
659
700
  const program = new ng.cli.NgtscProgram(roots, options, host, this.program);
@@ -674,7 +715,11 @@ class AngularDevProgram {
674
715
  if (resources.length)
675
716
  this.resourcesOf.set(real(source.fileName), new Set(resources.map(real)));
676
717
  }
677
- this.problems = problemsOf(ng, program, this.ctx.rootDir, (tsProgram) => defaultExportErrors(ng.ts, tsProgram, this.ctx.rootDir, roots));
718
+ this.checked.clear();
719
+ this.problems = [
720
+ ...programErrors(ng, program, this.ctx.rootDir),
721
+ ...defaultExportErrors(ng.ts, program.getTsProgram(), this.ctx.rootDir, roots)
722
+ ];
678
723
  emitOnly(program, (path) => this.emits(path));
679
724
  this.program = program;
680
725
  this.emitted = [...written.keys()].filter((file) => this.texts.has(file));
@@ -683,12 +728,15 @@ class AngularDevProgram {
683
728
  }
684
729
  record(program) {
685
730
  this.texts.clear();
731
+ this.fileNames.clear();
686
732
  for (const source of program.getTsProgram().getSourceFiles()) {
687
733
  if (source.isDeclarationFile)
688
734
  continue;
689
735
  const path = real(source.fileName);
690
- if (path.startsWith(this.root) || this.own.has(path))
691
- this.texts.set(path, source.text);
736
+ if (!path.startsWith(this.root) && !this.own.has(path))
737
+ continue;
738
+ this.texts.set(path, source.text);
739
+ this.fileNames.set(path, source.fileName);
692
740
  }
693
741
  }
694
742
  }
@@ -705,7 +753,7 @@ function compileGenerated(ctx, id, code) {
705
753
  if (hit?.hash === hash)
706
754
  return hit.emit;
707
755
  const emit = loadAngular(ctx.rootDir).then(async (ng) => {
708
- const files = await emitProgram(ng, ctx.rootDir, [path], { ...compilerOptions(ng.ts, ctx), _enableHmr: false }, ctx.preprocessStyle, (file) => file === path);
756
+ const files = await emitProgram(ng, ctx.rootDir, [path, ...generatedTypes(ctx.buildDir)], { ...compilerOptions(ng.ts, ctx), _enableHmr: false }, ctx.preprocessStyle, (file) => file === path, ctx.dev ? undefined : sourcesOf(ng));
709
757
  const emitted = files.get(path);
710
758
  if (!emitted)
711
759
  throw new Error(`${shown(ctx.rootDir, id)}: the Angular program emitted nothing for the generated module`);
@@ -908,6 +956,7 @@ var angularHooks = {
908
956
  close: () => {
909
957
  const { rootDir, buildDir } = useHamur().options;
910
958
  releaseDevProgram(rootDir, buildDir);
959
+ releaseBuildSources();
911
960
  }
912
961
  };
913
962
 
@@ -5,6 +5,8 @@ export interface AngularEmit {
5
5
  /** The declarations, emitted by `compilePartial` only. */
6
6
  types?: string;
7
7
  }
8
+ /** Drops the parsed files, which hold hundreds of megabytes, at the end of a build. */
9
+ export declare function releaseBuildSources(): void;
8
10
  /**
9
11
  * The app's program, shared by the client and server builds of one `hamur build`: the client and server steps
10
12
  * find the same roots unchanged and take the same emit; a later build in the process whose roots changed compiles again.
@@ -33,7 +35,8 @@ export interface AngularHotUpdate {
33
35
  /**
34
36
  * Built on the first load, then built again with the last good `NgtscProgram` as `oldProgram` when a load finds a
35
37
  * root whose text, or a resource whose stamp, changed. Unchanged source files keep their `ts.SourceFile`, so Angular reuses
36
- * their analysis and emits only the files the change reaches.
38
+ * their analysis and emits only the files the change reaches. A file is type-checked when it is loaded: checking the whole
39
+ * program takes over a second, and an error only shows on the file that has it.
37
40
  */
38
41
  export declare class AngularDevProgram {
39
42
  /** The real paths the last build emitted. */
@@ -46,6 +49,8 @@ export declare class AngularDevProgram {
46
49
  private readonly files;
47
50
  /** Real path of each source file of the program to the text it compiled. */
48
51
  private readonly texts;
52
+ /** Real path of each source file of the program to its name there. */
53
+ private readonly fileNames;
49
54
  /** Each resource the program read (templates, style files, a style file's imports) to its stamp when read. */
50
55
  private readonly resources;
51
56
  /** A style file's import to the style files that import it: Angular tracks the style file, not its imports. */
@@ -53,6 +58,8 @@ export declare class AngularDevProgram {
53
58
  private readonly sourceFiles;
54
59
  /** Real path of each component file to the real paths of the resources it reads (`getResourceDependencies`). */
55
60
  private readonly resourcesOf;
61
+ /** Real path of each file checked since the last build to its errors. */
62
+ private readonly checked;
56
63
  /** Component files a hot update left with errors. */
57
64
  private readonly broken;
58
65
  private options;
@@ -66,6 +73,7 @@ export declare class AngularDevProgram {
66
73
  private emits;
67
74
  /** The emit of `path` (a real path) after any build its load calls for; throws the program's errors for that file. */
68
75
  load(path: string): Promise<AngularEmit | undefined>;
76
+ private problemsOf;
69
77
  private stale;
70
78
  /** The stamps of the resources the components of `path` read, so `hamur dev`'s cache misses after an edit of one. */
71
79
  version(path: string): string;
@@ -16,7 +16,7 @@ export interface AsyncDataResource<T, D = undefined> extends Resource<T | D> {
16
16
  export interface InjectAsyncDataOptions<T = unknown, R = T, K extends keyof T & string = never, D = T> extends Omit<AsyncDataOptions<T, R, D>, "pick"> {
17
17
  /** Signals (or any getters) whose change runs the handler again. `false` is accepted and does nothing: nothing watches implicitly. */
18
18
  watch?: ReadonlyArray<() => unknown> | false;
19
- getCachedData?: GetCachedData<T>;
19
+ getCachedData?: GetCachedData<NoInfer<T>>;
20
20
  /** Top-level keys of an object result to keep. */
21
21
  pick?: readonly K[];
22
22
  }
@@ -28,10 +28,10 @@ export declare function injectAsyncData<I, R, T = R, K extends keyof T & string
28
28
  default: () => D;
29
29
  }): AsyncDataResource<PickFrom<T, K>, D>;
30
30
  export declare function injectAsyncData<I, R, T = R, K extends keyof T & string = never>(fn: Handler<I, R>, input?: NoInfer<I> | (() => NoInfer<I>), options?: InjectAsyncDataOptions<T, R, K, undefined>): AsyncDataResource<PickFrom<T, K>>;
31
- export declare function injectAsyncData<T = unknown, R = T, K extends keyof T & string = never, D = T>(key: string | (() => string), handler: AsyncDataHandler<R>, options: InjectAsyncDataOptions<T, R, K, D> & {
31
+ export declare function injectAsyncData<R, T = R, K extends keyof T & string = never, D = T>(key: string | (() => string), handler: AsyncDataHandler<R>, options: InjectAsyncDataOptions<T, R, K, D> & {
32
32
  default: () => D;
33
33
  }): AsyncDataResource<PickFrom<T, K>, D>;
34
- export declare function injectAsyncData<T = unknown, R = T, K extends keyof T & string = never>(key: string | (() => string), handler: AsyncDataHandler<R>, options?: InjectAsyncDataOptions<T, R, K, undefined>): AsyncDataResource<PickFrom<T, K>>;
34
+ export declare function injectAsyncData<R, T = R, K extends keyof T & string = never>(key: string | (() => string), handler: AsyncDataHandler<R>, options?: InjectAsyncDataOptions<T, R, K, undefined>): AsyncDataResource<PickFrom<T, K>>;
35
35
  /** What a literal `injectFetch` call is checked against; any other call stays loose. */
36
36
  type FetchInput<X> = X extends {
37
37
  key: infer K extends string;
@@ -1,6 +1,6 @@
1
1
  import { type Signal } from "@angular/core";
2
- import type { ActionOptions, ActionRunner, FormStatus, Handler } from "hamur/adapter";
3
- import type { ActionFailure, FieldsOf, HamurError, PendingRun, RouteLocation } from "hamur/app";
2
+ import type { ActionOptions, ActionRunner, ActionValue, FailureOf, FormStatus, Handler } from "hamur/adapter";
3
+ import type { FieldsOf, HamurError, PendingRun, RouteLocation } from "hamur/app";
4
4
  import * as i0 from "@angular/core";
5
5
  type FormHandler = Handler<any, any>;
6
6
  type FormAction = string | RouteLocation | FormHandler;
@@ -53,10 +53,10 @@ export interface InjectFormResult<I, O> extends InjectFormInstance<I, O> {
53
53
  export declare function injectForm<I, O>(fn: Handler<I, O>): InjectFormResult<I, O>;
54
54
  export interface InjectActionResult<I, O> {
55
55
  readonly run: ActionRunner<I, O>["run"];
56
- readonly state: Signal<O | undefined>;
56
+ readonly state: Signal<ActionValue<O> | undefined>;
57
57
  readonly pending: Signal<boolean>;
58
58
  readonly error: Signal<HamurError | undefined>;
59
- readonly failure: Signal<ActionFailure | undefined>;
59
+ readonly failure: Signal<FailureOf<O> | undefined>;
60
60
  reset(): void;
61
61
  }
62
62
  /** Runs `fn` one call after another; below a `Form` of `fn` it shows that form's posts. */
@@ -9,6 +9,6 @@ declare module "hamur" {
9
9
  }
10
10
  /**
11
11
  * `modules:done` serves `/@ng/component`; `dev:change` sends the update, or lists the components
12
- * that read the file as dependents with `hmr` off, and with it on those a template error is shown in; `close` drops the program.
12
+ * that read the file as dependents with `hmr` off, and with it on those a template error is shown in; `close` drops the program and what the build parsed.
13
13
  */
14
14
  export declare const angularHooks: NonNullable<Adapter["hooks"]>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hamur/adapter-angular",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -74,6 +74,6 @@
74
74
  "@angular/compiler-cli": "^22.3.0",
75
75
  "rxjs": "^7.8.2",
76
76
  "typescript": "~6.0.3",
77
- "hamur": "^0.0.2"
77
+ "hamur": ">=0.0.4 <0.1.0"
78
78
  }
79
79
  }
package/src/compile.ts CHANGED
@@ -11,6 +11,8 @@ const COMPILE_ID = /^(?!.*[\\/]node_modules[\\/]).*\.[cm]?ts$/
11
11
  /** Packages of the `@hamur` scope ship their partial-compiled components under the name of the source, `src/<name>.ts`. */
12
12
  const LINK_ID = /[\\/]node_modules[\\/](?:.+\.m?js|(?:.+[\\/])?@hamur[\\/][^\\/]+[\\/]src[\\/].+\.ts)$/
13
13
 
14
+ /** The generated types reach the sources of installed packages, which are not the program's to emit. */
15
+ const INSTALLED = /[\\/]node_modules[\\/]/
14
16
  const SCRIPT = /\.[cm]?ts$/
15
17
  const DECORATED = /^\s*@(?:Component|Directive|Pipe|NgModule|Injectable)\s*\(/m
16
18
  const ENTRY = /^(?:(pages|layouts)\/.+|(app|error))\.[cm]?ts$/
@@ -155,10 +157,21 @@ function workspaceRoot(rootDir: string, base: ts.CompilerOptions): ts.CompilerOp
155
157
  return { rootDir: root, ...(base.rootDirs ? { rootDirs: [...base.rootDirs, root] } : {}) }
156
158
  }
157
159
 
158
- /** Every `.ts` file under `app/`, then the package's own components; `server/` is never a root. */
159
- function rootNames(rootDir: string): string[] {
160
+ /** The generated file that references every other one, so `Route.Name` and the other registered types mean in a build what they mean in `hamur typecheck`. */
161
+ function generatedTypes(buildDir: string): string[] {
162
+ const file = join(buildDir, "types/hamur.d.ts")
163
+ return existsSync(file) ? [file] : []
164
+ }
165
+
166
+ /** Every `.ts` file under `app/`, the package's own components, then the generated types; `server/` is never a root. */
167
+ function rootNames({ rootDir, buildDir }: AdapterBuildContext): string[] {
160
168
  const app = join(rootDir, "app")
161
- return [...(existsSync(app) ? scripts(app) : []), ...ownComponents(), ...moduleComponents(rootDir)]
169
+ return [
170
+ ...(existsSync(app) ? scripts(app) : []),
171
+ ...ownComponents(),
172
+ ...moduleComponents(rootDir),
173
+ ...generatedTypes(buildDir),
174
+ ]
162
175
  }
163
176
 
164
177
  const shown = (rootDir: string, file: string): string => relative(rootDir, file).split(sep).join("/")
@@ -288,23 +301,15 @@ function compilerHost(ng: Angular, options: AngularCli.CompilerOptions, setup: H
288
301
  return host
289
302
  }
290
303
 
291
- /** The errors of the three `getNg*Diagnostics` and of `check`; warnings are not printed. */
292
- function problemsOf(
293
- ng: Angular,
294
- program: AngularCli.NgtscProgram,
295
- rootDir: string,
296
- check?: (program: ts.Program) => Problem[],
297
- ): Problem[] {
298
- const problems = [
299
- ...program.getNgOptionDiagnostics(),
300
- ...program.getNgStructuralDiagnostics(),
301
- ...program.getNgSemanticDiagnostics(),
302
- ]
304
+ /** The errors among `diagnostics`; warnings are not printed. */
305
+ const errorsOf = (ng: Angular, diagnostics: readonly ts.Diagnostic[], rootDir: string): Problem[] =>
306
+ diagnostics
303
307
  .filter((diagnostic) => diagnostic.category === ng.ts.DiagnosticCategory.Error)
304
308
  .map((diagnostic) => diagnosticProblem(ng.ts, diagnostic, rootDir))
305
- if (check) problems.push(...check(program.getTsProgram()))
306
- return problems
307
- }
309
+
310
+ /** The errors that belong to no file's own check. */
311
+ const programErrors = (ng: Angular, program: AngularCli.NgtscProgram, rootDir: string): Problem[] =>
312
+ errorsOf(ng, [...program.getNgOptionDiagnostics(), ...program.getNgStructuralDiagnostics()], rootDir)
308
313
 
309
314
  /**
310
315
  * Emits the source files whose real path `emits` keeps. TypeScript type-checks each file it emits in full, and in the
@@ -326,6 +331,48 @@ function emitOnly(program: AngularCli.NgtscProgram, emits: (file: string) => boo
326
331
  })
327
332
  }
328
333
 
334
+ interface ParsedFile {
335
+ stamp: string
336
+ file: ts.SourceFile
337
+ }
338
+
339
+ /**
340
+ * Reads a source file from `parsed` while its stamp or its text stays the same; `stamp` is empty for a file that does not
341
+ * change. A declaration file parsed again makes Angular compile and emit the whole program again, and `hamur dev` writes
342
+ * its types again, often with the same text, whenever a file is added or removed.
343
+ */
344
+ function reuseSourceFiles(
345
+ host: AngularCli.CompilerHost,
346
+ parsed: Map<string, ParsedFile>,
347
+ stampOfFile: (file: string) => string,
348
+ ): void {
349
+ const read = host.getSourceFile.bind(host)
350
+ host.getSourceFile = (fileName, language, onError, fresh) => {
351
+ const stamp = stampOfFile(fileName)
352
+ const hit = parsed.get(fileName)
353
+ if (hit && hit.stamp === stamp && !fresh) return hit.file
354
+ const file = read(fileName, language, onError, fresh)
355
+ if (!file) return file
356
+ const same = hit && !fresh && hit.file.text === file.text
357
+ parsed.set(fileName, { stamp, file: same ? hit.file : file })
358
+ return same ? hit.file : file
359
+ }
360
+ }
361
+
362
+ /** What the programs of the builds parsed, per compiler: the app's program and one per generated module read the same thousands of files. */
363
+ let buildSources = new WeakMap<Angular, Map<string, ParsedFile>>()
364
+
365
+ /** Drops the parsed files, which hold hundreds of megabytes, at the end of a build. */
366
+ export function releaseBuildSources(): void {
367
+ buildSources = new WeakMap()
368
+ }
369
+
370
+ function sourcesOf(ng: Angular): Map<string, ParsedFile> {
371
+ let parsed = buildSources.get(ng)
372
+ if (!parsed) buildSources.set(ng, (parsed = new Map()))
373
+ return parsed
374
+ }
375
+
329
376
  /** One `NgtscProgram` over `roots`, emitted into memory for the files `emits` keeps: real source path to its JavaScript and, with `sourceMap`, its map. */
330
377
  async function emitProgram(
331
378
  ng: Angular,
@@ -334,16 +381,19 @@ async function emitProgram(
334
381
  options: AngularCli.CompilerOptions,
335
382
  preprocessStyle: AdapterBuildContext["preprocessStyle"],
336
383
  emits: (file: string) => boolean,
384
+ parsed?: Map<string, ParsedFile>,
337
385
  check?: (program: ts.Program) => Problem[],
338
386
  ): Promise<Map<string, AngularEmit>> {
339
387
  const files = new Map<string, AngularEmit>()
340
- const program = new ng.cli.NgtscProgram(
341
- roots,
342
- options,
343
- compilerHost(ng, options, { rootDir, preprocessStyle, files }),
344
- )
388
+ const host = compilerHost(ng, options, { rootDir, preprocessStyle, files })
389
+ if (parsed) reuseSourceFiles(host, parsed, stampOf)
390
+ const program = new ng.cli.NgtscProgram(roots, options, host)
345
391
  await program.loadNgStructureAsync()
346
- const problems = problemsOf(ng, program, rootDir, check)
392
+ const problems = [
393
+ ...programErrors(ng, program, rootDir),
394
+ ...errorsOf(ng, program.getNgSemanticDiagnostics(), rootDir),
395
+ ...(check?.(program.getTsProgram()) ?? []),
396
+ ]
347
397
  if (problems.length) throw new Error(problems.map((problem) => problem.line).join("\n"))
348
398
  // A load file's `#server` pulls `server/` into the program; its emit must not replace the server files in the client build.
349
399
  const server = `${real(join(rootDir, "server"))}${sep}`
@@ -401,7 +451,7 @@ const programs = new Map<string, { stamp: string; files: Promise<Map<string, Ang
401
451
  * find the same roots unchanged and take the same emit; a later build in the process whose roots changed compiles again.
402
452
  */
403
453
  export function angularProgram(ctx: AdapterBuildContext): Promise<Map<string, AngularEmit>> {
404
- const roots = rootNames(ctx.rootDir)
454
+ const roots = rootNames(ctx)
405
455
  const stamp = roots
406
456
  .map((file) => {
407
457
  const stat = statSync(file)
@@ -420,7 +470,8 @@ export function angularProgram(ctx: AdapterBuildContext): Promise<Map<string, An
420
470
  roots,
421
471
  compilerOptions(ng.ts, ctx),
422
472
  ctx.preprocessStyle,
423
- (path) => path.startsWith(app) || own.has(path),
473
+ (path) => (path.startsWith(app) && !INSTALLED.test(path)) || own.has(path),
474
+ ctx.dev ? undefined : sourcesOf(ng),
424
475
  (program) => defaultExportErrors(ng.ts, program, ctx.rootDir, roots),
425
476
  ),
426
477
  )
@@ -490,7 +541,8 @@ export interface AngularHotUpdate {
490
541
  /**
491
542
  * Built on the first load, then built again with the last good `NgtscProgram` as `oldProgram` when a load finds a
492
543
  * root whose text, or a resource whose stamp, changed. Unchanged source files keep their `ts.SourceFile`, so Angular reuses
493
- * their analysis and emits only the files the change reaches.
544
+ * their analysis and emits only the files the change reaches. A file is type-checked when it is loaded: checking the whole
545
+ * program takes over a second, and an error only shows on the file that has it.
494
546
  */
495
547
  export class AngularDevProgram {
496
548
  /** The real paths the last build emitted. */
@@ -503,13 +555,17 @@ export class AngularDevProgram {
503
555
  private readonly files = new Map<string, AngularEmit>()
504
556
  /** Real path of each source file of the program to the text it compiled. */
505
557
  private readonly texts = new Map<string, string>()
558
+ /** Real path of each source file of the program to its name there. */
559
+ private readonly fileNames = new Map<string, string>()
506
560
  /** Each resource the program read (templates, style files, a style file's imports) to its stamp when read. */
507
561
  private readonly resources = new Map<string, string>()
508
562
  /** A style file's import to the style files that import it: Angular tracks the style file, not its imports. */
509
563
  private readonly importers = new Map<string, Set<string>>()
510
- private readonly sourceFiles = new Map<string, { stamp: string; file: ts.SourceFile }>()
564
+ private readonly sourceFiles = new Map<string, ParsedFile>()
511
565
  /** Real path of each component file to the real paths of the resources it reads (`getResourceDependencies`). */
512
566
  private readonly resourcesOf = new Map<string, Set<string>>()
567
+ /** Real path of each file checked since the last build to its errors. */
568
+ private readonly checked = new Map<string, Problem[]>()
513
569
  /** Component files a hot update left with errors. */
514
570
  private readonly broken = new Set<string>()
515
571
  private options: AngularCli.CompilerOptions | undefined
@@ -529,7 +585,7 @@ export class AngularDevProgram {
529
585
 
530
586
  /** As in a build: a load file's `#server` pulls `server/` into the program, whose emit must not replace the server files in the client. */
531
587
  private emits(path: string): boolean {
532
- return (path.startsWith(this.root) && !path.startsWith(this.server)) || this.own.has(path)
588
+ return (path.startsWith(this.root) && !path.startsWith(this.server) && !INSTALLED.test(path)) || this.own.has(path)
533
589
  }
534
590
 
535
591
  /** The emit of `path` (a real path) after any build its load calls for; throws the program's errors for that file. */
@@ -545,13 +601,23 @@ export class AngularDevProgram {
545
601
  await next
546
602
  if (this.failure) throw this.failure
547
603
  if (!this.texts.has(path)) return undefined
548
- const problems = this.problems.filter(
549
- (problem) => problem.file === undefined || problem.file === path || this.reads(path, problem.file),
550
- )
604
+ const problems = await this.problemsOf(path)
551
605
  if (problems.length) throw new Error(problems.map((problem) => problem.line).join("\n"))
552
606
  return this.files.get(path)
553
607
  }
554
608
 
609
+ private async problemsOf(path: string): Promise<Problem[]> {
610
+ const { program } = this
611
+ const fileName = this.fileNames.get(path)
612
+ let own = this.checked.get(path)
613
+ if (!own && program && fileName !== undefined) {
614
+ const ng = await loadAngular(this.ctx.rootDir)
615
+ own = errorsOf(ng, program.getNgSemanticDiagnostics(fileName), this.ctx.rootDir)
616
+ if (program === this.program) this.checked.set(path, own)
617
+ }
618
+ return [...this.problems.filter((problem) => problem.file === undefined || problem.file === path), ...(own ?? [])]
619
+ }
620
+
555
621
  private stale(path: string, text: string | undefined): boolean {
556
622
  const compiled = this.texts.get(path)
557
623
  if (compiled !== undefined) return compiled !== text
@@ -591,14 +657,9 @@ export class AngularDevProgram {
591
657
  await next
592
658
  const components = this.dependentsOf(path)
593
659
  const program = this.program
594
- const failing =
595
- this.failure || !program
596
- ? components
597
- : components.filter((component) =>
598
- this.problems.some(
599
- (problem) => problem.file === component || (!!problem.file && this.reads(component, problem.file)),
600
- ),
601
- )
660
+ const failing: string[] = []
661
+ for (const component of components)
662
+ if (this.failure || !program || (await this.problemsOf(component)).length) failing.push(component)
602
663
  if (failing.length || !program) {
603
664
  for (const component of failing) this.broken.add(component)
604
665
  return { updates: [], reload: failing }
@@ -650,7 +711,7 @@ export class AngularDevProgram {
650
711
  private async build(modified: string[]): Promise<void> {
651
712
  const ng = await loadAngular(this.ctx.rootDir)
652
713
  const options = (this.options ??= compilerOptions(ng.ts, this.ctx))
653
- const roots = rootNames(this.ctx.rootDir)
714
+ const roots = rootNames(this.ctx)
654
715
  const written = new Map<string, AngularEmit>()
655
716
  const host = compilerHost(ng, options, {
656
717
  rootDir: this.ctx.rootDir,
@@ -665,15 +726,7 @@ export class AngularDevProgram {
665
726
  },
666
727
  })
667
728
  host.getModifiedResourceFiles = () => new Set(modified)
668
- const read = host.getSourceFile.bind(host)
669
- host.getSourceFile = (fileName, language, onError, fresh) => {
670
- const stamp = /[\\/]node_modules[\\/]/.test(fileName) ? "" : stampOf(fileName)
671
- const hit = this.sourceFiles.get(fileName)
672
- if (hit && hit.stamp === stamp && !fresh) return hit.file
673
- const file = read(fileName, language, onError, fresh)
674
- if (file) this.sourceFiles.set(fileName, { stamp, file })
675
- return file
676
- }
729
+ reuseSourceFiles(host, this.sourceFiles, (file) => (INSTALLED.test(file) ? "" : stampOf(file)))
677
730
  for (const file of modified) this.resources.set(file, stampOf(file))
678
731
  const program = new ng.cli.NgtscProgram(roots, options, host, this.program)
679
732
  this.built = true
@@ -691,9 +744,11 @@ export class AngularDevProgram {
691
744
  const resources = program.compiler.getResourceDependencies(source)
692
745
  if (resources.length) this.resourcesOf.set(real(source.fileName), new Set(resources.map(real)))
693
746
  }
694
- this.problems = problemsOf(ng, program, this.ctx.rootDir, (tsProgram) =>
695
- defaultExportErrors(ng.ts, tsProgram, this.ctx.rootDir, roots),
696
- )
747
+ this.checked.clear()
748
+ this.problems = [
749
+ ...programErrors(ng, program, this.ctx.rootDir),
750
+ ...defaultExportErrors(ng.ts, program.getTsProgram(), this.ctx.rootDir, roots),
751
+ ]
697
752
  emitOnly(program, (path) => this.emits(path))
698
753
  this.program = program
699
754
  this.emitted = [...written.keys()].filter((file) => this.texts.has(file))
@@ -703,10 +758,13 @@ export class AngularDevProgram {
703
758
  /** The texts the program compiled, so a load of an unchanged file does not build again, even when the build fails. */
704
759
  private record(program: AngularCli.NgtscProgram): void {
705
760
  this.texts.clear()
761
+ this.fileNames.clear()
706
762
  for (const source of program.getTsProgram().getSourceFiles()) {
707
763
  if (source.isDeclarationFile) continue
708
764
  const path = real(source.fileName)
709
- if (path.startsWith(this.root) || this.own.has(path)) this.texts.set(path, source.text)
765
+ if (!path.startsWith(this.root) && !this.own.has(path)) continue
766
+ this.texts.set(path, source.text)
767
+ this.fileNames.set(path, source.fileName)
710
768
  }
711
769
  }
712
770
  }
@@ -735,10 +793,11 @@ function compileGenerated(ctx: AdapterBuildContext, id: string, code: string): P
735
793
  const files = await emitProgram(
736
794
  ng,
737
795
  ctx.rootDir,
738
- [path],
796
+ [path, ...generatedTypes(ctx.buildDir)],
739
797
  { ...compilerOptions(ng.ts, ctx), _enableHmr: false },
740
798
  ctx.preprocessStyle,
741
799
  (file) => file === path,
800
+ ctx.dev ? undefined : sourcesOf(ng),
742
801
  )
743
802
  const emitted = files.get(path)
744
803
  if (!emitted)
package/src/data.ts CHANGED
@@ -54,7 +54,7 @@ export interface InjectAsyncDataOptions<T = unknown, R = T, K extends keyof T &
54
54
  > {
55
55
  /** Signals (or any getters) whose change runs the handler again. `false` is accepted and does nothing: nothing watches implicitly. */
56
56
  watch?: ReadonlyArray<() => unknown> | false
57
- getCachedData?: GetCachedData<T>
57
+ getCachedData?: GetCachedData<NoInfer<T>>
58
58
  /** Top-level keys of an object result to keep. */
59
59
  pick?: readonly K[]
60
60
  }
@@ -215,12 +215,12 @@ export function injectAsyncData<I, R, T = R, K extends keyof T & string = never>
215
215
  input?: NoInfer<I> | (() => NoInfer<I>),
216
216
  options?: InjectAsyncDataOptions<T, R, K, undefined>,
217
217
  ): AsyncDataResource<PickFrom<T, K>>
218
- export function injectAsyncData<T = unknown, R = T, K extends keyof T & string = never, D = T>(
218
+ export function injectAsyncData<R, T = R, K extends keyof T & string = never, D = T>(
219
219
  key: string | (() => string),
220
220
  handler: AsyncDataHandler<R>,
221
221
  options: InjectAsyncDataOptions<T, R, K, D> & { default: () => D },
222
222
  ): AsyncDataResource<PickFrom<T, K>, D>
223
- export function injectAsyncData<T = unknown, R = T, K extends keyof T & string = never>(
223
+ export function injectAsyncData<R, T = R, K extends keyof T & string = never>(
224
224
  key: string | (() => string),
225
225
  handler: AsyncDataHandler<R>,
226
226
  options?: InjectAsyncDataOptions<T, R, K, undefined>,
package/src/hmr.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type {} from "hamur"
2
2
  import type { Adapter } from "hamur/adapter"
3
3
  import { addDevServerHandler, useDevChannel, useHamur, type DevChange, type HamurContext } from "hamur/kit"
4
- import { devProgramOf, releaseDevProgram, setDevBaseURL } from "./compile.ts"
4
+ import { devProgramOf, releaseBuildSources, releaseDevProgram, setDevBaseURL } from "./compile.ts"
5
5
 
6
6
  declare module "hamur" {
7
7
  interface HamurDevEvents {
@@ -16,7 +16,7 @@ const NO_STORE = { "content-type": "text/javascript", "cache-control": "no-store
16
16
 
17
17
  /**
18
18
  * `modules:done` serves `/@ng/component`; `dev:change` sends the update, or lists the components
19
- * that read the file as dependents with `hmr` off, and with it on those a template error is shown in; `close` drops the program.
19
+ * that read the file as dependents with `hmr` off, and with it on those a template error is shown in; `close` drops the program and what the build parsed.
20
20
  */
21
21
  export const angularHooks: NonNullable<Adapter["hooks"]> = {
22
22
  "modules:done": () => {
@@ -57,5 +57,6 @@ export const angularHooks: NonNullable<Adapter["hooks"]> = {
57
57
  close: () => {
58
58
  const { rootDir, buildDir } = useHamur().options
59
59
  releaseDevProgram(rootDir, buildDir)
60
+ releaseBuildSources()
60
61
  },
61
62
  }