loadwise 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (228) hide show
  1. package/README.md +23 -15
  2. package/dist/bin/loadwise.js +12 -24
  3. package/dist/lib/accessibility/analyze.js +5 -3
  4. package/dist/lib/accessibility/angular-inline.js +9 -11
  5. package/dist/lib/accessibility/angular-literal.js +39 -0
  6. package/dist/lib/accessibility/form-context.js +36 -0
  7. package/dist/lib/accessibility/frame-head.js +92 -0
  8. package/dist/lib/accessibility/frame-viewport.js +149 -0
  9. package/dist/lib/accessibility/jsx-elements.js +13 -3
  10. package/dist/lib/accessibility/markup-files.js +7 -2
  11. package/dist/lib/accessibility/rule-ids.js +3 -0
  12. package/dist/lib/accessibility/rules.js +128 -41
  13. package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
  14. package/dist/lib/accessibility/template-attributes.js +5 -3
  15. package/dist/lib/accessibility/template-elements.js +25 -6
  16. package/dist/lib/accessibility/template-file.js +40 -25
  17. package/dist/lib/editor/accessibility-examples.js +6 -1
  18. package/dist/lib/editor/actions.js +46 -7
  19. package/dist/lib/editor/apply-fix.js +69 -4
  20. package/dist/lib/editor/configured-setup.js +5 -3
  21. package/dist/lib/editor/diagnostics.js +206 -17
  22. package/dist/lib/editor/dismissals.js +85 -26
  23. package/dist/lib/editor/editor-document.js +5 -2
  24. package/dist/lib/editor/editor-launcher.js +7 -2
  25. package/dist/lib/editor/language-server.js +64 -25
  26. package/dist/lib/editor/native-setup.js +3 -2
  27. package/dist/lib/editor/perf-watch.js +8 -6
  28. package/dist/lib/editor/reliability-examples.js +15 -0
  29. package/dist/lib/editor/scan-session.js +29 -8
  30. package/dist/lib/editor/server-commands.js +36 -9
  31. package/dist/lib/editor/setup-server.js +1 -1
  32. package/dist/lib/editor/setup-vim.js +6 -4
  33. package/dist/lib/editor/workspace-files.js +61 -7
  34. package/dist/lib/editor/workspace-paths.js +41 -1
  35. package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
  36. package/dist/lib/maintainability/architecture/architecture.js +4 -4
  37. package/dist/lib/maintainability/cli/changed-lines.js +20 -2
  38. package/dist/lib/maintainability/cli/inputs.js +9 -1
  39. package/dist/lib/maintainability/cli.js +4 -0
  40. package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
  41. package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
  42. package/dist/lib/maintainability/quality/functions.js +9 -6
  43. package/dist/lib/maintainability/quality/limits.js +19 -0
  44. package/dist/lib/maintainability/quality/size-limits.js +8 -2
  45. package/dist/lib/maintainability/quality/stray-console.js +62 -1
  46. package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
  47. package/dist/lib/maintainability/scan-changed.js +4 -1
  48. package/dist/lib/maintainability/scan-worker.js +6 -2
  49. package/dist/lib/maintainability/scan.js +21 -8
  50. package/dist/lib/maintainability/unused/module-usage.js +43 -21
  51. package/dist/lib/maintainability/unused/unused-modules.js +5 -10
  52. package/dist/lib/performance/analysis/source-inputs.js +7 -2
  53. package/dist/lib/performance/analysis/source-options.js +7 -6
  54. package/dist/lib/performance/analyze.js +16 -3
  55. package/dist/lib/performance/cli/cli-output.js +1 -0
  56. package/dist/lib/performance/cli/cli-scan.js +21 -2
  57. package/dist/lib/performance/cli.js +8 -3
  58. package/dist/lib/performance/collections/memory-growth.js +55 -12
  59. package/dist/lib/performance/contracts/openapi.js +13 -4
  60. package/dist/lib/performance/datastores/pg-integrity.js +61 -22
  61. package/dist/lib/performance/datastores/pg-session-release.js +114 -0
  62. package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
  63. package/dist/lib/performance/datastores/pooling.js +56 -2
  64. package/dist/lib/performance/datastores/redis.js +94 -18
  65. package/dist/lib/performance/datastores/session-store.js +2 -1
  66. package/dist/lib/performance/db/checks.js +19 -8
  67. package/dist/lib/performance/db/gateway.js +3 -1
  68. package/dist/lib/performance/db/plan-estimates.js +4 -4
  69. package/dist/lib/performance/engine/native.js +11 -7
  70. package/dist/lib/performance/evidence/plans.js +7 -5
  71. package/dist/lib/performance/evidence/traces.js +21 -1
  72. package/dist/lib/performance/frontend/angular-teardown.js +96 -0
  73. package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
  74. package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
  75. package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
  76. package/dist/lib/performance/frontend/frontend-perf.js +72 -57
  77. package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
  78. package/dist/lib/performance/migrations/extract-code.js +13 -5
  79. package/dist/lib/performance/migrations/extract-sql.js +82 -38
  80. package/dist/lib/performance/migrations/operations.js +56 -13
  81. package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
  82. package/dist/lib/performance/migrations/postgres-registry.js +127 -26
  83. package/dist/lib/performance/migrations/postgres-settings.js +78 -0
  84. package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
  85. package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
  86. package/dist/lib/performance/migrations/rules-postgres.js +88 -39
  87. package/dist/lib/performance/orm/offset-pagination.js +6 -4
  88. package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
  89. package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
  90. package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
  91. package/dist/lib/performance/polyglot.js +111 -14
  92. package/dist/lib/performance/projects.js +3 -3
  93. package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
  94. package/dist/lib/performance/request/backend-mastery.js +151 -42
  95. package/dist/lib/performance/request/mongoose-lean.js +175 -10
  96. package/dist/lib/performance/request/phase5-rules.js +74 -13
  97. package/dist/lib/performance/request/sql-select-star.js +150 -0
  98. package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
  99. package/dist/lib/performance/request/upload-limits.js +5 -1
  100. package/dist/lib/performance/site-fix.js +4 -4
  101. package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
  102. package/dist/lib/performance/site-fixes/frontend-fixes.js +350 -10
  103. package/dist/lib/performance/site-fixes/migration-context.js +8 -1
  104. package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
  105. package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
  106. package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
  107. package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
  108. package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
  109. package/dist/lib/performance/sql/mysql-tokens.js +38 -12
  110. package/dist/lib/reliability/boundary-access.js +114 -57
  111. package/dist/lib/reliability/react-bugs.js +18 -4
  112. package/dist/lib/reliability/resource-leak-intervals.js +258 -0
  113. package/dist/lib/reliability/resource-leaks.js +209 -195
  114. package/dist/lib/reliability/rule-ids.js +10 -1
  115. package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
  116. package/dist/lib/reliability/swallowed-errors.js +107 -21
  117. package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
  118. package/dist/lib/reliability/walk.js +3 -2
  119. package/dist/lib/security/auth-crypto/hashing.js +24 -8
  120. package/dist/lib/security/auth-crypto/jwt.js +21 -6
  121. package/dist/lib/security/auth-crypto/secrets.js +44 -1
  122. package/dist/lib/security/auth-crypto/shared.js +3 -1
  123. package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
  124. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
  125. package/dist/lib/security/cli.js +6 -2
  126. package/dist/lib/security/cookie-credentials.js +115 -0
  127. package/dist/lib/security/cookie-csrf.js +241 -0
  128. package/dist/lib/security/deps/advisory.js +50 -109
  129. package/dist/lib/security/deps/cli.js +1 -1
  130. package/dist/lib/security/deps/cvss-score.js +14 -0
  131. package/dist/lib/security/deps/fixed-version.js +97 -0
  132. package/dist/lib/security/deps/lockfiles.js +135 -74
  133. package/dist/lib/security/deps/osv.js +11 -3
  134. package/dist/lib/security/deps/scan.js +47 -20
  135. package/dist/lib/security/deps/yarn-lock.js +158 -0
  136. package/dist/lib/security/examples/injection.cjs +4 -0
  137. package/dist/lib/security/exposure/cookies.js +17 -2
  138. package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
  139. package/dist/lib/security/exposure/frontend-security.js +21 -14
  140. package/dist/lib/security/exposure/jsx-url.js +18 -33
  141. package/dist/lib/security/exposure/logging.js +49 -10
  142. package/dist/lib/security/exposure/prototype-pollution.js +126 -56
  143. package/dist/lib/security/exposure/react-html.js +26 -0
  144. package/dist/lib/security/exposure/reflected-xss.js +34 -5
  145. package/dist/lib/security/files/compose.js +126 -1
  146. package/dist/lib/security/files/dockerfile.js +62 -4
  147. package/dist/lib/security/files/index.js +1 -1
  148. package/dist/lib/security/injection/command.js +46 -18
  149. package/dist/lib/security/injection/index.js +2 -0
  150. package/dist/lib/security/injection/ldap.js +86 -0
  151. package/dist/lib/security/injection/nosql.js +28 -4
  152. package/dist/lib/security/injection/redos.js +1 -1
  153. package/dist/lib/security/injection/rule-ids.js +1 -0
  154. package/dist/lib/security/injection/shared.js +5 -1
  155. package/dist/lib/security/injection/sql.js +28 -13
  156. package/dist/lib/security/lexical-declaration.js +113 -0
  157. package/dist/lib/security/pg-dynamic-query.js +28 -1
  158. package/dist/lib/security/pg-identifier-guards.js +107 -3
  159. package/dist/lib/security/phase5-rules.js +26 -135
  160. package/dist/lib/security/polyglot.js +2 -2
  161. package/dist/lib/security/redirect-settings.js +98 -0
  162. package/dist/lib/security/request-forgery/open-redirect.js +18 -5
  163. package/dist/lib/security/request-forgery/path-traversal.js +84 -6
  164. package/dist/lib/security/request-forgery/shared.js +1 -7
  165. package/dist/lib/security/request-forgery/ssrf.js +176 -14
  166. package/dist/lib/security/rule-descriptions.js +5 -1
  167. package/dist/lib/security/rule-ids.js +7 -0
  168. package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
  169. package/dist/lib/security/site-fixes/exposure.js +21 -3
  170. package/dist/lib/security/site-fixes/files.js +11 -13
  171. package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
  172. package/dist/lib/security/site-fixes/injection.js +17 -4
  173. package/dist/lib/security/site-fixes/jwt.js +1 -20
  174. package/dist/lib/security/site-fixes/request-forgery.js +37 -29
  175. package/dist/lib/security/taint/binding-inputs.js +236 -0
  176. package/dist/lib/security/taint/filename-guard.js +45 -45
  177. package/dist/lib/security/taint/guards.js +14 -8
  178. package/dist/lib/security/taint/index.js +126 -154
  179. package/dist/lib/security/taint/propagate.js +43 -9
  180. package/dist/lib/security/taint/record-writes.js +161 -0
  181. package/dist/lib/security/taint/resolution-cache.js +13 -7
  182. package/dist/lib/security/taint/sanitizers.js +89 -5
  183. package/dist/lib/security/taint/trace-nodes.js +61 -0
  184. package/dist/lib/security/taint/validators.js +89 -9
  185. package/dist/lib/shared/agent/agent-init.js +2 -1
  186. package/dist/lib/shared/agent/agent-verify.js +4 -1
  187. package/dist/lib/shared/agent/git-hook.js +17 -6
  188. package/dist/lib/shared/agent/review-mcp.js +8 -2
  189. package/dist/lib/shared/analysis/ast-semantics.js +2 -2
  190. package/dist/lib/shared/analysis/scan-cache.js +96 -12
  191. package/dist/lib/shared/cli-dispatch.js +17 -0
  192. package/dist/lib/shared/config.js +27 -10
  193. package/dist/lib/shared/explain.js +1 -1
  194. package/dist/lib/shared/fix/fix-convergence.js +5 -3
  195. package/dist/lib/shared/fix/fix-imports.js +4 -171
  196. package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
  197. package/dist/lib/shared/fix/fix-presentation.js +5 -3
  198. package/dist/lib/shared/fix/fix-safety.js +7 -1
  199. package/dist/lib/shared/fix/fix-typecheck.js +8 -4
  200. package/dist/lib/shared/fix/import-text-edits.js +148 -0
  201. package/dist/lib/shared/fix.js +31 -7
  202. package/dist/lib/shared/formats/finding-location.js +4 -1
  203. package/dist/lib/shared/formats/github.js +3 -3
  204. package/dist/lib/shared/formats/sarif.js +9 -3
  205. package/dist/lib/shared/report-fp.js +6 -2
  206. package/dist/lib/shared/reporting/baseline.js +7 -5
  207. package/dist/lib/shared/reporting/pillars.js +9 -3
  208. package/dist/lib/shared/reporting/source-report.js +1 -0
  209. package/dist/lib/shared/system/glob.js +34 -8
  210. package/dist/lib/shared/system/sentry.js +26 -7
  211. package/dist/lib/shared/workspaces.js +15 -3
  212. package/package.json +5 -1
  213. package/plugin/.claude-plugin/plugin.json +1 -1
  214. package/plugin/hooks/check-edited-file.mjs +27 -5
  215. package/polyglot/performance/rules/csharp.yml +34 -5
  216. package/polyglot/performance/rules/java.yml +24 -1
  217. package/polyglot/performance/rules/python.yml +74 -2
  218. package/polyglot/performance/sgconfig.yml +1 -0
  219. package/polyglot/reliability/rules/csharp.yml +12 -6
  220. package/polyglot/reliability/rules/go.yml +86 -6
  221. package/polyglot/reliability/rules/java.yml +22 -1
  222. package/polyglot/reliability/sgconfig.yml +1 -0
  223. package/polyglot/security/rules/go.yml +100 -22
  224. package/polyglot/security/rules/python.yml +74 -6
  225. package/polyglot/security/rules/rust.yml +65 -0
  226. package/polyglot/security/sgconfig.yml +1 -0
  227. package/schema/loadwise.config.schema.json +554 -76
  228. /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
