@fabricorg/experiments 0.6.0 → 0.6.1

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
@@ -1,332 +1,23 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- var path = require('path');
5
- var url = require('url');
6
- var promises = require('fs/promises');
7
- var experimentsYaml = require('@fabricorg/experiments-yaml');
8
- var fs = require('fs');
9
- var crypto$1 = require('crypto');
10
- var http = require('http');
11
- var module$1 = require('module');
12
- var yaml = require('yaml');
13
- var databricksTestkit = require('@fabricorg/databricks-testkit');
14
-
15
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
- var __defProp = Object.defineProperty;
17
- var __export = (target, all) => {
18
- for (var name in all)
19
- __defProp(target, name, { get: all[name], enumerable: true });
20
- };
21
- async function loadExperimentDir(dir) {
22
- const entries = await promises.readdir(dir, { withFileTypes: true });
23
- const out = [];
24
- for (const entry of entries) {
25
- if (!entry.isFile()) continue;
26
- const ext = path.extname(entry.name);
27
- if (ext !== ".yaml" && ext !== ".yml") continue;
28
- const path$1 = path.join(dir, entry.name);
29
- out.push({ path: path$1, spec: await loadExperimentFile(path$1) });
30
- }
31
- return out;
32
- }
33
- async function loadExperimentFile(path) {
34
- const text = await promises.readFile(path, "utf8");
35
- return experimentsYaml.parseExperimentYamlTextOrThrow(text);
36
- }
37
-
38
- // src/commands/validate.ts
39
- async function cmdValidate(dir) {
40
- const abs = path.resolve(dir);
41
- try {
42
- const specs = await loadExperimentDir(abs);
43
- if (specs.length === 0) {
44
- process.stdout.write(`No experiment YAML files found in ${abs}
45
- `);
46
- return 1;
47
- }
48
- for (const s of specs) {
49
- process.stdout.write(`\u2713 ${s.path} (${s.spec.id})
50
- `);
51
- }
52
- process.stdout.write(`
53
- ${specs.length} experiment(s) valid.
54
- `);
55
- return 0;
56
- } catch (e) {
57
- const err = e;
58
- process.stderr.write(`\u2717 Validation failed: ${err.message}
59
- `);
60
- return 1;
61
- }
62
- }
63
-
64
- // ../plan/dist/index.js
65
- function diff(args) {
66
- const out = [];
67
- const specsById = new Map(args.specs.map((s) => [s.id, s]));
68
- const currentById = new Map(args.current.map((c) => [c.id, c]));
69
- for (const spec of args.specs) {
70
- const current = currentById.get(spec.id);
71
- if (!current) {
72
- out.push({ kind: "create", spec });
73
- continue;
74
- }
75
- const changes = compareSpecToCurrent(spec, current);
76
- if (changes.length === 0) {
77
- out.push({ kind: "noop", id: spec.id });
78
- } else {
79
- const breaking = changes.some(
80
- (c) => (c.path === "variants" || c.path.startsWith("variants[]")) && // Only "added/removed/renamed variants" while running counts as breaking.
81
- (c.kind === "added" || c.kind === "removed") && (current.state === "running" || current.state === "paused" || current.state === "concluded")
82
- );
83
- out.push({ kind: "update", id: spec.id, spec, current, changes, breaking });
84
- }
85
- }
86
- for (const exp of args.current) {
87
- if (!specsById.has(exp.id) && exp.state !== "killed" && exp.state !== "archived") {
88
- out.push({ kind: "delete", id: exp.id, current: exp });
89
- }
90
- }
91
- return out;
92
- }
93
- function compareSpecToCurrent(spec, current) {
94
- const changes = [];
95
- if (spec.name !== current.name) {
96
- changes.push({ kind: "changed", path: "name", from: current.name, to: spec.name });
97
- }
98
- if ((spec.description ?? null) !== (current.description ?? null)) {
99
- changes.push({
100
- kind: "changed",
101
- path: "description",
102
- from: current.description ?? null,
103
- to: spec.description ?? null
104
- });
105
- }
106
- const specSampleRate = spec.sampleRate ?? (spec.holdback !== void 0 ? 1 - spec.holdback : void 0) ?? spec.audience?.sampleRate ?? 1;
107
- if (specSampleRate !== current.audience.sampleRate) {
108
- changes.push({
109
- kind: "changed",
110
- path: "audience.sampleRate",
111
- from: current.audience.sampleRate,
112
- to: specSampleRate
113
- });
114
- }
115
- if ((spec.divertTo ?? null) !== (current.divertTo ?? null)) {
116
- changes.push({
117
- kind: "changed",
118
- path: "divertTo",
119
- from: current.divertTo ?? null,
120
- to: spec.divertTo ?? null
121
- });
122
- }
123
- if ((spec.manualExposure ?? false) !== (current.manualExposure ?? false)) {
124
- changes.push({
125
- kind: "changed",
126
- path: "manualExposure",
127
- from: current.manualExposure ?? false,
128
- to: spec.manualExposure ?? false
129
- });
130
- }
131
- if (JSON.stringify(spec.trigger ?? null) !== JSON.stringify(current.trigger ?? null)) {
132
- changes.push({
133
- kind: "changed",
134
- path: "trigger",
135
- from: current.trigger ?? null,
136
- to: spec.trigger ?? null
137
- });
138
- }
139
- if ((spec.sharedJs ?? null) !== (current.sharedJs ?? null)) {
140
- changes.push({
141
- kind: "changed",
142
- path: "sharedJs",
143
- from: current.sharedJs ?? null,
144
- to: spec.sharedJs ?? null
145
- });
146
- }
147
- if ((spec.sharedCss ?? null) !== (current.sharedCss ?? null)) {
148
- changes.push({
149
- kind: "changed",
150
- path: "sharedCss",
151
- from: current.sharedCss ?? null,
152
- to: spec.sharedCss ?? null
153
- });
154
- }
155
- if (JSON.stringify(spec.metadata ?? null) !== JSON.stringify(current.metadata ?? null)) {
156
- changes.push({
157
- kind: "changed",
158
- path: "metadata",
159
- from: current.metadata ?? null,
160
- to: spec.metadata ?? null
161
- });
162
- }
163
- const specByKey = new Map(spec.variants.map((v) => [v.key, v]));
164
- const curByKey = new Map(current.variants.map((v) => [v.key, v]));
165
- for (const v of spec.variants) {
166
- if (!curByKey.has(v.key)) {
167
- changes.push({ kind: "added", path: `variants[].${v.key}`, value: v });
168
- } else {
169
- const cur = curByKey.get(v.key);
170
- const variantChanges = compareVariant(v, cur, `variants[${v.key}]`);
171
- changes.push(...variantChanges);
172
- }
173
- }
174
- for (const v of current.variants) {
175
- if (!specByKey.has(v.key)) {
176
- changes.push({ kind: "removed", path: `variants[].${v.key}`, value: v });
177
- }
178
- }
179
- return changes;
180
- }
181
- function compareVariant(spec, cur, prefix) {
182
- const out = [];
183
- if (spec.name !== cur.name) {
184
- out.push({ kind: "changed", path: `${prefix}.name`, from: cur.name, to: spec.name });
185
- }
186
- if ((spec.weight ?? 0) !== (cur.weight ?? 0)) {
187
- out.push({ kind: "changed", path: `${prefix}.weight`, from: cur.weight, to: spec.weight });
188
- }
189
- if ((spec.js ?? null) !== (cur.js ?? null)) {
190
- out.push({ kind: "changed", path: `${prefix}.js`, from: cur.js ?? null, to: spec.js ?? null });
191
- }
192
- if ((spec.css ?? null) !== (cur.css ?? null)) {
193
- out.push({
194
- kind: "changed",
195
- path: `${prefix}.css`,
196
- from: cur.css ?? null,
197
- to: spec.css ?? null
198
- });
199
- }
200
- if (JSON.stringify(spec.domOps ?? null) !== JSON.stringify(cur.domOps ?? null)) {
201
- out.push({
202
- kind: "changed",
203
- path: `${prefix}.domOps`,
204
- from: cur.domOps ?? null,
205
- to: spec.domOps ?? null
206
- });
207
- }
208
- if ((spec.recipeSampleRate ?? null) !== (cur.recipeSampleRate ?? null)) {
209
- out.push({
210
- kind: "changed",
211
- path: `${prefix}.recipeSampleRate`,
212
- from: cur.recipeSampleRate ?? null,
213
- to: spec.recipeSampleRate ?? null
214
- });
215
- }
216
- if (JSON.stringify(spec.payload ?? null) !== JSON.stringify(cur.payload ?? null)) {
217
- out.push({
218
- kind: "changed",
219
- path: `${prefix}.payload`,
220
- from: cur.payload ?? null,
221
- to: spec.payload ?? null
222
- });
223
- }
224
- return out;
225
- }
226
- function plan(args) {
227
- const diffs = diff({ specs: args.specs, current: args.current, tenantId: args.tenantId });
228
- const actions = [];
229
- const blocked = [];
230
- for (const d of diffs) {
231
- if (d.kind === "noop") continue;
232
- if (d.kind === "create") {
233
- actions.push({
234
- actionId: "experiment.create",
235
- params: { spec: d.spec, ownerId: args.ownerId, tenantId: args.tenantId }
236
- });
237
- actions.push({
238
- actionId: "experiment.submit_for_review",
239
- params: { experimentId: d.spec.id, tenantId: args.tenantId }
240
- });
241
- actions.push({
242
- actionId: "experiment.approve",
243
- params: { experimentId: d.spec.id, tenantId: args.tenantId, approverId: args.approverId }
244
- });
245
- actions.push({
246
- actionId: "experiment.start",
247
- params: { experimentId: d.spec.id, tenantId: args.tenantId }
248
- });
249
- } else if (d.kind === "update") {
250
- if (d.breaking) {
251
- blocked.push({
252
- id: d.id,
253
- reason: "Variant set changed after start; create a new experiment id instead."
254
- });
255
- continue;
256
- }
257
- actions.push({
258
- actionId: "experiment.update",
259
- params: { experimentId: d.id, tenantId: args.tenantId, spec: d.spec }
260
- });
261
- } else if (d.kind === "delete") {
262
- if (!args.allowDeletes) {
263
- blocked.push({
264
- id: d.id,
265
- reason: "Removed from YAML; pass --allow-deletes to kill in control plane."
266
- });
267
- continue;
268
- }
269
- actions.push({
270
- actionId: "experiment.kill",
271
- params: {
272
- experimentId: d.id,
273
- tenantId: args.tenantId,
274
- reason: "Removed from YAML"
275
- }
276
- });
277
- }
278
- }
279
- return { diffs, actions, blocked };
280
- }
281
- function formatPlan(p) {
282
- const lines = [];
283
- lines.push("Plan:");
284
- lines.push("");
285
- if (p.diffs.every((d) => d.kind === "noop")) {
286
- lines.push(" No changes. Infrastructure is up to date.");
287
- return lines.join("\n");
288
- }
289
- for (const d of p.diffs) {
290
- lines.push(...renderDiff(d));
291
- }
292
- if (p.blocked.length > 0) {
293
- lines.push("");
294
- lines.push("Blocked:");
295
- for (const b of p.blocked) lines.push(` ! ${b.id}: ${b.reason}`);
296
- }
297
- lines.push("");
298
- const counts = countBy(p.diffs, (d) => d.kind);
299
- lines.push(
300
- `Summary: +${counts.create ?? 0} create, ~${counts.update ?? 0} update, -${counts.delete ?? 0} delete, ${counts.noop ?? 0} unchanged.`
301
- );
302
- return lines.join("\n");
303
- }
304
- function renderDiff(d) {
305
- if (d.kind === "noop") return [];
306
- if (d.kind === "create") return [` + ${d.spec.id} ${d.spec.name} (create)`];
307
- if (d.kind === "delete") return [` - ${d.id} (in control plane but not in YAML; will kill)`];
308
- const out = [` ~ ${d.id} ${d.spec.name} (update${d.breaking ? " \u2014 BLOCKED" : ""})`];
309
- for (const c of d.changes) {
310
- if (c.kind === "added") out.push(` + ${c.path}: ${jsonish(c.value)}`);
311
- else if (c.kind === "removed") out.push(` - ${c.path}: ${jsonish(c.value)}`);
312
- else out.push(` ~ ${c.path}: ${jsonish(c.from)} \u2192 ${jsonish(c.to)}`);
313
- }
314
- return out;
315
- }
316
- function jsonish(v) {
317
- if (v == null) return String(v);
318
- if (typeof v === "string") return JSON.stringify(v);
319
- if (typeof v === "number" || typeof v === "boolean") return String(v);
320
- return JSON.stringify(v);
321
- }
322
- function countBy(arr, key) {
323
- const out = {};
324
- for (const v of arr) {
325
- const k = key(v);
326
- out[k] = (out[k] ?? 0) + 1;
327
- }
328
- return out;
329
- }
4
+ var fs = require('fs');
5
+ var path = require('path');
6
+ var url = require('url');
7
+ var promises = require('fs/promises');
8
+ var yaml = require('yaml');
9
+ var crypto$1 = require('crypto');
10
+ var http = require('http');
11
+ var module$1 = require('module');
12
+ var databricksTestkit = require('@fabricorg/databricks-testkit');
13
+ var fastXmlParser = require('fast-xml-parser');
14
+
15
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
+ var __defProp = Object.defineProperty;
17
+ var __export = (target, all) => {
18
+ for (var name in all)
19
+ __defProp(target, name, { get: all[name], enumerable: true });
20
+ };
330
21
 
