"use strict";
(() => {
var exports = {};
exports.id = 553;
exports.ids = [553];
exports.modules = {

/***/ 2748:
/***/ ((module) => {

module.exports = require("luxon");

/***/ }),

/***/ 1917:
/***/ ((module) => {

module.exports = require("p-retry");

/***/ }),

/***/ 9456:
/***/ ((module) => {

module.exports = require("phin");

/***/ }),

/***/ 8518:
/***/ ((module) => {

module.exports = import("serialize-error");;

/***/ }),

/***/ 3493:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ handler)
/* harmony export */ });
/* harmony import */ var _taskless_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6659);
/* harmony import */ var luxon__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2748);
/* harmony import */ var luxon__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(luxon__WEBPACK_IMPORTED_MODULE_1__);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_taskless_client__WEBPACK_IMPORTED_MODULE_0__]);
_taskless_client__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];


async function handler(req, res) {
    var ref, ref1, ref2;
    const variables = req.body;
    const q = new _taskless_client__WEBPACK_IMPORTED_MODULE_0__/* .Queue */ .c({
        name: ((ref = variables.__meta) === null || ref === void 0 ? void 0 : ref.queueName) ?? "manual",
        route: variables.job.endpoint,
        queueOptions: {
            credentials: {
                appId: ((ref1 = variables.__meta) === null || ref1 === void 0 ? void 0 : ref1.appId) ?? undefined,
                secret: ((ref2 = variables.__meta) === null || ref2 === void 0 ? void 0 : ref2.secret) ?? undefined
            }
        }
    });
    const now = luxon__WEBPACK_IMPORTED_MODULE_1__.DateTime.now().toISO();
    let body = variables.job.body;
    if (variables.job.body) {
        try {
            body = JSON.parse(variables.job.body);
        } catch  {
        /* noop */ }
    }
    const j = await q.enqueue(variables.name, body, {
        enabled: variables.job.enabled ?? undefined,
        headers: variables.job.headers ?? undefined,
        retries: variables.job.retries ?? undefined,
        runAt: variables.job.runAt === "" ? now : variables.job.runAt ?? now,
        runEvery: variables.job.runEvery
    });
    return res.status(200).json({
        upsertJob: j
    });
};

__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

/***/ 6698:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "a2": () => (/* binding */ JobMethodEnum),
/* harmony export */   "mK": () => (/* binding */ getSdk)
/* harmony export */ });
/* unused harmony exports RunnerStatusEnum, JobDataFragmentDoc, EnqueueJobDocument, UpdateJobDocument, DeleteJobDocument, GetJobByNameDocument */
/** Valid HTTP methods for Taskless Jobs */
var JobMethodEnum;
(function (JobMethodEnum) {
    JobMethodEnum["Get"] = "GET";
    JobMethodEnum["Post"] = "POST";
})(JobMethodEnum || (JobMethodEnum = {}));
/** The Job Runner's status */
var RunnerStatusEnum;
(function (RunnerStatusEnum) {
    RunnerStatusEnum["Aborted"] = "ABORTED";
    RunnerStatusEnum["Completed"] = "COMPLETED";
    RunnerStatusEnum["Failed"] = "FAILED";
    RunnerStatusEnum["Running"] = "RUNNING";
    RunnerStatusEnum["Scheduled"] = "SCHEDULED";
})(RunnerStatusEnum || (RunnerStatusEnum = {}));
const JobDataFragmentDoc = `
    fragment JobData on Job {
  __typename
  name
  endpoint
  headers
  enabled
  body
  retries
  runAt
  runEvery
}
    `;
const EnqueueJobDocument = `
    mutation enqueueJob($name: String!, $job: ReplaceJobInputType!) {
  replaceJob(name: $name, job: $job) {
    ...JobData
  }
}
    ${JobDataFragmentDoc}`;
const UpdateJobDocument = `
    mutation updateJob($name: String!, $job: UpdateJobInputType!) {
  updateJob(name: $name, job: $job) {
    ...JobData
  }
}
    ${JobDataFragmentDoc}`;
const DeleteJobDocument = `
    mutation deleteJob($name: String!) {
  deleteJob(name: $name) {
    ...JobData
  }
}
    ${JobDataFragmentDoc}`;
const GetJobByNameDocument = `
    query getJobByName($name: String!) {
  job(name: $name) {
    ...JobData
  }
}
    ${JobDataFragmentDoc}`;
function getSdk(requester) {
    return {
        enqueueJob(variables, options) {
            return requester(EnqueueJobDocument, variables, options);
        },
        updateJob(variables, options) {
            return requester(UpdateJobDocument, variables, options);
        },
        deleteJob(variables, options) {
            return requester(DeleteJobDocument, variables, options);
        },
        getJobByName(variables, options) {
            return requester(GetJobByNameDocument, variables, options);
        }
    };
}
//# sourceMappingURL=schema.js.map

/***/ }),

/***/ 5421:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Mw": () => (/* binding */ IS_PRODUCTION),
/* harmony export */   "TO": () => (/* binding */ TASKLESS_DEV_ENDPOINT),
/* harmony export */   "YG": () => (/* binding */ TASKLESS_ENDPOINT)
/* harmony export */ });
/** The default Taskless endpoint for Taskless.io */
const TASKLESS_ENDPOINT = "https://for.taskless.io/api/graphql";
/** The default Taskless Development Server endpoint */
const TASKLESS_DEV_ENDPOINT = "http://localhost:3001/api/rpc";
/** A reusable flag that determines if we are running in a production environment */
const IS_PRODUCTION = typeof process.env.TASKLESS_ENV !== "undefined"
    ? process.env.TASKLESS_ENV === "production"
    : "production" === "production";
