"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }


var _chunkEGTDJ4PLjs = require('./chunk-EGTDJ4PL.js');

// ../blocks/src/system/runtime/bindings.ts
var shouldLogWarnings = isNonProductionEnv();
function resolveParamsBindings(input, vm, meta) {
  if (input === null || typeof input !== "object") return input;
  if (Array.isArray(input)) return input.map((v) => resolveParamsBindings(v, vm, meta));
  const maybeBind = input.$bind;
  if (maybeBind && typeof maybeBind === "object") {
    try {
      const binding = _chunkEGTDJ4PLjs.bindingSchema.parse(maybeBind);
      const value = resolveBinding(binding.from, vm);
      if (value === void 0 || value === null) {
        return binding.fallback;
      }
      return value;
    } catch (err) {
      if (shouldLogWarnings) {
        console.warn(
          `bindings: failed to parse loader param binding for block "${_nullishCoalesce(_optionalChain([meta, 'optionalAccess', _ => _.blockKind]), () => ( "unknown"))}"`,
          err
        );
      }
      return void 0;
    }
  }
  const out = {};
  for (const [k, v] of Object.entries(input)) {
    out[k] = resolveParamsBindings(v, vm, meta);
  }
  return out;
}
function resolveBinding(path, vm) {
  const segments = splitPath(path);
  if (!segments.length) return void 0;
  const [first, ...rest] = segments;
  let source = vm;
  if (first === "$root") {
    source = vm;
    return readFromSource(source, [first, ...rest]);
  }
  if (first === "content") {
    source = vm.content;
    return readFromSource(source, rest);
  }
  const contentResult = readFromSource(vm.content, segments);
  if (contentResult !== void 0) {
    return contentResult;
  }
  return readFromSource(vm, segments);
}
function splitPath(path) {
  const PATH_SEPARATOR_REGEX = /\./g;
  const BRACKET_ACCESS_REGEX = /\[(?<token>[^\]]+)\]/g;
  const segments = [];
  const parts = path.split(PATH_SEPARATOR_REGEX);
  for (const raw of parts) {
    if (!raw) continue;
    const baseMatch = raw.match(/^([^\[]+)/);
    if (baseMatch) {
      segments.push(baseMatch[1]);
    }
    const bracketMatches = raw.matchAll(BRACKET_ACCESS_REGEX);
    for (const match of bracketMatches) {
      const token = _nullishCoalesce(_optionalChain([match, 'access', _2 => _2.groups, 'optionalAccess', _3 => _3.token]), () => ( ""));
      if (token.startsWith('"') || token.startsWith("'")) {
        segments.push(token.slice(1, -1));
      } else if (/^\d+$/.test(token)) {
        segments.push(Number(token));
      } else {
        segments.push(token);
      }
    }
    if (!baseMatch && !raw.includes("[")) {
      segments.push(raw);
    }
  }
  return segments;
}
function readFromSource(source, segments) {
  return segments.reduce((current, segment) => {
    if (current === void 0 || current === null) return void 0;
    if (typeof segment === "number") {
      if (Array.isArray(current)) return current[segment];
      return void 0;
    }
    if (typeof current === "object" && current !== null && segment in current) {
      return current[segment];
    }
    return void 0;
  }, source);
}
function isNonProductionEnv() {
  if (typeof globalThis === "undefined") {
    return true;
  }
  const maybeProcess = globalThis.process;
  const nodeEnv = _optionalChain([maybeProcess, 'optionalAccess', _4 => _4.env, 'optionalAccess', _5 => _5.NODE_ENV]);
  return nodeEnv !== "production";
}