331
22
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
332
23
  var external_exports = {};
@@ -4646,6 +4337,8 @@ var Exposure = external_exports.object({
4646
4337
  tenantId: external_exports.string().min(1).default("default"),
4647
4338
  manifestVersion: external_exports.number().int().min(0),
4648
4339
  at: external_exports.string().datetime(),
4340
+ /** Explicit low-cardinality dimensions used by segmented analytics. */
4341
+ dimensions: external_exports.record(external_exports.string()).optional(),
4649
4342
  /** Set when the variant code threw; used as a quality signal. */
4650
4343
  failure: external_exports.object({ message: external_exports.string(), stack: external_exports.string().optional() }).nullable().default(null)
4651
4344
  });
@@ -4893,33 +4586,370 @@ var DomainError = class extends Error {
4893
4586
  this.details = details;
4894
4587
  this.name = "DomainError";
4895
4588
  }
4896
- code;
4897
- details;
4898
- };
4899
- var IllegalTransition = class extends DomainError {
4900
- constructor(from, event2) {
4901
- super(`Illegal transition: ${event2} from state ${from}`, "ILLEGAL_TRANSITION", { from, event: event2 });
4902
- this.name = "IllegalTransition";
4589
+ code;
4590
+ details;
4591
+ };
4592
+ var IllegalTransition = class extends DomainError {
4593
+ constructor(from, event2) {
4594
+ super(`Illegal transition: ${event2} from state ${from}`, "ILLEGAL_TRANSITION", { from, event: event2 });
4595
+ this.name = "IllegalTransition";
4596
+ }
4597
+ };
4598
+ var NotFound = class extends DomainError {
4599
+ constructor(kind, id) {
4600
+ super(`${kind} not found: ${id}`, "NOT_FOUND", { kind, id });
4601
+ this.name = "NotFound";
4602
+ }
4603
+ };
4604
+ var ValidationFailed = class extends DomainError {
4605
+ constructor(message, details) {
4606
+ super(message, "VALIDATION_FAILED", details);
4607
+ this.name = "ValidationFailed";
4608
+ }
4609
+ };
4610
+ var PolicyDenied = class extends DomainError {
4611
+ constructor(message, details) {
4612
+ super(message, "POLICY_DENIED", details);
4613
+ this.name = "PolicyDenied";
4614
+ }
4615
+ };
4616
+ function parseExperimentYamlText(text) {
4617
+ let parsed;
4618
+ try {
4619
+ parsed = yaml.parse(text);
4620
+ } catch (e) {
4621
+ return { ok: false, message: `YAML parse failed: ${e.message}` };
4622
+ }
4623
+ const result = ExperimentSpec.safeParse(parsed);
4624
+ if (!result.success) {
4625
+ return {
4626
+ ok: false,
4627
+ message: "Experiment spec validation failed",
4628
+ issues: result.error.issues.map((issue) => ({
4629
+ path: issue.path.join(".") || "spec",
4630
+ message: issue.message
4631
+ }))
4632
+ };
4633
+ }
4634
+ return { ok: true, spec: result.data };
4635
+ }
4636
+ function parseExperimentYamlTextOrThrow(text) {
4637
+ const result = parseExperimentYamlText(text);
4638
+ if (result.ok) return result.spec;
4639
+ const issueText = result.issues?.map((issue) => `${issue.path}: ${issue.message}`).join("; ");
4640
+ throw new Error(issueText ? `${result.message}: ${issueText}` : result.message);
4641
+ }
4642
+
4643
+ // src/yaml-loader.ts
4644
+ async function loadExperimentDir(dir) {
4645
+ const entries = await promises.readdir(dir, { withFileTypes: true });
4646
+ const out = [];
4647
+ for (const entry of entries) {
4648
+ if (!entry.isFile()) continue;
4649
+ const ext = path.extname(entry.name);
4650
+ if (ext !== ".yaml" && ext !== ".yml") continue;
4651
+ const path$1 = path.join(dir, entry.name);
4652
+ out.push({ path: path$1, spec: await loadExperimentFile(path$1) });
4653
+ }
4654
+ return out;
4655
+ }
4656
+ async function loadExperimentFile(path) {
4657
+ const text = await promises.readFile(path, "utf8");
4658
+ return parseExperimentYamlTextOrThrow(text);
4659
+ }
4660
+
4661
+ // src/commands/validate.ts
4662
+ async function cmdValidate(dir) {
4663
+ const abs = path.resolve(dir);
4664
+ try {
4665
+ const specs = await loadExperimentDir(abs);
4666
+ if (specs.length === 0) {
4667
+ process.stdout.write(`No experiment YAML files found in ${abs}
4668
+ `);
4669
+ return 1;
4670
+ }
4671
+ for (const s of specs) {
4672
+ process.stdout.write(`\u2713 ${s.path} (${s.spec.id})
4673
+ `);
4674
+ }
4675
+ process.stdout.write(`
4676
+ ${specs.length} experiment(s) valid.
4677
+ `);
4678
+ return 0;
4679
+ } catch (e) {
4680
+ const err = e;
4681
+ process.stderr.write(`\u2717 Validation failed: ${err.message}
4682
+ `);
4683
+ return 1;
4684
+ }
4685
+ }
4686
+
4687
+ // ../plan/dist/index.js
4688
+ function diff(args) {
4689
+ const out = [];
4690
+ const specsById = new Map(args.specs.map((s) => [s.id, s]));
4691
+ const currentById = new Map(args.current.map((c) => [c.id, c]));
4692
+ for (const spec of args.specs) {
4693
+ const current = currentById.get(spec.id);
4694
+ if (!current) {
4695
+ out.push({ kind: "create", spec });
4696
+ continue;
4697
+ }
4698
+ const changes = compareSpecToCurrent(spec, current);
4699
+ if (changes.length === 0) {
4700
+ out.push({ kind: "noop", id: spec.id });
4701
+ } else {
4702
+ const breaking = changes.some(
4703
+ (c) => (c.path === "variants" || c.path.startsWith("variants[]")) && // Only "added/removed/renamed variants" while running counts as breaking.
4704
+ (c.kind === "added" || c.kind === "removed") && (current.state === "running" || current.state === "paused" || current.state === "concluded")
4705
+ );
4706
+ out.push({ kind: "update", id: spec.id, spec, current, changes, breaking });
4707
+ }
4708
+ }
4709
+ for (const exp of args.current) {
4710
+ if (!specsById.has(exp.id) && exp.state !== "killed" && exp.state !== "archived") {
4711
+ out.push({ kind: "delete", id: exp.id, current: exp });
4712
+ }
4713
+ }
4714
+ return out;
4715
+ }
4716
+ function compareSpecToCurrent(spec, current) {
4717
+ const changes = [];
4718
+ if (spec.name !== current.name) {
4719
+ changes.push({ kind: "changed", path: "name", from: current.name, to: spec.name });
4720
+ }
4721
+ if ((spec.description ?? null) !== (current.description ?? null)) {
4722
+ changes.push({
4723
+ kind: "changed",
4724
+ path: "description",
4725
+ from: current.description ?? null,
4726
+ to: spec.description ?? null
4727
+ });
4728
+ }
4729
+ const specSampleRate = spec.sampleRate ?? (spec.holdback !== void 0 ? 1 - spec.holdback : void 0) ?? spec.audience?.sampleRate ?? 1;
4730
+ if (specSampleRate !== current.audience.sampleRate) {
4731
+ changes.push({
4732
+ kind: "changed",
4733
+ path: "audience.sampleRate",
4734
+ from: current.audience.sampleRate,
4735
+ to: specSampleRate
4736
+ });
4737
+ }
4738
+ if ((spec.divertTo ?? null) !== (current.divertTo ?? null)) {
4739
+ changes.push({
4740
+ kind: "changed",
4741
+ path: "divertTo",
4742
+ from: current.divertTo ?? null,
4743
+ to: spec.divertTo ?? null
4744
+ });
4745
+ }
4746
+ if ((spec.manualExposure ?? false) !== (current.manualExposure ?? false)) {
4747
+ changes.push({
4748
+ kind: "changed",
4749
+ path: "manualExposure",
4750
+ from: current.manualExposure ?? false,
4751
+ to: spec.manualExposure ?? false
4752
+ });
4753
+ }
4754
+ if (JSON.stringify(spec.trigger ?? null) !== JSON.stringify(current.trigger ?? null)) {
4755
+ changes.push({
4756
+ kind: "changed",
4757
+ path: "trigger",
4758
+ from: current.trigger ?? null,
4759
+ to: spec.trigger ?? null
4760
+ });
4761
+ }
4762
+ if ((spec.sharedJs ?? null) !== (current.sharedJs ?? null)) {
4763
+ changes.push({
4764
+ kind: "changed",
4765
+ path: "sharedJs",
4766
+ from: current.sharedJs ?? null,
4767
+ to: spec.sharedJs ?? null
4768
+ });
4769
+ }
4770
+ if ((spec.sharedCss ?? null) !== (current.sharedCss ?? null)) {
4771
+ changes.push({
4772
+ kind: "changed",
4773
+ path: "sharedCss",
4774
+ from: current.sharedCss ?? null,
4775
+ to: spec.sharedCss ?? null
4776
+ });
4777
+ }
4778
+ if (JSON.stringify(spec.metadata ?? null) !== JSON.stringify(current.metadata ?? null)) {
4779
+ changes.push({
4780
+ kind: "changed",
4781
+ path: "metadata",
4782
+ from: current.metadata ?? null,
4783
+ to: spec.metadata ?? null
4784
+ });
4785
+ }
4786
+ const specByKey = new Map(spec.variants.map((v) => [v.key, v]));
4787
+ const curByKey = new Map(current.variants.map((v) => [v.key, v]));
4788
+ for (const v of spec.variants) {
4789
+ if (!curByKey.has(v.key)) {
4790
+ changes.push({ kind: "added", path: `variants[].${v.key}`, value: v });
4791
+ } else {
4792
+ const cur = curByKey.get(v.key);
4793
+ const variantChanges = compareVariant(v, cur, `variants[${v.key}]`);
4794
+ changes.push(...variantChanges);
4795
+ }
4796
+ }
4797
+ for (const v of current.variants) {
4798
+ if (!specByKey.has(v.key)) {
4799
+ changes.push({ kind: "removed", path: `variants[].${v.key}`, value: v });
4800
+ }
4801
+ }
4802
+ return changes;
4803
+ }
4804
+ function compareVariant(spec, cur, prefix) {
4805
+ const out = [];
4806
+ if (spec.name !== cur.name) {
4807
+ out.push({ kind: "changed", path: `${prefix}.name`, from: cur.name, to: spec.name });
4808
+ }
4809
+ if ((spec.weight ?? 0) !== (cur.weight ?? 0)) {
4810
+ out.push({ kind: "changed", path: `${prefix}.weight`, from: cur.weight, to: spec.weight });
4811
+ }
4812
+ if ((spec.js ?? null) !== (cur.js ?? null)) {
4813
+ out.push({ kind: "changed", path: `${prefix}.js`, from: cur.js ?? null, to: spec.js ?? null });
4814
+ }
4815
+ if ((spec.css ?? null) !== (cur.css ?? null)) {
4816
+ out.push({
4817
+ kind: "changed",
4818
+ path: `${prefix}.css`,
4819
+ from: cur.css ?? null,
4820
+ to: spec.css ?? null
4821
+ });
4822
+ }
4823
+ if (JSON.stringify(spec.domOps ?? null) !== JSON.stringify(cur.domOps ?? null)) {
4824
+ out.push({
4825
+ kind: "changed",
4826
+ path: `${prefix}.domOps`,
4827
+ from: cur.domOps ?? null,
4828
+ to: spec.domOps ?? null
4829
+ });
4830
+ }
4831
+ if ((spec.recipeSampleRate ?? null) !== (cur.recipeSampleRate ?? null)) {
4832
+ out.push({
4833
+ kind: "changed",
4834
+ path: `${prefix}.recipeSampleRate`,
4835
+ from: cur.recipeSampleRate ?? null,
4836
+ to: spec.recipeSampleRate ?? null
4837
+ });
4838
+ }
4839
+ if (JSON.stringify(spec.payload ?? null) !== JSON.stringify(cur.payload ?? null)) {
4840
+ out.push({
4841
+ kind: "changed",
4842
+ path: `${prefix}.payload`,
4843
+ from: cur.payload ?? null,
4844
+ to: spec.payload ?? null
4845
+ });
4846
+ }
4847
+ return out;
4848
+ }
4849
+ function plan(args) {
4850
+ const diffs = diff({ specs: args.specs, current: args.current, tenantId: args.tenantId });
4851
+ const actions = [];
4852
+ const blocked = [];
4853
+ for (const d of diffs) {
4854
+ if (d.kind === "noop") continue;
4855
+ if (d.kind === "create") {
4856
+ actions.push({
4857
+ actionId: "experiment.create",
4858
+ params: { spec: d.spec, ownerId: args.ownerId, tenantId: args.tenantId }
4859
+ });
4860
+ actions.push({
4861
+ actionId: "experiment.submit_for_review",
4862
+ params: { experimentId: d.spec.id, tenantId: args.tenantId }
4863
+ });
4864
+ actions.push({
4865
+ actionId: "experiment.approve",
4866
+ params: { experimentId: d.spec.id, tenantId: args.tenantId, approverId: args.approverId }
4867
+ });
4868
+ actions.push({
4869
+ actionId: "experiment.start",
4870
+ params: { experimentId: d.spec.id, tenantId: args.tenantId }
4871
+ });
4872
+ } else if (d.kind === "update") {
4873
+ if (d.breaking) {
4874
+ blocked.push({
4875
+ id: d.id,
4876
+ reason: "Variant set changed after start; create a new experiment id instead."
4877
+ });
4878
+ continue;
4879
+ }
4880
+ actions.push({
4881
+ actionId: "experiment.update",
4882
+ params: { experimentId: d.id, tenantId: args.tenantId, spec: d.spec }
4883
+ });
4884
+ } else if (d.kind === "delete") {
4885
+ if (!args.allowDeletes) {
4886
+ blocked.push({
4887
+ id: d.id,
4888
+ reason: "Removed from YAML; pass --allow-deletes to kill in control plane."
4889
+ });
4890
+ continue;
4891
+ }
4892
+ actions.push({
4893
+ actionId: "experiment.kill",
4894
+ params: {
4895
+ experimentId: d.id,
4896
+ tenantId: args.tenantId,
4897
+ reason: "Removed from YAML"
4898
+ }
4899
+ });
4900
+ }
4901
+ }
4902
+ return { diffs, actions, blocked };
4903
+ }
4904
+ function formatPlan(p) {
4905
+ const lines = [];
4906
+ lines.push("Plan:");
4907
+ lines.push("");
4908
+ if (p.diffs.every((d) => d.kind === "noop")) {
4909
+ lines.push(" No changes. Infrastructure is up to date.");
4910
+ return lines.join("\n");
4903
4911
  }
4904
- };
4905
- var NotFound = class extends DomainError {
4906
- constructor(kind, id) {
4907
- super(`${kind} not found: ${id}`, "NOT_FOUND", { kind, id });
4908
- this.name = "NotFound";
4912
+ for (const d of p.diffs) {
4913
+ lines.push(...renderDiff(d));
4909
4914
  }
4910
- };
4911
- var ValidationFailed = class extends DomainError {
4912
- constructor(message, details) {
4913
- super(message, "VALIDATION_FAILED", details);
4914
- this.name = "ValidationFailed";
4915
+ if (p.blocked.length > 0) {
4916
+ lines.push("");
4917
+ lines.push("Blocked:");
4918
+ for (const b of p.blocked) lines.push(` ! ${b.id}: ${b.reason}`);
4915
4919
  }
4916
- };
4917
- var PolicyDenied = class extends DomainError {
4918
- constructor(message, details) {
4919
- super(message, "POLICY_DENIED", details);
4920
- this.name = "PolicyDenied";
4920
+ lines.push("");
4921
+ const counts = countBy(p.diffs, (d) => d.kind);
4922
+ lines.push(
4923
+ `Summary: +${counts.create ?? 0} create, ~${counts.update ?? 0} update, -${counts.delete ?? 0} delete, ${counts.noop ?? 0} unchanged.`
4924
+ );
4925
+ return lines.join("\n");
4926
+ }
4927
+ function renderDiff(d) {
4928
+ if (d.kind === "noop") return [];
4929
+ if (d.kind === "create") return [` + ${d.spec.id} ${d.spec.name} (create)`];
4930
+ if (d.kind === "delete") return [` - ${d.id} (in control plane but not in YAML; will kill)`];
4931
+ const out = [` ~ ${d.id} ${d.spec.name} (update${d.breaking ? " \u2014 BLOCKED" : ""})`];
4932
+ for (const c of d.changes) {
4933
+ if (c.kind === "added") out.push(` + ${c.path}: ${jsonish(c.value)}`);
4934
+ else if (c.kind === "removed") out.push(` - ${c.path}: ${jsonish(c.value)}`);
4935
+ else out.push(` ~ ${c.path}: ${jsonish(c.from)} \u2192 ${jsonish(c.to)}`);
4921
4936
  }
4922
- };
4937
+ return out;
4938
+ }
4939
+ function jsonish(v) {
4940
+ if (v == null) return String(v);
4941
+ if (typeof v === "string") return JSON.stringify(v);
4942
+ if (typeof v === "number" || typeof v === "boolean") return String(v);
4943
+ return JSON.stringify(v);
4944
+ }
4945
+ function countBy(arr, key) {
4946
+ const out = {};
4947
+ for (const v of arr) {
4948
+ const k = key(v);
4949
+ out[k] = (out[k] ?? 0) + 1;
4950
+ }
4951
+ return out;
4952
+ }
4923
4953
  var MANIFEST_SCHEMA_VERSION = 1;
4924
4954
  var ManifestVariant = Variant.pick({
4925
4955
  key: true,
@@ -5917,6 +5947,126 @@ function cryptoUuid() {
5917
5947
  }
5918
5948
 
5919
5949
  // ../warehouse/dist/index.js
5950
+ function mean(values) {
5951
+ return values.length === 0 ? 0 : values.reduce((sum, value) => sum + value, 0) / values.length;
5952
+ }
5953
+ function variance(values) {
5954
+ if (values.length === 0) return 0;
5955
+ const average = mean(values);
5956
+ return mean(values.map((value) => (value - average) ** 2));
5957
+ }
5958
+ function covariance(left, right) {
5959
+ if (left.length === 0 || left.length !== right.length) return 0;
5960
+ const leftMean = mean(left);
5961
+ const rightMean = mean(right);
5962
+ return mean(left.map((value, index) => (value - leftMean) * ((right[index] ?? 0) - rightMean)));
5963
+ }
5964
+ function percentile(values, quantile) {
5965
+ if (values.length === 0) return null;
5966
+ const sorted = [...values].sort((left, right) => left - right);
5967
+ const index = (sorted.length - 1) * quantile;
5968
+ const lower = Math.floor(index);
5969
+ const upper = Math.ceil(index);
5970
+ if (lower === upper) return sorted[lower] ?? null;
5971
+ const fraction = index - lower;
5972
+ return (sorted[lower] ?? 0) * (1 - fraction) + (sorted[upper] ?? 0) * fraction;
5973
+ }
5974
+ function parseDimensions(value) {
5975
+ if (!value) return {};
5976
+ if (typeof value !== "string") return value;
5977
+ try {
5978
+ const parsed = JSON.parse(value);
5979
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
5980
+ return Object.fromEntries(
5981
+ Object.entries(parsed).filter(
5982
+ (entry) => typeof entry[1] === "string"
5983
+ )
5984
+ );
5985
+ } catch {
5986
+ return {};
5987
+ }
5988
+ }
5989
+ function buildExperimentAnalytics(subjects, query) {
5990
+ const prePeriodDays = query.prePeriodDays ?? 14;
5991
+ const outcomes = subjects.map((subject) => subject.conversionDepth > 0 ? 1 : 0);
5992
+ const covariates = subjects.map((subject) => subject.prePeriodDepth);
5993
+ const covariateVariance = variance(covariates);
5994
+ const theta = covariateVariance > 0 ? covariance(outcomes, covariates) / covariateVariance : 0;
5995
+ const covariateMean = mean(covariates);
5996
+ const adjusted = outcomes.map(
5997
+ (outcome2, index) => outcome2 - theta * ((covariates[index] ?? 0) - covariateMean)
5998
+ );
5999
+ const outcomeVariance = variance(outcomes);
6000
+ const adjustedVariance = variance(adjusted);
6001
+ const available = covariates.some((value) => value > 0) && covariateVariance > 0;
6002
+ const varianceReduction = available && outcomeVariance > 0 ? 1 - adjustedVariance / outcomeVariance : null;
6003
+ const variantKeys = [...new Set(subjects.map((subject) => subject.variantKey))].sort();
6004
+ const adjustedRate = /* @__PURE__ */ new Map();
6005
+ for (const variantKey of variantKeys) {
6006
+ const values = adjusted.filter((_, index) => subjects[index]?.variantKey === variantKey);
6007
+ adjustedRate.set(variantKey, mean(values));
6008
+ }
6009
+ const controlRate = adjustedRate.get(variantKeys[0] ?? "") ?? 0;
6010
+ const variants = variantKeys.map((variantKey) => {
6011
+ const cohort = subjects.filter((subject) => subject.variantKey === variantKey);
6012
+ const times = cohort.filter((subject) => subject.firstConversionAt).map(
6013
+ (subject) => new Date(subject.firstConversionAt).getTime() - new Date(subject.firstExposureAt).getTime()
6014
+ ).filter((value) => Number.isFinite(value) && value >= 0);
6015
+ const rate = adjustedRate.get(variantKey) ?? 0;
6016
+ return {
6017
+ variantKey,
6018
+ exposedSubjects: cohort.length,
6019
+ convertedSubjects: cohort.filter((subject) => subject.conversionDepth > 0).length,
6020
+ meanTimeToConvertMs: times.length > 0 ? mean(times) : null,
6021
+ medianTimeToConvertMs: percentile(times, 0.5),
6022
+ p90TimeToConvertMs: percentile(times, 0.9),
6023
+ meanConversionDepth: mean(cohort.map((subject) => subject.conversionDepth)),
6024
+ conversionDepth: {
6025
+ oneOrMore: cohort.filter((subject) => subject.conversionDepth >= 1).length,
6026
+ twoOrMore: cohort.filter((subject) => subject.conversionDepth >= 2).length,
6027
+ threeOrMore: cohort.filter((subject) => subject.conversionDepth >= 3).length
6028
+ },
6029
+ cupedAdjustedRate: available ? rate : null,
6030
+ cupedLift: available && variantKey !== variantKeys[0] ? rate - controlRate : null
6031
+ };
6032
+ });
6033
+ const segments = [];
6034
+ if (query.segmentKey) {
6035
+ const grouped = /* @__PURE__ */ new Map();
6036
+ for (const subject of subjects) {
6037
+ const segmentValue = parseDimensions(subject.dimensions)[query.segmentKey] ?? "(unknown)";
6038
+ const key = `${segmentValue}\0${subject.variantKey}`;
6039
+ const rows = grouped.get(key) ?? [];
6040
+ rows.push(subject);
6041
+ grouped.set(key, rows);
6042
+ }
6043
+ for (const [key, cohort] of grouped) {
6044
+ const [segmentValue = "(unknown)", variantKey = ""] = key.split("\0");
6045
+ const conversionCount = cohort.filter((subject) => subject.conversionDepth > 0).length;
6046
+ segments.push({
6047
+ segmentValue,
6048
+ variantKey,
6049
+ exposureCount: cohort.length,
6050
+ conversionCount,
6051
+ conversionRate: cohort.length === 0 ? 0 : conversionCount / cohort.length
6052
+ });
6053
+ }
6054
+ segments.sort(
6055
+ (left, right) => left.segmentValue.localeCompare(right.segmentValue) || left.variantKey.localeCompare(right.variantKey)
6056
+ );
6057
+ }
6058
+ return {
6059
+ variants,
6060
+ segments,
6061
+ ...query.segmentKey ? { segmentKey: query.segmentKey } : {},
6062
+ cuped: {
6063
+ available,
6064
+ prePeriodDays,
6065
+ theta: available ? theta : null,
6066
+ varianceReduction
6067
+ }
6068
+ };
6069
+ }
5920
6070
  var LocalWarehouse = class {
5921
6071
  constructor(dir) {
5922
6072
  this.dir = dir;
@@ -6000,8 +6150,48 @@ var LocalWarehouse = class {
6000
6150
  rows.sort((a, b) => a.variantKey.localeCompare(b.variantKey));
6001
6151
  return rows;
6002
6152
  }
6153
+ async analyze(query) {
6154
+ const exposures = this.firstExposures(query);
6155
+ const prePeriodMs = (query.prePeriodDays ?? 14) * 864e5;
6156
+ return buildExperimentAnalytics(
6157
+ [...exposures.values()].map((exposure) => {
6158
+ const firstAt = new Date(exposure.at).getTime();
6159
+ const matching = this.state.conversions.filter(
6160
+ (conversion) => conversion.tenantId === query.tenantId && conversion.subjectId === exposure.subjectId && conversion.eventName === query.metricEventName
6161
+ ).sort((left, right) => left.at.localeCompare(right.at));
6162
+ const post = matching.filter(
6163
+ (conversion) => conversion.at >= exposure.at && (!query.untilIso || conversion.at < query.untilIso)
6164
+ );
6165
+ const pre = matching.filter((conversion) => {
6166
+ const timestamp = new Date(conversion.at).getTime();
6167
+ return timestamp < firstAt && timestamp >= firstAt - prePeriodMs;
6168
+ });
6169
+ return {
6170
+ subjectId: exposure.subjectId,
6171
+ variantKey: exposure.variantKey,
6172
+ firstExposureAt: exposure.at,
6173
+ firstConversionAt: post[0]?.at,
6174
+ conversionDepth: post.length,
6175
+ prePeriodDepth: pre.length,
6176
+ dimensions: exposure.dimensions
6177
+ };
6178
+ }),
6179
+ query
6180
+ );
6181
+ }
6003
6182
  async close() {
6004
6183
  }
6184
+ firstExposures(query) {
6185
+ const exposures = this.state.exposures.filter(
6186
+ (exposure) => exposure.tenantId === query.tenantId && exposure.experimentId === query.experimentId && (!query.fromIso || exposure.at >= query.fromIso) && (!query.untilIso || exposure.at < query.untilIso)
6187
+ );
6188
+ const first = /* @__PURE__ */ new Map();
6189
+ for (const exposure of exposures) {
6190
+ const prior = first.get(exposure.subjectId);
6191
+ if (!prior || exposure.at < prior.at) first.set(exposure.subjectId, exposure);
6192
+ }
6193
+ return first;
6194
+ }
6005
6195
  };
6006
6196
  async function readNdjson(path) {
6007
6197
  const fs = await import('fs/promises');
@@ -7078,14 +7268,52 @@ var AggregateRow = external_exports.object({
7078
7268
  var AggregateInput = external_exports.object({
7079
7269
  metric: external_exports.string().min(1).max(120),
7080
7270
  fromIso: external_exports.string().datetime().optional(),
7081
- untilIso: external_exports.string().datetime().optional()
7271
+ untilIso: external_exports.string().datetime().optional(),
7272
+ segmentKey: external_exports.string().min(1).max(80).regex(/^[A-Za-z0-9_.-]+$/).optional(),
7273
+ prePeriodDays: external_exports.coerce.number().int().min(1).max(365).optional()
7082
7274
  });
7083
7275
  var AggregateResponse = external_exports.object({
7084
7276
  experimentId: ExperimentId,
7085
7277
  metric: external_exports.string(),
7086
7278
  rows: external_exports.array(AggregateRow),
7087
7279
  /** ISO datetime — when this aggregate was computed. SDKs may cache by this. */
7088
- computedAt: external_exports.string().datetime()
7280
+ computedAt: external_exports.string().datetime(),
7281
+ analytics: external_exports.object({
7282
+ variants: external_exports.array(
7283
+ external_exports.object({
7284
+ variantKey: external_exports.string(),
7285
+ exposedSubjects: external_exports.number().int().nonnegative(),
7286
+ convertedSubjects: external_exports.number().int().nonnegative(),
7287
+ meanTimeToConvertMs: external_exports.number().nonnegative().nullable(),
7288
+ medianTimeToConvertMs: external_exports.number().nonnegative().nullable(),
7289
+ p90TimeToConvertMs: external_exports.number().nonnegative().nullable(),
7290
+ meanConversionDepth: external_exports.number().nonnegative(),
7291
+ conversionDepth: external_exports.object({
7292
+ oneOrMore: external_exports.number().int().nonnegative(),
7293
+ twoOrMore: external_exports.number().int().nonnegative(),
7294
+ threeOrMore: external_exports.number().int().nonnegative()
7295
+ }),
7296
+ cupedAdjustedRate: external_exports.number().nullable(),
7297
+ cupedLift: external_exports.number().nullable()
7298
+ })
7299
+ ),
7300
+ segments: external_exports.array(
7301
+ external_exports.object({
7302
+ segmentValue: external_exports.string(),
7303
+ variantKey: external_exports.string(),
7304
+ exposureCount: external_exports.number().int().nonnegative(),
7305
+ conversionCount: external_exports.number().int().nonnegative(),
7306
+ conversionRate: external_exports.number().min(0).max(1)
7307
+ })
7308
+ ),
7309
+ segmentKey: external_exports.string().optional(),
7310
+ cuped: external_exports.object({
7311
+ available: external_exports.boolean(),
7312
+ prePeriodDays: external_exports.number().int().positive(),
7313
+ theta: external_exports.number().nullable(),
7314
+ varianceReduction: external_exports.number().nullable()
7315
+ })
7316
+ }).optional()
7089
7317
  });
7090
7318
  var InvokeActionInput = external_exports.object({
7091
7319
  actionId: ActionId,
@@ -7190,6 +7418,69 @@ var SamlConfig = external_exports.object({
7190
7418
  message: "connectionId, issuer, ssoUrl, certificate required when SAML is enabled"
7191
7419
  }
7192
7420
  );
7421
+ var TestRunStatus = external_exports.enum(["running", "passed", "failed", "skipped", "canceled"]);
7422
+ var TestCaseStatus = external_exports.enum([
7423
+ "passed",
7424
+ "failed",
7425
+ "skipped",
7426
+ "pending",
7427
+ "undefined",
7428
+ "unknown"
7429
+ ]);
7430
+ var TestCaseResult = external_exports.object({
7431
+ id: external_exports.string().max(240).optional(),
7432
+ name: external_exports.string().min(1).max(500),
7433
+ uri: external_exports.string().max(1e3).optional(),
7434
+ status: TestCaseStatus,
7435
+ durationMs: external_exports.number().int().nonnegative().max(864e5),
7436
+ tags: external_exports.array(external_exports.string().max(120)).max(100).default([]),
7437
+ error: external_exports.string().max(65536).optional(),
7438
+ statementId: external_exports.string().max(240).optional(),
7439
+ resourceUrl: external_exports.string().url().max(4e3).optional(),
7440
+ details: external_exports.record(external_exports.unknown()).optional()
7441
+ });
7442
+ var TestRunSummary = external_exports.object({
7443
+ total: external_exports.number().int().nonnegative(),
7444
+ passed: external_exports.number().int().nonnegative(),
7445
+ failed: external_exports.number().int().nonnegative(),
7446
+ skipped: external_exports.number().int().nonnegative(),
7447
+ pending: external_exports.number().int().nonnegative().default(0)
7448
+ });
7449
+ var TestRunArtifact = external_exports.object({
7450
+ name: external_exports.string().min(1).max(240),
7451
+ url: external_exports.string().url().max(4e3),
7452
+ mediaType: external_exports.string().max(240).optional()
7453
+ });
7454
+ var CreateTestRunInput = external_exports.object({
7455
+ externalId: external_exports.string().min(1).max(300).optional(),
7456
+ source: external_exports.enum(["bdd", "live-suite", "junit", "cli", "other"]),
7457
+ suite: external_exports.string().min(1).max(240),
7458
+ status: TestRunStatus,
7459
+ startedAt: external_exports.string().datetime().nullable().optional(),
7460
+ finishedAt: external_exports.string().datetime().nullable().optional(),
7461
+ durationMs: external_exports.number().int().nonnegative().max(6048e5).default(0),
7462
+ summary: TestRunSummary,
7463
+ environment: external_exports.record(external_exports.unknown()).default({}),
7464
+ revision: external_exports.record(external_exports.unknown()).default({}),
7465
+ cases: external_exports.array(TestCaseResult).max(2e3).default([]),
7466
+ artifacts: external_exports.array(TestRunArtifact).max(100).default([])
7467
+ });
7468
+ var TestRun = CreateTestRunInput.extend({
7469
+ id: external_exports.string().uuid(),
7470
+ orgId: external_exports.string(),
7471
+ createdBy: external_exports.string(),
7472
+ createdAt: external_exports.string().datetime(),
7473
+ updatedAt: external_exports.string().datetime()
7474
+ });
7475
+ var TestRunListInput = external_exports.object({
7476
+ status: TestRunStatus.optional(),
7477
+ source: CreateTestRunInput.shape.source.optional(),
7478
+ suite: external_exports.string().min(1).max(240).optional(),
7479
+ limit: external_exports.coerce.number().int().min(1).max(200).optional()
7480
+ });
7481
+ var TestRunListResponse = external_exports.object({
7482
+ runs: external_exports.array(TestRun.omit({ cases: true }))
7483
+ });
7193
7484
  var endpoints = {
7194
7485
  "tenants.me": {
7195
7486
  method: "GET",
@@ -7462,6 +7753,30 @@ var endpoints = {
7462
7753
  response: SamlConfig,
7463
7754
  mutates: true,
7464
7755
  requiresRole: "owner"
7756
+ },
7757
+ "testRuns.list": {
7758
+ method: "GET",
7759
+ path: "/v1/orgs/:orgId/test-runs",
7760
+ params: TestRunListInput,
7761
+ response: TestRunListResponse,
7762
+ mutates: false,
7763
+ requiresRole: "viewer"
7764
+ },
7765
+ "testRuns.create": {
7766
+ method: "POST",
7767
+ path: "/v1/orgs/:orgId/test-runs",
7768
+ params: CreateTestRunInput,
7769
+ response: TestRun,
7770
+ mutates: true,
7771
+ requiresRole: "experimenter"
7772
+ },
7773
+ "testRuns.get": {
7774
+ method: "GET",
7775
+ path: "/v1/orgs/:orgId/test-runs/:runId",
7776
+ params: Empty,
7777
+ response: TestRun,
7778
+ mutates: false,
7779
+ requiresRole: "viewer"
7465
7780
  }
7466
7781
  };
7467
7782
  function buildPath(template, pathParams) {
@@ -7517,7 +7832,9 @@ var ApiClient = class {
7517
7832
  method: def.method,
7518
7833
  headers: {
7519
7834
  accept: "application/json",
7520
- ...this.opts.apiKey ? { authorization: `Bearer ${this.opts.apiKey}` } : {}
7835
+ // Hosted Fabric API keys use their own header so upstream auth
7836
+ // middleware cannot mistake them for OAuth bearer credentials.
7837
+ ...this.opts.apiKey ? { "x-api-key": this.opts.apiKey } : {}
7521
7838
  },
7522
7839
  credentials: "include"
7523
7840
  };
@@ -7633,6 +7950,11 @@ var ApiClient = class {
7633
7950
  get: (orgId) => this.call("saml.get", {}, orgId ? { orgId } : void 0),
7634
7951
  update: (params, orgId) => this.call("saml.update", params, orgId ? { orgId } : void 0)
7635
7952
  };
7953
+ testRuns = {
7954
+ list: (params = {}, orgId) => this.call("testRuns.list", params, orgId ? { orgId } : void 0),
7955
+ get: (runId, orgId) => this.call("testRuns.get", {}, orgId ? { orgId, runId } : { runId }),
7956
+ create: (params, orgId) => this.call("testRuns.create", params, orgId ? { orgId } : void 0)
7957
+ };
7636
7958
  };
7637
7959
  async function safeJson(r) {
7638
7960
  try {
@@ -7642,7 +7964,7 @@ async function safeJson(r) {
7642
7964
  }
7643
7965
  }
7644
7966
  function sleep(ms) {
7645
- return new Promise((resolve10) => setTimeout(resolve10, ms));
7967
+ return new Promise((resolve11) => setTimeout(resolve11, ms));
7646
7968
  }
7647
7969
 
7648
7970
  // src/commands/preview.ts
@@ -7806,11 +8128,31 @@ async function invokeHostedPlanned(api, action, ownerId, approverId) {
7806
8128
  return api.experiments.invokeAction(action);
7807
8129
  }
7808
8130
  var FILES = {
8131
+ "package.json": `${JSON.stringify(
8132
+ {
8133
+ private: true,
8134
+ type: "module",
8135
+ scripts: { test: "cucumber-js", "test:pretty": "cucumber-js --format pretty" },
8136
+ devDependencies: {
8137
+ "@cucumber/cucumber": "^13.0.0",
8138
+ "@duckdb/node-api": "^1.5.0",
8139
+ "@fabricorg/databricks-bdd": "^0.3.1",
8140
+ tsx: "^4.19.2",
8141
+ typescript: "^5.8.3"
8142
+ }
8143
+ },
8144
+ null,
8145
+ 2
8146
+ )}
8147
+ `,
7809
8148
  "cucumber.mjs": `export default {
7810
8149
  paths: ['features/**/*.feature'],
7811
8150
  import: ['features/support/steps.ts'],
7812
8151
  format: [
7813
8152
  'progress',
8153
+ ['junit', 'reports/bdd-junit.xml'],
8154
+ ['html', 'reports/bdd.html'],
8155
+ ['rerun', 'reports/rerun.txt'],
7814
8156
  ['@fabricorg/databricks-bdd/evidence-formatter', 'reports/evidence.json'],
7815
8157
  ],
7816
8158
  };
@@ -8114,6 +8456,220 @@ async function writeState(path$1, state) {
8114
8456
  await promises.writeFile(path$1, `${JSON.stringify(state, null, 2)}
8115
8457
  `, "utf8");
8116
8458
  }
8459
+ async function cmdTestPublish(evidencePath, options = {}) {
8460
+ const env = options.env ?? process.env;
8461
+ const apiUrl = options.apiUrl ?? env.FX_API_URL;
8462
+ const apiKey = options.apiKey ?? env.FX_API_KEY;
8463
+ const tenantId = options.tenantId ?? env.FX_ORG_ID;
8464
+ if (!apiUrl || !apiKey || !tenantId) {
8465
+ process.stderr.write(
8466
+ "Usage: fx test publish <evidence.json> --api-url <url> --api-key <key> --tenant <orgId>\n"
8467
+ );
8468
+ return 1;
8469
+ }
8470
+ const evidence = parseEvidenceText(await promises.readFile(path.resolve(evidencePath), "utf8"));
8471
+ const input = normalizeTestEvidence(evidence, { ...options, env });
8472
+ const api = new ApiClient({ baseUrl: apiUrl, apiKey, defaultOrgId: tenantId });
8473
+ const created = await api.testRuns.create(input);
8474
+ process.stdout.write(
8475
+ `Published ${created.source} run ${created.id}: ${created.status} (${created.summary.passed}/${created.summary.total} passed)
8476
+ `
8477
+ );
8478
+ return 0;
8479
+ }
8480
+ function normalizeTestEvidence(value, options = {}) {
8481
+ if (!value || typeof value !== "object") throw new Error("Evidence must be a JSON object");
8482
+ const evidence = value;
8483
+ const env = options.env ?? process.env;
8484
+ const kind = String(evidence.kind ?? "");
8485
+ const revision = compact({
8486
+ repository: env.GITHUB_REPOSITORY,
8487
+ sha: env.GITHUB_SHA,
8488
+ branch: env.GITHUB_REF_NAME,
8489
+ runId: env.GITHUB_RUN_ID,
8490
+ runAttempt: env.GITHUB_RUN_ATTEMPT,
8491
+ runUrl: options.runUrl ?? (env.GITHUB_SERVER_URL && env.GITHUB_REPOSITORY && env.GITHUB_RUN_ID ? `${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}/actions/runs/${env.GITHUB_RUN_ID}` : void 0)
8492
+ });
8493
+ const artifacts = typeof revision.runUrl === "string" ? [{ name: "CI run", url: revision.runUrl, mediaType: "text/html" }] : [];
8494
+ const externalId = options.externalId ?? (env.GITHUB_REPOSITORY && env.GITHUB_RUN_ID ? `${kind}:${env.GITHUB_REPOSITORY}:${env.GITHUB_RUN_ID}:${env.GITHUB_RUN_ATTEMPT ?? "1"}` : void 0);
8495
+ if (kind === "databricks-bdd") {
8496
+ const cases = arrayOfRecords(evidence.scenarios).map((scenario, index) => {
8497
+ const failures = arrayOfRecords(scenario.failures);
8498
+ const statementId = failures.find((failure) => typeof failure.statementId === "string")?.statementId;
8499
+ return {
8500
+ id: `${scenario.uri ?? "scenario"}:${index}`,
8501
+ name: String(scenario.name ?? `Scenario ${index + 1}`),
8502
+ ...typeof scenario.uri === "string" ? { uri: scenario.uri } : {},
8503
+ status: normalizeCaseStatus(scenario.status),
8504
+ durationMs: nonnegativeNumber(scenario.durationMs),
8505
+ tags: Array.isArray(scenario.tags) ? scenario.tags.map(String) : [],
8506
+ ...typeof scenario.error === "string" ? { error: scenario.error } : {},
8507
+ ...statementId ? { statementId } : {},
8508
+ ...statementId && env.DATABRICKS_HOST ? {
8509
+ resourceUrl: `${env.DATABRICKS_HOST.replace(/\/$/, "")}/sql/history?uuid=${encodeURIComponent(statementId)}`
8510
+ } : {},
8511
+ ...failures.length > 0 ? { details: { failures } } : {}
8512
+ };
8513
+ });
8514
+ const summary = summarize(cases);
8515
+ return {
8516
+ ...externalId ? { externalId } : {},
8517
+ source: "bdd",
8518
+ suite: options.suite ?? "Databricks BDD",
8519
+ status: evidence.success === false ? "failed" : summary.total === summary.skipped ? "skipped" : "passed",
8520
+ startedAt: null,
8521
+ finishedAt: isoOrNull(evidence.finishedAt),
8522
+ durationMs: cases.reduce((sum, item) => sum + item.durationMs, 0),
8523
+ summary,
8524
+ environment: compact({ profile: evidence.profile }),
8525
+ revision,
8526
+ cases,
8527
+ artifacts
8528
+ };
8529
+ }
8530
+ if (kind === "databricks-live-suite") {
8531
+ const cases = arrayOfRecords(evidence.results).map((result) => ({
8532
+ id: String(result.id ?? ""),
8533
+ name: String(result.description ?? result.id ?? "Live check"),
8534
+ status: result.status === "pass" ? "passed" : result.status === "fail" ? "failed" : "skipped",
8535
+ durationMs: nonnegativeNumber(result.durationMs),
8536
+ tags: [],
8537
+ ...typeof result.error === "string" ? { error: result.error } : {},
8538
+ ...result.details && typeof result.details === "object" ? { details: result.details } : {}
8539
+ }));
8540
+ const summary = summarize(cases);
8541
+ return {
8542
+ ...externalId ? { externalId } : {},
8543
+ source: "live-suite",
8544
+ suite: options.suite ?? "Databricks live suite",
8545
+ status: evidence.success === false ? "failed" : "passed",
8546
+ startedAt: isoOrNull(evidence.startedAt),
8547
+ finishedAt: isoOrNull(evidence.finishedAt),
8548
+ durationMs: cases.reduce((sum, item) => sum + item.durationMs, 0),
8549
+ summary,
8550
+ environment: compact({
8551
+ profile: "live",
8552
+ cloud: env.DBX_TEST_CLOUD ?? "azure",
8553
+ workspace: env.DATABRICKS_HOST,
8554
+ warehouseId: env.DATABRICKS_WAREHOUSE_ID,
8555
+ runtime: env.DBX_TEST_RUNTIME_VERSION,
8556
+ compute: env.DBX_TEST_COMPUTE
8557
+ }),
8558
+ revision,
8559
+ cases,
8560
+ artifacts
8561
+ };
8562
+ }
8563
+ if (kind === "junit") {
8564
+ const cases = arrayOfRecords(evidence.cases).map((testCase, index) => ({
8565
+ id: String(testCase.id ?? `junit:${index}`),
8566
+ name: String(testCase.name ?? `Test ${index + 1}`),
8567
+ ...typeof testCase.uri === "string" ? { uri: testCase.uri } : {},
8568
+ status: normalizeCaseStatus(testCase.status),
8569
+ durationMs: nonnegativeNumber(testCase.durationMs),
8570
+ tags: [],
8571
+ ...typeof testCase.error === "string" ? { error: testCase.error } : {}
8572
+ }));
8573
+ const summary = summarize(cases);
8574
+ return {
8575
+ ...externalId ? { externalId } : {},
8576
+ source: "junit",
8577
+ suite: options.suite ?? String(evidence.suite ?? "JUnit test suite"),
8578
+ status: summary.failed > 0 ? "failed" : summary.total === summary.skipped ? "skipped" : "passed",
8579
+ startedAt: null,
8580
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
8581
+ durationMs: cases.reduce((sum, item) => sum + item.durationMs, 0),
8582
+ summary,
8583
+ environment: compact({ profile: env.DBX_TEST_PROFILE, workspace: env.DATABRICKS_HOST }),
8584
+ revision,
8585
+ cases,
8586
+ artifacts
8587
+ };
8588
+ }
8589
+ throw new Error(`Unsupported evidence kind '${kind || "(missing)"}'`);
8590
+ }
8591
+ function parseEvidenceText(text) {
8592
+ if (!text.trimStart().startsWith("<")) return JSON.parse(text);
8593
+ const parsed = new fastXmlParser.XMLParser({ ignoreAttributes: false, attributeNamePrefix: "@_" }).parse(
8594
+ text
8595
+ );
8596
+ const suites = collectSuites(parsed.testsuites ?? parsed.testsuite);
8597
+ const cases = suites.flatMap(
8598
+ (suite, suiteIndex) => asRecords(suite.testcase).map((testCase, caseIndex) => {
8599
+ const failure = testCase.failure ?? testCase.error;
8600
+ const skipped = testCase.skipped;
8601
+ const error = xmlText(failure);
8602
+ return {
8603
+ id: `${suite["@_name"] ?? suiteIndex}:${testCase["@_name"] ?? caseIndex}`,
8604
+ name: String(testCase["@_name"] ?? `Test ${caseIndex + 1}`),
8605
+ uri: String(testCase["@_classname"] ?? suite["@_name"] ?? ""),
8606
+ status: failure ? "failed" : skipped ? "skipped" : "passed",
8607
+ durationMs: Math.round(Number(testCase["@_time"] ?? 0) * 1e3),
8608
+ ...error ? { error } : {}
8609
+ };
8610
+ })
8611
+ );
8612
+ return {
8613
+ kind: "junit",
8614
+ suite: suites.map((suite) => String(suite["@_name"] ?? "")).filter(Boolean).join(", "),
8615
+ cases
8616
+ };
8617
+ }
8618
+ function summarize(cases) {
8619
+ return {
8620
+ total: cases.length,
8621
+ passed: cases.filter((item) => item.status === "passed").length,
8622
+ failed: cases.filter((item) => item.status === "failed").length,
8623
+ skipped: cases.filter((item) => item.status === "skipped").length,
8624
+ pending: cases.filter((item) => item.status === "pending" || item.status === "undefined").length
8625
+ };
8626
+ }
8627
+ function normalizeCaseStatus(value) {
8628
+ const status = String(value ?? "unknown").toLowerCase();
8629
+ if (["passed", "failed", "skipped", "pending", "undefined"].includes(status)) {
8630
+ return status;
8631
+ }
8632
+ return "unknown";
8633
+ }
8634
+ function arrayOfRecords(value) {
8635
+ return Array.isArray(value) ? value.filter(
8636
+ (item) => Boolean(item && typeof item === "object")
8637
+ ) : [];
8638
+ }
8639
+ function collectSuites(value) {
8640
+ return asRecords(value).flatMap((item) => [
8641
+ ...item.testcase ? [item] : [],
8642
+ ...collectSuites(item.testsuite)
8643
+ ]);
8644
+ }
8645
+ function asRecords(value) {
8646
+ if (Array.isArray(value)) {
8647
+ return value.filter(
8648
+ (item) => Boolean(item && typeof item === "object")
8649
+ );
8650
+ }
8651
+ return value && typeof value === "object" ? [value] : [];
8652
+ }
8653
+ function xmlText(value) {
8654
+ if (typeof value === "string") return value;
8655
+ if (value && typeof value === "object") {
8656
+ const record = value;
8657
+ const message = [record["@_message"], record["#text"]].filter(Boolean).map(String).join("\n");
8658
+ return message || void 0;
8659
+ }
8660
+ return void 0;
8661
+ }
8662
+ function compact(value) {
8663
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
8664
+ }
8665
+ function nonnegativeNumber(value) {
8666
+ const number = Number(value ?? 0);
8667
+ return Number.isFinite(number) && number >= 0 ? Math.round(number) : 0;
8668
+ }
8669
+ function isoOrNull(value) {
8670
+ if (typeof value !== "string" || Number.isNaN(Date.parse(value))) return null;
8671
+ return new Date(value).toISOString();
8672
+ }
8117
8673
 
8118
8674
  // src/bin/fx.ts
8119
8675
  var HELP = `fx \u2014 Fabric Experiments CLI
@@ -8133,6 +8689,7 @@ COMMANDS
8133
8689
  import-mojito <dir> Import a directory of Mojito waves into Fabric YAML.
8134
8690
  preview <experimentId> Mint a signed preview link for a variant. Requires --variant.
8135
8691
  test env <action> Create, destroy, list, or reap Databricks test environments.
8692
+ test publish <file> Publish BDD/live evidence to Studio Quality.
8136
8693
  init databricks-tests Scaffold a Databricks BDD test project.
8137
8694
 
8138
8695
  GLOBAL FLAGS
@@ -8158,12 +8715,15 @@ GLOBAL FLAGS
8158
8715
  --skip-catalog-grant principal already has USE CATALOG (least-privilege bootstrap)
8159
8716
  --lakebase-branch test env create: clone a TTL-scoped Lakebase branch
8160
8717
  --lakebase-project <name> Lakebase project resource (projects/<id>)
8718
+ --suite <name> test publish: display name for the suite
8719
+ --external-id <id> test publish: idempotent CI run identifier
8720
+ --run-url <url> test publish: CI artifact/run link
8161
8721
  --key-id <id> publish: keyId to sign with (default: dev-default)
8162
8722
  -h, --help print this help
8163
8723
  -v, --version print version
8164
8724
  `;
8165
- var VERSION2 = "0.6.0";
8166
- function parse(argv) {
8725
+ var VERSION2 = "0.6.1";
8726
+ function parse2(argv) {
8167
8727
  const positional = [];
8168
8728
  const flags = {};
8169
8729
  let command = "";
@@ -8197,7 +8757,7 @@ function parse(argv) {
8197
8757
  return { command, positional, flags };
8198
8758
  }
8199
8759
  async function main() {
8200
- const args = parse(process.argv.slice(2));
8760
+ const args = parse2(process.argv.slice(2));
8201
8761
  if (args.flags.h || args.flags.help) {
8202
8762
  process.stdout.write(HELP);
8203
8763
  return 0;
@@ -8298,8 +8858,22 @@ async function main() {
8298
8858
  local: args.flags.local === true
8299
8859
  });
8300
8860
  case "test":
8861
+ if (args.positional[0] === "publish") {
8862
+ if (!args.positional[1]) {
8863
+ process.stderr.write("Usage: fx test publish <evidence.json> [flags]\n");
8864
+ return 1;
8865
+ }
8866
+ return cmdTestPublish(args.positional[1], {
8867
+ tenantId,
8868
+ apiUrl: args.flags["api-url"],
8869
+ apiKey: args.flags["api-key"],
8870
+ suite: args.flags.suite,
8871
+ externalId: args.flags["external-id"],
8872
+ runUrl: args.flags["run-url"]
8873
+ });
8874
+ }
8301
8875
  if (args.positional[0] !== "env") {
8302
- process.stderr.write("Usage: fx test env <create|destroy|list|reap> [flags]\n");
8876
+ process.stderr.write("Usage: fx test <env|publish> [args] [flags]\n");
8303
8877
  return 1;
8304
8878
  }
8305
8879
  return cmdTestEnv(args.positional[1] ?? "", {
@@ -8325,7 +8899,7 @@ ${HELP}`);
8325
8899
  return 1;
8326
8900
  }
8327
8901
  }
8328
- var isMain = process.argv[1] && path.resolve(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('fx.cjs', document.baseURI).href)))) === path.resolve(process.argv[1]);
8902
+ var isMain = process.argv[1] && path.resolve(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('fx.cjs', document.baseURI).href)))) === path.resolve(fs.realpathSync(process.argv[1]));
8329
8903
  if (isMain) {
8330
8904
  main().then((code) => {
8331
8905
  process.exit(code);
@@ -8337,6 +8911,6 @@ if (isMain) {
8337
8911
  }
8338
8912
 
8339
8913
  exports.main = main;
8340
- exports.parse = parse;
8914
+ exports.parse = parse2;
8341
8915
  //# sourceMappingURL=fx.cjs.map
8342
8916
  //# sourceMappingURL=fx.cjs.map