notImplementedFail.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * Structural not-implemented stubs: a replaced module must expose every symbol
  3. * its importers name (a missing CommonJS symbol degrades to `undefined` at call
  4. * time instead of failing at link time), and every one of those symbols must
  5. * report exactly what is unavailable when it is finally called.
  6. */
  7. /**
  8. * Build a function that throws naming its module and symbol. The refusal is
  9. * also written to the console before it propagates: callers routinely swallow
  10. * these errors far from their cause, and the console line is what places the
  11. * failure while debugging a worker session.
  12. *
  13. * `Face` is the Node declaration this stub stands in for, so the replaced module
  14. * publishes the type its importers compile against. The value is one throwing
  15. * function whatever that declaration says: a caller reaches the throw before any
  16. * declared parameter, return value, or `new` result exists, so the assertion
  17. * below cannot be observed as a lie. It is a function expression rather than an
  18. * arrow because a stub standing in for a class must refuse under `new` too, and
  19. * an arrow has no construct behavior to reach.
  20. * @param module - module specifier being stubbed.
  21. * @param symbol - exported symbol name.
  22. * @returns the throwing stand-in, typed as the member it replaces.
  23. */
  24. // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- only the return position carries the Node declaration
  25. export function notImplementedFail<Face = (...args: never[]) => never>(module: string, symbol: string): Face {
  26. return (function refuse(): never {
  27. throw notAvailableError(module, symbol)
  28. }) as Face
  29. }
  30. /**
  31. * Build the refusal error and write it to the console first, for stubs that
  32. * cannot be a plain throwing function (constructors, methods on structural
  33. * fakes).
  34. * @param module - module specifier being stubbed.
  35. * @param symbol - unavailable member, named as the importer sees it.
  36. * @returns the error to throw.
  37. */
  38. export function notAvailableError(module: string, symbol: string): Error {
  39. const message = `web-preview: ${module}.${symbol} is not available in the worker host`
  40. console.error(message)
  41. return new Error(message)
  42. }