@lucern/sdk 0.3.0-alpha.2 → 0.3.0-alpha.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 (168) hide show
  1. package/dist/adminClient.d.ts +2 -0
  2. package/dist/adminClient.js +195 -3
  3. package/dist/adminClient.js.map +1 -1
  4. package/dist/answersClient.d.ts +2 -0
  5. package/dist/answersClient.js +195 -3
  6. package/dist/answersClient.js.map +1 -1
  7. package/dist/audiencesClient.d.ts +2 -0
  8. package/dist/audiencesClient.js +195 -3
  9. package/dist/audiencesClient.js.map +1 -1
  10. package/dist/auditClient.d.ts +2 -0
  11. package/dist/auditClient.js +197 -5
  12. package/dist/auditClient.js.map +1 -1
  13. package/dist/authContext.d.ts +56 -0
  14. package/dist/authContext.js +170 -0
  15. package/dist/authContext.js.map +1 -0
  16. package/dist/authDeviceClient.d.ts +49 -0
  17. package/dist/authDeviceClient.js +108 -0
  18. package/dist/authDeviceClient.js.map +1 -0
  19. package/dist/beliefs/index.d.ts +19 -2
  20. package/dist/beliefs/index.js +2648 -327
  21. package/dist/beliefs/index.js.map +1 -1
  22. package/dist/beliefsClient.d.ts +2 -0
  23. package/dist/beliefsClient.js +199 -7
  24. package/dist/beliefsClient.js.map +1 -1
  25. package/dist/boundaryClientSurface.d.ts +20 -0
  26. package/dist/boundaryClientSurface.js +66 -0
  27. package/dist/boundaryClientSurface.js.map +1 -0
  28. package/dist/{client-B6aWUUwp.d.ts → client-DOLqClbU.d.ts} +548 -9
  29. package/dist/client.d.ts +20 -3
  30. package/dist/client.js +2648 -327
  31. package/dist/client.js.map +1 -1
  32. package/dist/contextClient.d.ts +2 -0
  33. package/dist/contextClient.js +201 -9
  34. package/dist/contextClient.js.map +1 -1
  35. package/dist/contracts/api-enums.contract.d.ts +1 -1
  36. package/dist/contracts/api-enums.contract.js.map +1 -1
  37. package/dist/contracts/index.d.ts +1 -0
  38. package/dist/contracts/index.js +104 -1
  39. package/dist/contracts/index.js.map +1 -1
  40. package/dist/contracts/mcpTools.d.ts +46 -1
  41. package/dist/contracts/mcpTools.js +102 -0
  42. package/dist/contracts/mcpTools.js.map +1 -1
  43. package/dist/contradictions/index.d.ts +19 -2
  44. package/dist/contradictions/index.js +2648 -327
  45. package/dist/contradictions/index.js.map +1 -1
  46. package/dist/coreClient.d.ts +9 -0
  47. package/dist/coreClient.js +195 -3
  48. package/dist/coreClient.js.map +1 -1
  49. package/dist/decisions/index.d.ts +19 -2
  50. package/dist/decisions/index.js +2648 -327
  51. package/dist/decisions/index.js.map +1 -1
  52. package/dist/decisionsClient.d.ts +2 -0
  53. package/dist/decisionsClient.js +198 -6
  54. package/dist/decisionsClient.js.map +1 -1
  55. package/dist/edges/index.d.ts +19 -2
  56. package/dist/edges/index.js +2648 -327
  57. package/dist/edges/index.js.map +1 -1
  58. package/dist/embeddingsClient.d.ts +106 -0
  59. package/dist/embeddingsClient.js +708 -0
  60. package/dist/embeddingsClient.js.map +1 -0
  61. package/dist/eventingClient.d.ts +96 -0
  62. package/dist/eventingClient.js +705 -0
  63. package/dist/eventingClient.js.map +1 -0
  64. package/dist/eventsCore.d.ts +2 -0
  65. package/dist/eventsCore.js +195 -3
  66. package/dist/eventsCore.js.map +1 -1
  67. package/dist/evidence/index.d.ts +19 -2
  68. package/dist/evidence/index.js +2648 -327
  69. package/dist/evidence/index.js.map +1 -1
  70. package/dist/evidenceClient.d.ts +2 -0
  71. package/dist/evidenceClient.js +195 -3
  72. package/dist/evidenceClient.js.map +1 -1
  73. package/dist/gatewayFacades.d.ts +38 -3
  74. package/dist/gatewayFacades.js +371 -12
  75. package/dist/gatewayFacades.js.map +1 -1
  76. package/dist/graphAnalysisClient.d.ts +147 -0
  77. package/dist/graphAnalysisClient.js +756 -0
  78. package/dist/graphAnalysisClient.js.map +1 -0
  79. package/dist/graphClient.d.ts +2 -0
  80. package/dist/graphClient.js +202 -10
  81. package/dist/graphClient.js.map +1 -1
  82. package/dist/graphRecommendationsClient.d.ts +56 -0
  83. package/dist/graphRecommendationsClient.js +646 -0
  84. package/dist/graphRecommendationsClient.js.map +1 -0
  85. package/dist/graphStateClassifierClient.d.ts +73 -0
  86. package/dist/graphStateClassifierClient.js +694 -0
  87. package/dist/graphStateClassifierClient.js.map +1 -0
  88. package/dist/harnessClient.d.ts +2 -0
  89. package/dist/harnessClient.js +197 -5
  90. package/dist/harnessClient.js.map +1 -1
  91. package/dist/identityClient.d.ts +89 -3
  92. package/dist/identityClient.js +363 -4
  93. package/dist/identityClient.js.map +1 -1
  94. package/dist/index.d.ts +23 -4
  95. package/dist/index.js +3098 -353
  96. package/dist/index.js.map +1 -1
  97. package/dist/infisicalRuntime.d.ts +42 -0
  98. package/dist/infisicalRuntime.js +291 -0
  99. package/dist/infisicalRuntime.js.map +1 -0
  100. package/dist/jobsClient.d.ts +98 -0
  101. package/dist/jobsClient.js +704 -0
  102. package/dist/jobsClient.js.map +1 -0
  103. package/dist/learningClient.d.ts +2 -0
  104. package/dist/learningClient.js +197 -5
  105. package/dist/learningClient.js.map +1 -1
  106. package/dist/lenses/index.d.ts +43 -2
  107. package/dist/lenses/index.js +2648 -327
  108. package/dist/lenses/index.js.map +1 -1
  109. package/dist/mcpClient.d.ts +28 -0
  110. package/dist/mcpClient.js +650 -0
  111. package/dist/mcpClient.js.map +1 -0
  112. package/dist/modelRuntimeClient.d.ts +72 -0
  113. package/dist/modelRuntimeClient.js +681 -0
  114. package/dist/modelRuntimeClient.js.map +1 -0
  115. package/dist/nodes/index.d.ts +37 -2
  116. package/dist/nodes/index.js +2648 -327
  117. package/dist/nodes/index.js.map +1 -1
  118. package/dist/ontologies/index.d.ts +19 -2
  119. package/dist/ontologies/index.js +2648 -327
  120. package/dist/ontologies/index.js.map +1 -1
  121. package/dist/ontologyClient.d.ts +2 -0
  122. package/dist/ontologyClient.js +195 -3
  123. package/dist/ontologyClient.js.map +1 -1
  124. package/dist/ontologyLinksClient.d.ts +71 -0
  125. package/dist/ontologyLinksClient.js +675 -0
  126. package/dist/ontologyLinksClient.js.map +1 -0
  127. package/dist/orgGraphSearchClient.d.ts +85 -0
  128. package/dist/orgGraphSearchClient.js +652 -0
  129. package/dist/orgGraphSearchClient.js.map +1 -0
  130. package/dist/packRuntime.d.ts +1 -2
  131. package/dist/packsClient.d.ts +2 -0
  132. package/dist/packsClient.js +195 -3
  133. package/dist/packsClient.js.map +1 -1
  134. package/dist/policyClient.d.ts +2 -0
  135. package/dist/policyClient.js +195 -3
  136. package/dist/policyClient.js.map +1 -1
  137. package/dist/questions/index.d.ts +19 -2
  138. package/dist/questions/index.js +2648 -327
  139. package/dist/questions/index.js.map +1 -1
  140. package/dist/reportsClient.d.ts +2 -0
  141. package/dist/reportsClient.js +197 -5
  142. package/dist/reportsClient.js.map +1 -1
  143. package/dist/schemaClient.d.ts +2 -0
  144. package/dist/schemaClient.js +195 -3
  145. package/dist/schemaClient.js.map +1 -1
  146. package/dist/sdkSurface.d.ts +2 -0
  147. package/dist/sourcesClient.d.ts +2 -0
  148. package/dist/sourcesClient.js +195 -3
  149. package/dist/sourcesClient.js.map +1 -1
  150. package/dist/telemetryClient.d.ts +94 -0
  151. package/dist/telemetryClient.js +719 -0
  152. package/dist/telemetryClient.js.map +1 -0
  153. package/dist/toolRegistryClient.d.ts +107 -0
  154. package/dist/toolRegistryClient.js +733 -0
  155. package/dist/toolRegistryClient.js.map +1 -0
  156. package/dist/topics/index.d.ts +19 -2
  157. package/dist/topics/index.js +2648 -327
  158. package/dist/topics/index.js.map +1 -1
  159. package/dist/topicsClient.d.ts +2 -0
  160. package/dist/topicsClient.js +200 -8
  161. package/dist/topicsClient.js.map +1 -1
  162. package/dist/workflowClient.d.ts +43 -7
  163. package/dist/workflowClient.js +200 -8
  164. package/dist/workflowClient.js.map +1 -1
  165. package/dist/worktrees/index.d.ts +43 -2
  166. package/dist/worktrees/index.js +2648 -327
  167. package/dist/worktrees/index.js.map +1 -1
  168. package/package.json +3 -3
