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

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

module.exports = require("luxon");

/***/ }),

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

module.exports = require("phin");

/***/ }),

/***/ 290:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "default": () => (/* binding */ handler)
});

// EXTERNAL MODULE: external "luxon"
var external_luxon_ = __webpack_require__(2748);
;// CONCATENATED MODULE: ../client/dist/esm/error.js
class ResponseError extends Error {
}
class JobError extends ResponseError {
    constructor(message, options) {
        super(message);
        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
;// CONCATENATED MODULE: ../client/dist/esm/__generated__/schema.js
/** 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
;// CONCATENATED MODULE: external "p-retry"
const external_p_retry_namespaceObject = require("p-retry");
// EXTERNAL MODULE: external "phin"
var external_phin_ = __webpack_require__(9456);
;// CONCATENATED MODULE: ../client/dist/esm/net/netTypes.js
/** 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
;// CONCATENATED MODULE: ../client/dist/esm/net/graphqlClient.js




/** 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 external_p_retry_namespaceObject(() => external_phin_({
                ...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 RequestError("Unable to run operation", result.body);
            }
            if (!result.body.data) {
                throw new RequestError("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 getSdk(createGetter(options, phinOptions));
};
//# sourceMappingURL=graphqlClient.js.map
;// CONCATENATED MODULE: ../client/dist/esm/net/rpcClient.js



/**
 * 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 rpcClient_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 external_p_retry_namespaceObject(() => external_phin_({
                ...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 RequestError("Unable to run operation", result.body);
            }
            if (!result.body.data) {
                throw new RequestError("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
;// 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
;// CONCATENATED MODULE: ../client/dist/esm/constants.js
/** 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
;// CONCATENATED MODULE: ../client/dist/esm/graphql-helpers/headers.js
/** 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
;// 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
;// 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 = IS_PRODUCTION
    ? {}
    : {
        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
;// CONCATENATED MODULE: ../client/dist/esm/queue/queue.js









/** 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 = resolveOptions(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 } = encode(payload, (_a = this.queueOptions.encryptionKey) !== null && _a !== void 0 ? _a : undefined);
        return {
            v: 1,
            transport,
            text,
            signature: sign(text, this.queueOptions.credentials.secret),
        };
    }
    /** Turn a Taskless Body into a payload */
    b2p(body) {
        var _a, _b;
        if (body.v !== 1) {
            throw new Error("Unsupported Taskless Envelope");
        }
        const ver = verify(body.text, [
            this.queueOptions.credentials.secret,
            ...((_a = this.queueOptions.credentials.expiredSecrets) !== null && _a !== void 0 ? _a : []),
        ], body.signature);
        if (!ver) {
            if (true) {
                throw new Error("Signature mismatch");
            }
            else {}
        }
        const payload = decode(body.text, body.transport, [
            this.queueOptions.encryptionKey,
            ...((_b = this.queueOptions.expiredEncryptionKeys) !== null && _b !== void 0 ? _b : []),
        ].filter((t) => t));
        return payload;
    }
    /** 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 : "";
        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 = TASKLESS_ENDPOINT;
        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 = create({
            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 : TASKLESS_DEV_ENDPOINT;
        const c = rpcClient_create({
            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;
        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 = this.b2p(body);
        const h = await getHeaders();
        try {
            const result = await this.handler(payload, {
                applicationId: (_a = firstOf(h["x-taskless-application"])) !== null && _a !== void 0 ? _a : null,
                organizationId: (_b = firstOf(h["x-taskless-organization"])) !== null && _b !== void 0 ? _b : null,
                attempt: parseInt((_c = firstOf(h["x-taskless-attempt"])) !== null && _c !== void 0 ? _c : "0", 10),
            });
            await send(JSON.parse(JSON.stringify(result !== null && result !== void 0 ? result : {})));
            return;
        }
        catch (e) {
            console.error(e);
            if (e instanceof JobError) {
                await sendError(e.statusCode, e.headers, (_d = e.message) !== null && _d !== void 0 ? _d : e.statusMessage);
            }
            else {
                await sendError(500, {}, e instanceof Error ? e.message : "Internal Server Error");
            }
        }
    }
    /**
     * 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;
        const opts = resolveJobOptions(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: JobMethodEnum.Post,
                headers: headersToGql(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
                    ? external_luxon_.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),
            retries: job.replaceJob.retries,
            runAt: job.replaceJob.runAt,
            runEvery: (_e = job.replaceJob.runEvery) !== null && _e !== void 0 ? _e : 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;
        const opts = resolveJobOptions(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: JobMethodEnum.Post,
                headers: typeof opts.headers !== "undefined"
                    ? headersToGql(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
                    ? external_luxon_.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),
            retries: job.updateJob.retries,
            runAt: job.updateJob.runAt,
            runEvery: (_c = job.updateJob.runEvery) !== null && _c !== void 0 ? _c : 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;
        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),
            retries: job.deleteJob.retries,
            runAt: job.deleteJob.runAt,
            runEvery: (_b = job.deleteJob.runEvery) !== null && _b !== void 0 ? _b : null,
        };
    }
    async get(name) {
        var _a, _b;
        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),
            retries: result.job.retries,
            runAt: result.job.runAt,
            runEvery: (_b = result.job.runEvery) !== null && _b !== void 0 ? _b : null,
        };
    }
}
//# sourceMappingURL=queue.js.map
;// CONCATENATED MODULE: ../client/dist/esm/index.js


//# sourceMappingURL=index.js.map
;// CONCATENATED MODULE: ./src/pages/api/rest/job/upsert.ts


async function handler(req, res) {
    var ref, ref1, ref2;
    const variables = req.body;
    const q = new Queue({
        name: ((ref = variables.__meta) === null || ref === void 0 ? void 0 : ref.queueName) ?? "manual",
        route: variables.job.endpoint,
        queueOptions: {
            baseUrl: "",
            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 = external_luxon_.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
    });
};


/***/ })

};
;

// 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__(290));
module.exports = __webpack_exports__;

})();