@reicek/neataptic-ts 0.1.24 → 0.1.26

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 (215) hide show
  1. package/.github/copilot-instructions.md +11 -0
  2. package/.github/skills/trace-analyzer-extension/SKILL.md +3 -3
  3. package/.github/skills/trace-analyzer-extension/assets/extension-checklist.md +1 -1
  4. package/.github/skills/trace-analyzer-extension/references/analyzer-extension-workflow.md +1 -1
  5. package/.github/skills/trace-audit-reporting/SKILL.md +3 -3
  6. package/.github/skills/trace-audit-reporting/references/trace-analysis-workflow.md +1 -1
  7. package/.github/workflows/ci.yml +3 -3
  8. package/.github/workflows/deploy-pages.yml +6 -6
  9. package/.github/workflows/manual_release_pipeline.yml +3 -3
  10. package/.github/workflows/publish.yml +18 -19
  11. package/.github/workflows/release_dispatch.yml +3 -3
  12. package/package.json +26 -20
  13. package/plans/Flappy_Bird_Folder_Documentation_Pass.md +4 -4
  14. package/plans/README.md +24 -0
  15. package/plans/Roadmap.md +62 -40
  16. package/plans/analyze-trace-solid-split.plans.md +66 -0
  17. package/plans/architecture-solid-split.plans.md +9 -15
  18. package/plans/asciiMaze-typescript-repair.plans.md +1 -1
  19. package/plans/generate-docs-solid-split.plans.md +87 -0
  20. package/plans/methods-docs.plans.md +25 -1
  21. package/plans/methods-solid-split.plans.md +14 -14
  22. package/plans/neat-docs.plans.md +9 -1
  23. package/plans/neat-test-surface-repair.plans.md +1 -1
  24. package/plans/render-docs-html-solid-split.plans.md +68 -0
  25. package/plans/src-no-explicit-any-cleanup.plans.md +1 -1
  26. package/plans/utils-docs.plans.md +6 -1
  27. package/scripts/analyze-trace/analyze-trace.analysis.ts +479 -0
  28. package/scripts/analyze-trace/analyze-trace.constants.ts +35 -0
  29. package/scripts/analyze-trace/analyze-trace.io.ts +69 -0
  30. package/scripts/analyze-trace/analyze-trace.report.ts +100 -0
  31. package/scripts/analyze-trace/analyze-trace.shared.ts +116 -0
  32. package/scripts/analyze-trace/analyze-trace.ts +45 -0
  33. package/scripts/analyze-trace/analyze-trace.types.ts +72 -0
  34. package/scripts/assets/theme.css +80 -23
  35. package/scripts/copy-examples.ts +239 -0
  36. package/scripts/export-onnx.ts +223 -0
  37. package/scripts/generate-bench-tables.ts +378 -37
  38. package/scripts/generate-docs/generate-docs.constants.ts +107 -0
  39. package/scripts/generate-docs/generate-docs.order.ts +355 -0
  40. package/scripts/generate-docs/generate-docs.state.ts +31 -0
  41. package/scripts/generate-docs/generate-docs.targets.ts +165 -0
  42. package/scripts/generate-docs/generate-docs.ts +63 -0
  43. package/scripts/generate-docs/generate-docs.types.ts +112 -0
  44. package/scripts/generate-docs/output/generate-docs.output.folder-index.utils.ts +167 -0
  45. package/scripts/generate-docs/output/generate-docs.output.ordering.utils.ts +353 -0
  46. package/scripts/generate-docs/output/generate-docs.output.readme.utils.ts +420 -0
  47. package/scripts/generate-docs/output/generate-docs.output.ts +123 -0
  48. package/scripts/generate-docs/output/generate-docs.output.warnings.utils.ts +219 -0
  49. package/scripts/generate-docs/symbols/generate-docs.symbols.collection.utils.ts +365 -0
  50. package/scripts/generate-docs/symbols/generate-docs.symbols.jsdoc.utils.ts +373 -0
  51. package/scripts/generate-docs/symbols/generate-docs.symbols.normalize.utils.ts +155 -0
  52. package/scripts/generate-docs/symbols/generate-docs.symbols.render.utils.ts +149 -0
  53. package/scripts/generate-docs/symbols/generate-docs.symbols.signature.utils.ts +289 -0
  54. package/scripts/generate-docs/symbols/generate-docs.symbols.ts +11 -0
  55. package/scripts/mermaid-cli.mjs +102 -22
  56. package/scripts/mermaid-cli.ts +736 -0
  57. package/scripts/render-docs-html/render-docs-html.assets.ts +54 -0
  58. package/scripts/render-docs-html/render-docs-html.mermaid.ts +245 -0
  59. package/scripts/{render-docs-html.sidebar.ts → render-docs-html/render-docs-html.navigation.ts} +141 -144
  60. package/scripts/render-docs-html/render-docs-html.pages.ts +333 -0
  61. package/scripts/render-docs-html/render-docs-html.shared.ts +333 -0
  62. package/scripts/render-docs-html/render-docs-html.types.ts +42 -0
  63. package/scripts/render-docs-html.ts +23 -587
  64. package/scripts/run-docs.ts +238 -0
  65. package/scripts/write-dist-docs-pkg.ts +40 -0
  66. package/src/README.md +75 -75
  67. package/src/architecture/connection/README.md +5 -5
  68. package/src/architecture/layer/README.md +508 -508
  69. package/src/architecture/network/README.md +1458 -1458
  70. package/src/architecture/network/activate/README.md +694 -694
  71. package/src/architecture/network/bootstrap/README.md +77 -77
  72. package/src/architecture/network/connect/README.md +74 -74
  73. package/src/architecture/network/deterministic/README.md +135 -135
  74. package/src/architecture/network/evolve/README.md +364 -364
  75. package/src/architecture/network/gating/README.md +130 -130
  76. package/src/architecture/network/genetic/README.md +399 -399
  77. package/src/architecture/network/mutate/README.md +897 -897
  78. package/src/architecture/network/onnx/README.md +720 -720
  79. package/src/architecture/network/onnx/export/README.md +728 -728
  80. package/src/architecture/network/onnx/export/layers/README.md +450 -450
  81. package/src/architecture/network/onnx/import/README.md +618 -618
  82. package/src/architecture/network/onnx/schema/README.md +32 -32
  83. package/src/architecture/network/prune/README.md +245 -245
  84. package/src/architecture/network/remove/README.md +135 -135
  85. package/src/architecture/network/runtime/README.md +106 -106
  86. package/src/architecture/network/serialize/README.md +542 -542
  87. package/src/architecture/network/slab/README.md +608 -608
  88. package/src/architecture/network/standalone/README.md +212 -212
  89. package/src/architecture/network/stats/README.md +84 -84
  90. package/src/architecture/network/topology/README.md +465 -465
  91. package/src/architecture/network/training/README.md +200 -200
  92. package/src/architecture/node/README.md +5 -5
  93. package/src/architecture/nodePool/README.md +14 -14
  94. package/src/methods/README.md +99 -99
  95. package/src/methods/activation/README.md +189 -189
  96. package/src/methods/cost/README.md +131 -131
  97. package/src/methods/rate/README.md +86 -86
  98. package/src/multithreading/README.md +77 -77
  99. package/src/multithreading/workers/browser/README.md +8 -8
  100. package/src/multithreading/workers/node/README.md +8 -8
  101. package/src/neat/README.md +148 -148
  102. package/src/neat/adaptive/README.md +120 -120
  103. package/src/neat/adaptive/acceptance/README.md +40 -40
  104. package/src/neat/adaptive/complexity/README.md +137 -137
  105. package/src/neat/adaptive/core/README.md +197 -197
  106. package/src/neat/adaptive/lineage/README.md +90 -90
  107. package/src/neat/adaptive/mutation/README.md +284 -284
  108. package/src/neat/compat/README.md +43 -43
  109. package/src/neat/compat/core/README.md +90 -90
  110. package/src/neat/diversity/README.md +35 -35
  111. package/src/neat/diversity/core/README.md +88 -88
  112. package/src/neat/evaluate/README.md +85 -85
  113. package/src/neat/evaluate/auto-distance/README.md +75 -75
  114. package/src/neat/evaluate/entropy-compat/README.md +37 -37
  115. package/src/neat/evaluate/entropy-sharing/README.md +43 -43
  116. package/src/neat/evaluate/fitness/README.md +23 -23
  117. package/src/neat/evaluate/novelty/README.md +120 -120
  118. package/src/neat/evaluate/objectives/README.md +17 -17
  119. package/src/neat/evaluate/shared/README.md +94 -94
  120. package/src/neat/evolve/README.md +96 -96
  121. package/src/neat/evolve/adaptive/README.md +60 -60
  122. package/src/neat/evolve/objectives/README.md +63 -63
  123. package/src/neat/evolve/offspring/README.md +56 -56
  124. package/src/neat/evolve/population/README.md +171 -171
  125. package/src/neat/evolve/runtime/README.md +79 -79
  126. package/src/neat/evolve/speciation/README.md +74 -74
  127. package/src/neat/evolve/warnings/README.md +10 -10
  128. package/src/neat/export/README.md +114 -114
  129. package/src/neat/helpers/README.md +50 -50
  130. package/src/neat/init/README.md +9 -9
  131. package/src/neat/lineage/core/README.md +101 -101
  132. package/src/neat/multiobjective/category/README.md +74 -74
  133. package/src/neat/multiobjective/crowding/README.md +272 -272
  134. package/src/neat/multiobjective/dominance/README.md +171 -171
  135. package/src/neat/multiobjective/fronts/README.md +68 -68
  136. package/src/neat/multiobjective/metrics/README.md +43 -43
  137. package/src/neat/multiobjective/objectives/README.md +31 -31
  138. package/src/neat/multiobjective/shared/README.md +27 -27
  139. package/src/neat/mutation/README.md +97 -97
  140. package/src/neat/mutation/add-conn/README.md +115 -115
  141. package/src/neat/mutation/add-node/README.md +126 -126
  142. package/src/neat/mutation/flow/README.md +149 -149
  143. package/src/neat/mutation/repair/README.md +185 -185
  144. package/src/neat/mutation/select/README.md +117 -117
  145. package/src/neat/mutation/shared/README.md +32 -32
  146. package/src/neat/objectives/README.md +25 -25
  147. package/src/neat/objectives/core/README.md +67 -67
  148. package/src/neat/pruning/README.md +40 -40
  149. package/src/neat/pruning/core/README.md +171 -171
  150. package/src/neat/pruning/facade/README.md +32 -32
  151. package/src/neat/rng/README.md +104 -104
  152. package/src/neat/rng/core/README.md +137 -137
  153. package/src/neat/rng/facade/README.md +50 -50
  154. package/src/neat/selection/README.md +111 -111
  155. package/src/neat/selection/core/README.md +227 -227
  156. package/src/neat/selection/facade/README.md +61 -61
  157. package/src/neat/shared/README.md +163 -163
  158. package/src/neat/speciation/README.md +31 -31
  159. package/src/neat/speciation/threshold/README.md +35 -35
  160. package/src/neat/species/README.md +25 -25
  161. package/src/neat/species/core/README.md +20 -20
  162. package/src/neat/species/core/shared/README.md +18 -18
  163. package/src/neat/species/history/context/README.md +22 -22
  164. package/src/neat/telemetry/accessors/README.md +58 -58
  165. package/src/neat/telemetry/exports/README.md +233 -233
  166. package/src/neat/telemetry/facade/README.md +252 -252
  167. package/src/neat/telemetry/facade/archive/README.md +57 -57
  168. package/src/neat/telemetry/facade/buffer/README.md +43 -43
  169. package/src/neat/telemetry/facade/lineage/README.md +12 -12
  170. package/src/neat/telemetry/facade/objectives/README.md +44 -44
  171. package/src/neat/telemetry/facade/runtime/README.md +26 -26
  172. package/src/neat/telemetry/facade/species/README.md +27 -27
  173. package/src/neat/telemetry/metrics/README.md +696 -696
  174. package/src/neat/telemetry/recorder/README.md +57 -57
  175. package/src/neat/telemetry/types/README.md +32 -32
  176. package/src/neat/topology-intent/README.md +75 -75
  177. package/src/utils/README.md +193 -193
  178. package/test/examples/asciiMaze/browser-entry/README.md +92 -92
  179. package/test/examples/asciiMaze/dashboardManager/README.md +109 -109
  180. package/test/examples/asciiMaze/dashboardManager/telemetry/README.md +28 -28
  181. package/test/examples/asciiMaze/evolutionEngine/README.md +1527 -1527
  182. package/test/examples/asciiMaze/mazeMovement/README.md +105 -105
  183. package/test/examples/asciiMaze/mazeMovement/finalization/README.md +16 -16
  184. package/test/examples/asciiMaze/mazeMovement/policy/README.md +57 -57
  185. package/test/examples/asciiMaze/mazeMovement/runtime/README.md +52 -52
  186. package/test/examples/asciiMaze/mazeMovement/shaping/README.md +46 -46
  187. package/test/examples/flappy_bird/browser-entry/README.md +508 -508
  188. package/test/examples/flappy_bird/browser-entry/host/README.md +101 -101
  189. package/test/examples/flappy_bird/browser-entry/host/resize/README.md +144 -144
  190. package/test/examples/flappy_bird/browser-entry/network-view/README.md +194 -194
  191. package/test/examples/flappy_bird/browser-entry/playback/README.md +278 -278
  192. package/test/examples/flappy_bird/browser-entry/playback/background/README.md +129 -129
  193. package/test/examples/flappy_bird/browser-entry/playback/background/ground-grid/README.md +502 -502
  194. package/test/examples/flappy_bird/browser-entry/playback/frame-render/README.md +139 -139
  195. package/test/examples/flappy_bird/browser-entry/playback/snapshot/README.md +10 -10
  196. package/test/examples/flappy_bird/browser-entry/playback/trail/README.md +43 -43
  197. package/test/examples/flappy_bird/browser-entry/playback/worker-channel/README.md +30 -30
  198. package/test/examples/flappy_bird/browser-entry/runtime/README.md +59 -59
  199. package/test/examples/flappy_bird/browser-entry/visualization/README.md +276 -276
  200. package/test/examples/flappy_bird/browser-entry/worker-channel/README.md +16 -16
  201. package/test/examples/flappy_bird/constants/README.md +1070 -1070
  202. package/test/examples/flappy_bird/environment/README.md +22 -22
  203. package/test/examples/flappy_bird/evaluation/README.md +32 -32
  204. package/test/examples/flappy_bird/evaluation/rollout/README.md +141 -141
  205. package/test/examples/flappy_bird/flappy-evolution-worker/README.md +425 -425
  206. package/test/examples/flappy_bird/simulation-shared/README.md +170 -170
  207. package/test/examples/flappy_bird/simulation-shared/observation/README.md +109 -109
  208. package/test/examples/flappy_bird/trainer/README.md +325 -325
  209. package/test/examples/flappy_bird/trainer/evaluation/README.md +74 -74
  210. package/scripts/analyze-trace.ts +0 -590
  211. package/scripts/copy-examples.mjs +0 -114
  212. package/scripts/export-onnx.mjs +0 -86
  213. package/scripts/generate-bench-tables.mjs +0 -182
  214. package/scripts/generate-docs.ts +0 -2900
  215. package/scripts/write-dist-docs-pkg.mjs +0 -16