//# sourceMappingURL=constants.js.map

/***/ }),

/***/ 1085:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "K": () => (/* binding */ JobError)
/* harmony export */ });
class ResponseError extends Error {
    constructor(message) {
        super(message);
        this.type = "ResponseError";
    }
}
class JobError extends ResponseError {
    constructor(message, options) {
        super(message);
        this.type = "JobError";
        this.statusCode = 500;
        this.statusMessage = "Internal Server Error";
        this.headers = {};
        if (typeof (options === null || options === void 0 ? void 0 : options.retryAfter) !== "undefined") {
            this.headers["retry-after"] = options.retryAfter;
            this.statusCode = 503;
            this.statusMessage = "Unavailable";
        }
    }
}
//# sourceMappingURL=error.js.map

/***/ }),

/***/ 9325:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Y": () => (/* binding */ headersToGql)
/* harmony export */ });
/* unused harmony export gqlToHeaders */
/** Convert optional headers into a GraphQL friendly header input */
const headersToGql = (h) => {
    if (!h || typeof h === "undefined") {
        return undefined;
    }
    const headers = Object.getOwnPropertyNames(h);
    return headers.map((header) => {
        const value = h[header];
        const valueAsString = typeof value === "string"
            ? value
            : typeof value === "number"
                ? `${value}`
                : "";
        return {
            name: `${header}`,
            value: `${valueAsString}`,
        };
    });
};
/** Convert a GraphQL header payload into request-friendly JSON structure */
const gqlToHeaders = (h) => {
    if (!h)
        return {};
    return h.reduce((all, curr) => {
        all[curr.name] = curr.value;
        return all;
    }, {});
};
//# sourceMappingURL=headers.js.map

/***/ }),

/***/ 6659:
/***/ ((__webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "c": () => (/* reexport safe */ _queue_queue_js__WEBPACK_IMPORTED_MODULE_0__.c)
/* harmony export */ });
/* harmony import */ var _queue_queue_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(423);
/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1085);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_queue_queue_js__WEBPACK_IMPORTED_MODULE_0__]);
_queue_queue_js__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];


//# sourceMappingURL=index.js.map
__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

/***/ 6249:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "U": () => (/* binding */ create)
/* harmony export */ });
/* harmony import */ var p_retry__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1917);
/* harmony import */ var phin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9456);
/* harmony import */ var _netTypes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4838);
/* harmony import */ var _generated_schema_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6698);




/** A factory for creating getter objects */
const createGetter = (globalOptions, phinOptions) => {
    const { url, appId, secret, retries } = globalOptions;
    if (!url) {
        throw new Error("URL was not provided when creating the client");
    }
    if (!appId) {
        throw new Error("API Key was not provided when creating the client");
    }
    if (!secret) {
        throw new Error("API Secret was not provided when creating the client");
    }
    /** A graphql-code-generator friendly fetch function */
    const get = async (doc, vars
    // options?: object
    ) => {
        var _a, _b;
        const headers = {
            ...((_a = globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.headers) !== null && _a !== void 0 ? _a : {}),
            ...((_b = phinOptions === null || phinOptions === void 0 ? void 0 : phinOptions.headers) !== null && _b !== void 0 ? _b : {}),
            "user-agent": "Taskless Client",
            "x-taskless-app-id": appId,
            "x-taskless-secret": secret,
            "content-type": "application/json",
        };
        const body = {
            query: doc,
            variables: vars,
        };
        try {
            const result = await p_retry__WEBPACK_IMPORTED_MODULE_0__(() => phin__WEBPACK_IMPORTED_MODULE_1__({
                ...phinOptions,
                url: globalOptions.url,
                method: "POST",
                headers,
                data: JSON.stringify(body),
                parse: "json",
            }), {
                retries: retries !== null && retries !== void 0 ? retries : 5,
            });
            if (result.body.errors) {
                throw new _netTypes_js__WEBPACK_IMPORTED_MODULE_2__/* .RequestError */ .L("Unable to run operation", result.body);
            }
            if (!result.body.data) {
                throw new _netTypes_js__WEBPACK_IMPORTED_MODULE_2__/* .RequestError */ .L("Received malformed data", result.body);
            }
            return result.body.data;
        }
        catch (err) {
            console.warn(err);
            throw new Error("Could not make request: " + (typeof err === "string" ? err : "unknown"));
        }
    };
    return get;
};
/**
 * Creates a lightweight GraphQL client based on string documents
 * Under the hood, this uses phin + typed graphql codegen for type safety
 * @param options A set of request options
 * @param phinOptions A set of options to pass to phin
 * @returns A fully-typed GraphQL client
 */
const create = (options, phinOptions) => {
    return (0,_generated_schema_js__WEBPACK_IMPORTED_MODULE_3__/* .getSdk */ .mK)(createGetter(options, phinOptions));
};
//# sourceMappingURL=graphqlClient.js.map

/***/ }),

/***/ 4838:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "L": () => (/* binding */ RequestError)
/* harmony export */ });
/** A stand-in error object that works with Phin */
class RequestError extends Error {
    constructor(err, raw) {
        super(err);
        this.raw = raw;
    }
}
//# sourceMappingURL=netTypes.js.map

