style_impl.mjs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * @license
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. import '../environment/dev';
  6. import { ensureTokenIsValid, secretToken } from './secrets';
  7. /**
  8. * Sequence of CSS declarations safe to use in style contexts in an HTML
  9. * document or in DOM APIs.
  10. */
  11. export class SafeStyle {
  12. // @ts-ignore: error TS6133: 'brand' is declared but its value is never read.
  13. brand; // To prevent structural typing.
  14. }
  15. /** Implementation for `SafeStyle` */
  16. class StyleImpl extends SafeStyle {
  17. privateDoNotAccessOrElseWrappedStyle;
  18. constructor(style, token) {
  19. super();
  20. if (process.env.NODE_ENV !== 'production') {
  21. ensureTokenIsValid(token);
  22. }
  23. this.privateDoNotAccessOrElseWrappedStyle = style;
  24. }
  25. toString() {
  26. return this.privateDoNotAccessOrElseWrappedStyle;
  27. }
  28. }
  29. /**
  30. * Builds a new `SafeStyle` from the given string, without enforcing
  31. * safety guarantees. This shouldn't be exposed to application developers, and
  32. * must only be used as a step towards safe builders or safe constants.
  33. */
  34. export function createStyle(style) {
  35. return new StyleImpl(style, secretToken);
  36. }
  37. /**
  38. * Checks if the given value is a `SafeStyle` instance.
  39. */
  40. export function isStyle(value) {
  41. return value instanceof StyleImpl;
  42. }
  43. /**
  44. * Returns the string value of the passed `SafeStyle` object while ensuring it
  45. * has the correct type.
  46. */
  47. export function unwrapStyle(value) {
  48. if (value instanceof StyleImpl) {
  49. return value.privateDoNotAccessOrElseWrappedStyle;
  50. }
  51. else {
  52. let message = '';
  53. if (process.env.NODE_ENV !== 'production') {
  54. message = 'Unexpected type when unwrapping SafeStyle';
  55. }
  56. throw new Error(message);
  57. }
  58. }