@eagleoutice/flowr 2.15.9 → 2.15.10

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 (112) hide show
  1. package/README.md +34 -25
  2. package/abstract-interpretation/absint-inference.d.ts +2 -2
  3. package/abstract-interpretation/absint-inference.js +32 -79
  4. package/benchmark/slicer.d.ts +0 -1
  5. package/benchmark/slicer.js +1 -2
  6. package/cli/repl/commands/repl-signature.js +12 -3
  7. package/config.d.ts +5 -1
  8. package/control-flow/cfg-properties.js +0 -22
  9. package/control-flow/happens-before.d.ts +2 -2
  10. package/control-flow/happens-before.js +29 -19
  11. package/dataflow/environments/apply-kill.js +6 -2
  12. package/dataflow/environments/built-in-config.d.ts +2 -0
  13. package/dataflow/environments/built-in-props.d.ts +7 -1
  14. package/dataflow/environments/built-in-props.js +8 -1
  15. package/dataflow/environments/built-in.d.ts +7 -2
  16. package/dataflow/environments/built-in.js +11 -5
  17. package/dataflow/environments/default-builtin-config.d.ts +386 -8
  18. package/dataflow/environments/default-builtin-config.js +84 -22
  19. package/dataflow/environments/define.d.ts +3 -2
  20. package/dataflow/environments/define.js +4 -3
  21. package/dataflow/environments/deprecation-info.d.ts +45 -0
  22. package/dataflow/environments/deprecation-info.js +13 -0
  23. package/dataflow/environments/environment.d.ts +1 -1
  24. package/dataflow/environments/environment.js +5 -4
  25. package/dataflow/environments/identifier.d.ts +2 -0
  26. package/dataflow/extractor.js +6 -1
  27. package/dataflow/fn/class-declaration.d.ts +0 -11
  28. package/dataflow/fn/class-declaration.js +0 -20
  29. package/dataflow/fn/higher-order-function.d.ts +9 -1
  30. package/dataflow/fn/higher-order-function.js +14 -7
  31. package/dataflow/fn/strict-function.js +8 -3
  32. package/dataflow/graph/graph.d.ts +7 -0
  33. package/dataflow/graph/graph.js +17 -0
  34. package/dataflow/graph/vertex.d.ts +1 -1
  35. package/dataflow/internal/linker.d.ts +3 -0
  36. package/dataflow/internal/linker.js +67 -6
  37. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.d.ts +113 -0
  38. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.js +506 -0
  39. package/dataflow/internal/process/functions/call/built-in/built-in-apply.js +9 -0
  40. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.d.ts +2 -0
  41. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.js +22 -19
  42. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.d.ts +5 -1
  43. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.js +21 -14
  44. package/dataflow/internal/process/functions/call/built-in/built-in-eval.js +14 -4
  45. package/dataflow/internal/process/functions/call/built-in/built-in-expression-list.js +22 -2
  46. package/dataflow/internal/process/functions/call/built-in/built-in-for-loop.js +2 -0
  47. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +4 -3
  48. package/dataflow/internal/process/functions/call/built-in/built-in-library.js +19 -3
  49. package/dataflow/internal/process/functions/call/built-in/built-in-local.js +7 -3
  50. package/dataflow/internal/process/functions/call/built-in/built-in-repeat-loop.js +2 -0
  51. package/dataflow/internal/process/functions/call/built-in/built-in-s-four.d.ts +4 -2
  52. package/dataflow/internal/process/functions/call/built-in/built-in-s-four.js +3 -5
  53. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.js +2 -1
  54. package/dataflow/internal/process/functions/call/built-in/built-in-s-three-dispatch.js +8 -0
  55. package/dataflow/internal/process/functions/call/built-in/built-in-while-loop.js +2 -0
  56. package/dataflow/internal/process/functions/call/common.d.ts +3 -1
  57. package/dataflow/internal/process/functions/call/common.js +22 -4
  58. package/dataflow/internal/process/functions/call/deferred.d.ts +6 -0
  59. package/dataflow/internal/process/functions/call/deferred.js +33 -12
  60. package/dataflow/internal/process/functions/call/known-call-handling.js +1 -1
  61. package/dataflow/internal/process/functions/call/named-call-handling.js +15 -0
  62. package/dataflow/internal/process/functions/call/quoted.js +137 -24
  63. package/dataflow/internal/process/process-symbol.js +6 -2
  64. package/documentation/data/faq/faqs.js +3 -3
  65. package/documentation/data/interface/doc-writing-code.js +1 -2
  66. package/documentation/data/server/doc-data-server-messages.js +7 -7
  67. package/documentation/doc-capabilities.js +80 -34
  68. package/documentation/doc-util/doc-query.d.ts +0 -3
  69. package/documentation/doc-util/doc-query.js +4 -3
  70. package/documentation/wiki-analyzer.js +1 -1
  71. package/documentation/wiki-cfg.js +5 -6
  72. package/documentation/wiki-core.js +8 -8
  73. package/documentation/wiki-dataflow-graph.js +10 -11
  74. package/documentation/wiki-interface.js +2 -2
  75. package/documentation/wiki-linting-and-testing.js +3 -3
  76. package/documentation/wiki-overview.js +6 -6
  77. package/documentation/wiki-query.js +9 -101
  78. package/documentation/wiki-signature-database.js +1 -1
  79. package/linter/linter-rules.d.ts +1 -1
  80. package/linter/rules/deprecated-functions.d.ts +1 -45
  81. package/linter/rules/deprecated-functions.js +24 -33
  82. package/package.json +1 -1
  83. package/project/flowr-analyzer.d.ts +2 -0
  84. package/project/flowr-analyzer.js +24 -1
  85. package/project/plugins/file-plugins/files/flowr-rda-file.d.ts +0 -2
  86. package/project/plugins/file-plugins/files/flowr-rda-file.js +10 -55
  87. package/project/plugins/file-plugins/flowr-analyzer-file-plugin.js +2 -1
  88. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +6 -4
  89. package/project/plugins/project-discovery/flowr-analyzer-project-discovery-plugin.js +2 -2
  90. package/project/sigdb/build.js +4 -0
  91. package/project/sigdb/manifest.d.ts +2 -0
  92. package/project/sigdb/manifest.js +10 -1
  93. package/project/sigdb/reader.js +23 -61
  94. package/project/sigdb/sigdb-download.d.ts +29 -6
  95. package/project/sigdb/sigdb-download.js +212 -64
  96. package/queries/catalog/call-context-query/cascade-action.d.ts +3 -1
  97. package/queries/catalog/call-context-query/cascade-action.js +2 -0
  98. package/queries/catalog/call-context-query/identify-link-to-last-call-relation.js +3 -0
  99. package/queries/catalog/inspect-higher-order-query/inspect-higher-order-query-executor.js +2 -1
  100. package/queries/catalog/origin-query/origin-query-executor.d.ts +1 -1
  101. package/queries/catalog/origin-query/origin-query-executor.js +2 -2
  102. package/queries/catalog/origin-query/origin-query-format.d.ts +2 -2
  103. package/queries/catalog/origin-query/origin-query-format.js +1 -1
  104. package/queries/query.d.ts +1 -1
  105. package/r-bridge/data/data.d.ts +21 -14
  106. package/r-bridge/data/data.js +28 -20
  107. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-executor.d.ts +2 -2
  108. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-executor.js +11 -2
  109. package/util/files.d.ts +2 -0
  110. package/util/files.js +3 -1
  111. package/util/mermaid/mermaid.js +6 -2
  112. package/util/version.js +2 -2