@@ -0,0 +1,144 @@
1
+ import { parseStatements } from '../sql/pg-parser.js';
2
+ export const sessionSqlCandidate = /\b(?:listen|unlisten|discard|pg_(?:try_)?advisory_)/i;
3
+ const transactionCandidate = /\b(?:begin|start\s+transaction|commit|rollback|abort|end|savepoint|release)\b/i;
4
+ const advisoryAcquire = new Set([
5
+ 'pg_advisory_lock',
6
+ 'pg_advisory_lock_shared',
7
+ 'pg_try_advisory_lock',
8
+ 'pg_try_advisory_lock_shared',
9
+ ]);
10
+ const advisoryRelease = new Set(['pg_advisory_unlock', 'pg_advisory_unlock_shared']);
11
+ export function newSessionEffects() {
12
+ return { advisoryLocks: new Map(), subscriptions: new Set(), savepoints: [] };
13
+ }
14
+ function knownLockKey(args) {
15
+ const numbers = args.map(({ A_Const: constant }) => {
16
+ if (constant?.ival)
17
+ return String(constant.ival.ival ?? 0);
18
+ const bigInteger = constant?.fval?.fval;
19
+ return bigInteger && /^-?\d+$/.test(bigInteger) ? bigInteger : undefined;
20
+ });
21
+ if (numbers.length && numbers.every((number) => number !== undefined))
22
+ return numbers.join(',');
23
+ }
24
+ function decrementLock(locks, exactKey, kind) {
25
+ const candidates = [...locks.keys()].filter((held) => held === exactKey || held === kind || (exactKey === kind && held.startsWith(kind)));
26
+ // An ambiguous unlock can discharge any matching entry. Keep the remaining count while
27
+ // deferring which specific key remains, so a later literal unlock can still match it.
28
+ if (candidates.length > 1) {
29
+ let remaining = -1;
30
+ for (const candidate of candidates) {
31
+ remaining += locks.get(candidate) ?? 0;
32
+ locks.delete(candidate);
33
+ }
34
+ if (remaining > 0)
35
+ locks.set(kind, remaining);
36
+ return;
37
+ }
38
+ const [key] = candidates;
39
+ if (key === undefined)
40
+ return;
41
+ const count = locks.get(key) ?? 0;
42
+ if (count > 1)
43
+ locks.set(key, count - 1);
44
+ else
45
+ locks.delete(key);
46
+ }
47
+ function applyAdvisoryEffect(node, effects) {
48
+ let value = node.ResTarget?.val;
49
+ while (value?.TypeCast)
50
+ value = value.TypeCast.arg;
51
+ const call = value?.FuncCall;
52
+ const names = call?.funcname ?? [];
53
+ if (names.length > 2 || (names.length === 2 && names[0].String?.sval !== 'pg_catalog'))
54
+ return;
55
+ const name = names.at(-1)?.String?.sval;
56
+ if (!name)
57
+ return;
58
+ const kind = name.endsWith('_shared') ? 'shared:' : 'exclusive:';
59
+ const key = kind + (knownLockKey(call?.args ?? []) ?? '');
60
+ const locks = effects.advisoryLocks;
61
+ if (advisoryAcquire.has(name))
62
+ locks.set(key, (locks.get(key) ?? 0) + 1);
63
+ else if (advisoryRelease.has(name))
64
+ decrementLock(locks, key, kind);
65
+ else if (name === 'pg_advisory_unlock_all')
66
+ locks.clear();
67
+ }
68
+ function updateSubscriptionSavepoints(transaction, effects) {
69
+ const name = transaction.savepoint_name;
70
+ if (!name || !effects.pendingSubscriptions)
71
+ return;
72
+ if (transaction.kind === 'TRANS_STMT_SAVEPOINT') {
73
+ effects.savepoints.push({ name, subscriptions: new Set(effects.pendingSubscriptions) });
74
+ return;
75
+ }
76
+ const position = effects.savepoints.findLastIndex((savepoint) => savepoint.name === name);
77
+ if (position < 0)
78
+ return;
79
+ if (transaction.kind === 'TRANS_STMT_ROLLBACK_TO') {
80
+ effects.pendingSubscriptions = new Set(effects.savepoints[position].subscriptions);
81
+ effects.savepoints.length = position + 1;
82
+ }
83
+ else if (transaction.kind === 'TRANS_STMT_RELEASE')
84
+ effects.savepoints.length = position;
85
+ }
86
+ function applySubscriptionEffect(node, effects) {
87
+ const transaction = node.TransactionStmt;
88
+ if (transaction?.kind === 'TRANS_STMT_BEGIN' || transaction?.kind === 'TRANS_STMT_START')
89
+ effects.pendingSubscriptions ??= new Set(effects.subscriptions);
90
+ if (transaction?.kind === 'TRANS_STMT_COMMIT' || transaction?.kind === 'TRANS_STMT_ROLLBACK') {
91
+ if (transaction.kind === 'TRANS_STMT_COMMIT' && effects.pendingSubscriptions)
92
+ effects.subscriptions = effects.pendingSubscriptions;
93
+ effects.pendingSubscriptions = transaction.chain ? new Set(effects.subscriptions) : undefined;
94
+ effects.savepoints.length = 0;
95
+ }
96
+ if (transaction)
97
+ updateSubscriptionSavepoints(transaction, effects);
98
+ const subscriptions = effects.pendingSubscriptions ?? effects.subscriptions;
99
+ const added = node.ListenStmt?.conditionname;
100
+ if (added)
101
+ subscriptions.add(added);
102
+ if (node.UnlistenStmt) {
103
+ const removed = node.UnlistenStmt.conditionname;
104
+ if (removed)
105
+ subscriptions.delete(removed);
106
+ else
107
+ subscriptions.clear();
108
+ }
109
+ }
110
+ function applyNode(node, effects) {
111
+ applySubscriptionEffect(node, effects);
112
+ if (node.DiscardStmt?.target === 'DISCARD_ALL' && !effects.pendingSubscriptions) {
113
+ effects.subscriptions.clear();
114
+ effects.advisoryLocks.clear();
115
+ }
116
+ const selection = node.SelectStmt;
117
+ const filter = selection?.whereClause;
118
+ const limit = selection?.limitCount;
119
+ const condition = filter?.A_Const;
120
+ if (condition?.isnull || (condition?.boolval && !condition.boolval.boolval))
121
+ return;
122
+ if (limit?.A_Const?.ival && !limit.A_Const.ival.ival)
123
+ return;
124
+ for (const target of selection?.targetList ?? [])
125
+ applyAdvisoryEffect(target, effects);
126
+ }
127
+ // The main scanner initializes the parser before scanning source files. Callers that skip that
128
+ // preparation cannot establish a session effect for SQL that needs parsing.
129
+ export function recordSessionEffects(text, effects) {
130
+ if (!sessionSqlCandidate.test(text) && !transactionCandidate.test(text))
131
+ return true;
132
+ try {
133
+ const statements = parseStatements(text);
134
+ if (statements.some(({ error }) => error !== undefined))
135
+ return false;
136
+ for (const { node } of statements)
137
+ if (node)
138
+ applyNode(node, effects);
139
+ return true;
140
+ }
141
+ catch {
142
+ return false;
143
+ }
144
+ }
@@ -116,12 +116,65 @@ function guardsSharedBinding(guard, destination, owner, checker) {
116
116
  declaration.pos < owner.pos ||
117
117
  declaration.end > owner.end));
