@superblocksteam/library 2.0.149 → 2.0.150-next.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.
- package/dist/{build-manifest-Xi8oZhWX.js → build-manifest-BQAcrmit.js} +1 -1
- package/dist/{build-manifest-Xi8oZhWX.js.map → build-manifest-BQAcrmit.js.map} +1 -1
- package/dist/{devtools-consolidated--QF_TVsD.js → devtools-consolidated-C5sXwPGD.js} +1 -1
- package/dist/{devtools-consolidated--QF_TVsD.js.map → devtools-consolidated-C5sXwPGD.js.map} +1 -1
- package/dist/jsx-dev-runtime/index.js +2 -1
- package/dist/jsx-dev-runtime/index.js.map +1 -1
- package/dist/jsx-wrapper-c5W52jgK.js +638 -0
- package/dist/jsx-wrapper-c5W52jgK.js.map +1 -0
- package/dist/lib/index.d.ts.map +1 -1
- package/dist/lib/index.js +8 -321
- package/dist/lib/index.js.map +1 -1
- package/dist/{logs-Bo--dJx2.js → logs-DwKJqoRc.js} +1 -1
- package/dist/{logs-Bo--dJx2.js.map → logs-DwKJqoRc.js.map} +1 -1
- package/dist/rolldown-runtime-CiIaOW0V.js +13 -0
- package/dist/{jsx-wrapper-CSTsctdq.js → root-store-CkTnQd84.js} +215 -665
- package/dist/root-store-CkTnQd84.js.map +1 -0
- package/dist/sdk-api-discovery-ekr6aG8h.js +366 -0
- package/dist/sdk-api-discovery-ekr6aG8h.js.map +1 -0
- package/dist/{utils-C-i9g4Qh.js → utils-kXteBlMZ.js} +2 -13
- package/dist/{utils-C-i9g4Qh.js.map → utils-kXteBlMZ.js.map} +1 -1
- package/package.json +4 -4
- package/dist/jsx-wrapper-CSTsctdq.js.map +0 -1
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-CiIaOW0V.js";
|
|
2
|
+
import { T as sendMessageImmediately, n as root_store_default } from "./root-store-CkTnQd84.js";
|
|
3
|
+
import { getIntegrationDeclarations } from "@superblocksteam/sdk-api";
|
|
4
|
+
import zodToJsonSchema from "zod-to-json-schema";
|
|
5
|
+
//#region src/lib/internal-details/lib/registry-loader.ts
|
|
6
|
+
/**
|
|
7
|
+
* Dynamically import the SDK API registry module from the app origin.
|
|
8
|
+
*
|
|
9
|
+
* Uses a cache-busting parameter because the browser's ES module map
|
|
10
|
+
* caches modules by URL — without it, subsequent import() calls return
|
|
11
|
+
* the stale first-load module and newly created APIs are never discovered.
|
|
12
|
+
*/
|
|
13
|
+
async function loadRegistryModule() {
|
|
14
|
+
const registryUrl = new URL("/server/apis/index.ts", window.location.origin);
|
|
15
|
+
registryUrl.searchParams.set("t", String(Date.now()));
|
|
16
|
+
return (await import(
|
|
17
|
+
/* @vite-ignore */
|
|
18
|
+
registryUrl.href
|
|
19
|
+
)).default;
|
|
20
|
+
}
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/lib/internal-details/lib/utils/zod-to-typescript.ts
|
|
23
|
+
/**
|
|
24
|
+
* Zod schema conversion utilities.
|
|
25
|
+
*
|
|
26
|
+
* Converts Zod schemas to TypeScript type strings and JSON Schema for display in the UI.
|
|
27
|
+
*/
|
|
28
|
+
/**
|
|
29
|
+
* Convert a Zod schema to JSON Schema format.
|
|
30
|
+
*
|
|
31
|
+
* @param schema - The Zod schema to convert
|
|
32
|
+
* @returns JSON Schema representation
|
|
33
|
+
*/
|
|
34
|
+
function convertToJsonSchema(schema) {
|
|
35
|
+
try {
|
|
36
|
+
return zodToJsonSchema(schema, {
|
|
37
|
+
$refStrategy: "none",
|
|
38
|
+
errorMessages: false
|
|
39
|
+
});
|
|
40
|
+
} catch (error) {
|
|
41
|
+
console.warn("[zod-to-typescript] Failed to convert to JSON Schema:", error);
|
|
42
|
+
return { type: "unknown" };
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Convert a JSON Schema to TypeScript type string.
|
|
47
|
+
*
|
|
48
|
+
* @param schema - The JSON Schema to convert
|
|
49
|
+
* @param indent - Current indentation level
|
|
50
|
+
* @returns TypeScript type string representation
|
|
51
|
+
*/
|
|
52
|
+
function jsonSchemaToTypescript(schema, indent = 0) {
|
|
53
|
+
const indentStr = " ".repeat(indent);
|
|
54
|
+
const nextIndent = " ".repeat(indent + 1);
|
|
55
|
+
if (schema.$ref) return schema.$ref.split("/").pop() || "unknown";
|
|
56
|
+
if (schema.const !== void 0) return typeof schema.const === "string" ? `"${schema.const}"` : String(schema.const);
|
|
57
|
+
if (schema.enum) return schema.enum.map((v) => typeof v === "string" ? `"${v}"` : String(v)).join(" | ");
|
|
58
|
+
if (schema.anyOf) return schema.anyOf.map((s) => jsonSchemaToTypescript(s, indent)).join(" | ");
|
|
59
|
+
if (schema.oneOf) return schema.oneOf.map((s) => jsonSchemaToTypescript(s, indent)).join(" | ");
|
|
60
|
+
if (schema.allOf) return schema.allOf.map((s) => jsonSchemaToTypescript(s, indent)).join(" & ");
|
|
61
|
+
const nullable = schema.nullable ? " | null" : "";
|
|
62
|
+
switch (Array.isArray(schema.type) ? schema.type[0] : schema.type || "unknown") {
|
|
63
|
+
case "string": return "string" + nullable;
|
|
64
|
+
case "number":
|
|
65
|
+
case "integer": return "number" + nullable;
|
|
66
|
+
case "boolean": return "boolean" + nullable;
|
|
67
|
+
case "null": return "null";
|
|
68
|
+
case "array":
|
|
69
|
+
if (schema.items) {
|
|
70
|
+
if (Array.isArray(schema.items)) return `[${schema.items.map((s) => jsonSchemaToTypescript(s, indent)).join(", ")}]` + nullable;
|
|
71
|
+
const itemType = jsonSchemaToTypescript(schema.items, indent);
|
|
72
|
+
return (itemType.includes(" | ") || itemType.includes(" & ") ? `(${itemType})[]` : `${itemType}[]`) + nullable;
|
|
73
|
+
}
|
|
74
|
+
return "unknown[]" + nullable;
|
|
75
|
+
case "object": {
|
|
76
|
+
if (!schema.properties || Object.keys(schema.properties).length === 0) {
|
|
77
|
+
if (schema.additionalProperties) return `Record<string, ${typeof schema.additionalProperties === "object" ? jsonSchemaToTypescript(schema.additionalProperties, indent) : "unknown"}>` + nullable;
|
|
78
|
+
return "{}" + nullable;
|
|
79
|
+
}
|
|
80
|
+
const required = schema.required || [];
|
|
81
|
+
return `{\n${Object.entries(schema.properties).map(([key, propSchema]) => {
|
|
82
|
+
const isRequired = required.includes(key);
|
|
83
|
+
const propType = jsonSchemaToTypescript(propSchema, indent + 1);
|
|
84
|
+
return `${nextIndent}${key}${isRequired ? "" : "?"}: ${propType}`;
|
|
85
|
+
}).join(";\n")};\n${indentStr}}` + nullable;
|
|
86
|
+
}
|
|
87
|
+
default: return "unknown" + nullable;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Convert a Zod schema to both TypeScript string and JSON Schema.
|
|
92
|
+
*
|
|
93
|
+
* @param schema - The Zod schema to convert
|
|
94
|
+
* @returns Object containing both representations
|
|
95
|
+
*/
|
|
96
|
+
function convertZodSchema(schema) {
|
|
97
|
+
const jsonSchema = convertToJsonSchema(schema);
|
|
98
|
+
return {
|
|
99
|
+
typescript: jsonSchemaToTypescript(jsonSchema),
|
|
100
|
+
jsonSchema
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region src/lib/internal-details/lib/sdk-api-registry.ts
|
|
105
|
+
/**
|
|
106
|
+
* Set of registered API names to prevent duplicate registrations.
|
|
107
|
+
*/
|
|
108
|
+
const registeredApis = /* @__PURE__ */ new Set();
|
|
109
|
+
/**
|
|
110
|
+
* Extract metadata from a compiled API for display in the UI.
|
|
111
|
+
*
|
|
112
|
+
* @param name - The API name
|
|
113
|
+
* @param api - The compiled API
|
|
114
|
+
* @param sourceCode - Optional TypeScript source code
|
|
115
|
+
* @returns SdkApiMetadata for the API
|
|
116
|
+
*/
|
|
117
|
+
function extractSdkApiMetadata(name, api, sourceCode) {
|
|
118
|
+
const inputSchema = convertZodSchema(api.inputSchema);
|
|
119
|
+
const outputSchema = convertZodSchema(api.outputSchema);
|
|
120
|
+
const entryPoint = "entryPoint" in api ? api.entryPoint : void 0;
|
|
121
|
+
return {
|
|
122
|
+
name,
|
|
123
|
+
description: api.description,
|
|
124
|
+
inputSchema,
|
|
125
|
+
outputSchema,
|
|
126
|
+
isStreaming: false,
|
|
127
|
+
entryPoint,
|
|
128
|
+
exportName: root_store_default.getApiExportName(name),
|
|
129
|
+
integrations: (api.integrations ?? []).map((integration) => ({
|
|
130
|
+
key: integration.key,
|
|
131
|
+
pluginId: integration.pluginId,
|
|
132
|
+
name: integration.key,
|
|
133
|
+
id: integration.id
|
|
134
|
+
})),
|
|
135
|
+
sourceCode
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Register an SDK API and notify ui-code-mode.
|
|
140
|
+
*
|
|
141
|
+
* @param name - The API name
|
|
142
|
+
* @param api - The compiled API
|
|
143
|
+
* @param sourceCode - Optional TypeScript source code for display in the UI
|
|
144
|
+
* @returns true if the API was newly registered, false if already existed
|
|
145
|
+
*/
|
|
146
|
+
function registerSdkApi(name, api, sourceCode) {
|
|
147
|
+
const isNew = !registeredApis.has(name);
|
|
148
|
+
registeredApis.add(name);
|
|
149
|
+
sendMessageImmediately({
|
|
150
|
+
type: "sdk-api-registered",
|
|
151
|
+
payload: {
|
|
152
|
+
name,
|
|
153
|
+
metadata: extractSdkApiMetadata(name, api, sourceCode)
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
console.debug(`[sdk-api-registry] ${isNew ? "Registered" : "Updated"} SDK API: ${name}`);
|
|
157
|
+
return isNew;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Update the source code for an already-registered SDK API.
|
|
161
|
+
* This is called by the dev server when an API file changes.
|
|
162
|
+
*
|
|
163
|
+
* @param name - The API name
|
|
164
|
+
* @param sourceCode - The new TypeScript source code
|
|
165
|
+
*/
|
|
166
|
+
function updateSdkApiSourceCode(name, sourceCode) {
|
|
167
|
+
if (!registeredApis.has(name)) {
|
|
168
|
+
console.warn(`[sdk-api-registry] Cannot update source for unregistered API: ${name}`);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
sendMessageImmediately({
|
|
172
|
+
type: "sdk-api-source-updated",
|
|
173
|
+
payload: {
|
|
174
|
+
name,
|
|
175
|
+
sourceCode
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
console.debug(`[sdk-api-registry] Updated source code for SDK API: ${name}`);
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Clear all registered SDK APIs.
|
|
182
|
+
* Useful for testing or when the application reloads.
|
|
183
|
+
*/
|
|
184
|
+
function clearSdkApiRegistry() {
|
|
185
|
+
registeredApis.clear();
|
|
186
|
+
}
|
|
187
|
+
//#endregion
|
|
188
|
+
//#region src/lib/internal-details/lib/sdk-api-discovery.ts
|
|
189
|
+
/**
|
|
190
|
+
* SDK API Discovery Module.
|
|
191
|
+
*
|
|
192
|
+
* Discovers and registers all SDK APIs by importing the app's API registry
|
|
193
|
+
* at server/apis/index.ts. This enables SDK APIs to appear in the sidebar
|
|
194
|
+
* immediately, rather than waiting for them to be executed.
|
|
195
|
+
*/
|
|
196
|
+
var sdk_api_discovery_exports = /* @__PURE__ */ __exportAll({ discoverAndRegisterSdkApis: () => discoverAndRegisterSdkApis });
|
|
197
|
+
/** Joins concurrent HMR / execute-time rediscovery into one in-flight pass. */
|
|
198
|
+
let discoveryInFlight = null;
|
|
199
|
+
/**
|
|
200
|
+
* Set when discoverAndRegisterSdkApis is called while a pass is already
|
|
201
|
+
* running. After the current pass finishes we run again so a stale
|
|
202
|
+
* execute-time load cannot swallow a later HMR registry update.
|
|
203
|
+
*/
|
|
204
|
+
let discoveryDirty = false;
|
|
205
|
+
/**
|
|
206
|
+
* Discover and register all SDK APIs from the app's API registry.
|
|
207
|
+
*
|
|
208
|
+
* Imports server/apis/index.ts (the same registry used by useApi for type
|
|
209
|
+
* inference) and registers each exported API with the SDK API registry.
|
|
210
|
+
*
|
|
211
|
+
* Entry points are read from the `entryPoint` field on each CompiledApi,
|
|
212
|
+
* which is injected automatically by the sdkApiEntryPointPlugin Vite plugin.
|
|
213
|
+
*
|
|
214
|
+
* Last-known entryPoints/exportNames are kept until a full rediscovery pass
|
|
215
|
+
* is prepared, then swapped atomically so concurrent preview calls never see
|
|
216
|
+
* an empty map or entryPoints without their exportNames.
|
|
217
|
+
*/
|
|
218
|
+
function discoverAndRegisterSdkApis() {
|
|
219
|
+
if (!root_store_default.sdkApiEnabled) return Promise.resolve();
|
|
220
|
+
if (discoveryInFlight) {
|
|
221
|
+
discoveryDirty = true;
|
|
222
|
+
return discoveryInFlight;
|
|
223
|
+
}
|
|
224
|
+
discoveryInFlight = runDiscoveryLoop();
|
|
225
|
+
return discoveryInFlight;
|
|
226
|
+
}
|
|
227
|
+
async function runDiscoveryLoop() {
|
|
228
|
+
if (!root_store_default.hasUnresolvedGate()) root_store_default.initDiscoveryGate();
|
|
229
|
+
try {
|
|
230
|
+
do {
|
|
231
|
+
discoveryDirty = false;
|
|
232
|
+
await runDiscoveryPass();
|
|
233
|
+
} while (discoveryDirty);
|
|
234
|
+
} finally {
|
|
235
|
+
discoveryInFlight = null;
|
|
236
|
+
root_store_default.notifyDiscoveryComplete();
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
async function runDiscoveryPass() {
|
|
240
|
+
try {
|
|
241
|
+
const prepared = await prepareDiscoveredApis(await loadRegistryModule());
|
|
242
|
+
if (prepared.length === 0) {
|
|
243
|
+
console.debug("[sdk-api-discovery] No SDK APIs found in registry; keeping last-known registration");
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
clearSdkApiRegistry();
|
|
247
|
+
root_store_default.clearApiEntryPoints();
|
|
248
|
+
root_store_default.clearApiIntegrations();
|
|
249
|
+
console.debug(`[sdk-api-discovery] Discovering ${prepared.length} SDK APIs:`, prepared.map((api) => api.name));
|
|
250
|
+
for (const api of prepared) {
|
|
251
|
+
root_store_default.setApiEntryPoint(api.name, api.entryPoint);
|
|
252
|
+
if (api.exportName !== void 0) root_store_default.setApiExportName(api.name, api.exportName);
|
|
253
|
+
root_store_default.setApiIntegrations(api.name, api.integrations);
|
|
254
|
+
}
|
|
255
|
+
const results = await Promise.allSettled(prepared.map(async (api) => {
|
|
256
|
+
registerSdkApi(api.name, api.apiModule, api.source);
|
|
257
|
+
}));
|
|
258
|
+
const succeeded = results.filter((r) => r.status === "fulfilled").length;
|
|
259
|
+
const failed = results.filter((r) => r.status === "rejected").length;
|
|
260
|
+
console.debug(`[sdk-api-discovery] Registered ${succeeded} APIs, ${failed} failed`);
|
|
261
|
+
} catch (error) {
|
|
262
|
+
console.error("[sdk-api-discovery] Failed to discover SDK APIs:", error);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
async function prepareDiscoveredApis(apis) {
|
|
266
|
+
const apiNames = Object.keys(apis);
|
|
267
|
+
if (apiNames.length === 0) return [];
|
|
268
|
+
const entryPoints = apiNames.map((name) => {
|
|
269
|
+
const apiModule = apis[name];
|
|
270
|
+
const ep = apiModule && "entryPoint" in apiModule ? apiModule.entryPoint : void 0;
|
|
271
|
+
if (typeof ep !== "string") {
|
|
272
|
+
console.error(`[sdk-api-discovery] API "${name}" has no entryPoint. Was the Vite plugin applied?`);
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
return ep;
|
|
276
|
+
});
|
|
277
|
+
const sourcePromises = entryPoints.map(async (ep) => {
|
|
278
|
+
if (!ep) return void 0;
|
|
279
|
+
try {
|
|
280
|
+
const resp = await fetch(`/sb-raw-source/${ep}`);
|
|
281
|
+
return resp.ok ? await resp.text() : void 0;
|
|
282
|
+
} catch {
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
const sources = await Promise.all(sourcePromises);
|
|
287
|
+
const namedImportMap = await buildRegistryNamedImportMap();
|
|
288
|
+
const prepared = [];
|
|
289
|
+
for (let i = 0; i < apiNames.length; i++) {
|
|
290
|
+
const name = apiNames[i];
|
|
291
|
+
const apiModule = apis[name];
|
|
292
|
+
const entryPoint = entryPoints[i];
|
|
293
|
+
if (!apiModule || typeof entryPoint !== "string") continue;
|
|
294
|
+
const source = sources[i];
|
|
295
|
+
let exportName;
|
|
296
|
+
const namedExportName = namedImportMap.get(name);
|
|
297
|
+
if (namedExportName !== void 0) exportName = namedExportName;
|
|
298
|
+
else if (source && !/export\s+default\b/.test(source)) {
|
|
299
|
+
const namedExportPattern = /export\s+(?:const|let|var)\s+(\w+)\s*=/g;
|
|
300
|
+
let match;
|
|
301
|
+
const exportNames = [];
|
|
302
|
+
while ((match = namedExportPattern.exec(source)) !== null) if (match[1]) exportNames.push(match[1]);
|
|
303
|
+
if (exportNames.length === 1) exportName = exportNames[0];
|
|
304
|
+
else if (exportNames.length > 1) exportName = name;
|
|
305
|
+
}
|
|
306
|
+
prepared.push({
|
|
307
|
+
name,
|
|
308
|
+
apiModule,
|
|
309
|
+
entryPoint,
|
|
310
|
+
exportName,
|
|
311
|
+
integrations: getIntegrationDeclarations(apiModule),
|
|
312
|
+
source
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
return prepared;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Fetches `server/apis/index.ts` and builds a map of ALL named imports:
|
|
319
|
+
* `registryKey → originalExportName`.
|
|
320
|
+
*
|
|
321
|
+
* Given a registry line like:
|
|
322
|
+
* import { GetAllUsers as ListUsers, CreateOrder } from './users.js'
|
|
323
|
+
*
|
|
324
|
+
* The map will contain:
|
|
325
|
+
* ListUsers → GetAllUsers (aliased)
|
|
326
|
+
* CreateOrder → CreateOrder (non-aliased)
|
|
327
|
+
*
|
|
328
|
+
* Also handles mixed default+named imports:
|
|
329
|
+
* import Default, { GetOrders as ListOrders } from './orders.js'
|
|
330
|
+
* → ListOrders → GetOrders
|
|
331
|
+
*
|
|
332
|
+
* Default imports and type-only imports are excluded.
|
|
333
|
+
*/
|
|
334
|
+
async function buildRegistryNamedImportMap() {
|
|
335
|
+
const map = /* @__PURE__ */ new Map();
|
|
336
|
+
try {
|
|
337
|
+
const resp = await fetch("/sb-raw-source/server/apis/index.ts");
|
|
338
|
+
if (!resp.ok) return map;
|
|
339
|
+
const text = await resp.text();
|
|
340
|
+
const importBlockPattern = /import\s+(?:type\s+)?(?:\w+\s*,\s*)?\{([^}]+)\}\s*from\s*['"][^'"]+['"]/g;
|
|
341
|
+
let blockMatch;
|
|
342
|
+
while ((blockMatch = importBlockPattern.exec(text)) !== null) {
|
|
343
|
+
const fullStatement = blockMatch[0];
|
|
344
|
+
if (/^import\s+type\b/.test(fullStatement)) continue;
|
|
345
|
+
const specifiers = blockMatch[1].split(",");
|
|
346
|
+
for (const spec of specifiers) {
|
|
347
|
+
const trimmed = spec.trim();
|
|
348
|
+
if (!trimmed || /^type\s/.test(trimmed)) continue;
|
|
349
|
+
const parts = trimmed.split(/\s+as\s+/);
|
|
350
|
+
const originalName = parts[0].trim();
|
|
351
|
+
const localName = (parts[1] ?? originalName).trim();
|
|
352
|
+
if (/^\w+$/.test(originalName) && /^\w+$/.test(localName)) map.set(localName, originalName);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
} catch {}
|
|
356
|
+
return map;
|
|
357
|
+
}
|
|
358
|
+
if (import.meta.hot) import.meta.hot.accept("/server/apis/index.ts", () => {
|
|
359
|
+
if (!root_store_default.sdkApiEnabled) return;
|
|
360
|
+
console.debug("[sdk-api-discovery] API registry updated via HMR, re-running discovery");
|
|
361
|
+
discoverAndRegisterSdkApis();
|
|
362
|
+
});
|
|
363
|
+
//#endregion
|
|
364
|
+
export { sdk_api_discovery_exports as n, updateSdkApiSourceCode as r, discoverAndRegisterSdkApis as t };
|
|
365
|
+
|
|
366
|
+
//# sourceMappingURL=sdk-api-discovery-ekr6aG8h.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sdk-api-discovery-ekr6aG8h.js","names":["rootStore","rootStore"],"sources":["../src/lib/internal-details/lib/registry-loader.ts","../src/lib/internal-details/lib/utils/zod-to-typescript.ts","../src/lib/internal-details/lib/sdk-api-registry.ts","../src/lib/internal-details/lib/sdk-api-discovery.ts"],"sourcesContent":["/**\n * Registry module loader.\n *\n * Extracted from sdk-api-discovery.ts so that tests can mock the dynamic\n * import() call, which uses a runtime URL that vitest cannot intercept.\n */\n\nimport type { CompiledApi } from \"@superblocksteam/sdk-api\";\n\n/**\n * Dynamically import the SDK API registry module from the app origin.\n *\n * Uses a cache-busting parameter because the browser's ES module map\n * caches modules by URL — without it, subsequent import() calls return\n * the stale first-load module and newly created APIs are never discovered.\n */\nexport async function loadRegistryModule(): Promise<\n Record<string, CompiledApi>\n> {\n const registryUrl = new URL(\"/server/apis/index.ts\", window.location.origin);\n registryUrl.searchParams.set(\"t\", String(Date.now()));\n const mod = (await import(/* @vite-ignore */ registryUrl.href)) as {\n default: Record<string, CompiledApi>;\n };\n return mod.default;\n}\n","/**\n * Zod schema conversion utilities.\n *\n * Converts Zod schemas to TypeScript type strings and JSON Schema for display in the UI.\n */\n\nimport zodToJsonSchema from \"zod-to-json-schema\";\n\nimport type { z } from \"@superblocksteam/sdk-api\";\n\n/**\n * JSON Schema type definition (simplified).\n */\ntype JsonSchema = {\n type?: string | string[];\n properties?: Record<string, JsonSchema>;\n items?: JsonSchema | JsonSchema[];\n required?: string[];\n anyOf?: JsonSchema[];\n oneOf?: JsonSchema[];\n allOf?: JsonSchema[];\n const?: unknown;\n enum?: unknown[];\n format?: string;\n description?: string;\n $ref?: string;\n definitions?: Record<string, JsonSchema>;\n additionalProperties?: boolean | JsonSchema;\n nullable?: boolean;\n minimum?: number;\n maximum?: number;\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n};\n\n/**\n * Convert a Zod schema to JSON Schema format.\n *\n * @param schema - The Zod schema to convert\n * @returns JSON Schema representation\n */\nfunction convertToJsonSchema(schema: z.ZodType): object {\n try {\n // Use zod-to-json-schema to convert\n // Cast to any to avoid deep type instantiation issues\n const result = zodToJsonSchema(schema as any, {\n $refStrategy: \"none\",\n errorMessages: false,\n });\n return result as object;\n } catch (error) {\n console.warn(\n \"[zod-to-typescript] Failed to convert to JSON Schema:\",\n error,\n );\n return { type: \"unknown\" };\n }\n}\n\n/**\n * Convert a JSON Schema to TypeScript type string.\n *\n * @param schema - The JSON Schema to convert\n * @param indent - Current indentation level\n * @returns TypeScript type string representation\n */\nfunction jsonSchemaToTypescript(schema: JsonSchema, indent = 0): string {\n const indentStr = \" \".repeat(indent);\n const nextIndent = \" \".repeat(indent + 1);\n\n // Handle $ref (shouldn't happen with $refStrategy: \"none\", but just in case)\n if (schema.$ref) {\n const refName = schema.$ref.split(\"/\").pop() || \"unknown\";\n return refName;\n }\n\n // Handle const\n if (schema.const !== undefined) {\n return typeof schema.const === \"string\"\n ? `\"${schema.const}\"`\n : String(schema.const);\n }\n\n // Handle enum\n if (schema.enum) {\n return schema.enum\n .map((v) => (typeof v === \"string\" ? `\"${v}\"` : String(v)))\n .join(\" | \");\n }\n\n // Handle anyOf/oneOf/allOf\n if (schema.anyOf) {\n return schema.anyOf\n .map((s) => jsonSchemaToTypescript(s, indent))\n .join(\" | \");\n }\n if (schema.oneOf) {\n return schema.oneOf\n .map((s) => jsonSchemaToTypescript(s, indent))\n .join(\" | \");\n }\n if (schema.allOf) {\n return schema.allOf\n .map((s) => jsonSchemaToTypescript(s, indent))\n .join(\" & \");\n }\n\n // Handle nullable\n const nullable = schema.nullable ? \" | null\" : \"\";\n\n // Handle by type\n const type = Array.isArray(schema.type)\n ? schema.type[0]\n : schema.type || \"unknown\";\n\n switch (type) {\n case \"string\":\n return \"string\" + nullable;\n\n case \"number\":\n case \"integer\":\n return \"number\" + nullable;\n\n case \"boolean\":\n return \"boolean\" + nullable;\n\n case \"null\":\n return \"null\";\n\n case \"array\": {\n if (schema.items) {\n if (Array.isArray(schema.items)) {\n // Tuple type: [string, number]\n const tupleTypes = schema.items\n .map((s) => jsonSchemaToTypescript(s, indent))\n .join(\", \");\n return `[${tupleTypes}]` + nullable;\n }\n const itemType = jsonSchemaToTypescript(schema.items, indent);\n const needsParens =\n itemType.includes(\" | \") || itemType.includes(\" & \");\n return (needsParens ? `(${itemType})[]` : `${itemType}[]`) + nullable;\n }\n return \"unknown[]\" + nullable;\n }\n\n case \"object\": {\n if (!schema.properties || Object.keys(schema.properties).length === 0) {\n if (schema.additionalProperties) {\n const valueType =\n typeof schema.additionalProperties === \"object\"\n ? jsonSchemaToTypescript(schema.additionalProperties, indent)\n : \"unknown\";\n return `Record<string, ${valueType}>` + nullable;\n }\n // Empty object type\n return \"{}\" + nullable;\n }\n\n const required = schema.required || [];\n const properties = Object.entries(schema.properties)\n .map(([key, propSchema]) => {\n const isRequired = required.includes(key);\n const propType = jsonSchemaToTypescript(propSchema, indent + 1);\n const optionalMark = isRequired ? \"\" : \"?\";\n return `${nextIndent}${key}${optionalMark}: ${propType}`;\n })\n .join(\";\\n\");\n\n return `{\\n${properties};\\n${indentStr}}` + nullable;\n }\n\n default:\n return \"unknown\" + nullable;\n }\n}\n\n/**\n * Convert a Zod schema to both TypeScript string and JSON Schema.\n *\n * @param schema - The Zod schema to convert\n * @returns Object containing both representations\n */\nexport function convertZodSchema(schema: z.ZodType): {\n typescript: string;\n jsonSchema: object;\n} {\n const jsonSchema = convertToJsonSchema(schema);\n const typescript = jsonSchemaToTypescript(jsonSchema as JsonSchema);\n return { typescript, jsonSchema };\n}\n","/**\n * SDK API Registry for the library iframe.\n *\n * Tracks registered SDK APIs and notifies ui-code-mode when APIs are\n * registered (for display in the sidebar).\n */\n\nimport type { CompiledApi } from \"@superblocksteam/sdk-api\";\n\nimport { sendMessageImmediately } from \"./iframe.js\";\nimport rootStore from \"./root-store.js\";\nimport type { SdkApiMetadata } from \"./types.js\";\nimport { convertZodSchema } from \"./utils/zod-to-typescript.js\";\n\n/**\n * Set of registered API names to prevent duplicate registrations.\n */\nconst registeredApis = new Set<string>();\n\n/**\n * Extract metadata from a compiled API for display in the UI.\n *\n * @param name - The API name\n * @param api - The compiled API\n * @param sourceCode - Optional TypeScript source code\n * @returns SdkApiMetadata for the API\n */\nfunction extractSdkApiMetadata(\n name: string,\n api: CompiledApi,\n sourceCode?: string,\n): SdkApiMetadata {\n // Convert input schema\n const inputSchema = convertZodSchema(api.inputSchema);\n\n // Convert output schema\n const outputSchema = convertZodSchema(api.outputSchema);\n\n const entryPoint =\n \"entryPoint\" in api ? (api.entryPoint as string | undefined) : undefined;\n\n return {\n name,\n description: api.description,\n inputSchema,\n outputSchema,\n isStreaming: false,\n entryPoint,\n exportName: rootStore.getApiExportName(name),\n // IntegrationDeclaration only has key, pluginId, and id\n // The display name will be resolved by ui-code-mode using the id\n integrations: (api.integrations ?? []).map((integration) => ({\n key: integration.key,\n pluginId: integration.pluginId,\n // Name is resolved by ui-code-mode from the datasource by id\n name: integration.key,\n id: integration.id,\n })),\n sourceCode,\n };\n}\n\n/**\n * Register an SDK API and notify ui-code-mode.\n *\n * @param name - The API name\n * @param api - The compiled API\n * @param sourceCode - Optional TypeScript source code for display in the UI\n * @returns true if the API was newly registered, false if already existed\n */\nexport function registerSdkApi(\n name: string,\n api: CompiledApi,\n sourceCode?: string,\n): boolean {\n const isNew = !registeredApis.has(name);\n\n registeredApis.add(name);\n\n const metadata = extractSdkApiMetadata(name, api, sourceCode);\n\n // Send registration message to ui-code-mode\n // This also serves as an update if the API already exists\n sendMessageImmediately({\n type: \"sdk-api-registered\",\n payload: {\n name,\n metadata,\n },\n });\n\n console.debug(\n `[sdk-api-registry] ${isNew ? \"Registered\" : \"Updated\"} SDK API: ${name}`,\n );\n return isNew;\n}\n\n/**\n * Update the source code for an already-registered SDK API.\n * This is called by the dev server when an API file changes.\n *\n * @param name - The API name\n * @param sourceCode - The new TypeScript source code\n */\nexport function updateSdkApiSourceCode(name: string, sourceCode: string): void {\n if (!registeredApis.has(name)) {\n console.warn(\n `[sdk-api-registry] Cannot update source for unregistered API: ${name}`,\n );\n return;\n }\n\n // Send source code update message to ui-code-mode\n sendMessageImmediately({\n type: \"sdk-api-source-updated\",\n payload: {\n name,\n sourceCode,\n },\n });\n\n console.debug(`[sdk-api-registry] Updated source code for SDK API: ${name}`);\n}\n\n/**\n * Clear all registered SDK APIs.\n * Useful for testing or when the application reloads.\n */\nexport function clearSdkApiRegistry(): void {\n registeredApis.clear();\n}\n","/**\n * SDK API Discovery Module.\n *\n * Discovers and registers all SDK APIs by importing the app's API registry\n * at server/apis/index.ts. This enables SDK APIs to appear in the sidebar\n * immediately, rather than waiting for them to be executed.\n */\n\nimport {\n getIntegrationDeclarations,\n type CompiledApi,\n type IntegrationDeclaration,\n} from \"@superblocksteam/sdk-api\";\n\nimport { loadRegistryModule } from \"./registry-loader.js\";\nimport rootStore from \"./root-store.js\";\nimport { registerSdkApi, clearSdkApiRegistry } from \"./sdk-api-registry.js\";\n\n// Maps registry key → original export name for ALL named imports.\n// Aliased: `import { GetAllUsers as ListUsers }` → ListUsers → GetAllUsers\n// Non-aliased: `import { CreateOrder }` → CreateOrder → CreateOrder\ntype RegistryNamedImportMap = Map<string, string>;\n\ntype PreparedApi = {\n name: string;\n apiModule: CompiledApi;\n entryPoint: string;\n exportName?: string;\n integrations: IntegrationDeclaration[];\n source?: string;\n};\n\n/** Joins concurrent HMR / execute-time rediscovery into one in-flight pass. */\nlet discoveryInFlight: Promise<void> | null = null;\n/**\n * Set when discoverAndRegisterSdkApis is called while a pass is already\n * running. After the current pass finishes we run again so a stale\n * execute-time load cannot swallow a later HMR registry update.\n */\nlet discoveryDirty = false;\n\n/**\n * Discover and register all SDK APIs from the app's API registry.\n *\n * Imports server/apis/index.ts (the same registry used by useApi for type\n * inference) and registers each exported API with the SDK API registry.\n *\n * Entry points are read from the `entryPoint` field on each CompiledApi,\n * which is injected automatically by the sdkApiEntryPointPlugin Vite plugin.\n *\n * Last-known entryPoints/exportNames are kept until a full rediscovery pass\n * is prepared, then swapped atomically so concurrent preview calls never see\n * an empty map or entryPoints without their exportNames.\n */\nexport function discoverAndRegisterSdkApis(): Promise<void> {\n if (!rootStore.sdkApiEnabled) return Promise.resolve();\n if (discoveryInFlight) {\n discoveryDirty = true;\n return discoveryInFlight;\n }\n\n // Clear inFlight inside runDiscoveryLoop's finally (same async turn as loop\n // exit) — not a chained .finally — so callers cannot set discoveryDirty on\n // a flight that has already exited the dirty loop.\n discoveryInFlight = runDiscoveryLoop();\n return discoveryInFlight;\n}\n\n/** Test-only: reset module-level single-flight state. */\nexport function resetSdkApiDiscoveryStateForTests(): void {\n discoveryInFlight = null;\n discoveryDirty = false;\n}\n\nasync function runDiscoveryLoop(): Promise<void> {\n // setSdkApiEnabled(true) pre-initializes the gate immediately to prevent the\n // race where a child component's useEffect calls executeSdkApiV3 before\n // IframeConnected's parent useEffect has had a chance to run this function.\n // Only call initDiscoveryGate() if no pending gate exists (HMR re-discovery\n // or a call path that bypassed setSdkApiEnabled).\n if (!rootStore.hasUnresolvedGate()) {\n rootStore.initDiscoveryGate();\n }\n\n try {\n do {\n discoveryDirty = false;\n await runDiscoveryPass();\n } while (discoveryDirty);\n } finally {\n // Clear before notify so a caller racing after loop exit starts a fresh\n // flight instead of setting dirty on a finished one.\n discoveryInFlight = null;\n rootStore.notifyDiscoveryComplete();\n }\n}\n\nasync function runDiscoveryPass(): Promise<void> {\n try {\n const apis = await loadRegistryModule();\n const prepared = await prepareDiscoveredApis(apis);\n\n // Empty prepare can be a stale mid-HMR load (empty registry or every API\n // missing entryPoint). Keep last-known maps so concurrent executes and\n // dirty follow-up passes are not blanked.\n if (prepared.length === 0) {\n console.debug(\n \"[sdk-api-discovery] No SDK APIs found in registry; keeping last-known registration\",\n );\n return;\n }\n\n // Atomic replace: last-known maps stay live through prepare() awaits, then\n // swap entryPoints + exportNames + integrations together before register.\n // clearApiEntryPoints() also clears apiExportNames, so named→default\n // correctly drops a stale exportName when exportName is undefined.\n clearSdkApiRegistry();\n rootStore.clearApiEntryPoints();\n rootStore.clearApiIntegrations();\n\n console.debug(\n `[sdk-api-discovery] Discovering ${prepared.length} SDK APIs:`,\n prepared.map((api) => api.name),\n );\n\n for (const api of prepared) {\n rootStore.setApiEntryPoint(api.name, api.entryPoint);\n if (api.exportName !== undefined) {\n rootStore.setApiExportName(api.name, api.exportName);\n }\n rootStore.setApiIntegrations(api.name, api.integrations);\n }\n\n const results = await Promise.allSettled(\n prepared.map(async (api) => {\n registerSdkApi(api.name, api.apiModule, api.source);\n }),\n );\n\n const succeeded = results.filter((r) => r.status === \"fulfilled\").length;\n const failed = results.filter((r) => r.status === \"rejected\").length;\n\n console.debug(\n `[sdk-api-discovery] Registered ${succeeded} APIs, ${failed} failed`,\n );\n } catch (error) {\n // Keep last-known entryPoints / registry so a failed rediscovery does not\n // blank out APIs that were already working. Resolve (do not rethrow) so\n // awaitDiscovery / execute waiters are never stuck.\n console.error(\"[sdk-api-discovery] Failed to discover SDK APIs:\", error);\n }\n}\n\nasync function prepareDiscoveredApis(\n apis: Record<string, CompiledApi>,\n): Promise<PreparedApi[]> {\n const apiNames = Object.keys(apis);\n if (apiNames.length === 0) {\n return [];\n }\n\n const entryPoints = apiNames.map((name) => {\n const apiModule = apis[name];\n const ep =\n apiModule && \"entryPoint\" in apiModule\n ? (apiModule.entryPoint as string | undefined)\n : undefined;\n if (typeof ep !== \"string\") {\n console.error(\n `[sdk-api-discovery] API \"${name}\" has no entryPoint. Was the Vite plugin applied?`,\n );\n return undefined;\n }\n return ep;\n });\n\n const sourcePromises = entryPoints.map(async (ep) => {\n if (!ep) return undefined;\n try {\n const resp = await fetch(`/sb-raw-source/${ep}`);\n return resp.ok ? await resp.text() : undefined;\n } catch {\n return undefined;\n }\n });\n const sources = await Promise.all(sourcePromises);\n const namedImportMap = await buildRegistryNamedImportMap();\n\n const prepared: PreparedApi[] = [];\n for (let i = 0; i < apiNames.length; i++) {\n const name = apiNames[i]!;\n const apiModule = apis[name];\n const entryPoint = entryPoints[i];\n // Intentionally skip APIs without a valid entryPoint rather than partially\n // registering them. Without an entryPoint, executeSdkApiV3 cannot call the\n // orchestrator; registering would only create a false \"available\" signal.\n if (!apiModule || typeof entryPoint !== \"string\") {\n continue;\n }\n\n const source = sources[i];\n let exportName: string | undefined;\n const namedExportName = namedImportMap.get(name);\n if (namedExportName !== undefined) {\n exportName = namedExportName;\n } else if (source && !/export\\s+default\\b/.test(source)) {\n // No default export and not a named import — detect the named export\n // variable name from the source file.\n const namedExportPattern = /export\\s+(?:const|let|var)\\s+(\\w+)\\s*=/g;\n let match;\n const exportNames: string[] = [];\n while ((match = namedExportPattern.exec(source)) !== null) {\n if (match[1]) exportNames.push(match[1]);\n }\n if (exportNames.length === 1) {\n exportName = exportNames[0];\n } else if (exportNames.length > 1) {\n exportName = name;\n }\n }\n\n prepared.push({\n name,\n apiModule,\n entryPoint,\n exportName,\n integrations: getIntegrationDeclarations(apiModule),\n source,\n });\n }\n\n return prepared;\n}\n\n/**\n * Fetches `server/apis/index.ts` and builds a map of ALL named imports:\n * `registryKey → originalExportName`.\n *\n * Given a registry line like:\n * import { GetAllUsers as ListUsers, CreateOrder } from './users.js'\n *\n * The map will contain:\n * ListUsers → GetAllUsers (aliased)\n * CreateOrder → CreateOrder (non-aliased)\n *\n * Also handles mixed default+named imports:\n * import Default, { GetOrders as ListOrders } from './orders.js'\n * → ListOrders → GetOrders\n *\n * Default imports and type-only imports are excluded.\n */\nasync function buildRegistryNamedImportMap(): Promise<RegistryNamedImportMap> {\n const map: RegistryNamedImportMap = new Map();\n try {\n const resp = await fetch(\"/sb-raw-source/server/apis/index.ts\");\n if (!resp.ok) return map;\n const text = await resp.text();\n\n // Match import statements containing `{ ... }`, including mixed syntax\n // like `import Default, { A, B as C } from '...'`.\n const importBlockPattern =\n /import\\s+(?:type\\s+)?(?:\\w+\\s*,\\s*)?\\{([^}]+)\\}\\s*from\\s*['\"][^'\"]+['\"]/g;\n let blockMatch: RegExpExecArray | null;\n\n while ((blockMatch = importBlockPattern.exec(text)) !== null) {\n const fullStatement = blockMatch[0]!;\n if (/^import\\s+type\\b/.test(fullStatement)) continue;\n\n const specifiers = blockMatch[1]!.split(\",\");\n for (const spec of specifiers) {\n const trimmed = spec.trim();\n if (!trimmed || /^type\\s/.test(trimmed)) continue;\n const parts = trimmed.split(/\\s+as\\s+/);\n const originalName = parts[0]!.trim();\n const localName = (parts[1] ?? originalName).trim();\n if (/^\\w+$/.test(originalName) && /^\\w+$/.test(localName)) {\n map.set(localName, originalName);\n }\n }\n }\n } catch {\n // Registry fetch failed — return empty map; named export detection\n // will fall back to the source-based heuristic.\n }\n return map;\n}\n\n// Set up HMR to re-run discovery when the registry changes.\n// The sdkApiEnabled flag is checked inside the callback (not at registration\n// time) because the flag is only set to true later during bootstrap.\n// Do not clear entryPoints here — runDiscoveryPass replaces them only after\n// a full prepare() completes successfully.\nif (import.meta.hot) {\n import.meta.hot.accept(\"/server/apis/index.ts\", () => {\n if (!rootStore.sdkApiEnabled) return;\n console.debug(\n \"[sdk-api-discovery] API registry updated via HMR, re-running discovery\",\n );\n void discoverAndRegisterSdkApis();\n });\n}\n"],"mappings":";;;;;;;;;;;;AAgBA,eAAsB,qBAEpB;CACA,MAAM,cAAc,IAAI,IAAI,yBAAyB,OAAO,SAAS,OAAO;AAC5E,aAAY,aAAa,IAAI,KAAK,OAAO,KAAK,KAAK,CAAC,CAAC;AAIrD,SAAO,MAHY;;EAA0B,YAAY;GAG9C;;;;;;;;;;;;;;;ACkBb,SAAS,oBAAoB,QAA2B;AACtD,KAAI;AAOF,SAJe,gBAAgB,QAAe;GAC5C,cAAc;GACd,eAAe;GAChB,CACY;UACN,OAAO;AACd,UAAQ,KACN,yDACA,MACD;AACD,SAAO,EAAE,MAAM,WAAW;;;;;;;;;;AAW9B,SAAS,uBAAuB,QAAoB,SAAS,GAAW;CACtE,MAAM,YAAY,KAAK,OAAO,OAAO;CACrC,MAAM,aAAa,KAAK,OAAO,SAAS,EAAE;AAG1C,KAAI,OAAO,KAET,QADgB,OAAO,KAAK,MAAM,IAAI,CAAC,KAAK,IAAI;AAKlD,KAAI,OAAO,UAAU,KAAA,EACnB,QAAO,OAAO,OAAO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-1,3 +1,4 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-CiIaOW0V.js";
|
|
1
2
|
import { trace } from "@opentelemetry/api";
|
|
2
3
|
import { CompositePropagator, W3CBaggagePropagator, W3CTraceContextPropagator } from "@opentelemetry/core";
|
|
3
4
|
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
|
|
@@ -5,18 +6,6 @@ import { resourceFromAttributes } from "@opentelemetry/resources";
|
|
|
5
6
|
import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
|
|
6
7
|
import { WebTracerProvider } from "@opentelemetry/sdk-trace-web";
|
|
7
8
|
import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
|
|
8
|
-
//#region \0rolldown/runtime.js
|
|
9
|
-
var __defProp = Object.defineProperty;
|
|
10
|
-
var __exportAll = (all, no_symbols) => {
|
|
11
|
-
let target = {};
|
|
12
|
-
for (var name in all) __defProp(target, name, {
|
|
13
|
-
get: all[name],
|
|
14
|
-
enumerable: true
|
|
15
|
-
});
|
|
16
|
-
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
17
|
-
return target;
|
|
18
|
-
};
|
|
19
|
-
//#endregion
|
|
20
9
|
//#region src/lib/utils.ts
|
|
21
10
|
var utils_exports = /* @__PURE__ */ __exportAll({
|
|
22
11
|
getTracer: () => getTracer,
|
|
@@ -58,4 +47,4 @@ function getTracer(name) {
|
|
|
58
47
|
//#endregion
|
|
59
48
|
export { initTracerProviderWithOrigin as n, utils_exports as r, getTracer as t };
|
|
60
49
|
|
|
61
|
-
//# sourceMappingURL=utils-
|
|
50
|
+
//# sourceMappingURL=utils-kXteBlMZ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils-
|
|
1
|
+
{"version":3,"file":"utils-kXteBlMZ.js","names":[],"sources":["../src/lib/utils.ts"],"sourcesContent":["import { trace } from \"@opentelemetry/api\";\nimport {\n CompositePropagator,\n W3CBaggagePropagator,\n W3CTraceContextPropagator,\n} from \"@opentelemetry/core\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport { resourceFromAttributes } from \"@opentelemetry/resources\";\nimport { BatchSpanProcessor } from \"@opentelemetry/sdk-trace-base\";\nimport { WebTracerProvider } from \"@opentelemetry/sdk-trace-web\";\nimport { ATTR_SERVICE_NAME } from \"@opentelemetry/semantic-conventions\";\n\nconst serviceName = \"superblocks-ui-framework\";\n\nlet otlpEndpoint: string | undefined = undefined;\nconst otlpPath = \"/api/v1/traces\";\n\nlet currentProvider: WebTracerProvider | undefined;\nconst ATTR_DEPLOYMENT_ENVIRONMENT = \"deployment.environment\";\n\nexport function initTracerProviderWithOrigin(windowOriginUrl: string) {\n otlpEndpoint = windowOriginUrl + otlpPath;\n\n console.debug(\n \"Initializing direct OTLP tracer provider for iframe to:\",\n otlpEndpoint,\n );\n\n const provider = new WebTracerProvider({\n resource: resourceFromAttributes({\n [ATTR_SERVICE_NAME]: serviceName,\n [ATTR_DEPLOYMENT_ENVIRONMENT]: getEnvironmentFromHostname(otlpEndpoint),\n }),\n spanProcessors: [\n new BatchSpanProcessor(\n new OTLPTraceExporter({\n url: otlpEndpoint,\n }),\n ),\n ],\n });\n\n provider.register({\n propagator: new CompositePropagator({\n propagators: [\n new W3CBaggagePropagator(),\n new W3CTraceContextPropagator(),\n ],\n }),\n });\n\n currentProvider = provider;\n console.debug(\n \"Direct OTLP tracing initialized for iframe with dynamic origin\",\n );\n\n return provider;\n}\n\n// TODO: move this to a shared location since it's used by CLI as well\nfunction getEnvironmentFromHostname(hostname: string): string {\n if (hostname.match(/^app\\.superblocks(?:hq)?\\.com/)) {\n return \"prod\";\n } else if (hostname.match(/^eu\\.superblocks(?:hq)?\\.com/)) {\n return \"prod-eu\";\n } else if (hostname.match(/^staging\\.superblocks(?:hq)?\\.com/)) {\n return \"staging\";\n } else if (hostname.match(/^dev\\.superblocks(?:hq)?\\.com/)) {\n return \"dev\";\n } else if (hostname.match(/^pr-[0-9]+\\.superblocks(?:hq)?\\.dev/)) {\n return \"ephemeral\";\n } else if (hostname.match(/^localhost/)) {\n return \"local\";\n } else {\n return \"other\";\n }\n}\n\nexport function getTracer(name?: string) {\n if (!currentProvider) {\n console.error(\n \"Tracer provider not initialized. Call initTracerProviderWithOrigin() first with a valid windowOriginUrl. Tracing will be disabled.\",\n );\n }\n return trace.getTracer(name || serviceName);\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAM,cAAc;AAEpB,IAAI,eAAmC,KAAA;AACvC,MAAM,WAAW;AAEjB,IAAI;AACJ,MAAM,8BAA8B;AAEpC,SAAgB,6BAA6B,iBAAyB;AACpE,gBAAe,kBAAkB;AAEjC,SAAQ,MACN,2DACA,aACD;CAED,MAAM,WAAW,IAAI,kBAAkB;EACrC,UAAU,uBAAuB;IAC9B,oBAAoB;IACpB,8BAA8B,2BAA2B,aAAa;GACxE,CAAC;EACF,gBAAgB,CACd,IAAI,mBACF,IAAI,kBAAkB,EACpB,KAAK,cACN,CAAC,CACH,CACF;EACF,CAAC;AAEF,UAAS,SAAS,EAChB,YAAY,IAAI,oBAAoB,EAClC,aAAa,CACX,IAAI,sBAAsB,EAC1B,IAAI,2BAA2B,CAChC,EACF,CAAC,EACH,CAAC;AAEF,mBAAkB;AAClB,SAAQ,MACN,iEACD;AAED,QAAO;;AAIT,SAAS,2BAA2B,UAA0B;AAC5D,KAAI,SAAS,MAAM,gCAAgC,CACjD,QAAO;UACE,SAAS,MAAM,+BAA+B,CACvD,QAAO;UACE,SAAS,MAAM,oCAAoC,CAC5D,QAAO;UACE,SAAS,MAAM,gCAAgC,CACxD,QAAO;UACE,SAAS,MAAM,sCAAsC,CAC9D,QAAO;UACE,SAAS,MAAM,aAAa,CACrC,QAAO;KAEP,QAAO;;AAIX,SAAgB,UAAU,MAAe;AACvC,KAAI,CAAC,gBACH,SAAQ,MACN,qIACD;AAEH,QAAO,MAAM,UAAU,QAAQ,YAAY"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@superblocksteam/library",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.150-next.0",
|
|
4
4
|
"license": "Superblocks Community Software License",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist"
|
|
@@ -64,9 +64,9 @@
|
|
|
64
64
|
"swr": "2.4.1",
|
|
65
65
|
"tailwindcss": "^4.1.13",
|
|
66
66
|
"zod-to-json-schema": "^3.25.1",
|
|
67
|
-
"@superblocksteam/
|
|
68
|
-
"@superblocksteam/
|
|
69
|
-
"@superblocksteam/shared": "0.
|
|
67
|
+
"@superblocksteam/library-shared": "2.0.150-next.0",
|
|
68
|
+
"@superblocksteam/sdk-api": "2.0.150-next.0",
|
|
69
|
+
"@superblocksteam/shared": "0.9604.0"
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
72
|
"@eslint/js": "^9.39.2",
|