UNPKG

44.1 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@ngrx/store'), require('rxjs'), require('rxjs/operators'), require('@angular/core')) :
3 typeof define === 'function' && define.amd ? define('@ngrx/effects', ['exports', '@ngrx/store', 'rxjs', 'rxjs/operators', '@angular/core'], factory) :
4 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.ngrx = global.ngrx || {}, global.ngrx.effects = {}), global.ngrx.store, global.rxjs, global.rxjs.operators, global.ng.core));
5}(this, (function (exports, store, rxjs, operators, core) { 'use strict';
6
7 var DEFAULT_EFFECT_CONFIG = {
8 dispatch: true,
9 useEffectsErrorHandler: true,
10 };
11 var CREATE_EFFECT_METADATA_KEY = '__@ngrx/effects_create__';
12
13 /**
14 * @description
15 * Creates an effect from an `Observable` and an `EffectConfig`.
16 *
17 * @param source A function which returns an `Observable`.
18 * @param config A `Partial<EffectConfig>` to configure the effect. By default, `dispatch` is true and `useEffectsErrorHandler` is true.
19 * @returns If `EffectConfig`#`dispatch` is true, returns `Observable<Action>`. Else, returns `Observable<unknown>`.
20 *
21 * @usageNotes
22 *
23 * ** Mapping to a different action **
24 * ```ts
25 * effectName$ = createEffect(
26 * () => this.actions$.pipe(
27 * ofType(FeatureActions.actionOne),
28 * map(() => FeatureActions.actionTwo())
29 * )
30 * );
31 * ```
32 *
33 * ** Non-dispatching effects **
34 * ```ts
35 * effectName$ = createEffect(
36 * () => this.actions$.pipe(
37 * ofType(FeatureActions.actionOne),
38 * tap(() => console.log('Action One Dispatched'))
39 * ),
40 * { dispatch: false }
41 * // FeatureActions.actionOne is not dispatched
42 * );
43 * ```
44 */
45 function createEffect(source, config) {
46 var effect = source();
47 var value = Object.assign(Object.assign({}, DEFAULT_EFFECT_CONFIG), config);
48 Object.defineProperty(effect, CREATE_EFFECT_METADATA_KEY, {
49 value: value,
50 });
51 return effect;
52 }
53 function getCreateEffectMetadata(instance) {
54 var propertyNames = Object.getOwnPropertyNames(instance);
55 var metadata = propertyNames
56 .filter(function (propertyName) {
57 if (instance[propertyName] &&
58 instance[propertyName].hasOwnProperty(CREATE_EFFECT_METADATA_KEY)) {
59 // If the property type has overridden `hasOwnProperty` we need to ensure
60 // that the metadata is valid (containing a `dispatch`property)
61 // https://github.com/ngrx/platform/issues/2975
62 var property = instance[propertyName];
63 return property[CREATE_EFFECT_METADATA_KEY].hasOwnProperty('dispatch');
64 }
65 return false;
66 })
67 .map(function (propertyName) {
68 var metaData = instance[propertyName][CREATE_EFFECT_METADATA_KEY];
69 return Object.assign({ propertyName: propertyName }, metaData);
70 });
71 return metadata;
72 }
73
74 function getSourceForInstance(instance) {
75 return Object.getPrototypeOf(instance);
76 }
77
78 var METADATA_KEY = '__@ngrx/effects__';
79 /**
80 * @deprecated The Effect decorator (`@Effect`) is deprecated in favor for the `createEffect` method.
81 * See the docs for more info {@link https://ngrx.io/guide/migration/v11#the-effect-decorator}
82 */
83 function Effect(config) {
84 if (config === void 0) { config = {}; }
85 return function (target, propertyName) {
86 var metadata = Object.assign(Object.assign(Object.assign({}, DEFAULT_EFFECT_CONFIG), config), {
87 propertyName: propertyName
88 });
89 addEffectMetadataEntry(target, metadata);
90 };
91 }
92 function getEffectDecoratorMetadata(instance) {
93 var effectsDecorators = store.compose(getEffectMetadataEntries, getSourceForInstance)(instance);
94 return effectsDecorators;
95 }
96 /**
97 * Type guard to detemine whether METADATA_KEY is already present on the Class
98 * constructor
99 */
100 function hasMetadataEntries(sourceProto) {
101 return sourceProto.constructor.hasOwnProperty(METADATA_KEY);
102 }
103 /** Add Effect Metadata to the Effect Class constructor under specific key */
104 function addEffectMetadataEntry(sourceProto, metadata) {
105 if (hasMetadataEntries(sourceProto)) {
106 sourceProto.constructor[METADATA_KEY].push(metadata);
107 }
108 else {
109 Object.defineProperty(sourceProto.constructor, METADATA_KEY, {
110 value: [metadata],
111 });
112 }
113 }
114 function getEffectMetadataEntries(sourceProto) {
115 return hasMetadataEntries(sourceProto)
116 ? sourceProto.constructor[METADATA_KEY]
117 : [];
118 }
119
120 function getEffectsMetadata(instance) {
121 return getSourceMetadata(instance).reduce(function (acc, _a) {
122 var propertyName = _a.propertyName, dispatch = _a.dispatch, useEffectsErrorHandler = _a.useEffectsErrorHandler;
123 acc[propertyName] = { dispatch: dispatch, useEffectsErrorHandler: useEffectsErrorHandler };
124 return acc;
125 }, {});
126 }
127 function getSourceMetadata(instance) {
128 var effects = [
129 getEffectDecoratorMetadata,
130 getCreateEffectMetadata,
131 ];
132 return effects.reduce(function (sources, source) { return sources.concat(source(instance)); }, []);
133 }
134
135 /*! *****************************************************************************
136 Copyright (c) Microsoft Corporation.
137
138 Permission to use, copy, modify, and/or distribute this software for any
139 purpose with or without fee is hereby granted.
140
141 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
142 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
143 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
144 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
145 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
146 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
147 PERFORMANCE OF THIS SOFTWARE.
148 ***************************************************************************** */
149 /* global Reflect, Promise */
150 var extendStatics = function (d, b) {
151 extendStatics = Object.setPrototypeOf ||
152 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
153 function (d, b) { for (var p in b)
154 if (Object.prototype.hasOwnProperty.call(b, p))
155 d[p] = b[p]; };
156 return extendStatics(d, b);
157 };
158 function __extends(d, b) {
159 if (typeof b !== "function" && b !== null)
160 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
161 extendStatics(d, b);
162 function __() { this.constructor = d; }
163 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
164 }
165 var __assign = function () {
166 __assign = Object.assign || function __assign(t) {
167 for (var s, i = 1, n = arguments.length; i < n; i++) {
168 s = arguments[i];
169 for (var p in s)
170 if (Object.prototype.hasOwnProperty.call(s, p))
171 t[p] = s[p];
172 }
173 return t;
174 };
175 return __assign.apply(this, arguments);
176 };
177 function __rest(s, e) {
178 var t = {};
179 for (var p in s)
180 if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
181 t[p] = s[p];
182 if (s != null && typeof Object.getOwnPropertySymbols === "function")
183 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
184 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
185 t[p[i]] = s[p[i]];
186 }
187 return t;
188 }
189 function __decorate(decorators, target, key, desc) {
190 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
191 if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
192 r = Reflect.decorate(decorators, target, key, desc);
193 else
194 for (var i = decorators.length - 1; i >= 0; i--)
195 if (d = decorators[i])
196 r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
197 return c > 3 && r && Object.defineProperty(target, key, r), r;
198 }
199 function __param(paramIndex, decorator) {
200 return function (target, key) { decorator(target, key, paramIndex); };
201 }
202 function __metadata(metadataKey, metadataValue) {
203 if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
204 return Reflect.metadata(metadataKey, metadataValue);
205 }
206 function __awaiter(thisArg, _arguments, P, generator) {
207 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
208 return new (P || (P = Promise))(function (resolve, reject) {
209 function fulfilled(value) { try {
210 step(generator.next(value));
211 }
212 catch (e) {
213 reject(e);
214 } }
215 function rejected(value) { try {
216 step(generator["throw"](value));
217 }
218 catch (e) {
219 reject(e);
220 } }
221 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
222 step((generator = generator.apply(thisArg, _arguments || [])).next());
223 });
224 }
225 function __generator(thisArg, body) {
226 var _ = { label: 0, sent: function () { if (t[0] & 1)
227 throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
228 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
229 function verb(n) { return function (v) { return step([n, v]); }; }
230 function step(op) {
231 if (f)
232 throw new TypeError("Generator is already executing.");
233 while (_)
234 try {
235 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
236 return t;
237 if (y = 0, t)
238 op = [op[0] & 2, t.value];
239 switch (op[0]) {
240 case 0:
241 case 1:
242 t = op;
243 break;
244 case 4:
245 _.label++;
246 return { value: op[1], done: false };
247 case 5:
248 _.label++;
249 y = op[1];
250 op = [0];
251 continue;
252 case 7:
253 op = _.ops.pop();
254 _.trys.pop();
255 continue;
256 default:
257 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
258 _ = 0;
259 continue;
260 }
261 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
262 _.label = op[1];
263 break;
264 }
265 if (op[0] === 6 && _.label < t[1]) {
266 _.label = t[1];
267 t = op;
268 break;
269 }
270 if (t && _.label < t[2]) {
271 _.label = t[2];
272 _.ops.push(op);
273 break;
274 }
275 if (t[2])
276 _.ops.pop();
277 _.trys.pop();
278 continue;
279 }
280 op = body.call(thisArg, _);
281 }
282 catch (e) {
283 op = [6, e];
284 y = 0;
285 }
286 finally {
287 f = t = 0;
288 }
289 if (op[0] & 5)
290 throw op[1];
291 return { value: op[0] ? op[1] : void 0, done: true };
292 }
293 }
294 var __createBinding = Object.create ? (function (o, m, k, k2) {
295 if (k2 === undefined)
296 k2 = k;
297 Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
298 }) : (function (o, m, k, k2) {
299 if (k2 === undefined)
300 k2 = k;
301 o[k2] = m[k];
302 });
303 function __exportStar(m, o) {
304 for (var p in m)
305 if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
306 __createBinding(o, m, p);
307 }
308 function __values(o) {
309 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
310 if (m)
311 return m.call(o);
312 if (o && typeof o.length === "number")
313 return {
314 next: function () {
315 if (o && i >= o.length)
316 o = void 0;
317 return { value: o && o[i++], done: !o };
318 }
319 };
320 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
321 }
322 function __read(o, n) {
323 var m = typeof Symbol === "function" && o[Symbol.iterator];
324 if (!m)
325 return o;
326 var i = m.call(o), r, ar = [], e;
327 try {
328 while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
329 ar.push(r.value);
330 }
331 catch (error) {
332 e = { error: error };
333 }
334 finally {
335 try {
336 if (r && !r.done && (m = i["return"]))
337 m.call(i);
338 }
339 finally {
340 if (e)
341 throw e.error;
342 }
343 }
344 return ar;
345 }
346 /** @deprecated */
347 function __spread() {
348 for (var ar = [], i = 0; i < arguments.length; i++)
349 ar = ar.concat(__read(arguments[i]));
350 return ar;
351 }
352 /** @deprecated */
353 function __spreadArrays() {
354 for (var s = 0, i = 0, il = arguments.length; i < il; i++)
355 s += arguments[i].length;
356 for (var r = Array(s), k = 0, i = 0; i < il; i++)
357 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
358 r[k] = a[j];
359 return r;
360 }
361 function __spreadArray(to, from) {
362 for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
363 to[j] = from[i];
364 return to;
365 }
366 function __await(v) {
367 return this instanceof __await ? (this.v = v, this) : new __await(v);
368 }
369 function __asyncGenerator(thisArg, _arguments, generator) {
370 if (!Symbol.asyncIterator)
371 throw new TypeError("Symbol.asyncIterator is not defined.");
372 var g = generator.apply(thisArg, _arguments || []), i, q = [];
373 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
374 function verb(n) { if (g[n])
375 i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
376 function resume(n, v) { try {
377 step(g[n](v));
378 }
379 catch (e) {
380 settle(q[0][3], e);
381 } }
382 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
383 function fulfill(value) { resume("next", value); }
384 function reject(value) { resume("throw", value); }
385 function settle(f, v) { if (f(v), q.shift(), q.length)
386 resume(q[0][0], q[0][1]); }
387 }
388 function __asyncDelegator(o) {
389 var i, p;
390 return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
391 function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
392 }
393 function __asyncValues(o) {
394 if (!Symbol.asyncIterator)
395 throw new TypeError("Symbol.asyncIterator is not defined.");
396 var m = o[Symbol.asyncIterator], i;
397 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
398 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
399 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
400 }
401 function __makeTemplateObject(cooked, raw) {
402 if (Object.defineProperty) {
403 Object.defineProperty(cooked, "raw", { value: raw });
404 }
405 else {
406 cooked.raw = raw;
407 }
408 return cooked;
409 }
410 ;
411 var __setModuleDefault = Object.create ? (function (o, v) {
412 Object.defineProperty(o, "default", { enumerable: true, value: v });
413 }) : function (o, v) {
414 o["default"] = v;
415 };
416 function __importStar(mod) {
417 if (mod && mod.__esModule)
418 return mod;
419 var result = {};
420 if (mod != null)
421 for (var k in mod)
422 if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
423 __createBinding(result, mod, k);
424 __setModuleDefault(result, mod);
425 return result;
426 }
427 function __importDefault(mod) {
428 return (mod && mod.__esModule) ? mod : { default: mod };
429 }
430 function __classPrivateFieldGet(receiver, state, kind, f) {
431 if (kind === "a" && !f)
432 throw new TypeError("Private accessor was defined without a getter");
433 if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
434 throw new TypeError("Cannot read private member from an object whose class did not declare it");
435 return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
436 }
437 function __classPrivateFieldSet(receiver, state, value, kind, f) {
438 if (kind === "m")
439 throw new TypeError("Private method is not writable");
440 if (kind === "a" && !f)
441 throw new TypeError("Private accessor was defined without a setter");
442 if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
443 throw new TypeError("Cannot write private member to an object whose class did not declare it");
444 return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
445 }
446
447 function mergeEffects(sourceInstance, globalErrorHandler, effectsErrorHandler) {
448 var sourceName = getSourceForInstance(sourceInstance).constructor.name;
449 var observables$ = getSourceMetadata(sourceInstance).map(function (_a) {
450 var propertyName = _a.propertyName, dispatch = _a.dispatch, useEffectsErrorHandler = _a.useEffectsErrorHandler;
451 var observable$ = typeof sourceInstance[propertyName] === 'function'
452 ? sourceInstance[propertyName]()
453 : sourceInstance[propertyName];
454 var effectAction$ = useEffectsErrorHandler
455 ? effectsErrorHandler(observable$, globalErrorHandler)
456 : observable$;
457 if (dispatch === false) {
458 return effectAction$.pipe(operators.ignoreElements());
459 }
460 var materialized$ = effectAction$.pipe(operators.materialize());
461 return materialized$.pipe(operators.map(function (notification) { return ({
462 effect: sourceInstance[propertyName],
463 notification: notification,
464 propertyName: propertyName,
465 sourceName: sourceName,
466 sourceInstance: sourceInstance,
467 }); }));
468 });
469 return rxjs.merge.apply(void 0, __spreadArray([], __read(observables$)));
470 }
471
472 var MAX_NUMBER_OF_RETRY_ATTEMPTS = 10;
473 function defaultEffectsErrorHandler(observable$, errorHandler, retryAttemptLeft) {
474 if (retryAttemptLeft === void 0) { retryAttemptLeft = MAX_NUMBER_OF_RETRY_ATTEMPTS; }
475 return observable$.pipe(operators.catchError(function (error) {
476 if (errorHandler)
477 errorHandler.handleError(error);
478 if (retryAttemptLeft <= 1) {
479 return observable$; // last attempt
480 }
481 // Return observable that produces this particular effect
482 return defaultEffectsErrorHandler(observable$, errorHandler, retryAttemptLeft - 1);
483 }));
484 }
485
486 var Actions = /** @class */ (function (_super) {
487 __extends(Actions, _super);
488 function Actions(source) {
489 var _this = _super.call(this) || this;
490 if (source) {
491 _this.source = source;
492 }
493 return _this;
494 }
495 Actions.prototype.lift = function (operator) {
496 var observable = new Actions();
497 observable.source = this;
498 observable.operator = operator;
499 return observable;
500 };
501 return Actions;
502 }(rxjs.Observable));
503 /** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */
504 Actions.decorators = [
505 { type: core.Injectable }
506 ];
507 /**
508 * @type {function(): !Array<(null|{
509 * type: ?,
510 * decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>),
511 * })>}
512 * @nocollapse
513 */
514 Actions.ctorParameters = function () { return [
515 { type: rxjs.Observable, decorators: [{ type: core.Inject, args: [store.ScannedActionsSubject,] }] }
516 ]; };
517 /**
518 * `ofType` filters an Observable of `Actions` into an Observable of the actions
519 * whose type strings are passed to it.
520 *
521 * For example, if `actions` has type `Actions<AdditionAction|SubstractionAction>`, and
522 * the type of the `Addition` action is `add`, then
523 * `actions.pipe(ofType('add'))` returns an `Observable<AdditionAction>`.
524 *
525 * Properly typing this function is hard and requires some advanced TS tricks
526 * below.
527 *
528 * Type narrowing automatically works, as long as your `actions` object
529 * starts with a `Actions<SomeUnionOfActions>` instead of generic `Actions`.
530 *
531 * For backwards compatibility, when one passes a single type argument
532 * `ofType<T>('something')` the result is an `Observable<T>`. Note, that `T`
533 * completely overrides any possible inference from 'something'.
534 *
535 * Unfortunately, for unknown 'actions: Actions' these types will produce
536 * 'Observable<never>'. In such cases one has to manually set the generic type
537 * like `actions.ofType<AdditionAction>('add')`.
538 *
539 * @usageNotes
540 *
541 * Filter the Actions stream on the "customers page loaded" action
542 *
543 * ```ts
544 * import { ofType } from '@ngrx/effects';
545 * import * fromCustomers from '../customers';
546 *
547 * this.actions$.pipe(
548 * ofType(fromCustomers.pageLoaded)
549 * )
550 * ```
551 */
552 function ofType() {
553 var allowedTypes = [];
554 for (var _i = 0; _i < arguments.length; _i++) {
555 allowedTypes[_i] = arguments[_i];
556 }
557 return operators.filter(function (action) { return allowedTypes.some(function (typeOrActionCreator) {
558 if (typeof typeOrActionCreator === 'string') {
559 // Comparing the string to type
560 return typeOrActionCreator === action.type;
561 }
562 // We are filtering by ActionCreator
563 return typeOrActionCreator.type === action.type;
564 }); });
565 }
566
567 function reportInvalidActions(output, reporter) {
568 if (output.notification.kind === 'N') {
569 var action = output.notification.value;
570 var isInvalidAction = !isAction(action);
571 if (isInvalidAction) {
572 reporter.handleError(new Error("Effect " + getEffectName(output) + " dispatched an invalid action: " + stringify(action)));
573 }
574 }
575 }
576 function isAction(action) {
577 return (typeof action !== 'function' &&
578 action &&
579 action.type &&
580 typeof action.type === 'string');
581 }
582 function getEffectName(_b) {
583 var propertyName = _b.propertyName, sourceInstance = _b.sourceInstance, sourceName = _b.sourceName;
584 var isMethod = typeof sourceInstance[propertyName] === 'function';
585 return "\"" + sourceName + "." + String(propertyName) + (isMethod ? '()' : '') + "\"";
586 }
587 function stringify(action) {
588 try {
589 return JSON.stringify(action);
590 }
591 catch (_a) {
592 return action;
593 }
594 }
595
596 var onIdentifyEffectsKey = 'ngrxOnIdentifyEffects';
597 function isOnIdentifyEffects(instance) {
598 return isFunction(instance, onIdentifyEffectsKey);
599 }
600 var onRunEffectsKey = 'ngrxOnRunEffects';
601 function isOnRunEffects(instance) {
602 return isFunction(instance, onRunEffectsKey);
603 }
604 var onInitEffects = 'ngrxOnInitEffects';
605 function isOnInitEffects(instance) {
606 return isFunction(instance, onInitEffects);
607 }
608 function isFunction(instance, functionName) {
609 return (instance &&
610 functionName in instance &&
611 typeof instance[functionName] === 'function');
612 }
613
614 var _ROOT_EFFECTS_GUARD = new core.InjectionToken('@ngrx/effects Internal Root Guard');
615 var USER_PROVIDED_EFFECTS = new core.InjectionToken('@ngrx/effects User Provided Effects');
616 var _ROOT_EFFECTS = new core.InjectionToken('@ngrx/effects Internal Root Effects');
617 var ROOT_EFFECTS = new core.InjectionToken('@ngrx/effects Root Effects');
618 var _FEATURE_EFFECTS = new core.InjectionToken('@ngrx/effects Internal Feature Effects');
619 var FEATURE_EFFECTS = new core.InjectionToken('@ngrx/effects Feature Effects');
620 var EFFECTS_ERROR_HANDLER = new core.InjectionToken('@ngrx/effects Effects Error Handler');
621
622 var EffectSources = /** @class */ (function (_super) {
623 __extends(EffectSources, _super);
624 function EffectSources(errorHandler, effectsErrorHandler) {
625 var _this = _super.call(this) || this;
626 _this.errorHandler = errorHandler;
627 _this.effectsErrorHandler = effectsErrorHandler;
628 return _this;
629 }
630 EffectSources.prototype.addEffects = function (effectSourceInstance) {
631 this.next(effectSourceInstance);
632 };
633 /**
634 * @internal
635 */
636 EffectSources.prototype.toActions = function () {
637 var _this = this;
638 return this.pipe(operators.groupBy(getSourceForInstance), operators.mergeMap(function (source$) {
639 return source$.pipe(operators.groupBy(effectsInstance));
640 }), operators.mergeMap(function (source$) {
641 var effect$ = source$.pipe(operators.exhaustMap(function (sourceInstance) {
642 return resolveEffectSource(_this.errorHandler, _this.effectsErrorHandler)(sourceInstance);
643 }), operators.map(function (output) {
644 reportInvalidActions(output, _this.errorHandler);
645 return output.notification;
646 }), operators.filter(function (notification) { return notification.kind === 'N' && notification.value != null; }), operators.dematerialize());
647 // start the stream with an INIT action
648 // do this only for the first Effect instance
649 var init$ = source$.pipe(operators.take(1), operators.filter(isOnInitEffects), operators.map(function (instance) { return instance.ngrxOnInitEffects(); }));
650 return rxjs.merge(effect$, init$);
651 }));
652 };
653 return EffectSources;
654 }(rxjs.Subject));
655 /** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */
656 EffectSources.decorators = [
657 { type: core.Injectable }
658 ];
659 /**
660 * @type {function(): !Array<(null|{
661 * type: ?,
662 * decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>),
663 * })>}
664 * @nocollapse
665 */
666 EffectSources.ctorParameters = function () { return [
667 { type: core.ErrorHandler },
668 { type: undefined, decorators: [{ type: core.Inject, args: [EFFECTS_ERROR_HANDLER,] }] }
669 ]; };
670 function effectsInstance(sourceInstance) {
671 if (isOnIdentifyEffects(sourceInstance)) {
672 return sourceInstance.ngrxOnIdentifyEffects();
673 }
674 return '';
675 }
676 function resolveEffectSource(errorHandler, effectsErrorHandler) {
677 return function (sourceInstance) {
678 var mergedEffects$ = mergeEffects(sourceInstance, errorHandler, effectsErrorHandler);
679 if (isOnRunEffects(sourceInstance)) {
680 return sourceInstance.ngrxOnRunEffects(mergedEffects$);
681 }
682 return mergedEffects$;
683 };
684 }
685
686 var EffectsRunner = /** @class */ (function () {
687 function EffectsRunner(effectSources, store) {
688 this.effectSources = effectSources;
689 this.store = store;
690 this.effectsSubscription = null;
691 }
692 EffectsRunner.prototype.start = function () {
693 if (!this.effectsSubscription) {
694 this.effectsSubscription = this.effectSources
695 .toActions()
696 .subscribe(this.store);
697 }
698 };
699 EffectsRunner.prototype.ngOnDestroy = function () {
700 if (this.effectsSubscription) {
701 this.effectsSubscription.unsubscribe();
702 this.effectsSubscription = null;
703 }
704 };
705 return EffectsRunner;
706 }());
707 /** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */
708 EffectsRunner.decorators = [
709 { type: core.Injectable }
710 ];
711 /**
712 * @type {function(): !Array<(null|{
713 * type: ?,
714 * decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>),
715 * })>}
716 * @nocollapse
717 */
718 EffectsRunner.ctorParameters = function () { return [
719 { type: EffectSources },
720 { type: store.Store }
721 ]; };
722
723 var ROOT_EFFECTS_INIT = '@ngrx/effects/init';
724 var rootEffectsInit = store.createAction(ROOT_EFFECTS_INIT);
725 var EffectsRootModule = /** @class */ (function () {
726 function EffectsRootModule(sources, runner, store, rootEffects, storeRootModule, storeFeatureModule, guard) {
727 this.sources = sources;
728 runner.start();
729 rootEffects.forEach(function (effectSourceInstance) { return sources.addEffects(effectSourceInstance); });
730 store.dispatch({ type: ROOT_EFFECTS_INIT });
731 }
732 EffectsRootModule.prototype.addEffects = function (effectSourceInstance) {
733 this.sources.addEffects(effectSourceInstance);
734 };
735 return EffectsRootModule;
736 }());
737 /** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */
738 EffectsRootModule.decorators = [
739 { type: core.NgModule, args: [{},] }
740 ];
741 /**
742 * @type {function(): !Array<(null|{
743 * type: ?,
744 * decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>),
745 * })>}
746 * @nocollapse
747 */
748 EffectsRootModule.ctorParameters = function () { return [
749 { type: EffectSources },
750 { type: EffectsRunner },
751 { type: store.Store },
752 { type: Array, decorators: [{ type: core.Inject, args: [ROOT_EFFECTS,] }] },
753 { type: store.StoreRootModule, decorators: [{ type: core.Optional }] },
754 { type: store.StoreFeatureModule, decorators: [{ type: core.Optional }] },
755 { type: undefined, decorators: [{ type: core.Optional }, { type: core.Inject, args: [_ROOT_EFFECTS_GUARD,] }] }
756 ]; };
757
758 var EffectsFeatureModule = /** @class */ (function () {
759 function EffectsFeatureModule(root, effectSourceGroups, storeRootModule, storeFeatureModule) {
760 effectSourceGroups.forEach(function (group) { return group.forEach(function (effectSourceInstance) { return root.addEffects(effectSourceInstance); }); });
761 }
762 return EffectsFeatureModule;
763 }());
764 /** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */
765 EffectsFeatureModule.decorators = [
766 { type: core.NgModule, args: [{},] }
767 ];
768 /**
769 * @type {function(): !Array<(null|{
770 * type: ?,
771 * decorators: (undefined|!Array<{type: !Function, args: (undefined|!Array<?>)}>),
772 * })>}
773 * @nocollapse
774 */
775 EffectsFeatureModule.ctorParameters = function () { return [
776 { type: EffectsRootModule },
777 { type: Array, decorators: [{ type: core.Inject, args: [FEATURE_EFFECTS,] }] },
778 { type: store.StoreRootModule, decorators: [{ type: core.Optional }] },
779 { type: store.StoreFeatureModule, decorators: [{ type: core.Optional }] }
780 ]; };
781
782 var EffectsModule = /** @class */ (function () {
783 function EffectsModule() {
784 }
785 EffectsModule.forFeature = function (featureEffects) {
786 if (featureEffects === void 0) { featureEffects = []; }
787 return {
788 ngModule: EffectsFeatureModule,
789 providers: [
790 featureEffects,
791 {
792 provide: _FEATURE_EFFECTS,
793 multi: true,
794 useValue: featureEffects,
795 },
796 {
797 provide: USER_PROVIDED_EFFECTS,
798 multi: true,
799 useValue: [],
800 },
801 {
802 provide: FEATURE_EFFECTS,
803 multi: true,
804 useFactory: createEffects,
805 deps: [core.Injector, _FEATURE_EFFECTS, USER_PROVIDED_EFFECTS],
806 },
807 ],
808 };
809 };
810 EffectsModule.forRoot = function (rootEffects) {
811 if (rootEffects === void 0) { rootEffects = []; }
812 return {
813 ngModule: EffectsRootModule,
814 providers: [
815 {
816 provide: EFFECTS_ERROR_HANDLER,
817 useValue: defaultEffectsErrorHandler,
818 },
819 EffectsRunner,
820 EffectSources,
821 Actions,
822 rootEffects,
823 {
824 provide: _ROOT_EFFECTS,
825 useValue: [rootEffects],
826 },
827 {
828 provide: _ROOT_EFFECTS_GUARD,
829 useFactory: _provideForRootGuard,
830 deps: [
831 [EffectsRunner, new core.Optional(), new core.SkipSelf()],
832 [_ROOT_EFFECTS, new core.Self()],
833 ],
834 },
835 {
836 provide: USER_PROVIDED_EFFECTS,
837 multi: true,
838 useValue: [],
839 },
840 {
841 provide: ROOT_EFFECTS,
842 useFactory: createEffects,
843 deps: [core.Injector, _ROOT_EFFECTS, USER_PROVIDED_EFFECTS],
844 },
845 ],
846 };
847 };
848 return EffectsModule;
849 }());
850 /** @type {!Array<{type: !Function, args: (undefined|!Array<?>)}>} */
851 EffectsModule.decorators = [
852 { type: core.NgModule, args: [{},] }
853 ];
854 function createEffects(injector, effectGroups, userProvidedEffectGroups) {
855 var e_1, _a, e_2, _b;
856 var mergedEffects = [];
857 try {
858 for (var effectGroups_1 = __values(effectGroups), effectGroups_1_1 = effectGroups_1.next(); !effectGroups_1_1.done; effectGroups_1_1 = effectGroups_1.next()) {
859 var effectGroup = effectGroups_1_1.value;
860 mergedEffects.push.apply(mergedEffects, __spreadArray([], __read(effectGroup)));
861 }
862 }
863 catch (e_1_1) { e_1 = { error: e_1_1 }; }
864 finally {
865 try {
866 if (effectGroups_1_1 && !effectGroups_1_1.done && (_a = effectGroups_1.return)) _a.call(effectGroups_1);
867 }
868 finally { if (e_1) throw e_1.error; }
869 }
870 try {
871 for (var userProvidedEffectGroups_1 = __values(userProvidedEffectGroups), userProvidedEffectGroups_1_1 = userProvidedEffectGroups_1.next(); !userProvidedEffectGroups_1_1.done; userProvidedEffectGroups_1_1 = userProvidedEffectGroups_1.next()) {
872 var userProvidedEffectGroup = userProvidedEffectGroups_1_1.value;
873 mergedEffects.push.apply(mergedEffects, __spreadArray([], __read(userProvidedEffectGroup)));
874 }
875 }
876 catch (e_2_1) { e_2 = { error: e_2_1 }; }
877 finally {
878 try {
879 if (userProvidedEffectGroups_1_1 && !userProvidedEffectGroups_1_1.done && (_b = userProvidedEffectGroups_1.return)) _b.call(userProvidedEffectGroups_1);
880 }
881 finally { if (e_2) throw e_2.error; }
882 }
883 return createEffectInstances(injector, mergedEffects);
884 }
885 function createEffectInstances(injector, effects) {
886 return effects.map(function (effect) { return injector.get(effect); });
887 }
888 function _provideForRootGuard(runner, rootEffects) {
889 // check whether any effects are actually passed
890 var hasEffects = !(rootEffects.length === 1 && rootEffects[0].length === 0);
891 if (hasEffects && runner) {
892 throw new TypeError("EffectsModule.forRoot() called twice. Feature modules should use EffectsModule.forFeature() instead.");
893 }
894 return 'guarded';
895 }
896
897 /**
898 * Wraps project fn with error handling making it safe to use in Effects.
899 * Takes either a config with named properties that represent different possible
900 * callbacks or project/error callbacks that are required.
901 */
902 function act(
903 /** Allow to take either config object or project/error functions */
904 configOrProject, errorFn) {
905 var _a = typeof configOrProject === 'function'
906 ? {
907 project: configOrProject,
908 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
909 error: errorFn,
910 operator: operators.concatMap,
911 complete: undefined,
912 unsubscribe: undefined,
913 }
914 : Object.assign(Object.assign({}, configOrProject), { operator: configOrProject.operator || operators.concatMap }), project = _a.project, error = _a.error, complete = _a.complete, operator = _a.operator, unsubscribe = _a.unsubscribe;
915 return function (source) { return rxjs.defer(function () {
916 var subject = new rxjs.Subject();
917 return rxjs.merge(source.pipe(operator(function (input, index) { return rxjs.defer(function () {
918 var completed = false;
919 var errored = false;
920 var projectedCount = 0;
921 return project(input, index).pipe(operators.materialize(), operators.map(function (notification) {
922 switch (notification.kind) {
923 case 'E':
924 errored = true;
925 return new rxjs.Notification('N', error(notification.error, input));
926 case 'C':
927 completed = true;
928 return complete
929 ? new rxjs.Notification('N', complete(projectedCount, input))
930 : undefined;
931 default:
932 ++projectedCount;
933 return notification;
934 }
935 }), operators.filter(function (n) { return n != null; }), operators.dematerialize(), operators.finalize(function () {
936 if (!completed && !errored && unsubscribe) {
937 subject.next(unsubscribe(projectedCount, input));
938 }
939 }));
940 }); })), subject);
941 }); };
942 }
943
944 /**
945 * `concatLatestFrom` combines the source value
946 * and the last available value from a lazily evaluated Observable
947 * in a new array
948 *
949 * @usageNotes
950 *
951 * Select the active customer from the NgRx Store
952 *
953 * ```ts
954 * import { concatLatestFrom } from '@ngrx/effects';
955 * import * fromCustomers from '../customers';
956 *
957 * this.actions$.pipe(
958 * concatLatestFrom(() => this.store.select(fromCustomers.selectActiveCustomer))
959 * )
960 * ```
961 *
962 * Select a customer from the NgRx Store by its id that is available on the action
963 *
964 * ```ts
965 * import { concatLatestFrom } from '@ngrx/effects';
966 * import * fromCustomers from '../customers';
967 *
968 * this.actions$.pipe(
969 * concatLatestFrom((action) => this.store.select(fromCustomers.selectCustomer(action.customerId)))
970 * )
971 * ```
972 */
973 function concatLatestFrom(observablesFactory) {
974 return rxjs.pipe(operators.concatMap(function (value) {
975 var observables = observablesFactory(value);
976 var observablesAsArray = Array.isArray(observables)
977 ? observables
978 : [observables];
979 return rxjs.of(value).pipe(operators.withLatestFrom.apply(void 0, __spreadArray([], __read(observablesAsArray))));
980 }));
981 }
982
983 /**
984 * DO NOT EDIT
985 *
986 * This file is automatically generated at build
987 */
988
989 /**
990 * Generated bundle index. Do not edit.
991 */
992
993 exports.Actions = Actions;
994 exports.EFFECTS_ERROR_HANDLER = EFFECTS_ERROR_HANDLER;
995 exports.Effect = Effect;
996 exports.EffectSources = EffectSources;
997 exports.EffectsFeatureModule = EffectsFeatureModule;
998 exports.EffectsModule = EffectsModule;
999 exports.EffectsRootModule = EffectsRootModule;
1000 exports.EffectsRunner = EffectsRunner;
1001 exports.ROOT_EFFECTS_INIT = ROOT_EFFECTS_INIT;
1002 exports.USER_PROVIDED_EFFECTS = USER_PROVIDED_EFFECTS;
1003 exports.act = act;
1004 exports.concatLatestFrom = concatLatestFrom;
1005 exports.createEffect = createEffect;
1006 exports.defaultEffectsErrorHandler = defaultEffectsErrorHandler;
1007 exports.getEffectsMetadata = getEffectsMetadata;
1008 exports.mergeEffects = mergeEffects;
1009 exports.ofType = ofType;
1010 exports.rootEffectsInit = rootEffectsInit;
1011 exports.ɵa = getSourceMetadata;
1012 exports.ɵb = createEffects;
1013 exports.ɵc = _provideForRootGuard;
1014 exports.ɵd = _ROOT_EFFECTS_GUARD;
1015 exports.ɵe = _ROOT_EFFECTS;
1016 exports.ɵf = ROOT_EFFECTS;
1017 exports.ɵg = _FEATURE_EFFECTS;
1018 exports.ɵh = FEATURE_EFFECTS;
1019
1020 Object.defineProperty(exports, '__esModule', { value: true });
1021
1022})));
1023//# sourceMappingURL=ngrx-effects.umd.js.map