@fabricorg/experiments 0.6.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/fx.cjs CHANGED
@@ -11,6 +11,10 @@ var http = require('http');
11
11
  var module$1 = require('module');
12
12
  var databricksTestkit = require('@fabricorg/databricks-testkit');
13
13
  var fastXmlParser = require('fast-xml-parser');
14
+ var child_process = require('child_process');
15
+ var os = require('os');
16
+ var util$1 = require('util');
17
+ var process$1 = require('process');
14
18
 
15
19
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
20
  var __defProp = Object.defineProperty;
@@ -7437,6 +7441,39 @@ var AuditEvent = external_exports.object({
7437
7441
  payload: external_exports.record(external_exports.unknown())
7438
7442
  });
7439
7443
  var AuditListResponse = external_exports.object({ events: external_exports.array(AuditEvent) });
7444
+ var GovernanceSettings = external_exports.object({
7445
+ requireQualityForProduction: external_exports.boolean(),
7446
+ requiredQualitySuites: external_exports.array(external_exports.string().min(1).max(240)).max(50),
7447
+ qualityMaxAgeHours: external_exports.number().int().min(1).max(8760),
7448
+ retentionDays: external_exports.number().int().min(30).max(3650),
7449
+ legalHold: external_exports.boolean(),
7450
+ updatedBy: external_exports.string().nullable(),
7451
+ updatedAt: external_exports.string().datetime().nullable()
7452
+ });
7453
+ var UpdateGovernanceSettingsInput = GovernanceSettings.pick({
7454
+ requireQualityForProduction: true,
7455
+ requiredQualitySuites: true,
7456
+ qualityMaxAgeHours: true,
7457
+ retentionDays: true,
7458
+ legalHold: true
7459
+ });
7460
+ var QualityGateResult = external_exports.object({
7461
+ enabled: external_exports.boolean(),
7462
+ passed: external_exports.boolean(),
7463
+ checks: external_exports.array(
7464
+ external_exports.object({
7465
+ suite: external_exports.string(),
7466
+ passed: external_exports.boolean(),
7467
+ reason: external_exports.string(),
7468
+ runId: external_exports.string().nullable(),
7469
+ finishedAt: external_exports.string().datetime().nullable()
7470
+ })
7471
+ )
7472
+ });
7473
+ var GovernanceStatusResponse = external_exports.object({
7474
+ settings: GovernanceSettings,
7475
+ qualityGate: QualityGateResult
7476
+ });
7440
7477
  var AuditExport = external_exports.object({
7441
7478
  id: external_exports.string(),
7442
7479
  destinationKind: external_exports.enum(["s3", "r2", "splunk-hec"]),
@@ -7543,7 +7580,8 @@ var TestRunListInput = external_exports.object({
7543
7580
  status: TestRunStatus.optional(),
7544
7581
  source: CreateTestRunInput.shape.source.optional(),
7545
7582
  suite: external_exports.string().min(1).max(240).optional(),
7546
- limit: external_exports.coerce.number().int().min(1).max(200).optional()
7583
+ limit: external_exports.coerce.number().int().min(1).max(200).optional(),
7584
+ offset: external_exports.coerce.number().int().min(0).max(1e5).optional()
7547
7585
  });
7548
7586
  var TestRunListResponse = external_exports.object({
7549
7587
  runs: external_exports.array(TestRun.omit({ cases: true }))
@@ -7757,6 +7795,22 @@ var endpoints = {
7757
7795
  mutates: false,
7758
7796
  requiresRole: "viewer"
7759
7797
  },
7798
+ "governance.get": {
7799
+ method: "GET",
7800
+ path: "/v1/orgs/:orgId/governance",
7801
+ params: Empty,
7802
+ response: GovernanceStatusResponse,
7803
+ mutates: false,
7804
+ requiresRole: "viewer"
7805
+ },
7806
+ "governance.update": {
7807
+ method: "POST",
7808
+ path: "/v1/orgs/:orgId/governance",
7809
+ params: UpdateGovernanceSettingsInput,
7810
+ response: GovernanceStatusResponse,
7811
+ mutates: true,
7812
+ requiresRole: "admin"
7813
+ },
7760
7814
  "audit.exports.list": {
7761
7815
  method: "GET",
7762
7816
  path: "/v1/orgs/:orgId/audit/exports",
@@ -8008,6 +8062,10 @@ var ApiClient = class {
8008
8062
  audit = {
8009
8063
  list: (orgId) => this.call("audit.list", {}, orgId ? { orgId } : void 0)
8010
8064
  };
8065
+ governance = {
8066
+ get: (orgId) => this.call("governance.get", {}, orgId ? { orgId } : void 0),
8067
+ update: (params, orgId) => this.call("governance.update", params, orgId ? { orgId } : void 0)
8068
+ };
8011
8069
  preview = {
8012
8070
  sign: (params, orgId) => this.call("preview.sign", params, orgId ? { orgId } : void 0)
8013
8071
  };
@@ -8055,6 +8113,7 @@ async function cmdPreview(experimentId, options) {
8055
8113
  const client = new ApiClient({
8056
8114
  baseUrl: options.apiUrl,
8057
8115
  apiKey: options.apiKey,
8116
+ bearerToken: options.bearerToken,
8058
8117
  defaultOrgId: tenantId
8059
8118
  });
8060
8119
  const r = await client.call(
@@ -8141,7 +8200,12 @@ async function cmdPush(dir, options = {}) {
8141
8200
  );
8142
8201
  return 1;
8143
8202
  }
8144
- const api = new ApiClient({ baseUrl: apiUrl, apiKey, defaultOrgId: tenantId });
8203
+ const api = new ApiClient({
8204
+ baseUrl: apiUrl,
8205
+ apiKey,
8206
+ bearerToken: options.bearerToken,
8207
+ defaultOrgId: tenantId
8208
+ });
8145
8209
  const specs = (await loadExperimentDir(path.resolve(dir))).map((s) => s.spec);
8146
8210
  const summaries = (await api.experiments.list()).experiments;
8147
8211
  const current = [];
@@ -8526,6 +8590,141 @@ async function writeState(path$1, state) {
8526
8590
  await promises.writeFile(path$1, `${JSON.stringify(state, null, 2)}
8527
8591
  `, "utf8");
8528
8592
  }
8593
+ var execFileAsync = util$1.promisify(child_process.execFile);
8594
+ function defaultConfigPath(env = process.env) {
8595
+ const configDir = env.FX_CONFIG_DIR ?? (process.platform === "win32" ? path.join(env.APPDATA ?? os.homedir(), "Fabric Experiments") : path.join(env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"), "fabric-experiments"));
8596
+ return path.join(configDir, "config.json");
8597
+ }
8598
+ async function loadHostedConfig(path = defaultConfigPath()) {
8599
+ try {
8600
+ const parsed = JSON.parse(await promises.readFile(path, "utf8"));
8601
+ return {
8602
+ version: 1,
8603
+ activeProfile: parsed.activeProfile,
8604
+ profiles: parsed.profiles ?? {}
8605
+ };
8606
+ } catch (error) {
8607
+ if (error.code === "ENOENT") {
8608
+ return { version: 1, profiles: {} };
8609
+ }
8610
+ throw new Error(`Unable to read Fabric CLI config at ${path}: ${error.message}`);
8611
+ }
8612
+ }
8613
+ async function saveHostedConfig(config, path$1 = defaultConfigPath()) {
8614
+ await promises.mkdir(path.dirname(path$1), { recursive: true, mode: 448 });
8615
+ const temporary = `${path$1}.${process.pid}.tmp`;
8616
+ await promises.writeFile(temporary, `${JSON.stringify(config, null, 2)}
8617
+ `, { mode: 384 });
8618
+ await promises.rename(temporary, path$1);
8619
+ await promises.chmod(path$1, 384);
8620
+ }
8621
+ async function removeHostedProfile(profileName, path = defaultConfigPath()) {
8622
+ const config = await loadHostedConfig(path);
8623
+ if (!config.profiles[profileName]) return false;
8624
+ delete config.profiles[profileName];
8625
+ if (config.activeProfile === profileName) {
8626
+ config.activeProfile = Object.keys(config.profiles).sort()[0];
8627
+ }
8628
+ if (Object.keys(config.profiles).length === 0) {
8629
+ try {
8630
+ await promises.unlink(path);
8631
+ } catch (error) {
8632
+ if (error.code !== "ENOENT") throw error;
8633
+ }
8634
+ return true;
8635
+ }
8636
+ await saveHostedConfig(config, path);
8637
+ return true;
8638
+ }
8639
+ async function configPermissionsArePrivate(path = defaultConfigPath()) {
8640
+ if (process.platform === "win32") return true;
8641
+ try {
8642
+ const details = await promises.stat(path);
8643
+ return (details.mode & 63) === 0;
8644
+ } catch (error) {
8645
+ if (error.code === "ENOENT") return true;
8646
+ throw error;
8647
+ }
8648
+ }
8649
+ async function resolveHostedContext(options = {}) {
8650
+ const env = options.env ?? process.env;
8651
+ const config = await loadHostedConfig(options.configPath ?? defaultConfigPath(env));
8652
+ const profileName = options.profileName ?? env.FX_PROFILE ?? config.activeProfile;
8653
+ const profile = profileName ? config.profiles[profileName] : void 0;
8654
+ const apiUrl = options.apiUrl ?? env.FX_API_URL ?? profile?.apiUrl;
8655
+ const apiKey = options.apiKey ?? env.FX_API_KEY ?? profile?.apiKey;
8656
+ const tenantId = options.tenantId ?? env.FX_ORG_ID ?? profile?.orgId;
8657
+ const bearerToken = options.bearerToken ?? (apiUrl ? await resolveGatewayBearer(apiUrl, {
8658
+ env,
8659
+ databricksProfile: profile?.databricksProfile,
8660
+ tokenProvider: options.tokenProvider
8661
+ }) : void 0);
8662
+ return { profileName, apiUrl, apiKey, tenantId, bearerToken };
8663
+ }
8664
+ async function resolveStudioApiUrl(studioUrl, fetchImpl = globalThis.fetch) {
8665
+ const source = new URL(studioUrl);
8666
+ const response = await fetchImpl(source.toString(), { method: "HEAD", redirect: "manual" });
8667
+ const location = response.headers.get("location");
8668
+ const target = location ? new URL(location, source) : source;
8669
+ target.pathname = "/api";
8670
+ target.search = "";
8671
+ target.hash = "";
8672
+ return target.toString().replace(/\/$/, "");
8673
+ }
8674
+ async function resolveGatewayBearer(apiUrl, options = {}) {
8675
+ const env = options.env ?? process.env;
8676
+ if (env.FX_GATEWAY_BEARER_TOKEN) return env.FX_GATEWAY_BEARER_TOKEN;
8677
+ if (!new URL(apiUrl).hostname.endsWith(".databricksapps.com")) return void 0;
8678
+ const databricksProfile = options.databricksProfile ?? env.FX_DATABRICKS_PROFILE;
8679
+ if (databricksProfile) {
8680
+ return (options.tokenProvider ?? databricksCliToken)(databricksProfile);
8681
+ }
8682
+ const host = env.DATABRICKS_HOST?.replace(/\/$/, "");
8683
+ const clientId = env.FX_QUALITY_DATABRICKS_CLIENT_ID ?? env.DATABRICKS_CLIENT_ID;
8684
+ const clientSecret = env.FX_QUALITY_DATABRICKS_CLIENT_SECRET ?? env.DATABRICKS_CLIENT_SECRET;
8685
+ if (!host || !clientId || !clientSecret) {
8686
+ try {
8687
+ return await (options.tokenProvider ?? databricksCliToken)();
8688
+ } catch {
8689
+ throw new Error(
8690
+ "Databricks Apps access requires a Databricks CLI login, --databricks-profile, FX_DATABRICKS_PROFILE, or DATABRICKS_HOST with client credentials"
8691
+ );
8692
+ }
8693
+ }
8694
+ const response = await fetch(`${host}/oidc/v1/token`, {
8695
+ method: "POST",
8696
+ headers: {
8697
+ authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`,
8698
+ "content-type": "application/x-www-form-urlencoded"
8699
+ },
8700
+ body: new URLSearchParams({ grant_type: "client_credentials", scope: "all-apis" })
8701
+ });
8702
+ if (!response.ok) {
8703
+ throw new Error(`Databricks OAuth failed (${response.status} ${response.statusText})`);
8704
+ }
8705
+ const body = await response.json();
8706
+ if (typeof body.access_token !== "string" || !body.access_token) {
8707
+ throw new Error("Databricks OAuth response did not include an access token");
8708
+ }
8709
+ return body.access_token;
8710
+ }
8711
+ async function databricksCliToken(profile) {
8712
+ try {
8713
+ const args = ["auth", "token", ...profile ? [profile] : [], "--output", "json"];
8714
+ const { stdout } = await execFileAsync("databricks", args, { encoding: "utf8" });
8715
+ const parsed = JSON.parse(stdout);
8716
+ if (typeof parsed.access_token !== "string" || !parsed.access_token) {
8717
+ throw new Error("token response did not include access_token");
8718
+ }
8719
+ return parsed.access_token;
8720
+ } catch (error) {
8721
+ throw new Error(
8722
+ `Unable to obtain a Databricks token${profile ? ` for profile ${profile}` : ""}: ${error.message}`
8723
+ );
8724
+ }
8725
+ }
8726
+
8727
+ // src/commands/test-publish.ts
8529
8728
  async function cmdTestPublish(evidencePath, options = {}) {
8530
8729
  const env = options.env ?? process.env;
8531
8730
  const apiUrl = options.apiUrl ?? env.FX_API_URL;
@@ -8554,30 +8753,7 @@ async function cmdTestPublish(evidencePath, options = {}) {
8554
8753
  return 0;
8555
8754
  }
8556
8755
  async function resolveGatewayToken(apiUrl, env) {
8557
- if (env.FX_GATEWAY_BEARER_TOKEN) return env.FX_GATEWAY_BEARER_TOKEN;
8558
- if (!new URL(apiUrl).hostname.endsWith(".databricksapps.com")) return void 0;
8559
- const host = env.DATABRICKS_HOST?.replace(/\/$/, "");
8560
- const clientId = env.FX_QUALITY_DATABRICKS_CLIENT_ID ?? env.DATABRICKS_CLIENT_ID;
8561
- const clientSecret = env.FX_QUALITY_DATABRICKS_CLIENT_SECRET ?? env.DATABRICKS_CLIENT_SECRET;
8562
- if (!host || !clientId || !clientSecret) {
8563
- throw new Error("Databricks Apps publication requires DATABRICKS_HOST and client credentials");
8564
- }
8565
- const response = await fetch(`${host}/oidc/v1/token`, {
8566
- method: "POST",
8567
- headers: {
8568
- authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`,
8569
- "content-type": "application/x-www-form-urlencoded"
8570
- },
8571
- body: new URLSearchParams({ grant_type: "client_credentials", scope: "all-apis" })
8572
- });
8573
- if (!response.ok) {
8574
- throw new Error(`Databricks OAuth failed (${response.status} ${response.statusText})`);
8575
- }
8576
- const body = await response.json();
8577
- if (typeof body.access_token !== "string" || !body.access_token) {
8578
- throw new Error("Databricks OAuth response did not include an access token");
8579
- }
8580
- return body.access_token;
8756
+ return resolveGatewayBearer(apiUrl, { env });
8581
8757
  }
8582
8758
  function normalizeTestEvidence(value, options = {}) {
8583
8759
  if (!value || typeof value !== "object") throw new Error("Evidence must be a JSON object");
@@ -8662,6 +8838,42 @@ function normalizeTestEvidence(value, options = {}) {
8662
8838
  artifacts
8663
8839
  };
8664
8840
  }
8841
+ if (kind === "fabric-cli" || kind === "cli") {
8842
+ const cases = arrayOfRecords(evidence.cases).map((testCase, index) => ({
8843
+ id: String(testCase.id ?? `cli:${index}`),
8844
+ name: String(testCase.name ?? `CLI check ${index + 1}`),
8845
+ ...typeof testCase.uri === "string" ? { uri: testCase.uri } : {},
8846
+ status: normalizeCaseStatus(testCase.status),
8847
+ durationMs: nonnegativeNumber(testCase.durationMs),
8848
+ tags: Array.isArray(testCase.tags) ? testCase.tags.map(String) : [],
8849
+ ...typeof testCase.error === "string" ? { error: testCase.error } : {},
8850
+ ...typeof testCase.statementId === "string" ? { statementId: testCase.statementId } : {},
8851
+ ...typeof testCase.resourceUrl === "string" ? { resourceUrl: testCase.resourceUrl } : {},
8852
+ ...testCase.details && typeof testCase.details === "object" ? { details: testCase.details } : {}
8853
+ }));
8854
+ const summary = summarize(cases);
8855
+ const requestedStatus = String(evidence.status ?? "").toLowerCase();
8856
+ const status = ["running", "passed", "failed", "skipped", "canceled"].includes(requestedStatus) ? requestedStatus : evidence.success === false || summary.failed > 0 ? "failed" : summary.total > 0 && summary.total === summary.skipped ? "skipped" : "passed";
8857
+ return {
8858
+ ...externalId ? { externalId } : {},
8859
+ source: "cli",
8860
+ suite: options.suite ?? String(evidence.suite ?? "Fabric CLI checks"),
8861
+ status,
8862
+ startedAt: isoOrNull(evidence.startedAt),
8863
+ finishedAt: isoOrNull(evidence.finishedAt) ?? (/* @__PURE__ */ new Date()).toISOString(),
8864
+ durationMs: nonnegativeNumber(
8865
+ evidence.durationMs ?? cases.reduce((sum, item) => sum + item.durationMs, 0)
8866
+ ),
8867
+ summary,
8868
+ environment: {
8869
+ ...objectOf(evidence.environment),
8870
+ ...compact({ profile: env.DBX_TEST_PROFILE, workspace: env.DATABRICKS_HOST })
8871
+ },
8872
+ revision: { ...objectOf(evidence.revision), ...revision },
8873
+ cases,
8874
+ artifacts
8875
+ };
8876
+ }
8665
8877
  if (kind === "junit") {
8666
8878
  const cases = arrayOfRecords(evidence.cases).map((testCase, index) => ({
8667
8879
  id: String(testCase.id ?? `junit:${index}`),
@@ -8764,6 +8976,9 @@ function xmlText(value) {
8764
8976
  function compact(value) {
8765
8977
  return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
8766
8978
  }
8979
+ function objectOf(value) {
8980
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
8981
+ }
8767
8982
  function nonnegativeNumber(value) {
8768
8983
  const number = Number(value ?? 0);
8769
8984
  return Number.isFinite(number) && number >= 0 ? Math.round(number) : 0;
@@ -8772,6 +8987,188 @@ function isoOrNull(value) {
8772
8987
  if (typeof value !== "string" || Number.isNaN(Date.parse(value))) return null;
8773
8988
  return new Date(value).toISOString();
8774
8989
  }
8990
+ async function cmdLogin(options = {}) {
8991
+ const env = options.env ?? process.env;
8992
+ const profileName = options.profileName ?? "production";
8993
+ const apiUrl = options.apiUrl ? normalizeApiUrl(options.apiUrl) : await resolveStudioApiUrl(
8994
+ options.studioUrl ?? "https://studio.experiments.fabric.pro",
8995
+ options.fetchImpl
8996
+ );
8997
+ const apiKey = options.apiKey ?? env.FX_API_KEY ?? await (options.promptSecret ?? readSecretApiKey)();
8998
+ if (!apiKey) throw new Error("A Fabric API key is required");
8999
+ const bearerToken = await resolveGatewayBearer(apiUrl, {
9000
+ env,
9001
+ databricksProfile: options.databricksProfile,
9002
+ tokenProvider: options.tokenProvider
9003
+ });
9004
+ const client = new ApiClient({
9005
+ baseUrl: apiUrl,
9006
+ apiKey,
9007
+ bearerToken,
9008
+ fetchImpl: options.fetchImpl
9009
+ });
9010
+ const tenant = await client.tenants.me();
9011
+ if (options.tenantId && options.tenantId !== tenant.organization.id) {
9012
+ throw new Error(
9013
+ `API key belongs to ${tenant.organization.id}, not requested organization ${options.tenantId}`
9014
+ );
9015
+ }
9016
+ const now3 = (/* @__PURE__ */ new Date()).toISOString();
9017
+ const path = options.configPath ?? defaultConfigPath(env);
9018
+ const config = await loadHostedConfig(path);
9019
+ const existing = config.profiles[profileName];
9020
+ config.profiles[profileName] = {
9021
+ apiUrl,
9022
+ apiKey,
9023
+ orgId: tenant.organization.id,
9024
+ organizationName: tenant.organization.name,
9025
+ organizationSlug: tenant.organization.slug,
9026
+ role: tenant.member.role,
9027
+ databricksProfile: options.databricksProfile,
9028
+ createdAt: existing?.createdAt ?? now3,
9029
+ updatedAt: now3
9030
+ };
9031
+ config.activeProfile = profileName;
9032
+ await saveHostedConfig(config, path);
9033
+ process.stdout.write(
9034
+ `Logged in to ${tenant.organization.name} as ${tenant.member.role} (profile: ${profileName}).
9035
+ `
9036
+ );
9037
+ return 0;
9038
+ }
9039
+ async function cmdLogout(profileName, options = {}) {
9040
+ const env = options.env ?? process.env;
9041
+ const path = options.configPath ?? defaultConfigPath(env);
9042
+ const config = await loadHostedConfig(path);
9043
+ const target = profileName ?? config.activeProfile;
9044
+ if (!target) {
9045
+ process.stdout.write("No Fabric CLI profile is configured.\n");
9046
+ return 0;
9047
+ }
9048
+ const removed = await removeHostedProfile(target, path);
9049
+ process.stdout.write(
9050
+ removed ? `Logged out profile ${target}.
9051
+ ` : `Profile ${target} not found.
9052
+ `
9053
+ );
9054
+ return removed ? 0 : 1;
9055
+ }
9056
+ async function cmdProfile(action = "list", profileName, options = {}) {
9057
+ const env = options.env ?? process.env;
9058
+ const path = options.configPath ?? defaultConfigPath(env);
9059
+ const config = await loadHostedConfig(path);
9060
+ if (action === "use") {
9061
+ if (!profileName || !config.profiles[profileName]) {
9062
+ process.stderr.write("Usage: fx profile use <name>\n");
9063
+ return 1;
9064
+ }
9065
+ config.activeProfile = profileName;
9066
+ await saveHostedConfig(config, path);
9067
+ process.stdout.write(`Active profile: ${profileName}
9068
+ `);
9069
+ return 0;
9070
+ }
9071
+ if (action === "show") {
9072
+ const selected = profileName ?? config.activeProfile;
9073
+ const profile = selected ? config.profiles[selected] : void 0;
9074
+ if (!selected || !profile) {
9075
+ process.stderr.write("No active Fabric CLI profile. Run fx login.\n");
9076
+ return 1;
9077
+ }
9078
+ process.stdout.write(formatProfile(selected, profile, selected === config.activeProfile));
9079
+ return 0;
9080
+ }
9081
+ const names = Object.keys(config.profiles).sort();
9082
+ if (names.length === 0) {
9083
+ process.stdout.write("No Fabric CLI profiles. Run fx login.\n");
9084
+ return 0;
9085
+ }
9086
+ for (const name of names) {
9087
+ process.stdout.write(
9088
+ formatProfile(name, config.profiles[name], name === config.activeProfile)
9089
+ );
9090
+ }
9091
+ return 0;
9092
+ }
9093
+ async function cmdDoctor(options = {}) {
9094
+ const env = options.env ?? process.env;
9095
+ const path = options.configPath ?? defaultConfigPath(env);
9096
+ const context = await resolveHostedContext({
9097
+ profileName: options.profileName,
9098
+ env,
9099
+ configPath: path,
9100
+ tokenProvider: options.tokenProvider
9101
+ });
9102
+ if (!context.apiUrl || !context.apiKey || !context.tenantId) {
9103
+ process.stderr.write("No complete hosted profile. Run fx login.\n");
9104
+ return 1;
9105
+ }
9106
+ const client = new ApiClient({
9107
+ baseUrl: context.apiUrl,
9108
+ apiKey: context.apiKey,
9109
+ bearerToken: context.bearerToken,
9110
+ defaultOrgId: context.tenantId,
9111
+ fetchImpl: options.fetchImpl
9112
+ });
9113
+ const tenant = await client.tenants.me();
9114
+ const privatePermissions = await configPermissionsArePrivate(path);
9115
+ process.stdout.write(
9116
+ [
9117
+ "Fabric CLI doctor",
9118
+ ` Profile: ${context.profileName ?? "(environment)"}`,
9119
+ ` API: ${context.apiUrl}`,
9120
+ ` Organization: ${tenant.organization.name} (${tenant.organization.id})`,
9121
+ ` Role: ${tenant.member.role}`,
9122
+ ` Gateway: ${context.bearerToken ? "authenticated" : "not required"}`,
9123
+ ` Config mode: ${privatePermissions ? "private" : "INSECURE"}`,
9124
+ ""
9125
+ ].join("\n")
9126
+ );
9127
+ return privatePermissions ? 0 : 2;
9128
+ }
9129
+ function normalizeApiUrl(value) {
9130
+ const url = new URL(value);
9131
+ if (!url.pathname || url.pathname === "/") url.pathname = "/api";
9132
+ return url.toString().replace(/\/$/, "");
9133
+ }
9134
+ function formatProfile(name, profile, active) {
9135
+ return `${active ? "*" : " "} ${name} \u2014 ${profile.organizationName ?? profile.orgId} (${profile.role ?? "unknown"})
9136
+ ${profile.apiUrl}
9137
+ `;
9138
+ }
9139
+ async function readSecretApiKey() {
9140
+ if (!process$1.stdin.isTTY || typeof process$1.stdin.setRawMode !== "function") {
9141
+ throw new Error("Set FX_API_KEY or pass --api-key when stdin is not interactive");
9142
+ }
9143
+ process$1.stderr.write("Fabric API key: ");
9144
+ process$1.stdin.setRawMode(true);
9145
+ process$1.stdin.resume();
9146
+ return new Promise((resolve11, reject) => {
9147
+ let value = "";
9148
+ const onData = (chunk) => {
9149
+ const text = chunk.toString("utf8");
9150
+ if (text === "") {
9151
+ cleanup();
9152
+ reject(new Error("Login canceled"));
9153
+ return;
9154
+ }
9155
+ if (text === "\r" || text === "\n") {
9156
+ cleanup();
9157
+ process$1.stderr.write("\n");
9158
+ resolve11(value.trim());
9159
+ return;
9160
+ }
9161
+ if (text === "\x7F") value = value.slice(0, -1);
9162
+ else value += text;
9163
+ };
9164
+ const cleanup = () => {
9165
+ process$1.stdin.off("data", onData);
9166
+ process$1.stdin.setRawMode(false);
9167
+ process$1.stdin.pause();
9168
+ };
9169
+ process$1.stdin.on("data", onData);
9170
+ });
9171
+ }
8775
9172
 
8776
9173
  // src/bin/fx.ts
8777
9174
  var HELP = `fx \u2014 Fabric Experiments CLI
@@ -8791,8 +9188,12 @@ COMMANDS
8791
9188
  import-mojito <dir> Import a directory of Mojito waves into Fabric YAML.
8792
9189
  preview <experimentId> Mint a signed preview link for a variant. Requires --variant.
8793
9190
  test env <action> Create, destroy, list, or reap Databricks test environments.
8794
- test publish <file> Publish BDD/live evidence to Studio Quality.
9191
+ test publish <file> Publish BDD/live/JUnit/CLI evidence to Studio Quality.
8795
9192
  init databricks-tests Scaffold a Databricks BDD test project.
9193
+ login Configure and verify a secure hosted profile.
9194
+ logout [profile] Remove a stored hosted profile.
9195
+ profile [list|show|use] Inspect or switch hosted profiles.
9196
+ doctor Verify API, tenant, gateway, role, and config security.
8796
9197
 
8797
9198
  GLOBAL FLAGS
8798
9199
  --tenant <id> Tenant scope (default: default)
@@ -8807,8 +9208,11 @@ GLOBAL FLAGS
8807
9208
  --remote-url <url> publish: post to a manifest-worker
8808
9209
  --admin-token <tok> publish: bearer token for --remote-url
8809
9210
  --static <dir> publish: write signed manifest + tag-loader bundle to <dir>
8810
- --api-url <url> push/preview: hosted API base URL
8811
- --api-key <key> push/preview: hosted API key
9211
+ --api-url <url> push/preview/test publish: hosted API base URL
9212
+ --api-key <key> push/preview/test publish: hosted API key
9213
+ --profile <name> hosted profile (default: active profile)
9214
+ --studio-url <url> login: branded Studio URL
9215
+ --databricks-profile <p> login: Databricks CLI profile used for Apps OAuth
8812
9216
  --no-publish push: apply actions without publishing manifest
8813
9217
  --name <name> test env: environment name (for example pr-1234)
8814
9218
  --seed <dir> test env create: JSON fixture directory
@@ -8827,7 +9231,7 @@ GLOBAL FLAGS
8827
9231
  -h, --help print this help
8828
9232
  -v, --version print version
8829
9233
  `;
8830
- var VERSION2 = "0.6.4";
9234
+ var VERSION2 = "0.7.0";
8831
9235
  function parse2(argv) {
8832
9236
  const positional = [];
8833
9237
  const flags = {};
@@ -8872,13 +9276,32 @@ async function main() {
8872
9276
  `);
8873
9277
  return 0;
8874
9278
  }
8875
- const tenantId = args.flags.tenant ?? "default";
9279
+ const explicitTenantId = args.flags.tenant;
9280
+ const tenantId = explicitTenantId ?? "default";
8876
9281
  const allowDeletes = args.flags["allow-deletes"] === true;
8877
9282
  switch (args.command) {
8878
9283
  case "":
8879
9284
  case "help":
8880
9285
  process.stdout.write(HELP);
8881
9286
  return 0;
9287
+ case "login":
9288
+ return cmdLogin({
9289
+ profileName: args.flags.profile,
9290
+ studioUrl: args.flags["studio-url"],
9291
+ apiUrl: args.flags["api-url"],
9292
+ apiKey: args.flags["api-key"],
9293
+ tenantId: explicitTenantId,
9294
+ databricksProfile: args.flags["databricks-profile"]
9295
+ });
9296
+ case "logout":
9297
+ return cmdLogout(args.positional[0] ?? args.flags.profile);
9298
+ case "profile":
9299
+ return cmdProfile(
9300
+ args.positional[0] ?? "list",
9301
+ args.positional[1] ?? args.flags.profile
9302
+ );
9303
+ case "doctor":
9304
+ return cmdDoctor({ profileName: args.flags.profile });
8882
9305
  case "validate":
8883
9306
  return cmdValidate(args.positional[0] ?? ".");
8884
9307
  case "plan":
@@ -8897,17 +9320,25 @@ async function main() {
8897
9320
  dryRun: args.flags["dry-run"] === true,
8898
9321
  allowDeletes
8899
9322
  });
8900
- case "push":
9323
+ case "push": {
9324
+ const hosted = await resolveHostedContext({
9325
+ profileName: args.flags.profile,
9326
+ apiUrl: args.flags["api-url"],
9327
+ apiKey: args.flags["api-key"],
9328
+ tenantId: explicitTenantId
9329
+ });
8901
9330
  return cmdPush(args.positional[0] ?? ".", {
8902
- tenantId,
9331
+ tenantId: hosted.tenantId,
8903
9332
  ownerId: args.flags.owner,
8904
9333
  approverId: args.flags.approver,
8905
9334
  dryRun: args.flags["dry-run"] === true,
8906
9335
  allowDeletes,
8907
- apiUrl: args.flags["api-url"],
8908
- apiKey: args.flags["api-key"],
9336
+ apiUrl: hosted.apiUrl,
9337
+ apiKey: hosted.apiKey,
9338
+ bearerToken: hosted.bearerToken,
8909
9339
  publish: args.flags["no-publish"] !== true
8910
9340
  });
9341
+ }
8911
9342
  case "dev":
8912
9343
  return cmdDev({
8913
9344
  port: args.flags.port ? Number(args.flags.port) : void 0,
@@ -8950,32 +9381,47 @@ async function main() {
8950
9381
  outputDir: args.flags.out,
8951
9382
  reportFile: args.flags.report,
8952
9383
  strict: args.flags.strict === true});
8953
- case "preview":
9384
+ case "preview": {
8954
9385
  if (!args.positional[0]) {
8955
9386
  process.stderr.write(
8956
9387
  "Usage: fx preview <experimentId> --variant <key> [--ttl 900] [--origin https://...] [--api-url ... --api-key ...]\n"
8957
9388
  );
8958
9389
  return 1;
8959
9390
  }
9391
+ const hosted = args.flags.local === true ? {} : await resolveHostedContext({
9392
+ profileName: args.flags.profile,
9393
+ apiUrl: args.flags["api-url"],
9394
+ apiKey: args.flags["api-key"],
9395
+ tenantId: explicitTenantId
9396
+ });
8960
9397
  return cmdPreview(args.positional[0], {
8961
- tenantId,
9398
+ tenantId: hosted.tenantId ?? tenantId,
8962
9399
  variantKey: typeof args.flags.variant === "string" ? args.flags.variant : "",
8963
9400
  ttlSeconds: args.flags.ttl ? Number(args.flags.ttl) : void 0,
8964
9401
  origin: args.flags.origin,
8965
- apiUrl: args.flags["api-url"],
8966
- apiKey: args.flags["api-key"],
9402
+ apiUrl: hosted.apiUrl,
9403
+ apiKey: hosted.apiKey,
9404
+ bearerToken: hosted.bearerToken,
8967
9405
  local: args.flags.local === true
8968
9406
  });
9407
+ }
8969
9408
  case "test":
8970
9409
  if (args.positional[0] === "publish") {
8971
9410
  if (!args.positional[1]) {
8972
- process.stderr.write("Usage: fx test publish <evidence.json> [flags]\n");
9411
+ process.stderr.write("Usage: fx test publish <evidence.json|junit.xml> [flags]\n");
8973
9412
  return 1;
8974
9413
  }
8975
- return cmdTestPublish(args.positional[1], {
8976
- tenantId,
9414
+ const hosted = await resolveHostedContext({
9415
+ profileName: args.flags.profile,
8977
9416
  apiUrl: args.flags["api-url"],
8978
9417
  apiKey: args.flags["api-key"],
9418
+ tenantId: explicitTenantId
9419
+ });
9420
+ return cmdTestPublish(args.positional[1], {
9421
+ tenantId: hosted.tenantId,
9422
+ apiUrl: hosted.apiUrl,
9423
+ apiKey: hosted.apiKey,
9424
+ bearerToken: hosted.bearerToken,
8979
9425
  suite: args.flags.suite,
8980
9426
  externalId: args.flags["external-id"],
8981
9427
  runUrl: args.flags["run-url"]