invariant.js.flow 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @providesModule invariant
  8. * @flow
  9. */
  10. 'use strict';
  11. declare var __DEV__: boolean;
  12. const validateFormat = __DEV__ ? function (format: mixed): void {} : function (format: mixed): void {
  13. if (format === undefined) {
  14. throw new Error('invariant(...): Second argument must be a string.');
  15. }
  16. };
  17. /**
  18. * Use invariant() to assert state which your program assumes to be true.
  19. *
  20. * Provide sprintf-style format (only %s is supported) and arguments to provide
  21. * information about what broke and what you were expecting.
  22. *
  23. * The invariant message will be stripped in production, but the invariant will
  24. * remain to ensure logic does not differ in production.
  25. */
  26. function invariant(condition: mixed, format: string, ...args: Array<mixed>): void {
  27. validateFormat(format);
  28. if (!condition) {
  29. let error;
  30. if (format === undefined) {
  31. error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
  32. } else {
  33. let argIndex = 0;
  34. error = new Error(format.replace(/%s/g, () => String(args[argIndex++])));
  35. error.name = 'Invariant Violation';
  36. }
  37. (error: any).framesToPop = 1; // Skip invariant's own stack frame.
  38. throw error;
  39. }
  40. }
  41. module.exports = invariant;