118
118
  }
119
+ function isOutsideOwner(node, owner) {
120
+ return node.getSourceFile() !== owner.getSourceFile() || node.pos < owner.pos || node.end > owner.end;
121
+ }
122
+ function isPersistentTarget(target, owner, checker) {
123
+ if (ts.isIdentifier(target)) {
124
+ const declaration = checker.getSymbolAtLocation(target)?.valueDeclaration;
125
+ return Boolean(declaration && isOutsideOwner(declaration, owner));
126
+ }
127
+ let root = target;
128
+ while (ts.isPropertyAccessExpression(root) || ts.isElementAccessExpression(root)) {
129
+ root = unwrapExpression(root.expression);
130
+ }
131
+ if (root.kind === ts.SyntaxKind.ThisKeyword) {
132
+ const thisOwner = thisBindingOwner(target);
133
+ return Boolean(thisOwner && isOutsideOwner(thisOwner, owner));
134
+ }
135
+ if (ts.isIdentifier(root)) {
136
+ const declaration = aliasedDeclaration(root, checker);
137
+ return Boolean(declaration && isOutsideOwner(declaration, owner));
138
+ }
139
+ return false;
140
+ }
141
+ // An object literal only binds `this` for its methods and accessors, not for property initializers.
142
+ function thisBindingOwner(target) {
143
+ for (let child = target, current = target.parent; current; child = current, current = current.parent) {
144
+ if (ts.isClassLike(current))
145
+ return current;
146
+ if (ts.isObjectLiteralExpression(current) && ts.isFunctionLike(child) && !ts.isArrowFunction(child))
147
+ return current;
148
+ }
149
+ }
150
+ // Follows `const alias = other` chains so a loop-local alias of shared storage is still shared.
151
+ function aliasedDeclaration(identifier, checker) {
152
+ let current = identifier;
153
+ for (let depth = 0; depth < 8; depth++) {
154
+ const declaration = resolvedSymbol(current, checker)?.valueDeclaration;
155
+ if (!declaration ||
156
+ !ts.isVariableDeclaration(declaration) ||
157
+ !(declaration.parent.flags & ts.NodeFlags.Const) ||
158
+ !declaration.initializer)
159
+ return declaration;
160
+ const initializer = unwrapExpression(declaration.initializer);
161
+ if (!ts.isIdentifier(initializer))
162
+ return declaration;
163
+ current = initializer;
164
+ }
165
+ return resolvedSymbol(current, checker)?.valueDeclaration;
166
+ }
167
+ // An imported binding has no value declaration of its own; follow it to the exporting module.
168
+ function resolvedSymbol(identifier, checker) {
169
+ const symbol = checker.getSymbolAtLocation(identifier);
170
+ return symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
171
+ }
119
172
  function cachedInitialization(node, owner, checker) {
120
173
  let destination;
121
174
  for (let child = node, parent = node.parent; parent && parent !== owner; child = parent, parent = parent.parent) {
122
175
  if (ts.isBinaryExpression(parent) && parent.right === child) {
123
176
  const operator = parent.operatorToken.kind;
124
- if (cachingOperators().includes(operator))
177
+ if (cachingOperators().includes(operator) && isPersistentTarget(unwrapExpression(parent.left), owner, checker))
125
178
  return true;
126
179
  if (operator === ts.SyntaxKind.EqualsToken)
127
180
  destination = unwrapExpression(parent.left);
@@ -130,7 +183,8 @@ function cachedInitialization(node, owner, checker) {
130
183
  const guard = unwrapExpression(parent.expression);
131
184
  if (ts.isPrefixUnaryExpression(guard) &&
132
185
  guard.operator === ts.SyntaxKind.ExclamationToken &&
133
- unwrapExpression(guard.operand).getText() === destination.getText())
186
+ unwrapExpression(guard.operand).getText() === destination.getText() &&
187
+ isPersistentTarget(destination, owner, checker))
134
188
  return true;
135
189
  if (guardsSharedBinding(guard, destination, owner, checker))
136
190
  return true;
@@ -126,27 +126,103 @@ function sourceText(node) {
126
126
  const sourceFile = node.getSourceFile();
127
127
  return sourceFile.text.slice(node.getStart(sourceFile), node.end);
128
128
  }
129
- // The first `expire`-family call after `counter` in the same function on the same client and key.
130
- function followingExpire(counter, receiverText, keyText) {
131
- const enclosing = ts.findAncestor(counter.parent, ts.isFunctionLike);
132
- const scope = (enclosing && 'body' in enclosing ? enclosing.body : undefined) ?? counter.getSourceFile();
129
+ function findExpireInSubtree(node, minPos, receiverText, keyText) {
130
+ if (ts.isFunctionLike(node))
131
+ return undefined;
132
+ if (node.pos >= minPos &&
133
+ ts.isCallExpression(node) &&
134
+ ts.isPropertyAccessExpression(node.expression) &&
135
+ expireCommands.has(node.expression.name.text.toLowerCase()) &&
136
+ node.arguments[0] &&
137
+ sourceText(ts.skipOuterExpressions(node.expression.expression)) === receiverText &&
138
+ sourceText(ts.skipOuterExpressions(node.arguments[0])) === keyText) {
139
+ return node.expression;
140
+ }
141
+ if (ts.isBlock(node) || ts.isCaseClause(node) || ts.isDefaultClause(node)) {
142
+ // Statements after an unconditional exit never run, so an expiry there is not a real match.
143
+ for (const statement of node.statements) {
144
+ const match = findExpireInSubtree(statement, minPos, receiverText, keyText);
145
+ if (match)
146
+ return match;
147
+ if (unconditionalExit(statement))
148
+ return undefined;
149
+ }
150
+ return undefined;
151
+ }
133
152
  let found;
134
- (function visit(node) {
135
- if (found)
136
- return;
137
- if (node.pos >= counter.end &&
138
- ts.isCallExpression(node) &&
139
- ts.isPropertyAccessExpression(node.expression) &&
140
- expireCommands.has(node.expression.name.text.toLowerCase()) &&
141
- node.arguments[0] &&
142
- sourceText(ts.skipOuterExpressions(node.expression.expression)) === receiverText &&
143
- sourceText(ts.skipOuterExpressions(node.arguments[0])) === keyText)
144
- found = node.expression;
145
- else
146
- ts.forEachChild(node, visit);
147
- })(scope);
153
+ ts.forEachChild(node, (child) => {
154
+ if (!found)
155
+ found = findExpireInSubtree(child, minPos, receiverText, keyText);
156
+ });
148
157
  return found;
149
158
  }
159
+ function unconditionalExit(statement) {
160
+ if (ts.isReturnStatement(statement) ||
161
+ ts.isThrowStatement(statement) ||
162
+ ts.isBreakStatement(statement) ||
163
+ ts.isContinueStatement(statement)) {
164
+ return true;
165
+ }
166
+ if (ts.isBlock(statement))
167
+ return statement.statements.some(unconditionalExit);
168
+ if (ts.isIfStatement(statement)) {
169
+ return (statement.elseStatement !== undefined &&
170
+ unconditionalExit(statement.thenStatement) &&
171
+ unconditionalExit(statement.elseStatement));
172
+ }
173
+ if (ts.isLabeledStatement(statement))
174
+ return unconditionalExit(statement.statement);
175
+ return false;
176
+ }
177
+ // What follows `statements[startIndex]` in one statement list: the first `expire`-family call, and
178
+ // whether a statement always leaves the path before the list ends.
179
+ function expireAfterStatement(statements, startIndex, counterEnd, receiverText, keyText) {
180
+ if (unconditionalExit(statements[startIndex]))
181
+ return { exited: true };
182
+ for (let index = startIndex + 1; index < statements.length; index++) {
183
+ const match = findExpireInSubtree(statements[index], counterEnd, receiverText, keyText);
184
+ if (match)
185
+ return { match, exited: false };
186
+ if (unconditionalExit(statements[index]))
187
+ return { exited: true };
188
+ }
189
+ return { exited: false };
190
+ }
191
+ // The first `expire`-family call reachable after `counter` on the same execution path, on the same
192
+ // client and key.
193
+ function followingExpire(counter, receiverText, keyText) {
194
+ for (let child = counter, parent = child.parent; parent; child = parent, parent = parent.parent) {
195
+ if (ts.isFunctionLike(parent))
196
+ break;
197
+ if (ts.isBlock(parent) || ts.isSourceFile(parent) || ts.isCaseClause(parent) || ts.isDefaultClause(parent)) {
198
+ const statements = parent.statements;
199
+ const startIndex = statements.findIndex((statement) => statement === child || (statement.pos <= child.pos && child.end <= statement.end));
200
+ if (startIndex < 0)
201
+ continue;
202
+ const following = expireAfterStatement(statements, startIndex, counter.end, receiverText, keyText);
203
+ if (following.match)
204
+ return following.match;
205
+ if (following.exited)
206
+ return undefined;
207
+ continue;
208
+ }
209
+ if (ts.isIfStatement(parent) ||
210
+ ts.isConditionalExpression(parent) ||
211
+ ts.isSwitchStatement(parent) ||
212
+ ts.isCaseBlock(parent)) {
213
+ continue;
214
+ }
215
+ let found;
216
+ ts.forEachChild(parent, (sibling) => {
217
+ if (!found && sibling !== child && sibling.pos >= child.end) {
218
+ found = findExpireInSubtree(sibling, counter.end, receiverText, keyText);
219
+ }
220
+ });
221
+ if (found)
222
+ return found;
223
+ }
224
+ return undefined;
225
+ }
150
226
  function incrThenExpireMessage(label, counterMethod, expireMethod) {
151
227
  const counter = `${label}.${counterMethod}`;
152
228
  const expire = `${label}.${expireMethod}`;
@@ -1,4 +1,5 @@
1
1
  import { ts } from '../engine/compiler.js';
2
+ import { staticPropertyName } from '../../shared/analysis/ast-semantics.js';
2
3
  const RULE_ID = 'session-memory-store';
3
4
  const EXPRESS_SESSION = 'express-session';
4
5
  const FASTIFY_SESSION = '@fastify/session';
@@ -53,7 +54,7 @@ function resolveObjectLiteral(expression, context) {
53
54
  // A spread may carry a `store`, so only an object with no spread and no `store` key is certain to
54
55
  // use memory.
55
56
  function lacksStore(options) {
56
- return options.properties.every((property) => !ts.isSpreadAssignment(property) && property.name?.getText() !== 'store');
57
+ return options.properties.every((property) => !ts.isSpreadAssignment(property) && staticPropertyName(property.name) !== 'store');
57
58
  }
58
59
  function hasNoStore(optionsArgument, context) {
59
60
  const options = resolveObjectLiteral(optionsArgument, context);
@@ -41,6 +41,14 @@ function toNumber(value) {
41
41
  function tableKey(schema, name) {
42
42
  return `${schema}.${name}`;
43
43
  }
44
+ function quoteDottedPart(name) {
45
+ return /[."]/.test(name) ? quoteIdent(name) : name;
46
+ }
47
+ // Keep ordinary catalog keys stable. Quote a component when it could otherwise be read as
48
+ // multiple components or be mistaken for an already quoted name.
49
+ function postgresTableKey(schema, name) {
50
+ return `${quoteDottedPart(schema)}.${quoteDottedPart(name)}`;
51
+ }
44
52
  function qualified(schema, name) {
45
53
  return `${quoteIdent(schema)}.${quoteIdent(name)}`;
46
54
  }
@@ -91,7 +99,7 @@ function rowEstimateOf(row) {
91
99
  function buildPostgresModel({ tables = [], columns = [], indexes = [], foreignKeys = [], }) {
92
100
  const model = new Map();
93
101
  for (const row of tables) {
94
- model.set(tableKey(row.schema_name, row.table_name), {
102
+ model.set(postgresTableKey(row.schema_name, row.table_name), {
95
103
  schema: row.schema_name,
96
104
  name: row.table_name,
97
105
  rowEstimate: rowEstimateOf(row),
@@ -105,7 +113,7 @@ function buildPostgresModel({ tables = [], columns = [], indexes = [], foreignKe
105
113
  foreignKeys: [],
106
114
  });
107
115
  }
108
- const tableOf = (row) => model.get(tableKey(row.schema_name, row.table_name));
116
+ const tableOf = (row) => model.get(postgresTableKey(row.schema_name, row.table_name));
109
117
  for (const row of columns)
110
118
  tableOf(row)?.columns.push(row.column_name);
111
119
  for (const row of indexes)
@@ -114,7 +122,10 @@ function buildPostgresModel({ tables = [], columns = [], indexes = [], foreignKe
114
122
  tableOf(row)?.foreignKeys.push({
115
123
  name: row.constraint_name,
116
124
  columns: row.columns,
117
- references: { table: tableKey(row.referenced_schema, row.referenced_table), columns: row.referenced_columns },
125
+ references: {
126
+ table: postgresTableKey(row.referenced_schema, row.referenced_table),
127
+ columns: row.referenced_columns,
128
+ },
118
129
  });
119
130
  }
120
131
  return model;
@@ -150,7 +161,7 @@ function unindexedForeignKeys(model) {
150
161
  const fix = createIndexSql(table, foreignKey.columns);
151
162
  const columnList = foreignKey.columns.map((column) => `\`${column}\``).join(', ');
152
163
  findings.push({
153
- target: tableKey(table.schema, table.name),
164
+ target: postgresTableKey(table.schema, table.name),
154
165
  ruleId: 'db-unindexed-foreign-key',
155
166
  message: `Foreign key \`${foreignKey.name}\` (${columnList}) references \`${foreignKey.references.table}\` and no ` +
156
167
  `index starts with it, so joins on it scan \`${table.name}\` and every delete or key update on the ` +
@@ -178,7 +189,7 @@ function unusedIndexes(model, statsAgeDays) {
178
189
  const size = index.sizeBytes === undefined ? '' : ` It takes ${formatBytes(index.sizeBytes)} (measured) and`;
179
190
  const age = sinceEvent(statsAgeDays, 'statistics were reset');
180
191
  const finding = {
181
- target: tableKey(table.schema, table.name),
192
+ target: postgresTableKey(table.schema, table.name),
182
193
  ruleId: 'db-unused-index',
183
194
  message: `Index \`${index.name}\` on \`${table.name}\` was scanned 0 times (measured) ${age} on this server; ` +
184
195
  `replicas keep their own counters and are not counted.${size || ' It'} slows every write to the table. ` +
@@ -243,7 +254,7 @@ function tableDuplicateIndexes(table) {
243
254
  const fix = dropIndexSql(table, redundant);
244
255
  const relation = redundant.keys.length === kept.keys.length ? 'has the same keys as' : 'is a leading prefix of';
245
256
  findings.push({
246
- target: tableKey(table.schema, table.name),
257
+ target: postgresTableKey(table.schema, table.name),
247
258
  ruleId: 'db-duplicate-index',
248
259
  message: `Index \`${redundant.name}\` (${describeKeys(redundant)}) ${relation} \`${kept.name}\` ` +
249
260
  `(${describeKeys(kept)}), which serves the same lookups, so it only slows writes. Drop it: \`${fix}\``,
@@ -268,7 +279,7 @@ function seqScanHeavyTables(model, statsAgeDays) {
268
279
  continue;
269
280
  const period = sinceEvent(statsAgeDays, 'statistics were reset');
270
281
  findings.push({
271
- target: tableKey(table.schema, table.name),
282
+ target: postgresTableKey(table.schema, table.name),
272
283
  ruleId: 'db-seq-scan-heavy-table',
273
284
  message: `\`${table.name}\` had ${formatCount(seqScan)} sequential scans reading ${formatCount(seqTupRead)} rows ` +
274
285
  `against ${formatCount(idxScan ?? 0)} index scans ${period} (measured counters), and holds about ` +
@@ -395,4 +406,4 @@ function mysqlRedundantIndexes(model, rows) {
395
406
  function mysqlCatalogFindings(model, { unusedIndexes: unusedRows = [], redundantIndexes = [], uptimeDays } = {}) {
396
407
  return [...mysqlUnusedIndexes(model, unusedRows, uptimeDays), ...mysqlRedundantIndexes(model, redundantIndexes)];
397
408
  }
398
- export { buildMysqlModel, mysqlCatalogFindings, sizeGateRows, minimumStatsAgeDays, formatCount, sinceEvent, formatBytes, tableKey, generatedIndexName, createIndexSql, buildPostgresModel, redundantPair, sizeGate, sizeNote, postgresCatalogFindings, };
409
+ export { buildMysqlModel, mysqlCatalogFindings, sizeGateRows, minimumStatsAgeDays, formatCount, sinceEvent, formatBytes, tableKey, postgresTableKey, generatedIndexName, createIndexSql, buildPostgresModel, redundantPair, sizeGate, sizeNote, postgresCatalogFindings, };
@@ -79,7 +79,9 @@ function createGateway(adapter, options = {}) {
79
79
  interrupted = true;
80
80
  rollbackOrDestroy(rollbackStatement)
81
81
  .then(() => destroy())
82
- .catch(() => { })
82
+ .catch(() => {
83
+ // The session is being torn down on interrupt, so a failed destroy has nowhere to be reported.
84
+ })
83
85
  .finally(() => exit(interruptExitCode));
84
86
  };
85
87
  signals.on('SIGINT', onInterrupt);
@@ -1,4 +1,4 @@
1
- import { sizeGateRows } from './checks.js';
1
+ import { postgresTableKey, sizeGateRows } from './checks.js';
2
2
  // Estimate-only pass over EXPLAIN without ANALYZE: lib/plans.cjs needs actual row counts, which a
3
3
  // generic plan lacks.
4
4
  const maxQueryTextLength = 300;
@@ -45,7 +45,7 @@ function resolveTable(model, node) {
45
45
  if (!name)
46
46
  return;
47
47
  if (node.Schema)
48
- return model.get(`${node.Schema}.${name}`);
48
+ return model.get(postgresTableKey(node.Schema, name));
49
49
  const matches = [...model.values()].filter((table) => table.name === name);
50
50
  if (matches.length === 1)
51
51
  return matches[0];
@@ -113,7 +113,7 @@ function hypotheticalImpact(hypothetical) {
113
113
  function planFinding({ subject, location, candidate, fix, hypothetical, measured }) {
114
114
  const { table } = candidate;
115
115
  const columns = candidate.columns.map((column) => `\`${column}\``).join(', ');
116
- const scan = `${subject} plans a sequential scan of \`${table.schema}.${table.name}\` (about ` +
116
+ const scan = `${subject} plans a sequential scan of \`${postgresTableKey(table.schema, table.name)}\` (about ` +
117
117
  `${Math.round(table.rowEstimate).toLocaleString('en-US')} rows, estimated) filtering on ${columns}.`;
118
118
  const validated = Boolean(measured) || Boolean(hypothetical?.used);
119
119
  let advice;
@@ -132,7 +132,7 @@ function planFinding({ subject, location, candidate, fix, hypothetical, measured
132
132
  advice = ` Add \`${fix}\`, then confirm the plan change with HypoPG or \`--measure\` on staging.`;
133
133
  }
134
134
  const finding = {
135
- ...(location ?? { target: `${table.schema}.${table.name}` }),
135
+ ...(location ?? { target: postgresTableKey(table.schema, table.name) }),
136
136
  ruleId: validated ? 'db-missing-index' : 'db-slow-query-plan',
137
137
  message: scan + advice,
138
138
  suggestion: fix,
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { compareFindings, isInScope, isSourceInput, mergeFinding, scanEntries, relativeToWorkingDirectory, resolveConfig, } from '../analysis/source-inputs.js';
3
+ import { compareFindings, isInScope, isSourceInput, scopedProjectRoots, mergeFinding, scanEntries, relativeToWorkingDirectory, resolveConfig, } from '../analysis/source-inputs.js';
4
4
  import { withoutEmitOptions } from '../cli/emit-options.js';
5
5
  import { selectNativeSyntax } from './compiler.js';
6
6
  import { requireNative, executable } from './native-runtime.js';
@@ -115,7 +115,7 @@ function withoutRemovedOptions(options, { ModuleKind, ModuleResolutionKind }) {
115
115
  }
116
116
  // With fallback, an unavailable compiler or a rejected config returns { fallback: true, reason }
117
117
  // before the native syntax is selected, so the caller can run the JS engine in this process.
118
- // `project` is one config or an array of them. `onlyFiles` limits the roots of each config to the changed files;
118
+ // `project` is one config or an array of them. `onlyFiles` limits reportable roots while retaining configured declarations;
119
119
  // imports still resolve through the config. `analyzers` defaults to the performance rules; each
120
120
  // one's
121
121
  // `analyzeFile` must load its rules lazily, after the native syntax is selected.
@@ -138,6 +138,8 @@ function scanNative({ project, files = [], standaloneFiles = [], standaloneScope
138
138
  // Chosen once the native syntax is selected, because the default analyzer loads its rules lazily.
139
139
  let selectedAnalyzers = [];
140
140
  const visitedConfigs = new Set();
141
+ let usesReferences = false;
142
+ const multipleProjects = [project].flat().length > 1;
141
143
  const notedRootFiles = new Set();
142
144
  // Folders scanned with a config that leaves JavaScript out.
143
145
  const scopesWithoutJs = new Map();
@@ -196,13 +198,13 @@ function scanNative({ project, files = [], standaloneFiles = [], standaloneScope
196
198
  const inputs = roots.filter((filename) => isSourceInput(filename) && analyzes(filename));
197
199
  if (!inputs.length)
198
200
  return;
199
- const program = api.createProgram(roots, { ...options, noEmit: true });
201
+ const program = api.createProgram(roots, { ...withoutRemovedOptions(options, binding), noEmit: true });
200
202
  try {
201
203
  checkErrors(program.getProgramDiagnostics());
202
204
  // The native service accepts an array, saving a round-trip per input.
203
205
  const syntaxErrorsByFile = Map.groupBy(program.getSyntacticDiagnostics(inputs), (diagnostic) => canonical(diagnostic.fileName));
204
206
  const adapter = adaptProgram(program, options);
205
- if (!files.length && !onlyFiles && visitedConfigs.size === 1)
207
+ if (!files.length && !onlyFiles && visitedConfigs.size > 0 && !usesReferences && !multipleProjects)
206
208
  enableSchemaTooling(adapter);
207
209
  const localFiles = new Set();
208
210
  for (const filename of inputs) {
@@ -275,7 +277,9 @@ function scanNative({ project, files = [], standaloneFiles = [], standaloneScope
275
277
  // leaves the JavaScript out still has that JavaScript checked, so TS18003 waits for the final source count.
276
278
  const allowsJs = parsed.options.allowJs ?? parsed.options.checkJs;
277
279
  checkConfig(parsed.errors?.filter((diagnostic) => !isIgnorableUnknownOption(diagnostic) && !(diagnostic.code === noInputsCode && !allowsJs && !explicit)));
278
- const options = withWorkspaceSources(withoutRemovedOptions(withoutBaseUrl(withoutEmitOptions(parsed.options)), binding), path.dirname(filename));
280
+ const options = withWorkspaceSources(withoutBaseUrl(withoutEmitOptions(parsed.options)), path.dirname(filename));
281
+ if (parsed.projectReferences?.length)
282
+ usesReferences = true;
279
283
  for (const reference of parsed.projectReferences ?? []) {
280
284
  visitConfig(resolveConfig(reference.path), projects, scope, false, explicit);
281
285
  }
@@ -294,11 +298,11 @@ function scanNative({ project, files = [], standaloneFiles = [], standaloneScope
294
298
  standaloneRoots.add(folder);
295
299
  }
296
300
  }
297
- const rootFiles = onlyFiles ? existing.filter(onlyFiles) : existing;
301
+ const rootFiles = scopedProjectRoots(existing, onlyFiles);
298
302
  if (!rootFiles.some((filename) => isSourceInput(filename) && isInScope(scope, filename)))
299
303
  return;
300
304
  // Option diagnostics do not depend on root files, so an empty program reports them cheaply.
301
- const optionsProgram = api.createProgram([], { ...options, noEmit: true });
305
+ const optionsProgram = api.createProgram([], { ...withoutRemovedOptions(options, binding), noEmit: true });
302
306
  try {
303
307
  checkConfig(optionsProgram.getProgramDiagnostics());
304
308
  }
@@ -115,13 +115,15 @@ function inspectPostgres(root) {
115
115
  });
116
116
  }
117
117
  const plans = children(node.Plans ?? []);
118
- const [onlyChild] = plans;
119
- const relationship = member(onlyChild, 'Parent Relationship');
118
+ const primaryChildren = plans.filter((child) => {
119
+ const relationship = member(child, 'Parent Relationship');
120
+ return !(typeof relationship === 'string' && ['InitPlan', 'SubPlan'].includes(relationship));
121
+ });
122
+ const [onlyChild] = primaryChildren;
120
123
  if (node['Node Type'] === 'Limit' &&
121
- plans.length === 1 &&
124
+ primaryChildren.length === 1 &&
122
125
  object(onlyChild) &&
123
- onlyChild['Actual Loops'] === loops &&
124
- !(typeof relationship === 'string' && ['InitPlan', 'SubPlan'].includes(relationship))) {
126
+ onlyChild['Actual Loops'] === loops) {
125
127
  const childAverage = count(onlyChild['Actual Rows'], 'limit child Actual Rows', true);
126
128
  const walked = count(Math.round(childAverage * loops), 'limit child total rows');
127
129
  const returned = count(Math.round(averageRows * loops), 'limit total rows');
@@ -35,6 +35,8 @@ function isRecord(value) {
35
35
  return value !== null && typeof value === 'object' && !Array.isArray(value);
36
36
  }
37
37
  function records(value, field) {
38
+ if (value === undefined)
39
+ return [];
38
40
  if (!Array.isArray(value) || !value.every(isRecord)) {
39
41
  throw new TypeError(`Expected an OTLP array of objects at ${field}.`);
40
42
  }
@@ -116,11 +118,29 @@ function spanAttributes(list = [], state) {
116
118
  function digest(value) {
117
119
  return createHash('sha256').update(value).digest('hex');
118
120
  }
121
+ function canonicalizeAttributeValue(value) {
122
+ if ('arrayValue' in value && isRecord(value.arrayValue)) {
123
+ const values = Array.isArray(value.arrayValue.values) ? value.arrayValue.values : [];
124
+ return { arrayValue: { values: values.map((entry) => canonicalizeAttributeValue(entry)) } };
125
+ }
126
+ if ('kvlistValue' in value && isRecord(value.kvlistValue)) {
127
+ const entries = Array.isArray(value.kvlistValue.values) ? [...value.kvlistValue.values] : [];
128
+ entries.sort((left, right) => (left.key < right.key ? -1 : left.key > right.key ? 1 : 0));
129
+ return {
130
+ kvlistValue: {
131
+ values: entries.map((entry) => ({ key: entry.key, value: canonicalizeAttributeValue(entry.value) })),
132
+ },
133
+ };
134
+ }
135
+ return value;
136
+ }
119
137
  function resourceIdentity(resource) {
120
138
  if (resource !== undefined && !isRecord(resource))
121
139
  throw new TypeError('Invalid OTLP resource.');
122
140
  const attributes = readAttributes(isRecord(resource) ? resource.attributes : undefined, 'resource.attributes');
123
- const ordered = [...attributes.keys()].sort().map((key) => [key, attributes.get(key)]);
141
+ const ordered = [...attributes.keys()]
142
+ .sort()
143
+ .map((key) => [key, canonicalizeAttributeValue(attributes.get(key) ?? {})]);
124
144
  return digest(JSON.stringify(ordered));
125
145
  }
126
146
  function id(value, pattern, field) {