// ../blocks/src/system/data/utils.ts
function normalizeDataLoaders(def) {
  if (!_optionalChain([def, 'optionalAccess', _6 => _6.dataLoaders])) {
    return [];
  }
  return Object.entries(def.dataLoaders).map(([key, loader]) => ({ key, loader }));
}
function normalizeContent(block) {
  const source = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(block.draftContent, () => ( block.content)), () => ( block.publishedContent)), () => ( {}));
  if (!isRecord(source)) return {};
  if ("data" in source) {
    const data = source.data;
    if (isRecord(data)) {
      return data;
    }
    if (data === null || data === void 0) {
      return {};
    }
  }
  return source;
}
function normalizeParams(input) {
  if (!input || typeof input !== "object") return {};
  const entries = Object.entries(input).map(([key, value]) => [
    key,
    coerceToString(value)
  ]);
  return Object.fromEntries(entries);
}
function coerceToString(value) {
  if (value === null || value === void 0) return "";
  if (Array.isArray(value)) return value.map(coerceToString).join(",");
  return String(value);
}
function coercePayload(payload) {
  if (payload && typeof payload === "object" && !Array.isArray(payload)) {
    const record = payload;
    if ("data" in record && typeof record.data !== "function") return record.data;
    if ("form" in record && typeof record.form !== "function") return record.form;
    if ("entries" in record && typeof record.entries !== "function") return record.entries;
    if ("services" in record && typeof record.services !== "function") return record.services;
  }
  return payload;
}
function isRecord(value) {
  return typeof value === "object" && value !== null;
}

// ../blocks/src/system/data/prefetchBlockData.ts
async function prefetchBlockData(page, context, options) {
  const { apiClient, isValidEndpoint, onError, getCustomBlockLoaders } = options;
  const results = {};
  const tasks = [];
  for (const block of page.blocks) {
    const blockId = block.id;
    if (!blockId) continue;
    let loaders;
    const def = _chunkEGTDJ4PLjs.getBlockDefinition.call(void 0, block.kind);
    if (def) {
      loaders = normalizeDataLoaders(def);
    } else if (getCustomBlockLoaders) {
      const customLoaders = getCustomBlockLoaders(block.kind);
      loaders = customLoaders ? Object.entries(customLoaders).map(([key, loader]) => ({ key, loader })) : [];
    } else {
      loaders = [];
    }
    if (loaders.length === 0) continue;
    const root = {
      siteId: context.siteId,
      pageId: context.pageId,
      previewStage: context.previewStage
    };
    const normalizedContent = normalizeContent(block);
    const vm = { content: normalizedContent, $root: root };
    for (const { key, loader } of loaders) {
      if (loader.mode === "client") {
        continue;
      }
      const rawParams = resolveParamsBindings(loader.params, vm, {
        blockKind: block.kind
      });
      const params = normalizeParams(rawParams);
      const endpoint = loader.endpoint;
      if (isValidEndpoint && !isValidEndpoint(endpoint)) {
        continue;
      }
      tasks.push(
        (async () => {
          try {
            const payload = await apiClient({ endpoint, params });
            const data = coercePayload(payload);
            if (!results[blockId]) {
              results[blockId] = {};
            }
            results[blockId][key] = data;
          } catch (error) {
            if (onError) {
              onError(error, { block: block.kind, loader: key });
            }
          }
        })()
      );
    }
  }
  if (tasks.length > 0) {
    await Promise.all(tasks);
  }
  return results;
}