@@ -0,0 +1,652 @@
1
+ // src/authContext.ts
2
+ var LucernSdkAuthContextError = class extends Error {
3
+ reason;
4
+ constructor(reason, message) {
5
+ super(message);
6
+ this.name = "LucernSdkAuthContextError";
7
+ this.reason = reason;
8
+ }
9
+ };
10
+ function cleanString(value) {
11
+ const normalized = value?.trim();
12
+ return normalized ? normalized : void 0;
13
+ }
14
+ function cleanStringList(values) {
15
+ if (!values) {
16
+ return [];
17
+ }
18
+ return values.map((value) => value.trim()).filter(
19
+ (value, index, list) => value.length > 0 && list.indexOf(value) === index
20
+ );
21
+ }
22
+ function requireString(value, reason, label) {
23
+ const normalized = cleanString(value);
24
+ if (!normalized) {
25
+ throw new LucernSdkAuthContextError(
26
+ reason,
27
+ `Canonical Lucern SDK auth context is missing ${label}.`
28
+ );
29
+ }
30
+ return normalized;
31
+ }
32
+ function requirePrincipalType(principalType) {
33
+ if (!principalType) {
34
+ throw new LucernSdkAuthContextError(
35
+ "principal_missing",
36
+ "Canonical Lucern SDK auth context is missing principalType."
37
+ );
38
+ }
39
+ return principalType;
40
+ }
41
+ function requireAuthMode(authMode) {
42
+ if (!authMode) {
43
+ throw new LucernSdkAuthContextError(
44
+ "principal_missing",
45
+ "Canonical Lucern SDK auth context is missing authMode."
46
+ );
47
+ }
48
+ return authMode;
49
+ }
50
+ function ensurePermitMatch(args) {
51
+ const actual = cleanString(args.actual);
52
+ if (actual && actual !== args.expected) {
53
+ throw new LucernSdkAuthContextError(
54
+ "policy_denied",
55
+ `Canonical Lucern SDK auth context has conflicting Permit ${args.field}.`
56
+ );
57
+ }
58
+ }
59
+ function normalizeCanonicalLucernAuthContext(input) {
60
+ if (!input) {
61
+ throw new LucernSdkAuthContextError(
62
+ "principal_missing",
63
+ "Canonical Lucern SDK auth context is required."
64
+ );
65
+ }
66
+ if (input.policyDecision === "deny") {
67
+ throw new LucernSdkAuthContextError(
68
+ "policy_denied",
69
+ "Canonical Lucern SDK auth context carries a denied policy decision."
70
+ );
71
+ }
72
+ const principalId = requireString(
73
+ input.principalId,
74
+ "principal_missing",
75
+ "principalId"
76
+ );
77
+ const tenantId = requireString(input.tenantId, "tenant_missing", "tenantId");
78
+ const workspaceId = requireString(
79
+ input.workspaceId,
80
+ "workspace_missing",
81
+ "workspaceId"
82
+ );
83
+ const roles = cleanStringList(input.roles);
84
+ const scopes = cleanStringList(input.scopes);
85
+ const principalType = requirePrincipalType(input.principalType);
86
+ const authMode = requireAuthMode(input.authMode);
87
+ const roleBasedInteractiveAuth = authMode === "interactive_user" && roles.length > 0;
88
+ if (roles.length === 0 || scopes.length === 0 && !roleBasedInteractiveAuth) {
89
+ throw new LucernSdkAuthContextError(
90
+ "membership_missing",
91
+ "Canonical Lucern SDK auth context requires non-empty roles and scopes."
92
+ );
93
+ }
94
+ const subject = cleanString(input.permit?.subject) ?? principalId;
95
+ const tenant = cleanString(input.permit?.tenant) ?? tenantId;
96
+ const workspace = cleanString(input.permit?.workspace) ?? workspaceId;
97
+ ensurePermitMatch({
98
+ field: "subject",
99
+ expected: principalId,
100
+ actual: subject
101
+ });
102
+ ensurePermitMatch({ field: "tenant", expected: tenantId, actual: tenant });
103
+ ensurePermitMatch({
104
+ field: "workspace",
105
+ expected: workspaceId,
106
+ actual: workspace
107
+ });
108
+ const context = input.permit?.context ? { ...input.permit.context } : void 0;
109
+ return {
110
+ clerkId: cleanString(input.clerkId),
111
+ principalId,
112
+ tenantId,
113
+ workspaceId,
114
+ principalType,
115
+ authMode,
116
+ roles,
117
+ scopes,
118
+ delegationChain: input.delegationChain ? [...input.delegationChain] : [],
119
+ policyTraceId: cleanString(input.policyTraceId),
120
+ correlationId: cleanString(input.correlationId),
121
+ membershipId: cleanString(input.membershipId),
122
+ permit: {
123
+ subject,
124
+ tenant,
125
+ workspace,
126
+ resource: cleanString(input.permit?.resource),
127
+ action: cleanString(input.permit?.action),
128
+ relation: cleanString(input.permit?.relation),
129
+ context
130
+ }
131
+ };
132
+ }
133
+ function createCanonicalAuthHeaders(authContext) {
134
+ const headers = {
135
+ "x-lucern-principal-id": authContext.principalId,
136
+ "x-lucern-principal-type": authContext.principalType,
137
+ "x-lucern-tenant": authContext.tenantId,
138
+ "x-lucern-tenant-id": authContext.tenantId,
139
+ "x-lucern-workspace": authContext.workspaceId,
140
+ "x-lucern-workspace-id": authContext.workspaceId,
141
+ "x-lucern-auth-mode": authContext.authMode,
142
+ "x-lucern-roles": authContext.roles.join(","),
143
+ "x-lucern-scopes": authContext.scopes.join(","),
144
+ "x-lucern-permit-context": JSON.stringify(authContext.permit)
145
+ };
146
+ if (authContext.clerkId) {
147
+ headers["x-lucern-clerk-id"] = authContext.clerkId;
148
+ headers["x-lucern-user-id"] = authContext.clerkId;
149
+ }
150
+ if (authContext.delegationChain.length > 0) {
151
+ headers["x-lucern-delegation-chain"] = JSON.stringify(
152
+ authContext.delegationChain
153
+ );
154
+ }
155
+ if (authContext.policyTraceId) {
156
+ headers["x-lucern-policy-trace-id"] = authContext.policyTraceId;
157
+ }
158
+ if (authContext.correlationId) {
159
+ headers["x-correlation-id"] = authContext.correlationId;
160
+ headers["x-lucern-correlation-id"] = authContext.correlationId;
161
+ }
162
+ if (authContext.membershipId) {
163
+ headers["x-lucern-membership-id"] = authContext.membershipId;
164
+ }
165
+ return headers;
166
+ }
167
+
168
+ // src/coreClient.ts
169
+ var LucernApiError = class extends Error {
170
+ code;
171
+ status;
172
+ invariant;
173
+ suggestion;
174
+ details;
175
+ requestId;
176
+ correlationId;
177
+ policyTraceId;
178
+ constructor(args) {
179
+ super(args.message);
180
+ this.name = "LucernApiError";
181
+ this.code = args.code;
182
+ this.status = args.status;
183
+ this.invariant = args.invariant;
184
+ this.suggestion = args.suggestion;
185
+ this.details = args.details;
186
+ this.requestId = args.requestId;
187
+ this.correlationId = args.correlationId;
188
+ this.policyTraceId = args.policyTraceId;
189
+ }
190
+ };
191
+ function toQueryString(scope) {
192
+ const params = new URLSearchParams();
193
+ if (scope.tenantId) {
194
+ params.set("tenantId", scope.tenantId);
195
+ }
196
+ if (scope.workspaceId) {
197
+ params.set("workspaceId", scope.workspaceId);
198
+ }
199
+ for (const [key, value] of Object.entries(scope)) {
200
+ if (key === "tenantId" || key === "workspaceId") {
201
+ continue;
202
+ }
203
+ if (value === void 0) {
204
+ continue;
205
+ }
206
+ params.set(key, String(value));
207
+ }
208
+ const serialized = params.toString();
209
+ return serialized.length > 0 ? `?${serialized}` : "";
210
+ }
211
+ function fillRandomBytes(length) {
212
+ const bytes = new Uint8Array(length);
213
+ if (typeof globalThis.crypto?.getRandomValues === "function") {
214
+ globalThis.crypto.getRandomValues(bytes);
215
+ return bytes;
216
+ }
217
+ for (let index = 0; index < length; index += 1) {
218
+ bytes[index] = Math.floor(Math.random() * 256);
219
+ }
220
+ return bytes;
221
+ }
222
+ function generatePortableRequestId() {
223
+ if (typeof globalThis.crypto?.randomUUID === "function") {
224
+ return globalThis.crypto.randomUUID();
225
+ }
226
+ const bytes = fillRandomBytes(16);
227
+ bytes[6] = bytes[6] & 15 | 64;
228
+ bytes[8] = bytes[8] & 63 | 128;
229
+ const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, "0"));
230
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(
231
+ 6,
232
+ 8
233
+ ).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
234
+ }
235
+ function isRetryableStatus(status) {
236
+ return status >= 500 || status === 408 || status === 429;
237
+ }
238
+ function fallbackErrorCode(status) {
239
+ if (status === 401) {
240
+ return "AUTHENTICATION_REQUIRED";
241
+ }
242
+ if (status === 403) {
243
+ return "FORBIDDEN";
244
+ }
245
+ if (status === 404) {
246
+ return "NOT_FOUND";
247
+ }
248
+ if (status === 408) {
249
+ return "UPSTREAM_ERROR";
250
+ }
251
+ if (status === 409) {
252
+ return "CONFLICT";
253
+ }
254
+ if (status === 429) {
255
+ return "RATE_LIMIT_EXCEEDED";
256
+ }
257
+ if (status >= 500) {
258
+ return "UPSTREAM_ERROR";
259
+ }
260
+ return "INTERNAL_ERROR";
261
+ }
262
+ function delay(ms) {
263
+ return new Promise((resolve) => setTimeout(resolve, ms));
264
+ }
265
+ function parseRetryAfterMs(value) {
266
+ if (!value) {
267
+ return null;
268
+ }
269
+ const trimmed = value.trim();
270
+ if (!trimmed) {
271
+ return null;
272
+ }
273
+ const numeric = Number(trimmed);
274
+ if (Number.isFinite(numeric)) {
275
+ return Math.max(0, Math.round(numeric * 1e3));
276
+ }
277
+ const parsedDate = Date.parse(trimmed);
278
+ if (Number.isFinite(parsedDate)) {
279
+ return Math.max(0, parsedDate - Date.now());
280
+ }
281
+ return null;
282
+ }
283
+ function computeRetryDelayMs(args) {
284
+ const baseDelay = args.status === 429 ? Math.max(
285
+ args.retryAfterMs ?? 0,
286
+ Math.min(1e3 * 2 ** args.attempt, 1e4)
287
+ ) : Math.min(1e3 * 2 ** args.attempt, 4e3);
288
+ if (args.status !== 429) {
289
+ return baseDelay;
290
+ }
291
+ const jitterWindow = Math.max(250, Math.round(baseDelay * 0.25));
292
+ return baseDelay + Math.round(Math.random() * jitterWindow);
293
+ }
294
+ function timeoutError(timeoutMs) {
295
+ const error = new Error(`Request timed out after ${timeoutMs}ms`);
296
+ error.name = "AbortError";
297
+ return error;
298
+ }
299
+ function readPolicySummaryFromDetails(details) {
300
+ if (!details || typeof details !== "object" || Array.isArray(details)) {
301
+ return null;
302
+ }
303
+ const directSummary = details.summary;
304
+ if (typeof directSummary === "string" && directSummary.trim().length > 0) {
305
+ return directSummary.trim();
306
+ }
307
+ const policy = details.policy;
308
+ if (!policy || typeof policy !== "object" || Array.isArray(policy)) {
309
+ return null;
310
+ }
311
+ const explanation = policy.explanation;
312
+ if (!explanation || typeof explanation !== "object" || Array.isArray(explanation)) {
313
+ return null;
314
+ }
315
+ const nestedSummary = explanation.summary;
316
+ if (typeof nestedSummary === "string" && nestedSummary.trim().length > 0) {
317
+ return nestedSummary.trim();
318
+ }
319
+ return null;
320
+ }
321
+ async function resolveConfiguredAuthContext(authContext) {
322
+ if (typeof authContext === "function") {
323
+ return await authContext();
324
+ }
325
+ return authContext;
326
+ }
327
+ function mergeHeaderRecord(base, addition) {
328
+ const headers = new Headers(base);
329
+ for (const [key, value] of Object.entries(addition)) {
330
+ const existing = headers.get(key);
331
+ if (existing !== null && existing !== value) {
332
+ throw new LucernSdkAuthContextError(
333
+ "policy_denied",
334
+ `Canonical Lucern SDK auth context conflicts with existing ${key} header.`
335
+ );
336
+ }
337
+ headers.set(key, value);
338
+ }
339
+ return Object.fromEntries(headers.entries());
340
+ }
341
+ function createGatewayRequestClient(config = {}) {
342
+ const fetchImpl = config.fetchImpl ?? fetch;
343
+ const baseUrl = config.baseUrl?.replace(/\/+$/, "") ?? "";
344
+ const maxRetries = config.maxRetries ?? 2;
345
+ const requestIdFactory = config.requestIdFactory ?? (() => generatePortableRequestId());
346
+ async function resolveAuthHeaders() {
347
+ const base = config.getAuthHeaders ? await config.getAuthHeaders() : {};
348
+ const authContextInput = await resolveConfiguredAuthContext(
349
+ config.authContext
350
+ );
351
+ if (!authContextInput && !config.requireCanonicalAuthContext) {
352
+ return base;
353
+ }
354
+ const authContext = normalizeCanonicalLucernAuthContext(authContextInput);
355
+ return mergeHeaderRecord(base, createCanonicalAuthHeaders(authContext));
356
+ }
357
+ async function fetchWithTimeout(url, init, timeoutMs) {
358
+ const controller = new AbortController();
359
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
360
+ try {
361
+ return await fetchImpl(url, { ...init, signal: controller.signal });
362
+ } catch (error) {
363
+ if (controller.signal.aborted) {
364
+ throw timeoutError(timeoutMs);
365
+ }
366
+ throw error;
367
+ } finally {
368
+ clearTimeout(timer);
369
+ }
370
+ }
371
+ async function parsePayload(response) {
372
+ const text = await response.text();
373
+ if (!text) {
374
+ return null;
375
+ }
376
+ try {
377
+ return JSON.parse(text);
378
+ } catch {
379
+ return null;
380
+ }
381
+ }
382
+ function resolveTimeoutMs(method, requestTimeoutMs) {
383
+ if (typeof requestTimeoutMs === "number") {
384
+ return requestTimeoutMs;
385
+ }
386
+ const methodTimeoutMs = config.timeoutMsByMethod?.[method];
387
+ if (typeof methodTimeoutMs === "number") {
388
+ return methodTimeoutMs;
389
+ }
390
+ return config.timeoutMs ?? 15e3;
391
+ }
392
+ function buildApiError(args) {
393
+ const failure = args.failure;
394
+ const legacyError = failure && typeof failure.error === "object" && failure.error !== null ? failure.error : failure?.legacyError;
395
+ const correlationId = failure?.correlationId ?? args.response.headers.get("x-lucern-correlation-id")?.trim() ?? args.requestId;
396
+ const policyTraceId = failure?.policyTraceId ?? args.response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null;
397
+ const details = failure?.details ?? legacyError?.details;
398
+ const policySummary = readPolicySummaryFromDetails(details);
399
+ return new LucernApiError({
400
+ code: failure?.code ?? legacyError?.code ?? fallbackErrorCode(args.response.status),
401
+ message: policySummary ?? (typeof failure?.error === "string" ? failure.error : legacyError?.message ?? (args.response.ok ? "Platform API returned an invalid success payload." : "Platform API request failed.")),
402
+ status: args.response.status,
403
+ invariant: failure?.invariant,
404
+ suggestion: failure?.suggestion,
405
+ details,
406
+ requestId: args.requestId,
407
+ correlationId,
408
+ policyTraceId
409
+ });
410
+ }
411
+ async function request(args) {
412
+ const authHeaders = await resolveAuthHeaders();
413
+ const method = args.method ?? "GET";
414
+ const timeoutMs = resolveTimeoutMs(method, args.timeoutMs);
415
+ const headers = new Headers({
416
+ "content-type": "application/json",
417
+ ...authHeaders
418
+ });
419
+ if (args.idempotencyKey) {
420
+ headers.set("idempotency-key", args.idempotencyKey);
421
+ }
422
+ const requestId = headers.get("x-correlation-id")?.trim() || headers.get("x-request-id")?.trim() || args.requestId || requestIdFactory();
423
+ if (!headers.has("x-correlation-id") && !headers.has("x-request-id")) {
424
+ headers.set("x-correlation-id", requestId);
425
+ }
426
+ const url = `${baseUrl}${args.path}`;
427
+ const serializedBody = args.body ? JSON.stringify(args.body) : void 0;
428
+ const init = {
429
+ method,
430
+ headers,
431
+ body: serializedBody
432
+ };
433
+ let lastError;
434
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
435
+ const hookRequestContext = {
436
+ requestId,
437
+ attempt,
438
+ maxRetries,
439
+ method,
440
+ path: args.path,
441
+ url,
442
+ headers: new Headers(headers),
443
+ body: serializedBody,
444
+ timeoutMs
445
+ };
446
+ await config.onRequest?.(hookRequestContext);
447
+ const startedAt = Date.now();
448
+ try {
449
+ const response = await fetchWithTimeout(url, init, timeoutMs);
450
+ const responseClone = response.clone();
451
+ const payload = await parsePayload(response);
452
+ const retryAfterMs = parseRetryAfterMs(
453
+ response.headers.get("Retry-After")
454
+ );
455
+ if (!response.ok || !payload?.success) {
456
+ const failure = payload && !payload.success ? payload : null;
457
+ const apiError = buildApiError({
458
+ requestId,
459
+ response,
460
+ failure
461
+ });
462
+ const willRetry = attempt < maxRetries && isRetryableStatus(response.status);
463
+ await config.onResponse?.({
464
+ ...hookRequestContext,
465
+ durationMs: Date.now() - startedAt,
466
+ status: response.status,
467
+ response: responseClone,
468
+ error: apiError,
469
+ correlationId: apiError.correlationId ?? requestId,
470
+ policyTraceId: apiError.policyTraceId ?? null,
471
+ retryAfterMs,
472
+ willRetry
473
+ });
474
+ if (willRetry) {
475
+ lastError = apiError;
476
+ await delay(
477
+ computeRetryDelayMs({
478
+ attempt,
479
+ status: response.status,
480
+ retryAfterMs
481
+ })
482
+ );
483
+ continue;
484
+ }
485
+ throw apiError;
486
+ }
487
+ const successPayload = payload;
488
+ await config.onResponse?.({
489
+ ...hookRequestContext,
490
+ durationMs: Date.now() - startedAt,
491
+ status: response.status,
492
+ response: responseClone,
493
+ correlationId: successPayload.correlationId ?? response.headers.get("x-lucern-correlation-id")?.trim() ?? requestId,
494
+ policyTraceId: successPayload.policyTraceId ?? response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null,
495
+ idempotentReplay: successPayload.idempotentReplay,
496
+ retryAfterMs,
497
+ willRetry: false
498
+ });
499
+ return successPayload;
500
+ } catch (fetchError) {
501
+ if (fetchError instanceof LucernApiError) {
502
+ throw fetchError;
503
+ }
504
+ const willRetry = attempt < maxRetries;
505
+ await config.onResponse?.({
506
+ ...hookRequestContext,
507
+ durationMs: Date.now() - startedAt,
508
+ error: fetchError,
509
+ correlationId: requestId,
510
+ policyTraceId: null,
511
+ willRetry
512
+ });
513
+ lastError = fetchError;
514
+ if (willRetry) {
515
+ await delay(computeRetryDelayMs({ attempt }));
516
+ }
517
+ }
518
+ }
519
+ throw lastError instanceof Error ? lastError : new Error("Platform API request failed after retries.");
520
+ }
521
+ return {
522
+ request
523
+ };
524
+ }
525
+
526
+ // src/sdkSurface.ts
527
+ function createListResult(items, legacyKey) {
528
+ const result = {
529
+ items,
530
+ total: items.length
531
+ };
532
+ {
533
+ result[legacyKey] = items;
534
+ }
535
+ return result;
536
+ }
537
+ function mapGatewayData(response, mapper) {
538
+ return {
539
+ ...response,
540
+ data: mapper(response.data)
541
+ };
542
+ }
543
+
544
+ // src/orgGraphSearchClient.ts
545
+ var ORG_GRAPH_SEARCH_FIELDS = [
546
+ "tenantId",
547
+ "workspaceId",
548
+ "query",
549
+ "nodeTypes",
550
+ "minConfidence",
551
+ "limit",
552
+ "cursor",
553
+ "provenanceScope"
554
+ ];
555
+ function cleanString2(value, label) {
556
+ const normalized = value?.trim();
557
+ if (!normalized) {
558
+ throw new Error(`${label} is required`);
559
+ }
560
+ return normalized;
561
+ }
562
+ function assertKnownSearchKeys(input, operation) {
563
+ const allowed = new Set(ORG_GRAPH_SEARCH_FIELDS);
564
+ const unknownKeys = Object.keys(input).filter((key) => !allowed.has(key));
565
+ if (unknownKeys.length > 0) {
566
+ throw new Error(
567
+ `${operation} received unsupported field(s): ${unknownKeys.join(", ")}`
568
+ );
569
+ }
570
+ }
571
+ function searchBody(input) {
572
+ assertKnownSearchKeys(
573
+ input,
574
+ "orgGraphSearch.search"
575
+ );
576
+ return {
577
+ tenantId: cleanString2(input.tenantId, "tenantId"),
578
+ workspaceId: cleanString2(input.workspaceId, "workspaceId"),
579
+ query: cleanString2(input.query, "query"),
580
+ nodeTypes: input.nodeTypes,
581
+ minConfidence: input.minConfidence,
582
+ limit: input.limit,
583
+ cursor: input.cursor,
584
+ provenanceScope: input.provenanceScope
585
+ };
586
+ }
587
+ function listQuery(input) {
588
+ return {
589
+ tenantId: cleanString2(input.tenantId, "tenantId"),
590
+ workspaceId: cleanString2(input.workspaceId, "workspaceId"),
591
+ nodeTypes: input.nodeTypes?.join(","),
592
+ minConfidence: input.minConfidence,
593
+ limit: input.limit,
594
+ cursor: input.cursor
595
+ };
596
+ }
597
+ function mapResults(data) {
598
+ const record = data && typeof data === "object" ? data : {};
599
+ return createListResult(
600
+ Array.isArray(record.results) ? record.results : Array.isArray(data) ? data : [],
601
+ "results"
602
+ );
603
+ }
604
+ function createOrgGraphSearchClient(config = {}) {
605
+ const gateway = createGatewayRequestClient(config);
606
+ return {
607
+ search(input) {
608
+ return gateway.request({
609
+ path: "/api/platform/v1/org-graph-search/search",
610
+ method: "POST",
611
+ body: searchBody(input)
612
+ }).then((response) => mapGatewayData(response, mapResults));
613
+ },
614
+ getNode(input) {
615
+ const nodeId = input.nodeId?.trim();
616
+ const globalId = input.globalId?.trim();
617
+ if (!nodeId && !globalId) {
618
+ throw new Error("nodeId or globalId is required");
619
+ }
620
+ const nodePath = encodeURIComponent(nodeId ?? globalId ?? "");
621
+ return gateway.request({
622
+ path: `/api/platform/v1/org-graph-search/nodes/${nodePath}${toQueryString(
623
+ {
624
+ tenantId: cleanString2(input.tenantId, "tenantId"),
625
+ workspaceId: cleanString2(input.workspaceId, "workspaceId"),
626
+ globalId: nodeId ? void 0 : globalId
627
+ }
628
+ )}`
629
+ });
630
+ },
631
+ listByProvenance(input) {
632
+ return gateway.request({
633
+ path: `/api/platform/v1/org-graph-search/provenance${toQueryString({
634
+ ...listQuery(input),
635
+ provenanceScope: input.provenanceScope
636
+ })}`
637
+ }).then((response) => mapGatewayData(response, mapResults));
638
+ },
639
+ listPublishedFromWorkspace(input) {
640
+ return gateway.request({
641
+ path: `/api/platform/v1/org-graph-search/published${toQueryString({
642
+ ...listQuery(input),
643
+ sourceWorkspaceId: input.sourceWorkspaceId
644
+ })}`
645
+ }).then((response) => mapGatewayData(response, mapResults));
646
+ }
647
+ };
648
+ }
649
+
650
+ export { ORG_GRAPH_SEARCH_FIELDS, createOrgGraphSearchClient };
651
+ //# sourceMappingURL=orgGraphSearchClient.js.map
652
+ //# sourceMappingURL=orgGraphSearchClient.js.map