All files / core/src exception.ts

100% Statements 310/310
100% Branches 49/49
100% Functions 30/30
100% Lines 310/310

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358  1x 1x   1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   7x 7x 1x 11x 11x 11x 12x 11x 11x 1x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x   11x 11x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 1x 35x 35x 35x 36x 35x 35x 1x 35x 35x   35x 35x 35x 35x 35x 35x 35x 35x 35x 35x   35x 35x 1x 14x 14x 14x 14x 14x 14x 14x 14x   14x 14x 1x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x   79x 79x 1x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x   36x 36x 1x 13x 13x 13x 13x 13x 13x 13x 13x   13x 13x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   3x 3x 1x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x   33x 33x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 1x   1x 1x 1x 1x 14x 14x 14x   14x 14x 1x 1x 1x 11x 11x 11x 11x 1x 2x 2x 2x 2x 1x 35x 35x 35x 35x 1x 33x 33x 33x   33x 14x 14x 14x   19x 33x 1x 1x 1x 7x 7x 7x   7x 7x 1x 3x 3x   3x 3x 1x 10x 10x 10x 10x   10x 10x 1x 4x 4x 4x 4x 4x   4x 4x 1x 3x 3x 3x 3x 3x   3x 1x 1x 1x   2x 3x 1x 26x 26x 26x   26x 26x 1x 6x 6x 6x   6x 6x 1x 45x 45x 45x   45x 45x 1x 1x 1x 2x 2x 2x   2x 2x 1x 12x 12x 12x 12x 12x   12x 12x 1x 2x 2x 2x 2x 2x   2x 2x 1x 21x 21x 21x 21x 21x   21x 21x 1x 1x 1x 1x   1x 1x 1x 1x                           237x 237x 158x   158x 165x 165x 158x 237x  
import type { KeyLike, StateMutation } from './types.js';
import { typeOf } from '@beerush/utils';
import { microtask } from './utils/index.js';
 
