@superblocksteam/sdk 2.0.130-next.2 → 2.0.130-next.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/cli-replacement/dependency-install-classifier.d.mts.map +1 -1
  3. package/dist/cli-replacement/dependency-install-classifier.mjs +11 -0
  4. package/dist/cli-replacement/dependency-install-classifier.mjs.map +1 -1
  5. package/dist/cli-replacement/dependency-install-classifier.test.mjs +26 -0
  6. package/dist/cli-replacement/dependency-install-classifier.test.mjs.map +1 -1
  7. package/dist/cli-replacement/dev.d.mts.map +1 -1
  8. package/dist/cli-replacement/dev.mjs +63 -4
  9. package/dist/cli-replacement/dev.mjs.map +1 -1
  10. package/dist/cli-replacement/disk-space.d.mts +86 -0
  11. package/dist/cli-replacement/disk-space.d.mts.map +1 -0
  12. package/dist/cli-replacement/disk-space.mjs +133 -0
  13. package/dist/cli-replacement/disk-space.mjs.map +1 -0
  14. package/dist/cli-replacement/disk-space.test.d.mts +2 -0
  15. package/dist/cli-replacement/disk-space.test.d.mts.map +1 -0
  16. package/dist/cli-replacement/disk-space.test.mjs +186 -0
  17. package/dist/cli-replacement/disk-space.test.mjs.map +1 -0
  18. package/dist/dev-utils/dev-server-metrics.d.mts +11 -0
  19. package/dist/dev-utils/dev-server-metrics.d.mts.map +1 -1
  20. package/dist/dev-utils/dev-server-metrics.mjs +18 -0
  21. package/dist/dev-utils/dev-server-metrics.mjs.map +1 -1
  22. package/dist/telemetry/memory-metrics.d.ts +7 -0
  23. package/dist/telemetry/memory-metrics.d.ts.map +1 -1
  24. package/dist/telemetry/memory-metrics.js +221 -44
  25. package/dist/telemetry/memory-metrics.js.map +1 -1
  26. package/dist/telemetry/memory-metrics.test.d.ts +2 -0
  27. package/dist/telemetry/memory-metrics.test.d.ts.map +1 -0
  28. package/dist/telemetry/memory-metrics.test.js +256 -0
  29. package/dist/telemetry/memory-metrics.test.js.map +1 -0
  30. package/dist/vite-plugin-sdk-api-entry-point.d.mts +14 -1
  31. package/dist/vite-plugin-sdk-api-entry-point.d.mts.map +1 -1
  32. package/dist/vite-plugin-sdk-api-entry-point.mjs +68 -7
  33. package/dist/vite-plugin-sdk-api-entry-point.mjs.map +1 -1
  34. package/dist/vite-plugin-sdk-api-entry-point.test.mjs +53 -1
  35. package/dist/vite-plugin-sdk-api-entry-point.test.mjs.map +1 -1
  36. package/package.json +6 -6
  37. package/src/cli-replacement/dependency-install-classifier.mts +14 -0
  38. package/src/cli-replacement/dependency-install-classifier.test.mts +39 -0
  39. package/src/cli-replacement/dev.mts +81 -10
  40. package/src/cli-replacement/disk-space.mts +216 -0
  41. package/src/cli-replacement/disk-space.test.mts +246 -0
  42. package/src/dev-utils/dev-server-metrics.mts +20 -0
  43. package/src/telemetry/memory-metrics.test.ts +363 -0
  44. package/src/telemetry/memory-metrics.ts +329 -60
  45. package/src/vite-plugin-sdk-api-entry-point.mts +79 -9
  46. package/src/vite-plugin-sdk-api-entry-point.test.mts +134 -1
  47. package/tsconfig.tsbuildinfo +1 -1
@@ -1,7 +1,12 @@
1
+ import { readFileSync } from "node:fs";
1
2
  import {
3
+ constants,
4
+ monitorEventLoopDelay,
5
+ performance,
2
6
  PerformanceObserver,
3
7
  type PerformanceObserverEntryList,
4
8
  } from "node:perf_hooks";
