UNPKG

3.09 kBJavaScriptView Raw
1"use strict";
2/**
3 * @license
4 * Copyright Google LLC All Rights Reserved.
5 *
6 * Use of this source code is governed by an MIT-style license that can be
7 * found in the LICENSE file at https://angular.dev/license
8 */
9Object.defineProperty(exports, "__esModule", { value: true });
10exports.InvalidSourceResultException = exports.InvalidRuleResultException = void 0;
11exports.callSource = callSource;
12exports.callRule = callRule;
13const core_1 = require("@angular-devkit/core");
14const rxjs_1 = require("rxjs");
15const interface_1 = require("../tree/interface");
16function _getTypeOfResult(value) {
17 if (value === undefined) {
18 return 'undefined';
19 }
20 else if (value === null) {
21 return 'null';
22 }
23 else if (typeof value == 'function') {
24 return `Function()`;
25 }
26 else if (typeof value != 'object') {
27 return `${typeof value}(${JSON.stringify(value)})`;
28 }
29 else {
30 if (Object.getPrototypeOf(value) == Object) {
31 return `Object(${JSON.stringify(value)})`;
32 }
33 else if (value.constructor) {
34 return `Instance of class ${value.constructor.name}`;
35 }
36 else {
37 return 'Unknown Object';
38 }
39 }
40}
41/**
42 * When a rule or source returns an invalid value.
43 */
44class InvalidRuleResultException extends core_1.BaseException {
45 constructor(value) {
46 super(`Invalid rule result: ${_getTypeOfResult(value)}.`);
47 }
48}
49exports.InvalidRuleResultException = InvalidRuleResultException;
50class InvalidSourceResultException extends core_1.BaseException {
51 constructor(value) {
52 super(`Invalid source result: ${_getTypeOfResult(value)}.`);
53 }
54}
55exports.InvalidSourceResultException = InvalidSourceResultException;
56function callSource(source, context) {
57 return (0, rxjs_1.defer)(async () => {
58 let result = source(context);
59 if ((0, rxjs_1.isObservable)(result)) {
60 result = await (0, rxjs_1.lastValueFrom)(result.pipe((0, rxjs_1.defaultIfEmpty)(undefined)));
61 }
62 if (result && interface_1.TreeSymbol in result) {
63 return result;
64 }
65 throw new InvalidSourceResultException(result);
66 });
67}
68function callRule(rule, input, context) {
69 if ((0, rxjs_1.isObservable)(input)) {
70 return input.pipe((0, rxjs_1.mergeMap)((inputTree) => callRuleAsync(rule, inputTree, context)));
71 }
72 else {
73 return (0, rxjs_1.defer)(() => callRuleAsync(rule, input, context));
74 }
75}
76async function callRuleAsync(rule, tree, context) {
77 let result = await rule(tree, context);
78 while (typeof result === 'function') {
79 // This is considered a Rule, chain the rule and return its output.
80 result = await result(tree, context);
81 }
82 if (typeof result === 'undefined') {
83 return tree;
84 }
85 if ((0, rxjs_1.isObservable)(result)) {
86 result = await (0, rxjs_1.lastValueFrom)(result.pipe((0, rxjs_1.defaultIfEmpty)(tree)));
87 }
88 if (result && interface_1.TreeSymbol in result) {
89 return result;
90 }
91 throw new InvalidRuleResultException(result);
92}