@lucern/sdk 0.3.0-alpha.9 → 1.0.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.
Files changed (152) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +60 -1
  3. package/dist/accessControl.d.ts +79 -0
  4. package/dist/accessControl.js +1270 -0
  5. package/dist/accessControl.js.map +1 -0
  6. package/dist/adminClient.js +19 -1
  7. package/dist/adminClient.js.map +1 -1
  8. package/dist/answersClient.js +19 -1
  9. package/dist/answersClient.js.map +1 -1
  10. package/dist/audiencesClient.js +19 -1
  11. package/dist/audiencesClient.js.map +1 -1
  12. package/dist/auditClient.js +19 -1
  13. package/dist/auditClient.js.map +1 -1
  14. package/dist/authContext.d.ts +2 -2
  15. package/dist/authContext.js.map +1 -1
  16. package/dist/beliefs/index.d.ts +2 -0
  17. package/dist/beliefs/index.js +1196 -663
  18. package/dist/beliefs/index.js.map +1 -1
  19. package/dist/beliefsClient.js +19 -1
  20. package/dist/beliefsClient.js.map +1 -1
  21. package/dist/client.d.ts +146 -70
  22. package/dist/client.js +1196 -663
  23. package/dist/client.js.map +1 -1
  24. package/dist/contextClient.js +19 -1
  25. package/dist/contextClient.js.map +1 -1
  26. package/dist/contracts/api-enums.contract.d.ts +1 -1
  27. package/dist/contracts/api-enums.contract.js +6 -1
  28. package/dist/contracts/api-enums.contract.js.map +1 -1
  29. package/dist/contracts/auth-session.contract.d.ts +1 -1
  30. package/dist/contracts/auth-session.contract.js +14 -2
  31. package/dist/contracts/auth-session.contract.js.map +1 -1
  32. package/dist/contracts/index.js +26 -3
  33. package/dist/contracts/index.js.map +1 -1
  34. package/dist/contracts/mcpTools.js +6 -0
  35. package/dist/contracts/mcpTools.js.map +1 -1
  36. package/dist/contradictions/index.d.ts +2 -0
  37. package/dist/contradictions/index.js +1196 -663
  38. package/dist/contradictions/index.js.map +1 -1
  39. package/dist/control-plane.d.ts +69 -0
  40. package/dist/control-plane.js +674 -0
  41. package/dist/control-plane.js.map +1 -0
  42. package/dist/coreClient.d.ts +17 -1
  43. package/dist/coreClient.js +19 -1
  44. package/dist/coreClient.js.map +1 -1
  45. package/dist/decisions/index.d.ts +2 -0
  46. package/dist/decisions/index.js +1196 -663
  47. package/dist/decisions/index.js.map +1 -1
  48. package/dist/decisionsClient.js +19 -1
  49. package/dist/decisionsClient.js.map +1 -1
  50. package/dist/edges/index.d.ts +26 -84
  51. package/dist/edges/index.js +1196 -663
  52. package/dist/edges/index.js.map +1 -1
  53. package/dist/embeddingsClient.js +19 -1
  54. package/dist/embeddingsClient.js.map +1 -1
  55. package/dist/eventingClient.js +19 -1
  56. package/dist/eventingClient.js.map +1 -1
  57. package/dist/eventsCore.js +19 -1
  58. package/dist/eventsCore.js.map +1 -1
  59. package/dist/evidence/index.d.ts +2 -0
  60. package/dist/evidence/index.js +1196 -663
  61. package/dist/evidence/index.js.map +1 -1
  62. package/dist/evidenceClient.js +19 -1
  63. package/dist/evidenceClient.js.map +1 -1
  64. package/dist/functionSurface.d.ts +16 -1
  65. package/dist/functionSurface.js +95 -2
  66. package/dist/functionSurface.js.map +1 -1
  67. package/dist/functionSurfaceClient.js +95 -2
  68. package/dist/functionSurfaceClient.js.map +1 -1
  69. package/dist/gatewayFacades.d.ts +29 -2
  70. package/dist/gatewayFacades.js +156 -8
  71. package/dist/gatewayFacades.js.map +1 -1
  72. package/dist/graphAnalysisClient.js +19 -1
  73. package/dist/graphAnalysisClient.js.map +1 -1
  74. package/dist/graphClient.d.ts +1 -0
  75. package/dist/graphClient.js +19 -1
  76. package/dist/graphClient.js.map +1 -1
  77. package/dist/graphIntel.d.ts +1 -0
  78. package/dist/graphRecommendationsClient.js +19 -1
  79. package/dist/graphRecommendationsClient.js.map +1 -1
  80. package/dist/graphStateClassifierClient.js +19 -1
  81. package/dist/graphStateClassifierClient.js.map +1 -1
  82. package/dist/harnessClient.js +19 -1
  83. package/dist/harnessClient.js.map +1 -1
  84. package/dist/identityClient.d.ts +19 -1
  85. package/dist/identityClient.js +152 -6
  86. package/dist/identityClient.js.map +1 -1
  87. package/dist/index.d.ts +4 -1
  88. package/dist/index.js +1281 -664
  89. package/dist/index.js.map +1 -1
  90. package/dist/infisicalRuntime.d.ts +1 -0
  91. package/dist/infisicalRuntime.js +64 -32
  92. package/dist/infisicalRuntime.js.map +1 -1
  93. package/dist/jobsClient.js +19 -1
  94. package/dist/jobsClient.js.map +1 -1
  95. package/dist/learningClient.js +19 -1
  96. package/dist/learningClient.js.map +1 -1
  97. package/dist/lenses/index.d.ts +2 -0
  98. package/dist/lenses/index.js +1196 -663
  99. package/dist/lenses/index.js.map +1 -1
  100. package/dist/mcpClient.js +21 -2
  101. package/dist/mcpClient.js.map +1 -1
  102. package/dist/modelRuntimeClient.js +19 -1
  103. package/dist/modelRuntimeClient.js.map +1 -1
  104. package/dist/nodes/index.d.ts +21 -15
  105. package/dist/nodes/index.js +1196 -663
  106. package/dist/nodes/index.js.map +1 -1
  107. package/dist/ontologies/index.d.ts +2 -0
  108. package/dist/ontologies/index.js +1196 -663
  109. package/dist/ontologies/index.js.map +1 -1
  110. package/dist/ontologyClient.js +19 -1
  111. package/dist/ontologyClient.js.map +1 -1
  112. package/dist/ontologyLinksClient.js +19 -1
  113. package/dist/ontologyLinksClient.js.map +1 -1
  114. package/dist/orgGraphSearchClient.js +19 -1
  115. package/dist/orgGraphSearchClient.js.map +1 -1
  116. package/dist/packsClient.js +19 -1
  117. package/dist/packsClient.js.map +1 -1
  118. package/dist/policyClient.js +19 -1
  119. package/dist/policyClient.js.map +1 -1
  120. package/dist/questions/index.d.ts +2 -0
  121. package/dist/questions/index.js +1196 -663
  122. package/dist/questions/index.js.map +1 -1
  123. package/dist/reportsClient.js +19 -1
  124. package/dist/reportsClient.js.map +1 -1
  125. package/dist/schemaClient.js +19 -1
  126. package/dist/schemaClient.js.map +1 -1
  127. package/dist/secrets.d.ts +1 -0
  128. package/dist/secrets.js +3 -0
  129. package/dist/secrets.js.map +1 -0
  130. package/dist/sourcesClient.js +19 -1
  131. package/dist/sourcesClient.js.map +1 -1
  132. package/dist/telemetryClient.js +19 -1
  133. package/dist/telemetryClient.js.map +1 -1
  134. package/dist/toolRegistryClient.js +19 -1
  135. package/dist/toolRegistryClient.js.map +1 -1
  136. package/dist/topics/index.d.ts +11 -3
  137. package/dist/topics/index.js +1198 -663
  138. package/dist/topics/index.js.map +1 -1
  139. package/dist/topicsClient.d.ts +2 -0
  140. package/dist/topicsClient.js +19 -1
  141. package/dist/topicsClient.js.map +1 -1
  142. package/dist/types.d.ts +17 -0
  143. package/dist/version.d.ts +1 -1
  144. package/dist/version.js +1 -1
  145. package/dist/version.js.map +1 -1
  146. package/dist/workflowClient.d.ts +2 -0
  147. package/dist/workflowClient.js +19 -1
  148. package/dist/workflowClient.js.map +1 -1
  149. package/dist/worktrees/index.d.ts +2 -0
  150. package/dist/worktrees/index.js +1196 -663
  151. package/dist/worktrees/index.js.map +1 -1
  152. package/package.json +9 -4
