@featurevisor/core 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/lib/datasource/datasource.d.ts +1 -1
  2. package/lib/datasource/datasource.js +4 -14
  3. package/lib/datasource/datasource.js.map +1 -1
  4. package/lib/datasource/requiredFeatures.d.ts +7 -0
  5. package/lib/datasource/requiredFeatures.js +38 -0
  6. package/lib/datasource/requiredFeatures.js.map +1 -0
  7. package/lib/linter/checkCircularDependency.d.ts +1 -1
  8. package/lib/linter/checkCircularDependency.js +3 -22
  9. package/lib/linter/checkCircularDependency.js.map +1 -1
  10. package/lib/linter/conditionSchema.js +27 -3
  11. package/lib/linter/conditionSchema.js.map +1 -1
  12. package/lib/linter/testSchema.d.ts +4 -0
  13. package/lib/linter/testSchema.js +46 -4
  14. package/lib/linter/testSchema.js.map +1 -1
  15. package/lib/promoter/index.js +62 -1
  16. package/lib/promoter/index.js.map +1 -1
  17. package/lib/tester/testFeature.js +17 -16
  18. package/lib/tester/testFeature.js.map +1 -1
  19. package/package.json +10 -7
  20. package/CHANGELOG.md +0 -2246
  21. package/coverage/clover.xml +0 -5456
  22. package/coverage/coverage-final.json +0 -64
  23. package/coverage/lcov-report/base.css +0 -224
  24. package/coverage/lcov-report/block-navigation.js +0 -87
  25. package/coverage/lcov-report/favicon.png +0 -0
  26. package/coverage/lcov-report/index.html +0 -371
  27. package/coverage/lcov-report/prettify.css +0 -1
  28. package/coverage/lcov-report/prettify.js +0 -2
  29. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  30. package/coverage/lcov-report/sorter.js +0 -210
  31. package/coverage/lcov-report/src/assess-distribution/index.html +0 -116
  32. package/coverage/lcov-report/src/assess-distribution/index.ts.html +0 -754
  33. package/coverage/lcov-report/src/benchmark/index.html +0 -116
  34. package/coverage/lcov-report/src/benchmark/index.ts.html +0 -793
  35. package/coverage/lcov-report/src/builder/allocator.ts.html +0 -220
  36. package/coverage/lcov-report/src/builder/applyContextToConditions.ts.html +0 -502
  37. package/coverage/lcov-report/src/builder/applyContextToDatafile.ts.html +0 -772
  38. package/coverage/lcov-report/src/builder/applyContextToSegments.ts.html +0 -580
  39. package/coverage/lcov-report/src/builder/buildDatafile.ts.html +0 -2053
  40. package/coverage/lcov-report/src/builder/buildProject.ts.html +0 -1117
  41. package/coverage/lcov-report/src/builder/buildRuntimeDatafiles.ts.html +0 -256
  42. package/coverage/lcov-report/src/builder/getFeatureRanges.ts.html +0 -268
  43. package/coverage/lcov-report/src/builder/hashes.ts.html +0 -412
  44. package/coverage/lcov-report/src/builder/index.html +0 -311
  45. package/coverage/lcov-report/src/builder/index.ts.html +0 -91
  46. package/coverage/lcov-report/src/builder/mutateVariables.ts.html +0 -421
  47. package/coverage/lcov-report/src/builder/mutator.ts.html +0 -796
  48. package/coverage/lcov-report/src/builder/revision.ts.html +0 -151
  49. package/coverage/lcov-report/src/builder/traffic.ts.html +0 -661
  50. package/coverage/lcov-report/src/cli/cli.ts.html +0 -400
  51. package/coverage/lcov-report/src/cli/index.html +0 -131
  52. package/coverage/lcov-report/src/cli/plugins.ts.html +0 -214
  53. package/coverage/lcov-report/src/config/index.html +0 -131
  54. package/coverage/lcov-report/src/config/index.ts.html +0 -88
  55. package/coverage/lcov-report/src/config/projectConfig.ts.html +0 -925
  56. package/coverage/lcov-report/src/datasource/adapter.ts.html +0 -253
  57. package/coverage/lcov-report/src/datasource/datasource.ts.html +0 -1000
  58. package/coverage/lcov-report/src/datasource/filesystemAdapter.ts.html +0 -1576
  59. package/coverage/lcov-report/src/datasource/index.html +0 -161
  60. package/coverage/lcov-report/src/datasource/index.ts.html +0 -94
  61. package/coverage/lcov-report/src/evaluate/index.html +0 -116
  62. package/coverage/lcov-report/src/evaluate/index.ts.html +0 -814
  63. package/coverage/lcov-report/src/find-duplicate-segments/findDuplicateSegments.ts.html +0 -313
  64. package/coverage/lcov-report/src/find-duplicate-segments/index.html +0 -131
  65. package/coverage/lcov-report/src/find-duplicate-segments/index.ts.html +0 -307
  66. package/coverage/lcov-report/src/find-usage/index.html +0 -116
  67. package/coverage/lcov-report/src/find-usage/index.ts.html +0 -1780
  68. package/coverage/lcov-report/src/generate-code/index.html +0 -131
  69. package/coverage/lcov-report/src/generate-code/index.ts.html +0 -403
  70. package/coverage/lcov-report/src/generate-code/typescript.ts.html +0 -1909
  71. package/coverage/lcov-report/src/index.html +0 -131
  72. package/coverage/lcov-report/src/info/index.html +0 -116
  73. package/coverage/lcov-report/src/info/index.ts.html +0 -472
  74. package/coverage/lcov-report/src/init/index.html +0 -116
  75. package/coverage/lcov-report/src/init/index.ts.html +0 -280
  76. package/coverage/lcov-report/src/linter/attributeSchema.ts.html +0 -1963
  77. package/coverage/lcov-report/src/linter/checkCircularDependency.ts.html +0 -220
  78. package/coverage/lcov-report/src/linter/checkPercentageExceedingSlot.ts.html +0 -268
  79. package/coverage/lcov-report/src/linter/conditionSchema.ts.html +0 -2224
  80. package/coverage/lcov-report/src/linter/featureSchema.ts.html +0 -5851
  81. package/coverage/lcov-report/src/linter/groupSchema.ts.html +0 -226
  82. package/coverage/lcov-report/src/linter/index.html +0 -326
  83. package/coverage/lcov-report/src/linter/index.ts.html +0 -88
  84. package/coverage/lcov-report/src/linter/lintProject.ts.html +0 -2704
  85. package/coverage/lcov-report/src/linter/mutationNotation.ts.html +0 -1411
  86. package/coverage/lcov-report/src/linter/printError.ts.html +0 -289
  87. package/coverage/lcov-report/src/linter/schema.ts.html +0 -1558
  88. package/coverage/lcov-report/src/linter/segmentSchema.ts.html +0 -139
  89. package/coverage/lcov-report/src/linter/targetSchema.ts.html +0 -223
  90. package/coverage/lcov-report/src/linter/testSchema.ts.html +0 -529
  91. package/coverage/lcov-report/src/linter/zodHelpers.ts.html +0 -133
  92. package/coverage/lcov-report/src/list/index.html +0 -131
  93. package/coverage/lcov-report/src/list/index.ts.html +0 -2065
  94. package/coverage/lcov-report/src/list/matrix.ts.html +0 -721
  95. package/coverage/lcov-report/src/promoter/index.html +0 -116
  96. package/coverage/lcov-report/src/promoter/index.ts.html +0 -3883
  97. package/coverage/lcov-report/src/sets.ts.html +0 -313
  98. package/coverage/lcov-report/src/targeting.ts.html +0 -403
  99. package/coverage/lcov-report/src/tester/cliFormat.ts.html +0 -133
  100. package/coverage/lcov-report/src/tester/helpers.ts.html +0 -313
  101. package/coverage/lcov-report/src/tester/index.html +0 -206
  102. package/coverage/lcov-report/src/tester/prettyDuration.ts.html +0 -187
  103. package/coverage/lcov-report/src/tester/printTestResult.ts.html +0 -337
  104. package/coverage/lcov-report/src/tester/testFeature.ts.html +0 -1186
  105. package/coverage/lcov-report/src/tester/testProject.ts.html +0 -1018
  106. package/coverage/lcov-report/src/tester/testSegment.ts.html +0 -316
  107. package/coverage/lcov-report/src/utils/extractKeys.ts.html +0 -493
  108. package/coverage/lcov-report/src/utils/git.ts.html +0 -559
  109. package/coverage/lcov-report/src/utils/index.html +0 -161
  110. package/coverage/lcov-report/src/utils/index.ts.html +0 -94
  111. package/coverage/lcov-report/src/utils/pretty.ts.html +0 -121
  112. package/coverage/lcov.info +0 -11615
  113. package/jest.config.js +0 -22
  114. package/json-schema/README.md +0 -5
  115. package/json-schema/attribute.json +0 -40
  116. package/json-schema/feature.json +0 -394
  117. package/json-schema/segment.json +0 -137
  118. package/src/assess-distribution/index.ts +0 -223
  119. package/src/benchmark/index.ts +0 -236
  120. package/src/builder/allocator.spec.ts +0 -105
  121. package/src/builder/allocator.ts +0 -45
  122. package/src/builder/applyContextToConditions.spec.ts +0 -2677
  123. package/src/builder/applyContextToConditions.ts +0 -139
  124. package/src/builder/applyContextToDatafile.spec.ts +0 -2626
  125. package/src/builder/applyContextToDatafile.ts +0 -229
  126. package/src/builder/applyContextToSegments.spec.ts +0 -1593
  127. package/src/builder/applyContextToSegments.ts +0 -165
  128. package/src/builder/buildDatafile.spec.ts +0 -445
  129. package/src/builder/buildDatafile.ts +0 -656
  130. package/src/builder/buildProject.ts +0 -344
  131. package/src/builder/buildRuntimeDatafiles.ts +0 -57
  132. package/src/builder/getFeatureRanges.ts +0 -61
  133. package/src/builder/hashes.ts +0 -109
  134. package/src/builder/index.ts +0 -2
  135. package/src/builder/mutateVariables.spec.ts +0 -1179
  136. package/src/builder/mutateVariables.ts +0 -112
  137. package/src/builder/mutator.spec.ts +0 -413
  138. package/src/builder/mutator.ts +0 -237
  139. package/src/builder/revision.spec.ts +0 -22
  140. package/src/builder/revision.ts +0 -22
  141. package/src/builder/traffic.spec.ts +0 -946
  142. package/src/builder/traffic.ts +0 -192
  143. package/src/cli/cli.ts +0 -105
  144. package/src/cli/index.ts +0 -2
  145. package/src/cli/plugins.ts +0 -43
  146. package/src/config/index.ts +0 -1
  147. package/src/config/projectConfig.spec.ts +0 -194
  148. package/src/config/projectConfig.ts +0 -280
  149. package/src/datasource/adapter.ts +0 -56
  150. package/src/datasource/datasource.ts +0 -305
  151. package/src/datasource/filesystemAdapter.spec.ts +0 -212
  152. package/src/datasource/filesystemAdapter.ts +0 -497
  153. package/src/datasource/index.ts +0 -3
  154. package/src/dependencies.ts +0 -13
  155. package/src/evaluate/index.ts +0 -243
  156. package/src/find-duplicate-segments/findDuplicateSegments.ts +0 -76
  157. package/src/find-duplicate-segments/index.ts +0 -74
  158. package/src/find-usage/index.ts +0 -565
  159. package/src/generate-code/index.ts +0 -106
  160. package/src/generate-code/typescript.spec.ts +0 -214
  161. package/src/generate-code/typescript.ts +0 -608
  162. package/src/index.ts +0 -20
  163. package/src/info/index.ts +0 -129
  164. package/src/init/index.ts +0 -65
  165. package/src/linter/attributeSchema.spec.ts +0 -342
  166. package/src/linter/attributeSchema.ts +0 -626
  167. package/src/linter/checkCircularDependency.ts +0 -45
  168. package/src/linter/checkPercentageExceedingSlot.ts +0 -61
  169. package/src/linter/conditionSchema.spec.ts +0 -510
  170. package/src/linter/conditionSchema.ts +0 -713
  171. package/src/linter/featureSchema.spec.ts +0 -1985
  172. package/src/linter/featureSchema.ts +0 -1922
  173. package/src/linter/groupSchema.ts +0 -47
  174. package/src/linter/index.ts +0 -1
  175. package/src/linter/lintProject.spec.ts +0 -336
  176. package/src/linter/lintProject.ts +0 -873
  177. package/src/linter/mutationNotation.spec.ts +0 -704
  178. package/src/linter/mutationNotation.ts +0 -442
  179. package/src/linter/printError.ts +0 -68
  180. package/src/linter/schema.spec.ts +0 -690
  181. package/src/linter/schema.ts +0 -491
  182. package/src/linter/segmentSchema.spec.ts +0 -358
  183. package/src/linter/segmentSchema.ts +0 -18
  184. package/src/linter/targetSchema.spec.ts +0 -159
  185. package/src/linter/targetSchema.ts +0 -46
  186. package/src/linter/testSchema.spec.ts +0 -258
  187. package/src/linter/testSchema.ts +0 -148
  188. package/src/linter/zodHelpers.ts +0 -16
  189. package/src/list/index.spec.ts +0 -135
  190. package/src/list/index.ts +0 -660
  191. package/src/list/matrix.spec.ts +0 -49
  192. package/src/list/matrix.ts +0 -212
  193. package/src/promoter/index.spec.ts +0 -617
  194. package/src/promoter/index.ts +0 -1266
  195. package/src/sets.ts +0 -76
  196. package/src/targeting.spec.ts +0 -74
  197. package/src/targeting.ts +0 -106
  198. package/src/tester/cliFormat.ts +0 -16
  199. package/src/tester/helpers.spec.ts +0 -149
  200. package/src/tester/helpers.ts +0 -76
  201. package/src/tester/index.ts +0 -2
  202. package/src/tester/prettyDuration.ts +0 -34
  203. package/src/tester/printTestResult.ts +0 -84
  204. package/src/tester/testFeature.ts +0 -367
  205. package/src/tester/testProject.spec.ts +0 -50
  206. package/src/tester/testProject.ts +0 -311
  207. package/src/tester/testSegment.ts +0 -77
  208. package/src/utils/extractKeys.ts +0 -136
  209. package/src/utils/git.ts +0 -158
  210. package/src/utils/index.ts +0 -3
  211. package/src/utils/pretty.ts +0 -12
  212. package/tsconfig.cjs.json +0 -13
  213. package/tsconfig.typecheck.json +0 -9