/***/ }),

/***/ 2123:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "U": () => (/* binding */ create)
/* harmony export */ });
/* harmony import */ var phin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9456);
/* harmony import */ var p_retry__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1917);
/* harmony import */ var _netTypes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4838);



/**
 * Creates a lightweight RPC client mirroring GraphQL functions
 * Under the hood, this uses phin and enforces methods via the typed
 * graphql codegen output for type safety
 * @param options A set of request options
 * @param phinOptions A set of options to pass to phin
 * @returns A fully-typed GraphQL client
 */
const create = (options, phinOptions) => {
    var _a, _b;
    const headers = {
        ...((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}),
        ...((_b = phinOptions === null || phinOptions === void 0 ? void 0 : phinOptions.headers) !== null && _b !== void 0 ? _b : {}),
        "user-agent": "Taskless Client",
        "x-taskless-app-id": options.appId,
        "x-taskless-secret": options.secret,
        "content-type": "application/json",
    };
    const send = async (method, variables) => {
        var _a;
        try {
            const result = await p_retry__WEBPACK_IMPORTED_MODULE_1__(() => phin__WEBPACK_IMPORTED_MODULE_0__({
                ...phinOptions,
                url: options.url,
                method: "POST",
                headers,
                data: JSON.stringify({
                    method,
                    variables,
                }),
                parse: "json",
            }), {
                retries: (_a = options === null || options === void 0 ? void 0 : options.retries) !== null && _a !== void 0 ? _a : 5,
            });
            if (result.body.errors) {
                throw new _netTypes_js__WEBPACK_IMPORTED_MODULE_2__/* .RequestError */ .L("Unable to run operation", result.body);
            }
            if (!result.body.data) {
                throw new _netTypes_js__WEBPACK_IMPORTED_MODULE_2__/* .RequestError */ .L("Received malformed data", result.body);
            }
            return result.body.data;
        }
        catch (err) {
            console.warn(err);
            throw new Error("Could not make request: " + (typeof err === "string" ? err : "unknown"));
        }
    };
    return {
        async enqueueJob(variables) {
            return send("enqueueJob", variables);
        },
        async updateJob(variables) {
            return send("updateJob", variables);
        },
        async deleteJob(variables) {
            return send("deleteJob", variables);
        },
        async getJobByName(variables) {
            return send("getJobByName", variables);
        },
    };
};
//# sourceMappingURL=rpcClient.js.map

/***/ }),

/***/ 4385:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {


// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "Jx": () => (/* binding */ decode),
  "cv": () => (/* binding */ encode),
  "Xx": () => (/* binding */ sign),
  "T": () => (/* binding */ verify)
});

;// CONCATENATED MODULE: external "node:crypto"
const external_node_crypto_namespaceObject = require("node:crypto");
;// CONCATENATED MODULE: ../client/dist/esm/queue/encoder.js

/** Convert a UTF-8 string into a valid hash key of the matching hash length */
const strToKey = (str, cipher) => {
    var _a;
    const info = (_a = hashMap[cipher]) !== null && _a !== void 0 ? _a : null;
    if (!info) {
        return Buffer.from("");
    }
    return (0,external_node_crypto_namespaceObject.createHash)(info).update(Buffer.from(str)).digest();
};
/**
 * Get the cipher info given a supported cipher
 * @deprecated To be removed once Node 16 lts is lowest supported version
 * @param name A cipher name
 * @returns An object containing the cipher's info
 */
const getCipherInfo = (name) => {
    const cipherInfo = {
        "aes-256-gcm": {
            mode: "gcm",
            name: "id-aes-256-gcm",
            nid: 901,
            ivLength: 12,
            keyLength: 32,
        },
        none: undefined,
    };
    if (name === "aes-256-gcm") {
        return cipherInfo["aes-256-gcm"];
    }
    return undefined;
};
/** For any given cipher we support, there is a hash that will generate a key of proper bit length from a string */
const hashMap = {
    none: "",
    "aes-256-gcm": "sha256",
};
/** Sign a string against a secret token */
const sign = (input, secret) => {
    return (0,external_node_crypto_namespaceObject.createHmac)("sha256", secret).update(input).digest("base64");
};
/** Verify a string against a set of secret tokens */
const verify = (input, secrets, signature) => {
    for (const s of secrets) {
        if (!s)
            continue;
        const sig = sign(input, s);
        if (sig === signature) {
            return true;
        }
    }
    return false;
};
/**
 * Encode an object by placing it into a stringified JSON object and ciphering
 * By using a JSON object, we ensure that whatever we encode can be JSON parsed
 * later.
 * @param obj
 * @param secret
 * @returns
 */
