import {
  ata,
  prettier
} from "./chunk-chunk-NHK6UHLW.mjs";
import {
  __name,
  init_define_process
} from "./chunk-chunk-5RXWZEI4.mjs";

// src/startMonaco.ts
init_define_process();
import { editor, languages, Uri } from "/monaco-editor";
var { createModel } = editor;
var create = editor.create;
var originToUse = location.origin;
var lib = [
  "dom",
  "dom.iterable",
  "es2015",
  "es2016",
  "esnext"
];
function fetchAndCreateExtraModels(code, originToUse2) {
  const extraModels = [];
  const search = new RegExp(
    ` from "(${originToUse2})?/live/[a-zA-Z0-9-_]+`,
    "gm"
  );
  const models = code.matchAll(search);
  for (const match of models) {
    const codeSpace = match[0].split("/live/").pop();
    const extraModel = new URL(
      `/live/${codeSpace}/index.tsx`,
      originToUse2
    ).toString();
    const mUri = Uri.parse(`${originToUse2}/live/${codeSpace}/index.tsx`);
    extraModels.push(
      fetch(extraModel).then((res) => res.text()).then((content) => {
        editor.getModel(mUri) || createModel(content, "typescript", mUri);
        return true;
      })
    );
  }
  return extraModels;
}
__name(fetchAndCreateExtraModels, "fetchAndCreateExtraModels");
var monacoContribution = /* @__PURE__ */ __name((code) => {
  languages.typescript.typescriptDefaults.setCompilerOptions({
    baseUrl: originToUse,
    target: languages.typescript.ScriptTarget.Latest,
    allowNonTsExtensions: true,
    moduleResolution: languages.typescript.ModuleResolutionKind.NodeJs,
    module: languages.typescript.ModuleKind.CommonJS,
    importHelpers: true,
    lib,
    allowJs: true,
    skipLibCheck: false,
    downlevelIteration: true,
    esModuleInterop: true,
    allowSyntheticDefaultImports: true,
    forceConsistentCasingInFileNames: true,
    noFallthroughCasesInSwitch: true,
    resolveJsonModule: true,
    noEmit: true,
    traceResolution: true,
    declaration: true,
    noEmitOnError: true,
    sourceMap: true,
    maxNodeModuleJsDepth: 20,
    rootDir: `${originToUse}/`,
    paths: {
      "tslib": ["/tslib"]
    },
    jsxImportSource: "@emotion/react",
    jsx: languages.typescript.JsxEmit.ReactJSX,
    allowUmdGlobalAccess: false,
    include: [`${originToUse}/`]
  });
  const extraModels = fetchAndCreateExtraModels(code, originToUse);
  ata({ code, originToUse }).then(async (extraLibs) => {
    console.log({ extraLibs });
    languages.typescript.typescriptDefaults.setExtraLibs([...extraLibs, { content: await fetch(`${originToUse}/v125/tslib@2.5.3/es2022/tslib.bundle.mjs`).then((x) => x.text()), filePath: originToUse + "/tslib" }]);
    if (extraModels.length)
      await Promise.all(extraModels);
    languages.typescript.typescriptDefaults.setDiagnosticsOptions({
      noSuggestionDiagnostics: false,
      noSemanticValidation: false,
      noSyntaxValidation: false,
      diagnosticCodesToIgnore: [2691]
    });
    languages.typescript.typescriptDefaults.setEagerModelSync(true);
  });
  return code;
}, "monacoContribution");
self.MonacoEnvironment = {
  baseUrl: originToUse,
  getWorker: async (_, label) => {
    if (label === "json") {
      const jWorker = (await import(`${originToUse}/monaco-editor/esm/vs/language/json/json.worker?worker`)).default;
      return jWorker();
    }
    if (label === "css" || label === "scss" || label === "less") {
      const cWorker = (await import(`${originToUse}/monaco-editor/esm/vs/language/css/css.worker?worker`)).default;
      return cWorker();
    }
    if (label === "html" || label === "handlebars" || label === "razor") {
      const hWorker = (await import(`${originToUse}/monaco-editor/esm/vs/language/html/html.worker?worker`)).default;
      return hWorker();
    }
    if (label === "typescript" || label === "javascript") {
      const tsWorker = (await import(`${originToUse}/monaco-editor/esm/vs/language/typescript/ts.worker.js?worker`)).default;
      return tsWorker();
    }
    const edWorker = (await import(`${originToUse}/monaco-editor/esm/vs/editor/editor.worker?worker`)).default;
    return edWorker();
  }
};
var mod = {};
var startMonaco = /* @__PURE__ */ __name(async ({ code, container, codeSpace, onChange }) => mod[codeSpace] = mod[codeSpace] || await startMonacoPristine({ code, container, codeSpace, onChange }), "startMonaco");
async function startMonacoPristine({ code, container, codeSpace, onChange }) {
  var _a;
  const BC = new BroadcastChannel(`${location.origin}/live/${codeSpace}/`);
  const replaced = await monacoContribution(
    code
  );
  languages.typescript.typescriptDefaults.setDiagnosticsOptions({
    noSuggestionDiagnostics: true,
    noSemanticValidation: true,
    noSyntaxValidation: true,
    diagnosticCodesToIgnore: [2691]
  });
  const uri = Uri.parse(`${originToUse}/live/${codeSpace}/index.tsx`);
  const model = editor.getModel(uri) || createModel(
    replaced,
    "typescript",
    uri
  );
  const myEditor = create(container, {
    model,
    scrollbar: {
      scrollByPage: false,
      alwaysConsumeMouseWheel: false
    },
    scrollBeyondLastLine: true,
    scrollPredominantAxis: false,
    smoothScrolling: true,
    suggest: {
      /**
       * Overwrite word ends on accept. Default to false.
       */
      insertMode: "replace",
      /**
       * Enable graceful matching. Defaults to true.
       */
      filterGraceful: true,
      /**
       * Prevent quick suggestions when a snippet is active. Defaults to true.
       */
      snippetsPreventQuickSuggestions: true,
      /**
       * Favors words that appear close to the cursor.
       */
      localityBonus: true,
      /**
       * Enable using global storage for remembering suggestions.
       */
      shareSuggestSelections: true,
      /**
       * Enable or disable icons in suggestions. Defaults to true.
       */
      showIcons: true,
      /**
       * Enable or disable the suggest status bar.
       */
      showStatusBar: true,
      /**
       * Enable or disable the rendering of the suggestion preview.
       */
      preview: true,
      /**
       * Configures the mode of the preview.
       */
      previewMode: "subwordSmart",
      /**
       * Show details inline with the label. Defaults to true.
       */
      showInlineDetails: true,
      /**
       * Show method-suggestions.
       */
      showMethods: true,
      /**
       * Show function-suggestions.
       */
      showFunctions: true,
      /**
       * Show constructor-suggestions.
       */
      showConstructors: true,
      /**
       * Show deprecated-suggestions.
       */
      /**
       * Show field-suggestions.
       */
      showFields: true,
      showModules: true,
      /**
       * Show color-suggestions.
       */
      showColors: true,
      /**
       * Show file-suggestions.
       */
      showFiles: true,
      /**
       * Show reference-suggestions.
       */
      showReferences: true,
      /**
       * Show folder-suggestions.
       */
      showFolders: false,
      /**
       * Show typeParameter-suggestions.
       */
      showTypeParameters: true,
      /**
       * Show issue-suggestions.
       */
      showIssues: true,
      /**
       * Show user-suggestions.
       */
      showUsers: true,
      /**
       * Show snippet-suggestions.
       */
      showSnippets: true
    },
    automaticLayout: true,
    useShadowDOM: false,
    tabSize: 2,
    insertSpaces: true,
    contextmenu: true,
    stablePeek: true,
    roundedSelection: true,
    //  Editing: true,
    bracketPairColorization: {
      independentColorPoolPerBracketType: true,
      enabled: true
    },
    // bracketPairGuides: {
    // bracketPairs: true,
    // bracketPairsHorizontal : true,
    // highlightActiveBracketPair: true,
    ///  indentation: true,
    // highlightActiveIndentation:  'always'
    // },
    codeLens: true,
    "semanticHighlighting.enabled": true,
    dragAndDrop: true,
    codeActionsOnSaveTimeout: 100,
    dropIntoEditor: { enabled: true },
    // GotoLocation: true,]]
    mouseStyle: "default",
    definitionLinkOpensInPeek: true,
    theme: "vs-dark",
    autoClosingBrackets: "beforeWhitespace"
  });
  let ctr = new AbortController();
  setInterval(async () => {
    const typeScriptWorker = await (await languages.typescript.getTypeScriptWorker())(uri);
    const diag2 = await typeScriptWorker.getSyntacticDiagnostics(
      uri.toString()
    );
    diag2.map((d) => false);
    const diag3 = await typeScriptWorker.getSemanticDiagnostics(uri.toString());
    diag3.map(async (d) => {
      const message = d.messageText.toString();
      if (message.indexOf("Cannot find module") !== -1) {
        const pkg = message.split("'")[1];
        if (pkg.indexOf("https://"))
          return;
        const cnt = await fetch(originToUse + "/" + pkg, {
          redirect: "follow"
        });
        if (cnt.headers.has("X-TypeScript-Types")) {
          languages.typescript.typescriptDefaults.addExtraLib(
            await (await fetch(cnt.headers.get("X-TypeScript-Types"))).text(),
            `${originToUse}/${pkg}/index.d.ts`
          );
        }
        if (cnt.headers.has("X-TypeScript-Types")) {
          languages.typescript.typescriptDefaults.addExtraLib(
            await cnt.text(),
            `/${pkg}/index.ts`
          );
        }
        console.error({ pkg });
      }
    });
    return typeScriptWorker.getSuggestionDiagnostics(uri.toString()).then((diag) => diag.map((d) => false)).catch(
      (e) => {
        console.log("ts error, will retry", e);
      }
    );
  }, 5e3);
  const mod2 = {
    getValue: () => model.getValue(),
    silent: false,
    getErrors: async () => {
      return (await (await languages.typescript.getTypeScriptWorker())(uri)).getSuggestionDiagnostics(uri.toString()).then((diag) => diag.map((d) => d.messageText.toString())).catch(
        (e) => {
          console.log("ts error, will retry", e);
        }
      );
    },
    isEdit: false,
    setValue: (code2) => {
      var _a2;
      (_a2 = myEditor.getDomNode()) == null ? void 0 : _a2.blur();
      if (mod2.isEdit)
        return;
      mod2.silent = true;
      let state = null;
      try {
        try {
          state = myEditor.saveViewState();
        } catch {
          console.error("error while saving monaco state");
        }
        model.setValue(code2);
        if (state) {
          myEditor.restoreViewState(state);
        }
      } catch {
        console.error("error while saving the state");
      } finally {
        setTimeout(() => {
          mod2.silent = false;
        }, 500);
      }
    }
  };
  (_a = myEditor.getDomNode()) == null ? void 0 : _a.blur();
  myEditor.onDidFocusEditorText(() => {
    mod2.isEdit = true;
    ctr.abort();
    ctr = new AbortController();
    setTimeout(() => {
      if (ctr.signal.aborted)
        return;
      mod2.isEdit = false;
    }, 200);
  });
  myEditor.onDidBlurEditorText(async () => {
    mod2.setValue(await prettier(model.getValue()));
    mod2.isEdit = true;
  });
  BC.onmessage = ({ data }) => {
    if (mod2.silent)
      return;
    if (data.changes) {
      mod2.silent = true;
      model.applyEdits(data.changes);
      mod2.silent = false;
    }
  };
  model.onDidChangeContent((_ev) => {
    const newCode = model.getValue();
    mod2.isEdit = true;
    ctr.abort();
    ctr = new AbortController();
    setTimeout(() => {
      if (ctr.signal.aborted)
        return;
      mod2.isEdit = false;
    }, 1e3);
    if (!mod2.silent) {
      onChange(newCode);
    }
  });
  return mod2;
}
__name(startMonacoPristine, "startMonacoPristine");
export {
  startMonaco
};
