export function splitSource()

in src/parse.ts [57:110]


export function splitSource(source: string): string[] {
  source = source.replace(/^#.*$/gm, "\n"); // remove comments
  source = source.trim();
  const len = source.length;
  const sources = [];
  let index = 0;
  let prev = 0;
  while (index < len) {
    // Beginning of a new command, we should find the method and proceede to the url.
    for (const method of httpMethods) {
      if (source.slice(index, len).startsWith(method)) {
        index += method.length;
        break;
      }
    }

    nextCommand();
    sources.push(source.slice(prev, index).trim());
    prev = index;
  }

  return sources;

  function nextCommand() {
    if (index == len) return;
    let brackets = 0;
    // If we found an http method, then we have found a new command.
    for (const method of httpMethods) {
      if (source.slice(index, len).startsWith(method)) {
        return;
      }
    }

    // If we didn't find an http method, we should increment the index.
    // If we find an open curly bracket, we should also find the closing one
    // before to checking for the http method.
    if (source[index] == "{") {
      while (index < len) {
        if (source[index] == "{") {
          brackets += 1;
        } else if (source[index] == "}") {
          brackets -= 1;
        }
        if (brackets == 0) {
          break;
        }
        index += 1;
      }
    } else {
      index += 1;
    }
    nextCommand();
  }
}