const encode = (obj, secret) => {
    const algo = "aes-256-gcm";
    const info = getCipherInfo(algo);
    const str = JSON.stringify({
        envelope: obj,
    });
    if (!info) {
        throw new Error("Unknown algo: " + algo);
    }
    if (!secret) {
        return {
            transport: {
                ev: 1,
                alg: "none",
            },
            text: str,
        };
    }
    const key = strToKey(secret, algo);
    const iv = (0,external_node_crypto_namespaceObject.randomBytes)(info.ivLength);
    const authTagLength = 16;
    const cipher = (0,external_node_crypto_namespaceObject.createCipheriv)(algo, key, iv, {
        authTagLength,
    });
    const ciphered = Buffer.concat([cipher.update(str, "utf-8"), cipher.final()]);
    return {
        transport: {
            ev: 1,
            alg: algo,
            atl: authTagLength,
            at: cipher.getAuthTag().toString("base64"),
            iv: iv.toString("base64"),
        },
        text: ciphered.toString("base64"),
    };
};
/** Decodes a single string to JSON and removes the payload from the envelope key */
const decodeOne = (text, transport, secret) => {
    const algo = transport.alg;
    if (algo === "none") {
        return text;
    }
    const key = strToKey(secret !== null && secret !== void 0 ? secret : "", algo);
    const decipher = (0,external_node_crypto_namespaceObject.createDecipheriv)(algo, key, Buffer.from(transport.iv, "base64"), {
        authTagLength: transport.atl,
    });
    decipher.setAuthTag(Buffer.from(transport.at, "base64"));
    const deciphered = Buffer.concat([
        decipher.update(text, "base64"),
        decipher.final(),
    ]).toString();
    return deciphered;
};
/**
 * Decode an object from an encrypted string through one or more keys.
 * An array of possible secrets allows old keys to be rotated away if needed
 * @param str
 * @param secrets
 * @returns
 */
const decode = (text, transport, secrets) => {
    var _a;
    for (const secret of secrets.concat(undefined)) {
        try {
            // break on success
            const result = decodeOne(text, transport, secret);
            return (_a = JSON.parse(result)) === null || _a === void 0 ? void 0 : _a.envelope;
        }
        catch (e) {
            // ignore failures
        }
    }
    // no keys worked
    throw new Error("No valid decryption keys found");
};
//# sourceMappingURL=encoder.js.map

/***/ }),

/***/ 423:
/***/ ((__webpack_module__, __webpack_exports__, __webpack_require__) => {

__webpack_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "c": () => (/* binding */ Queue)
/* harmony export */ });
/* harmony import */ var luxon__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2748);
/* harmony import */ var serialize_error__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8518);
/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1085);
/* harmony import */ var _generated_schema_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6698);
/* harmony import */ var _net_graphqlClient_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6249);
/* harmony import */ var _net_rpcClient_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(2123);
/* harmony import */ var _encoder_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(4385);
/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(5421);
/* harmony import */ var _graphql_helpers_headers_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(9325);
/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(4376);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([serialize_error__WEBPACK_IMPORTED_MODULE_1__]);
serialize_error__WEBPACK_IMPORTED_MODULE_1__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];










