"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { createConnector: () => createConnector, createNeedleFileId: () => createNeedleFileId, deleteConnector: () => deleteConnector, getConnector: () => getConnector, listCollections: () => listCollections, listConnectors: () => listConnectors, publishConnectorRun: () => publishConnectorRun, validateSession: () => validateSession, verifyJwt: () => verifyJwt }); module.exports = __toCommonJS(src_exports); // src/models/api-models.ts var import_zod = require("zod"); var ApiErrorSchema = import_zod.z.object({ error: import_zod.z.object({ message: import_zod.z.string(), data: import_zod.z.unknown().optional() }) }); var UserSchema = import_zod.z.object({ id: import_zod.z.string(), email: import_zod.z.string(), name: import_zod.z.string().optional().nullable(), image_url: import_zod.z.string().optional().nullable(), plan: import_zod.z.string(), confirmed_at: import_zod.z.string().transform((str) => new Date(str)), created_at: import_zod.z.string().transform((str) => new Date(str)) }); var SessionSchema = import_zod.z.object({ id: import_zod.z.string(), expires_at: import_zod.z.string().transform((str) => new Date(str)), fresh: import_zod.z.boolean(), user_id: import_zod.z.string() }); var ValidateSessionResponseSchema = import_zod.z.object({ result: import_zod.z.object({ user: UserSchema.optional().nullable(), session: SessionSchema.optional().nullable() }) }); var FileTypeSchema = import_zod.z.enum([ // google "application/vnd.google-apps.document", "application/vnd.google-apps.presentation", "application/vnd.google-apps.spreadsheet", // open formats "application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // microsoft "application/msword", "application/vnd.ms-excel", "application/vnd.ms-powerpoint", // text "text/csv", "text/html", "text/calendar", "text/plain" ]); var ConnectorSchema = import_zod.z.object({ id: import_zod.z.string(), name: import_zod.z.string(), created_at: import_zod.z.string().transform((str) => new Date(str)), type: import_zod.z.string(), cron_job: import_zod.z.string(), timezone: import_zod.z.string(), credentials: import_zod.z.string().optional().nullable(), error: import_zod.z.string().nullable() }); var GetConnectorResponseSchema = import_zod.z.object({ result: ConnectorSchema }); var ListConnectorsResponseSchema = import_zod.z.object({ result: import_zod.z.array(ConnectorSchema) }); var CreateConnectorRequestSchema = import_zod.z.object({ name: import_zod.z.string().min(1, "Cannot be empty").max(255), cronJob: import_zod.z.string(), cronJobTimezone: import_zod.z.string(), collectionIds: import_zod.z.array(import_zod.z.string()), credentials: import_zod.z.string().optional().nullable() }); var CreateConnectorResponseSchema = import_zod.z.object({ result: ConnectorSchema }); var CreateFileActionSchema = import_zod.z.object({ id: import_zod.z.string(), url: import_zod.z.string().url(), type: FileTypeSchema }); var UpdateFileActionSchema = import_zod.z.object({ id: import_zod.z.string() }); var DeleteFileActionSchema = import_zod.z.object({ id: import_zod.z.string() }); var ConnectorRunDescriptorSchema = import_zod.z.object({ create: import_zod.z.array(CreateFileActionSchema), update: import_zod.z.array(UpdateFileActionSchema), delete: import_zod.z.array(DeleteFileActionSchema) }); var CollectionSchema = import_zod.z.object({ id: import_zod.z.string(), name: import_zod.z.string() }); var ListCollectionsResponseSchema = import_zod.z.object({ result: import_zod.z.array(CollectionSchema) }); // src/utils/auth-utils.ts var import_jsonwebtoken = __toESM(require("jsonwebtoken"), 1); // src/utils/config-utils.ts var import_lilconfig = require("lilconfig"); // src/models/config-models.ts var import_zod2 = require("zod"); var NeedleAppConfigSchema = import_zod2.z.object({ appId: import_zod2.z.string(), appName: import_zod2.z.string(), appSlug: import_zod2.z.string(), connectorType: import_zod2.z.string(), connectorLogo: import_zod2.z.union([import_zod2.z.string().url().nullish(), import_zod2.z.literal("")]) }); // src/utils/config-utils.ts var config = null; var options = { searchPlaces: ["needle.config.js"] }; async function getConfig() { if (config) { return config; } const res = await (0, import_lilconfig.lilconfig)("needle-config", options).search(); config = NeedleAppConfigSchema.parse(res?.config); return config; } // src/utils/auth-utils.ts async function getJwt(sub) { if (!process.env.NEEDLE_APP_SECRET) { throw new Error("NEEDLE_APP_SECRET is not set"); } if (!process.env.NEEDLE_APP_ENV) { throw new Error("NEEDLE_APP_ENV is not set"); } const cfg = await getConfig(); const payload = { iss: cfg.appId, sub, aud: process.env.NEEDLE_URL, exp: Math.floor(Date.now() / 1e3) + 60 * 60 * 24, // 1 day jti: uuid(), appName: cfg.appName, appEnv: process.env.NEEDLE_APP_ENV }; return import_jsonwebtoken.default.sign(payload, process.env.NEEDLE_APP_SECRET); } async function verifyJwt(token) { if (!process.env.NEEDLE_APP_SECRET) { throw new Error("NEEDLE_APP_SECRET is not set"); } const verifiedToken = import_jsonwebtoken.default.verify(token, process.env.NEEDLE_APP_SECRET); if (typeof verifiedToken === "string") { throw new Error("Invalid bearer token"); } return verifiedToken; } function uuid() { let dt = (/* @__PURE__ */ new Date()).getTime(); const uuid2 = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace( /[xy]/g, function(c) { const r = (dt + Math.random() * 16) % 16 | 0; dt = Math.floor(dt / 16); return (c == "x" ? r : r & 3 | 8).toString(16); } ); return uuid2; } // src/sessions.ts async function validateSession(sessionId) { const token = await getJwt(sessionId); const res = await fetch( `${process.env.NEEDLE_URL}/api/v1/apps/sessions/validate`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` } } ); if (res.status > 400) { throw ApiErrorSchema.parse(await res.json()).error; } return ValidateSessionResponseSchema.parse(await res.json()).result; } // src/connectors.ts async function createConnector(params, sessionId) { const token = await getJwt(sessionId); const res = await fetch(`${process.env.NEEDLE_URL}/api/v1/apps/connectors`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, body: JSON.stringify(params) }); if (res.status > 400) { throw ApiErrorSchema.parse(await res.json()).error; } return CreateConnectorResponseSchema.parse(await res.json()).result; } async function getConnector(connectorId, sessionId) { const token = await getJwt(sessionId); const res = await fetch( `${process.env.NEEDLE_URL}/api/v1/apps/connectors/${connectorId}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` } } ); if (res.status > 400) { throw ApiErrorSchema.parse(await res.json()).error; } return GetConnectorResponseSchema.parse(await res.json()).result; } async function listConnectors(sessionId) { const token = await getJwt(sessionId); const res = await fetch(`${process.env.NEEDLE_URL}/api/v1/apps/connectors`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` } }); if (res.status > 400) { throw ApiErrorSchema.parse(await res.json()).error; } return ListConnectorsResponseSchema.parse(await res.json()).result; } async function deleteConnector(connectorId, sessionId) { const token = await getJwt(sessionId); const res = await fetch( `${process.env.NEEDLE_URL}/api/v1/apps/connectors/${connectorId}`, { method: "DELETE", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` } } ); if (res.status > 400) { throw ApiErrorSchema.parse(await res.json()).error; } } async function publishConnectorRun(connectorId, descriptor) { const cfg = await getConfig(); const token = await getJwt(cfg.appId); const res = await fetch( `${process.env.NEEDLE_URL}/api/v1/apps/connectors/${connectorId}/runs`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, body: JSON.stringify(descriptor) } ); if (res.status > 400) { throw ApiErrorSchema.parse(await res.json()).error; } } // src/collections.ts async function listCollections(sessionId) { const token = await getJwt(sessionId); const res = await fetch(`${process.env.NEEDLE_URL}/api/v1/apps/collections`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` } }); if (res.status > 400) { throw ApiErrorSchema.parse(await res.json()).error; } return ListCollectionsResponseSchema.parse(await res.json()).result; } // src/files.ts var import_ulid = require("ulid"); function createNeedleFileId() { return "fle_" + (0, import_ulid.ulid)(); } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { createConnector, createNeedleFileId, deleteConnector, getConnector, listCollections, listConnectors, publishConnectorRun, validateSession, verifyJwt }); //# sourceMappingURL=index.cjs.map