@@ -0,0 +1,1270 @@
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(principalType2) {
33
+ if (!principalType2) {
34
+ throw new LucernSdkAuthContextError(
35
+ "principal_missing",
36
+ "Canonical Lucern SDK auth context is missing principalType."
37
+ );
38
+ }
39
+ return principalType2;
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 principalType2 = 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: principalType2,
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
+ var randomIdempotencyKey = generatePortableRequestId;
236
+ function isRetryableStatus(status) {
237
+ return status >= 500 || status === 408 || status === 429;
238
+ }
239
+ function fallbackErrorCode(status) {
240
+ if (status === 401) {
241
+ return "AUTHENTICATION_REQUIRED";
242
+ }
243
+ if (status === 403) {
244
+ return "FORBIDDEN";
245
+ }
246
+ if (status === 404) {
247
+ return "NOT_FOUND";
248
+ }
249
+ if (status === 408) {
250
+ return "UPSTREAM_ERROR";
251
+ }
252
+ if (status === 409) {
253
+ return "CONFLICT";
254
+ }
255
+ if (status === 429) {
256
+ return "RATE_LIMIT_EXCEEDED";
257
+ }
258
+ if (status >= 500) {
259
+ return "UPSTREAM_ERROR";
260
+ }
261
+ return "INTERNAL_ERROR";
262
+ }
263
+ function delay(ms) {
264
+ return new Promise((resolve) => setTimeout(resolve, ms));
265
+ }
266
+ function parseRetryAfterMs(value) {
267
+ if (!value) {
268
+ return null;
269
+ }
270
+ const trimmed = value.trim();
271
+ if (!trimmed) {
272
+ return null;
273
+ }
274
+ const numeric = Number(trimmed);
275
+ if (Number.isFinite(numeric)) {
276
+ return Math.max(0, Math.round(numeric * 1e3));
277
+ }
278
+ const parsedDate = Date.parse(trimmed);
279
+ if (Number.isFinite(parsedDate)) {
280
+ return Math.max(0, parsedDate - Date.now());
281
+ }
282
+ return null;
283
+ }
284
+ function computeRetryDelayMs(args) {
285
+ const baseDelay = args.status === 429 ? Math.max(
286
+ args.retryAfterMs ?? 0,
287
+ Math.min(1e3 * 2 ** args.attempt, 1e4)
288
+ ) : Math.min(1e3 * 2 ** args.attempt, 4e3);
289
+ if (args.status !== 429) {
290
+ return baseDelay;
291
+ }
292
+ const jitterWindow = Math.max(250, Math.round(baseDelay * 0.25));
293
+ return baseDelay + Math.round(Math.random() * jitterWindow);
294
+ }
295
+ function timeoutError(timeoutMs) {
296
+ const error = new Error(`Request timed out after ${timeoutMs}ms`);
297
+ error.name = "AbortError";
298
+ return error;
299
+ }
300
+ function isRecord(value) {
301
+ return value !== null && typeof value === "object" && !Array.isArray(value);
302
+ }
303
+ function readPolicySummaryFromDetails(details) {
304
+ if (!isRecord(details)) {
305
+ return null;
306
+ }
307
+ const directSummary = details.summary;
308
+ if (typeof directSummary === "string" && directSummary.trim().length > 0) {
309
+ return directSummary.trim();
310
+ }
311
+ const policy = details.policy;
312
+ if (!isRecord(policy)) {
313
+ return null;
314
+ }
315
+ const explanation = policy.explanation;
316
+ if (!isRecord(explanation)) {
317
+ return null;
318
+ }
319
+ const nestedSummary = explanation.summary;
320
+ if (typeof nestedSummary === "string" && nestedSummary.trim().length > 0) {
321
+ return nestedSummary.trim();
322
+ }
323
+ return null;
324
+ }
325
+ async function resolveConfiguredAuthContext(authContext) {
326
+ if (typeof authContext === "function") {
327
+ return await authContext();
328
+ }
329
+ return authContext;
330
+ }
331
+ function mergeHeaderRecord(base, addition) {
332
+ const headers = new Headers(base);
333
+ for (const [key, value] of Object.entries(addition)) {
334
+ const existing = headers.get(key);
335
+ if (existing !== null && existing !== value) {
336
+ throw new LucernSdkAuthContextError(
337
+ "policy_denied",
338
+ `Canonical Lucern SDK auth context conflicts with existing ${key} header.`
339
+ );
340
+ }
341
+ headers.set(key, value);
342
+ }
343
+ return Object.fromEntries(headers.entries());
344
+ }
345
+ function cleanHeaderValue(value) {
346
+ const normalized = value?.trim();
347
+ return normalized ? normalized : void 0;
348
+ }
349
+ function createGatewayRequestClient(config = {}) {
350
+ const fetchImpl = config.fetchImpl ?? fetch;
351
+ const baseUrl = config.baseUrl?.replace(/\/+$/, "") ?? "";
352
+ const maxRetries = config.maxRetries ?? 2;
353
+ const requestIdFactory = config.requestIdFactory ?? (() => generatePortableRequestId());
354
+ async function resolveAuthHeaders() {
355
+ const provided = config.getAuthHeaders ? await config.getAuthHeaders() : {};
356
+ const headers = new Headers(provided);
357
+ const setIfAbsent = (name, value) => {
358
+ const normalized = cleanHeaderValue(value);
359
+ if (normalized && !headers.has(name)) {
360
+ headers.set(name, normalized);
361
+ }
362
+ };
363
+ setIfAbsent("x-lucern-key", config.apiKey);
364
+ setIfAbsent("x-lucern-session-token", config.userToken);
365
+ setIfAbsent("x-lucern-environment", config.environment);
366
+ setIfAbsent("x-lucern-clerk-id", config.clerkId);
367
+ setIfAbsent("x-lucern-user-id", config.userId ?? config.clerkId);
368
+ setIfAbsent("x-lucern-deployment-host", config.deploymentHost);
369
+ const base = Object.fromEntries(headers.entries());
370
+ const authContextInput = await resolveConfiguredAuthContext(
371
+ config.authContext
372
+ );
373
+ if (!authContextInput && !config.requireCanonicalAuthContext) {
374
+ return base;
375
+ }
376
+ const authContext = normalizeCanonicalLucernAuthContext(authContextInput);
377
+ return mergeHeaderRecord(base, createCanonicalAuthHeaders(authContext));
378
+ }
379
+ async function fetchWithTimeout(url, init, timeoutMs) {
380
+ const controller = new AbortController();
381
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
382
+ try {
383
+ return await fetchImpl(url, { ...init, signal: controller.signal });
384
+ } catch (error) {
385
+ if (controller.signal.aborted) {
386
+ throw timeoutError(timeoutMs);
387
+ }
388
+ throw error;
389
+ } finally {
390
+ clearTimeout(timer);
391
+ }
392
+ }
393
+ async function parsePayload(response) {
394
+ const text = await response.text();
395
+ if (!text) {
396
+ return null;
397
+ }
398
+ const parsed = tryParseGatewayEnvelopeJson(text);
399
+ if (!parsed.ok) {
400
+ return null;
401
+ }
402
+ return isRecord(parsed.value) ? parsed.value : null;
403
+ }
404
+ function resolveTimeoutMs(method, requestTimeoutMs) {
405
+ if (typeof requestTimeoutMs === "number") {
406
+ return requestTimeoutMs;
407
+ }
408
+ const methodTimeoutMs = config.timeoutMsByMethod?.[method];
409
+ if (typeof methodTimeoutMs === "number") {
410
+ return methodTimeoutMs;
411
+ }
412
+ return config.timeoutMs ?? 15e3;
413
+ }
414
+ function tryParseGatewayEnvelopeJson(text) {
415
+ const trimmed = text.trim();
416
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) {
417
+ return { ok: false, reason: "non-json" };
418
+ }
419
+ try {
420
+ return { ok: true, value: JSON.parse(trimmed) };
421
+ } catch (error) {
422
+ if (error instanceof SyntaxError) {
423
+ return { ok: false, reason: "invalid-json", error };
424
+ }
425
+ throw error;
426
+ }
427
+ }
428
+ function buildApiError(args) {
429
+ const failure = args.failure;
430
+ const legacyError = failure && isRecord(failure.error) ? failure.error : failure?.legacyError;
431
+ const correlationId = failure?.correlationId ?? args.response.headers.get("x-lucern-correlation-id")?.trim() ?? args.requestId;
432
+ const policyTraceId = failure?.policyTraceId ?? args.response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null;
433
+ const details = failure?.details ?? legacyError?.details;
434
+ const policySummary = readPolicySummaryFromDetails(details);
435
+ const failureMessage = typeof failure?.error === "string" ? failure.error : legacyError?.message;
436
+ return new LucernApiError({
437
+ code: failure?.code ?? legacyError?.code ?? fallbackErrorCode(args.response.status),
438
+ message: policySummary ?? failureMessage ?? (args.response.ok ? "Platform API returned an invalid success payload." : "Platform API request failed."),
439
+ status: args.response.status,
440
+ invariant: failure?.invariant,
441
+ suggestion: failure?.suggestion,
442
+ details,
443
+ requestId: args.requestId,
444
+ correlationId,
445
+ policyTraceId
446
+ });
447
+ }
448
+ async function request(args) {
449
+ const authHeaders = await resolveAuthHeaders();
450
+ const method = args.method ?? "GET";
451
+ const timeoutMs = resolveTimeoutMs(method, args.timeoutMs);
452
+ const headers = new Headers({
453
+ "content-type": "application/json",
454
+ ...authHeaders
455
+ });
456
+ if (args.idempotencyKey) {
457
+ headers.set("idempotency-key", args.idempotencyKey);
458
+ }
459
+ const requestId = headers.get("x-correlation-id")?.trim() || headers.get("x-request-id")?.trim() || args.requestId || requestIdFactory();
460
+ if (!headers.has("x-correlation-id") && !headers.has("x-request-id")) {
461
+ headers.set("x-correlation-id", requestId);
462
+ }
463
+ const url = `${baseUrl}${args.path}`;
464
+ const serializedBody = args.body ? JSON.stringify(args.body) : void 0;
465
+ const init = {
466
+ method,
467
+ headers,
468
+ body: serializedBody
469
+ };
470
+ let lastError;
471
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
472
+ const hookRequestContext = {
473
+ requestId,
474
+ attempt,
475
+ maxRetries,
476
+ method,
477
+ path: args.path,
478
+ url,
479
+ headers: new Headers(headers),
480
+ body: serializedBody,
481
+ timeoutMs
482
+ };
483
+ await config.onRequest?.(hookRequestContext);
484
+ const startedAt = Date.now();
485
+ try {
486
+ const response = await fetchWithTimeout(url, init, timeoutMs);
487
+ const responseClone = response.clone();
488
+ const payload = await parsePayload(response);
489
+ const retryAfterMs = parseRetryAfterMs(
490
+ response.headers.get("Retry-After")
491
+ );
492
+ if (!response.ok || !payload?.success) {
493
+ const failure = payload && !payload.success ? payload : null;
494
+ const apiError = buildApiError({
495
+ requestId,
496
+ response,
497
+ failure
498
+ });
499
+ const willRetry = attempt < maxRetries && isRetryableStatus(response.status);
500
+ await config.onResponse?.({
501
+ ...hookRequestContext,
502
+ durationMs: Date.now() - startedAt,
503
+ status: response.status,
504
+ response: responseClone,
505
+ error: apiError,
506
+ correlationId: apiError.correlationId ?? requestId,
507
+ policyTraceId: apiError.policyTraceId ?? null,
508
+ retryAfterMs,
509
+ willRetry
510
+ });
511
+ if (willRetry) {
512
+ lastError = apiError;
513
+ await delay(
514
+ computeRetryDelayMs({
515
+ attempt,
516
+ status: response.status,
517
+ retryAfterMs
518
+ })
519
+ );
520
+ continue;
521
+ }
522
+ throw apiError;
523
+ }
524
+ const successPayload = payload;
525
+ await config.onResponse?.({
526
+ ...hookRequestContext,
527
+ durationMs: Date.now() - startedAt,
528
+ status: response.status,
529
+ response: responseClone,
530
+ correlationId: successPayload.correlationId ?? response.headers.get("x-lucern-correlation-id")?.trim() ?? requestId,
531
+ policyTraceId: successPayload.policyTraceId ?? response.headers.get("x-lucern-policy-trace-id")?.trim() ?? null,
532
+ idempotentReplay: successPayload.idempotentReplay,
533
+ retryAfterMs,
534
+ willRetry: false
535
+ });
536
+ return successPayload;
537
+ } catch (fetchError) {
538
+ if (fetchError instanceof LucernApiError) {
539
+ throw fetchError;
540
+ }
541
+ const willRetry = attempt < maxRetries;
542
+ await config.onResponse?.({
543
+ ...hookRequestContext,
544
+ durationMs: Date.now() - startedAt,
545
+ error: fetchError,
546
+ correlationId: requestId,
547
+ policyTraceId: null,
548
+ willRetry
549
+ });
550
+ lastError = fetchError;
551
+ if (willRetry) {
552
+ await delay(computeRetryDelayMs({ attempt }));
553
+ }
554
+ }
555
+ }
556
+ throw lastError instanceof Error ? lastError : new Error("Platform API request failed after retries.");
557
+ }
558
+ return {
559
+ request
560
+ };
561
+ }
562
+
563
+ // src/sdkSurface.ts
564
+ function createListResult(items, legacyKey) {
565
+ const result = {
566
+ items,
567
+ total: items.length
568
+ };
569
+ if (legacyKey) {
570
+ return {
571
+ ...result,
572
+ [legacyKey]: items
573
+ };
574
+ }
575
+ return result;
576
+ }
577
+ function mapGatewayData(response, mapper) {
578
+ return {
579
+ ...response,
580
+ data: mapper(response.data)
581
+ };
582
+ }
583
+
584
+ // src/boundaryClientSurface.ts
585
+ function cleanOptionalString(value) {
586
+ const normalized = value?.trim();
587
+ return normalized ? normalized : void 0;
588
+ }
589
+ function isRecord2(value) {
590
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
591
+ }
592
+ function cleanRequiredString(value, label) {
593
+ const normalized = cleanOptionalString(value);
594
+ if (!normalized) {
595
+ throw new Error(`${label} is required`);
596
+ }
597
+ return normalized;
598
+ }
599
+ function assertKnownKeys(input, allowed, operation) {
600
+ const allowedSet = new Set(allowed);
601
+ const unknownKeys = Object.keys(input).filter((key) => !allowedSet.has(key));
602
+ if (unknownKeys.length > 0) {
603
+ throw new Error(
604
+ `${operation} received unsupported field(s): ${unknownKeys.join(", ")}`
605
+ );
606
+ }
607
+ }
608
+ function knownPayload(input, allowed, operation) {
609
+ assertKnownKeys(input, allowed, operation);
610
+ return { ...input };
611
+ }
612
+ function listResultFromEnvelope(data, legacyKey) {
613
+ const record = isRecord2(data) ? data : {};
614
+ const legacyItems = record[legacyKey];
615
+ return createListResult(
616
+ Array.isArray(legacyItems) ? legacyItems : Array.isArray(data) ? data : [],
617
+ legacyKey
618
+ );
619
+ }
620
+
621
+ // src/control-plane.ts
622
+ var LucernControlPlaneIdentityError = class extends Error {
623
+ reason;
624
+ principalStatus;
625
+ tenantStatus;
626
+ workspaceStatus;
627
+ details;
628
+ constructor(failure) {
629
+ super(failure.message);
630
+ this.name = "LucernControlPlaneIdentityError";
631
+ this.reason = failure.reason;
632
+ this.principalStatus = failure.principalStatus;
633
+ this.tenantStatus = failure.tenantStatus;
634
+ this.workspaceStatus = failure.workspaceStatus;
635
+ this.details = failure.details;
636
+ }
637
+ };
638
+ function cleanString2(value) {
639
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
640
+ }
641
+ function stringList(value) {
642
+ if (!Array.isArray(value)) {
643
+ return [];
644
+ }
645
+ return [
646
+ ...new Set(
647
+ value.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean)
648
+ )
649
+ ];
650
+ }
651
+ function principalType(value) {
652
+ switch (value) {
653
+ case "service":
654
+ case "service_principal":
655
+ return "service";
656
+ case "agent":
657
+ return "agent";
658
+ case "group":
659
+ return "group";
660
+ case "external_viewer":
661
+ case "external_stakeholder":
662
+ return "external_viewer";
663
+ default:
664
+ return "human";
665
+ }
666
+ }
667
+ function adminFlags(roles) {
668
+ const normalized = roles.map((role) => role.toLowerCase());
669
+ const isPlatformAdmin = normalized.includes("platform_admin");
670
+ const isTenantAdmin = isPlatformAdmin || normalized.includes("tenant_admin");
671
+ const isWorkspaceAdmin = isTenantAdmin || normalized.includes("workspace_admin") || normalized.includes("workspace_owner");
672
+ return { isPlatformAdmin, isTenantAdmin, isWorkspaceAdmin };
673
+ }
674
+ function normalizeResolvedInteractivePrincipal(payload) {
675
+ if ("ok" in payload && payload.ok === false) {
676
+ throw new LucernControlPlaneIdentityError(payload);
677
+ }
678
+ const principalId = cleanString2(payload.principalId);
679
+ const clerkId = cleanString2(payload.clerkId);
680
+ const tenantId = cleanString2(payload.tenantId);
681
+ if (!principalId || !clerkId || !tenantId) {
682
+ throw new LucernControlPlaneIdentityError({
683
+ ok: false,
684
+ reason: "resolver_unavailable",
685
+ message: "Control-plane principal resolver returned an incomplete principal context.",
686
+ principalStatus: payload.principalStatus ?? "missing",
687
+ tenantStatus: payload.tenantStatus,
688
+ workspaceStatus: payload.workspaceStatus
689
+ });
690
+ }
691
+ const roles = stringList(payload.roles);
692
+ const scopes = stringList(payload.scopes);
693
+ const workspaceId = cleanString2(payload.workspaceId) ?? null;
694
+ const flags = adminFlags(roles);
695
+ return {
696
+ principalId,
697
+ principalType: principalType(payload.principalType),
698
+ clerkId,
699
+ tenantId,
700
+ workspaceId,
701
+ roles,
702
+ scopes,
703
+ groupIds: stringList(payload.groupIds),
704
+ permittedToolNames: stringList(payload.permittedToolNames),
705
+ permittedPackKeys: stringList(payload.permittedPackKeys),
706
+ principalStatus: cleanString2(payload.principalStatus) ?? "active",
707
+ tenantStatus: cleanString2(payload.tenantStatus) ?? "active",
708
+ workspaceStatus: cleanString2(payload.workspaceStatus) ?? (workspaceId ? "active" : "none"),
709
+ isPlatformAdmin: typeof payload.isPlatformAdmin === "boolean" ? payload.isPlatformAdmin : flags.isPlatformAdmin,
710
+ isTenantAdmin: typeof payload.isTenantAdmin === "boolean" ? payload.isTenantAdmin : flags.isTenantAdmin,
711
+ isWorkspaceAdmin: typeof payload.isWorkspaceAdmin === "boolean" ? payload.isWorkspaceAdmin : flags.isWorkspaceAdmin,
712
+ permit: {
713
+ subject: cleanString2(payload.permit?.subject) ?? principalId,
714
+ tenant: cleanString2(payload.permit?.tenant) ?? tenantId,
715
+ ...workspaceId ? { workspace: cleanString2(payload.permit?.workspace) ?? workspaceId } : {}
716
+ },
717
+ authMode: "interactive_user",
718
+ sessionId: payload.sessionId,
719
+ delegatedBy: payload.delegatedBy,
720
+ expiresAt: payload.expiresAt
721
+ };
722
+ }
723
+
724
+ // src/identityClient.ts
725
+ function createIdentityWhoamiClient(config = {}) {
726
+ const gateway = createGatewayRequestClient(config);
727
+ return {
728
+ async whoami() {
729
+ return gateway.request({
730
+ path: "/api/platform/v1/identity/whoami"
731
+ });
732
+ }
733
+ };
734
+ }
735
+ var TENANT_IDENTITY_FIELDS = [
736
+ "tenantId",
737
+ "workspaceId",
738
+ "principalId",
739
+ "integrationKey",
740
+ "secretRef",
741
+ "policySubject",
742
+ "policyAction",
743
+ "policyResource",
744
+ "decision",
745
+ "config",
746
+ "configKey",
747
+ "configValue",
748
+ "provider",
749
+ "status",
750
+ "metadata",
751
+ "limit",
752
+ "cursor"
753
+ ];
754
+ function tenantIdentityQuery(input) {
755
+ return {
756
+ tenantId: cleanRequiredString(input.tenantId, "tenantId"),
757
+ workspaceId: input.workspaceId,
758
+ principalId: input.principalId,
759
+ limit: input.limit,
760
+ cursor: input.cursor
761
+ };
762
+ }
763
+ function tenantIdentityBody(input, operation) {
764
+ return knownPayload(input, TENANT_IDENTITY_FIELDS, operation);
765
+ }
766
+ function createIdentityClient(config = {}) {
767
+ const gateway = createGatewayRequestClient(config);
768
+ const whoamiClient = createIdentityWhoamiClient(config);
769
+ const requestPrincipalWrite = (method, input, idempotencyKey) => gateway.request({
770
+ path: "/api/platform/v1/identity/principals",
771
+ method,
772
+ body: input,
773
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
774
+ });
775
+ const updatePrincipal = (input, idempotencyKey) => requestPrincipalWrite("PATCH", input, idempotencyKey);
776
+ const deleteKey = (keyId, input = {}, idempotencyKey) => gateway.request({
777
+ path: `/api/platform/v1/identity/keys/${encodeURIComponent(keyId)}/revoke`,
778
+ method: "POST",
779
+ body: input,
780
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
781
+ });
782
+ return {
783
+ /**
784
+ * Resolve the current authenticated identity summary.
785
+ */
786
+ async whoami() {
787
+ return whoamiClient.whoami().then(
788
+ (response) => mapGatewayData(response, (data) => ({
789
+ principalId: data.principalId,
790
+ principalType: data.principalType,
791
+ clerkId: data.clerkId,
792
+ tenantId: data.tenantId ?? null,
793
+ workspaceId: data.workspaceId ?? null,
794
+ scopes: Array.isArray(data.scopes) ? data.scopes : [],
795
+ roles: Array.isArray(data.roles) ? data.roles : [],
796
+ groupIds: Array.isArray(data.groupIds) ? data.groupIds : [],
797
+ permittedToolNames: Array.isArray(data.permittedToolNames) ? data.permittedToolNames : [],
798
+ permittedPackKeys: Array.isArray(data.permittedPackKeys) ? data.permittedPackKeys : [],
799
+ principalStatus: data.principalStatus,
800
+ tenantStatus: data.tenantStatus,
801
+ workspaceStatus: data.workspaceStatus,
802
+ isPlatformAdmin: data.isPlatformAdmin === true,
803
+ isTenantAdmin: data.isTenantAdmin === true,
804
+ isWorkspaceAdmin: data.isWorkspaceAdmin === true,
805
+ permit: data.permit ?? (data.tenantId ? {
806
+ subject: data.principalId,
807
+ tenant: data.tenantId,
808
+ ...data.workspaceId ? { workspace: data.workspaceId } : {}
809
+ } : void 0),
810
+ authMode: data.authMode,
811
+ sessionId: data.sessionId,
812
+ delegatedBy: data.delegatedBy,
813
+ expiresAt: data.expiresAt
814
+ }))
815
+ );
816
+ },
817
+ /**
818
+ * Resolve a Clerk subject through the tenant control-plane Permit projection.
819
+ * @deprecated Prefer lucern.controlPlane.identity.resolveInteractivePrincipal().
820
+ */
821
+ async resolveInteractivePrincipal(input) {
822
+ return gateway.request({
823
+ path: "/api/platform/v1/control-plane/identity/resolve-interactive-principal",
824
+ method: "POST",
825
+ body: input
826
+ }).then(
827
+ (response) => mapGatewayData(response, normalizeResolvedInteractivePrincipal)
828
+ );
829
+ },
830
+ /**
831
+ * List principals in the current identity scope.
832
+ */
833
+ async listPrincipals(query = {}) {
834
+ return gateway.request({
835
+ path: `/api/platform/v1/identity/principals${toQueryString(query)}`
836
+ }).then(
837
+ (response) => mapGatewayData(
838
+ response,
839
+ (data) => createListResult(
840
+ Array.isArray(data) ? data : [],
841
+ "principals"
842
+ )
843
+ )
844
+ );
845
+ },
846
+ /**
847
+ * Create a principal.
848
+ */
849
+ async createPrincipal(input, idempotencyKey) {
850
+ return requestPrincipalWrite("POST", input, idempotencyKey);
851
+ },
852
+ /**
853
+ * Update a principal.
854
+ */
855
+ updatePrincipal,
856
+ /**
857
+ * @deprecated Use createPrincipal or updatePrincipal.
858
+ */
859
+ upsertPrincipal: updatePrincipal,
860
+ /**
861
+ * List keys in the current identity scope.
862
+ */
863
+ async listKeys(query = {}) {
864
+ return gateway.request({
865
+ path: `/api/platform/v1/identity/keys${toQueryString(query)}`
866
+ }).then(
867
+ (response) => mapGatewayData(
868
+ response,
869
+ (data) => createListResult(Array.isArray(data) ? data : [], "keys")
870
+ )
871
+ );
872
+ },
873
+ /**
874
+ * Create an API key.
875
+ */
876
+ async createKey(input, idempotencyKey) {
877
+ return gateway.request({
878
+ path: "/api/platform/v1/identity/keys",
879
+ method: "POST",
880
+ body: input,
881
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
882
+ });
883
+ },
884
+ /**
885
+ * Rotate an API key.
886
+ */
887
+ async rotateKey(keyId, input = {}, idempotencyKey) {
888
+ return gateway.request({
889
+ path: `/api/platform/v1/identity/keys/${encodeURIComponent(keyId)}/rotate`,
890
+ method: "POST",
891
+ body: input,
892
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
893
+ });
894
+ },
895
+ /**
896
+ * Delete an API key by revoking it.
897
+ */
898
+ deleteKey,
899
+ /**
900
+ * @deprecated Use deleteKey.
901
+ */
902
+ revokeKey: deleteKey,
903
+ /**
904
+ * Search Clerk users by email or display attributes.
905
+ */
906
+ async searchClerkUsers(q) {
907
+ return gateway.request({
908
+ path: `/api/platform/v1/identity/clerk-users${toQueryString({ q })}`
909
+ });
910
+ },
911
+ async getTenantConfig(input) {
912
+ return gateway.request({
913
+ path: `/api/platform/v1/identity/tenant-config${toQueryString(
914
+ tenantIdentityQuery(input)
915
+ )}`
916
+ });
917
+ },
918
+ async updateTenantConfig(input, idempotencyKey) {
919
+ cleanRequiredString(input.tenantId, "tenantId");
920
+ return gateway.request({
921
+ path: "/api/platform/v1/identity/tenant-config",
922
+ method: "PATCH",
923
+ body: tenantIdentityBody(
924
+ input,
925
+ "identity.updateTenantConfig"
926
+ ),
927
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
928
+ });
929
+ },
930
+ async listIntegrations(input) {
931
+ return gateway.request({
932
+ path: `/api/platform/v1/identity/integrations${toQueryString(
933
+ tenantIdentityQuery(input)
934
+ )}`
935
+ }).then(
936
+ (response) => mapGatewayData(
937
+ response,
938
+ (data) => listResultFromEnvelope(
939
+ data,
940
+ "integrations"
941
+ )
942
+ )
943
+ );
944
+ },
945
+ async upsertIntegration(input, idempotencyKey) {
946
+ cleanRequiredString(input.tenantId, "tenantId");
947
+ cleanRequiredString(input.integrationKey, "integrationKey");
948
+ return gateway.request({
949
+ path: "/api/platform/v1/identity/integrations",
950
+ method: "PUT",
951
+ body: tenantIdentityBody(
952
+ input,
953
+ "identity.upsertIntegration"
954
+ ),
955
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
956
+ });
957
+ },
958
+ async listSecrets(input) {
959
+ return gateway.request({
960
+ path: `/api/platform/v1/identity/secrets${toQueryString(
961
+ tenantIdentityQuery(input)
962
+ )}`
963
+ }).then(
964
+ (response) => mapGatewayData(
965
+ response,
966
+ (data) => listResultFromEnvelope(
967
+ data,
968
+ "secrets"
969
+ )
970
+ )
971
+ );
972
+ },
973
+ async putSecretReference(input, idempotencyKey) {
974
+ cleanRequiredString(input.tenantId, "tenantId");
975
+ cleanRequiredString(input.secretRef, "secretRef");
976
+ return gateway.request({
977
+ path: "/api/platform/v1/identity/secrets",
978
+ method: "PUT",
979
+ body: tenantIdentityBody(
980
+ input,
981
+ "identity.putSecretReference"
982
+ ),
983
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
984
+ });
985
+ },
986
+ async evaluatePolicy(input, idempotencyKey) {
987
+ cleanRequiredString(input.tenantId, "tenantId");
988
+ cleanRequiredString(input.policySubject, "policySubject");
989
+ cleanRequiredString(input.policyAction, "policyAction");
990
+ cleanRequiredString(input.policyResource, "policyResource");
991
+ return gateway.request({
992
+ path: "/api/platform/v1/identity/policy/evaluate",
993
+ method: "POST",
994
+ body: tenantIdentityBody(
995
+ input,
996
+ "identity.evaluatePolicy"
997
+ ),
998
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
999
+ });
1000
+ },
1001
+ async recordPolicyDecision(input, idempotencyKey) {
1002
+ cleanRequiredString(input.tenantId, "tenantId");
1003
+ cleanRequiredString(input.decision, "decision");
1004
+ return gateway.request({
1005
+ path: "/api/platform/v1/identity/policy/decisions",
1006
+ method: "POST",
1007
+ body: tenantIdentityBody(
1008
+ input,
1009
+ "identity.recordPolicyDecision"
1010
+ ),
1011
+ idempotencyKey: idempotencyKey ?? randomIdempotencyKey()
1012
+ });
1013
+ }
1014
+ };
1015
+ }
1016
+
1017
+ // src/accessControl.ts
1018
+ var LucernAccessControlError = class extends LucernSdkAuthContextError {
1019
+ policyDecision;
1020
+ constructor(reason, message, policyDecision) {
1021
+ super(reason, message);
1022
+ this.name = "LucernAccessControlError";
1023
+ this.policyDecision = policyDecision;
1024
+ }
1025
+ };
1026
+ function cleanString3(value) {
1027
+ const normalized = value?.trim();
1028
+ return normalized ? normalized : void 0;
1029
+ }
1030
+ function cleanStringList2(values) {
1031
+ if (!values) {
1032
+ return [];
1033
+ }
1034
+ return [
1035
+ ...new Set(
1036
+ values.map((value) => value.trim()).filter((value) => value.length > 0)
1037
+ )
1038
+ ];
1039
+ }
1040
+ function requireString2(value, reason, label) {
1041
+ const normalized = cleanString3(value);
1042
+ if (!normalized) {
1043
+ throw new LucernAccessControlError(
1044
+ reason,
1045
+ `Lucern SDK access control requires ${label}.`
1046
+ );
1047
+ }
1048
+ return normalized;
1049
+ }
1050
+ function normalizePrincipalType(principalType2) {
1051
+ if (principalType2 === "agent") {
1052
+ return "agent";
1053
+ }
1054
+ if (principalType2 === "service") {
1055
+ return "service";
1056
+ }
1057
+ if (principalType2 === "group") {
1058
+ return "group";
1059
+ }
1060
+ if (principalType2 === "external_viewer") {
1061
+ return "external_viewer";
1062
+ }
1063
+ return "human";
1064
+ }
1065
+ function aliasKey(alias) {
1066
+ return `${alias.provider}:${alias.providerProjectId ?? ""}:${alias.externalSubjectId}`;
1067
+ }
1068
+ function normalizeAliases(input, canonicalClerkUserId) {
1069
+ const aliases = /* @__PURE__ */ new Map();
1070
+ for (const alias of input ?? []) {
1071
+ const externalSubjectId = cleanString3(alias.externalSubjectId);
1072
+ if (!externalSubjectId) {
1073
+ continue;
1074
+ }
1075
+ const normalized = {
1076
+ provider: cleanString3(alias.provider) ?? "clerk",
1077
+ providerProjectId: cleanString3(alias.providerProjectId),
1078
+ externalSubjectId,
1079
+ status: cleanString3(alias.status)
1080
+ };
1081
+ aliases.set(aliasKey(normalized), normalized);
1082
+ }
1083
+ if (canonicalClerkUserId) {
1084
+ const canonicalAlias = {
1085
+ provider: "clerk",
1086
+ externalSubjectId: canonicalClerkUserId,
1087
+ status: "active"
1088
+ };
1089
+ aliases.set(aliasKey(canonicalAlias), canonicalAlias);
1090
+ }
1091
+ return [...aliases.values()];
1092
+ }
1093
+ function isKnownClerkSubject(args) {
1094
+ if (args.clerkId === args.canonicalClerkUserId) {
1095
+ return true;
1096
+ }
1097
+ return args.aliases.some(
1098
+ (alias) => alias.provider === "clerk" && alias.externalSubjectId === args.clerkId
1099
+ );
1100
+ }
1101
+ function authContextToPrincipalInput(input) {
1102
+ const normalized = normalizeCanonicalLucernAuthContext(input);
1103
+ return {
1104
+ principalId: normalized.principalId,
1105
+ principalType: normalized.principalType,
1106
+ canonicalClerkUserId: normalized.clerkId,
1107
+ clerkId: normalized.clerkId,
1108
+ tenantId: normalized.tenantId,
1109
+ workspaceId: normalized.workspaceId,
1110
+ roles: normalized.roles,
1111
+ scopes: normalized.scopes
1112
+ };
1113
+ }
1114
+ function isAuthContextInput(input) {
1115
+ return "authMode" in input || "permit" in input || "delegationChain" in input;
1116
+ }
1117
+ function normalizeCanonicalPrincipalIdentity(input, options = {}) {
1118
+ const principalInput = isAuthContextInput(input) ? authContextToPrincipalInput(input) : input;
1119
+ const principalId = requireString2(
1120
+ principalInput.principalId,
1121
+ "principal_missing",
1122
+ "principalId"
1123
+ );
1124
+ const principalType2 = normalizePrincipalType(principalInput.principalType);
1125
+ const observedClerkId = cleanString3(options.observedClerkId);
1126
+ const canonicalClerkUserId = cleanString3(principalInput.canonicalClerkUserId) ?? cleanString3(principalInput.clerkId);
1127
+ if (principalType2 === "human" && !canonicalClerkUserId) {
1128
+ throw new LucernAccessControlError(
1129
+ "clerk_alias_missing",
1130
+ "Human principals require one canonical Clerk user id."
1131
+ );
1132
+ }
1133
+ const aliases = normalizeAliases(
1134
+ principalInput.clerkIdentityAliases,
1135
+ canonicalClerkUserId
1136
+ );
1137
+ if (observedClerkId && !isKnownClerkSubject({
1138
+ clerkId: observedClerkId,
1139
+ canonicalClerkUserId,
1140
+ aliases
1141
+ })) {
1142
+ throw new LucernAccessControlError(
1143
+ "clerk_alias_unrecognized",
1144
+ "Observed Clerk user id does not match the canonical human principal id."
1145
+ );
1146
+ }
1147
+ return {
1148
+ principalId,
1149
+ principalType: principalType2,
1150
+ canonicalClerkUserId,
1151
+ clerkIdentityAliases: aliases,
1152
+ tenantId: cleanString3(principalInput.tenantId),
1153
+ workspaceId: cleanString3(principalInput.workspaceId),
1154
+ roles: cleanStringList2(principalInput.roles),
1155
+ scopes: cleanStringList2(principalInput.scopes)
1156
+ };
1157
+ }
1158
+ function formatPermitResource(resource) {
1159
+ if (typeof resource === "string") {
1160
+ return requireString2(resource, "policy_denied", "policyResource");
1161
+ }
1162
+ const type = requireString2(resource.type, "policy_denied", "resource.type");
1163
+ const key = requireString2(resource.key, "policy_denied", "resource.key");
1164
+ return key.startsWith(`${type}:`) ? key : `${type}:${key}`;
1165
+ }
1166
+ function resourceRequiresWorkspace(resource) {
1167
+ if (typeof resource === "string") {
1168
+ return !resource.startsWith("tenant:");
1169
+ }
1170
+ return resource.type !== "tenant";
1171
+ }
1172
+ function buildPolicyInput(identity, input) {
1173
+ const tenantId = requireString2(
1174
+ input.tenantId ?? identity.tenantId,
1175
+ "tenant_missing",
1176
+ "tenantId"
1177
+ );
1178
+ const workspaceId = cleanString3(input.workspaceId ?? identity.workspaceId);
1179
+ if (resourceRequiresWorkspace(input.resource) && !workspaceId) {
1180
+ throw new LucernAccessControlError(
1181
+ "workspace_missing",
1182
+ "Workspace-scoped Permit checks require workspaceId."
1183
+ );
1184
+ }
1185
+ return {
1186
+ tenantId,
1187
+ workspaceId,
1188
+ principalId: identity.principalId,
1189
+ policySubject: identity.principalId,
1190
+ policyAction: requireString2(input.action, "policy_denied", "policyAction"),
1191
+ policyResource: formatPermitResource(input.resource),
1192
+ metadata: input.context
1193
+ };
1194
+ }
1195
+ async function resolveConfiguredPrincipalInput(authContext) {
1196
+ if (typeof authContext === "function") {
1197
+ return await authContext();
1198
+ }
1199
+ return authContext;
1200
+ }
1201
+ function assertPermitAllowed(decision) {
1202
+ if (decision.decision !== "allow") {
1203
+ throw new LucernAccessControlError(
1204
+ decision.decision === "deny" ? "policy_denied" : "policy_unknown",
1205
+ `Permit denied ${decision.policyAction} on ${decision.policyResource}.`,
1206
+ decision
1207
+ );
1208
+ }
1209
+ }
1210
+ function createAccessControlClient(config = {}) {
1211
+ const identityClient = createIdentityClient(config);
1212
+ async function resolveIdentity(input, observedClerkId) {
1213
+ const identityInput = input ?? await resolveConfiguredPrincipalInput(config.authContext);
1214
+ if (!identityInput) {
1215
+ throw new LucernAccessControlError(
1216
+ "principal_missing",
1217
+ "Lucern SDK access control requires a canonical principal identity."
1218
+ );
1219
+ }
1220
+ return normalizeCanonicalPrincipalIdentity(identityInput, {
1221
+ observedClerkId
1222
+ });
1223
+ }
1224
+ async function checkAccess(input, idempotencyKey) {
1225
+ const identity = await resolveIdentity(input.identity, input.observedClerkId);
1226
+ const policyInput = buildPolicyInput(identity, input);
1227
+ try {
1228
+ const response = await identityClient.evaluatePolicy(
1229
+ policyInput,
1230
+ idempotencyKey
1231
+ );
1232
+ return {
1233
+ identity,
1234
+ policyInput,
1235
+ decision: response.data
1236
+ };
1237
+ } catch (error) {
1238
+ if (error instanceof LucernSdkAuthContextError) {
1239
+ throw error;
1240
+ }
1241
+ throw new LucernAccessControlError(
1242
+ "policy_unavailable",
1243
+ "Permit policy check failed closed before an allow decision was returned."
1244
+ );
1245
+ }
1246
+ }
1247
+ async function requireAccess(input, idempotencyKey) {
1248
+ const result = await checkAccess(input, idempotencyKey);
1249
+ assertPermitAllowed(result.decision);
1250
+ return result;
1251
+ }
1252
+ async function canAccess(input, idempotencyKey) {
1253
+ try {
1254
+ await requireAccess(input, idempotencyKey);
1255
+ return true;
1256
+ } catch {
1257
+ return false;
1258
+ }
1259
+ }
1260
+ return {
1261
+ normalizePrincipal: normalizeCanonicalPrincipalIdentity,
1262
+ checkAccess,
1263
+ requireAccess,
1264
+ canAccess
1265
+ };
1266
+ }
1267
+
1268
+ export { LucernAccessControlError, assertPermitAllowed, createAccessControlClient, formatPermitResource, normalizeCanonicalPrincipalIdentity };
1269
+ //# sourceMappingURL=accessControl.js.map
1270
+ //# sourceMappingURL=accessControl.js.map