1.1.1Updated a month ago
import { join } from 'node:path';
import { existsSync } from "jsr:@std/fs/exists";
import type { VP_Request } from "./vp_request.ts";
import { HandlePublish } from "./handle_publish.ts";
import { Package } from "../classes/package.ts";
import { ServeTyped } from "../utils/serve_ts.ts";
import { HOST_URL } from "../cli/config.ts";

export const HandleRequest = async (request: VP_Request, _info: Deno.ServeHandlerInfo<Deno.NetAddr>) => {
  if(request.method == 'PUT') return HandlePublish(request);

  if(request.method !== 'GET') return 400;

  try {
    const location = request.pathname.replace(/^\//, '');

    const _package = await Package.FindByPath(location);

    if(!_package) throw new Deno.errors.NotFound;

    const deep_file_path = location.replace(/@\w+\/\w+(?:@[\d\.]+)?/, "");

    const render_path = join(_package.path!, deep_file_path);

    if(existsSync(render_path, { isFile: true })) return ServeTyped(render_path);

    const is_root_path = ['', '/'].includes(deep_file_path);

    if(!is_root_path) return 404;

    const check_files = [
      join(_package.path!, 'mod.ts'),
      join(_package.path!, 'main.ts'),
      join(_package.path!, 'index.ts'),
    ];

    for(const infer_path of check_files) {
      if(existsSync(infer_path)) {
        const file_path = infer_path.replace(_package.path!, '').replace(/^\/+/, '');

        return new Response(null, {
          headers: {
            Location: `${HOST_URL}/${_package.namespace}/${_package.name}@${_package.versions.current}/${file_path}`
          },
          status: 307
        });
      }
    }

    return 404;
  } catch(_) {
    return 500;
  }
}