@flaghoist/core 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Damilola Oluwafemi and the Flaghoist contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/index.cjs ADDED
@@ -0,0 +1,300 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ FLAG_KEY_RULE: () => FLAG_KEY_RULE,
24
+ FORBIDDEN_ATTRIBUTES: () => FORBIDDEN_ATTRIBUTES,
25
+ LIMITS: () => LIMITS,
26
+ clampPercentage: () => clampPercentage,
27
+ compareSemver: () => compareSemver,
28
+ createFlag: () => createFlag,
29
+ evaluate: () => evaluate,
30
+ evaluateAll: () => evaluateAll,
31
+ isInRollout: () => isInRollout,
32
+ isValidFlagKey: () => isValidFlagKey,
33
+ matchCondition: () => matchCondition,
34
+ matchesAllConditions: () => matchesAllConditions,
35
+ parseFlag: () => parseFlag,
36
+ stickyBucket: () => stickyBucket,
37
+ version: () => version
38
+ });
39
+ module.exports = __toCommonJS(index_exports);
40
+
41
+ // src/hash.ts
42
+ function clampPercentage(percentage) {
43
+ if (Number.isNaN(percentage)) return 0;
44
+ return Math.max(0, Math.min(100, percentage));
45
+ }
46
+ async function stickyBucket(seed) {
47
+ const data = new TextEncoder().encode(seed);
48
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", data);
49
+ return new DataView(digest).getUint32(0) % 100;
50
+ }
51
+ async function isInRollout(targetingKey, flagKey, percentage) {
52
+ const pct = clampPercentage(percentage);
53
+ if (pct >= 100) return true;
54
+ if (pct <= 0) return false;
55
+ const bucket = await stickyBucket(`${targetingKey}:${flagKey}`);
56
+ return bucket < pct;
57
+ }
58
+
59
+ // src/limits.ts
60
+ var LIMITS = {
61
+ maxKeyLength: 256,
62
+ maxRules: 100,
63
+ maxConditionsPerRule: 50,
64
+ maxListItems: 1e3,
65
+ maxValueLength: 1024
66
+ };
67
+ var FLAG_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
68
+ var FORBIDDEN_ATTRIBUTES = /* @__PURE__ */ new Set([
69
+ "__proto__",
70
+ "constructor",
71
+ "prototype"
72
+ ]);
73
+ function isValidFlagKey(key) {
74
+ return key.length >= 1 && key.length <= LIMITS.maxKeyLength && FLAG_KEY_PATTERN.test(key);
75
+ }
76
+ var FLAG_KEY_RULE = "must be 1-256 characters of [A-Za-z0-9._-] and start with an alphanumeric";
77
+
78
+ // src/operators.ts
79
+ function isScalar(v) {
80
+ return typeof v === "string" || typeof v === "number" || typeof v === "boolean";
81
+ }
82
+ function compareNumbers(a, v, test) {
83
+ const x = Number(a);
84
+ const y = Number(v);
85
+ if (Number.isNaN(x) || Number.isNaN(y)) return false;
86
+ return test(x, y);
87
+ }
88
+ function toInt(part) {
89
+ const n = parseInt(part ?? "", 10);
90
+ return Number.isNaN(n) ? 0 : n;
91
+ }
92
+ function parseSemver(v) {
93
+ const clean = v.trim().replace(/^v/, "");
94
+ const dash = clean.indexOf("-");
95
+ const core = dash === -1 ? clean : clean.slice(0, dash);
96
+ const pre = dash === -1 ? "" : clean.slice(dash + 1);
97
+ const [major, minor, patch] = core.split(".");
98
+ return { major: toInt(major), minor: toInt(minor), patch: toInt(patch), pre };
99
+ }
100
+ function compareSemver(a, b) {
101
+ const x = parseSemver(a);
102
+ const y = parseSemver(b);
103
+ if (x.major !== y.major) return x.major < y.major ? -1 : 1;
104
+ if (x.minor !== y.minor) return x.minor < y.minor ? -1 : 1;
105
+ if (x.patch !== y.patch) return x.patch < y.patch ? -1 : 1;
106
+ if (x.pre === y.pre) return 0;
107
+ if (x.pre === "") return 1;
108
+ if (y.pre === "") return -1;
109
+ return x.pre < y.pre ? -1 : 1;
110
+ }
111
+ function compareSemvers(a, v, test) {
112
+ if (typeof a !== "string" || typeof v !== "string") return false;
113
+ return test(compareSemver(a, v));
114
+ }
115
+ var operators = {
116
+ eq: (a, v) => isScalar(v) && a === v,
117
+ neq: (a, v) => isScalar(v) && a !== v,
118
+ in: (a, v) => Array.isArray(v) && v.some((item) => item === a),
119
+ notIn: (a, v) => Array.isArray(v) && !v.some((item) => item === a),
120
+ contains: (a, v) => typeof a === "string" && typeof v === "string" && a.includes(v),
121
+ startsWith: (a, v) => typeof a === "string" && typeof v === "string" && a.startsWith(v),
122
+ endsWith: (a, v) => typeof a === "string" && typeof v === "string" && a.endsWith(v),
123
+ gt: (a, v) => compareNumbers(a, v, (x, y) => x > y),
124
+ gte: (a, v) => compareNumbers(a, v, (x, y) => x >= y),
125
+ lt: (a, v) => compareNumbers(a, v, (x, y) => x < y),
126
+ lte: (a, v) => compareNumbers(a, v, (x, y) => x <= y),
127
+ semverGte: (a, v) => compareSemvers(a, v, (cmp) => cmp >= 0),
128
+ semverLt: (a, v) => compareSemvers(a, v, (cmp) => cmp < 0)
129
+ };
130
+ function matchCondition(condition, context) {
131
+ if (FORBIDDEN_ATTRIBUTES.has(condition.attribute)) return false;
132
+ if (!Object.hasOwn(context, condition.attribute)) return false;
133
+ const attr = context[condition.attribute];
134
+ if (attr === void 0) return false;
135
+ const op = operators[condition.operator];
136
+ if (!op) return false;
137
+ return op(attr, condition.value);
138
+ }
139
+ function matchesAllConditions(conditions, context) {
140
+ return conditions.every((condition) => matchCondition(condition, context));
141
+ }
142
+
143
+ // src/evaluate.ts
144
+ function isSplit(percentage) {
145
+ return percentage > 0 && percentage < 100;
146
+ }
147
+ async function resolveRule(result, targetingKey, flagKey, ruleIndex) {
148
+ if (!result.enabled) return { value: false, reason: "TARGETING_MATCH", ruleIndex };
149
+ const percentage = result.rollout?.percentage ?? 100;
150
+ const value = await isInRollout(targetingKey, flagKey, percentage);
151
+ return { value, reason: isSplit(percentage) ? "SPLIT" : "TARGETING_MATCH", ruleIndex };
152
+ }
153
+ async function evaluate(flag, context = {}) {
154
+ if (!flag.enabled) return { value: false, reason: "DISABLED" };
155
+ const targetingKey = context.targetingKey ?? "";
156
+ let ruleIndex = 0;
157
+ for (const rule of flag.rules ?? []) {
158
+ if (matchesAllConditions(rule.conditions, context)) {
159
+ return resolveRule(rule.result, targetingKey, flag.key, ruleIndex);
160
+ }
161
+ ruleIndex++;
162
+ }
163
+ const percentage = flag.rollout.percentage;
164
+ const value = await isInRollout(targetingKey, flag.key, percentage);
165
+ return { value, reason: isSplit(percentage) ? "SPLIT" : "DEFAULT" };
166
+ }
167
+ async function evaluateAll(flags, context = {}) {
168
+ const entries = await Promise.all(
169
+ flags.map(async (flag) => [flag.key, await evaluate(flag, context)])
170
+ );
171
+ return Object.fromEntries(entries);
172
+ }
173
+
174
+ // src/validate.ts
175
+ var OPERATORS = [
176
+ "eq",
177
+ "neq",
178
+ "in",
179
+ "notIn",
180
+ "contains",
181
+ "startsWith",
182
+ "endsWith",
183
+ "gt",
184
+ "gte",
185
+ "lt",
186
+ "lte",
187
+ "semverGte",
188
+ "semverLt"
189
+ ];
190
+ function asRecord(input) {
191
+ return typeof input === "object" && input !== null ? input : null;
192
+ }
193
+ function isConditionValue(v) {
194
+ if (typeof v === "string") return v.length <= LIMITS.maxValueLength;
195
+ if (typeof v === "number" || typeof v === "boolean") return true;
196
+ if (Array.isArray(v)) {
197
+ if (v.length > LIMITS.maxListItems) return false;
198
+ return v.every(
199
+ (x) => typeof x === "string" ? x.length <= LIMITS.maxValueLength : typeof x === "number"
200
+ );
201
+ }
202
+ return false;
203
+ }
204
+ function parseCondition(input) {
205
+ const o = asRecord(input);
206
+ if (!o) return null;
207
+ if (typeof o.attribute !== "string") return null;
208
+ if (o.attribute.length === 0 || o.attribute.length > LIMITS.maxKeyLength) return null;
209
+ if (FORBIDDEN_ATTRIBUTES.has(o.attribute)) return null;
210
+ if (typeof o.operator !== "string" || !OPERATORS.includes(o.operator)) return null;
211
+ if (!isConditionValue(o.value)) return null;
212
+ return { attribute: o.attribute, operator: o.operator, value: o.value };
213
+ }
214
+ function parseRuleResult(input) {
215
+ const o = asRecord(input);
216
+ if (!o || typeof o.enabled !== "boolean") return null;
217
+ const result = { enabled: o.enabled };
218
+ const rollout = asRecord(o.rollout);
219
+ if (rollout && typeof rollout.percentage === "number") {
220
+ result.rollout = { percentage: clampPercentage(rollout.percentage) };
221
+ }
222
+ return result;
223
+ }
224
+ function parseRule(input) {
225
+ const o = asRecord(input);
226
+ if (!o || !Array.isArray(o.conditions)) return null;
227
+ if (o.conditions.length > LIMITS.maxConditionsPerRule) return null;
228
+ const conditions = o.conditions.map(parseCondition);
229
+ if (conditions.some((c) => c === null)) return null;
230
+ const result = parseRuleResult(o.result);
231
+ if (!result) return null;
232
+ const rule = { conditions, result };
233
+ if (typeof o.description === "string") rule.description = o.description;
234
+ return rule;
235
+ }
236
+ function parseMetadata(input) {
237
+ const now = (/* @__PURE__ */ new Date()).toISOString();
238
+ const o = asRecord(input) ?? {};
239
+ return {
240
+ createdBy: typeof o.createdBy === "string" ? o.createdBy : "unknown",
241
+ createdAt: typeof o.createdAt === "string" ? o.createdAt : now,
242
+ updatedBy: typeof o.updatedBy === "string" ? o.updatedBy : "unknown",
243
+ updatedAt: typeof o.updatedAt === "string" ? o.updatedAt : now
244
+ };
245
+ }
246
+ function parseFlag(input) {
247
+ const o = asRecord(input);
248
+ if (!o) return null;
249
+ if (typeof o.key !== "string" || !isValidFlagKey(o.key)) return null;
250
+ if (typeof o.enabled !== "boolean") return null;
251
+ const rollout = asRecord(o.rollout);
252
+ const percentage = rollout && typeof rollout.percentage === "number" ? clampPercentage(rollout.percentage) : 0;
253
+ const rawRules = Array.isArray(o.rules) ? o.rules : [];
254
+ if (rawRules.length > LIMITS.maxRules) return null;
255
+ const rules = rawRules.map(parseRule).filter((r) => r !== null);
256
+ return {
257
+ key: o.key,
258
+ enabled: o.enabled,
259
+ rollout: { percentage },
260
+ rules,
261
+ description: typeof o.description === "string" ? o.description : "",
262
+ metadata: parseMetadata(o.metadata)
263
+ };
264
+ }
265
+ function createFlag(input) {
266
+ if (!isValidFlagKey(input.key)) {
267
+ throw new Error(`Invalid flag key ${JSON.stringify(input.key)}: ${FLAG_KEY_RULE}.`);
268
+ }
269
+ const now = (/* @__PURE__ */ new Date()).toISOString();
270
+ const identity = input.identity ?? "system";
271
+ return {
272
+ key: input.key,
273
+ enabled: input.enabled ?? false,
274
+ rollout: { percentage: clampPercentage(input.rollout?.percentage ?? 0) },
275
+ rules: input.rules ?? [],
276
+ description: input.description ?? "",
277
+ metadata: { createdBy: identity, createdAt: now, updatedBy: identity, updatedAt: now }
278
+ };
279
+ }
280
+
281
+ // src/index.ts
282
+ var version = "0.0.0";
283
+ // Annotate the CommonJS export names for ESM import in node:
284
+ 0 && (module.exports = {
285
+ FLAG_KEY_RULE,
286
+ FORBIDDEN_ATTRIBUTES,
287
+ LIMITS,
288
+ clampPercentage,
289
+ compareSemver,
290
+ createFlag,
291
+ evaluate,
292
+ evaluateAll,
293
+ isInRollout,
294
+ isValidFlagKey,
295
+ matchCondition,
296
+ matchesAllConditions,
297
+ parseFlag,
298
+ stickyBucket,
299
+ version
300
+ });
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Comparison operators available to targeting conditions. The set is intentionally
3
+ * bounded for v1; regex (`matches`) is deliberately excluded as a ReDoS footgun.
4
+ */
5
+ type Operator = 'eq' | 'neq' | 'in' | 'notIn' | 'contains' | 'startsWith' | 'endsWith' | 'gt' | 'gte' | 'lt' | 'lte' | 'semverGte' | 'semverLt';
6
+ /** A scalar attribute drawn from the evaluation context. */
7
+ type AttributeValue = string | number | boolean;
8
+ /** A value a condition compares against — scalar, or a list for `in` / `notIn`. */
9
+ type ConditionValue = string | number | boolean | Array<string | number>;
10
+ /** A single `attribute operator value` predicate. */
11
+ interface Condition {
12
+ attribute: string;
13
+ operator: Operator;
14
+ value: ConditionValue;
15
+ }
16
+ /** What a matched targeting rule serves. */
17
+ interface RuleResult {
18
+ enabled: boolean;
19
+ /** Optional rollout within the matched cohort. Absent means 100% (fully on). */
20
+ rollout?: {
21
+ percentage: number;
22
+ };
23
+ }
24
+ /**
25
+ * An ordered targeting rule. All `conditions` must hold (logical AND); express OR
26
+ * with a second rule. Rules are evaluated top to bottom and the first match wins.
27
+ */
28
+ interface TargetingRule {
29
+ description?: string;
30
+ conditions: Condition[];
31
+ result: RuleResult;
32
+ }
33
+ interface FlagMetadata {
34
+ createdBy: string;
35
+ createdAt: string;
36
+ updatedBy: string;
37
+ updatedAt: string;
38
+ }
39
+ /**
40
+ * A feature flag as stored. `rules` is optional and additive: a flag with no rules
41
+ * evaluates purely on `enabled` + `rollout`, identical to a plain boolean-with-percentage
42
+ * flag. The top-level `rollout` acts as the default rule when no targeting rule matches.
43
+ */
44
+ interface FeatureFlag {
45
+ key: string;
46
+ enabled: boolean;
47
+ rollout: {
48
+ percentage: number;
49
+ };
50
+ rules?: TargetingRule[];
51
+ description: string;
52
+ metadata: FlagMetadata;
53
+ }
54
+ /**
55
+ * The OpenFeature-style evaluation context: an optional stable `targetingKey` used for
56
+ * sticky percentage bucketing, plus arbitrary attributes referenced by targeting rules.
57
+ */
58
+ interface EvaluationContext {
59
+ targetingKey?: string;
60
+ [attribute: string]: AttributeValue | undefined;
61
+ }
62
+ /** Why a flag resolved the way it did. Maps onto OpenFeature/OFREP resolution reasons. */
63
+ type EvaluationReason = 'DISABLED' | 'TARGETING_MATCH' | 'SPLIT' | 'DEFAULT';
64
+ interface EvaluationResult {
65
+ value: boolean;
66
+ reason: EvaluationReason;
67
+ /** Index of the targeting rule that matched, when `reason` is TARGETING_MATCH or SPLIT via a rule. */
68
+ ruleIndex?: number;
69
+ }
70
+ /**
71
+ * Storage contract — the "bring your own DB" seam. Any key/value store fits: a key maps
72
+ * to one flag's JSON. Implement these four methods and the server never knows the difference.
73
+ */
74
+ interface StorageAdapter {
75
+ get(key: string): Promise<FeatureFlag | null>;
76
+ put(key: string, flag: FeatureFlag): Promise<void>;
77
+ delete(key: string): Promise<void>;
78
+ list(): Promise<FeatureFlag[]>;
79
+ }
80
+ /** The authenticated caller, extracted from a validated admin token. */
81
+ interface AuthContext {
82
+ identity: string;
83
+ groups: string[];
84
+ }
85
+ /**
86
+ * Auth contract for the admin/write path. Returns the caller's identity on success, or
87
+ * null when the token is missing/invalid. Group checks are layered on top by the server.
88
+ */
89
+ interface AuthVerifier {
90
+ verify(token: string | null): Promise<AuthContext | null>;
91
+ }
92
+
93
+ /** Clamp a percentage into [0, 100]; NaN becomes 0 (conservative — feature stays hidden). */
94
+ declare function clampPercentage(percentage: number): number;
95
+ /**
96
+ * Deterministically map a seed string into a bucket in [0, 100). Uses SHA-256 so the
97
+ * distribution is uniform and the result is stable across runtimes and languages — the
98
+ * same seed always lands in the same bucket. Cryptographic strength is incidental here;
99
+ * what matters is determinism and even spread.
100
+ */
101
+ declare function stickyBucket(seed: string): Promise<number>;
102
+ /**
103
+ * Decide whether a given target is inside a percentage rollout for a flag. Sticky: the
104
+ * same (targetingKey, flagKey) pair always resolves the same way, so a partner does not
105
+ * flip in and out of a feature between page loads. No assignment state is stored.
106
+ */
107
+ declare function isInRollout(targetingKey: string, flagKey: string, percentage: number): Promise<boolean>;
108
+
109
+ /**
110
+ * Resource limits enforced when parsing untrusted flag input. These bound how much work a
111
+ * single flag can impose on evaluation, so a compromised or fat-fingered admin write cannot
112
+ * wedge the read path. Generous enough that legitimate flags never hit them.
113
+ */
114
+ declare const LIMITS: {
115
+ readonly maxKeyLength: 256;
116
+ readonly maxRules: 100;
117
+ readonly maxConditionsPerRule: 50;
118
+ readonly maxListItems: 1000;
119
+ readonly maxValueLength: 1024;
120
+ };
121
+ /**
122
+ * Attribute names that resolve onto the prototype chain rather than to real data. They are
123
+ * never valid targeting attributes and must never be read from an evaluation context.
124
+ */
125
+ declare const FORBIDDEN_ATTRIBUTES: ReadonlySet<string>;
126
+ /**
127
+ * A flag key is URL- and storage-safe: it appears verbatim in request paths
128
+ * (`/flags/:key`, `/ofrep/v1/evaluate/flags/{key}`) and as a raw key in whatever storage
129
+ * backend is plugged in. Restrict to alphanumerics plus dot, underscore, and hyphen,
130
+ * starting with an alphanumeric, within a bounded length. This excludes path separators
131
+ * and control characters, closing off traversal and key-injection classes for any adapter.
132
+ */
133
+ declare function isValidFlagKey(key: string): boolean;
134
+ /** Human-readable description of the flag key rule, for error messages. */
135
+ declare const FLAG_KEY_RULE = "must be 1-256 characters of [A-Za-z0-9._-] and start with an alphanumeric";
136
+
137
+ /**
138
+ * Compare two semver strings. Returns -1, 0, or 1. A version with no prerelease outranks
139
+ * one with a prerelease (1.0.0 > 1.0.0-rc.1); prereleases are otherwise compared lexically.
140
+ */
141
+ declare function compareSemver(a: string, b: string): number;
142
+ /**
143
+ * Evaluate a single condition against the context. A referenced attribute that is absent
144
+ * from the context never matches — you cannot target on data you were not given. Prototype
145
+ * attribute names are rejected, and only own properties are read, so a crafted attribute
146
+ * name can never reach up the prototype chain.
147
+ */
148
+ declare function matchCondition(condition: Condition, context: EvaluationContext): boolean;
149
+ /** True when every condition matches (logical AND). An empty list matches everyone. */
150
+ declare function matchesAllConditions(conditions: Condition[], context: EvaluationContext): boolean;
151
+
152
+ /**
153
+ * Evaluate one flag against a context. The cascade:
154
+ *
155
+ * 1. If the flag is disabled, serve off.
156
+ * 2. Walk targeting rules in order; the first whose conditions all match decides the result
157
+ * (optionally gated by a per-rule rollout).
158
+ * 3. If no rule matches, fall through to the flag's default rollout percentage.
159
+ */
160
+ declare function evaluate(flag: FeatureFlag, context?: EvaluationContext): Promise<EvaluationResult>;
161
+ /** Evaluate many flags against one context, returning a map keyed by flag key. */
162
+ declare function evaluateAll(flags: FeatureFlag[], context?: EvaluationContext): Promise<Record<string, EvaluationResult>>;
163
+
164
+ /**
165
+ * Parse arbitrary (untrusted) input — e.g. JSON read back from a storage adapter — into a
166
+ * FeatureFlag, or return null if it is not a valid flag. A rule with any malformed condition
167
+ * is rejected wholesale rather than silently weakened. Percentages are clamped to [0, 100].
168
+ */
169
+ declare function parseFlag(input: unknown): FeatureFlag | null;
170
+ interface CreateFlagInput {
171
+ key: string;
172
+ enabled?: boolean;
173
+ rollout?: {
174
+ percentage: number;
175
+ };
176
+ rules?: TargetingRule[];
177
+ description?: string;
178
+ /** Identity recorded in createdBy/updatedBy metadata. */
179
+ identity?: string;
180
+ }
181
+ /**
182
+ * Construct a well-formed FeatureFlag with sensible defaults and fresh metadata.
183
+ * Throws if the key is invalid — this is a programmer-facing constructor, so bad input
184
+ * fails fast rather than producing an unusable flag.
185
+ */
186
+ declare function createFlag(input: CreateFlagInput): FeatureFlag;
187
+
188
+ declare const version = "0.0.0";
189
+
190
+ export { type AttributeValue, type AuthContext, type AuthVerifier, type Condition, type ConditionValue, type CreateFlagInput, type EvaluationContext, type EvaluationReason, type EvaluationResult, FLAG_KEY_RULE, FORBIDDEN_ATTRIBUTES, type FeatureFlag, type FlagMetadata, LIMITS, type Operator, type RuleResult, type StorageAdapter, type TargetingRule, clampPercentage, compareSemver, createFlag, evaluate, evaluateAll, isInRollout, isValidFlagKey, matchCondition, matchesAllConditions, parseFlag, stickyBucket, version };
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Comparison operators available to targeting conditions. The set is intentionally
3
+ * bounded for v1; regex (`matches`) is deliberately excluded as a ReDoS footgun.
4
+ */
5
+ type Operator = 'eq' | 'neq' | 'in' | 'notIn' | 'contains' | 'startsWith' | 'endsWith' | 'gt' | 'gte' | 'lt' | 'lte' | 'semverGte' | 'semverLt';
6
+ /** A scalar attribute drawn from the evaluation context. */
7
+ type AttributeValue = string | number | boolean;
8
+ /** A value a condition compares against — scalar, or a list for `in` / `notIn`. */
9
+ type ConditionValue = string | number | boolean | Array<string | number>;
10
+ /** A single `attribute operator value` predicate. */
11
+ interface Condition {
12
+ attribute: string;
13
+ operator: Operator;
14
+ value: ConditionValue;
15
+ }
16
+ /** What a matched targeting rule serves. */
17
+ interface RuleResult {
18
+ enabled: boolean;
19
+ /** Optional rollout within the matched cohort. Absent means 100% (fully on). */
20
+ rollout?: {
21
+ percentage: number;
22
+ };
23
+ }
24
+ /**
25
+ * An ordered targeting rule. All `conditions` must hold (logical AND); express OR
26
+ * with a second rule. Rules are evaluated top to bottom and the first match wins.
27
+ */
28
+ interface TargetingRule {
29
+ description?: string;
30
+ conditions: Condition[];
31
+ result: RuleResult;
32
+ }
33
+ interface FlagMetadata {
34
+ createdBy: string;
35
+ createdAt: string;
36
+ updatedBy: string;
37
+ updatedAt: string;
38
+ }
39
+ /**
40
+ * A feature flag as stored. `rules` is optional and additive: a flag with no rules
41
+ * evaluates purely on `enabled` + `rollout`, identical to a plain boolean-with-percentage
42
+ * flag. The top-level `rollout` acts as the default rule when no targeting rule matches.
43
+ */
44
+ interface FeatureFlag {
45
+ key: string;
46
+ enabled: boolean;
47
+ rollout: {
48
+ percentage: number;
49
+ };
50
+ rules?: TargetingRule[];
51
+ description: string;
52
+ metadata: FlagMetadata;
53
+ }
54
+ /**
55
+ * The OpenFeature-style evaluation context: an optional stable `targetingKey` used for
56
+ * sticky percentage bucketing, plus arbitrary attributes referenced by targeting rules.
57
+ */
58
+ interface EvaluationContext {
59
+ targetingKey?: string;
60
+ [attribute: string]: AttributeValue | undefined;
61
+ }
62
+ /** Why a flag resolved the way it did. Maps onto OpenFeature/OFREP resolution reasons. */
63
+ type EvaluationReason = 'DISABLED' | 'TARGETING_MATCH' | 'SPLIT' | 'DEFAULT';
64
+ interface EvaluationResult {
65
+ value: boolean;
66
+ reason: EvaluationReason;
67
+ /** Index of the targeting rule that matched, when `reason` is TARGETING_MATCH or SPLIT via a rule. */
68
+ ruleIndex?: number;
69
+ }
70
+ /**
71
+ * Storage contract — the "bring your own DB" seam. Any key/value store fits: a key maps
72
+ * to one flag's JSON. Implement these four methods and the server never knows the difference.
73
+ */
74
+ interface StorageAdapter {
75
+ get(key: string): Promise<FeatureFlag | null>;
76
+ put(key: string, flag: FeatureFlag): Promise<void>;
77
+ delete(key: string): Promise<void>;
78
+ list(): Promise<FeatureFlag[]>;
79
+ }
80
+ /** The authenticated caller, extracted from a validated admin token. */
81
+ interface AuthContext {
82
+ identity: string;
83
+ groups: string[];
84
+ }
85
+ /**
86
+ * Auth contract for the admin/write path. Returns the caller's identity on success, or
87
+ * null when the token is missing/invalid. Group checks are layered on top by the server.
88
+ */
89
+ interface AuthVerifier {
90
+ verify(token: string | null): Promise<AuthContext | null>;
91
+ }
92
+
93
+ /** Clamp a percentage into [0, 100]; NaN becomes 0 (conservative — feature stays hidden). */
94
+ declare function clampPercentage(percentage: number): number;
95
+ /**
96
+ * Deterministically map a seed string into a bucket in [0, 100). Uses SHA-256 so the
97
+ * distribution is uniform and the result is stable across runtimes and languages — the
98
+ * same seed always lands in the same bucket. Cryptographic strength is incidental here;
99
+ * what matters is determinism and even spread.
100
+ */
101
+ declare function stickyBucket(seed: string): Promise<number>;
102
+ /**
103
+ * Decide whether a given target is inside a percentage rollout for a flag. Sticky: the
104
+ * same (targetingKey, flagKey) pair always resolves the same way, so a partner does not
105
+ * flip in and out of a feature between page loads. No assignment state is stored.
106
+ */
107
+ declare function isInRollout(targetingKey: string, flagKey: string, percentage: number): Promise<boolean>;
108
+
109
+ /**
110
+ * Resource limits enforced when parsing untrusted flag input. These bound how much work a
111
+ * single flag can impose on evaluation, so a compromised or fat-fingered admin write cannot
112
+ * wedge the read path. Generous enough that legitimate flags never hit them.
113
+ */
114
+ declare const LIMITS: {
115
+ readonly maxKeyLength: 256;
116
+ readonly maxRules: 100;
117
+ readonly maxConditionsPerRule: 50;
118
+ readonly maxListItems: 1000;
119
+ readonly maxValueLength: 1024;
120
+ };
121
+ /**
122
+ * Attribute names that resolve onto the prototype chain rather than to real data. They are
123
+ * never valid targeting attributes and must never be read from an evaluation context.
124
+ */
125
+ declare const FORBIDDEN_ATTRIBUTES: ReadonlySet<string>;
126
+ /**
127
+ * A flag key is URL- and storage-safe: it appears verbatim in request paths
128
+ * (`/flags/:key`, `/ofrep/v1/evaluate/flags/{key}`) and as a raw key in whatever storage
129
+ * backend is plugged in. Restrict to alphanumerics plus dot, underscore, and hyphen,
130
+ * starting with an alphanumeric, within a bounded length. This excludes path separators
131
+ * and control characters, closing off traversal and key-injection classes for any adapter.
132
+ */
133
+ declare function isValidFlagKey(key: string): boolean;
134
+ /** Human-readable description of the flag key rule, for error messages. */
135
+ declare const FLAG_KEY_RULE = "must be 1-256 characters of [A-Za-z0-9._-] and start with an alphanumeric";
136
+
137
+ /**
138
+ * Compare two semver strings. Returns -1, 0, or 1. A version with no prerelease outranks
139
+ * one with a prerelease (1.0.0 > 1.0.0-rc.1); prereleases are otherwise compared lexically.
140
+ */
141
+ declare function compareSemver(a: string, b: string): number;
142
+ /**
143
+ * Evaluate a single condition against the context. A referenced attribute that is absent
144
+ * from the context never matches — you cannot target on data you were not given. Prototype
145
+ * attribute names are rejected, and only own properties are read, so a crafted attribute
146
+ * name can never reach up the prototype chain.
147
+ */
148
+ declare function matchCondition(condition: Condition, context: EvaluationContext): boolean;
149
+ /** True when every condition matches (logical AND). An empty list matches everyone. */
150
+ declare function matchesAllConditions(conditions: Condition[], context: EvaluationContext): boolean;
151
+
152
+ /**
153
+ * Evaluate one flag against a context. The cascade:
154
+ *
155
+ * 1. If the flag is disabled, serve off.
156
+ * 2. Walk targeting rules in order; the first whose conditions all match decides the result
157
+ * (optionally gated by a per-rule rollout).
158
+ * 3. If no rule matches, fall through to the flag's default rollout percentage.
159
+ */
160
+ declare function evaluate(flag: FeatureFlag, context?: EvaluationContext): Promise<EvaluationResult>;
161
+ /** Evaluate many flags against one context, returning a map keyed by flag key. */
162
+ declare function evaluateAll(flags: FeatureFlag[], context?: EvaluationContext): Promise<Record<string, EvaluationResult>>;
163
+
164
+ /**
165
+ * Parse arbitrary (untrusted) input — e.g. JSON read back from a storage adapter — into a
166
+ * FeatureFlag, or return null if it is not a valid flag. A rule with any malformed condition
167
+ * is rejected wholesale rather than silently weakened. Percentages are clamped to [0, 100].
168
+ */
169
+ declare function parseFlag(input: unknown): FeatureFlag | null;
170
+ interface CreateFlagInput {
171
+ key: string;
172
+ enabled?: boolean;
173
+ rollout?: {
174
+ percentage: number;
175
+ };
176
+ rules?: TargetingRule[];
177
+ description?: string;
178
+ /** Identity recorded in createdBy/updatedBy metadata. */
179
+ identity?: string;
180
+ }
181
+ /**
182
+ * Construct a well-formed FeatureFlag with sensible defaults and fresh metadata.
183
+ * Throws if the key is invalid — this is a programmer-facing constructor, so bad input
184
+ * fails fast rather than producing an unusable flag.
185
+ */
186
+ declare function createFlag(input: CreateFlagInput): FeatureFlag;
187
+
188
+ declare const version = "0.0.0";
189
+
190
+ export { type AttributeValue, type AuthContext, type AuthVerifier, type Condition, type ConditionValue, type CreateFlagInput, type EvaluationContext, type EvaluationReason, type EvaluationResult, FLAG_KEY_RULE, FORBIDDEN_ATTRIBUTES, type FeatureFlag, type FlagMetadata, LIMITS, type Operator, type RuleResult, type StorageAdapter, type TargetingRule, clampPercentage, compareSemver, createFlag, evaluate, evaluateAll, isInRollout, isValidFlagKey, matchCondition, matchesAllConditions, parseFlag, stickyBucket, version };
package/dist/index.js ADDED
@@ -0,0 +1,259 @@
1
+ // src/hash.ts
2
+ function clampPercentage(percentage) {
3
+ if (Number.isNaN(percentage)) return 0;
4
+ return Math.max(0, Math.min(100, percentage));
5
+ }
6
+ async function stickyBucket(seed) {
7
+ const data = new TextEncoder().encode(seed);
8
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", data);
9
+ return new DataView(digest).getUint32(0) % 100;
10
+ }
11
+ async function isInRollout(targetingKey, flagKey, percentage) {
12
+ const pct = clampPercentage(percentage);
13
+ if (pct >= 100) return true;
14
+ if (pct <= 0) return false;
15
+ const bucket = await stickyBucket(`${targetingKey}:${flagKey}`);
16
+ return bucket < pct;
17
+ }
18
+
19
+ // src/limits.ts
20
+ var LIMITS = {
21
+ maxKeyLength: 256,
22
+ maxRules: 100,
23
+ maxConditionsPerRule: 50,
24
+ maxListItems: 1e3,
25
+ maxValueLength: 1024
26
+ };
27
+ var FLAG_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
28
+ var FORBIDDEN_ATTRIBUTES = /* @__PURE__ */ new Set([
29
+ "__proto__",
30
+ "constructor",
31
+ "prototype"
32
+ ]);
33
+ function isValidFlagKey(key) {
34
+ return key.length >= 1 && key.length <= LIMITS.maxKeyLength && FLAG_KEY_PATTERN.test(key);
35
+ }
36
+ var FLAG_KEY_RULE = "must be 1-256 characters of [A-Za-z0-9._-] and start with an alphanumeric";
37
+
38
+ // src/operators.ts
39
+ function isScalar(v) {
40
+ return typeof v === "string" || typeof v === "number" || typeof v === "boolean";
41
+ }
42
+ function compareNumbers(a, v, test) {
43
+ const x = Number(a);
44
+ const y = Number(v);
45
+ if (Number.isNaN(x) || Number.isNaN(y)) return false;
46
+ return test(x, y);
47
+ }
48
+ function toInt(part) {
49
+ const n = parseInt(part ?? "", 10);
50
+ return Number.isNaN(n) ? 0 : n;
51
+ }
52
+ function parseSemver(v) {
53
+ const clean = v.trim().replace(/^v/, "");
54
+ const dash = clean.indexOf("-");
55
+ const core = dash === -1 ? clean : clean.slice(0, dash);
56
+ const pre = dash === -1 ? "" : clean.slice(dash + 1);
57
+ const [major, minor, patch] = core.split(".");
58
+ return { major: toInt(major), minor: toInt(minor), patch: toInt(patch), pre };
59
+ }
60
+ function compareSemver(a, b) {
61
+ const x = parseSemver(a);
62
+ const y = parseSemver(b);
63
+ if (x.major !== y.major) return x.major < y.major ? -1 : 1;
64
+ if (x.minor !== y.minor) return x.minor < y.minor ? -1 : 1;
65
+ if (x.patch !== y.patch) return x.patch < y.patch ? -1 : 1;
66
+ if (x.pre === y.pre) return 0;
67
+ if (x.pre === "") return 1;
68
+ if (y.pre === "") return -1;
69
+ return x.pre < y.pre ? -1 : 1;
70
+ }
71
+ function compareSemvers(a, v, test) {
72
+ if (typeof a !== "string" || typeof v !== "string") return false;
73
+ return test(compareSemver(a, v));
74
+ }
75
+ var operators = {
76
+ eq: (a, v) => isScalar(v) && a === v,
77
+ neq: (a, v) => isScalar(v) && a !== v,
78
+ in: (a, v) => Array.isArray(v) && v.some((item) => item === a),
79
+ notIn: (a, v) => Array.isArray(v) && !v.some((item) => item === a),
80
+ contains: (a, v) => typeof a === "string" && typeof v === "string" && a.includes(v),
81
+ startsWith: (a, v) => typeof a === "string" && typeof v === "string" && a.startsWith(v),
82
+ endsWith: (a, v) => typeof a === "string" && typeof v === "string" && a.endsWith(v),
83
+ gt: (a, v) => compareNumbers(a, v, (x, y) => x > y),
84
+ gte: (a, v) => compareNumbers(a, v, (x, y) => x >= y),
85
+ lt: (a, v) => compareNumbers(a, v, (x, y) => x < y),
86
+ lte: (a, v) => compareNumbers(a, v, (x, y) => x <= y),
87
+ semverGte: (a, v) => compareSemvers(a, v, (cmp) => cmp >= 0),
88
+ semverLt: (a, v) => compareSemvers(a, v, (cmp) => cmp < 0)
89
+ };
90
+ function matchCondition(condition, context) {
91
+ if (FORBIDDEN_ATTRIBUTES.has(condition.attribute)) return false;
92
+ if (!Object.hasOwn(context, condition.attribute)) return false;
93
+ const attr = context[condition.attribute];
94
+ if (attr === void 0) return false;
95
+ const op = operators[condition.operator];
96
+ if (!op) return false;
97
+ return op(attr, condition.value);
98
+ }
99
+ function matchesAllConditions(conditions, context) {
100
+ return conditions.every((condition) => matchCondition(condition, context));
101
+ }
102
+
103
+ // src/evaluate.ts
104
+ function isSplit(percentage) {
105
+ return percentage > 0 && percentage < 100;
106
+ }
107
+ async function resolveRule(result, targetingKey, flagKey, ruleIndex) {
108
+ if (!result.enabled) return { value: false, reason: "TARGETING_MATCH", ruleIndex };
109
+ const percentage = result.rollout?.percentage ?? 100;
110
+ const value = await isInRollout(targetingKey, flagKey, percentage);
111
+ return { value, reason: isSplit(percentage) ? "SPLIT" : "TARGETING_MATCH", ruleIndex };
112
+ }
113
+ async function evaluate(flag, context = {}) {
114
+ if (!flag.enabled) return { value: false, reason: "DISABLED" };
115
+ const targetingKey = context.targetingKey ?? "";
116
+ let ruleIndex = 0;
117
+ for (const rule of flag.rules ?? []) {
118
+ if (matchesAllConditions(rule.conditions, context)) {
119
+ return resolveRule(rule.result, targetingKey, flag.key, ruleIndex);
120
+ }
121
+ ruleIndex++;
122
+ }
123
+ const percentage = flag.rollout.percentage;
124
+ const value = await isInRollout(targetingKey, flag.key, percentage);
125
+ return { value, reason: isSplit(percentage) ? "SPLIT" : "DEFAULT" };
126
+ }
127
+ async function evaluateAll(flags, context = {}) {
128
+ const entries = await Promise.all(
129
+ flags.map(async (flag) => [flag.key, await evaluate(flag, context)])
130
+ );
131
+ return Object.fromEntries(entries);
132
+ }
133
+
134
+ // src/validate.ts
135
+ var OPERATORS = [
136
+ "eq",
137
+ "neq",
138
+ "in",
139
+ "notIn",
140
+ "contains",
141
+ "startsWith",
142
+ "endsWith",
143
+ "gt",
144
+ "gte",
145
+ "lt",
146
+ "lte",
147
+ "semverGte",
148
+ "semverLt"
149
+ ];
150
+ function asRecord(input) {
151
+ return typeof input === "object" && input !== null ? input : null;
152
+ }
153
+ function isConditionValue(v) {
154
+ if (typeof v === "string") return v.length <= LIMITS.maxValueLength;
155
+ if (typeof v === "number" || typeof v === "boolean") return true;
156
+ if (Array.isArray(v)) {
157
+ if (v.length > LIMITS.maxListItems) return false;
158
+ return v.every(
159
+ (x) => typeof x === "string" ? x.length <= LIMITS.maxValueLength : typeof x === "number"
160
+ );
161
+ }
162
+ return false;
163
+ }
164
+ function parseCondition(input) {
165
+ const o = asRecord(input);
166
+ if (!o) return null;
167
+ if (typeof o.attribute !== "string") return null;
168
+ if (o.attribute.length === 0 || o.attribute.length > LIMITS.maxKeyLength) return null;
169
+ if (FORBIDDEN_ATTRIBUTES.has(o.attribute)) return null;
170
+ if (typeof o.operator !== "string" || !OPERATORS.includes(o.operator)) return null;
171
+ if (!isConditionValue(o.value)) return null;
172
+ return { attribute: o.attribute, operator: o.operator, value: o.value };
173
+ }
174
+ function parseRuleResult(input) {
175
+ const o = asRecord(input);
176
+ if (!o || typeof o.enabled !== "boolean") return null;
177
+ const result = { enabled: o.enabled };
178
+ const rollout = asRecord(o.rollout);
179
+ if (rollout && typeof rollout.percentage === "number") {
180
+ result.rollout = { percentage: clampPercentage(rollout.percentage) };
181
+ }
182
+ return result;
183
+ }
184
+ function parseRule(input) {
185
+ const o = asRecord(input);
186
+ if (!o || !Array.isArray(o.conditions)) return null;
187
+ if (o.conditions.length > LIMITS.maxConditionsPerRule) return null;
188
+ const conditions = o.conditions.map(parseCondition);
189
+ if (conditions.some((c) => c === null)) return null;
190
+ const result = parseRuleResult(o.result);
191
+ if (!result) return null;
192
+ const rule = { conditions, result };
193
+ if (typeof o.description === "string") rule.description = o.description;
194
+ return rule;
195
+ }
196
+ function parseMetadata(input) {
197
+ const now = (/* @__PURE__ */ new Date()).toISOString();
198
+ const o = asRecord(input) ?? {};
199
+ return {
200
+ createdBy: typeof o.createdBy === "string" ? o.createdBy : "unknown",
201
+ createdAt: typeof o.createdAt === "string" ? o.createdAt : now,
202
+ updatedBy: typeof o.updatedBy === "string" ? o.updatedBy : "unknown",
203
+ updatedAt: typeof o.updatedAt === "string" ? o.updatedAt : now
204
+ };
205
+ }
206
+ function parseFlag(input) {
207
+ const o = asRecord(input);
208
+ if (!o) return null;
209
+ if (typeof o.key !== "string" || !isValidFlagKey(o.key)) return null;
210
+ if (typeof o.enabled !== "boolean") return null;
211
+ const rollout = asRecord(o.rollout);
212
+ const percentage = rollout && typeof rollout.percentage === "number" ? clampPercentage(rollout.percentage) : 0;
213
+ const rawRules = Array.isArray(o.rules) ? o.rules : [];
214
+ if (rawRules.length > LIMITS.maxRules) return null;
215
+ const rules = rawRules.map(parseRule).filter((r) => r !== null);
216
+ return {
217
+ key: o.key,
218
+ enabled: o.enabled,
219
+ rollout: { percentage },
220
+ rules,
221
+ description: typeof o.description === "string" ? o.description : "",
222
+ metadata: parseMetadata(o.metadata)
223
+ };
224
+ }
225
+ function createFlag(input) {
226
+ if (!isValidFlagKey(input.key)) {
227
+ throw new Error(`Invalid flag key ${JSON.stringify(input.key)}: ${FLAG_KEY_RULE}.`);
228
+ }
229
+ const now = (/* @__PURE__ */ new Date()).toISOString();
230
+ const identity = input.identity ?? "system";
231
+ return {
232
+ key: input.key,
233
+ enabled: input.enabled ?? false,
234
+ rollout: { percentage: clampPercentage(input.rollout?.percentage ?? 0) },
235
+ rules: input.rules ?? [],
236
+ description: input.description ?? "",
237
+ metadata: { createdBy: identity, createdAt: now, updatedBy: identity, updatedAt: now }
238
+ };
239
+ }
240
+
241
+ // src/index.ts
242
+ var version = "0.0.0";
243
+ export {
244
+ FLAG_KEY_RULE,
245
+ FORBIDDEN_ATTRIBUTES,
246
+ LIMITS,
247
+ clampPercentage,
248
+ compareSemver,
249
+ createFlag,
250
+ evaluate,
251
+ evaluateAll,
252
+ isInRollout,
253
+ isValidFlagKey,
254
+ matchCondition,
255
+ matchesAllConditions,
256
+ parseFlag,
257
+ stickyBucket,
258
+ version
259
+ };
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@flaghoist/core",
3
+ "version": "0.1.0",
4
+ "description": "Flag schema, evaluation engine, and storage/auth interfaces for Flaghoist. Zero dependencies.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "import": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "require": {
17
+ "types": "./dist/index.d.cts",
18
+ "default": "./dist/index.cjs"
19
+ }
20
+ }
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "sideEffects": false,
26
+ "engines": {
27
+ "node": ">=20"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "scripts": {
33
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
34
+ "test": "vitest run --passWithNoTests",
35
+ "typecheck": "tsc --noEmit",
36
+ "check:package": "publint --strict && attw --pack ."
37
+ }
38
+ }