9
+ import { getHeapStatistics } from "node:v8";
5
10
 
6
11
  import type { BatchObservableResult } from "@opentelemetry/api";
7
12
 
@@ -9,77 +14,341 @@ import { getMeter } from "./index.js";
9
14
 
10
15
  let cleanupFn: (() => void) | undefined;
11
16
 
17
+ interface CgroupMemory {
18
+ currentBytes: number;
19
+ limitBytes: number;
20
+ usageRatio: number;
21
+ }
22
+
23
+ interface CgroupNumber {
24
+ exists: boolean;
25
+ value?: number;
26
+ }
27
+
28
+ interface GcPerformanceEntry {
29
+ duration: number;
30
+ kind?: number;
31
+ detail?: {
32
+ kind?: number;
33
+ };
34
+ }
35
+
36
+ const NS_PER_MS = 1_000_000;
37
+ const US_PER_SECOND = 1_000_000;
38
+
39
+ function finiteNonNegative(value: number): number {
40
+ return Number.isFinite(value) && value > 0 ? value : 0;
41
+ }
42
+
43
+ function nsToMs(value: number): number {
44
+ return finiteNonNegative(value) / NS_PER_MS;
45
+ }
46
+
47
+ function ratio(numerator: number, denominator: number): number {
48
+ if (!Number.isFinite(numerator) || !Number.isFinite(denominator)) {
49
+ return 0;
50
+ }
51
+ if (denominator <= 0) {
52
+ return 0;
53
+ }
54
+ return Math.max(0, numerator / denominator);
55
+ }
56
+
57
+ function readCgroupNumber(filePath: string): CgroupNumber {
58
+ try {
59
+ const value = readFileSync(filePath, "utf-8").trim();
60
+ if (!value || value === "max") {
61
+ return { exists: true };
62
+ }
63
+ const parsed = Number(value);
64
+ if (
65
+ Number.isFinite(parsed) &&
66
+ parsed >= 0 &&
67
+ parsed < Number.MAX_SAFE_INTEGER
68
+ ) {
69
+ return { exists: true, value: parsed };
70
+ }
71
+ return { exists: true };
72
+ } catch {
73
+ return { exists: false };
74
+ }
75
+ }
76
+
77
+ export function readCgroupMemory(
78
+ root = "/sys/fs/cgroup",
79
+ ): CgroupMemory | undefined {
80
+ const v2Current = readCgroupNumber(`${root}/memory.current`);
81
+ const v2Limit = readCgroupNumber(`${root}/memory.max`);
82
+ const usesCgroupV2 = v2Current.exists || v2Limit.exists;
83
+ const currentBytes = usesCgroupV2
84
+ ? v2Current.value
85
+ : readCgroupNumber(`${root}/memory/memory.usage_in_bytes`).value;
86
+ const limitBytes = usesCgroupV2
87
+ ? v2Limit.value
88
+ : readCgroupNumber(`${root}/memory/memory.limit_in_bytes`).value;
89
+
90
+ if (
91
+ currentBytes === undefined ||
92
+ limitBytes === undefined ||
93
+ limitBytes <= 0
94
+ ) {
95
+ return undefined;
96
+ }
97
+
98
+ return {
99
+ currentBytes,
100
+ limitBytes,
101
+ usageRatio: ratio(currentBytes, limitBytes),
102
+ };
103
+ }
104
+
105
+ function gcKind(kind: number | undefined): string {
106
+ switch (kind) {
107
+ case constants.NODE_PERFORMANCE_GC_MINOR:
108
+ return "minor";
109
+ case constants.NODE_PERFORMANCE_GC_MAJOR:
110
+ return "major";
111
+ case constants.NODE_PERFORMANCE_GC_INCREMENTAL:
112
+ return "incremental";
113
+ case constants.NODE_PERFORMANCE_GC_WEAKCB:
114
+ return "weakcb";
115
+ default:
116
+ return "unknown";
117
+ }
118
+ }
119
+
12
120
  export function startMemoryMetrics(): void {
13
121
  if (cleanupFn) {
14
122
  return;
15
123
  }
16
124
 
17
125
  const meter = getMeter();
126
+ const eventLoopDelay = monitorEventLoopDelay({ resolution: 20 });
127
+ let previousEventLoopUtilization = performance.eventLoopUtilization();
128
+ let removeBatchCallback: (() => void) | undefined;
129
+ let disconnectGcObserver: (() => void) | undefined;
18
130
 
19
- const heapUsedGauge = meter.createObservableGauge(
20
- "nodejs.memory.heap_used_bytes",
21
- { description: "V8 heap memory used (bytes)", unit: "By" },
22
- );
23
- const heapTotalGauge = meter.createObservableGauge(
24
- "nodejs.memory.heap_total_bytes",
25
- { description: "V8 heap memory allocated (bytes)", unit: "By" },
26
- );
27
- const rssGauge = meter.createObservableGauge("nodejs.memory.rss_bytes", {
28
- description: "Resident Set Size - total memory allocated for the process",
29
- unit: "By",
30
- });
31
- const externalGauge = meter.createObservableGauge(
32
- "nodejs.memory.external_bytes",
33
- {
34
- description: "Memory used by C++ objects bound to JavaScript objects",
35
- unit: "By",
36
- },
37
- );
38
- const arrayBuffersGauge = meter.createObservableGauge(
39
- "nodejs.memory.array_buffers_bytes",
40
- {
41
- description:
42
- "Memory allocated for ArrayBuffers and SharedArrayBuffers (also included in external)",
131
+ try {
132
+ const heapUsedGauge = meter.createObservableGauge(
133
+ "nodejs.memory.heap_used_bytes",
134
+ { description: "V8 heap memory used (bytes)", unit: "By" },
135
+ );
136
+ const heapTotalGauge = meter.createObservableGauge(
137
+ "nodejs.memory.heap_total_bytes",
138
+ { description: "V8 heap memory allocated (bytes)", unit: "By" },
139
+ );
140
+ const rssGauge = meter.createObservableGauge("nodejs.memory.rss_bytes", {
141
+ description: "Resident Set Size - total memory allocated for the process",
43
142
  unit: "By",
44
- },
45
- );
46
-
47
- const gcCountCounter = meter.createCounter("nodejs.gc.count", {
48
- description: "Number of garbage collection events",
49
- unit: "{event}",
50
- });
51
-
52
- const gauges = [
53
- heapUsedGauge,
54
- heapTotalGauge,
55
- rssGauge,
56
- externalGauge,
57
- arrayBuffersGauge,
58
- ];
59
-
60
- // Single memoryUsage() call per export interval for all 5 gauges (idiomatic OTEL batch pattern).
61
- const batchCb = (result: BatchObservableResult) => {
62
- const mem = process.memoryUsage();
63
- result.observe(heapUsedGauge, mem.heapUsed);
64
- result.observe(heapTotalGauge, mem.heapTotal);
65
- result.observe(rssGauge, mem.rss);
66
- result.observe(externalGauge, mem.external);
67
- result.observe(arrayBuffersGauge, mem.arrayBuffers);
68
- };
143
+ });
144
+ const externalGauge = meter.createObservableGauge(
145
+ "nodejs.memory.external_bytes",
146
+ {
147
+ description: "Memory used by C++ objects bound to JavaScript objects",
148
+ unit: "By",
149
+ },
150
+ );
151
+ const arrayBuffersGauge = meter.createObservableGauge(
152
+ "nodejs.memory.array_buffers_bytes",
153
+ {
154
+ description:
155
+ "Memory allocated for ArrayBuffers and SharedArrayBuffers (also included in external)",
156
+ unit: "By",
157
+ },
158
+ );
159
+ const heapLimitGauge = meter.createObservableGauge(
160
+ "nodejs.memory.heap_limit_bytes",
161
+ { description: "Configured V8 heap size limit (bytes)", unit: "By" },
162
+ );
163
+ const heapUsedRatioGauge = meter.createObservableGauge(
164
+ "nodejs.memory.heap_used_ratio",
165
+ { description: "V8 heap used divided by V8 heap size limit", unit: "1" },
166
+ );
167
+ const cgroupCurrentGauge = meter.createObservableGauge(
168
+ "nodejs.memory.cgroup_current_bytes",
169
+ { description: "Current cgroup memory usage when available", unit: "By" },
170
+ );
171
+ const cgroupLimitGauge = meter.createObservableGauge(
172
+ "nodejs.memory.cgroup_limit_bytes",
173
+ { description: "Cgroup memory limit when available", unit: "By" },
174
+ );
175
+ const cgroupUsageRatioGauge = meter.createObservableGauge(
176
+ "nodejs.memory.cgroup_usage_ratio",
177
+ {
178
+ description: "Cgroup memory usage divided by cgroup memory limit",
179
+ unit: "1",
180
+ },
181
+ );
182
+ const eventLoopDelayMeanGauge = meter.createObservableGauge(
183
+ "nodejs.event_loop.delay.mean_ms",
184
+ {
185
+ description: "Mean event-loop delay for the last collection window",
186
+ unit: "ms",
187
+ },
188
+ );
189
+ const eventLoopDelayMaxGauge = meter.createObservableGauge(
190
+ "nodejs.event_loop.delay.max_ms",
191
+ {
192
+ description: "Max event-loop delay for the last collection window",
193
+ unit: "ms",
194
+ },
195
+ );
196
+ const eventLoopDelayP50Gauge = meter.createObservableGauge(
197
+ "nodejs.event_loop.delay.p50_ms",
198
+ {
199
+ description: "p50 event-loop delay for the last collection window",
200
+ unit: "ms",
201
+ },
202
+ );
203
+ const eventLoopDelayP90Gauge = meter.createObservableGauge(
204
+ "nodejs.event_loop.delay.p90_ms",
205
+ {
206
+ description: "p90 event-loop delay for the last collection window",
207
+ unit: "ms",
208
+ },
209
+ );
210
+ const eventLoopDelayP99Gauge = meter.createObservableGauge(
211
+ "nodejs.event_loop.delay.p99_ms",
212
+ {
213
+ description: "p99 event-loop delay for the last collection window",
214
+ unit: "ms",
215
+ },
216
+ );
217
+ const eventLoopUtilizationGauge = meter.createObservableGauge(
218
+ "nodejs.event_loop.utilization",
219
+ {
220
+ description:
221
+ "Event-loop utilization delta for the last collection window",
222
+ unit: "1",
223
+ },
224
+ );
225
+ const processCpuUserCounter = meter.createObservableCounter(
226
+ "nodejs.process.cpu.user_seconds",
227
+ { description: "Process user CPU time since start", unit: "s" },
228
+ );
229
+ const processCpuSystemCounter = meter.createObservableCounter(
230
+ "nodejs.process.cpu.system_seconds",
231
+ { description: "Process system CPU time since start", unit: "s" },
232
+ );
69
233
 
70
- meter.addBatchObservableCallback(batchCb, gauges);
234
+ const gcCountCounter = meter.createCounter("nodejs.gc.count", {
235
+ description: "Number of garbage collection events",
236
+ unit: "{event}",
237
+ });
238
+ const gcDurationHistogram = meter.createHistogram("nodejs.gc.duration_ms", {
239
+ description: "Garbage collection duration by collection kind",
240
+ unit: "ms",
241
+ advice: {
242
+ explicitBucketBoundaries: [0.5, 1, 2, 5, 10, 25, 50, 100, 250, 500],
243
+ },
244
+ });
71
245
 
72
- const gcObserver = new PerformanceObserver(
73
- (list: PerformanceObserverEntryList) => {
74
- gcCountCounter.add(list.getEntries().length);
75
- },
76
- );
77
- gcObserver.observe({ entryTypes: ["gc"], buffered: false });
246
+ const observableInstruments = [
247
+ heapUsedGauge,
248
+ heapTotalGauge,
249
+ rssGauge,
250
+ externalGauge,
251
+ arrayBuffersGauge,
252
+ heapLimitGauge,
253
+ heapUsedRatioGauge,
254
+ cgroupCurrentGauge,
255
+ cgroupLimitGauge,
256
+ cgroupUsageRatioGauge,
257
+ eventLoopDelayMeanGauge,
258
+ eventLoopDelayMaxGauge,
259
+ eventLoopDelayP50Gauge,
260
+ eventLoopDelayP90Gauge,
261
+ eventLoopDelayP99Gauge,
262
+ eventLoopUtilizationGauge,
263
+ processCpuUserCounter,
264
+ processCpuSystemCounter,
265
+ ];
78
266
 
79
- cleanupFn = () => {
80
- gcObserver.disconnect();
81
- meter.removeBatchObservableCallback(batchCb, gauges);
82
- };
267
+ // Single callback per export interval keeps runtime stats temporally aligned.
268
+ const batchCb = (result: BatchObservableResult) => {
269
+ try {
270
+ const mem = process.memoryUsage();
271
+ const heap = getHeapStatistics();
272
+ const cgroup = readCgroupMemory();
273
+ const elu = performance.eventLoopUtilization(
274
+ previousEventLoopUtilization,
275
+ );
276
+ previousEventLoopUtilization = performance.eventLoopUtilization();
277
+ const cpu = process.cpuUsage();
278
+
279
+ result.observe(heapUsedGauge, mem.heapUsed);
280
+ result.observe(heapTotalGauge, mem.heapTotal);
281
+ result.observe(rssGauge, mem.rss);
282
+ result.observe(externalGauge, mem.external);
283
+ result.observe(arrayBuffersGauge, mem.arrayBuffers);
284
+ result.observe(heapLimitGauge, heap.heap_size_limit);
285
+ result.observe(
286
+ heapUsedRatioGauge,
287
+ ratio(mem.heapUsed, heap.heap_size_limit),
288
+ );
289
+ // Omit cgroup gauges when no finite cgroup limit is available; absence means host/unlimited memory, not telemetry setup failure.
290
+ if (cgroup) {
291
+ result.observe(cgroupCurrentGauge, cgroup.currentBytes);
292
+ result.observe(cgroupLimitGauge, cgroup.limitBytes);
293
+ result.observe(cgroupUsageRatioGauge, cgroup.usageRatio);
294
+ }
295
+ result.observe(eventLoopDelayMeanGauge, nsToMs(eventLoopDelay.mean));
296
+ result.observe(eventLoopDelayMaxGauge, nsToMs(eventLoopDelay.max));
297
+ result.observe(
298
+ eventLoopDelayP50Gauge,
299
+ nsToMs(eventLoopDelay.percentile(50)),
300
+ );
301
+ result.observe(
302
+ eventLoopDelayP90Gauge,
303
+ nsToMs(eventLoopDelay.percentile(90)),
304
+ );
305
+ result.observe(
306
+ eventLoopDelayP99Gauge,
307
+ nsToMs(eventLoopDelay.percentile(99)),
308
+ );
309
+ result.observe(
310
+ eventLoopUtilizationGauge,
311
+ finiteNonNegative(elu.utilization),
312
+ );
313
+ result.observe(processCpuUserCounter, cpu.user / US_PER_SECOND);
314
+ result.observe(processCpuSystemCounter, cpu.system / US_PER_SECOND);
315
+ } finally {
316
+ eventLoopDelay.reset();
317
+ }
318
+ };
319
+
320
+ meter.addBatchObservableCallback(batchCb, observableInstruments);
321
+ removeBatchCallback = () => {
322
+ meter.removeBatchObservableCallback(batchCb, observableInstruments);
323
+ };
324
+
325
+ const gcObserver = new PerformanceObserver(
326
+ (list: PerformanceObserverEntryList) => {
327
+ for (const entry of list.getEntries() as GcPerformanceEntry[]) {
328
+ const kind = gcKind(entry.detail?.kind ?? entry.kind);
329
+ const attrs = { kind };
330
+ gcCountCounter.add(1, attrs);
331
+ gcDurationHistogram.record(finiteNonNegative(entry.duration), attrs);
332
+ }
333
+ },
334
+ );
335
+ disconnectGcObserver = () => {
336
+ gcObserver.disconnect();
337
+ };
338
+ gcObserver.observe({ entryTypes: ["gc"], buffered: false });
339
+
340
+ eventLoopDelay.enable();
341
+ cleanupFn = () => {
342
+ eventLoopDelay.disable();
343
+ disconnectGcObserver?.();
344
+ removeBatchCallback?.();
345
+ };
346
+ } catch (error) {
347
+ eventLoopDelay.disable();
348
+ disconnectGcObserver?.();
349
+ removeBatchCallback?.();
350
+ throw error;
351
+ }
83
352
  }