/** Get either the first object of the array or the object if not an array */
const firstOf = (unk) => {
    return Array.isArray(unk) ? unk[0] : unk;
};
class Queue {
    constructor(args) {
        const options = (0,_util_js__WEBPACK_IMPORTED_MODULE_8__/* .resolveOptions */ .F)(args.queueOptions);
        this.queueOptions = {
            ...options,
        };
        this.route = args.route;
        this.handler = args.handler;
    }
    /** Packs a name into string format */
    packName(name) {
        var _a;
        const s = (_a = this.queueOptions.separator) !== null && _a !== void 0 ? _a : "/";
        return Array.isArray(name) ? name.join(s) : `${name}`;
    }
    /** Turn a payload into a Taskless Body */
    p2b(payload) {
        var _a;
        const { transport, text } = (0,_encoder_js__WEBPACK_IMPORTED_MODULE_6__/* .encode */ .cv)(payload, (_a = this.queueOptions.encryptionKey) !== null && _a !== void 0 ? _a : undefined);
        return {
            v: 1,
            transport,
            text,
            signature: (0,_encoder_js__WEBPACK_IMPORTED_MODULE_6__/* .sign */ .Xx)(text, this.queueOptions.credentials.secret),
        };
    }
    /** Turn a Taskless Body into a payload */
    b2p(body, allowUnsigned) {
        var _a, _b;
        if (body.v !== 1) {
            throw new Error("Unsupported Taskless Envelope");
        }
        const ver = (0,_encoder_js__WEBPACK_IMPORTED_MODULE_6__/* .verify */ .T)(body.text, [
            this.queueOptions.credentials.secret,
            ...((_a = this.queueOptions.credentials.expiredSecrets) !== null && _a !== void 0 ? _a : []),
        ], body.signature);
        if (!ver && !allowUnsigned) {
            if (true) {
                throw new Error("Signature mismatch");
            }
            else {}
        }
        const payload = (0,_encoder_js__WEBPACK_IMPORTED_MODULE_6__/* .decode */ .Jx)(body.text, body.transport, [
            this.queueOptions.encryptionKey,
            ...((_b = this.queueOptions.expiredEncryptionKeys) !== null && _b !== void 0 ? _b : []),
        ].filter((t) => t));
        return { payload, verified: ver };
    }
    /** Resolves a route to a fully qualified URL */
    resolveRoute() {
        var _a, _b;
        const route = typeof this.route === "function" ? this.route() : (_a = this.route) !== null && _a !== void 0 ? _a : "";
        // if route starts with https?://, it's valid already
        if (route.indexOf("http://") === 0 || route.indexOf("https://") === 0) {
            return route;
        }
        return `${(_b = this.queueOptions.baseUrl) !== null && _b !== void 0 ? _b : ""}${route.indexOf("/") === 0 ? route : "/" + route}`;
    }
    /** Gets an instance of the GraphQL client or a simplified dev client */
    getGraphQLClient() {
        const endpoint = _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .TASKLESS_ENDPOINT */ .YG;
        const creds = this.queueOptions.credentials;
        if (typeof (creds === null || creds === void 0 ? void 0 : creds.appId) === "undefined") {
            throw new Error("credentials.appId or TASKLESS_APP_ID was not set");
        }
        if (typeof (creds === null || creds === void 0 ? void 0 : creds.secret) === "undefined") {
            throw new Error("credentials.secret or TASKLESS_APP_SECRET was not set");
        }
        const c = (0,_net_graphqlClient_js__WEBPACK_IMPORTED_MODULE_4__/* .create */ .U)({
            url: endpoint,
            appId: creds.appId,
            secret: creds.secret,
        });
        return c;
    }
    /** Get an RPC client that looks and acts like our GraphQL client for local development */
    getRPCClient() {
        var _a;
        const endpoint = (_a = process.env.TASKLESS_DEV_ENDPOINT) !== null && _a !== void 0 ? _a : _constants_js__WEBPACK_IMPORTED_MODULE_7__/* .TASKLESS_DEV_ENDPOINT */ .TO;
        const c = (0,_net_rpcClient_js__WEBPACK_IMPORTED_MODULE_5__/* .create */ .U)({
            url: endpoint,
            appId: "",
            secret: "",
        });
        return c;
    }
    getClient() {
        const isDevelopment = "production" !== "production";
        const isForcedDev = process.env.TASKLESS_DEV_ENABLED === "1";
        const isForcedProd = process.env.TASKLESS_DEV_ENABLED === "0";
        if (isForcedDev) {
            return this.getRPCClient();
        }
        else if (isForcedProd) {
            return this.getGraphQLClient();
        }
        else if (isDevelopment) {
            return this.getRPCClient();
        }
        return this.getGraphQLClient();
    }
    /**
     * Recieve a message and execute the handler for it
     * errors are caught and converted to a 500 response, while
     * any success is returned as a 200
     * @param functions A set of accessory functions for accessing the request and dispatching a response
     */
    async receive(functions) {
        var _a, _b, _c, _d, _e;
        const { getBody, getHeaders, send, sendError } = functions;
        // skip missing handler (enqueue-only)
        if (typeof this.handler === "undefined") {
            await sendError(500, {}, "This Queue was not configured with a handler");
            return;
        }
        const body = await Promise.resolve(getBody());
        const { payload, verified } = this.b2p(body, (_b = (_a = this.queueOptions.__dangerouslyAllowUnverifiedSignatures) === null || _a === void 0 ? void 0 : _a.allowed) !== null && _b !== void 0 ? _b : false);
        const h = await getHeaders();
        try {
            const result = await this.handler(payload, {
                applicationId: (_c = firstOf(h["x-taskless-application"])) !== null && _c !== void 0 ? _c : null,
                organizationId: (_d = firstOf(h["x-taskless-organization"])) !== null && _d !== void 0 ? _d : null,
                attempt: parseInt((_e = firstOf(h["x-taskless-attempt"])) !== null && _e !== void 0 ? _e : "0", 10),
                verified,
            });
            await send(JSON.parse(JSON.stringify(result !== null && result !== void 0 ? result : {})));
            return;
        }
        catch (e) {
            console.error(e);
            const ser = (0,serialize_error__WEBPACK_IMPORTED_MODULE_1__.serializeError)(e);
            if (e instanceof _error_js__WEBPACK_IMPORTED_MODULE_2__/* .JobError */ .K) {
                await sendError(e.statusCode, e.headers, ser);
            }
            else {
                await sendError(500, {}, ser);
            }
        }
    }
    /**
     * Adds a job to the queue for processing
     * @param name The name of the job
     * @param payload The job's payload
     * @param options Additional job options overriding the queue's defaults
     * @returns a Promise containing the Job object enqueued
     */
    async enqueue(name, payload, options) {
        var _a, _b, _c, _d, _e, _f, _g;
        const opts = (0,_util_js__WEBPACK_IMPORTED_MODULE_8__/* .resolveJobOptions */ .s)(this.queueOptions.defaultJobOptions, options);
        const client = this.getClient();
        const body = this.p2b(payload);
        const resolvedName = this.packName(name);
        const job = await client.enqueueJob({
            name: resolvedName,
            job: {
                endpoint: this.resolveRoute(),
                method: _generated_schema_js__WEBPACK_IMPORTED_MODULE_3__/* .JobMethodEnum.Post */ .a2.Post,
                headers: (0,_graphql_helpers_headers_js__WEBPACK_IMPORTED_MODULE_9__/* .headersToGql */ .Y)(opts.headers),
                enabled: opts.enabled === false ? false : true,
                body: JSON.stringify(body),
                retries: opts.retries === 0 ? 0 : (_a = opts.retries) !== null && _a !== void 0 ? _a : 0,
                runAt: opts.runAt === null
                    ? luxon__WEBPACK_IMPORTED_MODULE_0__.DateTime.now().toISO()
                    : (_b = opts.runAt) !== null && _b !== void 0 ? _b : undefined,
                runEvery: opts.runEvery === null ? null : (_c = opts.runEvery) !== null && _c !== void 0 ? _c : undefined,
            },
        });
        // populate result
        const resolvedBody = JSON.parse((_d = job.replaceJob.body) !== null && _d !== void 0 ? _d : "");
        return {
            name: job.replaceJob.name,
            endpoint: job.replaceJob.endpoint,
            enabled: job.replaceJob.enabled === false ? false : true,
            headers: opts.headers,
            payload: this.b2p(resolvedBody, (_f = (_e = this.queueOptions.__dangerouslyAllowUnverifiedSignatures) === null || _e === void 0 ? void 0 : _e.allowed) !== null && _f !== void 0 ? _f : false).payload,
            retries: job.replaceJob.retries,
            runAt: job.replaceJob.runAt,
            runEvery: (_g = job.replaceJob.runEvery) !== null && _g !== void 0 ? _g : null,
        };
    }
    /**
     * Updates a job in the queue
     * @param name The name of the job
     * @param payload The job's payload. A value of `undefined` will reuse the existing payload
     * @param options Additional job options overriding the queue's defaults
     * @returns a Promise containing the updated Job object
     */
    async update(name, payload, options) {
        var _a, _b, _c, _d, _e;
        const opts = (0,_util_js__WEBPACK_IMPORTED_MODULE_8__/* .resolveJobOptions */ .s)(this.queueOptions.defaultJobOptions, options);
        const client = this.getClient();
        const body = typeof payload !== "undefined" ? this.p2b(payload) : undefined;
        const resolvedName = this.packName(name);
        const job = await client.updateJob({
            name: resolvedName,
            job: {
                endpoint: this.resolveRoute(),
                method: _generated_schema_js__WEBPACK_IMPORTED_MODULE_3__/* .JobMethodEnum.Post */ .a2.Post,
                headers: typeof opts.headers !== "undefined"
                    ? (0,_graphql_helpers_headers_js__WEBPACK_IMPORTED_MODULE_9__/* .headersToGql */ .Y)(opts.headers)
                    : undefined,
                enabled: opts.enabled === false ? false : opts.enabled,
                body: typeof body !== "undefined" ? JSON.stringify(body) : undefined,
                retries: opts.retries === 0 ? 0 : opts.retries,
                runAt: opts.runAt === null
                    ? luxon__WEBPACK_IMPORTED_MODULE_0__.DateTime.now().toISO()
                    : (_a = opts.runAt) !== null && _a !== void 0 ? _a : undefined,
                runEvery: opts.runEvery,
            },
        });
        // result
        const resolvedBody = JSON.parse((_b = job.updateJob.body) !== null && _b !== void 0 ? _b : "");
        return {
            name: job.updateJob.name,
            endpoint: job.updateJob.endpoint,
            enabled: job.updateJob.enabled === false ? false : true,
            payload: this.b2p(resolvedBody, (_d = (_c = this.queueOptions.__dangerouslyAllowUnverifiedSignatures) === null || _c === void 0 ? void 0 : _c.allowed) !== null && _d !== void 0 ? _d : false).payload,
            retries: job.updateJob.retries,
            runAt: job.updateJob.runAt,
            runEvery: (_e = job.updateJob.runEvery) !== null && _e !== void 0 ? _e : null,
        };
    }
    /**
     * Removes a job from the queue
     * @param name The name of the job
     * @returns a Promise containing the Job object that was removed
     */
    async delete(name) {
        var _a, _b, _c, _d;
        const client = this.getClient();
        const resolvedName = this.packName(name);
        const job = await client.deleteJob({
            name: resolvedName,
        });
        if (!job.deleteJob) {
            return null;
        }
        // result
        const resolvedBody = JSON.parse((_a = job.deleteJob.body) !== null && _a !== void 0 ? _a : "");
        return {
            name: job.deleteJob.name,
            endpoint: job.deleteJob.endpoint,
            enabled: job.deleteJob.enabled === false ? false : true,
            payload: this.b2p(resolvedBody, (_c = (_b = this.queueOptions.__dangerouslyAllowUnverifiedSignatures) === null || _b === void 0 ? void 0 : _b.allowed) !== null && _c !== void 0 ? _c : false).payload,
            retries: job.deleteJob.retries,
            runAt: job.deleteJob.runAt,
            runEvery: (_d = job.deleteJob.runEvery) !== null && _d !== void 0 ? _d : null,
        };
    }
    async get(name) {
        var _a, _b, _c, _d;
        const client = this.getClient();
        const resolvedName = this.packName(name);
        const result = await client.getJobByName({
            name: resolvedName,
        });
        if (!result.job) {
            return null;
        }
        // result
        const resolvedBody = JSON.parse((_a = result.job.body) !== null && _a !== void 0 ? _a : "");
        return {
            name: result.job.name,
            endpoint: result.job.endpoint,
            enabled: result.job.enabled === false ? false : true,
            payload: this.b2p(resolvedBody, (_c = (_b = this.queueOptions.__dangerouslyAllowUnverifiedSignatures) === null || _b === void 0 ? void 0 : _b.allowed) !== null && _c !== void 0 ? _c : false).payload,
            retries: result.job.retries,
            runAt: result.job.runAt,
            runEvery: (_d = result.job.runEvery) !== null && _d !== void 0 ? _d : null,
        };
    }
}
//# sourceMappingURL=queue.js.map
__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