const generator = {
  init(message: string) {
    const messages = [
      '\x1b[1m[violation] Initializing non-linkable object:\x1b[0m',
      '',
      `\x1b[4m\x1b[1m${message}\x1b[0m`,
      '',
      '\x1b[1mRemember\x1b[0m: Only the following types are supported:',
      '- Object, Array, Set, and Map',
      '',
      '\x1b[3m\x1b[1mPlease check the error stack below for more details.',
    ];
 
    return `⚠️\x1b[31m${'\x1b[1m[anchor]' + messages.join('\n')}\x1b[0m\n\n`;
  },
  argumentException(message: string) {
    message = message
      .split('\n')
      .map((line, i) => {
        if (i === 0) {
          return `\x1b[4m\x1b[1m${line}\x1b[0m`;
        }
        return line;
      })
      .join('\n');
 
    const messages = [
      '\x1b[1mAn invalid function argument given:\x1b[0m',
      '',
      `\x1b[4m\x1b[1m${message}\x1b[0m`,
      '',
      'This is likely due to an invalid argument being passed.',
      'Please check the provided arguments and try again.',
      '',
      '\x1b[3m\x1b[1mSee stack trace below for debugging information.',
    ];
 
    return `⚠️\x1b[31m${'\x1b[1m[anchor] ' + messages.join('\n')}\x1b[0m\n\n`;
  },
  internalException(message: string) {
    const messages = [
      '\x1b[1mAn internal exception occured:\x1b[0m',
      '',
      `\x1b[4m\x1b[1m${message}\x1b[0m`,
      '',
      'This is likely a bug in the library implementation.',
      'Please report this issue with the full stack trace.',
      '',
      '\x1b[3m\x1b[1mSee stack trace below for debugging information.',
    ];
 
    return `⚠️\x1b[31m${'\x1b[1m[anchor] ' + messages.join('\n')}\x1b[0m\n\n`;
  },
  externalException(message: string) {
    message = message
      .split('\n')
      .map((line, i) => {
        if (i === 0) {
          return `\x1b[4m\x1b[1m${line}\x1b[0m`;
        }
        return line;
      })
      .join('\n');
 
    const messages = [
      '\x1b[1mAn external exception occured:\x1b[0m',
      '',
      `\x1b[4m\x1b[1m${message}\x1b[0m`,
      '',
      'This error originated from an external source (e.g., application logic, subscription handler).',
      'If you believe this is an issue with the library, please report it with the full stack trace.',
      '',
      '\x1b[3m\x1b[1mSee stack trace below for debugging information.',
    ];
 
    return `⚠️\x1b[31m${'\x1b[1m[anchor] ' + messages.join('\n')}\x1b[0m\n\n`;
  },
  warning(title: string, message: string, ...extras: string[]) {
    const messages = [
      `\x1b[1m[warning] ${title}\x1b[0m`,
      '',
      `\x1b[4m\x1b[1m${message}\x1b[0m`,
      ...extras,
      '',
      '\x1b[3m\x1b[1mSee stack trace below for more details if available.',
    ];
 
    return `⚠️\x1b[33m${'\x1b[1m[anchor]' + messages.join('\n')}\x1b[0m\n\n`;
  },
  violation(message: string) {
    const messages = [
      '\x1b[1m[violation] Read-only state violation detected:\x1b[0m',
      '',
      `\x1b[4m\x1b[1m${message}\x1b[0m`,
      '',
      '\x1b[1mImportant\x1b[0m: Direct mutation of read-only state is not permitted.',
      "- If this state was declared immutable, use a designated 'writer' function to modify it.",
      "- If this state should be mutable, ensure it was initialized without the 'immutable: true' option.",
      '',
      '\x1b[3m\x1b[1mSee stack trace below for debugging information.',
    ];
 
    return `⚠️\x1b[31m${'\x1b[1m[anchor]' + messages.join('\n')}\x1b[0m\n\n`;
  },
  contractViolation(message: string) {
    const messages = [
      '\x1b[1m[violation] Write contract violation detected:\x1b[0m',
      '',
      `\x1b[4m\x1b[1m${message}\x1b[0m`,
      '',
      '\x1b[1mImportant\x1b[0m: Mutation of non-contract property is not allowed.',
      '- If write contract is declared with specific props, only those props are mutable.',
      '- If write contract of array, set, and map is declared with specific methods, only those methods are available.',
      '',
      '\x1b[3m\x1b[1mSee stack trace below for debugging information.',
    ];
 
    return `⚠️\x1b[31m${'\x1b[1m[anchor]' + messages.join('\n')}\x1b[0m\n\n`;
  },
  generalViolation(title: string, message: string, notes?: string[]) {
    const messages = [
      `\x1b[1m[violation] ${title}\x1b[0m`,
      '',
      `\x1b[4m\x1b[1m${message}\x1b[0m`,
      notes ? `\n\x1b[1mImportant\x1b[0m: ${notes.join('\n')}\x1b[0m` : undefined,
      '',
      '\x1b[3m\x1b[1mSee stack trace below for debugging information.',
    ].filter((t) => t !== undefined);
 
    return `⚠️\x1b[31m${'\x1b[1m[anchor]' + messages.join('\n')}\x1b[0m\n\n`;
  },
  schemaViolation(message: string) {
    const messages = [
      '\x1b[1m[schema] Schema violation detected:\x1b[0m',
      '',
      `\x1b[4m\x1b[1m${message}\x1b[0m`,
      '',
      'The provided schema does not match the expected structure.',
      '- Ensure that all required properties are present and of the correct type.',
      '- Check that the schema adheres to the defined structure and constraints.',
      '',
      '\x1b[3m\x1b[1mSee stack trace below for debugging information.',
    ];
 
    return `⚠️\x1b[31m${'\x1b[1m[anchor]' + messages.join('\n')}\x1b[0m\n\n`;
  },
  validation(context: string, message: string) {
    const messages = [
      '\x1b[1m[schema] Input validation failed:\x1b[0m',
      '',
      `\x1b[4m\x1b[1m${context}\x1b[0m`,
      '',
      message,
      '',
      'The provided input does not match the expected structure.',
      '- Ensure that all required properties are present and of the correct type.',
      '- Check that the schema adheres to the defined structure and constraints.',
      '',
      '\x1b[3m\x1b[1mSee stack trace below for debugging information.',
    ];
 
    return `⚠️\x1b[31m${'\x1b[1m[anchor]' + messages.join('\n')}\x1b[0m\n\n`;
  },
  circularViolation(message: string) {
    const messages = [
      '\x1b[1m[violation] Circular reference detected:\x1b[0m',
      '',
      `\x1b[4m\x1b[1m${message}\x1b[0m`,
      '',
      '\x1b[1mImportant\x1b[0m: Circular references in state objects are not permitted.',
      '- Ensure that the state object does not contain circular references.',
      '- Consider using a different data structure or serialization approach.',
      '',
      '\x1b[3m\x1b[1mSee stack trace below for debugging information.',
    ];
 
    return `⚠️\x1b[31m${'\x1b[1m[anchor]' + messages.join('\n')}\x1b[0m\n\n`;
  },
};
 
