"use strict";

var __createBinding = void 0 && (void 0).__createBinding || (Object.create ? function (o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  var desc = Object.getOwnPropertyDescriptor(m, k);
  if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
    desc = {
      enumerable: true,
      get: function () {
        return m[k];
      }
    };
  }
  Object.defineProperty(o, k2, desc);
} : function (o, m, k, k2) {
  if (k2 === undefined) k2 = k;
  o[k2] = m[k];
});
var __setModuleDefault = void 0 && (void 0).__setModuleDefault || (Object.create ? function (o, v) {
  Object.defineProperty(o, "default", {
    enumerable: true,
    value: v
  });
} : function (o, v) {
  o["default"] = v;
});
var __importStar = void 0 && (void 0).__importStar || function () {
  var ownKeys = function (o) {
    ownKeys = Object.getOwnPropertyNames || function (o) {
      var ar = [];
      for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
      return ar;
    };
    return ownKeys(o);
  };
  return function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
    __setModuleDefault(result, mod);
    return result;
  };
}();
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.syncHttpRequest = syncHttpRequest;
const crypto_1 = require("crypto");
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const worker_threads_1 = require("worker_threads");
function syncHttpRequest(url, body, timeout = 3000) {
  var _a;
  const tmpFile = path.join(os.tmpdir(), `sync-http-${(0, crypto_1.randomBytes)(16).toString('hex')}.json`);
  const shared = new SharedArrayBuffer(4);
  const state = new Int32Array(shared);
  const workerCode = `
    'use strict';
    const { workerData } = require('worker_threads');
    const http = require('http');
    const https = require('https');
    const fs = require('fs');
    const { URL } = require('url');

    function writeResult(obj) {
      try {
        fs.writeFileSync(workerData.outFile, JSON.stringify(obj), 'utf8');
      } finally {
        const state = new Int32Array(workerData.shared);
        Atomics.store(state, 0, 1);
        Atomics.notify(state, 0);
      }
    }

    try {
      const u = new URL(workerData.url);
      const mod = u.protocol === 'https:' ? https : http;
      const requestBody = workerData.body ?? '';
      const req = mod.request(workerData.url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(requestBody),
          'Connection': 'keep-alive'
        },
        timeout: workerData.timeout,
      }, (res) => {
        res.setEncoding('utf8');
        let responseData = '';
        res.on('data', (chunk) => { responseData += chunk; });
        res.on('end', () => writeResult({ ok: true, data: responseData }));
        res.on('error', (err) => writeResult({ ok: false, error: err && err.message ? err.message : String(err) }));
      });
      req.on('error', (err) => writeResult({ ok: false, error: err && err.message ? err.message : String(err) }));
      req.on('timeout', () => req.destroy(new Error('request timeout')));
      req.end(requestBody);
    } catch (err) {
      writeResult({ ok: false, error: err && err.message ? err.message : String(err) });
    }
  `;
  const worker = new worker_threads_1.Worker(workerCode, {
    eval: true,
    workerData: {
      url,
      body,
      timeout,
      outFile: tmpFile,
      shared
    }
  });
  try {
    const waitMs = Math.max(1, timeout + 1500);
    const waitResult = Atomics.wait(state, 0, 0, waitMs);
    if (waitResult === 'timed-out') {
      worker.terminate().catch(() => undefined);
      throw new Error(`HTTP request failed: timeout after ${waitMs}ms`);
    }
    const parsed = JSON.parse(fs.readFileSync(tmpFile, 'utf8'));
    if (!(parsed === null || parsed === void 0 ? void 0 : parsed.ok)) {
      throw new Error((parsed === null || parsed === void 0 ? void 0 : parsed.error) || 'HTTP request failed');
    }
    return (_a = parsed.data) !== null && _a !== void 0 ? _a : '';
  } finally {
    worker.terminate().catch(() => undefined);
    try {
      fs.unlinkSync(tmpFile);
    } catch {}
  }
}
//# sourceMappingURL=http.util.js.map