@@ -1,590 +0,0 @@
1
- /**
2
- * analyze-trace.ts
3
- *
4
- * Reads a Chrome/Perfetto trace export and prints a compact performance report.
5
- * The report is intentionally thread-aware so browser-main, renderer-main,
6
- * worker, compositor, and GPU activity can be inspected separately.
7
- *
8
- * Usage:
9
- * npm run trace:analyze -- test/examples/flappy_bird/Trace-20260309T191949.json
10
- * npx ts-node scripts/analyze-trace.ts path/to/trace.json --top=20
11
- */
12
- import fs from 'fs';
13
- import path from 'path';
14
-
15
- type Primitive = string | number | boolean | null | undefined;
16
-
17
- interface TraceEvent {
18
- pid?: number;
19
- tid?: number;
20
- ts?: number;
21
- dur?: number;
22
- tdur?: number;
23
- ph?: string;
24
- cat?: string;
25
- name?: string;
26
- args?: Record<string, unknown>;
27
- }
28
-
29
- interface TraceFile {
30
- traceEvents?: TraceEvent[];
31
- }
32
-
33
- interface ThreadIdentity {
34
- pid: number;
35
- tid: number;
36
- }
37
-
38
- interface ThreadSummary {
39
- label: string;
40
- totalDurationMs: number;
41
- runTaskDurationMs: number;
42
- longTaskCount16ms: number;
43
- longTaskCount50ms: number;
44
- maxTaskMs: number;
45
- }
46
-
47
- interface AggregatedDuration {
48
- name: string;
49
- count: number;
50
- totalMs: number;
51
- maxMs: number;
52
- }
53
-
54
- interface LongEventSummary {
55
- durationMs: number;
56
- threadLabel: string;
57
- eventName: string;
58
- scriptUrl?: string;
59
- }
60
-
61
- const MICROSECONDS_PER_MILLISECOND = 1000;
62
- const DEFAULT_TOP_COUNT = 12;
63
- const LONG_TASK_THRESHOLD_MS = 16.7;
64
- const VERY_LONG_TASK_THRESHOLD_MS = 50;
65
-
66
- /**
67
- * CLI entry point.
68
- *
69
- * Reads the trace, derives thread metadata, and prints a deterministic textual
70
- * report that is easy to compare across captures.
71
- */
72
- function main(): void {
73
- const options = resolveCliOptions(process.argv.slice(2));
74
- const traceFilePath = path.resolve(options.tracePath);
75
- const trace = loadTrace(traceFilePath);
76
- const traceEvents = trace.traceEvents ?? [];
77
-
78
- if (traceEvents.length === 0) {
79
- throw new Error(`Trace contains no events: ${traceFilePath}`);
80
- }
81
-
82
- const processNames = collectMetadataNames(traceEvents, 'process_name');
83
- const threadNames = collectMetadataNames(traceEvents, 'thread_name');
84
- const workerThreadLabels = collectWorkerThreadLabels(traceEvents);
85
- const timeRange = resolveTimeRange(traceEvents);
86
- const droppedFrameCount = traceEvents.filter(
87
- (traceEvent) => traceEvent.name === 'DroppedFrame',
88
- ).length;
89
- const beginFrameCount = traceEvents.filter(
90
- (traceEvent) => traceEvent.name === 'BeginFrame',
91
- ).length;
92
-
93
- const threadSummaries = buildThreadSummaries({
94
- traceEvents,
95
- processNames,
96
- threadNames,
97
- workerThreadLabels,
98
- });
99
- const hottestEvents = aggregateDurationsByName(traceEvents, options.topCount);
100
- const hottestFunctionCalls = aggregateFunctionCalls(traceEvents, options.topCount);
101
- const longestEvents = collectLongestEvents({
102
- traceEvents,
103
- processNames,
104
- threadNames,
105
- workerThreadLabels,
106
- topCount: options.topCount,
107
- });
108
- const fireAnimationFrameDurations = collectEventDurationsMs(
109
- traceEvents,
110
- 'FireAnimationFrame',
111
- );
112
- const functionCallDurations = collectEventDurationsMs(traceEvents, 'FunctionCall');
113
-
114
- printSection('Trace');
115
- printLine(`File: ${traceFilePath}`);
116
- printLine(
117
- `Window: ${formatMs(timeRange.windowMs)} across ${traceEvents.length.toLocaleString()} events`,
118
- );
119
- printLine(
120
- `Frames: ${beginFrameCount.toLocaleString()} begin, ${droppedFrameCount.toLocaleString()} dropped`,
121
- );
122
-
123
- printSection('Thread Summary');
124
- for (const threadSummary of threadSummaries) {
125
- printLine(
126
- `${threadSummary.label}: total=${formatMs(threadSummary.totalDurationMs)}, ` +
127
- `RunTask=${formatMs(threadSummary.runTaskDurationMs)}, ` +
128
- `>16.7ms=${threadSummary.longTaskCount16ms}, ` +
129
- `>50ms=${threadSummary.longTaskCount50ms}, ` +
130
- `max=${formatMs(threadSummary.maxTaskMs)}`,
131
- );
132
- }
133
-
134
- printSection('Animation Frames');
135
- printLine(`FireAnimationFrame: ${formatDistribution(fireAnimationFrameDurations)}`);
136
- printLine(`FunctionCall: ${formatDistribution(functionCallDurations)}`);
137
-
138
- printSection('Longest Events');
139
- for (const longEvent of longestEvents) {
140
- printLine(
141
- `${formatMs(longEvent.durationMs)} | ${longEvent.threadLabel} | ${longEvent.eventName}${
142
- longEvent.scriptUrl ? ` | ${longEvent.scriptUrl}` : ''
143
- }`,
144
- );
145
- }
146
-
147
- printSection('Top Events');
148
- for (const eventSummary of hottestEvents) {
149
- printLine(
150
- `${eventSummary.name}: count=${eventSummary.count.toLocaleString()}, total=${formatMs(eventSummary.totalMs)}, max=${formatMs(eventSummary.maxMs)}`,
151
- );
152
- }
153
-
154
- printSection('Top Function Calls');
155
- for (const functionCallSummary of hottestFunctionCalls) {
156
- printLine(
157
- `${functionCallSummary.name}: count=${functionCallSummary.count.toLocaleString()}, total=${formatMs(functionCallSummary.totalMs)}, max=${formatMs(functionCallSummary.maxMs)}`,
158
- );
159
- }
160
- }
161
-
162
- /**
163
- * Resolves CLI flags.
164
- *
165
- * Supported flags:
166
- * - positional trace path
167
- * - `--top=NUMBER`
168
- */
169
- function resolveCliOptions(argumentsList: string[]): {
170
- tracePath: string;
171
- topCount: number;
172
- } {
173
- const pathArgument = argumentsList.find((argument) => !argument.startsWith('--'));
174
- if (!pathArgument) {
175
- throw new Error(
176
- 'Missing trace path. Example: npm run trace:analyze -- test/examples/flappy_bird/Trace.json',
177
- );
178
- }
179
-
180
- const topArgument = argumentsList.find((argument) => argument.startsWith('--top='));
181
- const requestedTopCount = topArgument
182
- ? Number.parseInt(topArgument.slice('--top='.length), 10)
183
- : DEFAULT_TOP_COUNT;
184
-
185
- return {
186
- tracePath: pathArgument,
187
- topCount:
188
- Number.isFinite(requestedTopCount) && requestedTopCount > 0
189
- ? requestedTopCount
190
- : DEFAULT_TOP_COUNT,
191
- };
192
- }
193
-
194
- /** Reads and parses a trace JSON file. */
195
- function loadTrace(traceFilePath: string): TraceFile {
196
- const traceFileContents = fs.readFileSync(traceFilePath, 'utf8');
197
- return JSON.parse(traceFileContents) as TraceFile;
198
- }
199
-
200
- /**
201
- * Collects thread or process metadata labels keyed by `pid:tid`.
202
- *
203
- * Chrome emits metadata events (`ph === 'M'`) that attach human-readable names
204
- * to otherwise numeric process and thread identifiers.
205
- */
206
- function collectMetadataNames(
207
- traceEvents: TraceEvent[],
208
- metadataName: 'process_name' | 'thread_name',
209
- ): Map<string, string> {
210
- const metadataNames = new Map<string, string>();
211
-
212
- for (const traceEvent of traceEvents) {
213
- if (traceEvent.ph !== 'M' || traceEvent.name !== metadataName) {
214
- continue;
215
- }
216
-
217
- const resolvedName = readNestedPrimitive(traceEvent.args, ['name']);
218
- if (typeof resolvedName !== 'string') {
219
- continue;
220
- }
221
-
222
- const metadataKey =
223
- metadataName === 'process_name'
224
- ? createProcessKey(traceEvent.pid)
225
- : createThreadKey(traceEvent.pid, traceEvent.tid);
226
-
227
- if (metadataKey) {
228
- metadataNames.set(metadataKey, resolvedName);
229
- }
230
- }
231
-
232
- return metadataNames;
233
- }
234
-
235
- /**
236
- * Resolves worker-thread labels from worker attachment events.
237
- *
238
- * This helps map generic `DedicatedWorker thread` labels back to the worker
239
- * script URL that spawned them.
240
- */
241
- function collectWorkerThreadLabels(traceEvents: TraceEvent[]): Map<string, string> {
242
- const workerThreadLabels = new Map<string, string>();
243
-
244
- for (const traceEvent of traceEvents) {
245
- if (traceEvent.name !== 'TracingSessionIdForWorker') {
246
- continue;
247
- }
248
-
249
- const workerThreadId = readNestedPrimitive(traceEvent.args, [
250
- 'data',
251
- 'workerThreadId',
252
- ]);
253
- const workerUrl = readNestedPrimitive(traceEvent.args, ['data', 'url']);
254
-
255
- if (typeof workerThreadId !== 'number' || typeof workerUrl !== 'string') {
256
- continue;
257
- }
258
-
259
- const threadKey = createThreadKey(traceEvent.pid, workerThreadId);
260
- if (!threadKey) {
261
- continue;
262
- }
263
-
264
- workerThreadLabels.set(threadKey, workerUrl);
265
- }
266
-
267
- return workerThreadLabels;
268
- }
269
-
270
- /** Computes the visible time window spanned by non-zero timestamp events. */
271
- function resolveTimeRange(traceEvents: TraceEvent[]): { windowMs: number } {
272
- let minimumTimestamp = Number.POSITIVE_INFINITY;
273
- let maximumTimestamp = 0;
274
-
275
- for (const traceEvent of traceEvents) {
276
- const eventTimestamp = traceEvent.ts;
277
- if (typeof eventTimestamp === 'number' && eventTimestamp > 0) {
278
- minimumTimestamp = Math.min(minimumTimestamp, eventTimestamp);
279
- }
280
-
281
- const eventDuration = typeof traceEvent.dur === 'number' ? traceEvent.dur : 0;
282
- maximumTimestamp = Math.max(maximumTimestamp, (eventTimestamp ?? 0) + eventDuration);
283
- }
284
-
285
- if (!Number.isFinite(minimumTimestamp)) {
286
- minimumTimestamp = 0;
287
- }
288
-
289
- return {
290
- windowMs: (maximumTimestamp - minimumTimestamp) / MICROSECONDS_PER_MILLISECOND,
291
- };
292
- }
293
-
294
- /**
295
- * Builds per-thread rollups for total duration and long-task counts.
296
- */
297
- function buildThreadSummaries(options: {
298
- traceEvents: TraceEvent[];
299
- processNames: Map<string, string>;
300
- threadNames: Map<string, string>;
301
- workerThreadLabels: Map<string, string>;
302
- }): ThreadSummary[] {
303
- const {
304
- traceEvents,
305
- processNames,
306
- threadNames,
307
- workerThreadLabels,
308
- } = options;
309
- const durationByThread = new Map<string, ThreadSummary>();
310
-
311
- for (const traceEvent of traceEvents) {
312
- if (traceEvent.ph !== 'X' || typeof traceEvent.dur !== 'number') {
313
- continue;
314
- }
315
-
316
- const threadKey = createThreadKey(traceEvent.pid, traceEvent.tid);
317
- if (!threadKey) {
318
- continue;
319
- }
320
-
321
- const threadSummaryLabel = resolveThreadLabel({
322
- traceEvent,
323
- processNames,
324
- threadNames,
325
- workerThreadLabels,
326
- });
327
- const threadSummary =
328
- durationByThread.get(threadSummaryLabel) ?? {
329
- label: threadSummaryLabel,
330
- totalDurationMs: 0,
331
- runTaskDurationMs: 0,
332
- longTaskCount16ms: 0,
333
- longTaskCount50ms: 0,
334
- maxTaskMs: 0,
335
- };
336
- const eventDurationMs = traceEvent.dur / MICROSECONDS_PER_MILLISECOND;
337
-
338
- threadSummary.totalDurationMs += eventDurationMs;
339
- if (traceEvent.name === 'RunTask') {
340
- threadSummary.runTaskDurationMs += eventDurationMs;
341
- if (eventDurationMs >= LONG_TASK_THRESHOLD_MS) {
342
- threadSummary.longTaskCount16ms += 1;
343
- }
344
- if (eventDurationMs >= VERY_LONG_TASK_THRESHOLD_MS) {
345
- threadSummary.longTaskCount50ms += 1;
346
- }
347
- threadSummary.maxTaskMs = Math.max(threadSummary.maxTaskMs, eventDurationMs);
348
- }
349
-
350
- durationByThread.set(threadSummaryLabel, threadSummary);
351
- }
352
-
353
- return Array.from(durationByThread.values()).toSorted(
354
- (leftSummary, rightSummary) => rightSummary.totalDurationMs - leftSummary.totalDurationMs,
355
- );
356
- }
357
-
358
- /** Resolves a readable process/thread label for one event. */
359
- function resolveThreadLabel(options: {
360
- traceEvent: TraceEvent;
361
- processNames: Map<string, string>;
362
- threadNames: Map<string, string>;
363
- workerThreadLabels: Map<string, string>;
364
- }): string {
365
- const { traceEvent, processNames, threadNames, workerThreadLabels } = options;
366
- const processLabel = processNames.get(createProcessKey(traceEvent.pid) ?? '') ?? 'unknown-process';
367
- const threadKey = createThreadKey(traceEvent.pid, traceEvent.tid) ?? 'unknown-thread';
368
- const threadLabel = threadNames.get(threadKey) ?? 'unknown-thread';
369
- const workerLabel = workerThreadLabels.get(threadKey);
370
- return workerLabel
371
- ? `${processLabel} / ${threadLabel} / ${workerLabel}`
372
- : `${processLabel} / ${threadLabel}`;
373
- }
374
-
375
- /** Collects the longest complete events in the trace. */
376
- function collectLongestEvents(options: {
377
- traceEvents: TraceEvent[];
378
- processNames: Map<string, string>;
379
- threadNames: Map<string, string>;
380
- workerThreadLabels: Map<string, string>;
381
- topCount: number;
382
- }): LongEventSummary[] {
383
- const { traceEvents, processNames, threadNames, workerThreadLabels, topCount } = options;
384
-
385
- return traceEvents
386
- .filter(
387
- (traceEvent) =>
388
- traceEvent.ph === 'X' &&
389
- typeof traceEvent.dur === 'number' &&
390
- typeof traceEvent.name === 'string',
391
- )
392
- .map((traceEvent) => ({
393
- durationMs: traceEvent.dur! / MICROSECONDS_PER_MILLISECOND,
394
- threadLabel: resolveThreadLabel({
395
- traceEvent,
396
- processNames,
397
- threadNames,
398
- workerThreadLabels,
399
- }),
400
- eventName: traceEvent.name!,
401
- scriptUrl:
402
- (readNestedPrimitive(traceEvent.args, ['data', 'url']) as string | undefined) ??
403
- undefined,
404
- }))
405
- .toSorted((leftEvent, rightEvent) => rightEvent.durationMs - leftEvent.durationMs)
406
- .slice(0, topCount);
407
- }
408
-
409
- /**
410
- * Aggregates complete-event durations by event name.
411
- *
412
- * `RunTask` is kept because it is still useful for thread pressure, but the
413
- * separate function-call rollup below is generally more actionable.
414
- */
415
- function aggregateDurationsByName(
416
- traceEvents: TraceEvent[],
417
- topCount: number,
418
- ): AggregatedDuration[] {
419
- const durationsByName = new Map<string, AggregatedDuration>();
420
-
421
- for (const traceEvent of traceEvents) {
422
- if (traceEvent.ph !== 'X' || typeof traceEvent.dur !== 'number' || !traceEvent.name) {
423
- continue;
424
- }
425
-
426
- const eventDurationMs = traceEvent.dur / MICROSECONDS_PER_MILLISECOND;
427
- const eventSummary = durationsByName.get(traceEvent.name) ?? {
428
- name: traceEvent.name,
429
- count: 0,
430
- totalMs: 0,
431
- maxMs: 0,
432
- };
433
-
434
- eventSummary.count += 1;
435
- eventSummary.totalMs += eventDurationMs;
436
- eventSummary.maxMs = Math.max(eventSummary.maxMs, eventDurationMs);
437
- durationsByName.set(traceEvent.name, eventSummary);
438
- }
439
-
440
- return Array.from(durationsByName.values())
441
- .toSorted((leftSummary, rightSummary) => rightSummary.totalMs - leftSummary.totalMs)
442
- .slice(0, topCount);
443
- }
444
-
445
- /**
446
- * Aggregates `FunctionCall` events by script URL.
447
- *
448
- * This is the most direct way to see which bundle or worker file owns main
449
- * thread or worker thread execution time in the trace.
450
- */
451
- function aggregateFunctionCalls(
452
- traceEvents: TraceEvent[],
453
- topCount: number,
454
- ): AggregatedDuration[] {
455
- const durationsByFunctionCall = new Map<string, AggregatedDuration>();
456
-
457
- for (const traceEvent of traceEvents) {
458
- if (
459
- traceEvent.ph !== 'X' ||
460
- traceEvent.name !== 'FunctionCall' ||
461
- typeof traceEvent.dur !== 'number'
462
- ) {
463
- continue;
464
- }
465
-
466
- const functionCallName =
467
- (readNestedPrimitive(traceEvent.args, ['data', 'url']) as string | undefined) ??
468
- '(unknown-script)';
469
- const functionCallSummary = durationsByFunctionCall.get(functionCallName) ?? {
470
- name: functionCallName,
471
- count: 0,
472
- totalMs: 0,
473
- maxMs: 0,
474
- };
475
- const eventDurationMs = traceEvent.dur / MICROSECONDS_PER_MILLISECOND;
476
-
477
- functionCallSummary.count += 1;
478
- functionCallSummary.totalMs += eventDurationMs;
479
- functionCallSummary.maxMs = Math.max(functionCallSummary.maxMs, eventDurationMs);
480
- durationsByFunctionCall.set(functionCallName, functionCallSummary);
481
- }
482
-
483
- return Array.from(durationsByFunctionCall.values())
484
- .toSorted((leftSummary, rightSummary) => rightSummary.totalMs - leftSummary.totalMs)
485
- .slice(0, topCount);
486
- }
487
-
488
- /** Collects all durations for one event name in milliseconds. */
489
- function collectEventDurationsMs(
490
- traceEvents: TraceEvent[],
491
- eventName: string,
492
- ): number[] {
493
- return traceEvents
494
- .filter(
495
- (traceEvent) =>
496
- traceEvent.ph === 'X' &&
497
- traceEvent.name === eventName &&
498
- typeof traceEvent.dur === 'number',
499
- )
500
- .map((traceEvent) => traceEvent.dur! / MICROSECONDS_PER_MILLISECOND)
501
- .toSorted((leftDuration, rightDuration) => leftDuration - rightDuration);
502
- }
503
-
504
- /** Formats a percentile-style summary for one event duration collection. */
505
- function formatDistribution(durationsMs: number[]): string {
506
- if (durationsMs.length === 0) {
507
- return 'count=0';
508
- }
509
-
510
- return [
511
- `count=${durationsMs.length.toLocaleString()}`,
512
- `p50=${formatMs(percentile(durationsMs, 0.5))}`,
513
- `p90=${formatMs(percentile(durationsMs, 0.9))}`,
514
- `p99=${formatMs(percentile(durationsMs, 0.99))}`,
515
- `max=${formatMs(durationsMs.at(-1) ?? 0)}`,
516
- ].join(', ');
517
- }
518
-
519
- /** Computes a nearest-rank percentile from sorted durations. */
520
- function percentile(sortedDurations: number[], rank: number): number {
521
- if (sortedDurations.length === 0) {
522
- return 0;
523
- }
524
-
525
- const clampedRank = Math.max(0, Math.min(1, rank));
526
- const index = Math.min(
527
- sortedDurations.length - 1,
528
- Math.floor(clampedRank * (sortedDurations.length - 1)),
529
- );
530
- return sortedDurations[index];
531
- }
532
-
533
- /** Safely resolves a nested primitive value from an event args object. */
534
- function readNestedPrimitive(
535
- value: unknown,
536
- pathSegments: string[],
537
- ): Primitive {
538
- let currentValue: unknown = value;
539
-
540
- for (const pathSegment of pathSegments) {
541
- if (!currentValue || typeof currentValue !== 'object') {
542
- return undefined;
543
- }
544
-
545
- currentValue = (currentValue as Record<string, unknown>)[pathSegment];
546
- }
547
-
548
- if (
549
- currentValue == null ||
550
- typeof currentValue === 'string' ||
551
- typeof currentValue === 'number' ||
552
- typeof currentValue === 'boolean'
553
- ) {
554
- return currentValue;
555
- }
556
-
557
- return undefined;
558
- }
559
-
560
- /** Formats a duration for stable human-readable output. */
561
- function formatMs(durationMs: number): string {
562
- return `${durationMs.toFixed(2)}ms`;
563
- }
564
-
565
- /** Creates a stable process lookup key. */
566
- function createProcessKey(pid: number | undefined): string | undefined {
567
- return typeof pid === 'number' ? `pid:${pid}` : undefined;
568
- }
569
-
570
- /** Creates a stable thread lookup key. */
571
- function createThreadKey(
572
- pid: number | undefined,
573
- tid: number | undefined,
574
- ): string | undefined {
575
- return typeof pid === 'number' && typeof tid === 'number'
576
- ? `pid:${pid}:tid:${tid}`
577
- : undefined;
578
- }
579
-
580
- /** Prints a section title. */
581
- function printSection(title: string): void {
582
- console.log(`\n[${title}]`);
583
- }
584
-
585
- /** Prints one content line. */
586
- function printLine(value: string): void {
587
- console.log(value);
588
- }
589
-
590
- main();
@@ -1,114 +0,0 @@
1
- // Copies browser-viewable examples into docs/examples/* so they are published with GitHub Pages.
2
- import fs from 'fs';
3
- import path from 'path';
4
-
5
- function copyAsciiMaze() {
6
- const srcDir = path.resolve('test', 'examples', 'asciiMaze');
7
- if (!fs.existsSync(srcDir)) {
8
- console.warn(
9
- '[docs:examples] asciiMaze source directory not found, skipping',
10
- );
11
- return;
12
- }
13
- const destDir = path.resolve('docs', 'examples', 'asciiMaze');
14
- fs.mkdirSync(destDir, { recursive: true });
15
- // Copy index.html only (bundle already built to docs/assets). Could copy other static assets if added later.
16
- const indexSrc = path.join(srcDir, 'index.html');
17
- if (fs.existsSync(indexSrc)) {
18
- fs.copyFileSync(indexSrc, path.join(destDir, 'index.html'));
19
- console.log('[docs:examples] Copied asciiMaze index.html');
20
- } else {
21
- console.warn('[docs:examples] asciiMaze index.html missing');
22
- }
23
- }
24
-
25
- function copyFlappyBird() {
26
- const srcDir = path.resolve('test', 'examples', 'flappy_bird');
27
- if (!fs.existsSync(srcDir)) {
28
- console.warn(
29
- '[docs:examples] flappy_bird source directory not found, skipping',
30
- );
31
- return;
32
- }
33
- const destDir = path.resolve('docs', 'examples', 'flappy_bird');
34
- fs.mkdirSync(destDir, { recursive: true });
35
- // Copy index.html only (bundle already built to docs/assets).
36
- const indexSrc = path.join(srcDir, 'index.html');
37
- if (fs.existsSync(indexSrc)) {
38
- fs.copyFileSync(indexSrc, path.join(destDir, 'index.html'));
39
- console.log('[docs:examples] Copied flappy_bird index.html');
40
- } else {
41
- console.warn('[docs:examples] flappy_bird index.html missing');
42
- }
43
- }
44
-
45
- function writeExamplesLandingPage() {
46
- const examplesDir = path.resolve('docs', 'examples');
47
- fs.mkdirSync(examplesDir, { recursive: true });
48
-
49
- const demoEntries = [
50
- {
51
- dirName: 'asciiMaze',
52
- label: 'asciiMaze',
53
- title: 'ASCII Maze (NeatapticTS)',
54
- },
55
- {
56
- dirName: 'flappy_bird',
57
- label: 'flappy_bird',
58
- title: 'Flappy Bird (NeatapticTS)',
59
- },
60
- ];
61
-
62
- const linksMarkup = demoEntries
63
- .filter((entry) =>
64
- fs.existsSync(path.join(examplesDir, entry.dirName, 'index.html')),
65
- )
66
- .map(
67
- (entry) =>
68
- `<li><a href="./${entry.dirName}/index.html">${entry.title}</a> <span class="demo-path">(examples/${entry.label})</span></li>`,
69
- )
70
- .join('');
71
-
72
- const html = `<!doctype html>
73
- <html lang="en">
74
- <head>
75
- <meta charset="utf-8" />
76
- <meta name="viewport" content="width=device-width, initial-scale=1" />
77
- <title>Examples • NeatapticTS Docs</title>
78
- <link rel="stylesheet" href="../assets/theme.css" />
79
- </head>
80
- <body>
81
- <header class="topbar">
82
- <div class="inner">
83
- <div class="brand"><a href="../index.html">NeatapticTS</a></div>
84
- <nav class="main-nav">
85
- <a href="../index.html">Home</a>
86
- <a href="../index.html">Docs</a>
87
- <a href="./index.html" class="active">Examples</a>
88
- <a href="https://github.com/reicek/NeatapticTS" target="_blank" rel="noopener">GitHub</a>
89
- </nav>
90
- </div>
91
- </header>
92
- <div class="layout">
93
- <main class="content">
94
- <h1>Examples</h1>
95
- <p>Interactive browser demos built from this repository:</p>
96
- <ul>${linksMarkup}</ul>
97
- <footer class="site-footer">Generated from source JSDoc • <a href="https://github.com/reicek/NeatapticTS">GitHub</a></footer>
98
- </main>
99
- </div>
100
- </body>
101
- </html>`;
102
-
103
- fs.writeFileSync(path.join(examplesDir, 'index.html'), html, 'utf8');
104
- console.log('[docs:examples] Wrote examples landing page');
105
- }
106
-
107
- try {
108
- copyAsciiMaze();
109
- copyFlappyBird();
110
- writeExamplesLandingPage();
111
- } catch (e) {
112
- console.error('[docs:examples] Failed:', e);
113
- process.exit(1);
114
- }