'use strict';

var fs2 = require('fs');
var path = require('path');
var module$1 = require('module');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var fs2__default = /*#__PURE__*/_interopDefault(fs2);
var path__default = /*#__PURE__*/_interopDefault(path);

// src/features/gen-html/infrastructure/local-server/lock.ts
var LOCAL_SERVER_LOCK_STALE_MS = 12e4;
new Set(
  module$1.builtinModules.flatMap((moduleName) => [moduleName, moduleName.replace(/^node:/, ""), `node:${moduleName.replace(/^node:/, "")}`])
);
function getLocalServerPaths(paths) {
  const directoryPath = path__default.default.join(paths.baseDir, "local-server");
  const generatedDirectoryPath = path__default.default.join(directoryPath, "generated");
  const multipleDirectoryPath = path__default.default.join(directoryPath, "multiple");
  const storybookConfigDirectoryPath = path__default.default.join(directoryPath, ".storybook");
  return {
    directoryPath,
    generatedDirectoryPath,
    generatedRegistryPath: path__default.default.join(directoryPath, "generated-registry.json"),
    multipleDirectoryPath,
    logPath: path__default.default.join(directoryPath, "server.log"),
    packageJsonPath: path__default.default.join(directoryPath, "package.json"),
    packageCustomJsonPath: path__default.default.join(directoryPath, "package-custom.json"),
    previewTargetPath: path__default.default.join(directoryPath, "preview-target.json"),
    refreshLockPath: path__default.default.join(directoryPath, "refresh.lock"),
    scssModuleDeclarationPath: path__default.default.join(directoryPath, "scss.d.ts"),
    serverLockPath: path__default.default.join(directoryPath, "server.lock"),
    statePath: path__default.default.join(directoryPath, "server-state.json"),
    storybookConfigDirectoryPath,
    storybookMainConfigPath: path__default.default.join(storybookConfigDirectoryPath, "main.ts"),
    storybookManagerConfigPath: path__default.default.join(storybookConfigDirectoryPath, "manager.tsx"),
    storybookPreviewConfigPath: path__default.default.join(storybookConfigDirectoryPath, "preview.ts"),
    tsconfigPath: path__default.default.join(directoryPath, "tsconfig.json")
  };
}

// src/features/gen-html/infrastructure/local-server/lock.ts
function wait(delayMs) {
  return new Promise((resolve) => {
    setTimeout(resolve, delayMs);
  });
}
function isStaleLock(lockPath, staleMs) {
  try {
    const stat = fs2__default.default.statSync(lockPath);
    return Date.now() - stat.mtimeMs > staleMs;
  } catch {
    return false;
  }
}
function tryAcquireFileLock(options) {
  const record = {
    acquiredAt: (/* @__PURE__ */ new Date()).toISOString(),
    owner: options.owner,
    pid: process.pid
  };
  fs2__default.default.mkdirSync(path__default.default.dirname(options.lockPath), { recursive: true });
  try {
    const fileDescriptor = fs2__default.default.openSync(options.lockPath, "wx");
    fs2__default.default.writeFileSync(fileDescriptor, `${JSON.stringify(record, null, 2)}
`, "utf8");
    fs2__default.default.closeSync(fileDescriptor);
    options.trace("local-server:lock:acquired", `${options.owner} ${options.lockPath}`);
    return true;
  } catch {
    return false;
  }
}
async function withFileLock(options, task) {
  const staleMs = options.staleMs ?? LOCAL_SERVER_LOCK_STALE_MS;
  const timeoutMs = options.timeoutMs ?? staleMs;
  const startedAt = Date.now();
  while (!tryAcquireFileLock(options)) {
    if (isStaleLock(options.lockPath, staleMs)) {
      options.trace("local-server:lock:stale:remove", `${options.owner} ${options.lockPath}`);
      fs2__default.default.rmSync(options.lockPath, { force: true });
      continue;
    }
    if (Date.now() - startedAt > timeoutMs) {
      throw new Error(`local-server \uB77D \uD68D\uB4DD \uC2DC\uAC04\uC774 \uCD08\uACFC\uB418\uC5C8\uC2B5\uB2C8\uB2E4. owner=${options.owner} lock=${options.lockPath}`);
    }
    options.trace("local-server:lock:wait", `${options.owner} ${options.lockPath}`);
    await wait(100);
  }
  try {
    return await task();
  } finally {
    fs2__default.default.rmSync(options.lockPath, { force: true });
    options.trace("local-server:lock:released", `${options.owner} ${options.lockPath}`);
  }
}
function withLocalServerLock(paths, trace, owner, task) {
  return withFileLock(
    {
      lockPath: getLocalServerPaths(paths).serverLockPath,
      owner,
      trace
    },
    task
  );
}
function withLocalServerRefreshLock(paths, trace, owner, task) {
  return withFileLock(
    {
      lockPath: getLocalServerPaths(paths).refreshLockPath,
      owner,
      trace
    },
    task
  );
}

exports.withFileLock = withFileLock;
exports.withLocalServerLock = withLocalServerLock;
exports.withLocalServerRefreshLock = withLocalServerRefreshLock;
