@glasstrace/sdk 0.4.2 → 0.7.1

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.
@@ -9,7 +9,7 @@ import {
9
9
  } from "../chunk-PLJVIWHN.js";
10
10
  import {
11
11
  readAnonKey
12
- } from "../chunk-TVOYTJ7I.js";
12
+ } from "../chunk-QW6W4CSA.js";
13
13
  import "../chunk-PZ5AY32C.js";
14
14
 
15
15
  // src/cli/mcp-add.ts
package/dist/index.cjs CHANGED
@@ -1617,6 +1617,7 @@ var src_exports = {};
1617
1617
  __export(src_exports, {
1618
1618
  GlasstraceExporter: () => GlasstraceExporter,
1619
1619
  GlasstraceSpanProcessor: () => GlasstraceSpanProcessor,
1620
+ PRESIGNED_THRESHOLD_BYTES: () => PRESIGNED_THRESHOLD_BYTES,
1620
1621
  SdkError: () => SdkError,
1621
1622
  SessionManager: () => SessionManager,
1622
1623
  buildImportGraph: () => buildImportGraph,
@@ -1644,6 +1645,8 @@ __export(src_exports, {
1644
1645
  saveCachedConfig: () => saveCachedConfig,
1645
1646
  sendInitRequest: () => sendInitRequest,
1646
1647
  uploadSourceMaps: () => uploadSourceMaps,
1648
+ uploadSourceMapsAuto: () => uploadSourceMapsAuto,
1649
+ uploadSourceMapsPresigned: () => uploadSourceMapsPresigned,
1647
1650
  withGlasstraceConfig: () => withGlasstraceConfig
1648
1651
  });
1649
1652
  module.exports = __toCommonJS(src_exports);
@@ -15556,7 +15559,12 @@ var SdkInitResponseSchema = external_exports.object({
15556
15559
  linkedAccountId: external_exports.string().uuid().optional(),
15557
15560
  minimumSdkVersion: external_exports.string(),
15558
15561
  apiVersion: external_exports.string(),
15559
- tierLimits: TierLimitsSchema
15562
+ tierLimits: TierLimitsSchema,
15563
+ claimResult: external_exports.object({
15564
+ newApiKey: DevApiKeySchema,
15565
+ accountId: external_exports.string().uuid(),
15566
+ graceExpiresAt: external_exports.number().int().positive()
15567
+ }).optional()
15560
15568
  });
15561
15569
  var DiscoveryResponseSchema = external_exports.object({
15562
15570
  key: AnonApiKeySchema,
@@ -15568,6 +15576,45 @@ var SourceMapUploadResponseSchema = external_exports.object({
15568
15576
  fileCount: external_exports.number().int().nonnegative(),
15569
15577
  totalSizeBytes: external_exports.number().int().nonnegative()
15570
15578
  });
15579
+ var PresignedUploadRequestSchema = external_exports.object({
15580
+ buildHash: BuildHashSchema,
15581
+ files: external_exports.array(
15582
+ external_exports.object({
15583
+ filePath: external_exports.string().min(1),
15584
+ sizeBytes: external_exports.number().int().positive()
15585
+ })
15586
+ ).min(1).max(100)
15587
+ });
15588
+ var PresignedUploadResponseSchema = external_exports.object({
15589
+ uploadId: external_exports.string().uuid(),
15590
+ expiresAt: external_exports.number().int().positive(),
15591
+ files: external_exports.array(
15592
+ external_exports.object({
15593
+ filePath: external_exports.string().min(1),
15594
+ clientToken: external_exports.string().min(1),
15595
+ pathname: external_exports.string().min(1),
15596
+ maxBytes: external_exports.number().int().positive()
15597
+ })
15598
+ ).min(1).max(100)
15599
+ });
15600
+ var SourceMapManifestRequestSchema = external_exports.object({
15601
+ uploadId: external_exports.string().uuid(),
15602
+ buildHash: BuildHashSchema,
15603
+ files: external_exports.array(
15604
+ external_exports.object({
15605
+ filePath: external_exports.string().min(1),
15606
+ sizeBytes: external_exports.number().int().positive(),
15607
+ blobUrl: external_exports.string().url()
15608
+ })
15609
+ ).min(1).max(100)
15610
+ });
15611
+ var SourceMapManifestResponseSchema = external_exports.object({
15612
+ success: external_exports.literal(true),
15613
+ buildHash: BuildHashSchema,
15614
+ fileCount: external_exports.number().int().nonnegative(),
15615
+ totalSizeBytes: external_exports.number().int().nonnegative(),
15616
+ activatedAt: external_exports.number().int().positive()
15617
+ });
15571
15618
  var GLASSTRACE_ATTRIBUTE_NAMES = {
15572
15619
  // Server-side attributes
15573
15620
  TRACE_TYPE: "glasstrace.trace.type",
@@ -15803,12 +15850,14 @@ async function saveCachedConfig(response, projectRoot) {
15803
15850
  const dirPath = (0, import_node_path2.join)(root, GLASSTRACE_DIR2);
15804
15851
  const configPath = (0, import_node_path2.join)(dirPath, CONFIG_FILE);
15805
15852
  try {
15806
- await (0, import_promises2.mkdir)(dirPath, { recursive: true });
15853
+ await (0, import_promises2.mkdir)(dirPath, { recursive: true, mode: 448 });
15854
+ await (0, import_promises2.chmod)(dirPath, 448);
15807
15855
  const cached2 = {
15808
15856
  response,
15809
15857
  cachedAt: Date.now()
15810
15858
  };
15811
- await (0, import_promises2.writeFile)(configPath, JSON.stringify(cached2), "utf-8");
15859
+ await (0, import_promises2.writeFile)(configPath, JSON.stringify(cached2), { encoding: "utf-8", mode: 384 });
15860
+ await (0, import_promises2.chmod)(configPath, 384);
15812
15861
  } catch (err) {
15813
15862
  console.warn(
15814
15863
  `[glasstrace] Failed to cache config to ${configPath}: ${err instanceof Error ? err.message : String(err)}`
@@ -15861,16 +15910,88 @@ async function sendInitRequest(config2, anonKey, sdkVersion, importGraph, health
15861
15910
  const body = await response.json();
15862
15911
  return SdkInitResponseSchema.parse(body);
15863
15912
  }
15913
+ async function writeClaimedKey(newApiKey, projectRoot) {
15914
+ const root = projectRoot ?? process.cwd();
15915
+ const envLocalPath = (0, import_node_path2.join)(root, ".env.local");
15916
+ let envLocalWritten = false;
15917
+ try {
15918
+ let content;
15919
+ try {
15920
+ content = await (0, import_promises2.readFile)(envLocalPath, "utf-8");
15921
+ if (/^GLASSTRACE_API_KEY=.*/m.test(content)) {
15922
+ content = content.replace(
15923
+ /^GLASSTRACE_API_KEY=.*$/gm,
15924
+ `GLASSTRACE_API_KEY=${newApiKey}`
15925
+ );
15926
+ } else {
15927
+ if (content.length > 0 && !content.endsWith("\n")) {
15928
+ content += "\n";
15929
+ }
15930
+ content += `GLASSTRACE_API_KEY=${newApiKey}
15931
+ `;
15932
+ }
15933
+ } catch (readErr) {
15934
+ const code = readErr instanceof Error ? readErr.code : void 0;
15935
+ if (code !== "ENOENT") {
15936
+ throw readErr;
15937
+ }
15938
+ content = `GLASSTRACE_API_KEY=${newApiKey}
15939
+ `;
15940
+ }
15941
+ await (0, import_promises2.writeFile)(envLocalPath, content, { encoding: "utf-8", mode: 384 });
15942
+ await (0, import_promises2.chmod)(envLocalPath, 384);
15943
+ envLocalWritten = true;
15944
+ } catch {
15945
+ }
15946
+ if (envLocalWritten) {
15947
+ try {
15948
+ process.stderr.write(
15949
+ "[glasstrace] Account claimed! API key written to .env.local. Restart your dev server to use it.\n"
15950
+ );
15951
+ } catch {
15952
+ }
15953
+ return;
15954
+ }
15955
+ let claimedKeyWritten = false;
15956
+ try {
15957
+ const dirPath = (0, import_node_path2.join)(root, GLASSTRACE_DIR2);
15958
+ await (0, import_promises2.mkdir)(dirPath, { recursive: true, mode: 448 });
15959
+ await (0, import_promises2.chmod)(dirPath, 448);
15960
+ const claimedKeyPath = (0, import_node_path2.join)(dirPath, "claimed-key");
15961
+ await (0, import_promises2.writeFile)(claimedKeyPath, newApiKey, {
15962
+ encoding: "utf-8",
15963
+ mode: 384
15964
+ });
15965
+ await (0, import_promises2.chmod)(claimedKeyPath, 384);
15966
+ claimedKeyWritten = true;
15967
+ } catch {
15968
+ }
15969
+ if (claimedKeyWritten) {
15970
+ try {
15971
+ process.stderr.write(
15972
+ "[glasstrace] Account claimed! API key written to .glasstrace/claimed-key. Copy it to your .env.local file.\n"
15973
+ );
15974
+ } catch {
15975
+ }
15976
+ return;
15977
+ }
15978
+ try {
15979
+ process.stderr.write(
15980
+ "[glasstrace] Account claimed but could not write key to disk. Visit your dashboard settings to rotate and retrieve a new API key.\n"
15981
+ );
15982
+ } catch {
15983
+ }
15984
+ }
15864
15985
  async function performInit(config2, anonKey, sdkVersion) {
15865
15986
  if (rateLimitBackoff) {
15866
15987
  rateLimitBackoff = false;
15867
- return;
15988
+ return null;
15868
15989
  }
15869
15990
  try {
15870
15991
  const effectiveKey = config2.apiKey || anonKey;
15871
15992
  if (!effectiveKey) {
15872
15993
  console.warn("[glasstrace] No API key available for init request.");
15873
- return;
15994
+ return null;
15874
15995
  }
15875
15996
  const controller = new AbortController();
15876
15997
  const timeoutId = setTimeout(() => controller.abort(), INIT_TIMEOUT_MS);
@@ -15887,45 +16008,55 @@ async function performInit(config2, anonKey, sdkVersion) {
15887
16008
  clearTimeout(timeoutId);
15888
16009
  currentConfig = result;
15889
16010
  await saveCachedConfig(result);
16011
+ if (result.claimResult) {
16012
+ try {
16013
+ await writeClaimedKey(result.claimResult.newApiKey);
16014
+ } catch {
16015
+ }
16016
+ return { claimResult: result.claimResult };
16017
+ }
16018
+ return null;
15890
16019
  } catch (err) {
15891
16020
  clearTimeout(timeoutId);
15892
16021
  if (err instanceof DOMException && err.name === "AbortError") {
15893
16022
  console.warn("[glasstrace] ingestion_unreachable: Init request timed out.");
15894
- return;
16023
+ return null;
15895
16024
  }
15896
16025
  const status = err.status;
15897
16026
  if (status === 401) {
15898
16027
  console.warn(
15899
16028
  "[glasstrace] ingestion_auth_failed: Check your GLASSTRACE_API_KEY."
15900
16029
  );
15901
- return;
16030
+ return null;
15902
16031
  }
15903
16032
  if (status === 429) {
15904
16033
  console.warn("[glasstrace] ingestion_rate_limited: Backing off.");
15905
16034
  rateLimitBackoff = true;
15906
- return;
16035
+ return null;
15907
16036
  }
15908
16037
  if (typeof status === "number" && status >= 400) {
15909
16038
  console.warn(
15910
16039
  `[glasstrace] Init request failed with status ${status}. Using cached config.`
15911
16040
  );
15912
- return;
16041
+ return null;
15913
16042
  }
15914
16043
  if (err instanceof Error && err.name === "ZodError") {
15915
16044
  console.warn(
15916
16045
  "[glasstrace] Init response failed validation (schema version mismatch?). Using cached config."
15917
16046
  );
15918
- return;
16047
+ return null;
15919
16048
  }
15920
16049
  console.warn(
15921
16050
  `[glasstrace] ingestion_unreachable: ${err instanceof Error ? err.message : String(err)}`
15922
16051
  );
16052
+ return null;
15923
16053
  }
15924
16054
  } catch (err) {
15925
16055
  console.warn(
15926
16056
  `[glasstrace] Unexpected init error: ${err instanceof Error ? err.message : String(err)}`
15927
16057
  );
15928
16058
  }
16059
+ return null;
15929
16060
  }
15930
16061
  function getActiveConfig() {
15931
16062
  if (currentConfig) {
@@ -19066,6 +19197,14 @@ async function installConsoleCapture() {
19066
19197
  }
19067
19198
  };
19068
19199
  }
19200
+ function sdkLog(level, message) {
19201
+ isGlasstraceLog = true;
19202
+ try {
19203
+ console[level](message);
19204
+ } finally {
19205
+ isGlasstraceLog = false;
19206
+ }
19207
+ }
19069
19208
 
19070
19209
  // src/register.ts
19071
19210
  var consoleCaptureInstalled = false;
@@ -19155,7 +19294,11 @@ function registerGlasstrace(options) {
19155
19294
  if (config2.verbose) {
19156
19295
  console.info("[glasstrace] Background init firing.");
19157
19296
  }
19158
- await performInit(config2, anonKey, "0.4.2");
19297
+ const initResult = await performInit(config2, anonKey, "0.7.1");
19298
+ if (initResult?.claimResult) {
19299
+ setResolvedApiKey(initResult.claimResult.newApiKey);
19300
+ notifyApiKeyResolved();
19301
+ }
19159
19302
  maybeInstallConsoleCapture();
19160
19303
  } catch (err) {
19161
19304
  console.warn(
@@ -19175,7 +19318,11 @@ function registerGlasstrace(options) {
19175
19318
  if (config2.verbose) {
19176
19319
  console.info("[glasstrace] Background init firing.");
19177
19320
  }
19178
- await performInit(config2, anonKey, "0.4.2");
19321
+ const initResult = await performInit(config2, anonKey, "0.7.1");
19322
+ if (initResult?.claimResult) {
19323
+ setResolvedApiKey(initResult.claimResult.newApiKey);
19324
+ notifyApiKeyResolved();
19325
+ }
19179
19326
  maybeInstallConsoleCapture();
19180
19327
  } catch (err) {
19181
19328
  console.warn(
@@ -19197,7 +19344,7 @@ function registerGlasstrace(options) {
19197
19344
  if (config2.verbose) {
19198
19345
  console.info("[glasstrace] Background init firing.");
19199
19346
  }
19200
- await performInit(config2, anonKeyForInit, "0.4.2");
19347
+ await performInit(config2, anonKeyForInit, "0.7.1");
19201
19348
  maybeInstallConsoleCapture();
19202
19349
  } catch (err) {
19203
19350
  console.warn(
@@ -19296,10 +19443,7 @@ async function uploadSourceMaps(apiKey, endpoint, buildHash, maps) {
19296
19443
  sourceMap: m.content
19297
19444
  }))
19298
19445
  };
19299
- let baseUrl = endpoint;
19300
- while (baseUrl.endsWith("/")) {
19301
- baseUrl = baseUrl.slice(0, -1);
19302
- }
19446
+ const baseUrl = stripTrailingSlashes(endpoint);
19303
19447
  const response = await fetch(`${baseUrl}/v1/source-maps`, {
19304
19448
  method: "POST",
19305
19449
  headers: {
@@ -19320,6 +19464,155 @@ async function uploadSourceMaps(apiKey, endpoint, buildHash, maps) {
19320
19464
  const json2 = await response.json();
19321
19465
  return SourceMapUploadResponseSchema.parse(json2);
19322
19466
  }
19467
+ var PRESIGNED_THRESHOLD_BYTES = 45e5;
19468
+ function stripTrailingSlashes(url2) {
19469
+ let result = url2;
19470
+ while (result.endsWith("/")) {
19471
+ result = result.slice(0, -1);
19472
+ }
19473
+ return result;
19474
+ }
19475
+ async function requestPresignedTokens(apiKey, endpoint, buildHash, files) {
19476
+ const baseUrl = stripTrailingSlashes(endpoint);
19477
+ const response = await fetch(`${baseUrl}/v1/source-maps/presign`, {
19478
+ method: "POST",
19479
+ headers: {
19480
+ "Content-Type": "application/json",
19481
+ Authorization: `Bearer ${apiKey}`
19482
+ },
19483
+ body: JSON.stringify({ buildHash, files })
19484
+ });
19485
+ if (!response.ok) {
19486
+ try {
19487
+ await response.text();
19488
+ } catch {
19489
+ }
19490
+ throw new Error(
19491
+ `Presigned token request failed: ${String(response.status)} ${response.statusText}`
19492
+ );
19493
+ }
19494
+ const json2 = await response.json();
19495
+ return PresignedUploadResponseSchema.parse(json2);
19496
+ }
19497
+ async function uploadToBlob(clientToken, pathname, content) {
19498
+ let mod;
19499
+ try {
19500
+ mod = await import("@vercel/blob/client");
19501
+ } catch (err) {
19502
+ const code = err.code;
19503
+ if (code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND") {
19504
+ throw new Error(
19505
+ "Presigned upload requires @vercel/blob. Install it: npm install @vercel/blob"
19506
+ );
19507
+ }
19508
+ throw err;
19509
+ }
19510
+ const result = await mod.put(pathname, new Blob([content]), {
19511
+ access: "public",
19512
+ token: clientToken
19513
+ });
19514
+ return { url: result.url, size: Buffer.byteLength(content, "utf-8") };
19515
+ }
19516
+ async function submitManifest(apiKey, endpoint, uploadId, buildHash, files) {
19517
+ const baseUrl = stripTrailingSlashes(endpoint);
19518
+ const response = await fetch(`${baseUrl}/v1/source-maps/manifest`, {
19519
+ method: "POST",
19520
+ headers: {
19521
+ "Content-Type": "application/json",
19522
+ Authorization: `Bearer ${apiKey}`
19523
+ },
19524
+ body: JSON.stringify({ uploadId, buildHash, files })
19525
+ });
19526
+ if (!response.ok) {
19527
+ try {
19528
+ await response.text();
19529
+ } catch {
19530
+ }
19531
+ throw new Error(
19532
+ `Source map manifest submission failed: ${String(response.status)} ${response.statusText}`
19533
+ );
19534
+ }
19535
+ const json2 = await response.json();
19536
+ return SourceMapManifestResponseSchema.parse(json2);
19537
+ }
19538
+ async function uploadSourceMapsPresigned(apiKey, endpoint, buildHash, maps, blobUploader = uploadToBlob) {
19539
+ if (maps.length === 0) {
19540
+ throw new Error("No source maps to upload");
19541
+ }
19542
+ const presigned = await requestPresignedTokens(
19543
+ apiKey,
19544
+ endpoint,
19545
+ buildHash,
19546
+ maps.map((m) => ({
19547
+ filePath: m.filePath,
19548
+ sizeBytes: Buffer.byteLength(m.content, "utf-8")
19549
+ }))
19550
+ );
19551
+ const mapsByPath = new Map(maps.map((m) => [m.filePath, m]));
19552
+ if (mapsByPath.size !== maps.length) {
19553
+ throw new Error("Duplicate filePath entries in source maps");
19554
+ }
19555
+ for (const token of presigned.files) {
19556
+ if (!mapsByPath.has(token.filePath)) {
19557
+ throw new Error(
19558
+ `Presigned token for "${token.filePath}" has no matching source map entry`
19559
+ );
19560
+ }
19561
+ }
19562
+ const CONCURRENCY = 5;
19563
+ const uploadResults = [];
19564
+ for (let i = 0; i < presigned.files.length; i += CONCURRENCY) {
19565
+ const chunk = presigned.files.slice(i, i + CONCURRENCY);
19566
+ const chunkResults = await Promise.all(
19567
+ chunk.map(async (token) => {
19568
+ const entry = mapsByPath.get(token.filePath);
19569
+ const result = await blobUploader(token.clientToken, token.pathname, entry.content);
19570
+ return {
19571
+ filePath: token.filePath,
19572
+ sizeBytes: result.size,
19573
+ blobUrl: result.url
19574
+ };
19575
+ })
19576
+ );
19577
+ uploadResults.push(...chunkResults);
19578
+ }
19579
+ return submitManifest(apiKey, endpoint, presigned.uploadId, buildHash, uploadResults);
19580
+ }
19581
+ async function uploadSourceMapsAuto(apiKey, endpoint, buildHash, maps, options) {
19582
+ if (maps.length === 0) {
19583
+ throw new Error("No source maps to upload");
19584
+ }
19585
+ const totalBytes = maps.reduce(
19586
+ (sum, m) => sum + Buffer.byteLength(m.content, "utf-8"),
19587
+ 0
19588
+ );
19589
+ if (totalBytes < PRESIGNED_THRESHOLD_BYTES) {
19590
+ return uploadSourceMaps(apiKey, endpoint, buildHash, maps);
19591
+ }
19592
+ const checkAvailable = options?.checkBlobAvailable ?? (async () => {
19593
+ try {
19594
+ await import("@vercel/blob/client");
19595
+ return true;
19596
+ } catch {
19597
+ return false;
19598
+ }
19599
+ });
19600
+ const blobAvailable = await checkAvailable();
19601
+ if (blobAvailable) {
19602
+ return uploadSourceMapsPresigned(
19603
+ apiKey,
19604
+ endpoint,
19605
+ buildHash,
19606
+ maps,
19607
+ options?.blobUploader
19608
+ );
19609
+ }
19610
+ sdkLog(
19611
+ "warn",
19612
+ `[glasstrace] Build exceeds 4.5MB (${totalBytes} bytes). Install @vercel/blob for presigned uploads to avoid serverless body size limits. Falling back to legacy upload.`
19613
+ );
19614
+ return uploadSourceMaps(apiKey, endpoint, buildHash, maps);
19615
+ }
19323
19616
 
19324
19617
  // src/config-wrapper.ts
19325
19618
  function withGlasstraceConfig(nextConfig) {
@@ -19609,6 +19902,7 @@ async function buildImportGraph(projectRoot) {
19609
19902
  0 && (module.exports = {
19610
19903
  GlasstraceExporter,
19611
19904
  GlasstraceSpanProcessor,
19905
+ PRESIGNED_THRESHOLD_BYTES,
19612
19906
  SdkError,
19613
19907
  SessionManager,
19614
19908
  buildImportGraph,
@@ -19636,6 +19930,8 @@ async function buildImportGraph(projectRoot) {
19636
19930
  saveCachedConfig,
19637
19931
  sendInitRequest,
19638
19932
  uploadSourceMaps,
19933
+ uploadSourceMapsAuto,
19934
+ uploadSourceMapsPresigned,
19639
19935
  withGlasstraceConfig
19640
19936
  });
19641
19937
  //# sourceMappingURL=index.cjs.map