@experiture/xyra-cli 0.6.0 → 0.6.2

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.
@@ -1,126 +1,668 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ConfigStore = void 0;
4
- exports.validateEnvironment = validateEnvironment;
5
- const node_fs_1 = require("node:fs");
6
- const node_os_1 = require("node:os");
7
- const node_path_1 = require("node:path");
8
- const CliError_1 = require("../errors/CliError");
9
- const environments_1 = require("./environments");
10
- const CONFIG_DIR = process.env.XYRA_CLI_CONFIG_DIR ?? (0, node_path_1.join)((0, node_os_1.homedir)(), '.config', 'xyra');
11
- const CONFIG_PATH = (0, node_path_1.join)(CONFIG_DIR, 'config.json');
12
- function requireHttpsOrTest(name, url) {
13
- let parsed;
14
- try {
15
- parsed = new URL(url);
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // ../../libs/xyra-types/dist/xyra-administration.js
34
+ var require_xyra_administration = __commonJS({
35
+ "../../libs/xyra-types/dist/xyra-administration.js"(exports2) {
36
+ "use strict";
37
+ Object.defineProperty(exports2, "__esModule", { value: true });
38
+ exports2.runtimeAdministrationTarget = runtimeAdministrationTarget;
39
+ exports2.parseXyraAdministrationTargetV1 = parseXyraAdministrationTargetV12;
40
+ exports2.xyraAdministrationTargetKeyV1 = xyraAdministrationTargetKeyV1;
41
+ exports2.parseXyraAdministrationResolvedTargetV1 = parseXyraAdministrationResolvedTargetV1;
42
+ exports2.parseXyraAdministrationDecisionV1 = parseXyraAdministrationDecisionV1;
43
+ function runtimeAdministrationTarget(identity) {
44
+ return identity.licenseSourceProductId !== identity.licensedProductId && identity.tenantId === identity.licenseOwnerTenantId ? {
45
+ targetKind: "configuration-owner",
46
+ configurationTenantId: identity.licenseOwnerTenantId,
47
+ managedProductId: identity.licenseSourceProductId
48
+ } : { targetKind: "customer-resource", targetTenantId: identity.tenantId, activeProductId: identity.productId };
16
49
  }
17
- catch {
18
- throw new CliError_1.CliError(CliError_1.CliErrorCodes.ConfigInvalid, `Environment '${name}' has an invalid URL: ${url}`);
50
+ var identifier = (value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,49}$/.test(value);
51
+ var guid = (value) => typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value) && value !== "00000000-0000-0000-0000-000000000000";
52
+ var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
53
+ var exact = (value, keys) => Object.keys(value).length === keys.length && keys.every((key) => Object.prototype.hasOwnProperty.call(value, key));
54
+ function parseXyraAdministrationTargetV12(value) {
55
+ if (!record(value))
56
+ return null;
57
+ if (value.targetKind === "global-resource" && exact(value, ["targetKind", "managedProductId"]) && value.managedProductId === "xyra-ai") {
58
+ return { targetKind: "global-resource", managedProductId: "xyra-ai" };
59
+ }
60
+ if (value.targetKind === "configuration-owner" && exact(value, ["targetKind", "configurationTenantId", "managedProductId"]) && identifier(value.configurationTenantId) && identifier(value.managedProductId)) {
61
+ return {
62
+ targetKind: "configuration-owner",
63
+ configurationTenantId: value.configurationTenantId,
64
+ managedProductId: value.managedProductId
65
+ };
66
+ }
67
+ if (value.targetKind === "customer-resource" && exact(value, ["targetKind", "targetTenantId", "activeProductId"]) && identifier(value.targetTenantId) && identifier(value.activeProductId)) {
68
+ return { targetKind: "customer-resource", targetTenantId: value.targetTenantId, activeProductId: value.activeProductId };
69
+ }
70
+ return null;
19
71
  }
20
- const isTestDomain = parsed.hostname.endsWith('.test');
21
- if (parsed.protocol !== 'https:' && !isTestDomain) {
22
- throw new CliError_1.CliError(CliError_1.CliErrorCodes.ConfigInvalid, `Environment '${name}' must use https (got ${parsed.protocol}//${parsed.host}).`);
72
+ function xyraAdministrationTargetKeyV1(target) {
73
+ return JSON.stringify(target.targetKind === "global-resource" ? [target.targetKind, target.managedProductId] : target.targetKind === "configuration-owner" ? [target.targetKind, target.configurationTenantId, target.managedProductId] : [target.targetKind, target.targetTenantId, target.activeProductId]);
23
74
  }
24
- }
25
- function requireHttpOrigin(name, url) {
26
- let parsed;
27
- try {
28
- parsed = new URL(url);
75
+ function parseXyraAdministrationResolvedTargetV1(value, target) {
76
+ if (!record(value) || value.targetKind !== target.targetKind)
77
+ return null;
78
+ const managedProductId = target.targetKind === "customer-resource" ? "xyra-ai" : target.managedProductId;
79
+ if (value.managedProductId !== managedProductId)
80
+ return null;
81
+ if (target.targetKind === "global-resource") {
82
+ return exact(value, ["targetKind", "managedProductId", "relationshipKind"]) && value.relationshipKind === "global-resource" ? { targetKind: "global-resource", managedProductId: "xyra-ai", relationshipKind: "global-resource" } : null;
83
+ }
84
+ const base = ["targetKind", "managedProductId", "relationshipKind", "activeProductId", "actualTenantId", "licensedProductId", "commercialState"];
85
+ const embedded = ["licenseSourceProductId", "licenseOwnerTenantId", "bindingId", "entitlementId", "sourceEntitlementId"];
86
+ const isNative = value.relationshipKind === "native-product-tenant";
87
+ if (!isNative && value.relationshipKind !== "embedded-product-entitlement" || !exact(value, isNative ? base : [...base, ...embedded]) || value.licensedProductId !== "xyra-ai" || !base.filter((key) => !["targetKind", "relationshipKind"].includes(key)).every((key) => identifier(value[key])) || (isNative ? value.activeProductId !== "xyra-ai" : !embedded.every((key) => identifier(value[key]))) || value.actualTenantId !== (target.targetKind === "customer-resource" ? target.targetTenantId : target.configurationTenantId) || target.targetKind === "customer-resource" && value.activeProductId !== target.activeProductId || target.targetKind === "configuration-owner" && value.activeProductId !== target.managedProductId || !isNative && (value.activeProductId !== value.licenseSourceProductId && value.activeProductId !== value.licensedProductId || !["bindingId", "entitlementId", "sourceEntitlementId"].every((key) => guid(value[key])) || target.targetKind === "configuration-owner" && (value.licenseOwnerTenantId !== target.configurationTenantId || value.licenseSourceProductId !== target.managedProductId)))
88
+ return null;
89
+ return { ...value };
29
90
  }
30
- catch {
31
- throw new CliError_1.CliError(CliError_1.CliErrorCodes.ConfigInvalid, `Environment '${name}' has an invalid URL: ${url}`);
91
+ function parseXyraAdministrationDecisionV1(value, request, purpose) {
92
+ if (!record(value) || !exact(value, [
93
+ "operationId",
94
+ "purpose",
95
+ "accessPurpose",
96
+ "allowed",
97
+ "code",
98
+ "productId",
99
+ "operatorTenantId",
100
+ "targetTenantId",
101
+ "grantId",
102
+ "target",
103
+ "resolvedTarget",
104
+ ...Object.prototype.hasOwnProperty.call(value, "configurationAccess") ? ["configurationAccess"] : []
105
+ ]) || value.configurationAccess !== void 0 && !["read", "manage", "manage_selection"].includes(String(value.configurationAccess)) || value.operationId !== request.operationId || value.purpose !== purpose || value.accessPurpose !== "administration" || value.productId !== "xyra-ai" || typeof value.allowed !== "boolean" || typeof value.code !== "string" || !/^[A-Z0-9_.]{1,160}$/.test(value.code) || !(value.operatorTenantId === null || identifier(value.operatorTenantId)) || !(value.grantId === null || guid(value.grantId)))
106
+ return null;
107
+ const target = parseXyraAdministrationTargetV12(value.target);
108
+ if (!target || xyraAdministrationTargetKeyV1(target) !== xyraAdministrationTargetKeyV1(request.target) || value.targetTenantId !== (target.targetKind === "global-resource" ? null : target.targetKind === "configuration-owner" ? target.configurationTenantId : target.targetTenantId))
109
+ return null;
110
+ const resolvedTarget = parseXyraAdministrationResolvedTargetV1(value.resolvedTarget, target);
111
+ if (value.allowed) {
112
+ if (!resolvedTarget)
113
+ return null;
114
+ if (value.code === "AUTHORIZATION.ALLOWED.SAME_TENANT") {
115
+ if (target.targetKind !== "customer-resource" || value.operatorTenantId !== target.targetTenantId || value.grantId !== null)
116
+ return null;
117
+ } else if (value.code === "AUTHORIZATION.ALLOWED.SUPER_USER" ? value.operatorTenantId !== null || value.grantId !== null : !["AUTHORIZATION.ALLOWED", "AUTHORIZATION.ALLOWED.LICENSEE"].includes(value.code) || value.operatorTenantId === null || value.grantId === null)
118
+ return null;
119
+ if (value.code === "AUTHORIZATION.ALLOWED.LICENSEE" && (target.targetKind === "global-resource" || resolvedTarget.relationshipKind !== "embedded-product-entitlement" || resolvedTarget.licenseOwnerTenantId !== value.operatorTenantId))
120
+ return null;
121
+ } else if (value.code.startsWith("AUTHORIZATION.ALLOWED") || value.resolvedTarget !== null)
122
+ return null;
123
+ return { ...value, target, resolvedTarget };
32
124
  }
33
- const isLocalhost = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1';
34
- const isTestDomain = parsed.hostname.endsWith('.test');
35
- const allowedProtocol = parsed.protocol === 'https:' || (parsed.protocol === 'http:' && (isLocalhost || isTestDomain));
36
- if (!allowedProtocol || parsed.username || parsed.password || parsed.search || parsed.hash
37
- || (parsed.pathname !== '/' && parsed.pathname !== '')) {
38
- throw new CliError_1.CliError(CliError_1.CliErrorCodes.ConfigInvalid, `Environment '${name}' must be an HTTP(S) origin without credentials, path, query, or fragment.`);
125
+ }
126
+ });
127
+
128
+ // ../../libs/xyra-types/dist/canonical-runtime-json.js
129
+ var require_canonical_runtime_json = __commonJS({
130
+ "../../libs/xyra-types/dist/canonical-runtime-json.js"(exports2) {
131
+ "use strict";
132
+ Object.defineProperty(exports2, "__esModule", { value: true });
133
+ exports2.MAXIMUM_BOUNDED_RUNTIME_JSON_BYTES_V1 = exports2.BoundedRuntimeJsonErrorV1 = exports2.CanonicalRuntimeJsonErrorV1 = void 0;
134
+ exports2.canonicalRuntimeJsonV1 = canonicalRuntimeJsonV1;
135
+ exports2.canonicalRuntimeUtf8BytesV1 = canonicalRuntimeUtf8BytesV1;
136
+ exports2.canonicalRuntimeUtf8ByteLengthV1 = canonicalRuntimeUtf8ByteLengthV1;
137
+ exports2.boundedRuntimeDataV1 = boundedRuntimeDataV1;
138
+ exports2.boundedRuntimeJsonDataV1 = boundedRuntimeJsonDataV1;
139
+ exports2.parseBoundedRuntimeJsonV1 = parseBoundedRuntimeJsonV12;
140
+ var CanonicalRuntimeJsonErrorV1 = class extends TypeError {
141
+ constructor(reason, path) {
142
+ super(`Canonical runtime JSON rejected ${reason} at ${path}.`);
143
+ this.reason = reason;
144
+ this.path = path;
145
+ this.code = "XYRA.RUNTIME.CANONICAL_JSON_INVALID";
146
+ this.name = "CanonicalRuntimeJsonErrorV1";
147
+ }
148
+ };
149
+ exports2.CanonicalRuntimeJsonErrorV1 = CanonicalRuntimeJsonErrorV1;
150
+ function invalid(reason, path) {
151
+ throw new CanonicalRuntimeJsonErrorV1(reason, path);
39
152
  }
40
- }
41
- function validateEnvironment(env) {
42
- for (const [field, url] of [
43
- ['mcpUrl', env.mcpUrl],
44
- ['authorizationEndpoint', env.authorizationEndpoint],
45
- ['tokenEndpoint', env.tokenEndpoint],
46
- ]) {
47
- if (!url) {
48
- throw new CliError_1.CliError(CliError_1.CliErrorCodes.ConfigInvalid, `Environment '${env.name}' is missing ${field}.`);
153
+ function compareOrdinal(left, right) {
154
+ return left < right ? -1 : left > right ? 1 : 0;
155
+ }
156
+ function objectPath(parent, key) {
157
+ return `${parent}[${JSON.stringify(key)}]`;
158
+ }
159
+ function assertCanonicalString(value, path) {
160
+ for (let index = 0; index < value.length; index += 1) {
161
+ const codeUnit = value.charCodeAt(index);
162
+ if (codeUnit === 0)
163
+ invalid("invalid_unicode", path);
164
+ if (codeUnit >= 55296 && codeUnit <= 56319) {
165
+ const next = value.charCodeAt(index + 1);
166
+ if (!(next >= 56320 && next <= 57343))
167
+ invalid("invalid_unicode", path);
168
+ index += 1;
169
+ } else if (codeUnit >= 56320 && codeUnit <= 57343) {
170
+ invalid("invalid_unicode", path);
49
171
  }
50
- requireHttpsOrTest(`${env.name}.${field}`, url);
172
+ }
51
173
  }
52
- if (!env.orchestratorUrl) {
53
- throw new CliError_1.CliError(CliError_1.CliErrorCodes.ConfigInvalid, `Environment '${env.name}' is missing orchestratorUrl.`);
174
+ function isPlainJsonObject(value) {
175
+ const prototype = Object.getPrototypeOf(value);
176
+ return prototype === Object.prototype || prototype === null;
54
177
  }
55
- requireHttpOrigin(`${env.name}.orchestratorUrl`, env.orchestratorUrl);
56
- if (!env.clientId) {
57
- throw new CliError_1.CliError(CliError_1.CliErrorCodes.ConfigInvalid, `Environment '${env.name}' is missing clientId.`);
178
+ function canonicalize(value, path, ancestors) {
179
+ if (value === null || typeof value === "boolean")
180
+ return value;
181
+ if (typeof value === "string") {
182
+ assertCanonicalString(value, path);
183
+ return value;
184
+ }
185
+ if (typeof value === "number") {
186
+ if (!Number.isFinite(value))
187
+ invalid("non_finite_number", path);
188
+ return value;
189
+ }
190
+ if (typeof value !== "object")
191
+ invalid("unsupported_value", path);
192
+ if (ancestors.has(value))
193
+ invalid("cyclic_value", path);
194
+ ancestors.add(value);
195
+ try {
196
+ if (Array.isArray(value)) {
197
+ if (Object.getOwnPropertySymbols(value).length > 0)
198
+ invalid("symbol_key", path);
199
+ const ownKeys = Object.keys(value);
200
+ if (ownKeys.length !== value.length)
201
+ invalid("sparse_array", path);
202
+ const result2 = [];
203
+ for (let index = 0; index < value.length; index += 1) {
204
+ if (!Object.prototype.hasOwnProperty.call(value, index))
205
+ invalid("sparse_array", `${path}[${index}]`);
206
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
207
+ if (!descriptor || descriptor.get || descriptor.set)
208
+ invalid("accessor_property", `${path}[${index}]`);
209
+ result2.push(canonicalize(descriptor.value, `${path}[${index}]`, ancestors));
210
+ }
211
+ return result2;
212
+ }
213
+ if (!isPlainJsonObject(value))
214
+ invalid("non_plain_object", path);
215
+ if (Object.getOwnPropertySymbols(value).length > 0)
216
+ invalid("symbol_key", path);
217
+ const result = {};
218
+ for (const key of Object.keys(value).sort(compareOrdinal)) {
219
+ assertCanonicalString(key, objectPath(path, key));
220
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
221
+ if (!descriptor || descriptor.get || descriptor.set) {
222
+ invalid("accessor_property", objectPath(path, key));
223
+ }
224
+ result[key] = canonicalize(descriptor.value, objectPath(path, key), ancestors);
225
+ }
226
+ return result;
227
+ } finally {
228
+ ancestors.delete(value);
229
+ }
58
230
  }
59
- if (!env.redirectPath.startsWith('/')) {
60
- throw new CliError_1.CliError(CliError_1.CliErrorCodes.ConfigInvalid, `Environment '${env.name}' redirectPath must start with '/'.`);
231
+ function canonicalRuntimeJsonV1(value) {
232
+ return JSON.stringify(canonicalize(value, "$", /* @__PURE__ */ new Set()));
61
233
  }
62
- }
63
- class ConfigStore {
64
- path;
65
- activeEnvironmentOverride;
66
- constructor(path = CONFIG_PATH, activeEnvironmentOverride) {
67
- this.path = path;
68
- this.activeEnvironmentOverride = activeEnvironmentOverride;
69
- }
70
- load() {
71
- if (!(0, node_fs_1.existsSync)(this.path)) {
72
- return {
73
- activeEnvironment: this.activeEnvironmentOverride ?? environments_1.DEFAULT_ENVIRONMENT_NAME,
74
- environments: { ...environments_1.DEFAULT_ENVIRONMENTS },
75
- };
234
+ function canonicalRuntimeUtf8BytesV1(value) {
235
+ return new TextEncoder().encode(canonicalRuntimeJsonV1(value));
236
+ }
237
+ function canonicalRuntimeUtf8ByteLengthV1(value) {
238
+ return canonicalRuntimeUtf8BytesV1(value).byteLength;
239
+ }
240
+ var BoundedRuntimeJsonErrorV1 = class extends SyntaxError {
241
+ constructor(reason) {
242
+ super(`Bounded runtime JSON rejected ${reason}.`);
243
+ this.reason = reason;
244
+ this.name = "BoundedRuntimeJsonErrorV1";
245
+ }
246
+ };
247
+ exports2.BoundedRuntimeJsonErrorV1 = BoundedRuntimeJsonErrorV1;
248
+ var boundedInvalid = (reason) => {
249
+ throw new BoundedRuntimeJsonErrorV1(reason);
250
+ };
251
+ exports2.MAXIMUM_BOUNDED_RUNTIME_JSON_BYTES_V1 = 2097152;
252
+ function boundedLimits(limits) {
253
+ const maximumBytes = limits.maximumBytes ?? 1048576;
254
+ const maximumDepth = limits.maximumDepth ?? 16;
255
+ if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 1 || maximumBytes > exports2.MAXIMUM_BOUNDED_RUNTIME_JSON_BYTES_V1 || !Number.isSafeInteger(maximumDepth) || maximumDepth < 1 || maximumDepth > 24)
256
+ boundedInvalid("limits");
257
+ return { maximumBytes, maximumDepth };
258
+ }
259
+ function boundedUnicode(value) {
260
+ for (let index = 0; index < value.length; index += 1) {
261
+ const unit = value.charCodeAt(index);
262
+ if (unit >= 55296 && unit <= 56319) {
263
+ const next = value.charCodeAt(++index);
264
+ if (!(next >= 56320 && next <= 57343))
265
+ return false;
266
+ } else if (unit >= 56320 && unit <= 57343)
267
+ return false;
268
+ }
269
+ return true;
270
+ }
271
+ function copyBoundedRuntimeData(input, maximumBytes, maximumDepth, jsonOnly, preserveKeyOrder = false) {
272
+ let nodes = 0;
273
+ let characters = 0;
274
+ const ancestors = /* @__PURE__ */ new Set();
275
+ function copy(value, depth) {
276
+ if (++nodes > (jsonOnly ? 2e5 : 1e5) || depth > maximumDepth)
277
+ boundedInvalid("shape");
278
+ if (value === null || typeof value === "boolean" || !jsonOnly && value === void 0)
279
+ return value;
280
+ if (typeof value === "number" && Number.isFinite(value))
281
+ return value;
282
+ if (typeof value === "string") {
283
+ characters += value.length;
284
+ if (jsonOnly ? characters > maximumBytes || !boundedUnicode(value) : value.length > 1048576 || characters > 16777216)
285
+ boundedInvalid("text");
286
+ return value;
76
287
  }
77
- let raw;
288
+ if (!value || typeof value !== "object" || ancestors.has(value))
289
+ boundedInvalid("shape");
290
+ const objectValue = value;
291
+ const array = Array.isArray(objectValue);
292
+ const prototype = Object.getPrototypeOf(objectValue);
293
+ const arrayLength = array ? objectValue.length : 0;
294
+ if (array ? prototype !== Array.prototype && (jsonOnly || prototype !== null) : prototype !== Object.prototype && prototype !== null)
295
+ boundedInvalid("shape");
296
+ const keys = Reflect.ownKeys(objectValue);
297
+ if (keys.length > 10001 || keys.some((key) => typeof key !== "string"))
298
+ boundedInvalid("shape");
299
+ if (array && keys.length !== arrayLength + 1)
300
+ boundedInvalid("array");
301
+ const seen = /* @__PURE__ */ new Set();
302
+ const result = array ? [] : {};
303
+ ancestors.add(objectValue);
78
304
  try {
79
- raw = JSON.parse((0, node_fs_1.readFileSync)(this.path, 'utf8'));
305
+ for (const key of jsonOnly || array || preserveKeyOrder ? keys : keys.sort()) {
306
+ if (array && key === "length")
307
+ continue;
308
+ const descriptor = Object.getOwnPropertyDescriptor(objectValue, key);
309
+ if (!descriptor.enumerable || !("value" in descriptor) || key.length > (jsonOnly ? 160 : 256) || jsonOnly && seen.has(key.toLowerCase()) || array && (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= arrayLength))
310
+ boundedInvalid("shape");
311
+ seen.add(key.toLowerCase());
312
+ Object.defineProperty(result, key, { enumerable: true, writable: true, configurable: true, value: copy(descriptor.value, depth + 1) });
313
+ }
314
+ } finally {
315
+ ancestors.delete(objectValue);
80
316
  }
81
- catch {
82
- throw new CliError_1.CliError(CliError_1.CliErrorCodes.ConfigInvalid, `Config file at ${this.path} is not valid JSON.`);
317
+ return result;
318
+ }
319
+ return copy(input, 0);
320
+ }
321
+ function boundedRuntimeDataV1(input, preserveKeyOrder = false) {
322
+ return copyBoundedRuntimeData(input, 16777216, 24, false, preserveKeyOrder);
323
+ }
324
+ function boundedRuntimeJsonDataV1(input, limits = {}) {
325
+ const { maximumBytes, maximumDepth } = boundedLimits(limits);
326
+ const value = copyBoundedRuntimeData(input, maximumBytes, maximumDepth, true);
327
+ if (canonicalRuntimeUtf8ByteLengthV1(value) > maximumBytes)
328
+ boundedInvalid("bytes");
329
+ return value;
330
+ }
331
+ function parseBoundedRuntimeJsonV12(source, limits = {}) {
332
+ const { maximumBytes, maximumDepth } = boundedLimits(limits);
333
+ if (typeof source !== "string" || source.length > maximumBytes || !boundedUnicode(source) || new TextEncoder().encode(source).byteLength > maximumBytes)
334
+ boundedInvalid("bytes");
335
+ let index = 0;
336
+ let nodes = 0;
337
+ const whitespace = () => {
338
+ while (/[\x20\t\r\n]/.test(source[index] ?? "\0"))
339
+ index += 1;
340
+ };
341
+ function string() {
342
+ const start = index;
343
+ if (source[index++] !== '"')
344
+ boundedInvalid("string");
345
+ while (index < source.length) {
346
+ const char = source[index++];
347
+ if (char === "\\") {
348
+ index += 1;
349
+ continue;
350
+ }
351
+ if (char === '"') {
352
+ try {
353
+ const parsed = JSON.parse(source.slice(start, index));
354
+ if (!boundedUnicode(parsed))
355
+ boundedInvalid("unicode");
356
+ return parsed;
357
+ } catch (error) {
358
+ if (error instanceof BoundedRuntimeJsonErrorV1)
359
+ throw error;
360
+ boundedInvalid("string");
361
+ }
362
+ }
363
+ }
364
+ return boundedInvalid("string");
365
+ }
366
+ function value(depth) {
367
+ if (++nodes > 2e5 || depth > maximumDepth)
368
+ boundedInvalid("shape");
369
+ whitespace();
370
+ const char = source[index];
371
+ if (char === '"') {
372
+ string();
373
+ return;
374
+ }
375
+ if (char === "{") {
376
+ index += 1;
377
+ whitespace();
378
+ const seen = /* @__PURE__ */ new Set();
379
+ if (source[index] === "}") {
380
+ index += 1;
381
+ return;
382
+ }
383
+ for (; ; ) {
384
+ const item = string().toLowerCase();
385
+ if (seen.has(item))
386
+ boundedInvalid("duplicate_key");
387
+ seen.add(item);
388
+ whitespace();
389
+ if (source[index++] !== ":")
390
+ boundedInvalid("object");
391
+ value(depth + 1);
392
+ whitespace();
393
+ const end = source[index++];
394
+ if (end === "}")
395
+ return;
396
+ if (end !== ",")
397
+ boundedInvalid("object");
398
+ whitespace();
399
+ }
83
400
  }
84
- // Merge built-in defaults so new default envs appear without a rewrite,
85
- // but user-defined overrides win.
86
- const environments = Object.fromEntries(Object.entries({ ...environments_1.DEFAULT_ENVIRONMENTS, ...(raw.environments ?? {}) })
87
- .map(([name, env]) => [
88
- name,
89
- environments_1.DEFAULT_ENVIRONMENTS[name] ? { ...environments_1.DEFAULT_ENVIRONMENTS[name], ...env } : env,
90
- ]));
91
- const activeEnvironment = this.activeEnvironmentOverride ?? raw.activeEnvironment ?? environments_1.DEFAULT_ENVIRONMENT_NAME;
92
- return { activeEnvironment, environments };
93
- }
94
- save(config) {
95
- (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(this.path), { recursive: true });
96
- (0, node_fs_1.writeFileSync)(this.path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
97
- }
98
- listEnvironments() {
99
- const config = this.load();
100
- return Object.keys(config.environments)
101
- .sort()
102
- .map((name) => ({ name, active: name === config.activeEnvironment }));
103
- }
104
- getActiveEnvironment() {
105
- const config = this.load();
106
- const env = config.environments[config.activeEnvironment];
107
- if (!env) {
108
- throw new CliError_1.CliError(CliError_1.CliErrorCodes.EnvironmentNotFound, `Active environment '${config.activeEnvironment}' is not defined. Run 'xyra env use <name>'.`);
401
+ if (char === "[") {
402
+ index += 1;
403
+ whitespace();
404
+ if (source[index] === "]") {
405
+ index += 1;
406
+ return;
407
+ }
408
+ let count = 0;
409
+ for (; ; ) {
410
+ if (++count > 1e4)
411
+ boundedInvalid("array");
412
+ value(depth + 1);
413
+ whitespace();
414
+ const end = source[index++];
415
+ if (end === "]")
416
+ return;
417
+ if (end !== ",")
418
+ boundedInvalid("array");
419
+ whitespace();
420
+ }
109
421
  }
110
- validateEnvironment(env);
111
- return env;
112
- }
113
- useEnvironment(name) {
114
- const config = this.load();
115
- const env = config.environments[name];
116
- if (!env) {
117
- throw new CliError_1.CliError(CliError_1.CliErrorCodes.EnvironmentNotFound, `Environment '${name}' is not defined. Known: ${Object.keys(config.environments).join(', ')}.`);
422
+ const token = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(source.slice(index));
423
+ if (!token)
424
+ boundedInvalid("value");
425
+ const tokenText = token[0];
426
+ if (/^-?\d/.test(tokenText)) {
427
+ const numeric = Number(tokenText);
428
+ if (!Number.isFinite(numeric))
429
+ boundedInvalid("number");
430
+ if (Number.isInteger(numeric)) {
431
+ if (!Number.isSafeInteger(numeric))
432
+ boundedInvalid("number");
433
+ const parts = /^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(tokenText);
434
+ let digits = (parts[2] + (parts[3] ?? "")).replace(/^0+/, "");
435
+ let power = Number(parts[4] ?? 0) - (parts[3]?.length ?? 0);
436
+ if (digits) {
437
+ const trimmed = digits.replace(/0+$/, "");
438
+ power += digits.length - trimmed.length;
439
+ digits = trimmed;
440
+ if (power < 0 || digits.length + power > 16 || Number(digits + "0".repeat(power)) !== Math.abs(numeric))
441
+ boundedInvalid("number");
442
+ }
443
+ }
118
444
  }
119
- validateEnvironment(env);
120
- config.activeEnvironment = name;
121
- this.save({ ...config, activeEnvironment: name });
122
- return env;
445
+ index += tokenText.length;
446
+ }
447
+ value(0);
448
+ whitespace();
449
+ if (index !== source.length)
450
+ boundedInvalid("trailing");
451
+ try {
452
+ return boundedRuntimeJsonDataV1(JSON.parse(source), limits);
453
+ } catch (error) {
454
+ if (error instanceof BoundedRuntimeJsonErrorV1)
455
+ throw error;
456
+ return boundedInvalid("json");
457
+ }
458
+ }
459
+ }
460
+ });
461
+
462
+ // src/config/configStore.ts
463
+ var configStore_exports = {};
464
+ __export(configStore_exports, {
465
+ ConfigStore: () => ConfigStore,
466
+ validateEnvironment: () => validateEnvironment
467
+ });
468
+ module.exports = __toCommonJS(configStore_exports);
469
+ var import_node_fs = require("node:fs");
470
+ var import_node_os = require("node:os");
471
+ var import_node_path = require("node:path");
472
+ var import_CliError = require("../errors/CliError");
473
+ var import_xyra_administration = __toESM(require_xyra_administration());
474
+ var import_canonical_runtime_json = __toESM(require_canonical_runtime_json());
475
+
476
+ // src/config/environments.ts
477
+ var DEFAULT_ENVIRONMENTS = {
478
+ dev: {
479
+ name: "dev",
480
+ mcpUrl: "https://mcp.dev.experiture.ai/mcp",
481
+ orchestratorUrl: "https://orchestrator.dev.experiture.ai",
482
+ oauthResource: "https://mcp.dev.experiture.ai/mcp",
483
+ authorizationEndpoint: "https://dev.app.experiture.ai/api/auth/oauth/authorize",
484
+ tokenEndpoint: "https://dev.app.experiture.ai/api/auth/oauth/token",
485
+ clientId: "experiture-xyra-mcp-delegated",
486
+ redirectPath: "/callback/QYfSVwRg9okE",
487
+ scopes: ["openid", "profile", "email", "offline_access"]
488
+ },
489
+ staging: {
490
+ name: "staging",
491
+ mcpUrl: "https://mcp.staging.experiture.ai/mcp",
492
+ orchestratorUrl: "https://app.experiture.ai",
493
+ oauthResource: "https://mcp.staging.experiture.ai/mcp",
494
+ authorizationEndpoint: "https://app.experiture.ai/api/auth/oauth/authorize",
495
+ tokenEndpoint: "https://app.experiture.ai/api/auth/oauth/token",
496
+ clientId: "experiture-xyra-mcp-delegated",
497
+ redirectPath: "/callback/QYfSVwRg9okE",
498
+ scopes: ["openid", "profile", "email", "offline_access"]
499
+ },
500
+ local: {
501
+ name: "local",
502
+ mcpUrl: "https://app.experiture.test/mcp",
503
+ orchestratorUrl: "http://localhost:8000",
504
+ oauthResource: "https://mcp.dev.experiture.ai/mcp",
505
+ authorizationEndpoint: "https://app.experiture.test/api/auth/oauth/authorize",
506
+ tokenEndpoint: "https://app.experiture.test/api/auth/oauth/token",
507
+ clientId: "experiture-xyra-mcp-delegated",
508
+ redirectPath: "/callback/QYfSVwRg9okE",
509
+ scopes: ["openid", "profile", "email", "offline_access"]
510
+ }
511
+ };
512
+ var DEFAULT_ENVIRONMENT_NAME = "dev";
513
+
514
+ // src/config/configStore.ts
515
+ var CONFIG_DIR = process.env.XYRA_CLI_CONFIG_DIR ?? (0, import_node_path.join)((0, import_node_os.homedir)(), ".config", "xyra");
516
+ var CONFIG_PATH = (0, import_node_path.join)(CONFIG_DIR, "config.json");
517
+ function requireHttpsOrTest(name, url) {
518
+ let parsed;
519
+ try {
520
+ parsed = new URL(url);
521
+ } catch {
522
+ throw new import_CliError.CliError(import_CliError.CliErrorCodes.ConfigInvalid, `Environment '${name}' has an invalid URL: ${url}`);
523
+ }
524
+ const isTestDomain = parsed.hostname.endsWith(".test");
525
+ if (parsed.protocol !== "https:" && !isTestDomain) {
526
+ throw new import_CliError.CliError(
527
+ import_CliError.CliErrorCodes.ConfigInvalid,
528
+ `Environment '${name}' must use https (got ${parsed.protocol}//${parsed.host}).`
529
+ );
530
+ }
531
+ }
532
+ function requireHttpOrigin(name, url) {
533
+ let parsed;
534
+ try {
535
+ parsed = new URL(url);
536
+ } catch {
537
+ throw new import_CliError.CliError(import_CliError.CliErrorCodes.ConfigInvalid, `Environment '${name}' has an invalid URL: ${url}`);
538
+ }
539
+ const isLocalhost = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
540
+ const isTestDomain = parsed.hostname.endsWith(".test");
541
+ const allowedProtocol = parsed.protocol === "https:" || parsed.protocol === "http:" && (isLocalhost || isTestDomain);
542
+ if (!allowedProtocol || parsed.username || parsed.password || parsed.search || parsed.hash || parsed.pathname !== "/" && parsed.pathname !== "") {
543
+ throw new import_CliError.CliError(
544
+ import_CliError.CliErrorCodes.ConfigInvalid,
545
+ `Environment '${name}' must be an HTTP(S) origin without credentials, path, query, or fragment.`
546
+ );
547
+ }
548
+ }
549
+ function validateEnvironment(env) {
550
+ for (const [field, url] of [
551
+ ["mcpUrl", env.mcpUrl],
552
+ ["authorizationEndpoint", env.authorizationEndpoint],
553
+ ["tokenEndpoint", env.tokenEndpoint]
554
+ ]) {
555
+ if (!url) {
556
+ throw new import_CliError.CliError(import_CliError.CliErrorCodes.ConfigInvalid, `Environment '${env.name}' is missing ${field}.`);
123
557
  }
558
+ requireHttpsOrTest(`${env.name}.${field}`, url);
559
+ }
560
+ if (!env.orchestratorUrl) {
561
+ throw new import_CliError.CliError(import_CliError.CliErrorCodes.ConfigInvalid, `Environment '${env.name}' is missing orchestratorUrl.`);
562
+ }
563
+ requireHttpOrigin(`${env.name}.orchestratorUrl`, env.orchestratorUrl);
564
+ if (!env.clientId) {
565
+ throw new import_CliError.CliError(import_CliError.CliErrorCodes.ConfigInvalid, `Environment '${env.name}' is missing clientId.`);
566
+ }
567
+ if (!env.redirectPath.startsWith("/")) {
568
+ throw new import_CliError.CliError(import_CliError.CliErrorCodes.ConfigInvalid, `Environment '${env.name}' redirectPath must start with '/'.`);
569
+ }
124
570
  }
125
- exports.ConfigStore = ConfigStore;
126
- //# sourceMappingURL=configStore.js.map
571
+ var ConfigStore = class {
572
+ constructor(path = CONFIG_PATH, activeEnvironmentOverride, accessPurposeOverride, administrationTargetOverride, sessionNameOverride) {
573
+ this.path = path;
574
+ this.activeEnvironmentOverride = activeEnvironmentOverride;
575
+ this.accessPurposeOverride = accessPurposeOverride;
576
+ this.administrationTargetOverride = administrationTargetOverride;
577
+ this.sessionNameOverride = sessionNameOverride;
578
+ }
579
+ getSessionName() {
580
+ return this.sessionNameOverride;
581
+ }
582
+ load() {
583
+ if (!(0, import_node_fs.existsSync)(this.path)) {
584
+ return {
585
+ activeEnvironment: this.activeEnvironmentOverride ?? DEFAULT_ENVIRONMENT_NAME,
586
+ environments: { ...DEFAULT_ENVIRONMENTS }
587
+ };
588
+ }
589
+ let raw;
590
+ try {
591
+ raw = JSON.parse((0, import_node_fs.readFileSync)(this.path, "utf8"));
592
+ } catch {
593
+ throw new import_CliError.CliError(import_CliError.CliErrorCodes.ConfigInvalid, `Config file at ${this.path} is not valid JSON.`);
594
+ }
595
+ const environments = Object.fromEntries(
596
+ Object.entries({ ...DEFAULT_ENVIRONMENTS, ...raw.environments ?? {} }).map(([name, env]) => [
597
+ name,
598
+ DEFAULT_ENVIRONMENTS[name] ? { ...DEFAULT_ENVIRONMENTS[name], ...env } : env
599
+ ])
600
+ );
601
+ const activeEnvironment = this.activeEnvironmentOverride ?? raw.activeEnvironment ?? DEFAULT_ENVIRONMENT_NAME;
602
+ return { activeEnvironment, environments };
603
+ }
604
+ save(config) {
605
+ (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(this.path), { recursive: true });
606
+ (0, import_node_fs.writeFileSync)(this.path, `${JSON.stringify(config, null, 2)}
607
+ `, { mode: 384 });
608
+ }
609
+ listEnvironments() {
610
+ const config = this.load();
611
+ return Object.keys(config.environments).sort().map((name) => ({ name, active: name === config.activeEnvironment }));
612
+ }
613
+ getActiveEnvironment() {
614
+ const config = this.load();
615
+ const env = config.environments[config.activeEnvironment];
616
+ if (!env) {
617
+ throw new import_CliError.CliError(
618
+ import_CliError.CliErrorCodes.EnvironmentNotFound,
619
+ `Active environment '${config.activeEnvironment}' is not defined. Run 'xyra env use <name>'.`
620
+ );
621
+ }
622
+ validateEnvironment(env);
623
+ if (env.accessPurpose !== void 0 || env.administrationTarget !== void 0) throw new import_CliError.CliError(
624
+ import_CliError.CliErrorCodes.ConfigInvalid,
625
+ "Purpose and selected administration target are invocation-only, not stored environment or actor fields."
626
+ );
627
+ const purpose = this.accessPurposeOverride ?? "runtime";
628
+ if (!["runtime", "administration"].includes(purpose) || purpose === "runtime" && this.administrationTargetOverride !== void 0)
629
+ throw new import_CliError.CliError(import_CliError.CliErrorCodes.InvalidArguments, "Select runtime or administration; a maintenance target requires administration purpose.");
630
+ if (purpose === "runtime") return env;
631
+ const profile = env.administrationOAuth;
632
+ if (!profile || !profile.clientId || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/.test(profile.clientId) || profile.clientId === env.clientId || env.mcpUrl !== env.oauthResource || !Array.isArray(profile.scopes) || profile.scopes.length > 100 || !profile.scopes.includes("openid") || !profile.scopes.includes("offline_access") || profile.scopes.some((scope) => typeof scope !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(scope)) || !profile.redirectPath || !/^\/callback\/[A-Za-z0-9_-]+$/.test(profile.redirectPath))
633
+ throw new import_CliError.CliError(
634
+ import_CliError.CliErrorCodes.ConfigInvalid,
635
+ `Environment '${env.name}' needs its registered Xyra-owned public administration CLI profile.`,
636
+ "Configure administrationOAuth with its separate native client, approved loopback callback path and delegated scopes; do not reuse the runtime or HTTPS connector client."
637
+ );
638
+ let selected;
639
+ try {
640
+ selected = this.administrationTargetOverride === void 0 ? { targetKind: "global-resource", managedProductId: "xyra-ai" } : (0, import_canonical_runtime_json.parseBoundedRuntimeJsonV1)(this.administrationTargetOverride, { maximumBytes: 8192, maximumDepth: 4 });
641
+ } catch {
642
+ throw new import_CliError.CliError(import_CliError.CliErrorCodes.InvalidArguments, "The administration target must be one bounded JSON object without repeated fields.");
643
+ }
644
+ const target = (0, import_xyra_administration.parseXyraAdministrationTargetV1)(selected);
645
+ if (!target) throw new import_CliError.CliError(import_CliError.CliErrorCodes.InvalidArguments, "Select one complete global, configuration-owner or customer administration target.");
646
+ return { ...env, clientId: profile.clientId, redirectPath: profile.redirectPath, scopes: [...profile.scopes], accessPurpose: "administration", administrationTarget: target };
647
+ }
648
+ useEnvironment(name) {
649
+ const config = this.load();
650
+ const env = config.environments[name];
651
+ if (!env) {
652
+ throw new import_CliError.CliError(
653
+ import_CliError.CliErrorCodes.EnvironmentNotFound,
654
+ `Environment '${name}' is not defined. Known: ${Object.keys(config.environments).join(", ")}.`
655
+ );
656
+ }
657
+ validateEnvironment(env);
658
+ config.activeEnvironment = name;
659
+ this.save({ ...config, activeEnvironment: name });
660
+ return env;
661
+ }
662
+ };
663
+ // Annotate the CommonJS export names for ESM import in node:
664
+ 0 && (module.exports = {
665
+ ConfigStore,
666
+ validateEnvironment
667
+ });
668
+ //# sourceMappingURL=configStore.js.map