const [schedule] = microtask(0);
export const captureStack = {
  warning: {
    external(title: string, body: string, trace: string | unknown, ...excludeStacks: unknown[]) {
      const message = generator.warning(title, body);
      const error = new Error(typeof trace === 'string' ? trace : body);
      shiftStack(error, captureStack.warning.external, excludeStacks);
 
      console.warn(message, error, '\n');
    },
  },
  error: {
    argument(text: string, error: Error, ...excludeStacks: unknown[]) {
      const message = generator.argumentException(text);
      shiftStack(error, captureStack.error.argument, excludeStacks);
      console.error(message, error, '\n');
    },
    internal(text: string, error: Error, ...excludeStacks: unknown[]) {
      const message = generator.internalException(text);
      shiftStack(error, captureStack.error.internal, excludeStacks);
      console.error(message, error, '\n');
    },
    external(text: string, error: Error, ...excludeStacks: unknown[]) {
      const message = generator.externalException(text);
      shiftStack(error, captureStack.error.external, excludeStacks);
      console.error(message, error, '\n');
    },
    validation(context: string, error: Error, strict?: boolean, ...excludeStacks: unknown[]) {
      const message = generator.validation(context, error.message as string);
      error = new Error('Invalid input.');
      shiftStack(error, captureStack.error.validation, excludeStacks);
 
      if (strict) {
        console.error(message);
        throw error;
      }
 
      console.error(message, error, '\n');
    },
  },
  violation: {
    init(value: unknown, ...excludeStacks: unknown[]) {
      const message = generator.init(`Attempted to create state from "${typeOf(value)}".`);
      const error = new Error(`Type data "${typeOf(value)}" is not observable.`);
      shiftStack(error, captureStack.violation.init, excludeStacks);
 
      console.error(message, error, '\n');
    },
    general(title: string, body: string, error: Error, notes?: string[], ...excludedStacks: unknown[]) {
      const message = generator.generalViolation(title, body, notes);
      shiftStack(error, captureStack.violation.general, excludedStacks);
 
      schedule(() => console.error(message, error, '\n'));
    },
    derivation(body: string, error: Error, ...excludedStacks: unknown[]) {
      const message = generator.generalViolation('Derivation violation detected:', body, [
        'This error is caused by providing a non-reactive state to the derivation call. If you think this is a bug, please report it at https://github.com/beerush-id/anchor/issues',
      ]);
      shiftStack(error, captureStack.violation.derivation, excludedStacks);
 
      console.error(message, error, '\n');
    },
    circular(prop: KeyLike, ...excludeStacks: unknown[]) {
      const message = generator.circularViolation(
        `Attempted to link child state: "${prop as string}" that references to itself.`
      );
      const error = new Error(`Circular reference violation: "${prop as string}".`);
      shiftStack(error, captureStack.violation.circular, excludeStacks);
 
      console.error(message, error, '\n');
    },
    schema(expected: string, value: string, strict: boolean, ...excludeStacks: unknown[]) {
      const message = generator.schemaViolation(
        `Attempted to initialize schema of state: "${value}". Expected: "${value}".`
      );
      const error = new Error(`Invalid init schema: "${typeOf(value)}".`);
      shiftStack(error, captureStack.violation.schema, excludeStacks);
 
      if (strict) {
        console.error(message);
        throw error;
      }
 
      console.error(message, error, '\n');
    },
    setter(prop: KeyLike, ...excludeStacks: unknown[]) {
      const message = generator.violation(`Attempted to modify property "${prop as string}" of a read-only state.`);
      const error = new Error(`Property "${prop as string}" is read-only.`);
      shiftStack(error, captureStack.violation.setter, excludeStacks);
 
      console.error(message, error, '\n');
    },
    remover(prop: KeyLike, ...excludeStacks: unknown[]) {
      const message = generator.violation(`Attempt to delete property "${prop as string}" of a read-only state.`);
      const error = new Error(`Property "${prop as string}" is read-only.`);
      shiftStack(error, captureStack.violation.remover, excludeStacks);
 
      console.error(message, error, '\n');
    },
    methodCall(method: StateMutation, ...excludeStacks: unknown[]) {
      const message = generator.violation(`Attempt to mutate: "${method}" of a read-only state.`);
      const error = new Error(`State is read-only.`);
      shiftStack(error, captureStack.violation.methodCall, excludeStacks);
 
      console.error(message, error, '\n');
    },
  },
  contractViolation: {
    init(...excludeStacks: unknown[]) {
      const message = generator.violation('Attempted to create write contract of non-reactive state.');
      const error = new Error('State is not reactive.');
      shiftStack(error, captureStack.contractViolation.init, excludeStacks);
 
      console.error(message, error, '\n');
    },
    setter(prop: KeyLike, ...excludeStacks: unknown[]) {
      const message = generator.contractViolation(
        `Attempted to modify property "${prop as string}" of a write contract.`
      );
      const error = new Error(`Property "${prop as string}" is read-only.`);
      shiftStack(error, captureStack.contractViolation.setter, excludeStacks);
 
      console.error(message, error, '\n');
    },
    remover(prop: KeyLike, ...excludeStacks: unknown[]) {
      const message = generator.contractViolation(
        `Attempt to delete property "${prop as string}" of a write contract.`
      );
      const error = new Error(`Property "${prop as string}" is read-only.`);
      shiftStack(error, captureStack.contractViolation.remover, excludeStacks);
 
      console.error(message, error, '\n');
    },
    methodRead(prop: KeyLike, ...excludeStacks: unknown[]) {
      const message = generator.contractViolation(
        `Attempted to access mutation: "${prop as string}" of a write contract.`
      );
      const error = new Error(`Method "${prop as string}" is immutable.`);
      shiftStack(error, captureStack.contractViolation.methodRead, excludeStacks);
 
      console.error(message, error, '\n');
    },
    methodCall(method: StateMutation, ...excludeStacks: unknown[]) {
      const message = generator.contractViolation(`Attempt to mutate: "${method}" of a write contract.`);
      const error = new Error(`State is read-only.`);
      shiftStack(error, captureStack.contractViolation.methodCall, excludeStacks);
 
      console.error(message, error, '\n');
    },
  },
};
 
/**
 * Shifts the stack trace of an error to exclude specified stack frames.
 *
 * This function modifies the stack trace of the provided error object by
 * removing stack frames associated with the caller and any functions
 * specified in the excludedStacks array. It uses Error.captureStackTrace
 * when available (e.g., in Node.js environments).
 *
 * @param error - The error object whose stack trace will be modified
 * @param caller - The function that should appear as the top of the stack trace
 * @param excludedStacks - An array of functions whose stack frames should be removed
 */
function shiftStack(error: Error, caller: unknown, excludedStacks: unknown[]) {
  if (excludedStacks.length) {
    Error.captureStackTrace?.(error, caller as () => void);
 
    for (const fn of [...excludedStacks]) {
      Error.captureStackTrace?.(error, fn as () => void);
    }
  }
}