@ocap/rule-dsl 0.0.0-stage → 1.30.26

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/lib/expr.d.cts ADDED
@@ -0,0 +1,29 @@
1
+ import { BoolExpr, ValueExpr } from "./types.cjs";
2
+
3
+ //#region src/expr.d.ts
4
+
5
+ interface ExprParseResult<T> {
6
+ ok: boolean;
7
+ value?: T;
8
+ /** Present when ok === false: a short reason, e.g. 'function-call', 'malformed'. */
9
+ reason?: string;
10
+ }
11
+ declare function parseValueExpr(src: string): ExprParseResult<ValueExpr>;
12
+ declare function parseBoolExpr(src: string): ExprParseResult<BoolExpr>;
13
+ /**
14
+ * Literal-vs-literal type compatibility check for a bool expr (Primitive 2 /
15
+ * error code TYPE_MISMATCH). Refs (`tx.*`/state key) have no statically known
16
+ * type in this PoC (no external state schema is part of the DSL grammar), so
17
+ * we only flag mismatches we can prove from literal values themselves:
18
+ * - equality ops (==, !=) between literals of different kinds
19
+ * - ordering ops (<, <=, >, >=) applied to a boolean or string literal
20
+ */
21
+ declare function boolExprTypeMismatch(expr: BoolExpr): boolean;
22
+ /**
23
+ * `counter.value` (and `rate.limit.sum`) must be `number | tx.field | state.field`
24
+ * (planning/35 Primitive 1: "value 只能是纯表达式(number | tx.field | state.field)").
25
+ * A string or boolean literal here is a TYPE_MISMATCH.
26
+ */
27
+ declare function isValidCounterValueType(v: ValueExpr): boolean;
28
+ //#endregion
29
+ export { ExprParseResult, boolExprTypeMismatch, isValidCounterValueType, parseBoolExpr, parseValueExpr };
package/lib/index.cjs ADDED
@@ -0,0 +1,30 @@
1
+ const require_errors = require('./errors.cjs');
2
+ const require_compiler = require('./compiler.cjs');
3
+ const require_expr = require('./expr.cjs');
4
+ const require_primitives = require('./primitives.cjs');
5
+ const require_parser = require('./parser.cjs');
6
+ const require_validator = require('./validator.cjs');
7
+ const require_pipeline = require('./pipeline.cjs');
8
+
9
+ exports.BANNED_KEYS = require_primitives.BANNED_KEYS;
10
+ exports.CONSTRAINT_PRIMITIVES = require_primitives.CONSTRAINT_PRIMITIVES;
11
+ exports.COUNTER_OPS = require_primitives.COUNTER_OPS;
12
+ exports.DECISIONS = require_primitives.DECISIONS;
13
+ exports.EFFECT_PRIMITIVES = require_primitives.EFFECT_PRIMITIVES;
14
+ exports.ELIGIBILITY_MODES = require_primitives.ELIGIBILITY_MODES;
15
+ exports.MATCH_PRIMITIVES = require_primitives.MATCH_PRIMITIVES;
16
+ exports.ON_FAIL_MODES = require_primitives.ON_FAIL_MODES;
17
+ exports.ORDERING_MODES = require_primitives.ORDERING_MODES;
18
+ exports.RULE_DSL_ERROR_CODES = require_errors.RULE_DSL_ERROR_CODES;
19
+ exports.RULE_TOP_LEVEL_KEYS = require_primitives.RULE_TOP_LEVEL_KEYS;
20
+ exports.STRATEGY_TYPES = require_primitives.STRATEGY_TYPES;
21
+ exports.TIME_TYPES = require_primitives.TIME_TYPES;
22
+ exports.boolExprTypeMismatch = require_expr.boolExprTypeMismatch;
23
+ exports.compileRule = require_compiler.compileRule;
24
+ exports.isValidCounterValueType = require_expr.isValidCounterValueType;
25
+ exports.makeError = require_errors.makeError;
26
+ exports.parseBoolExpr = require_expr.parseBoolExpr;
27
+ exports.parseRuleDsl = require_parser.parseRuleDsl;
28
+ exports.parseValueExpr = require_expr.parseValueExpr;
29
+ exports.processRuleDsl = require_pipeline.processRuleDsl;
30
+ exports.validateRule = require_validator.validateRule;
@@ -0,0 +1,9 @@
1
+ import { RULE_DSL_ERROR_CODES, RuleDslError, RuleDslErrorCode, makeError } from "./errors.cjs";
2
+ import { AllocateEffect, AllocateStrategy, AppliesTo, BoolExpr, Branch, ComparisonOp, CompiledRuleDag, ConstraintNode, CounterEffect, DagEdge, DagNode, DagNodeKind, EffectNode, EligibilityMatch, ExprLiteral, ExprRef, MatchNode, Metadata, Ordering, RateLimit, RateMatch, RuleAst, ThresholdConstraint, TimeMatch, ValueExpr } from "./types.cjs";
3
+ import { CompileResult, compileRule } from "./compiler.cjs";
4
+ import { boolExprTypeMismatch, isValidCounterValueType, parseBoolExpr, parseValueExpr } from "./expr.cjs";
5
+ import { BANNED_KEYS, CONSTRAINT_PRIMITIVES, COUNTER_OPS, DECISIONS, EFFECT_PRIMITIVES, ELIGIBILITY_MODES, MATCH_PRIMITIVES, ON_FAIL_MODES, ORDERING_MODES, RULE_TOP_LEVEL_KEYS, STRATEGY_TYPES, TIME_TYPES } from "./primitives.cjs";
6
+ import { ParseResult, parseRuleDsl } from "./parser.cjs";
7
+ import { ValidateOptions, validateRule } from "./validator.cjs";
8
+ import { ProcessResult, processRuleDsl } from "./pipeline.cjs";
9
+ export { AllocateEffect, AllocateStrategy, AppliesTo, BANNED_KEYS, BoolExpr, Branch, CONSTRAINT_PRIMITIVES, COUNTER_OPS, ComparisonOp, type CompileResult, CompiledRuleDag, ConstraintNode, CounterEffect, DECISIONS, DagEdge, DagNode, DagNodeKind, EFFECT_PRIMITIVES, ELIGIBILITY_MODES, EffectNode, EligibilityMatch, ExprLiteral, ExprRef, MATCH_PRIMITIVES, MatchNode, Metadata, ON_FAIL_MODES, ORDERING_MODES, Ordering, type ParseResult, type ProcessResult, RULE_DSL_ERROR_CODES, RULE_TOP_LEVEL_KEYS, RateLimit, RateMatch, RuleAst, RuleDslError, RuleDslErrorCode, STRATEGY_TYPES, TIME_TYPES, ThresholdConstraint, TimeMatch, type ValidateOptions, ValueExpr, boolExprTypeMismatch, compileRule, isValidCounterValueType, makeError, parseBoolExpr, parseRuleDsl, parseValueExpr, processRuleDsl, validateRule };
package/lib/parser.cjs ADDED
@@ -0,0 +1,400 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ const require_errors = require('./errors.cjs');
3
+ const require_expr = require('./expr.cjs');
4
+ const require_primitives = require('./primitives.cjs');
5
+ let js_yaml = require("js-yaml");
6
+ js_yaml = require_rolldown_runtime.__toESM(js_yaml);
7
+
8
+ //#region src/parser.ts
9
+ /**
10
+ * Rule DSL v1 parser: YAML text -> RuleAst (planning/35 §6.6, L811-1129).
11
+ *
12
+ * This does structural/shape parsing plus the expression-level checks that
13
+ * only make sense while walking the tree (UNKNOWN_PRIMITIVE, INVALID_EXPR,
14
+ * TYPE_MISMATCH, MISSING_REQUIRED_FIELD). Cross-cutting semantic checks that
15
+ * need the *whole* AST (state-key existence, DAG cycles) live in
16
+ * validator.ts / compiler.ts instead.
17
+ */
18
+ function isPlainObject(v) {
19
+ return typeof v === "object" && v !== null && !Array.isArray(v);
20
+ }
21
+ function isString(v) {
22
+ return typeof v === "string" && v.length > 0;
23
+ }
24
+ function isNumber(v) {
25
+ return typeof v === "number" && Number.isFinite(v);
26
+ }
27
+ /** Recursively scans the raw YAML doc for banned keys (`for` / `while`) at any depth. */
28
+ function scanBannedKeys(node, path, errors) {
29
+ if (Array.isArray(node)) {
30
+ node.forEach((item, idx) => scanBannedKeys(item, `${path}[${idx}]`, errors));
31
+ return;
32
+ }
33
+ if (isPlainObject(node)) for (const key of Object.keys(node)) {
34
+ if (require_primitives.BANNED_KEYS.includes(key)) errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", path ? `${path}.${key}` : key, `Banned keyword "${key}" is not a Rule DSL construct (no loops allowed, planning/35 L1089-1097)`));
35
+ scanBannedKeys(node[key], path ? `${path}.${key}` : key, errors);
36
+ }
37
+ }
38
+ function singleKey(obj) {
39
+ const keys = Object.keys(obj);
40
+ return keys.length === 1 ? keys[0] : null;
41
+ }
42
+ function parseAppliesTo(raw, path, errors) {
43
+ if (!isPlainObject(raw)) {
44
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", path, "applies_to is required and must be an object"));
45
+ return null;
46
+ }
47
+ const allowedKeys = ["tx_kind", "scope"];
48
+ for (const key of Object.keys(raw)) if (!allowedKeys.includes(key)) errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", `${path}.${key}`, `Unknown applies_to field "${key}"`));
49
+ if (!isString(raw.tx_kind)) {
50
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", `${path}.tx_kind`, "applies_to.tx_kind is required"));
51
+ return null;
52
+ }
53
+ const appliesTo = { txKind: raw.tx_kind };
54
+ if (raw.scope !== void 0) if (!isString(raw.scope)) errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", `${path}.scope`, "applies_to.scope must be a string"));
55
+ else appliesTo.scope = raw.scope;
56
+ return appliesTo;
57
+ }
58
+ function parseEligibility(raw, path, errors) {
59
+ if (!isString(raw.set)) {
60
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", `${path}.set`, "eligibility.set is required"));
61
+ return null;
62
+ }
63
+ if (!require_primitives.ELIGIBILITY_MODES.includes(raw.mode)) {
64
+ errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", `${path}.mode`, `eligibility.mode must be one of ${require_primitives.ELIGIBILITY_MODES.join("|")}, got ${JSON.stringify(raw.mode)}`));
65
+ return null;
66
+ }
67
+ return {
68
+ primitive: "eligibility",
69
+ set: raw.set,
70
+ mode: raw.mode
71
+ };
72
+ }
73
+ function parseTime(raw, path, errors) {
74
+ if (!require_primitives.TIME_TYPES.includes(raw.type)) {
75
+ errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", `${path}.type`, `time.type must be one of ${require_primitives.TIME_TYPES.join("|")}, got ${JSON.stringify(raw.type)}`));
76
+ return null;
77
+ }
78
+ if (!(isString(raw.value) || isNumber(raw.value))) {
79
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", `${path}.value`, "time.value is required (timestamp | duration | epoch_id)"));
80
+ return null;
81
+ }
82
+ return {
83
+ primitive: "time",
84
+ timeType: raw.type,
85
+ value: raw.value
86
+ };
87
+ }
88
+ function parseRate(raw, path, errors) {
89
+ if (!isString(raw.window)) {
90
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", `${path}.window`, "rate.window is required"));
91
+ return null;
92
+ }
93
+ if (!isPlainObject(raw.limit)) {
94
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", `${path}.limit`, "rate.limit is required"));
95
+ return null;
96
+ }
97
+ const limitRaw = raw.limit;
98
+ const hasCount = limitRaw.count !== void 0;
99
+ if (hasCount === (limitRaw.sum !== void 0)) {
100
+ errors.push(require_errors.makeError("INVALID_EXPR", `${path}.limit`, "rate.limit must have exactly one of \"count\" or \"sum\""));
101
+ return null;
102
+ }
103
+ if (hasCount) {
104
+ if (!isNumber(limitRaw.count)) {
105
+ errors.push(require_errors.makeError("TYPE_MISMATCH", `${path}.limit.count`, "rate.limit.count must be a number"));
106
+ return null;
107
+ }
108
+ return {
109
+ primitive: "rate",
110
+ window: raw.window,
111
+ limit: { count: limitRaw.count }
112
+ };
113
+ }
114
+ if (!isString(limitRaw.sum)) {
115
+ errors.push(require_errors.makeError("INVALID_EXPR", `${path}.limit.sum`, "rate.limit.sum must be an expression string"));
116
+ return null;
117
+ }
118
+ const parsed = require_expr.parseValueExpr(limitRaw.sum);
119
+ if (!parsed.ok || !parsed.value) {
120
+ errors.push(require_errors.makeError("INVALID_EXPR", `${path}.limit.sum`, `Invalid expression: ${limitRaw.sum}`));
121
+ return null;
122
+ }
123
+ if (!require_expr.isValidCounterValueType(parsed.value)) {
124
+ errors.push(require_errors.makeError("TYPE_MISMATCH", `${path}.limit.sum`, "rate.limit.sum must be number | tx.field | state.field"));
125
+ return null;
126
+ }
127
+ return {
128
+ primitive: "rate",
129
+ window: raw.window,
130
+ limit: { sum: parsed.value }
131
+ };
132
+ }
133
+ function parseMatchList(raw, path, errors) {
134
+ if (raw === void 0) return [];
135
+ if (!Array.isArray(raw)) {
136
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", path, "match must be an array"));
137
+ return [];
138
+ }
139
+ const nodes = [];
140
+ raw.forEach((item, idx) => {
141
+ const itemPath = `${path}[${idx}]`;
142
+ if (!isPlainObject(item)) {
143
+ errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", itemPath, "match item must be an object with one primitive key"));
144
+ return;
145
+ }
146
+ const key = singleKey(item);
147
+ if (key === "eligibility") {
148
+ const node = parseEligibility(item.eligibility, `${itemPath}.eligibility`, errors);
149
+ if (node) nodes.push(node);
150
+ } else if (key === "time") {
151
+ const node = parseTime(item.time, `${itemPath}.time`, errors);
152
+ if (node) nodes.push(node);
153
+ } else if (key === "rate") {
154
+ const node = parseRate(item.rate, `${itemPath}.rate`, errors);
155
+ if (node) nodes.push(node);
156
+ } else errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", itemPath, `Unknown match primitive "${key ?? Object.keys(item).join(",")}", expected one of eligibility|time|rate`));
157
+ });
158
+ return nodes;
159
+ }
160
+ function parseCounter(raw, path, errors) {
161
+ if (!require_primitives.COUNTER_OPS.includes(raw.op)) {
162
+ errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", `${path}.op`, `counter.op must be one of ${require_primitives.COUNTER_OPS.join("|")}, got ${JSON.stringify(raw.op)}`));
163
+ return null;
164
+ }
165
+ if (!isString(raw.key)) {
166
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", `${path}.key`, "counter.key is required"));
167
+ return null;
168
+ }
169
+ if (raw.value === void 0 || raw.value === null) {
170
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", `${path}.value`, "counter.value is required"));
171
+ return null;
172
+ }
173
+ if (typeof raw.value === "boolean") {
174
+ errors.push(require_errors.makeError("TYPE_MISMATCH", `${path}.value`, "counter.value must be number | tx.field | state.field, got a boolean literal (planning/35 Primitive 1)"));
175
+ return null;
176
+ }
177
+ if (!isString(raw.value) && !isNumber(raw.value)) {
178
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", `${path}.value`, "counter.value is required"));
179
+ return null;
180
+ }
181
+ const exprSrc = String(raw.value);
182
+ const parsed = require_expr.parseValueExpr(exprSrc);
183
+ if (!parsed.ok || !parsed.value) {
184
+ errors.push(require_errors.makeError("INVALID_EXPR", `${path}.value`, `Invalid expression: ${exprSrc}`));
185
+ return null;
186
+ }
187
+ if (!require_expr.isValidCounterValueType(parsed.value)) {
188
+ errors.push(require_errors.makeError("TYPE_MISMATCH", `${path}.value`, "counter.value must be number | tx.field | state.field (planning/35 Primitive 1)"));
189
+ return null;
190
+ }
191
+ return {
192
+ primitive: "counter",
193
+ op: raw.op,
194
+ key: raw.key,
195
+ value: parsed.value
196
+ };
197
+ }
198
+ function parseAllocate(raw, path, errors) {
199
+ if (!isString(raw.source)) {
200
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", `${path}.source`, "allocate.source is required"));
201
+ return null;
202
+ }
203
+ if (!isPlainObject(raw.strategy)) {
204
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", `${path}.strategy`, "allocate.strategy is required"));
205
+ return null;
206
+ }
207
+ const strategyRaw = raw.strategy;
208
+ if (!require_primitives.STRATEGY_TYPES.includes(strategyRaw.type)) {
209
+ errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", `${path}.strategy.type`, `allocate.strategy.type must be one of ${require_primitives.STRATEGY_TYPES.join("|")}, got ${JSON.stringify(strategyRaw.type)}`));
210
+ return null;
211
+ }
212
+ const params = strategyRaw.params;
213
+ if (params !== void 0 && !isPlainObject(params)) {
214
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", `${path}.strategy.params`, "allocate.strategy.params must be an object"));
215
+ return null;
216
+ }
217
+ return {
218
+ primitive: "allocate",
219
+ source: raw.source,
220
+ strategy: {
221
+ type: strategyRaw.type,
222
+ params: params ?? {}
223
+ }
224
+ };
225
+ }
226
+ function parseEffectsList(raw, path, errors) {
227
+ if (raw === void 0) return [];
228
+ if (!Array.isArray(raw)) {
229
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", path, "effects must be an array"));
230
+ return [];
231
+ }
232
+ const nodes = [];
233
+ raw.forEach((item, idx) => {
234
+ const itemPath = `${path}[${idx}]`;
235
+ if (!isPlainObject(item)) {
236
+ errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", itemPath, "effects item must be an object with one primitive key"));
237
+ return;
238
+ }
239
+ const key = singleKey(item);
240
+ if (key === "counter") {
241
+ const node = parseCounter(item.counter, `${itemPath}.counter`, errors);
242
+ if (node) nodes.push(node);
243
+ } else if (key === "allocate") {
244
+ const node = parseAllocate(item.allocate, `${itemPath}.allocate`, errors);
245
+ if (node) nodes.push(node);
246
+ } else errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", itemPath, `Unknown effect primitive "${key ?? Object.keys(item).join(",")}", expected one of counter|allocate`));
247
+ });
248
+ return nodes;
249
+ }
250
+ function parseThreshold(raw, path, errors) {
251
+ if (!isString(raw.expr)) {
252
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", `${path}.expr`, "threshold.expr is required"));
253
+ return null;
254
+ }
255
+ const parsed = require_expr.parseBoolExpr(raw.expr);
256
+ if (!parsed.ok || !parsed.value) {
257
+ errors.push(require_errors.makeError("INVALID_EXPR", `${path}.expr`, `Invalid expression: ${raw.expr}`));
258
+ return null;
259
+ }
260
+ if (require_expr.boolExprTypeMismatch(parsed.value)) {
261
+ errors.push(require_errors.makeError("TYPE_MISMATCH", `${path}.expr`, `Type mismatch in expression: ${raw.expr}`));
262
+ return null;
263
+ }
264
+ if (!require_primitives.ON_FAIL_MODES.includes(raw.on_fail)) {
265
+ errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", `${path}.on_fail`, `threshold.on_fail must be one of ${require_primitives.ON_FAIL_MODES.join("|")}, got ${JSON.stringify(raw.on_fail)}`));
266
+ return null;
267
+ }
268
+ return {
269
+ primitive: "threshold",
270
+ expr: parsed.value,
271
+ onFail: raw.on_fail
272
+ };
273
+ }
274
+ function parseConstraintsList(raw, path, errors) {
275
+ if (raw === void 0) return [];
276
+ if (!Array.isArray(raw)) {
277
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", path, "constraints must be an array"));
278
+ return [];
279
+ }
280
+ const nodes = [];
281
+ raw.forEach((item, idx) => {
282
+ const itemPath = `${path}[${idx}]`;
283
+ if (!isPlainObject(item)) {
284
+ errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", itemPath, "constraints item must be an object with one primitive key"));
285
+ return;
286
+ }
287
+ const key = singleKey(item);
288
+ if (key === "threshold") {
289
+ const node = parseThreshold(item.threshold, `${itemPath}.threshold`, errors);
290
+ if (node) nodes.push(node);
291
+ } else errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", itemPath, `Unknown constraint primitive "${key ?? Object.keys(item).join(",")}", expected threshold`));
292
+ });
293
+ return nodes;
294
+ }
295
+ function parseOrdering(raw, path, errors) {
296
+ if (raw === void 0) return void 0;
297
+ if (!isPlainObject(raw)) {
298
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", path, "ordering must be an object"));
299
+ return;
300
+ }
301
+ const ordering = {};
302
+ if (raw.priority !== void 0) if (!isNumber(raw.priority)) errors.push(require_errors.makeError("TYPE_MISMATCH", `${path}.priority`, "ordering.priority must be a number"));
303
+ else ordering.priority = raw.priority;
304
+ if (raw.mode !== void 0) if (!require_primitives.ORDERING_MODES.includes(raw.mode)) errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", `${path}.mode`, `ordering.mode must be one of ${require_primitives.ORDERING_MODES.join("|")}, got ${JSON.stringify(raw.mode)}`));
305
+ else ordering.mode = raw.mode;
306
+ return ordering;
307
+ }
308
+ function parseBranches(raw, path, errors) {
309
+ if (raw === void 0) return void 0;
310
+ if (!Array.isArray(raw)) {
311
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", path, "branches must be an array"));
312
+ return;
313
+ }
314
+ const branches = [];
315
+ raw.forEach((item, idx) => {
316
+ const itemPath = `${path}[${idx}]`;
317
+ if (!isPlainObject(item)) {
318
+ errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", itemPath, "branch item must be an object"));
319
+ return;
320
+ }
321
+ if (!require_primitives.DECISIONS.includes(item.decision)) {
322
+ errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", `${itemPath}.decision`, `branch.decision must be one of ${require_primitives.DECISIONS.join("|")}, got ${JSON.stringify(item.decision)}`));
323
+ return;
324
+ }
325
+ const branch = { decision: item.decision };
326
+ if (item.when !== void 0) branch.when = parseConstraintsList(item.when, `${itemPath}.when`, errors);
327
+ if (item.delay !== void 0) if (!isString(item.delay)) errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", `${itemPath}.delay`, "branch.delay must be a string"));
328
+ else branch.delay = item.delay;
329
+ branches.push(branch);
330
+ });
331
+ return branches;
332
+ }
333
+ function parseMetadata(raw, path, errors) {
334
+ if (raw === void 0) return void 0;
335
+ if (!isPlainObject(raw)) {
336
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", path, "metadata must be an object"));
337
+ return;
338
+ }
339
+ const metadata = {};
340
+ if (raw.issuer !== void 0) if (!isString(raw.issuer)) errors.push(require_errors.makeError("TYPE_MISMATCH", `${path}.issuer`, "metadata.issuer must be a string"));
341
+ else metadata.issuer = raw.issuer;
342
+ if (raw.version !== void 0) if (!isNumber(raw.version)) errors.push(require_errors.makeError("TYPE_MISMATCH", `${path}.version`, "metadata.version must be a number"));
343
+ else metadata.version = raw.version;
344
+ if (raw.valid_from !== void 0) if (!isNumber(raw.valid_from)) errors.push(require_errors.makeError("TYPE_MISMATCH", `${path}.valid_from`, "metadata.valid_from must be a number"));
345
+ else metadata.validFrom = raw.valid_from;
346
+ if (raw.valid_until !== void 0) if (!isNumber(raw.valid_until)) errors.push(require_errors.makeError("TYPE_MISMATCH", `${path}.valid_until`, "metadata.valid_until must be a number"));
347
+ else metadata.validUntil = raw.valid_until;
348
+ return metadata;
349
+ }
350
+ /** Parses Rule DSL v1 YAML text into an AST, collecting all shape/expr errors found. */
351
+ function parseRuleDsl(text) {
352
+ const errors = [];
353
+ let raw;
354
+ try {
355
+ raw = js_yaml.default.load(text);
356
+ } catch (e) {
357
+ errors.push(require_errors.makeError("YAML_SYNTAX_ERROR", "$", `YAML syntax error: ${e.message}`));
358
+ return {
359
+ ast: null,
360
+ errors
361
+ };
362
+ }
363
+ if (!isPlainObject(raw)) {
364
+ errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", "$", "Rule document must be a YAML mapping"));
365
+ return {
366
+ ast: null,
367
+ errors
368
+ };
369
+ }
370
+ scanBannedKeys(raw, "", errors);
371
+ for (const key of Object.keys(raw)) if (!require_primitives.RULE_TOP_LEVEL_KEYS.includes(key)) errors.push(require_errors.makeError("UNKNOWN_PRIMITIVE", key, `Unknown top-level rule field "${key}"`));
372
+ if (!isString(raw.rule)) errors.push(require_errors.makeError("MISSING_REQUIRED_FIELD", "rule", "rule (rule id) is required"));
373
+ const appliesTo = parseAppliesTo(raw.applies_to, "applies_to", errors);
374
+ const match = parseMatchList(raw.match, "match", errors);
375
+ const effects = parseEffectsList(raw.effects, "effects", errors);
376
+ const constraints = parseConstraintsList(raw.constraints, "constraints", errors);
377
+ const ordering = parseOrdering(raw.ordering, "ordering", errors);
378
+ const branches = parseBranches(raw.branches, "branches", errors);
379
+ const metadata = parseMetadata(raw.metadata, "metadata", errors);
380
+ if (!isString(raw.rule) || !appliesTo) return {
381
+ ast: null,
382
+ errors
383
+ };
384
+ return {
385
+ ast: {
386
+ rule: raw.rule,
387
+ appliesTo,
388
+ match,
389
+ effects,
390
+ constraints,
391
+ ...ordering && Object.keys(ordering).length > 0 ? { ordering } : {},
392
+ ...branches ? { branches } : {},
393
+ ...metadata && Object.keys(metadata).length > 0 ? { metadata } : {}
394
+ },
395
+ errors
396
+ };
397
+ }
398
+
399
+ //#endregion
400
+ exports.parseRuleDsl = parseRuleDsl;
@@ -0,0 +1,12 @@
1
+ import { RuleDslError } from "./errors.cjs";
2
+ import { RuleAst } from "./types.cjs";
3
+
4
+ //#region src/parser.d.ts
5
+ interface ParseResult {
6
+ ast: RuleAst | null;
7
+ errors: RuleDslError[];
8
+ }
9
+ /** Parses Rule DSL v1 YAML text into an AST, collecting all shape/expr errors found. */
10
+ declare function parseRuleDsl(text: string): ParseResult;
11
+ //#endregion
12
+ export { ParseResult, parseRuleDsl };
@@ -0,0 +1,37 @@
1
+ const require_compiler = require('./compiler.cjs');
2
+ const require_parser = require('./parser.cjs');
3
+ const require_validator = require('./validator.cjs');
4
+
5
+ //#region src/pipeline.ts
6
+ /**
7
+ * Convenience orchestration of the full "text -> parse -> validate -> compile"
8
+ * pipeline described in issue #870. Prefer calling parseRuleDsl / validateRule
9
+ * / compileRule directly when you need to inspect an intermediate stage.
10
+ */
11
+ function processRuleDsl(text, options = {}) {
12
+ const { ast, errors: parseErrors } = require_parser.parseRuleDsl(text);
13
+ if (!ast) return {
14
+ ast: null,
15
+ dag: null,
16
+ errors: parseErrors
17
+ };
18
+ const validateErrors = require_validator.validateRule(ast, options);
19
+ if (parseErrors.length > 0 || validateErrors.length > 0) return {
20
+ ast,
21
+ dag: null,
22
+ errors: [...parseErrors, ...validateErrors]
23
+ };
24
+ const { dag, errors: compileErrors } = require_compiler.compileRule(ast);
25
+ return {
26
+ ast,
27
+ dag,
28
+ errors: [
29
+ ...parseErrors,
30
+ ...validateErrors,
31
+ ...compileErrors
32
+ ]
33
+ };
34
+ }
35
+
36
+ //#endregion
37
+ exports.processRuleDsl = processRuleDsl;
@@ -0,0 +1,18 @@
1
+ import { RuleDslError } from "./errors.cjs";
2
+ import { CompiledRuleDag, RuleAst } from "./types.cjs";
3
+ import { ValidateOptions } from "./validator.cjs";
4
+
5
+ //#region src/pipeline.d.ts
6
+ interface ProcessResult {
7
+ ast: RuleAst | null;
8
+ dag: CompiledRuleDag | null;
9
+ errors: RuleDslError[];
10
+ }
11
+ /**
12
+ * Convenience orchestration of the full "text -> parse -> validate -> compile"
13
+ * pipeline described in issue #870. Prefer calling parseRuleDsl / validateRule
14
+ * / compileRule directly when you need to inspect an intermediate stage.
15
+ */
16
+ declare function processRuleDsl(text: string, options?: ValidateOptions): ProcessResult;
17
+ //#endregion
18
+ export { ProcessResult, processRuleDsl };
@@ -0,0 +1,69 @@
1
+
2
+ //#region src/primitives.ts
3
+ /** Closed-world enums for Rule DSL v1 (planning/35 §6.6). */
4
+ const MATCH_PRIMITIVES = [
5
+ "eligibility",
6
+ "time",
7
+ "rate"
8
+ ];
9
+ const EFFECT_PRIMITIVES = ["counter", "allocate"];
10
+ const CONSTRAINT_PRIMITIVES = ["threshold"];
11
+ const COUNTER_OPS = [
12
+ "increment",
13
+ "decrement",
14
+ "set"
15
+ ];
16
+ const ELIGIBILITY_MODES = ["include", "exclude"];
17
+ const TIME_TYPES = [
18
+ "at",
19
+ "after",
20
+ "window",
21
+ "epoch"
22
+ ];
23
+ const STRATEGY_TYPES = [
24
+ "fixed",
25
+ "weighted",
26
+ "waterfall"
27
+ ];
28
+ const ON_FAIL_MODES = [
29
+ "reject",
30
+ "timelock",
31
+ "skip"
32
+ ];
33
+ const ORDERING_MODES = ["first_match", "all_apply"];
34
+ const DECISIONS = [
35
+ "allow",
36
+ "reject",
37
+ "timelock"
38
+ ];
39
+ const RULE_TOP_LEVEL_KEYS = [
40
+ "rule",
41
+ "applies_to",
42
+ "match",
43
+ "effects",
44
+ "constraints",
45
+ "ordering",
46
+ "branches",
47
+ "metadata"
48
+ ];
49
+ /**
50
+ * Syntax explicitly banned by planning/35 ("非法语法(明确禁止)", L1089-1097).
51
+ * We scan raw YAML keys for these regardless of nesting depth: the DSL has no
52
+ * legitimate construct named `for`/`while`, so their presence anywhere means
53
+ * the author is trying to smuggle in imperative control flow.
54
+ */
55
+ const BANNED_KEYS = ["for", "while"];
56
+
57
+ //#endregion
58
+ exports.BANNED_KEYS = BANNED_KEYS;
59
+ exports.CONSTRAINT_PRIMITIVES = CONSTRAINT_PRIMITIVES;
60
+ exports.COUNTER_OPS = COUNTER_OPS;
61
+ exports.DECISIONS = DECISIONS;
62
+ exports.EFFECT_PRIMITIVES = EFFECT_PRIMITIVES;
63
+ exports.ELIGIBILITY_MODES = ELIGIBILITY_MODES;
64
+ exports.MATCH_PRIMITIVES = MATCH_PRIMITIVES;
65
+ exports.ON_FAIL_MODES = ON_FAIL_MODES;
66
+ exports.ORDERING_MODES = ORDERING_MODES;
67
+ exports.RULE_TOP_LEVEL_KEYS = RULE_TOP_LEVEL_KEYS;
68
+ exports.STRATEGY_TYPES = STRATEGY_TYPES;
69
+ exports.TIME_TYPES = TIME_TYPES;
@@ -0,0 +1,22 @@
1
+ //#region src/primitives.d.ts
2
+ /** Closed-world enums for Rule DSL v1 (planning/35 §6.6). */
3
+ declare const MATCH_PRIMITIVES: readonly ["eligibility", "time", "rate"];
4
+ declare const EFFECT_PRIMITIVES: readonly ["counter", "allocate"];
5
+ declare const CONSTRAINT_PRIMITIVES: readonly ["threshold"];
6
+ declare const COUNTER_OPS: readonly ["increment", "decrement", "set"];
7
+ declare const ELIGIBILITY_MODES: readonly ["include", "exclude"];
8
+ declare const TIME_TYPES: readonly ["at", "after", "window", "epoch"];
9
+ declare const STRATEGY_TYPES: readonly ["fixed", "weighted", "waterfall"];
10
+ declare const ON_FAIL_MODES: readonly ["reject", "timelock", "skip"];
11
+ declare const ORDERING_MODES: readonly ["first_match", "all_apply"];
12
+ declare const DECISIONS: readonly ["allow", "reject", "timelock"];
13
+ declare const RULE_TOP_LEVEL_KEYS: readonly ["rule", "applies_to", "match", "effects", "constraints", "ordering", "branches", "metadata"];
14
+ /**
15
+ * Syntax explicitly banned by planning/35 ("非法语法(明确禁止)", L1089-1097).
16
+ * We scan raw YAML keys for these regardless of nesting depth: the DSL has no
17
+ * legitimate construct named `for`/`while`, so their presence anywhere means
18
+ * the author is trying to smuggle in imperative control flow.
19
+ */
20
+ declare const BANNED_KEYS: readonly ["for", "while"];
21
+ //#endregion
22
+ export { BANNED_KEYS, CONSTRAINT_PRIMITIVES, COUNTER_OPS, DECISIONS, EFFECT_PRIMITIVES, ELIGIBILITY_MODES, MATCH_PRIMITIVES, ON_FAIL_MODES, ORDERING_MODES, RULE_TOP_LEVEL_KEYS, STRATEGY_TYPES, TIME_TYPES };
package/lib/types.cjs ADDED
File without changes