// src/data/prefetchBlockData.ts
var SUPPORTED_LOADER_ENDPOINTS = [
  "listPublishedEntries",
  "getPublishedEntryPreview",
  "listPublicEvents",
  "getPublicFormById",
  "getPublicBookingServices"
];
async function prefetchBlockData2(page, context, client, options) {
  const { customBlocks } = _nullishCoalesce(options, () => ( {}));
  const customBlockMap = new Map(
    (_nullishCoalesce(customBlocks, () => ( []))).map((block) => [block.id, block])
  );
  return prefetchBlockData(page, context, {
    apiClient: async ({ endpoint, params }) => {
      if (!isSupportedEndpoint(endpoint)) {
        throw new Error(
          `Unsupported loader endpoint: ${endpoint}. SDK only supports: ${SUPPORTED_LOADER_ENDPOINTS.join(", ")}`
        );
      }
      switch (endpoint) {
        case "listPublishedEntries": {
          const { siteId, type, orderBy, limit, stage, mode, entryIds } = _nullishCoalesce(params, () => ( {}));
          if (!siteId || !type) {
            throw new Error("listPublishedEntries requires siteId and type params");
          }
          const parsedLimit = typeof limit === "string" ? Number.parseInt(limit, 10) : typeof limit === "number" ? limit : void 0;
          const order = orderBy === "newest" || orderBy === "oldest" || orderBy === "title" || orderBy === "order" ? orderBy : void 0;
          let parsedEntryIds;
          if (mode === "manual" && Array.isArray(entryIds)) {
            parsedEntryIds = entryIds.map((item) => {
              if (typeof item === "object" && item !== null && "entryId" in item) {
                return item.entryId;
              }
              if (typeof item === "string") {
                return item;
              }
              return null;
            }).filter((id) => id !== null);
          }
          return await client.getEntries({
            siteId,
            contentType: type,
            limit: parsedLimit,
            order,
            preview: stage === "preview",
            // Manual mode - pass entry IDs for hydration
            mode: mode === "manual" ? "manual" : void 0,
            entryIds: parsedEntryIds
          });
        }
        case "getPublishedEntryPreview": {
          const { siteId, type, slug } = _nullishCoalesce(params, () => ( {}));
          if (!siteId || !type || !slug) {
            throw new Error("getPublishedEntryPreview requires siteId, type, and slug params");
          }
          return await client.getEntry({ siteId, contentType: type, slug });
        }
        case "listPublicEvents": {
          const { siteId, limit, from, to, stage } = _nullishCoalesce(params, () => ( {}));
          if (!siteId) {
            throw new Error("listPublicEvents requires siteId param");
          }
          const parsedLimit = typeof limit === "string" ? Number.parseInt(limit, 10) : typeof limit === "number" ? limit : void 0;
          return await client.listPublicEvents({ siteId, limit: parsedLimit, from, to, stage });
        }
        case "getPublicFormById": {
          const { formId } = _nullishCoalesce(params, () => ( {}));
          if (!formId) {
            throw new Error("getPublicFormById requires formId param");
          }
          return await client.getPublicFormById({ formId });
        }
        case "getPublicBookingServices": {
          const { siteId, ids } = _nullishCoalesce(params, () => ( {}));
          if (!siteId) {
            throw new Error("getPublicBookingServices requires siteId param");
          }
          return await client.getPublicBookingServices({ siteId, ids });
        }
        default: {
          const _exhaustive = endpoint;
          throw new Error(`Unhandled endpoint: ${_exhaustive}`);
        }
      }
    },
    isValidEndpoint: isSupportedEndpoint,
    onError: (error, { block, loader }) => {
      console.warn("[prefetchBlockData] failed to prefetch block data", {
        block,
        loader,
        error
      });
    },
    // Provide custom block loader lookup for SDK custom blocks
    getCustomBlockLoaders: (blockKind) => {
      const customBlock = customBlockMap.get(blockKind);
      if (!_optionalChain([customBlock, 'optionalAccess', _7 => _7.dataLoaders])) return void 0;
      const loaders = {};
      for (const [key, loader] of Object.entries(customBlock.dataLoaders)) {
        loaders[key] = {
          endpoint: loader.endpoint,
          params: loader.params,
          mode: loader.mode
        };
      }
      return loaders;
    }
  });
}
function isSupportedEndpoint(endpoint) {
  return SUPPORTED_LOADER_ENDPOINTS.includes(endpoint);
}




exports.SUPPORTED_LOADER_ENDPOINTS = SUPPORTED_LOADER_ENDPOINTS; exports.prefetchBlockData = prefetchBlockData2;
//# sourceMappingURL=chunk-HOY77YBF.js.map