/***/ 4376:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {


// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "s": () => (/* binding */ resolveJobOptions),
  "F": () => (/* binding */ resolveOptions)
});

;// CONCATENATED MODULE: external "generic-type-guard"
const external_generic_type_guard_namespaceObject = require("generic-type-guard");
;// CONCATENATED MODULE: ../types/dist/esm/types/ciphers.guard.js

/** Typeguard for {@link CipherAes256Gcm} */
const isCipherAes256Gcm = new external_generic_type_guard_namespaceObject.IsInterface()
    .with((0,external_generic_type_guard_namespaceObject.combine)(external_generic_type_guard_namespaceObject.isObject, (0,external_generic_type_guard_namespaceObject.hasProperties)({
    alg: (0,external_generic_type_guard_namespaceObject.isSingletonString)("aes-256-gcm"),
    atl: external_generic_type_guard_namespaceObject.isNumber,
    at: external_generic_type_guard_namespaceObject.isString,
    iv: external_generic_type_guard_namespaceObject.isString,
})))
    .get();
/** Typeguard for {@link CipherNone} */
const isCipherNone = new external_generic_type_guard_namespaceObject.IsInterface()
    .with((0,external_generic_type_guard_namespaceObject.combine)(external_generic_type_guard_namespaceObject.isObject, (0,external_generic_type_guard_namespaceObject.hasProperties)({
    alg: (0,external_generic_type_guard_namespaceObject.isSingletonString)("none"),
})))
    .get();
