import { stringify } from "querystring";
import { z } from "zod";
import { m as WEBAPP_URL, l as logger, p as prisma } from "./index-Cw1zbw54.js";
import { d as defaultHandler } from "./defaultHandler-yvm7aMmf.js";
import { d as defaultResponder } from "./defaultResponder-s4VQhYfH.js";
import { g as getAppKeysFromSlug } from "./getAppKeysFromSlug-S62aYXii.js";
import { e as encodeOAuthState } from "./encodeOAuthState-ADe35aHB.js";
import { g as getSafeRedirectUrl } from "./getSafeRedirectUrl-hxmyPhEi.js";
import { g as getInstalledAppPath } from "./getInstalledAppPath-6P3H-VDB.js";
import { d as decodeOAuthState } from "./decodeOAuthState-KhwGAxqw.js";
import { a5 as getLocation } from "./email-manager-ED8hrFPG.js";
import { r as refreshOAuthTokens } from "./refreshOAuthTokens-k3EbNmEo.js";
import { m } from "./_metadata-jK-G0Ayz.js";
const LARK_HOST = "open.larksuite.com";
const getAppKeys = () => getAppKeysFromSlug("lark-calendar");
const isExpired = (expiryDate) => !expiryDate || expiryDate < Math.round(Number(/* @__PURE__ */ new Date()) / 1e3);
async function handleLarkError(response, log2) {
  const data = await response.json();
  if (!response.ok || data.code !== 0) {
    log2.error("lark error with error: ", data, ", logid is:", response.headers.get("X-Tt-Logid"));
    log2.debug("lark request with data", data);
    throw data;
  }
  log2.info("lark request with logid:", response.headers.get("X-Tt-Logid"));
  log2.debug("lark request with data", data);
  return data;
}
const larkKeysSchema$1 = z.object({
  app_id: z.string(),
  app_secret: z.string()
});
async function getHandler$1(req) {
  const appKeys = await getAppKeysFromSlug("lark-calendar");
  const { app_secret, app_id } = larkKeysSchema$1.parse(appKeys);
  const state = encodeOAuthState(req);
  const params = {
    app_id,
    redirect_uri: `${WEBAPP_URL}/api/integrations/larkcalendar/callback`,
    state
  };
  const query = stringify(params);
  const url = `https://${LARK_HOST}/open-apis/authen/v1/index?${query}`;
  fetch(`https://${LARK_HOST}/open-apis/auth/v3/app_ticket/resend`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json; charset=utf-8"
    },
    body: JSON.stringify({
      app_id,
      app_secret
    })
  });
  return { url };
}
const add = defaultHandler({
  GET: Promise.resolve({ default: defaultResponder(getHandler$1) })
});
const log$3 = logger.getSubLogger({ prefix: [`[[LarkAppCredential]`] });
function makePoolingPromise(promiseCreator, times = 24, delay = 5 * 1e3) {
  return new Promise((resolve, reject) => {
    promiseCreator().then(resolve).catch((err) => {
      if (times <= 0) {
        reject(err);
        return;
      }
      setTimeout(() => {
        makePoolingPromise(promiseCreator, times - 1, delay).then(resolve).catch(reject);
      }, delay);
    });
  });
}
const appKeysSchema = z.object({
  app_id: z.string().min(1),
  app_secret: z.string().min(1),
  app_access_token: z.string().optional(),
  app_ticket: z.string().optional(),
  expire_date: z.number().optional(),
  open_verification_token: z.string().min(1)
});
const getValidAppKeys = async () => {
  const appKeys = await getAppKeys();
  const validAppKeys = appKeysSchema.parse(appKeys);
  return validAppKeys;
};
const getAppTicketFromKeys = async () => {
  const appKeys = await getValidAppKeys();
  const appTicketNew = appKeys?.app_ticket;
  if (appTicketNew) {
    return appTicketNew;
  }
  throw Error("lark appTicketNew not found in getAppTicketFromKeys");
};
const getAppTicket = async () => {
  log$3.debug("get app ticket invoked");
  const appKeys = await getValidAppKeys();
  if (typeof appKeys.app_ticket === "string" && appKeys.app_ticket !== "") {
    log$3.debug("has app ticket", appKeys.app_ticket);
    return appKeys.app_ticket;
  }
  log$3.info("Invoke app-ticket resend", appKeys.app_ticket);
  fetch(`https://${LARK_HOST}/open-apis/auth/v3/app_ticket/resend`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      app_id: appKeys.app_id,
      app_secret: appKeys.app_secret
    })
  });
  const appTicketNew = await makePoolingPromise(getAppTicketFromKeys);
  if (appTicketNew) {
    log$3.debug("has new app ticket", appTicketNew);
    return appTicketNew;
  }
  log$3.error("app ticket not found");
  throw new Error("No app ticket found");
};
const getAppAccessToken = async () => {
  log$3.debug("get app access token invoked");
  const appKeys = await getValidAppKeys();
  const appAccessToken = appKeys.app_access_token;
  const expireDate = appKeys.expire_date;
  if (appAccessToken && expireDate && !isExpired(expireDate)) {
    log$3.debug("get app access token not expired");
    return appAccessToken;
  }
  const appTicket = await getAppTicket();
  const fetchAppAccessToken = (app_ticket) => fetch(`https://${LARK_HOST}/open-apis/auth/v3/app_access_token`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      app_id: appKeys.app_id,
      app_secret: appKeys.app_secret,
      app_ticket
    })
  });
  const resp = await fetchAppAccessToken(appTicket);
  const data = await resp.json();
  if (!resp.ok || data.code !== 0) {
    logger.error("lark error with error: ", data, ", logid is:", resp.headers.get("X-Tt-Logid"));
    if (data.code === 10012) {
      await prisma.app.update({
        where: { slug: "lark-calendar" },
        data: { keys: { ...appKeys, app_ticket: "" } }
      });
      throw new Error("app_ticket invalid, please try again");
    }
  }
  const newAppAccessToken = data.app_access_token;
  const newExpireDate = Math.round(Number(/* @__PURE__ */ new Date()) / 1e3 + data.expire);
  await prisma.app.update({
    where: { slug: "lark-calendar" },
    data: {
      keys: {
        ...appKeys,
        app_access_token: newAppAccessToken,
        expire_date: newExpireDate
      }
    }
  });
  return newAppAccessToken;
};
const log$2 = logger.getSubLogger({ prefix: [`[[lark/api/callback]`] });
const callbackQuerySchema = z.object({
  code: z.string().min(1)
});
async function getHandler(req, res) {
  const { code } = callbackQuerySchema.parse(req.query);
  const state = decodeOAuthState(req);
  try {
    const appAccessToken = await getAppAccessToken();
    const response = await fetch(`https://${LARK_HOST}/open-apis/authen/v1/access_token`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${appAccessToken}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        grant_type: "authorization_code",
        code
      })
    });
    const responseBody = await response.json();
    if (!response.ok || responseBody.code !== 0) {
      log$2.error("get user_access_token failed with none 0 code", responseBody);
      return res.redirect(`/apps/installed?error=${JSON.stringify(responseBody)}`);
    }
    const key = {
      expiry_date: Math.round(+/* @__PURE__ */ new Date() / 1e3 + responseBody.data.expires_in),
      access_token: responseBody.data.access_token,
      refresh_token: responseBody.data.refresh_token,
      refresh_expires_date: Math.round(+/* @__PURE__ */ new Date() / 1e3 + responseBody.data.refresh_expires_in)
    };
    const currentCredential = await prisma.credential.findFirst({
      where: {
        userId: req.session?.user.id,
        type: "lark_calendar"
      }
    });
    if (!currentCredential) {
      await prisma.credential.create({
        data: {
          type: "lark_calendar",
          key,
          userId: req.session?.user.id,
          appId: "lark-calendar"
        }
      });
    } else {
      await prisma.credential.update({
        data: {
          type: "lark_calendar",
          key,
          userId: req.session?.user.id,
          appId: "lark-calendar"
        },
        where: {
          id: currentCredential.id
        }
      });
    }
    const primaryCalendarResponse = await fetch(
      `https://${LARK_HOST}/open-apis/calendar/v4/calendars/primary`,
      {
        method: "GET",
        headers: {
          Authorization: `Bearer ${key.access_token}`,
          "Content-Type": "application/json"
        }
      }
    );
    if (primaryCalendarResponse.status === 200) {
      const primaryCalendar = await primaryCalendarResponse.json();
      if (primaryCalendar.data.calendars.calendar.calendar_id && req.session?.user?.id) {
        await prisma.selectedCalendar.create({
          data: {
            userId: req.session?.user.id,
            integration: "lark_calendar",
            externalId: primaryCalendar.data.calendars.calendar.calendar_id,
            credentialId: currentCredential?.id
          }
        });
      }
    }
    res.redirect(
      getSafeRedirectUrl(state?.returnTo) ?? getInstalledAppPath({ variant: "calendar", slug: "lark-calendar" })
    );
  } catch (error) {
    log$2.error("handle callback error", error);
    res.redirect(state?.returnTo ?? "/apps/installed");
  }
}
const callback = defaultHandler({
  GET: Promise.resolve({ default: defaultResponder(getHandler) })
});
const log$1 = logger.getSubLogger({ prefix: [`[[LarkTenantCredential]`] });
const msg = {
  en_us: {
    title: "Welcome to Cal.com!",
    content: [
      [
        {
          tag: "text",
          text: "Cal.com is an open source scheduling infrastructure."
        }
      ],
      [
        {
          tag: "text",
          text: 'It allows users to send a unique "cal.com" URL that allows anyone to create bookings on their calendars'
        }
      ],
      [
        {
          tag: "text",
          text: ""
        }
      ],
      [
        {
          tag: "text",
          text: "Get started"
        }
      ],
      [
        {
          tag: "text",
          text: "1. Visit https://cal.com and sign up for an account."
        }
      ],
      [
        {
          tag: "text",
          text: '2. Then go to "Apps" in Cal -> install '
        },
        {
          tag: "a",
          text: '"Larksuite Calendar"',
          href: "https://www.larksuite.com/hc/articles/057527702350"
        },
        {
          tag: "text",
          text: " -> sign-in via Lark"
        }
      ],
      [
        {
          tag: "text",
          text: "3. Done. Create your Event Types and share your booking links with external participants!"
        }
      ],
      [
        {
          tag: "text",
          text: ""
        }
      ],
      [
        {
          tag: "text",
          text: "Do not hesitate to reach out to our agents if you need any assistance."
        }
      ],
      [
        {
          tag: "a",
          text: "Get Help",
          href: "https://applink.larksuite.com/client/helpdesk/open?id=6650327445582905610"
        }
      ]
    ]
  }
};
async function getTenantAccessTokenByTenantKey(tenantKey) {
  try {
    const appAccessToken = await getAppAccessToken();
    const resp = await fetch(`https://${LARK_HOST}/open-apis/auth/v3/tenant_access_token`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        app_access_token: appAccessToken,
        tenant_key: tenantKey
      })
    });
    const data = await resp.json();
    return data.tenant_access_token;
  } catch (error) {
    log$1.error(error);
    throw error;
  }
}
async function sendPostMsg(tenantKey, senderOpenId, message = JSON.stringify(msg)) {
  const tenantAccessToken = await getTenantAccessTokenByTenantKey(tenantKey);
  const response = await fetch(`https://${LARK_HOST}/open-apis/im/v1/messages?receive_id_type=open_id`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${tenantAccessToken}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      receive_id: senderOpenId,
      content: message,
      msg_type: "post"
    })
  });
  const responseBody = await response.json();
  log$1.debug("send message success", responseBody);
  return responseBody;
}
const log = logger.getSubLogger({ prefix: [`[lark/api/events]`] });
const larkKeysSchema = z.object({
  open_verification_token: z.string()
});
const appTicketEventsReqSchema = z.object({
  body: z.object({
    event: z.object({
      app_ticket: z.string().min(1)
    })
  })
});
const imMessageReceivedEventsReqSchema = z.object({
  body: z.object({
    header: z.object({
      tenant_key: z.string().min(1)
    }),
    event: z.object({
      sender: z.object({
        sender_id: z.object({
          open_id: z.string().min(1)
        })
      })
    })
  })
});
const p2pChatCreateEventsReqSchema = z.object({
  body: z.object({
    tenant_key: z.string().min(1),
    event: z.object({
      user: z.object({
        open_id: z.string().min(1)
      })
    })
  })
});
async function postHandler(req, res) {
  log.debug("receive events", req.body);
  const appKeys = await getAppKeys();
  const { open_verification_token } = larkKeysSchema.parse(appKeys);
  if (req.body.type === "url_verification" && req.body.token === open_verification_token) {
    log.debug("update token", req.body);
    return res.status(200).json({ challenge: req.body.challenge });
  }
  if (req.body.event?.type === "app_ticket" && open_verification_token === req.body.token) {
    const {
      body: {
        event: { app_ticket: appTicket }
      }
    } = appTicketEventsReqSchema.parse(req);
    await prisma.app.update({
      where: { slug: "lark-calendar" },
      data: {
        keys: {
          ...appKeys,
          app_ticket: appTicket
        }
      }
    });
    return res.status(200).json({ code: 0, msg: "success" });
  }
  if (req.body.header?.event_type === "im.message.receive_v1") {
    const {
      body: {
        header: { tenant_key: tenantKey },
        event: {
          sender: {
            sender_id: { open_id: senderOpenId }
          }
        }
      }
    } = imMessageReceivedEventsReqSchema.parse(req);
    sendPostMsg(tenantKey, senderOpenId);
    return res.status(200).json({ code: 0, msg: "success" });
  }
  if (req.body.event?.type === "p2p_chat_create") {
    const {
      body: {
        tenant_key: tenantKey,
        event: {
          user: { open_id: senderOpenId }
        }
      }
    } = p2pChatCreateEventsReqSchema.parse(req);
    sendPostMsg(tenantKey, senderOpenId);
    return res.status(200).json({ code: 0, msg: "success" });
  }
}
const events = defaultHandler({
  POST: Promise.resolve({ default: defaultResponder(postHandler) })
});
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add,
  callback,
  events
}, Symbol.toStringTag, { value: "Module" }));
function parseEventTime2Timestamp(eventTime) {
  return String(+new Date(eventTime) / 1e3);
}
class LarkCalendarService {
  constructor(credential) {
    this.url = `https://${LARK_HOST}/open-apis`;
    this.integrationName = "";
    this.larkAuth = (credential2) => {
      const larkAuthCredentials = credential2.key;
      return {
        getToken: () => !isExpired(larkAuthCredentials.expiry_date) ? Promise.resolve(larkAuthCredentials.access_token) : this.refreshAccessToken(credential2)
      };
    };
    this.refreshAccessToken = async (credential2) => {
      const larkAuthCredentials = credential2.key;
      const refreshExpireDate = larkAuthCredentials.refresh_expires_date;
      const refreshToken = larkAuthCredentials.refresh_token;
      if (isExpired(refreshExpireDate) || !refreshToken) {
        await prisma.credential.delete({ where: { id: credential2.id } });
        throw new Error("Lark Calendar refresh token expired");
      }
      try {
        const appAccessToken = await getAppAccessToken();
        const resp = await refreshOAuthTokens(
          async () => await fetch(`${this.url}/authen/v1/refresh_access_token`, {
            method: "POST",
            headers: {
              Authorization: `Bearer ${appAccessToken}`,
              "Content-Type": "application/json; charset=utf-8"
            },
            body: JSON.stringify({
              grant_type: "refresh_token",
              refresh_token: refreshToken
            })
          }),
          "lark-calendar",
          credential2.userId
        );
        const data = await handleLarkError(resp, this.log);
        this.log.debug(
          "LarkCalendarService refreshAccessToken data refresh_expires_in",
          data.data.refresh_expires_in,
          "and access token expire in",
          data.data.expires_in
        );
        const newLarkAuthCredentials = {
          refresh_token: data.data.refresh_token,
          refresh_expires_date: Math.round(+/* @__PURE__ */ new Date() / 1e3 + data.data.refresh_expires_in),
          access_token: data.data.access_token,
          expiry_date: Math.round(+/* @__PURE__ */ new Date() / 1e3 + data.data.expires_in)
        };
        await prisma.credential.update({
          where: {
            id: credential2.id
          },
          data: {
            key: newLarkAuthCredentials
          }
        });
        return newLarkAuthCredentials.access_token;
      } catch (error) {
        this.log.error("LarkCalendarService refreshAccessToken error", error);
        throw error;
      }
    };
    this.fetcher = async (endpoint, init) => {
      let accessToken = "";
      try {
        accessToken = await this.auth.getToken();
      } catch (error) {
        throw new Error("get access token error");
      }
      return fetch(`${this.url}${endpoint}`, {
        method: "GET",
        headers: {
          Authorization: `Bearer ${accessToken}`,
          "Content-Type": "application/json",
          ...init?.headers
        },
        ...init
      });
    };
    this.createAttendees = async (event, eventId, credentialId) => {
      const mainHostDestinationCalendar = event.destinationCalendar ? event.destinationCalendar.find((cal) => cal.credentialId === credentialId) ?? event.destinationCalendar[0] : void 0;
      const calendarId = mainHostDestinationCalendar?.externalId;
      if (!calendarId) {
        this.log.error("no calendar id provided in createAttendees");
        throw new Error("no calendar id provided in createAttendees");
      }
      const attendeeResponse = await this.fetcher(
        `/calendar/v4/calendars/${calendarId}/events/${eventId}/attendees/create_attendees`,
        {
          method: "POST",
          body: JSON.stringify({
            attendees: this.translateAttendees(event),
            need_notification: false
          })
        }
      );
      return handleLarkError(attendeeResponse, this.log);
    };
    this.listCalendars = async () => {
      try {
        const resp = await this.fetcher(`/calendar/v4/calendars`);
        const data = await handleLarkError(resp, this.log);
        const result = data.data.calendar_list.filter((cal) => {
          if (cal.type !== "primary" && cal.type !== "shared") {
            return false;
          }
          if (cal.permissions === "private") {
            return false;
          }
          if (cal.role === "owner" || cal.role === "writer") {
            return true;
          }
          return false;
        }).map((cal) => {
          const calendar = {
            externalId: cal.calendar_id ?? "No Id",
            integration: this.integrationName,
            name: cal.summary_alias || cal.summary || "No calendar name",
            primary: cal.type === "primary",
            email: cal.calendar_id ?? ""
          };
          return calendar;
        });
        if (result.some((cal) => !!cal.primary)) {
          return result;
        }
        const respPrimary = await this.fetcher(`/calendar/v4/calendars/primary`, {
          method: "POST"
        });
        const dataPrimary = await handleLarkError(respPrimary, this.log);
        return dataPrimary.data.calendars.map((item) => {
          const cal = item.calendar;
          const calendar = {
            externalId: cal.calendar_id ?? "No Id",
            integration: this.integrationName,
            name: cal.summary_alias || cal.summary || "No calendar name",
            primary: cal.type === "primary",
            email: cal.calendar_id ?? ""
          };
          return calendar;
        });
      } catch (err) {
        this.log.error("There was an error contacting lark calendar service: ", err);
        throw err;
      }
    };
    this.translateEvent = (event) => {
      const larkEvent = {
        summary: event.title,
        description: event.calendarDescription,
        start_time: {
          timestamp: parseEventTime2Timestamp(event.startTime),
          timezone: event.organizer.timeZone
        },
        end_time: {
          timestamp: parseEventTime2Timestamp(event.endTime),
          timezone: event.organizer.timeZone
        },
        attendee_ability: "none",
        free_busy_status: "busy",
        reminders: [
          {
            minutes: 5
          }
        ]
      };
      if (event.location) {
        larkEvent.location = { name: getLocation(event) };
      }
      return larkEvent;
    };
    this.translateAttendees = (event) => {
      const attendeeArray = [];
      event.attendees.filter((att) => att.email).forEach((att) => {
        const attendee = {
          type: "third_party",
          is_optional: false,
          third_party_email: att.email
        };
        attendeeArray.push(attendee);
      });
      event.team?.members.forEach((member) => {
        if (member.email !== this.credential.user?.email) {
          const attendee = {
            type: "third_party",
            is_optional: false,
            third_party_email: member.email
          };
          attendeeArray.push(attendee);
        }
      });
      return attendeeArray;
    };
    this.integrationName = "lark_calendar";
    this.auth = this.larkAuth(credential);
    this.log = logger.getSubLogger({ prefix: [`[[lib] ${this.integrationName}`] });
    this.credential = credential;
  }
  async createEvent(event, credentialId) {
    let eventId = "";
    let eventRespData;
    const mainHostDestinationCalendar = event.destinationCalendar ? event.destinationCalendar.find((cal) => cal.credentialId === this.credential.id) ?? event.destinationCalendar[0] : void 0;
    const calendarId = mainHostDestinationCalendar?.externalId;
    if (!calendarId) {
      throw new Error("no calendar id");
    }
    try {
      const eventResponse = await this.fetcher(`/calendar/v4/calendars/${calendarId}/events/create_event`, {
        method: "POST",
        body: JSON.stringify(this.translateEvent(event))
      });
      eventRespData = await handleLarkError(eventResponse, this.log);
      eventId = eventRespData.data.event.event_id;
    } catch (error) {
      this.log.error(error);
      throw error;
    }
    try {
      await this.createAttendees(event, eventId, credentialId);
      return {
        ...eventRespData,
        uid: eventRespData.data.event.event_id,
        id: eventRespData.data.event.event_id,
        type: "lark_calendar",
        password: "",
        url: "",
        additionalInfo: {}
      };
    } catch (error) {
      this.log.error(error);
      await this.deleteEvent(eventId, event, calendarId);
      throw error;
    }
  }
  /**
   * @param uid
   * @param event
   * @returns
   */
  async updateEvent(uid, event, externalCalendarId) {
    const eventId = uid;
    let eventRespData;
    const mainHostDestinationCalendar = event.destinationCalendar?.find(
      (cal) => cal.externalId === externalCalendarId
    );
    const calendarId = externalCalendarId || mainHostDestinationCalendar?.externalId;
    if (!calendarId) {
      this.log.error("no calendar id provided in updateEvent");
      throw new Error("no calendar id provided in updateEvent");
    }
    try {
      const eventResponse = await this.fetcher(
        `/calendar/v4/calendars/${calendarId}/events/${eventId}/patch_event`,
        {
          method: "PATCH",
          body: JSON.stringify(this.translateEvent(event))
        }
      );
      eventRespData = await handleLarkError(eventResponse, this.log);
    } catch (error) {
      this.log.error(error);
      throw error;
    }
    try {
      return {
        ...eventRespData,
        uid: eventRespData.data.event.event_id,
        id: eventRespData.data.event.event_id,
        type: "lark_calendar",
        password: "",
        url: "",
        additionalInfo: {}
      };
    } catch (error) {
      this.log.error(error);
      await this.deleteEvent(eventId, event);
      throw error;
    }
  }
  /**
   * @param uid
   * @param event
   * @returns
   */
  async deleteEvent(uid, event, externalCalendarId) {
    const mainHostDestinationCalendar = event.destinationCalendar?.find(
      (cal) => cal.externalId === externalCalendarId
    );
    const calendarId = externalCalendarId || mainHostDestinationCalendar?.externalId;
    if (!calendarId) {
      this.log.error("no calendar id provided in deleteEvent");
      throw new Error("no calendar id provided in deleteEvent");
    }
    try {
      const response = await this.fetcher(`/calendar/v4/calendars/${calendarId}/events/${uid}`, {
        method: "DELETE"
      });
      await handleLarkError(response, this.log);
    } catch (error) {
      this.log.error(error);
      throw error;
    }
  }
  async getAvailability(dateFrom, dateTo, selectedCalendars) {
    const selectedCalendarIds = selectedCalendars.filter((e) => e.integration === this.integrationName).map((e) => e.externalId).filter(Boolean);
    if (selectedCalendarIds.length === 0 && selectedCalendars.length > 0) {
      return Promise.resolve([]);
    }
    try {
      let queryIds = selectedCalendarIds;
      if (queryIds.length === 0) {
        queryIds = (await this.listCalendars()).map((e) => e.externalId).filter(Boolean) || [];
        if (queryIds.length === 0) {
          return Promise.resolve([]);
        }
      }
      const response = await this.fetcher(`/calendar/v4/freebusy/batch_get`, {
        method: "POST",
        body: JSON.stringify({
          time_min: dateFrom,
          time_max: dateTo,
          calendar_ids: queryIds
        })
      });
      const data = await handleLarkError(response, this.log);
      const busyData = data.data.freebusy_list?.reduce((acc, cur) => {
        acc.push({
          start: cur.start_time,
          end: cur.end_time
        });
        return acc;
      }, []) || [];
      return busyData;
    } catch (error) {
      this.log.error(error);
      return [];
    }
  }
}
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  CalendarService: LarkCalendarService
}, Symbol.toStringTag, { value: "Module" }));
export {
  index$1 as api,
  index as lib,
  m as metadata
};