@@ -8,6 +8,8 @@ const retriever_1 = require("../r-bridge/retriever");
8
8
  const files_1 = require("../util/files");
9
9
  const tree_sitter_normalize_1 = require("../r-bridge/lang-4.x/tree-sitter/tree-sitter-normalize");
10
10
  const tree_sitter_executor_1 = require("../r-bridge/lang-4.x/tree-sitter/tree-sitter-executor");
11
+ const vertex_1 = require("../dataflow/graph/vertex");
12
+ const df_helper_1 = require("../dataflow/graph/df-helper");
11
13
  /**
12
14
  * Central class for conducting analyses with FlowR.
13
15
  * Use the {@link FlowrAnalyzerBuilder} to create a new instance.
@@ -24,6 +26,8 @@ class FlowrAnalyzer {
24
26
  cache;
25
27
  ctx;
26
28
  parserInfo;
29
+ /** the graph whose calls are already being qualified in the background, see {@link qualifyInBackground} */
30
+ qualifying;
27
31
  /**
28
32
  * Create a new analyzer instance.
29
33
  * **Prefer the use of the {@link FlowrAnalyzerBuilder} instead of calling this constructor directly.**
@@ -133,7 +137,12 @@ class FlowrAnalyzer {
133
137
  return this.cache.peekNormalize();
134
138
  }
135
139
  async dataflow(force) {
136
- return this.cache.dataflow(force);
140
+ const dataflow = await this.cache.dataflow(force);
141
+ if (this.qualifying !== dataflow.graph) {
142
+ this.qualifying = dataflow.graph;
143
+ qualifyInBackground(dataflow.graph);
144
+ }
145
+ return dataflow;
137
146
  }
138
147
  peekDataflow() {
139
148
  return this.cache.peekDataflow();
@@ -170,4 +179,18 @@ class FlowrAnalyzer {
170
179
  }
171
180
  }
172
181
  exports.FlowrAnalyzer = FlowrAnalyzer;
182
+ /** Qualifies calls (see {@link Dataflow.qualify}) in idle time on unreferenced timers, so later queries find it done. */
183
+ function qualifyInBackground(graph) {
184
+ const calls = Array.from(graph.verticesOfType(vertex_1.VertexType.FunctionCall), ([id]) => id);
185
+ let next = 0;
186
+ const step = () => {
187
+ for (const end = Math.min(next + 256, calls.length); next < end; next++) {
188
+ df_helper_1.Dataflow.qualify(calls[next], graph, false);
189
+ }
190
+ if (next < calls.length) {
191
+ setTimeout(step, 0).unref();
192
+ }
193
+ };
194
+ setTimeout(step, 0).unref();
195
+ }
173
196
  //# sourceMappingURL=flowr-analyzer.js.map