@@ -1,223 +0,0 @@
1
- import { randomBytes } from "crypto";
2
-
3
- import type { FeatureKey, AttributeKey, Context, DatafileContent } from "@featurevisor/types";
4
- import { createFeaturevisor } from "@featurevisor/sdk";
5
-
6
- import { Dependencies } from "../dependencies";
7
- import { buildRuntimeDatafiles } from "../builder/buildRuntimeDatafiles";
8
- import { prettyPercentage, prettyNumber } from "../utils";
9
- import { Plugin } from "../cli";
10
- import { getProjectSetExecutions, printSetHeader } from "../sets";
11
- import { CLI_COLOR_CYAN, CLI_FORMAT_BOLD, CLI_FORMAT_GREEN, colorize } from "../tester/cliFormat";
12
-
13
- const UUID_LENGTHS = [4, 2, 2, 2, 6];
14
-
15
- function generateUUID(): string {
16
- return UUID_LENGTHS.map((len) => randomBytes(len).toString("hex")).join("-");
17
- }
18
-
19
- type EvaluationsCount = Record<string, number>;
20
-
21
- function printCounts(evaluations: EvaluationsCount, n: number, sort = true) {
22
- let entries = Object.entries(evaluations);
23
-
24
- if (sort) {
25
- entries = entries.sort((a, b) => {
26
- if (a[1] > b[1]) {
27
- return -1;
28
- }
29
-
30
- if (a[1] < b[1]) {
31
- return 1;
32
- }
33
-
34
- return 0;
35
- });
36
- }
37
-
38
- const longestValueLength = Object.keys(evaluations).reduce(
39
- (acc, curr) => (curr.length > acc ? curr.length : acc),
40
- 0,
41
- );
42
-
43
- const highestCount = Object.values(evaluations).reduce(
44
- (acc, curr) => (curr > acc ? curr : acc),
45
- 0,
46
- );
47
- const prettyHighestCountLength = prettyNumber(highestCount).length;
48
-
49
- for (const [value, count] of entries) {
50
- console.log(
51
- ` ${colorize("•", CLI_COLOR_CYAN)} ${value}:`.padEnd(longestValueLength + 14, " "),
52
- `\t${prettyNumber(count).padStart(prettyHighestCountLength, " ")}`,
53
- `\t${prettyPercentage(count, n).padStart(7, " ")}`,
54
- );
55
- }
56
- }
57
-
58
- function createContext(providedContext: Context, populateUuid?: AttributeKey[]): Context {
59
- const context = { ...providedContext };
60
-
61
- if (populateUuid) {
62
- for (const key of populateUuid) {
63
- context[key] = generateUUID();
64
- }
65
- }
66
-
67
- return context;
68
- }
69
-
70
- export interface AssessDistributionOptions {
71
- environment?: string;
72
- feature: FeatureKey;
73
- context: Context;
74
- n: number;
75
- inflate?: number;
76
-
77
- populateUuid?: AttributeKey[];
78
- verbose?: boolean;
79
- target?: string | string[];
80
- }
81
-
82
- async function assessDistributionWithDatafile(
83
- datafileContent: DatafileContent,
84
- options: AssessDistributionOptions,
85
- target?: string,
86
- ) {
87
- console.log("");
88
- console.log(CLI_FORMAT_BOLD, "Assess Featurevisor distribution");
89
- console.log(` ${colorize("Feature", CLI_COLOR_CYAN)}: ${options.feature}`);
90
- console.log(` ${colorize("Environment", CLI_COLOR_CYAN)}: ${options.environment || false}`);
91
- if (target) console.log(` ${colorize("Target", CLI_COLOR_CYAN)}: ${target}`);
92
- console.log(` ${colorize("Iterations", CLI_COLOR_CYAN)}: ${prettyNumber(options.n)}`);
93
-
94
- /**
95
- * Initialize SDK
96
- */
97
- const f = createFeaturevisor({
98
- datafile: datafileContent as DatafileContent,
99
- logLevel: "warn",
100
- });
101
- console.log("");
102
- console.log(CLI_FORMAT_GREEN, "SDK initialized");
103
-
104
- /**
105
- * Evaluations
106
- */
107
- let hasVariations = false;
108
- const feature = f.getFeature(options.feature);
109
-
110
- if (feature && feature.variations) {
111
- hasVariations = true;
112
- }
113
-
114
- const flagEvaluations: EvaluationsCount = {
115
- enabled: 0,
116
- disabled: 0,
117
- };
118
-
119
- const variationEvaluations: EvaluationsCount = {};
120
-
121
- console.log("");
122
- console.log(`Evaluating ${prettyNumber(options.n)} times...`);
123
-
124
- for (let i = 0; i < options.n; i++) {
125
- const context = createContext(options.context, options.populateUuid);
126
- if (options.verbose) {
127
- console.log(`[${i + 1}/${options.n}] Evaluating against context: ${JSON.stringify(context)}`);
128
- }
129
-
130
- // flag
131
- const flagEvaluation = f.isEnabled(options.feature, context);
132
-
133
- if (flagEvaluation) {
134
- flagEvaluations.enabled++;
135
- } else {
136
- flagEvaluations.disabled++;
137
- }
138
-
139
- // variation
140
- if (hasVariations) {
141
- const variationEvaluation = f.getVariation(options.feature, context) as string;
142
-
143
- if (!variationEvaluations[variationEvaluation]) {
144
- variationEvaluations[variationEvaluation] = 0;
145
- }
146
-
147
- variationEvaluations[variationEvaluation]++;
148
- }
149
- }
150
-
151
- /**
152
- * Print results
153
- */
154
-
155
- console.log("");
156
- console.log(CLI_FORMAT_BOLD, "Flag evaluations");
157
- console.log("");
158
- printCounts(flagEvaluations, options.n);
159
-
160
- if (hasVariations) {
161
- console.log("");
162
- console.log(CLI_FORMAT_BOLD, "Variation evaluations");
163
- console.log("");
164
- printCounts(variationEvaluations, options.n);
165
- }
166
- }
167
-
168
- export async function assessDistribution(deps: Dependencies, options: AssessDistributionOptions) {
169
- const datafileBuildStart = Date.now();
170
- const datafiles = await buildRuntimeDatafiles(deps, {
171
- environment: options.environment || false,
172
- target: options.target,
173
- revision: "include-all-features",
174
- inflate: options.inflate,
175
- });
176
- const datafileBuildDuration = Date.now() - datafileBuildStart;
177
-
178
- console.log("");
179
- console.log(`Building ${datafiles.length} datafile${datafiles.length === 1 ? "" : "s"}...`);
180
- console.log(` ${colorize("Build duration", CLI_COLOR_CYAN)}: ${datafileBuildDuration}ms`);
181
-
182
- for (const entry of datafiles) {
183
- await assessDistributionWithDatafile(entry.datafile, options, entry.target);
184
- }
185
- }
186
-
187
- export const assessDistributionPlugin: Plugin = {
188
- command: "assess-distribution",
189
- handler: async ({ rootDirectoryPath, projectConfig, datasource, parsed }) => {
190
- const executions = await getProjectSetExecutions(projectConfig, datasource, parsed.set);
191
-
192
- for (const execution of executions) {
193
- printSetHeader(projectConfig, execution.set);
194
-
195
- await assessDistribution(
196
- {
197
- rootDirectoryPath,
198
- projectConfig: execution.projectConfig,
199
- datasource: execution.datasource,
200
- options: parsed,
201
- },
202
- {
203
- environment: parsed.environment,
204
- feature: parsed.feature,
205
- n: parseInt(parsed.n, 10) || 1,
206
- context: parsed.context ? JSON.parse(parsed.context) : {},
207
- populateUuid: Array.isArray(parsed.populateUuid)
208
- ? parsed.populateUuid
209
- : [parsed.populateUuid as string].filter(Boolean),
210
- verbose: parsed.verbose,
211
- target: parsed.target,
212
- },
213
- );
214
- }
215
- },
216
- examples: [
217
- {
218
- command:
219
- "assess-distribution --environment=production --feature=my_feature --context='{}' --populateUuid=userId -n=100",
220
- description: "test traffic distribution a feature against provided context",
221
- },
222
- ],
223
- };
@@ -1,236 +0,0 @@
1
- import type { Context, DatafileContent } from "@featurevisor/types";
2
- import { createFeaturevisor } from "@featurevisor/sdk";
3
- import type { Featurevisor } from "@featurevisor/sdk";
4
-
5
- import { buildRuntimeDatafiles } from "../builder/buildRuntimeDatafiles";
6
- import { Dependencies } from "../dependencies";
7
- import { prettyDuration } from "../tester/prettyDuration";
8
- import { Plugin } from "../cli";
9
- import { getProjectSetExecutions, printSetHeader } from "../sets";
10
- import { CLI_COLOR_CYAN, CLI_FORMAT_BOLD, CLI_FORMAT_GREEN, colorize } from "../tester/cliFormat";
11
-
12
- export interface BenchmarkOutput {
13
- value: any;
14
- duration: number; // ms
15
- minDuration: number; // ms
16
- averageDuration: number; // ms
17
- maxDuration: number; // ms
18
- }
19
-
20
- function benchmarkEvaluation(n: number, evaluate: () => any): BenchmarkOutput {
21
- let value: any;
22
- let totalDurationNs = 0n;
23
- let minDurationNs: bigint | undefined;
24
- let maxDurationNs = 0n;
25
-
26
- for (let i = 0; i < n; i++) {
27
- const start = process.hrtime.bigint();
28
- value = evaluate();
29
- const durationNs = process.hrtime.bigint() - start;
30
-
31
- totalDurationNs += durationNs;
32
- if (typeof minDurationNs === "undefined" || durationNs < minDurationNs) {
33
- minDurationNs = durationNs;
34
- }
35
- if (durationNs > maxDurationNs) {
36
- maxDurationNs = durationNs;
37
- }
38
- }
39
-
40
- const duration = Number(totalDurationNs) / 1_000_000;
41
-
42
- return {
43
- value,
44
- duration,
45
- minDuration: Number(minDurationNs || 0n) / 1_000_000,
46
- averageDuration: duration / n,
47
- maxDuration: Number(maxDurationNs) / 1_000_000,
48
- };
49
- }
50
-
51
- function formatDurationMs(duration: number): string {
52
- return `${duration.toFixed(6)}ms`;
53
- }
54
-
55
- export function benchmarkFeatureFlag(
56
- f: Featurevisor,
57
- featureKey: string,
58
- context: Record<string, unknown>,
59
- n: number,
60
- ): BenchmarkOutput {
61
- return benchmarkEvaluation(n, () => f.isEnabled(featureKey, context as Context));
62
- }
63
-
64
- export function benchmarkFeatureVariation(
65
- f: Featurevisor,
66
- featureKey: string,
67
- context: Record<string, unknown>,
68
- n: number,
69
- ): BenchmarkOutput {
70
- return benchmarkEvaluation(n, () => f.getVariation(featureKey, context as Context));
71
- }
72
-
73
- export function benchmarkFeatureVariable(
74
- f: Featurevisor,
75
- featureKey: string,
76
- variableKey: string,
77
- context: Record<string, unknown>,
78
- n: number,
79
- ): BenchmarkOutput {
80
- return benchmarkEvaluation(n, () => f.getVariable(featureKey, variableKey, context as Context));
81
- }
82
-
83
- export interface BenchmarkOptions {
84
- environment?: string;
85
- feature: string;
86
- n: number;
87
- context: Record<string, unknown>;
88
- variation?: boolean;
89
- variable?: string;
90
- inflate?: number;
91
- target?: string | string[];
92
- }
93
-
94
- async function benchmarkFeatureWithDatafile(
95
- datafileContent: DatafileContent,
96
- options: BenchmarkOptions,
97
- target?: string,
98
- ): Promise<void> {
99
- console.log("");
100
- console.log(CLI_FORMAT_BOLD, "Benchmark Featurevisor feature");
101
- console.log(` ${colorize("Feature", CLI_COLOR_CYAN)}: ${options.feature}`);
102
- console.log(` ${colorize("Environment", CLI_COLOR_CYAN)}: ${options.environment || false}`);
103
- if (target) console.log(` ${colorize("Target", CLI_COLOR_CYAN)}: ${target}`);
104
- console.log(` ${colorize("Iterations", CLI_COLOR_CYAN)}: ${options.n}`);
105
-
106
- console.log(
107
- ` ${colorize("Datafile size", CLI_COLOR_CYAN)}: ${(JSON.stringify(datafileContent).length / 1024).toFixed(2)} kB`,
108
- );
109
-
110
- if (options.inflate) {
111
- console.log("");
112
- console.log(
113
- ` ${colorize("Features count", CLI_COLOR_CYAN)}: ${Object.keys(datafileContent.features).length}`,
114
- );
115
- console.log(
116
- ` ${colorize("Segments count", CLI_COLOR_CYAN)}: ${Object.keys(datafileContent.segments).length}`,
117
- );
118
- }
119
-
120
- console.log("");
121
-
122
- const f = createFeaturevisor({
123
- datafile: datafileContent as DatafileContent,
124
- logLevel: "warn",
125
- });
126
- console.log(CLI_FORMAT_GREEN, "SDK initialized");
127
-
128
- console.log("");
129
- console.log(` ${colorize("Context", CLI_COLOR_CYAN)}: ${JSON.stringify(options.context)}`);
130
-
131
- let output: BenchmarkOutput;
132
- if (options.variable) {
133
- // variable
134
- console.log(`Evaluating variable "${options.variable}" ${options.n} times...`);
135
- output = benchmarkFeatureVariable(
136
- f,
137
- options.feature,
138
- options.variable,
139
- options.context,
140
- options.n,
141
- );
142
- } else if (options.variation) {
143
- // variation
144
- console.log(`Evaluating variation ${options.n} times...`);
145
- output = benchmarkFeatureVariation(f, options.feature, options.context, options.n);
146
- } else {
147
- // flag
148
- console.log(`Evaluating flag ${options.n} times...`);
149
- output = benchmarkFeatureFlag(f, options.feature, options.context, options.n);
150
- }
151
-
152
- console.log("");
153
-
154
- console.log(` ${colorize("Evaluated value", CLI_COLOR_CYAN)}: ${JSON.stringify(output.value)}`);
155
- console.log(
156
- ` ${colorize("Total duration", CLI_COLOR_CYAN)}: ${prettyDuration(output.duration)}`,
157
- );
158
- console.log(
159
- ` ${colorize("Minimum duration", CLI_COLOR_CYAN)}: ${formatDurationMs(output.minDuration)}`,
160
- );
161
- console.log(
162
- ` ${colorize("Average duration", CLI_COLOR_CYAN)}: ${formatDurationMs(output.averageDuration)}`,
163
- );
164
- console.log(
165
- ` ${colorize("Maximum duration", CLI_COLOR_CYAN)}: ${formatDurationMs(output.maxDuration)}`,
166
- );
167
- }
168
-
169
- export async function benchmarkFeature(
170
- deps: Dependencies,
171
- options: BenchmarkOptions,
172
- ): Promise<void> {
173
- const datafileBuildStart = Date.now();
174
- const datafiles = await buildRuntimeDatafiles(deps, {
175
- environment: options.environment || false,
176
- target: options.target,
177
- revision: "include-all-features",
178
- inflate: options.inflate,
179
- });
180
- const datafileBuildDuration = Date.now() - datafileBuildStart;
181
-
182
- console.log("");
183
- console.log(`Building ${datafiles.length} datafile${datafiles.length === 1 ? "" : "s"}...`);
184
- console.log(` ${colorize("Build duration", CLI_COLOR_CYAN)}: ${datafileBuildDuration}ms`);
185
-
186
- for (const entry of datafiles) {
187
- await benchmarkFeatureWithDatafile(entry.datafile, options, entry.target);
188
- }
189
- }
190
-
191
- export const benchmarkPlugin: Plugin = {
192
- command: "benchmark",
193
- handler: async ({ rootDirectoryPath, projectConfig, datasource, parsed }) => {
194
- const executions = await getProjectSetExecutions(projectConfig, datasource, parsed.set);
195
-
196
- for (const execution of executions) {
197
- printSetHeader(projectConfig, execution.set);
198
-
199
- await benchmarkFeature(
200
- {
201
- rootDirectoryPath,
202
- projectConfig: execution.projectConfig,
203
- datasource: execution.datasource,
204
- options: parsed,
205
- },
206
- {
207
- environment: parsed.environment,
208
- feature: parsed.feature,
209
- n: parseInt(parsed.n, 10) || 1,
210
- context: parsed.context ? JSON.parse(parsed.context) : {},
211
- variation: parsed.variation || undefined,
212
- variable: parsed.variable || undefined,
213
- inflate: parseInt(parsed.inflate, 10) || undefined,
214
- target: parsed.target,
215
- },
216
- );
217
- }
218
- },
219
- examples: [
220
- {
221
- command:
222
- 'benchmark --environment=production --feature=my_feature -n=1000 --context=\'{"userId": "123"}\'',
223
- description: "Benchmark a feature flag",
224
- },
225
- {
226
- command:
227
- 'benchmark --environment=production --feature=my_feature -n=1000 --context=\'{"userId": "123"}\' --variation',
228
- description: "Benchmark a feature variation",
229
- },
230
- {
231
- command:
232
- 'benchmark --environment=production --feature=my_feature -n=1000 --context=\'{"userId": "123"}\' --variable=my-variable',
233
- description: "Benchmark a feature variable",
234
- },
235
- ],
236
- };
@@ -1,105 +0,0 @@
1
- import type { Range } from "@featurevisor/types";
2
- import { getAllocation, getUpdatedAvailableRangesAfterFilling } from "./allocator";
3
-
4
- describe("core: allocator", function () {
5
- test("is a function", function () {
6
- expect(getAllocation).toBeInstanceOf(Function);
7
- expect(getUpdatedAvailableRangesAfterFilling).toBeInstanceOf(Function);
8
- });
9
-
10
- test("fills a single range fully", function () {
11
- const availableRanges = [[0, 100]] as Range[];
12
- const result = getAllocation(availableRanges, 100);
13
-
14
- expect(result).toEqual(availableRanges);
15
-
16
- const updatedAvailableRanges = getUpdatedAvailableRangesAfterFilling(availableRanges, 100);
17
- expect(updatedAvailableRanges).toEqual([]);
18
- });
19
-
20
- test("fills a single range partially", function () {
21
- const availableRanges = [[0, 100]] as Range[];
22
- const result = getAllocation(availableRanges, 80);
23
-
24
- expect(result).toEqual([[0, 80]]);
25
-
26
- const updatedAvailableRanges = getUpdatedAvailableRangesAfterFilling(availableRanges, 80);
27
- expect(updatedAvailableRanges).toEqual([[80, 100]]);
28
- });
29
-
30
- test("fills multiple ranges fully", function () {
31
- const availableRanges = [
32
- [0, 50],
33
- [50, 100],
34
- ] as Range[];
35
- const result = getAllocation(availableRanges, 100);
36
-
37
- expect(result).toEqual(availableRanges);
38
-
39
- const updatedAvailableRanges = getUpdatedAvailableRangesAfterFilling(availableRanges, 100);
40
- expect(updatedAvailableRanges).toEqual([]);
41
- });
42
-
43
- test("fills multiple ranges with breaks in between fully", function () {
44
- const availableRanges = [
45
- [0, 40],
46
- [60, 100],
47
- ] as Range[];
48
- const result = getAllocation(availableRanges, 80);
49
-
50
- expect(result).toEqual(availableRanges);
51
-
52
- const updatedAvailableRanges = getUpdatedAvailableRangesAfterFilling(availableRanges, 80);
53
- expect(updatedAvailableRanges).toEqual([]);
54
- });
55
-
56
- test("fills multiple ranges partially", function () {
57
- const availableRanges = [
58
- [0, 50],
59
- [50, 100],
60
- ] as Range[];
61
- const result = getAllocation(availableRanges, 80);
62
-
63
- expect(result).toEqual([
64
- [0, 50],
65
- [50, 80],
66
- ]);
67
-
68
- const updatedAvailableRanges = getUpdatedAvailableRangesAfterFilling(availableRanges, 80);
69
- expect(updatedAvailableRanges).toEqual([[80, 100]]);
70
- });
71
-
72
- test("fills multiple ranges with breaks in between partially", function () {
73
- const availableRanges = [
74
- [0, 40],
75
- [60, 100],
76
- ] as Range[];
77
- const result = getAllocation(availableRanges, 50);
78
-
79
- expect(result).toEqual([
80
- [0, 40],
81
- [60, 70],
82
- ]);
83
-
84
- const updatedAvailableRanges = getUpdatedAvailableRangesAfterFilling(availableRanges, 50);
85
- expect(updatedAvailableRanges).toEqual([[70, 100]]);
86
- });
87
-
88
- test("fills multiple ranges with breaks in between partially, with 3 range items", function () {
89
- const availableRanges = [
90
- [0, 30],
91
- [60, 70],
92
- [90, 95],
93
- ] as Range[];
94
- const result = getAllocation(availableRanges, 42);
95
-
96
- expect(result).toEqual([
97
- [0, 30],
98
- [60, 70],
99
- [90, 92],
100
- ]);
101
-
102
- const updatedAvailableRanges = getUpdatedAvailableRangesAfterFilling(availableRanges, 42);
103
- expect(updatedAvailableRanges).toEqual([[92, 95]]);
104
- });
105
- });
@@ -1,45 +0,0 @@
1
- import type { Range, Percentage } from "@featurevisor/types";
2
-
3
- export function getAllocation(availableRanges: Range[], fill: Percentage): Range[] {
4
- const result: Range[] = [];
5
-
6
- let remaining = fill;
7
- let i = 0;
8
- while (remaining > 0 && i < availableRanges.length) {
9
- const range = availableRanges[i];
10
- const [start, end] = range;
11
-
12
- const rangeFill = Math.min(remaining, end - start);
13
- result.push([start, start + rangeFill]);
14
- remaining -= rangeFill;
15
- i++;
16
- }
17
-
18
- return result;
19
- }
20
-
21
- export function getUpdatedAvailableRangesAfterFilling(
22
- availableRanges: Range[],
23
- fill: Percentage,
24
- ): Range[] {
25
- if (fill === 0) {
26
- return availableRanges;
27
- }
28
-
29
- const result: Range[] = [];
30
-
31
- let remaining = fill;
32
- let i = 0;
33
- while (remaining > 0 && i < availableRanges.length) {
34
- const range = availableRanges[i];
35
- const [start, end] = range;
36
- const rangeFill = Math.min(remaining, end - start);
37
- if (rangeFill < end - start) {
38
- result.push([start + rangeFill, end]);
39
- }
40
- remaining -= rangeFill;
41
- i++;
42
- }
43
-
44
- return result;
45
- }