/** Typeguard for {@link Cipher} */
const isCipherEnvelope = new external_generic_type_guard_namespaceObject.UnionOf(isCipherNone)
    .with(isCipherAes256Gcm)
    .get();
//# sourceMappingURL=ciphers.guard.js.map
;// CONCATENATED MODULE: ../types/dist/esm/types/job.guard.js

/** Typeguard for {@link JobHeaders} */
const isJobHeaders = (o) => {
    return (0,external_generic_type_guard_namespaceObject.isObject)(o);
};
/** Typeguard for {@link Job} with an unknown payload */
const isJob = new external_generic_type_guard_namespaceObject.IsInterface()
    .with((0,external_generic_type_guard_namespaceObject.hasProperties)({
    name: external_generic_type_guard_namespaceObject.isString,
    endpoint: external_generic_type_guard_namespaceObject.isString,
    headers: (0,external_generic_type_guard_namespaceObject.isOptional)(isJobHeaders),
    enabled: external_generic_type_guard_namespaceObject.isBoolean,
    payload: external_generic_type_guard_namespaceObject.isUnknown,
    retries: external_generic_type_guard_namespaceObject.isNumber,
    runAt: external_generic_type_guard_namespaceObject.isString,
    runEvery: (0,external_generic_type_guard_namespaceObject.isNullable)(external_generic_type_guard_namespaceObject.isString),
}))
    .get();
//# sourceMappingURL=job.guard.js.map
;// CONCATENATED MODULE: ../types/dist/esm/types/queue.guard.js
/** Typeguard for {@link FinalizedQueueOptions} */
const isFinalizedQueueOptions = (o) => {
    var _a, _b;
    return (typeof ((_a = o.credentials) === null || _a === void 0 ? void 0 : _a.appId) !== "undefined" &&
        typeof ((_b = o.credentials) === null || _b === void 0 ? void 0 : _b.secret) !== "undefined");
};
//# sourceMappingURL=queue.guard.js.map
;// CONCATENATED MODULE: ../types/dist/esm/types/tasklessBody.guard.js


/** Typeguard for {@link Transport} */
const isTransport = new external_generic_type_guard_namespaceObject.IsInterface()
    .withProperties({
    ev: (0,external_generic_type_guard_namespaceObject.isSingletonNumber)(1),
})
    .with(isCipherEnvelope)
    .get();
/** Typeguard for {@link TasklessBody} */
const isTasklessBody = new external_generic_type_guard_namespaceObject.IsInterface()
    .with((0,external_generic_type_guard_namespaceObject.combine)(external_generic_type_guard_namespaceObject.isObject, (0,external_generic_type_guard_namespaceObject.hasProperties)({
    v: external_generic_type_guard_namespaceObject.isNumber,
    transport: isTransport,
    text: external_generic_type_guard_namespaceObject.isString,
    signature: external_generic_type_guard_namespaceObject.isString,
})))
    .get();
//# sourceMappingURL=tasklessBody.guard.js.map
;// CONCATENATED MODULE: ../types/dist/esm/index.js








const Guards = {
    Cipher: {
        isCipherEnvelope: isCipherEnvelope,
    },
    Job: {
        isJob: isJob,
    },
    Queue: {
        isFinalizedQueueOptions: isFinalizedQueueOptions,
    },
    TasklessBody: {
        isTasklessBody: isTasklessBody,
        isTransport: isTransport,
    },
};
//# sourceMappingURL=index.js.map
// EXTERNAL MODULE: ../client/dist/esm/constants.js
var constants = __webpack_require__(5421);
;// CONCATENATED MODULE: ../client/dist/esm/queue/util.js
var _a, _b;


/** A set of default options for job objects */
const defaultJobOptions = {
    enabled: true,
    runAt: null,
    headers: {
        // actions are always json unless overridden
        "content-type": "application/json",
    },
    retries: 5,
};
/** Base configuration for development-like environments */
const developmentQueueOptions = constants/* IS_PRODUCTION */.Mw
    ? {}
    : {
        baseUrl: "http://localhost:3000",
        credentials: {
            appId: "00000000-0000-0000-0000-000000000000",
            secret: "taskless.development",
        },
    };
