microsoft / typespec

https://typespec.io/
MIT License
4.46k stars 209 forks source link

[Bug]: Compiler crashes when importing mjs #4878

Open crowbait opened 3 hours ago

crowbait commented 3 hours ago

Describe the bug

While trying to implement a decorator, I didn't want to create an entire package for a few lines of code. This seems convoluted.

Since the project this spec is located in is not a module, I have to use mjs files to be able to use imports. This leads to the following, as soon as I import the mjs file:

ExternalError: Emitter "@typespec/openapi3" crashed!

Since this is a very slim project, I'm hestitant to make it more extensive as it needs to be. So my battle plan is:

Reproduction

partial.mts

import {DecoratorContext, Model, ModelProperty, validateDecoratorTarget} from '@typespec/compiler';

function updateModelPropertiesInPlace(
  model: Model,
  callback: (key: string, prop: ModelProperty) => ModelProperty
): void {
  for (const [key, prop] of model.properties) {
    const updatedProp = callback(key, prop);
    model.properties.set(key, updatedProp);
  }
}

export const $withPartial = (
  context: DecoratorContext,
  target: Model
): void => {
  if (!validateDecoratorTarget(context, target, '@withPartial', 'Model')) {
    return;
  }
  updateModelPropertiesInPlace(target, (key, prop) => {
    if (prop.optional) return prop;
    return {...prop, optional: true};
  });
};

partial.tsp

import "./partial.mjs";
using TypeSpec.Reflection;
extern dec withPartial(target: Model);

helpers.tsconfig.json

{
  "compilerOptions": {
    "target": "es2019",
    "module": "Node16",
    "moduleResolution": "Node16",
    "rootDir": ".",
    "outDir": ".",
    "strict": true
  },
  "include": ["./*.mts"],
  "exclude": ["node_modules"]
}

Calling tsc -p helpers.tsconfig.json compiles without errors, the output mjs looks fine, but as soon as import "./partial.mjs"; is hit in the tsp file, TypeSpec crashes on me.

Is there a better way of extending TypeSpec to my needs? I feel like extending the framework (especially with something as light as this) wouldn't / shouldn't need the entire overhead of managing an entirely separate package.

Checklist

crowbait commented 3 hours ago

This is my try to make use of this comment: https://github.com/microsoft/typespec/discussions/4230#discussioncomment-10412266