84
353
 
85
354
  export function stopMemoryMetrics(): void {
@@ -2,6 +2,8 @@ import path from "node:path";
2
2
 
3
3
  import type { Plugin } from "vite";
4
4
 
5
+ const SERVER_APIS_DIR = "server/apis";
6
+
5
7
  /**
6
8
  * Build a sourcemap `mappings` string for a simple prepend operation.
7
9
  *
@@ -24,27 +26,95 @@ function buildPrependMappings(
24
26
  return empty + original;
25
27
  }
26
28
 
29
+ function qualifyAnchoredServerApisRelative(relative: string): string | null {
30
+ if (relative === `${SERVER_APIS_DIR}/index.ts`) {
31
+ return null;
32
+ }
33
+ const baseName = path.posix.basename(relative);
34
+ if (baseName === "index.ts") {
35
+ return null;
36
+ }
37
+ if (!relative.endsWith(".ts") && !relative.endsWith(".tsx")) {
38
+ return null;
39
+ }
40
+ return relative;
41
+ }
42
+
43
+ function qualifySegmentFallbackRelative(relative: string): string | null {
44
+ if (!relative.startsWith(`${SERVER_APIS_DIR}/`)) {
45
+ return null;
46
+ }
47
+ // Reject false positives when appRootDir sits under a server/apis/ path.
48
+ if (relative.includes("/client/")) {
49
+ return null;
50
+ }
51
+ const baseName = path.posix.basename(relative);
52
+ if (baseName !== "api.ts" && baseName !== "api.tsx") {
53
+ return null;
54
+ }
55
+ return relative;
56
+ }
57
+
58
+ /**
59
+ * Resolve the app-root-relative entry point path for a Vite module id.
60
+ *
61
+ * Fullstack apps keep `server/apis/` at the app root while `vite.config.ts`
62
+ * often sets `root: "./client"`. Dev server and build already pass the true
63
+ * app root into the plugin; failures are intermittent and depend on how Vite
64
+ * resolves module ids for files outside the client subtree (for example
65
+ * `../server/apis/...` relatives or `/@fs/...` absolute ids). Plain absolute
66
+ * paths under `<appRoot>/server/apis/` already matched before this helper.
67
+ */
68
+ export function resolveSdkApiEntryPointRelativePath(
69
+ appRootDir: string,
70
+ moduleId: string,
71
+ ): string | null {
72
+ const normalizedId = path.normalize(moduleId);
73
+ const normalizedRoot = path.normalize(appRootDir);
74
+
75
+ const relative = path
76
+ .relative(normalizedRoot, normalizedId)
77
+ .replace(/\\/g, "/");
78
+ if (relative.startsWith(`${SERVER_APIS_DIR}/`)) {
79
+ return qualifyAnchoredServerApisRelative(relative);
80
+ }
81
+
82
+ // Plugin base is client/ or Vite passes a ../server/apis/... module id.
83
+ if (relative.startsWith(`../${SERVER_APIS_DIR}/`)) {
84
+ return qualifyAnchoredServerApisRelative(relative.slice("../".length));
85
+ }
86
+
87
+ // Fallback for module ids not matched above: /@fs/ prefixed ids, standard
88
+ // absolute paths when appRootDir is 2+ levels above server/apis/, etc.
89
+ // NOTE: unanchored to appRootDir — matches any id containing /server/apis/
90
+ // with an api.ts/api.tsx basename. lastIndexOf picks the deepest segment.
91
+ const posixId = normalizedId.replace(/\\/g, "/");
92
+ const segment = `/${SERVER_APIS_DIR}/`;
93
+ const segmentIndex = posixId.lastIndexOf(segment);
94
+ if (segmentIndex !== -1) {
95
+ return qualifySegmentFallbackRelative(posixId.slice(segmentIndex + 1));
96
+ }
97
+
98
+ return null;
99
+ }
100
+
27
101
  /**
28
102
  * Vite plugin that prepends `__setEntryPoint(relativePath)` to SDK API files
29
103
  * so that `api()` can stamp the authoritative source file
30
104
  * path onto the compiled API object.
31
105
  *
106
+ * @param appRootDir - App root (parent of `client/` and `server/`).
107
+ *
32
108
  * Runs in both dev and build. The user's source code is never modified on disk.
33
109
  */
34
- export function sdkApiEntryPointPlugin(root: string): Plugin {
110
+ export function sdkApiEntryPointPlugin(appRootDir: string): Plugin {
35
111
  return {
36
112
  name: "sb-sdk-api-entry-point",
37
113
  enforce: "pre",
38
114
 
39
115
  transform(code, id) {
40
- const relative = path.relative(root, id).replace(/\\/g, "/");
41
- if (
42
- !relative.startsWith("server/apis/") ||
43
- relative === "server/apis/index.ts"
44
- ) {
45
- return null;
46
- }
47
- if (!relative.endsWith(".ts") && !relative.endsWith(".tsx")) {
116
+ const relative = resolveSdkApiEntryPointRelativePath(appRootDir, id);
117
+ if (!relative) {
48
118
  return null;
49
119
  }
50
120
 
@@ -2,7 +2,10 @@ import path from "node:path";
2
2
 
3
3
  import { describe, it, expect } from "vitest";
4
4
 
5
- import { sdkApiEntryPointPlugin } from "./vite-plugin-sdk-api-entry-point.mjs";
5
+ import {
6
+ resolveSdkApiEntryPointRelativePath,
7
+ sdkApiEntryPointPlugin,
8
+ } from "./vite-plugin-sdk-api-entry-point.mjs";
6
9
 
7
10
  type TransformResult = {
8
11
  code: string;
@@ -88,6 +91,95 @@ function expectValidSourcemap(
88
91
  });
89
92
  }
90
93
 
94
+ describe("resolveSdkApiEntryPointRelativePath", () => {
95
+ it("resolves server API paths from the true app root", () => {
96
+ expect(
97
+ resolveSdkApiEntryPointRelativePath(
98
+ "/app",
99
+ "/app/server/apis/GetUsers/api.ts",
100
+ ),
101
+ ).toBe("server/apis/GetUsers/api.ts");
102
+ });
103
+
104
+ it("resolves server API paths when the base dir is vite client/", () => {
105
+ expect(
106
+ resolveSdkApiEntryPointRelativePath(
107
+ "/app/client",
108
+ "/app/server/apis/GetPastAnalyses/api.ts",
109
+ ),
110
+ ).toBe("server/apis/GetPastAnalyses/api.ts");
111
+ });
112
+
113
+ it("resolves server API paths from absolute /@fs module ids", () => {
114
+ expect(
115
+ resolveSdkApiEntryPointRelativePath(
116
+ "/app",
117
+ "/@fs/Users/me/app/server/apis/GetFeedback/api.ts",
118
+ ),
119
+ ).toBe("server/apis/GetFeedback/api.ts");
120
+ });
121
+
122
+ it("returns null for the registry barrel file", () => {
123
+ expect(
124
+ resolveSdkApiEntryPointRelativePath("/app", "/app/server/apis/index.ts"),
125
+ ).toBeNull();
126
+ });
127
+
128
+ it("returns null when app root contains server/apis and module is a client file", () => {
129
+ expect(
130
+ resolveSdkApiEntryPointRelativePath(
131
+ "/home/server/apis/myapp",
132
+ "/home/server/apis/myapp/client/components/Button.tsx",
133
+ ),
134
+ ).toBeNull();
135
+ });
136
+
137
+ it("uses the deepest server/apis segment in /@fs fallback", () => {
138
+ expect(
139
+ resolveSdkApiEntryPointRelativePath(
140
+ "/app",
141
+ "/@fs/home/server/apis/decoy/server/apis/GetReal/api.ts",
142
+ ),
143
+ ).toBe("server/apis/GetReal/api.ts");
144
+ });
145
+
146
+ it("resolves server API paths for api.tsx entry points", () => {
147
+ expect(
148
+ resolveSdkApiEntryPointRelativePath(
149
+ "/app",
150
+ "/app/server/apis/Render/api.tsx",
151
+ ),
152
+ ).toBe("server/apis/Render/api.tsx");
153
+ });
154
+
155
+ it("resolves Clark-style API entry points that are not named api.ts", () => {
156
+ expect(
157
+ resolveSdkApiEntryPointRelativePath(
158
+ "/app",
159
+ "/app/server/apis/issues/list-issues.ts",
160
+ ),
161
+ ).toBe("server/apis/issues/list-issues.ts");
162
+ });
163
+
164
+ it("resolves helper modules under server/apis/ on anchored paths", () => {
165
+ expect(
166
+ resolveSdkApiEntryPointRelativePath(
167
+ "/app",
168
+ "/app/server/apis/GetFoo/helper.ts",
169
+ ),
170
+ ).toBe("server/apis/GetFoo/helper.ts");
171
+ });
172
+
173
+ it("returns null for index.ts under an API directory", () => {
174
+ expect(
175
+ resolveSdkApiEntryPointRelativePath(
176
+ "/app",
177
+ "/app/server/apis/GetFoo/index.ts",
178
+ ),
179
+ ).toBeNull();
180
+ });
181
+ });
182
+
91
183
  describe("sdkApiEntryPointPlugin", () => {
92
184
  const root = "/app";
93
185
 
@@ -98,6 +190,19 @@ describe("sdkApiEntryPointPlugin", () => {
98
190
  });
99
191
 
100
192
  describe("transform", () => {
193
+ it("prepends __setEntryPoint for Clark-style list-issues.ts entry points", () => {
194
+ const { transform } = createPlugin(root);
195
+ const result = transform(
196
+ 'export default api({ name: "ListIssues" });',
197
+ path.join(root, "server/apis/issues/list-issues.ts"),
198
+ );
199
+
200
+ expect(result).not.toBeNull();
201
+ expect(result!.code).toContain(
202
+ '__sb_set_ep("server/apis/issues/list-issues.ts");',
203
+ );
204
+ });
205
+
101
206
  it("prepends __setEntryPoint for a standard API file", () => {
102
207
  const { transform } = createPlugin(root);
103
208
  const result = transform(
@@ -171,6 +276,34 @@ describe("sdkApiEntryPointPlugin", () => {
171
276
  );
172
277
  });
173
278
 
279
+ it("prepends __setEntryPoint when plugin root is vite client/ subdir (fullstack)", () => {
280
+ const appRoot = "/app";
281
+ const viteRoot = path.join(appRoot, "client");
282
+ const { transform } = createPlugin(viteRoot);
283
+ const result = transform(
284
+ 'export default api({ name: "GetPastAnalyses" });',
285
+ path.join(appRoot, "server/apis/GetPastAnalyses/api.ts"),
286
+ );
287
+
288
+ expect(result).not.toBeNull();
289
+ expect(result!.code).toContain(
290
+ '__sb_set_ep("server/apis/GetPastAnalyses/api.ts");',
291
+ );
292
+ });
293
+
294
+ it("prepends __setEntryPoint for /@fs/ module ids", () => {
295
+ const { transform } = createPlugin(root);
296
+ const result = transform(
297
+ 'export default api({ name: "GetFeedback" });',
298
+ "/@fs/Users/me/app/server/apis/GetFeedback/api.ts",
299
+ );
300
+
301
+ expect(result).not.toBeNull();
302
+ expect(result!.code).toContain(
303
+ '__sb_set_ep("server/apis/GetFeedback/api.ts");',
304
+ );
305
+ });
306
+
174
307
  it("preserves original code after the prepend", () => {
175
308
  const { transform } = createPlugin(root);
176
309
  const originalCode = [