/** A set of default options for queue objects, taken from process.env */
const productionQueueOptions = {
    baseUrl: (_a = process.env.TASKLESS_BASE_URL) !== null && _a !== void 0 ? _a : undefined,
    encryptionKey: (_b = process.env.TASKLESS_ENCRYPTION_KEY) !== null && _b !== void 0 ? _b : undefined,
    expiredEncryptionKeys: process.env.TASKLESS_PREVIOUS_ENCRYPTION_KEYS
        ? `${process.env.TASKLESS_PREVIOUS_ENCRYPTION_KEYS}`
            .split(",")
            .map((s) => s.trim())
        : [],
    credentials: process.env.TASKLESS_APP_ID && process.env.TASKLESS_APP_SECRET
        ? {
            appId: process.env.TASKLESS_APP_ID,
            secret: process.env.TASKLESS_APP_SECRET,
            expiredSecrets: process.env.TASKLESS_PREVIOUS_APP_SECRETS
                ? `${process.env.TASKLESS_PREVIOUS_APP_SECRETS}`
                    .split(",")
                    .map((s) => s.trim())
                : [],
        }
        : undefined,
};
/** Resolve the options into finalized queue options, including runtime safety */
const resolveOptions = (additionalOptions) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y;
    /** Combined set of development and optionally env-based queue option defaults */
    const options = {
        baseUrl: (_b = (_a = additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.baseUrl) !== null && _a !== void 0 ? _a : productionQueueOptions === null || productionQueueOptions === void 0 ? void 0 : productionQueueOptions.baseUrl) !== null && _b !== void 0 ? _b : developmentQueueOptions === null || developmentQueueOptions === void 0 ? void 0 : developmentQueueOptions.baseUrl,
        credentials: {
            appId: (_f = (_d = (_c = additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.credentials) === null || _c === void 0 ? void 0 : _c.appId) !== null && _d !== void 0 ? _d : (_e = productionQueueOptions === null || productionQueueOptions === void 0 ? void 0 : productionQueueOptions.credentials) === null || _e === void 0 ? void 0 : _e.appId) !== null && _f !== void 0 ? _f : (_g = developmentQueueOptions === null || developmentQueueOptions === void 0 ? void 0 : developmentQueueOptions.credentials) === null || _g === void 0 ? void 0 : _g.appId,
            secret: (_l = (_j = (_h = additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.credentials) === null || _h === void 0 ? void 0 : _h.secret) !== null && _j !== void 0 ? _j : (_k = productionQueueOptions === null || productionQueueOptions === void 0 ? void 0 : productionQueueOptions.credentials) === null || _k === void 0 ? void 0 : _k.secret) !== null && _l !== void 0 ? _l : (_m = developmentQueueOptions === null || developmentQueueOptions === void 0 ? void 0 : developmentQueueOptions.credentials) === null || _m === void 0 ? void 0 : _m.secret,
            expiredSecrets: [
                ...((_p = (_o = additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.credentials) === null || _o === void 0 ? void 0 : _o.expiredSecrets) !== null && _p !== void 0 ? _p : []),
                ...((_r = (_q = productionQueueOptions === null || productionQueueOptions === void 0 ? void 0 : productionQueueOptions.credentials) === null || _q === void 0 ? void 0 : _q.expiredSecrets) !== null && _r !== void 0 ? _r : []),
                ...((_t = (_s = developmentQueueOptions === null || developmentQueueOptions === void 0 ? void 0 : developmentQueueOptions.credentials) === null || _s === void 0 ? void 0 : _s.expiredSecrets) !== null && _t !== void 0 ? _t : []),
            ],
        },
        encryptionKey: (_v = (_u = additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.encryptionKey) !== null && _u !== void 0 ? _u : productionQueueOptions === null || productionQueueOptions === void 0 ? void 0 : productionQueueOptions.encryptionKey) !== null && _v !== void 0 ? _v : developmentQueueOptions === null || developmentQueueOptions === void 0 ? void 0 : developmentQueueOptions.encryptionKey,
        expiredEncryptionKeys: [
            ...((_w = additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.expiredEncryptionKeys) !== null && _w !== void 0 ? _w : []),
            ...((_x = productionQueueOptions === null || productionQueueOptions === void 0 ? void 0 : productionQueueOptions.expiredEncryptionKeys) !== null && _x !== void 0 ? _x : []),
            ...((_y = developmentQueueOptions === null || developmentQueueOptions === void 0 ? void 0 : developmentQueueOptions.expiredEncryptionKeys) !== null && _y !== void 0 ? _y : []),
        ],
        defaultJobOptions: resolveJobOptions(defaultJobOptions, additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.defaultJobOptions),
    };
    // guard
    if (!Guards.Queue.isFinalizedQueueOptions(options)) {
        throw new Error("You must either set TASKLESS_APP_ID and TASKLESS_APP_SECRET in process.env or pass these values in your queue options.");
    }
    return options;
};
/** Merge sets of job options together, handling undefined sets of options */
const resolveJobOptions = (...opts) => {
    var _a, _b;
    let result = {};
    for (const opt of opts) {
        if (typeof opt === "undefined" || opt === null) {
            continue;
        }
        result = {
            ...result,
            headers: {
                ...((_a = result.headers) !== null && _a !== void 0 ? _a : {}),
                ...((_b = opt.headers) !== null && _b !== void 0 ? _b : {}),
            },
        };
    }
    return result;
};
//# sourceMappingURL=util.js.map

/***/ })

};
;

// load runtime
var __webpack_require__ = require("../../../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = (__webpack_exec__(3493));
module.exports = __webpack_exports__;

})();