@@ -403,8 +403,6 @@ export declare class RDAParser {
403
403
  * See {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/memory.c#L4122-L4142 | R source: VECTOR_ELT}
404
404
  */
405
405
  VECTOR_ELT(x: RObjectData, i: number): RObject;
406
- /** Whether a {@link SexpType.BcodesSxp}'s version is within the supported range. See {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/eval.c#L7166-L7175 | R source: R_BCVersionOK} */
407
- R_BCVersionOK(s: RObjectData): boolean;
408
406
  /** Source-language expression for an unsupported bytecode object: its first constant pool entry, or {@link RValues.NilValue}. See {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/eval.c#L5566-L5574 | R source: bytecodeExpr} */
409
407
  R_BytecodeExpr(s: RObjectData): RObject;
410
408
  /**
@@ -121,6 +121,8 @@ const BareStreamFormats = new Set(['A', 'B', 'X']);
121
121
  function isBareSerializationStream(buf) {
122
122
  return buf.length >= 2 && buf[1] === 0x0a && BareStreamFormats.has(String.fromCodePoint(buf[0]));
123
123
  }
124
+ /** The control characters an ASCII-format string spells with a backslash escape; any other escaped character stands for itself. */
125
+ const AsciiEscapes = { n: '\n', t: '\t', v: '\v', b: '\b', r: '\r', f: '\f', a: '\x07' };
124
126
  /** The variants {@link RDAParser.deserialize} handles. */
125
127
  const SupportedSerializationTypes = new Set([
126
128
  SerializationTypeTag.MagicAsciiV2, SerializationTypeTag.MagicBinaryV2, SerializationTypeTag.MagicXdrV2,
@@ -406,7 +408,7 @@ class RDAParser {
406
408
  if (neLen > RDAParser.R_CODE_SET_MAX || neLen < 0) {
407
409
  throw new Error('invalid length of encoding name');
408
410
  }
409
- const _nativeEncoding = this.inString(neLen);
411
+ this.inString(neLen);
410
412
  break;
411
413
  }
412
414
  default:
@@ -536,37 +538,13 @@ class RDAParser {
536
538
  c = String.fromCodePoint(this.buffer[this.offset++]);
537
539
  switch (c) {
538
540
  case 'n':
539
- result.push('\n');
540
- break;
541
541
  case 't':
542
- result.push('\t');
543
- break;
544
542
  case 'v':
545
- result.push('\v');
546
- break;
547
543
  case 'b':
548
- result.push('\b');
549
- break;
550
544
  case 'r':
551
- result.push('\r');
552
- break;
553
545
  case 'f':
554
- result.push('\f');
555
- break;
556
546
  case 'a':
557
- result.push('\x07');
558
- break; // \a
559
- case '\\':
560
- result.push('\\');
561
- break;
562
- case '?':
563
- result.push('?');
564
- break;
565
- case '\'':
566
- result.push('\'');
567
- break;
568
- case '"':
569
- result.push('"');
547
+ result.push(AsciiEscapes[c]);
570
548
  break;
571
549
  case '0':
572
550
  case '1':
@@ -641,28 +619,21 @@ class RDAParser {
641
619
  const shell = new shell_executor_1.RShellExecutor();
642
620
  const result = shell.run(code);
643
621
  shell.close();
644
- const val = { type: SexpType.EnvSxp };
645
- if (result === '<environment: R_GlobalEnv>') {
646
- val.value = RValues.GlobalEnv;
647
- }
648
- return val;
622
+ return result === '<environment: R_GlobalEnv>' ? { type: SexpType.EnvSxp, value: RValues.GlobalEnv } : { type: SexpType.EnvSxp };
649
623
  }
650
624
  /**
651
625
  * Resolves a namespace reference by name via `getNamespace()` in R. Simpler variant of {@link R_FindNamespace1}.
652
626
  * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/envir.c#L3795-L3804 | R source: R_FindNamespace}
653
627
  */
654
628
  R_FindNamespace(info) {
655
- const namespaceName = info.value.name;
656
- return this.runNamespaceLookup(`getNamespace("${namespaceName}")`);
629
+ return this.runNamespaceLookup(`getNamespace("${info.value.name}")`);
657
630
  }
658
631
  /**
659
632
  * Resolves a serialized namespace reference by executing R at runtime. See {@link R_FindNamespace} for the result shape.
660
633
  * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L1785-L1796 | R source: R_FindNamespace1}
661
634
  */
662
635
  R_FindNamespace1(info) {
663
- const where = this.lastName;
664
- const code = `..getNamespace("${info.value[0].name}", "${where}")`;
665
- return this.runNamespaceLookup(code);
636
+ return this.runNamespaceLookup(`..getNamespace("${info.value[0].name}", "${this.lastName}")`);
666
637
  }
667
638
  /**
668
639
  * Deserializes a single SEXP node, dispatching on its encoded {@link SexpType}.
@@ -933,7 +904,7 @@ class RDAParser {
933
904
  s.attributes = hasAttribute ? [skip ? this.skipItem() : this.assertRObjectData(this.readItem())] : undefined;
934
905
  this.currentDepth--;
935
906
  }
936
- if (!skip && s.type === SexpType.BcodesSxp && !this.R_BCVersionOK(s)) {
907
+ if (!skip && s.type === SexpType.BcodesSxp) {
937
908
  return this.R_BytecodeExpr(s);
938
909
  }
939
910
  return s;
@@ -1597,28 +1568,12 @@ class RDAParser {
1597
1568
  return x.value[i];
1598
1569
  }
1599
1570
  }
1600
- /** Whether a {@link SexpType.BcodesSxp}'s version is within the supported range. See {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/eval.c#L7166-L7175 | R source: R_BCVersionOK} */
1601
- R_BCVersionOK(s) {
1602
- if (s.type !== SexpType.BcodesSxp) {
1603
- return false;
1604
- }
1605
- // const version = s.code;
1606
- const version = 0;
1607
- return version >= 9 && version <= 12;
1608
- }
1609
1571
  /** Source-language expression for an unsupported bytecode object: its first constant pool entry, or {@link RValues.NilValue}. See {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/eval.c#L5566-L5574 | R source: bytecodeExpr} */
1610
1572
  R_BytecodeExpr(s) {
1611
- if (s.type === SexpType.BcodesSxp) {
1612
- if (s.cdr.value?.length > 0) {
1613
- return this.VECTOR_ELT(s.cdr, 0);
1614
- }
1615
- else {
1616
- return RValues.NilValue;
1617
- }
1618
- }
1619
- else {
1573
+ if (s.type !== SexpType.BcodesSxp) {
1620
1574
  return s;
1621
1575
  }
1576
+ return s.cdr.value?.length > 0 ? this.VECTOR_ELT(s.cdr, 0) : RValues.NilValue;
1622
1577
  }
1623
1578
  /**
1624
1579
  * Attempts to unserialize an ALTREP object. Throws error if the base type is not a supported vector type.
@@ -4,6 +4,7 @@ exports.FlowrAnalyzerRoleFilePlugin = exports.FlowrAnalyzerPatternFilePlugin = e
4
4
  const flowr_analyzer_plugin_1 = require("../flowr-analyzer-plugin");
5
5
  const flowr_file_1 = require("../../context/flowr-file");
6
6
  const semver_1 = require("semver");
7
+ const files_1 = require("../../../util/files");
7
8
  const built_in_source_1 = require("../../../dataflow/internal/process/functions/call/built-in/built-in-source");
8
9
  /**
9
10
  * This is the base class for all plugins that load and possibly transform files when they are loaded.
@@ -34,7 +35,7 @@ class DefaultFlowrAnalyzerFilePlugin extends FlowrAnalyzerFilePlugin {
34
35
  }
35
36
  process(_ctx, arg) {
36
37
  const path = arg.path().toString();
37
- if (/\.r$/i.test(path)) {
38
+ if (/\.r$/i.test(path) || files_1.rPackageSourceRegex.test(path)) {
38
39
  // we just assign the role :D
39
40
  arg.assignRole(flowr_file_1.FileRole.Source);
40
41
  }
@@ -201,16 +201,18 @@ class FlowrAnalyzerPackageVersionsSigDbPlugin extends flowr_analyzer_package_ver
201
201
  if (!dl.sigDbNeedsSync()) {
202
202
  return;
203
203
  }
204
- exports.sigDbLog.info('sigdb: committed link file changed, re-syncing shards in the background');
205
- const { files } = await dl.downloadFullSigDb({
204
+ exports.sigDbLog.info('sigdb: the committed link file names shards missing from the cache, syncing them in the background');
205
+ const { tag, files, downloaded, stale } = await dl.downloadFullSigDb({
206
206
  repo: ctx.config.solver.sigdb.downloadRepo,
207
207
  onProgress: msg => exports.sigDbLog.info(`sigdb sync: ${msg}`)
208
208
  });
209
- for (const manifest of files.filter(f => /\.manifest\.json(\.br)?$/.test(f))) {
209
+ const manifests = files.filter(f => dl.isManifestFile(f));
210
+ for (const manifest of manifests) {
210
211
  await ctx.deps.addDatabaseSource(manifest);
211
212
  }
213
+ exports.sigDbLog.info(`sigdb sync: ${tag} ready (${downloaded.length} file(s) fetched, ${manifests.length} manifest(s) mounted${stale.length > 0 ? `, ${stale.length} older bundle(s) still cached` : ''})`);
212
214
  })().catch((e) => {
213
- exports.sigDbLog.warn(`background sigdb sync failed (keeping the cached shards): ${e.message}`);
215
+ exports.sigDbLog.warn(`background sigdb sync failed, analyzing with the signatures already cached: ${e.message}`);
214
216
  });
215
217
  }
216
218
  warmPromise;
@@ -29,8 +29,8 @@ class FlowrAnalyzerProjectDiscoveryPlugin extends flowr_analyzer_plugin_1.FlowrA
29
29
  }
30
30
  }
31
31
  exports.FlowrAnalyzerProjectDiscoveryPlugin = FlowrAnalyzerProjectDiscoveryPlugin;
32
- // `.Rprofile`/`Rprofile.site` carry no extension but are plain R sources
33
- exports.discoverRSourcesRegex = /(\.(r|rmd|rmarkdown|ipynb|qmd|rnw)|(^|[\\/])\.?Rprofile(\.site)?)$/i;
32
+ // `.Rprofile`/`Rprofile.site` carry no extension but are plain R sources, as are the `.S`/`.s`/`.q` files below `R/`
33
+ exports.discoverRSourcesRegex = new RegExp(`(\\.(r|rmd|rmarkdown|ipynb|qmd|rnw)|(^|[\\\\/])\\.?Rprofile(\\.site)?)$|${files_1.rPackageSourceRegex.source}`, 'i');
34
34
  // matched against the posix path relative to the project root
35
35
  exports.ignorePathsWith = /(^|\/)(\.git|\.svn|\.hg|node_modules|__pycache__|\.Rproj\.user|\.uvr|Rtmp[^/]*|(packrat|renv|rv)\/(lib|library|src|staging|sandbox|bundles)[^/]*)(\/|$)/i;
36
36
  exports.excludeRequestsForPaths = /vignettes?|tests?|revdep|inst|data/i;
@@ -502,6 +502,10 @@ const NdjsonBatchBytes = 8_000_000;
502
502
  * rather than a JSON array of quoted strings, which loads as a single `split('\n')` instead of parsing ~1.4M elements.
503
503
  */
504
504
  function* dictLines(strings) {
505
+ /* a line holding no names would read back as one empty name */
506
+ if (strings.length === 0) {
507
+ return;
508
+ }
505
509
  let start = 0;
506
510
  let parts = [];
507
511
  let bytes = 0;
@@ -55,6 +55,8 @@ export declare function readManifestFile(manifestFile: string): SigDbManifest;
55
55
  export declare function readManifestDate(manifestFile: string): string | undefined;
56
56
  /** breadth/temporal scope of a bundled sigdb: base R only, `current` (latest CRAN + base R), or the `full` history */
57
57
  export type SigDbScope = 'base' | 'current' | 'full';
58
+ /** the bundle directories in the cache, the most recently synced first (it takes precedence) */
59
+ export declare function sigDbBundleDirs(watched?: [string, number][]): string[];
58
60
  /**
59
61
  * Location of a bundled sigdb **manifest**, found by walking up from several roots (this module,
60
62
  * `$FLOWR_SIGDB_DIR`, the working directory) across the dev (`src`), build (`dist`), and data-mount
@@ -7,6 +7,7 @@ exports.SigDbManifestSchema = exports.SigDbManifestMagic = void 0;
7
7
  exports.writeManifest = writeManifest;
8
8
  exports.readManifestFile = readManifestFile;
9
9
  exports.readManifestDate = readManifestDate;
10
+ exports.sigDbBundleDirs = sigDbBundleDirs;
10
11
  exports.defaultSigDbPath = defaultSigDbPath;
11
12
  exports.defaultSigDbPaths = defaultSigDbPaths;
12
13
  /**
@@ -65,6 +66,7 @@ const SigDbSubDirs = ['', 'data/sigdb', 'src/data/sigdb', 'dist/src/data/sigdb']
65
66
  const ManifestFilePattern = new RegExp(`\\.manifest\\.json${codec_1.CompressedExtPattern}$`);
66
67
  /** a `<name>.sigs.ndjson` bundle, in any of the codecs we can read */
67
68
  const BundleFilePattern = new RegExp(`${schema_1.SigDbExt.replace(/\./g, '\\.')}${codec_1.CompressedExtPattern}$`);
69
+ /** the bundle directories in the cache, the most recently synced first (it takes precedence) */
68
70
  function sigDbBundleDirs(watched) {
69
71
  if (typeof fs_1.default?.readdirSync !== 'function') {
70
72
  return [];
@@ -72,9 +74,16 @@ function sigDbBundleDirs(watched) {
72
74
  try {
73
75
  const bundles = path_1.default.join((0, decompress_1.sigDbCacheDir)(undefined, false), 'bundles');
74
76
  const mtimeMs = fs_1.default.statSync(bundles).mtimeMs;
77
+ /* a bundle of every release synced so far stays in the cache, and the first one found wins: the most recently
78
+ synced comes first, or an update to a release that happens to sort before the old one would be ignored */
75
79
  const dirs = fs_1.default.readdirSync(bundles, { withFileTypes: true })
76
80
  .filter(e => e.isDirectory())
77
- .map(e => path_1.default.join(bundles, e.name));
81
+ .map(e => {
82
+ const dir = path_1.default.join(bundles, e.name);
83
+ return { dir, mtimeMs: fs_1.default.statSync(dir).mtimeMs };
84
+ })
85
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
86
+ .map(e => e.dir);
78
87
  watched?.push([bundles, mtimeMs]); // a bundle directory appearing here has to be picked up too
79
88
  return dirs;
80
89
  }
@@ -39,10 +39,7 @@ function dictLineRun(json) {
39
39
  /** apply one `d` line to a plain array, for the whole-file form {@link readSigDbFile} reads */
40
40
  function applyDictLine(json, strings) {
41
41
  const { start, names } = dictLineRun(json);
42
- const batch = names.split('\n');
43
- for (let k = 0; k < batch.length; k++) {
44
- strings[start + k] = batch[k];
45
- }
42
+ names.split('\n').forEach((name, k) => strings[start + k] = name);
46
43
  }
47
44
  /**
48
45
  * Dictionary ids grouped by first byte and byte length, kept per dictionary rather than per reader (the shards of one
@@ -353,10 +350,6 @@ function keepBlob(db, blobIdx, bytes) {
353
350
  cachedBlobBytes += bytes;
354
351
  return entry;
355
352
  }
356
- /** Mark `entry` read, so the hand passes over it once before dropping it. */
357
- function touchBlob(entry) {
358
- entry.used = true;
359
- }
360
353
  /** give back what `db` held, so a closed bundle stops spending the budget of the open ones */
361
354
  function releaseBlobs(db) {
362
355
  for (let i = cachedBlobs.length - 1; i >= 0; i--) {
@@ -440,12 +433,13 @@ class SigDatabase {
440
433
  * is compressed. Pass `strings` for a blob-only shard that shares an already-loaded dictionary.
441
434
  */
442
435
  static openSyncFrom(source, opts) {
443
- const plain = (0, decompress_1.isCompressed)(source)
444
- ? (opts.hash !== undefined ? (0, decompress_1.ensurePlainSync)(source, { cacheDir: opts.cacheDir, hash: opts.hash, index: opts.index })
445
- : (() => {
446
- throw new Error('openSyncFrom needs a hash to key the cache for a compressed source');
447
- })())
448
- : source;
436
+ let plain = source;
437
+ if ((0, decompress_1.isCompressed)(source)) {
438
+ if (opts.hash === undefined) {
439
+ throw new Error('openSyncFrom needs a hash to key the cache for a compressed source');
440
+ }
441
+ plain = (0, decompress_1.ensurePlainSync)(source, { cacheDir: opts.cacheDir, hash: opts.hash, index: opts.index });
442
+ }
449
443
  return SigDatabase.openSync(plain, { index: opts.index, strings: opts.strings });
450
444
  }
451
445
  has(pkg) {
@@ -463,12 +457,12 @@ class SigDatabase {
463
457
  const cached = this.blobCache.get(blobIdx);
464
458
  if (cached !== undefined) {
465
459
  if (cached.entry !== undefined) {
466
- touchBlob(cached.entry);
460
+ cached.entry.used = true;
467
461
  }
468
462
  return cached.blob;
469
463
  }
470
464
  if (this.fd === NoFile) {
471
- return undefined; // an in-memory database starts out with every blob cached
465
+ return undefined;
472
466
  }
473
467
  const range = this.index.blobs[blobIdx];
474
468
  const blob = this.readBlobAt(range);
@@ -595,16 +589,7 @@ class SigDatabase {
595
589
  */
596
590
  exportsNameId(pkg, id) {
597
591
  const r = this.versionFns(pkg);
598
- if (r === undefined) {
599
- return false;
600
- }
601
- for (const i of r.fns.idxs) {
602
- const fn = r.blob.fns[i];
603
- if (fn[0] === id && (fn[3] & 1 /* FnProp.Exported */) !== 0) {
604
- return true;
605
- }
606
- }
607
- return false;
592
+ return r?.fns.idxs.some(i => r.blob.fns[i][0] === id && (r.blob.fns[i][3] & 1 /* FnProp.Exported */) !== 0) ?? false;
608
593
  }
609
594
  classOwner(className, version) {
610
595
  if (version !== undefined) {
@@ -851,40 +836,22 @@ class SigDatabaseSet {
851
836
  }
852
837
  const ref = this.manifest.shards[i];
853
838
  const strings = ref.dict ? this.dictionaryStrings(ref.dict) : undefined;
854
- const db = SigDatabase.openSyncFrom((0, decompress_1.resolveSource)(this.baseDir, ref.path), { cacheDir: this.cacheDir, hash: ref.hash, index: this.indices[i], strings });
855
- this.opened[i] = db;
856
- return db;
839
+ return this.opened[i] = SigDatabase.openSyncFrom((0, decompress_1.resolveSource)(this.baseDir, ref.path), { cacheDir: this.cacheDir, hash: ref.hash, index: this.indices[i], strings });
857
840
  }
858
841
  /**
859
842
  * Warm the shards (and their shared dictionaries) needed for `pkgs`, or **everything** when omitted.
860
843
  * Afterward, the synchronous query methods, for the latest *and* historical versions, do no I/O or decompression.
861
844
  */
862
845
  async preload(pkgs) {
863
- const need = new Set();
864
- if (pkgs) {
865
- for (const p of pkgs) {
866
- for (const i of this.routes.get(p) ?? []) {
867
- need.add(i);
868
- }
869
- }
870
- }
871
- else {
872
- this.manifest.shards.forEach((_, i) => need.add(i));
873
- }
874
- await this.warmShards(need);
846
+ const need = pkgs ? pkgs.flatMap(p => this.routes.get(p) ?? []) : this.manifest.shards.map((_, i) => i);
847
+ await this.warmShards(new Set(need));
875
848
  }
876
849
  /**
877
850
  * Warm just the shards matching `include`, e.g., only the current-tier top shards (the base + most-downloaded
878
851
  * packages) to speed up common lookups without paying for the long tail or the history shards. See {@link preload}.
879
852
  */
880
853
  async preloadShards(include) {
881
- const need = new Set();
882
- this.manifest.shards.forEach((s, i) => {
883
- if (include(s)) {
884
- need.add(i);
885
- }
886
- });
887
- await this.warmShards(need);
854
+ await this.warmShards(new Set(this.manifest.shards.flatMap((s, i) => include(s) ? [i] : [])));
888
855
  }
889
856
  /** decompress the given shards + their shared dictionaries concurrently, then open them (see {@link preload}) */
890
857
  async warmShards(need) {
@@ -912,7 +879,7 @@ class SigDatabaseSet {
912
879
  /** read (once) the blob from the shard with the most complete history: a `full` or `history` tier if present */
913
880
  historyBlob(pkg) {
914
881
  const candidates = this.routes.get(pkg);
915
- if (!candidates || candidates.length === 0) {
882
+ if (!candidates?.length) {
916
883
  return undefined;
917
884
  }
918
885
  const full = candidates.find(i => this.manifest.shards[i].tier === 'full' || this.manifest.shards[i].tier === 'history');
@@ -997,10 +964,7 @@ class SigDatabaseSet {
997
964
  /** whether this is an R-core / base package (see {@link SigDatabase.isBaseR}); O(1) via the hoisted metadata */
998
965
  isBaseR(pkg) {
999
966
  const meta = this.manifest.meta?.[pkg];
1000
- if (meta) {
1001
- return meta[3] === 1;
1002
- }
1003
- return this.route(pkg).some(i => this.shard(i).isBaseR(pkg));
967
+ return meta ? meta[3] === 1 : this.route(pkg).some(i => this.shard(i).isBaseR(pkg));
1004
968
  }
1005
969
  /** the download count of the package; O(1) via the hoisted metadata, so no shard has to be unpacked for it */
1006
970
  downloads(pkg) {
@@ -1023,8 +987,8 @@ class SigDatabaseSet {
1023
987
  return undefined;
1024
988
  }
1025
989
  const ver = version ?? (0, sigdb_version_1.newestVersion)(blob, this.manifest.meta?.[pkg]?.[0] ?? '');
1026
- const day = ver !== undefined ? blob.dates[ver] : undefined;
1027
- return day !== undefined ? new Date((0, sigdb_version_1.dayToMillis)(day)) : undefined;
990
+ const day = ver === undefined ? undefined : blob.dates[ver];
991
+ return day === undefined ? undefined : new Date((0, sigdb_version_1.dayToMillis)(day));
1028
992
  }
1029
993
  latestVersion(pkg) {
1030
994
  const blob = this.historyBlob(pkg);
@@ -1056,12 +1020,9 @@ function isSyncOpenable(source) {
1056
1020
  */
1057
1021
  function getSharedSigSourceSync(source) {
1058
1022
  const cached = sharedSources.get(source);
1059
- if (cached) {
1023
+ if (cached || !isSyncOpenable(source)) {
1060
1024
  return cached;
1061
1025
  }
1062
- if (!isSyncOpenable(source)) {
1063
- return undefined;
1064
- }
1065
1026
  const opened = source.endsWith(schema_1.SigDbExt) ? SigDatabase.openSync(source) : SigDatabaseSet.openManifestSync(source);
1066
1027
  sharedSources.set(source, opened);
1067
1028
  return opened;
@@ -1107,7 +1068,8 @@ async function verifyShardedDatabase(manifestFile, opts = {}) {
1107
1068
  }
1108
1069
  // 2. every shard's content hash, recomputed from its re-read blobs, matches the manifest and the file header
1109
1070
  const shardResults = [];
1110
- for (const { ref, db } of set.allShards()) {
1071
+ const mounted = set.allShards();
1072
+ for (const { ref, db } of mounted) {
1111
1073
  const blobs = db.allBlobs();
1112
1074
  // shared-dictionary shards are hashed over blobs+pkgs only; self-contained shards over their whole content
1113
1075
  const actual = ref.dict ? (0, hash_1.shardHash)(blobs, db.index.pkgs) : db.contentHash(blobs);
@@ -1124,7 +1086,7 @@ async function verifyShardedDatabase(manifestFile, opts = {}) {
1124
1086
  }
1125
1087
  // 3. routing covers every package that any shard holds
1126
1088
  const routed = new Set(set.packageNames());
1127
- for (const { ref, db } of set.allShards()) {
1089
+ for (const { ref, db } of mounted) {
1128
1090
  for (const pkg of Object.keys(db.index.pkgs)) {
1129
1091
  if (!routed.has(pkg)) {
1130
1092
  errors.push(`package '${pkg}' in shard '${ref.id}' is not routed by the manifest`);
@@ -27,22 +27,45 @@ export interface SigDbDownloadOptions {
27
27
  readonly repo?: string;
28
28
  /** release version, i.e. tag `sigdb-v<version>` (default the running flowR version); ignored when the committed `sigdb.remote.json` is present, whose `tag` then drives the download */
29
29
  readonly version?: string;
30
- /** progress callback (one line per asset) */
30
+ /** progress callback (one line per step) */
31
31
  readonly onProgress?: (msg: string) => void;
32
32
  readonly force?: boolean;
33
33
  }
34
34
  export interface SigDbDownloadResult {
35
+ /** the release tag the files belong to */
36
+ readonly tag: string;
35
37
  /** the directory the bundle landed in (add it to `solver.sigdb.additionalPaths` to keep it mounted) */
36
38
  readonly dir: string;
37
39
  /** the manifest to mount (richest scope), or `undefined` if the release ships only standalone bundles */
38
40
  readonly manifest: string | undefined;
39
- /** every downloaded file */
41
+ /** every file of the bundle, downloaded now or already cached */
40
42
  readonly files: readonly string[];
43
+ /** the files fetched by this call */
44
+ readonly downloaded: readonly string[];
45
+ readonly bytes: number;
46
+ /** how long the sync took */
47
+ readonly ms: number;
48
+ /** bundle directories of other releases still in the cache (e.g., the one this sync replaces) */
49
+ readonly stale: readonly string[];
41
50
  }
51
+ /** Thrown when some files of a bundle could not be fetched; the others are cached, so a retry only fetches the rest. */
52
+ export declare class SigDbDownloadError extends Error {
53
+ readonly tag: string;
54
+ readonly failed: readonly {
55
+ readonly name: string;
56
+ readonly reason: string;
57
+ }[];
58
+ readonly completed: number;
59
+ constructor(tag: string, failed: readonly {
60
+ readonly name: string;
61
+ readonly reason: string;
62
+ }[], completed: number);
63
+ }
64
+ /** whether the file is a manifest (in any codec); these go last as they reference the shards */
65
+ export declare const isManifestFile: (name: string) => boolean;
42
66
  /**
43
- * Download the signature-database shards into the cache directory and return where they landed. Prefers the
44
- * committed `sigdb.remote.json`, we verify each download by content hash, and **skip shards already
45
- * present with the right hash**.
67
+ * Downloads the signature-database shards into the cache, verified by hash and skipping cached ones. A failing file
68
+ * does not stop the others; a {@link SigDbDownloadError} names what is missing at the end.
46
69
  * Use the returned {@link SigDbDownloadResult.manifest}, or point `solver.sigdb.additionalPaths` at the dir.
47
70
  */
48
71
  export declare function downloadFullSigDb(opts?: SigDbDownloadOptions): Promise<SigDbDownloadResult>;
@@ -60,5 +83,5 @@ export declare function sigDbRemoteRelease(): {
60
83
  } | undefined;
61
84
  /** Fast presence check (existence + byte size only, no hashing) for the shards the committed pointer selects for this runtime; `false` when no pointer is committed or any selected shard is missing/wrong-size. */
62
85
  export declare function sigDbCacheComplete(): boolean;
63
- /** Startup check: `true` when a committed link file lists shards whose cached copies are missing or hash-mismatched */
86
+ /** Startup check: `true` when a committed link file lists shards whose cached copies are missing or mismatched */
64
87
  export declare function sigDbNeedsSync(): boolean;