@sqrzro/server 2.0.0-bz.8 → 2.0.0-r19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/auth.js +1 -1
- package/cache.js +1 -1
- package/dist/auth/index.cjs +3 -0
- package/dist/auth/index.cjs.map +1 -0
- package/dist/auth/index.d.cts +110 -0
- package/dist/auth/index.d.ts +110 -0
- package/dist/auth/index.js +3 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/cache/index.cjs +2 -0
- package/dist/cache/index.cjs.map +1 -0
- package/dist/cache/index.d.cts +4 -0
- package/dist/cache/index.d.ts +4 -0
- package/dist/cache/index.js +2 -0
- package/dist/cache/index.js.map +1 -0
- package/dist/database/schema.cjs +2 -0
- package/dist/database/schema.cjs.map +1 -0
- package/dist/database/schema.d.cts +405 -0
- package/dist/database/schema.d.ts +405 -0
- package/dist/database/schema.js +2 -0
- package/dist/database/schema.js.map +1 -0
- package/dist/forms/index.cjs +2 -0
- package/dist/forms/index.cjs.map +1 -0
- package/dist/forms/index.d.cts +50 -0
- package/dist/forms/index.d.ts +50 -0
- package/dist/forms/index.js +2 -0
- package/dist/forms/index.js.map +1 -0
- package/dist/lists/index.cjs +2 -0
- package/dist/lists/index.cjs.map +1 -0
- package/dist/lists/index.d.cts +18 -0
- package/dist/lists/index.d.ts +18 -0
- package/dist/lists/index.js +2 -0
- package/dist/lists/index.js.map +1 -0
- package/dist/mail/index.cjs +3 -0
- package/dist/mail/index.cjs.map +1 -0
- package/dist/mail/index.d.cts +19 -0
- package/dist/mail/index.d.ts +19 -0
- package/dist/mail/index.js +3 -0
- package/dist/mail/index.js.map +1 -0
- package/dist/middleware.cjs +2 -0
- package/dist/middleware.cjs.map +1 -0
- package/dist/middleware.d.cts +5 -0
- package/dist/middleware.d.ts +5 -0
- package/dist/middleware.js +2 -0
- package/dist/middleware.js.map +1 -0
- package/dist/url/index.cjs +3 -0
- package/dist/url/index.cjs.map +1 -0
- package/dist/url/index.d.cts +33 -0
- package/dist/url/index.d.ts +33 -0
- package/dist/url/index.js +3 -0
- package/dist/url/index.js.map +1 -0
- package/forms.js +1 -1
- package/jest.config.js +7 -0
- package/lists.js +1 -1
- package/mail.js +1 -1
- package/middleware.js +1 -1
- package/next-env.d.ts +5 -0
- package/package.json +76 -44
- package/schema.js +1 -1
- package/url.js +1 -1
- package/database.d.ts +0 -1
- package/database.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/forms/ValidationError.ts","../../src/forms/lang.ts","../../src/forms/ValidationService.ts","../../src/forms/FormService.ts","../../src/forms/ImageService.ts"],"names":["ValidationError","messages","ValidationError_default","lang_default","validate","Joi","getDefaultErrorMessages","getErrorMessages","acc","key","value","transformErrors","error","cur","validateSchema","formData","validation","err","createSchema","schema","extendSchema","appends","serializeError","hasFn","args","submitForm","data","validated","validationError","model","submitAPIRequest","response","errors","NextResponse","DEFAULT_TYPES","validateImage","image","config"],"mappings":"8DAAMA,CAAN,CAAA,cAA8B,KAAM,CACzB,QAAA,CAEA,WAAYC,CAAAA,CAAAA,CAAkC,CACjD,KAAM,CAAA,IAAA,CAAK,UAAUA,CAAQ,CAAC,EAE9B,IAAK,CAAA,QAAA,CAAWA,CAChB,CAAA,IAAA,CAAK,KAAO,kBAChB,CACJ,EAEOC,CAAQF,CAAAA,ECXf,IAAMC,CAAmC,CAAA,CACrC,mBAAoB,EACpB,CAAA,kBAAA,CAAoB,GACpB,oBAAsB,CAAA,EAAA,CACtB,mBAAoB,EACpB,CAAA,oBAAA,CAAsB,EACtB,CAAA,YAAA,CAAc,GACd,aAAe,CAAA,EAAA,CACf,eAAgB,EAChB,CAAA,aAAA,CAAe,GACf,UAAY,CAAA,EAAA,CACZ,SAAW,CAAA,EAAA,CACX,eAAgB,wBAChB,CAAA,aAAA,CAAe,GACf,YAAc,CAAA,EAAA,CACd,iBAAkB,EAClB,CAAA,4BAAA,CAA8B,EAC9B,CAAA,8BAAA,CAAgC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,CAAC,CAgBnE","file":"index.js","sourcesContent":["class ValidationError extends Error {\n public messages: Record<string, string>;\n\n public constructor(messages: Record<string, string>) {\n super(JSON.stringify(messages));\n\n this.messages = messages;\n this.name = 'ValidationError';\n }\n}\n\nexport default ValidationError;\n","const messages: Record<string, string> = {\n 'alternatives.all': '',\n 'alternatives.any': '',\n 'alternatives.match': '',\n 'alternatives.one': '',\n 'alternatives.types': '',\n 'any.custom': '',\n 'any.default': '',\n 'any.failover': '',\n 'any.invalid': '',\n 'any.only': '',\n 'any.ref': '',\n 'any.required': '{{#label}} is required',\n 'any.unknown': '',\n 'array.base': '',\n 'array.excludes': '',\n 'array.includesRequiredBoth': '',\n 'array.includesRequiredKnowns': '',\n 'array.includesRequiredUnknowns': '',\n 'array.includes': '',\n 'array.length': '',\n 'array.max': '',\n 'array.min': '',\n 'array.orderedLength': '',\n 'array.sort': '',\n 'array.sort.mismatching': '',\n 'array.sort.unsupported': '',\n 'array.sparse': '',\n 'array.unique': '',\n 'array.hasKnown': '',\n 'array.hasUnknown': '',\n 'binary.base': '',\n 'binary.length': '',\n 'binary.max': '',\n 'binary.min': '',\n 'boolean.base': '',\n 'date.base': '',\n 'date.format': '',\n 'date.greater': '',\n 'date.less': '',\n 'date.max': '',\n 'date.min': '',\n 'date.strict': '',\n 'function.arity': '',\n 'function.class': '',\n 'function.maxArity': '',\n 'function.minArity': '',\n 'number.base': '{{#label}} should be a number',\n 'number.greater': '',\n 'number.infinity': '',\n 'number.integer': '',\n 'number.less': '',\n 'number.max': '',\n 'number.min': '{{#label}} should be greater than or equal to {{#limit}}',\n 'number.multiple': '',\n 'number.negative': '',\n 'number.port': '',\n 'number.positive': '',\n 'number.precision': '',\n 'number.unsafe': '',\n 'object.unknown': '',\n 'object.and': '',\n 'object.assert': '',\n 'object.base': '',\n 'object.length': '',\n 'object.max': '',\n 'object.min': '',\n 'object.missing': '',\n 'object.nand': '',\n 'object.pattern.match': '',\n 'object.refType': '',\n 'object.regex': '',\n 'object.rename.multiple': '',\n 'object.rename.override': '',\n 'object.schema': '',\n 'object.instance': '',\n 'object.with': '',\n 'object.without': '',\n 'object.xor': '',\n 'object.oxor': '',\n 'string.alphanum': '',\n 'string.base64': '',\n 'string.base': '',\n 'string.creditCard': '',\n 'string.dataUri': '',\n 'string.domain': '',\n 'string.email': '',\n 'string.empty': '{{#label}} is required',\n 'string.guid': '',\n 'string.hexAlign': '',\n 'string.hex': '',\n 'string.hostname': '',\n 'string.ipVersion': '',\n 'string.ip': '',\n 'string.isoDate': '',\n 'string.isoDuration': '',\n 'string.length': '',\n 'string.lowercase': '',\n 'string.max': '',\n 'string.min': '',\n 'string.normalize': '',\n 'string.pattern.base': '{{#label}} is not in the correct format',\n 'string.pattern.name': '',\n 'string.pattern.invert.base': '',\n 'string.pattern.invert.name': '',\n 'string.token': '',\n 'string.trim': '',\n 'string.uppercase': '',\n 'string.uri': '',\n 'string.uriCustomScheme': '',\n 'string.uriRelativeOnly': '',\n 'symbol.base': '',\n 'symbol.map': '',\n};\n\nexport default messages;\n","import type { Errorable } from '@sqrzro/interfaces';\nimport Joi from 'joi';\n\nimport lang from './lang';\nimport ValidationError from './ValidationError';\n\nexport function validate(): typeof Joi {\n return Joi;\n}\n\nexport type ValidationCustomHelpers<V = any> = Joi.CustomHelpers<V>; // eslint-disable-line @typescript-eslint/no-explicit-any\nexport type ValidationExternalHelpers<V = any> = Joi.ExternalHelpers<V>; // eslint-disable-line @typescript-eslint/no-explicit-any\nexport type ValidationErrorReport = Joi.ErrorReport;\n\nexport function getDefaultErrorMessages(): Record<string, string> {\n return lang;\n}\n\nfunction getErrorMessages(): Record<string, string> {\n return Object.entries(lang).reduce((acc, [key, value]) => {\n if (!value) {\n return acc;\n }\n return {\n ...acc,\n [key]: value,\n };\n }, {});\n}\n\nfunction transformErrors(error: Joi.ValidationError): ValidationError {\n const messages = error.details.reduce(\n (acc, cur) => ({\n ...acc,\n [cur.path.join('.')]: cur.message.replace(/\"/gu, ''),\n }),\n {}\n );\n return new ValidationError(messages);\n}\n\n/**\n * This function takes FormData and a schema. It then attempts to transform the FormData into an\n * object that matches `T`. This is because the FormData object is not typed and we want to be able\n * to validate it properly typed.\n *\n * Once transformed, the object is validated against the schema. This will result in either a\n * properly typed `T` object or an array of validation errors.\n * @param formData\n * @param validation\n * @returns\n */\nexport async function validateSchema<T>(\n formData: Partial<T>,\n validation: Joi.ObjectSchema<T>,\n messages?: Record<string, string>\n): Promise<Errorable<T>> {\n try {\n const validated = await validation.validateAsync(formData, {\n abortEarly: false,\n messages: messages || getErrorMessages(),\n stripUnknown: true,\n });\n\n return [validated, null];\n } catch (err) {\n if (err instanceof Joi.ValidationError) {\n return [null, transformErrors(err)];\n }\n\n if (err instanceof Error) {\n return [null, err];\n }\n\n return [null, new Error('Unknown validation error occured')];\n }\n}\n\nexport function createSchema<T>(schema: Joi.SchemaMap<T, true>): Joi.ObjectSchema<T> {\n return Joi.object<T>(schema);\n}\n\nexport function extendSchema<T, U extends T>(\n schema: Joi.ObjectSchema<T>,\n appends: Joi.PartialSchemaMap<U>\n): Joi.ObjectSchema<U> {\n return schema.append<U>(appends);\n}\n","/* eslint-disable max-statements */\n\nimport type { SerializedError, SerializedErrorable } from '@sqrzro/interfaces';\nimport type Joi from 'joi';\nimport { NextResponse } from 'next/server';\n\nimport ValidationError from './ValidationError';\nimport { validateSchema } from './ValidationService';\n\nfunction serializeError(err: Error): SerializedError {\n return {\n cause: err.cause,\n message: err.message,\n name: err.name,\n stack: err.stack,\n };\n}\n\ninterface SubmitFormArgs<F extends object> {\n formData: F;\n onSuccess?: (model: F) => Promise<void> | void;\n onValidationError?: (error: ValidationError) => void;\n request?: Joi.ObjectSchema<F>;\n}\n\ninterface SubmitFormArgsWithFn<F extends object, M> extends Omit<SubmitFormArgs<F>, 'onSuccess'> {\n fn: (data: F) => Promise<M | null>;\n onSuccess?: (model: M) => Promise<void> | void;\n}\n\nfunction hasFn<F extends object, M>(\n args: SubmitFormArgs<F> | SubmitFormArgsWithFn<F, M>\n): args is SubmitFormArgsWithFn<F, M> {\n return Boolean(Object.prototype.hasOwnProperty.call(args, 'fn'));\n}\n\nexport async function submitForm<F extends object>(\n args: SubmitFormArgs<F>\n): Promise<SerializedErrorable<F>>;\nexport async function submitForm<F extends object, M>(\n args: SubmitFormArgsWithFn<F, M>\n): Promise<SerializedErrorable<M>>;\n\nexport async function submitForm<F extends object, M>(\n args: SubmitFormArgs<F> | SubmitFormArgsWithFn<F, M>\n): Promise<[F, null] | [M, null] | [null, SerializedError]> {\n let data = { ...args.formData };\n\n if (args.request) {\n const [validated, validationError] = await validateSchema<F>(args.formData, args.request);\n\n if (validationError !== null) {\n if (validationError instanceof ValidationError) {\n args.onValidationError?.(validationError);\n }\n\n return [null, serializeError(validationError)];\n }\n\n data = validated;\n }\n\n if (!hasFn(args)) {\n await args.onSuccess?.(data);\n return [data, null];\n }\n\n let model: Awaited<M> | null = null;\n\n try {\n model = await args.fn(data);\n } catch (err: unknown) {\n if (err instanceof ValidationError) {\n args.onValidationError?.(err);\n return [null, serializeError(err)];\n }\n if (err instanceof Error) {\n throw err;\n }\n throw new Error('The function supplied to submitForm encountered an unknown error');\n }\n\n if (!model) {\n throw new Error('NO_MODEL');\n }\n\n await args.onSuccess?.(model);\n return [model, null];\n}\n\nexport async function submitAPIRequest<F extends object, M>(\n args: SubmitFormArgsWithFn<F, M>\n): Promise<[M, null] | [null, NextResponse]> {\n const [response, error] = await submitForm<F, M>(args);\n\n if (error !== null) {\n if (error.name === 'ValidationError') {\n try {\n const errors = JSON.parse(error.message) as Record<string, string>;\n return [null, NextResponse.json(errors, { status: 422 })];\n } catch (err) {\n return [\n null,\n NextResponse.json({ message: 'An unknown error occured' }, { status: 500 }),\n ];\n }\n }\n return [null, NextResponse.json({ message: error.message }, { status: 500 })];\n }\n\n return [response, null];\n}\n","'use server';\n\nimport type { Errorable } from '@sqrzro/interfaces';\n\nconst DEFAULT_TYPES = ['image/png', 'image/jpeg', 'image/jpg'];\n// 5MB\nconst DEFAULT_MAX_SIZE = 5242880;\n\ninterface ImageValidationConfig {\n maxSize?: number;\n types?: string[];\n}\n\nexport async function validateImage(\n image: File | null,\n config?: ImageValidationConfig\n): Promise<Errorable<File>> {\n if (!image) {\n return Promise.resolve([null, new Error('IMAGE_UNDEFINED')]);\n }\n\n if (!(image instanceof File)) {\n return Promise.resolve([null, new Error('IMAGE_NOT_VALID')]);\n }\n\n if (!(config?.types || DEFAULT_TYPES).includes(image.type)) {\n return Promise.resolve([null, new Error('IMAGE_TYPE_NOT_VALID')]);\n }\n\n if (image.size > (config?.maxSize || DEFAULT_MAX_SIZE)) {\n return Promise.resolve([null, new Error('IMAGE_TOO_HEAVY')]);\n }\n\n return Promise.resolve([image, null]);\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var utility=require('@sqrzro/utility');var g="id",c="asc",A=1,s=10;function d(n){return {skip:(n-1)*s,take:s}}function u(n,t=[]){let{dir:e,page:r,sort:i,...o}=n||{};return {...d(r?parseInt(r,10):A),orderBy:{[i||g]:e||c},where:utility.getFromObject(o,t)}}async function l({allowedFilters:n,fn:t,searchParams:e}){try{let r=u(e,n);return [await t(r),null]}catch(r){return r instanceof Error?[null,r]:[null,new Error("[getList] An unknown error occurred")]}}exports.getList=l;//# sourceMappingURL=index.cjs.map
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/lists/ListService.ts"],"names":["DEFAULT_SORT","DEFAULT_DIR","DEFAULT_PAGE","DEFAULT_LIMIT","createPaginationArgs","page","createFindManyArgs","searchParams","allowedFilters","dir","sort","filters","getFromObject","getList","fn","args","err"],"mappings":"oDAaA,IAAMA,CAAAA,CAAe,IACfC,CAAAA,CAAAA,CAAc,KACdC,CAAAA,CAAAA,CAAe,CACfC,CAAAA,CAAAA,CAAgB,EAQtB,CAAA,SAASC,EAAqBC,CAAsB,CAAA,CAChD,OAAO,CAAE,IAAOA,CAAAA,CAAAA,CAAAA,CAAO,CAAKF,EAAAA,CAAAA,CAAe,IAAMA,CAAAA,CAAc,CACnE,CAEA,SAASG,CAAAA,CACLC,EACAC,CAA2B,CAAA,EACf,CAAA,CACZ,GAAM,CAAE,GAAAC,CAAAA,CAAAA,CAAK,IAAAJ,CAAAA,CAAAA,CAAM,IAAAK,CAAAA,CAAAA,CAAM,GAAGC,CAAQ,CAAIJ,CAAAA,CAAAA,EAAgB,EAAC,CAEzD,OAAO,CACH,GAAGH,CAAAA,CAAqBC,CAAO,CAAA,QAAA,CAASA,CAAM,CAAA,EAAE,CAAIH,CAAAA,CAAY,CAChE,CAAA,OAAA,CAAS,CAAE,CAACQ,CAAAA,EAAQV,CAAY,EAAGS,CAAOR,EAAAA,CAAY,CACtD,CAAA,KAAA,CAAOW,qBAAcD,CAAAA,CAAAA,CAASH,CAAc,CAChD,CACJ,CAEA,eAAsBK,CAAW,CAAA,CAC7B,cAAAL,CAAAA,CAAAA,CACA,EAAAM,CAAAA,CAAAA,CACA,YAAAP,CAAAA,CACJ,CAA4C,CAAA,CACxC,GAAI,CACA,IAAMQ,CAAAA,CAAOT,EAAmBC,CAAcC,CAAAA,CAAc,CAC5D,CAAA,OAAO,CAAC,MAAMM,CAAGC,CAAAA,CAAI,CAAG,CAAA,IAAI,CAChC,CAAA,MAASC,CAAK,CAAA,CACV,OAAIA,CAAAA,YAAe,KACR,CAAA,CAAC,IAAMA,CAAAA,CAAG,CAEd,CAAA,CAAC,IAAM,CAAA,IAAI,KAAM,CAAA,qCAAqC,CAAC,CAClE,CACJ","file":"index.cjs","sourcesContent":["import type { Errorable } from '@sqrzro/interfaces';\nimport { getFromObject } from '@sqrzro/utility';\n\ninterface PaginationArgs {\n skip: number;\n take: number;\n}\n\ninterface FindManyArgs extends PaginationArgs {\n orderBy: Record<string, string>;\n where: Record<string, string>;\n}\n\nconst DEFAULT_SORT = 'id';\nconst DEFAULT_DIR = 'asc';\nconst DEFAULT_PAGE = 1;\nconst DEFAULT_LIMIT = 10;\n\ninterface GetListArgs<T> {\n allowedFilters?: string[];\n fn: (args: FindManyArgs) => Promise<T[]>;\n searchParams?: Record<string, string>;\n}\n\nfunction createPaginationArgs(page): PaginationArgs {\n return { skip: (page - 1) * DEFAULT_LIMIT, take: DEFAULT_LIMIT };\n}\n\nfunction createFindManyArgs(\n searchParams?: Record<string, string>,\n allowedFilters: string[] = []\n): FindManyArgs {\n const { dir, page, sort, ...filters } = searchParams || {};\n\n return {\n ...createPaginationArgs(page ? parseInt(page, 10) : DEFAULT_PAGE),\n orderBy: { [sort || DEFAULT_SORT]: dir || DEFAULT_DIR },\n where: getFromObject(filters, allowedFilters),\n };\n}\n\nexport async function getList<T>({\n allowedFilters,\n fn,\n searchParams,\n}: GetListArgs<T>): Promise<Errorable<T[]>> {\n try {\n const args = createFindManyArgs(searchParams, allowedFilters);\n return [await fn(args), null];\n } catch (err) {\n if (err instanceof Error) {\n return [null, err];\n }\n return [null, new Error('[getList] An unknown error occurred')];\n }\n}\n"]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Errorable } from '@sqrzro/interfaces';
|
|
2
|
+
|
|
3
|
+
interface PaginationArgs {
|
|
4
|
+
skip: number;
|
|
5
|
+
take: number;
|
|
6
|
+
}
|
|
7
|
+
interface FindManyArgs extends PaginationArgs {
|
|
8
|
+
orderBy: Record<string, string>;
|
|
9
|
+
where: Record<string, string>;
|
|
10
|
+
}
|
|
11
|
+
interface GetListArgs<T> {
|
|
12
|
+
allowedFilters?: string[];
|
|
13
|
+
fn: (args: FindManyArgs) => Promise<T[]>;
|
|
14
|
+
searchParams?: Record<string, string>;
|
|
15
|
+
}
|
|
16
|
+
declare function getList<T>({ allowedFilters, fn, searchParams, }: GetListArgs<T>): Promise<Errorable<T[]>>;
|
|
17
|
+
|
|
18
|
+
export { getList };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Errorable } from '@sqrzro/interfaces';
|
|
2
|
+
|
|
3
|
+
interface PaginationArgs {
|
|
4
|
+
skip: number;
|
|
5
|
+
take: number;
|
|
6
|
+
}
|
|
7
|
+
interface FindManyArgs extends PaginationArgs {
|
|
8
|
+
orderBy: Record<string, string>;
|
|
9
|
+
where: Record<string, string>;
|
|
10
|
+
}
|
|
11
|
+
interface GetListArgs<T> {
|
|
12
|
+
allowedFilters?: string[];
|
|
13
|
+
fn: (args: FindManyArgs) => Promise<T[]>;
|
|
14
|
+
searchParams?: Record<string, string>;
|
|
15
|
+
}
|
|
16
|
+
declare function getList<T>({ allowedFilters, fn, searchParams, }: GetListArgs<T>): Promise<Errorable<T[]>>;
|
|
17
|
+
|
|
18
|
+
export { getList };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {getFromObject}from'@sqrzro/utility';var g="id",c="asc",A=1,s=10;function d(n){return {skip:(n-1)*s,take:s}}function u(n,t=[]){let{dir:e,page:r,sort:i,...o}=n||{};return {...d(r?parseInt(r,10):A),orderBy:{[i||g]:e||c},where:getFromObject(o,t)}}async function l({allowedFilters:n,fn:t,searchParams:e}){try{let r=u(e,n);return [await t(r),null]}catch(r){return r instanceof Error?[null,r]:[null,new Error("[getList] An unknown error occurred")]}}export{l as getList};//# sourceMappingURL=index.js.map
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/lists/ListService.ts"],"names":["DEFAULT_SORT","DEFAULT_DIR","DEFAULT_PAGE","DEFAULT_LIMIT","createPaginationArgs","page","createFindManyArgs","searchParams","allowedFilters","dir","sort","filters","getFromObject","getList","fn","args","err"],"mappings":"4CAaA,IAAMA,CAAAA,CAAe,IACfC,CAAAA,CAAAA,CAAc,KACdC,CAAAA,CAAAA,CAAe,CACfC,CAAAA,CAAAA,CAAgB,EAQtB,CAAA,SAASC,EAAqBC,CAAsB,CAAA,CAChD,OAAO,CAAE,IAAOA,CAAAA,CAAAA,CAAAA,CAAO,CAAKF,EAAAA,CAAAA,CAAe,IAAMA,CAAAA,CAAc,CACnE,CAEA,SAASG,CAAAA,CACLC,EACAC,CAA2B,CAAA,EACf,CAAA,CACZ,GAAM,CAAE,GAAAC,CAAAA,CAAAA,CAAK,IAAAJ,CAAAA,CAAAA,CAAM,IAAAK,CAAAA,CAAAA,CAAM,GAAGC,CAAQ,CAAIJ,CAAAA,CAAAA,EAAgB,EAAC,CAEzD,OAAO,CACH,GAAGH,CAAAA,CAAqBC,CAAO,CAAA,QAAA,CAASA,CAAM,CAAA,EAAE,CAAIH,CAAAA,CAAY,CAChE,CAAA,OAAA,CAAS,CAAE,CAACQ,CAAAA,EAAQV,CAAY,EAAGS,CAAOR,EAAAA,CAAY,CACtD,CAAA,KAAA,CAAOW,aAAcD,CAAAA,CAAAA,CAASH,CAAc,CAChD,CACJ,CAEA,eAAsBK,CAAW,CAAA,CAC7B,cAAAL,CAAAA,CAAAA,CACA,EAAAM,CAAAA,CAAAA,CACA,YAAAP,CAAAA,CACJ,CAA4C,CAAA,CACxC,GAAI,CACA,IAAMQ,CAAAA,CAAOT,EAAmBC,CAAcC,CAAAA,CAAc,CAC5D,CAAA,OAAO,CAAC,MAAMM,CAAGC,CAAAA,CAAI,CAAG,CAAA,IAAI,CAChC,CAAA,MAASC,CAAK,CAAA,CACV,OAAIA,CAAAA,YAAe,KACR,CAAA,CAAC,IAAMA,CAAAA,CAAG,CAEd,CAAA,CAAC,IAAM,CAAA,IAAI,KAAM,CAAA,qCAAqC,CAAC,CAClE,CACJ","file":"index.js","sourcesContent":["import type { Errorable } from '@sqrzro/interfaces';\nimport { getFromObject } from '@sqrzro/utility';\n\ninterface PaginationArgs {\n skip: number;\n take: number;\n}\n\ninterface FindManyArgs extends PaginationArgs {\n orderBy: Record<string, string>;\n where: Record<string, string>;\n}\n\nconst DEFAULT_SORT = 'id';\nconst DEFAULT_DIR = 'asc';\nconst DEFAULT_PAGE = 1;\nconst DEFAULT_LIMIT = 10;\n\ninterface GetListArgs<T> {\n allowedFilters?: string[];\n fn: (args: FindManyArgs) => Promise<T[]>;\n searchParams?: Record<string, string>;\n}\n\nfunction createPaginationArgs(page): PaginationArgs {\n return { skip: (page - 1) * DEFAULT_LIMIT, take: DEFAULT_LIMIT };\n}\n\nfunction createFindManyArgs(\n searchParams?: Record<string, string>,\n allowedFilters: string[] = []\n): FindManyArgs {\n const { dir, page, sort, ...filters } = searchParams || {};\n\n return {\n ...createPaginationArgs(page ? parseInt(page, 10) : DEFAULT_PAGE),\n orderBy: { [sort || DEFAULT_SORT]: dir || DEFAULT_DIR },\n where: getFromObject(filters, allowedFilters),\n };\n}\n\nexport async function getList<T>({\n allowedFilters,\n fn,\n searchParams,\n}: GetListArgs<T>): Promise<Errorable<T[]>> {\n try {\n const args = createFindManyArgs(searchParams, allowedFilters);\n return [await fn(args), null];\n } catch (err) {\n if (err instanceof Error) {\n return [null, err];\n }\n return [null, new Error('[getList] An unknown error occurred')];\n }\n}\n"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var m=require('stream');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var m__default=/*#__PURE__*/_interopDefault(m);function b(e,n){return {subject:e,template:n}}async function l(e){let n=(await import('react-dom/server')).default;return new Promise(s=>{let r=new m__default.default.Writable,t="";r._write=(a,c,i)=>{t+=a.toString(),i();};let{pipe:o}=n.renderToPipeableStream(e,{onShellReady:()=>{o(r),s(t);}});})}async function p(e,n){let{subject:s,template:r}=e,t=await r(n),o=await l(t);return {subject:s,html:o}}function g(){if(!process.env.MAIL_FROM)throw new Error("Mail from address has not been set");let e=/^(?<name>[^<]+)<(?<email>[^>]+)>$/u.exec(process.env.MAIL_FROM);if(!e?.groups?.name||!e?.groups?.email)throw new Error('Mail from address is not the correct format. It should be "Name <email>".');return {email:e.groups.email.trim(),name:e.groups.name.trim()}}async function u(e){if(!process.env.MAIL_API_KEY)throw new Error("Mail API key has not been set");let[n,s]=process.env.MAIL_API_KEY.split("."),r=Array.isArray(e.to)?e.to.map(t=>({email:t})):[{email:e.to}];try{return (await(await fetch(`https://sandbox.api.mailtrap.io/api/send/${n}`,{method:"POST",headers:{"Api-Token":s,"Content-Type":"application/json"},body:JSON.stringify({attachments:e.attachments,bcc:e.bcc?.map(a=>({email:a})),cc:e.cc?.map(a=>({email:a})),from:e.from,html:e.html,subject:e.subject,to:r})})).json()).success}catch{return !1}}async function h(e,n,s,r,t){if(!process.env.MAIL_API_KEY)throw new Error("Mail API key has not been set");let o=g(),{subject:a,html:c}=await p(e,n),i={attachments:t,bcc:r?.bcc,cc:r?.cc,from:o,html:c,subject:a,to:s};return u(i)}
|
|
2
|
+
exports.createMail=b;exports.getMail=p;exports.sendMail=h;//# sourceMappingURL=index.cjs.map
|
|
3
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/mail/MailService.ts"],"names":["createMail","subject","template","renderMail","element","ReactDOMServer","resolve","ws","stream","content","chunk","enc","next","pipe","getMail","mail","data","html","getSenderDetails","matches","sendDevelopmentMail","sendObject","id","key","to","email","sendMail","options","attachments","from"],"mappings":"qJASO,SAASA,CACZC,CAAAA,CAAAA,CACAC,EACa,CACb,OAAO,CAAE,OAAA,CAAAD,EAAS,QAAAC,CAAAA,CAAS,CAC/B,CAEA,eAAeC,CAAWC,CAAAA,CAAAA,CAA8C,CACpE,IAAMC,GAAkB,MAAM,OAAO,kBAAkB,CAAA,EAAG,QAE1D,OAAO,IAAI,OAASC,CAAAA,CAAAA,EAAY,CAC5B,IAAMC,CAAAA,CAAK,IAAIC,kBAAO,CAAA,QAAA,CAClBC,EAAU,EAEdF,CAAAA,CAAAA,CAAG,MAAS,CAAA,CACRG,EACAC,CACAC,CAAAA,CAAAA,GACO,CACPH,CAAAA,EAAWC,EAAM,QAAS,EAAA,CAC1BE,CAAK,GACT,EAEA,GAAM,CAAE,KAAAC,CAAK,CAAA,CAAIR,EAAe,sBAAuBD,CAAAA,CAAAA,CAAS,CAC5D,YAA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,CACJ,EAOA,OAAOJ,CAAAA,CAAoBC,CAAU,CACzC","file":"index.cjs","sourcesContent":["// import sgMail from '@sendgrid/mail';\n\nimport stream from 'node:stream';\n\nexport interface MailObject<T extends object> {\n subject: string;\n template: (data: T) => Promise<React.ReactElement> | React.ReactElement;\n}\n\nexport function createMail<T extends object>(\n subject: string,\n template: (data: T) => Promise<React.ReactElement> | React.ReactElement\n): MailObject<T> {\n return { subject, template };\n}\n\nasync function renderMail(element: React.ReactElement): Promise<string> {\n const ReactDOMServer = (await import('react-dom/server')).default;\n\n return new Promise((resolve) => {\n const ws = new stream.Writable();\n let content = '';\n\n ws._write = <T extends { toString: () => string }>( // eslint-disable-line no-underscore-dangle\n chunk: T,\n enc: BufferEncoding,\n next: (error?: Error | null) => void\n ): void => {\n content += chunk.toString();\n next();\n };\n\n const { pipe } = ReactDOMServer.renderToPipeableStream(element, {\n onShellReady: () => {\n pipe(ws);\n resolve(content);\n },\n });\n });\n}\n\nexport async function getMail<T extends object>(\n mail: MailObject<T>,\n data: T\n): Promise<{ subject: string; html: string }> {\n const { subject, template } = mail;\n\n const element = await template(data);\n const html = await renderMail(element);\n\n return {\n subject,\n html,\n };\n}\n\nfunction getSenderDetails(): { email: string; name: string } {\n if (!process.env.MAIL_FROM) {\n throw new Error('Mail from address has not been set');\n }\n\n const matches = /^(?<name>[^<]+)<(?<email>[^>]+)>$/u.exec(process.env.MAIL_FROM);\n\n if (!matches?.groups?.name || !matches?.groups?.email) {\n throw new Error(\n 'Mail from address is not the correct format. It should be \"Name <email>\".'\n );\n }\n\n return {\n email: matches.groups.email.trim(),\n name: matches.groups.name.trim(),\n };\n}\n\ninterface SendMailObject {\n attachments?: { content: string; filename: string; type: string }[];\n bcc?: string[];\n cc?: string[];\n from: { email: string; name: string };\n html: string;\n subject: string;\n to: string[] | string;\n}\n\nasync function sendDevelopmentMail(sendObject: SendMailObject): Promise<boolean> {\n if (!process.env.MAIL_API_KEY) {\n throw new Error('Mail API key has not been set');\n }\n\n /*\n * The account id and api key are both in the MAIL_API_KEY variable, separated by a `.`. We need\n * to split them.\n */\n\n const [id, key] = process.env.MAIL_API_KEY.split('.');\n\n const to = Array.isArray(sendObject.to)\n ? sendObject.to.map((email) => ({ email }))\n : [{ email: sendObject.to }];\n\n try {\n const response = await fetch(`https://sandbox.api.mailtrap.io/api/send/${id}`, {\n method: 'POST',\n headers: { 'Api-Token': key, 'Content-Type': 'application/json' },\n body: JSON.stringify({\n attachments: sendObject.attachments,\n bcc: sendObject.bcc?.map((email) => ({ email })),\n cc: sendObject.cc?.map((email) => ({ email })),\n from: sendObject.from,\n html: sendObject.html,\n subject: sendObject.subject,\n to,\n }),\n });\n const json = (await response.json()) as { success: boolean };\n return json.success;\n } catch (err) {\n return false;\n }\n}\n\n// async function sendProductionMail<T extends object>(\n// mail: Promise<MailFn<T>>,\n// data: T,\n// to: string\n// ): Promise<boolean> {\n// if (process.env.NODE_ENV === 'production') {\n// throw new Error('Trying to run production mail in a development environment');\n// }\n\n// if (!process.env.MAIL_ENABLE_PRODUCTION) {\n// throw new Error(\n// 'Mail has not been enabled in production. Please add MAIL_ENABLE_PRODUCTION to your environment variables.'\n// );\n// }\n\n// if (!process.env.MAIL_API_KEY) {\n// throw new Error('Mail API key has not been set');\n// }\n\n// sgMail.setApiKey(process.env.MAIL_API_KEY);\n\n// try {\n// const response = await sgMail.send({\n// to,\n// from,\n// subject,\n// html,\n// });\n// console.log(response);\n\n// return true;\n// } catch (err) {\n// console.log('err', err);\n// return false;\n// }\n// }\n\nexport async function sendMail<T extends object>(\n mail: MailObject<T>,\n data: T,\n to: string[] | string,\n options?: { cc?: string[]; bcc?: string[] },\n attachments?: { content: string; filename: string; type: string }[]\n): Promise<boolean> {\n if (!process.env.MAIL_API_KEY) {\n throw new Error('Mail API key has not been set');\n }\n\n const from = getSenderDetails();\n const { subject, html } = await getMail(mail, data);\n\n const sendObject: SendMailObject = {\n attachments,\n bcc: options?.bcc,\n cc: options?.cc,\n from,\n html,\n subject,\n to,\n };\n\n /*\n * For now, just send the email in development.\n * @TODO: Implement the production email sending.\n */\n\n return sendDevelopmentMail(sendObject);\n}\n"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
interface MailObject<T extends object> {
|
|
2
|
+
subject: string;
|
|
3
|
+
template: (data: T) => Promise<React.ReactElement> | React.ReactElement;
|
|
4
|
+
}
|
|
5
|
+
declare function createMail<T extends object>(subject: string, template: (data: T) => Promise<React.ReactElement> | React.ReactElement): MailObject<T>;
|
|
6
|
+
declare function getMail<T extends object>(mail: MailObject<T>, data: T): Promise<{
|
|
7
|
+
subject: string;
|
|
8
|
+
html: string;
|
|
9
|
+
}>;
|
|
10
|
+
declare function sendMail<T extends object>(mail: MailObject<T>, data: T, to: string[] | string, options?: {
|
|
11
|
+
cc?: string[];
|
|
12
|
+
bcc?: string[];
|
|
13
|
+
}, attachments?: {
|
|
14
|
+
content: string;
|
|
15
|
+
filename: string;
|
|
16
|
+
type: string;
|
|
17
|
+
}[]): Promise<boolean>;
|
|
18
|
+
|
|
19
|
+
export { type MailObject, createMail, getMail, sendMail };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
interface MailObject<T extends object> {
|
|
2
|
+
subject: string;
|
|
3
|
+
template: (data: T) => Promise<React.ReactElement> | React.ReactElement;
|
|
4
|
+
}
|
|
5
|
+
declare function createMail<T extends object>(subject: string, template: (data: T) => Promise<React.ReactElement> | React.ReactElement): MailObject<T>;
|
|
6
|
+
declare function getMail<T extends object>(mail: MailObject<T>, data: T): Promise<{
|
|
7
|
+
subject: string;
|
|
8
|
+
html: string;
|
|
9
|
+
}>;
|
|
10
|
+
declare function sendMail<T extends object>(mail: MailObject<T>, data: T, to: string[] | string, options?: {
|
|
11
|
+
cc?: string[];
|
|
12
|
+
bcc?: string[];
|
|
13
|
+
}, attachments?: {
|
|
14
|
+
content: string;
|
|
15
|
+
filename: string;
|
|
16
|
+
type: string;
|
|
17
|
+
}[]): Promise<boolean>;
|
|
18
|
+
|
|
19
|
+
export { type MailObject, createMail, getMail, sendMail };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import m from'stream';function b(e,n){return {subject:e,template:n}}async function l(e){let n=(await import('react-dom/server')).default;return new Promise(s=>{let r=new m.Writable,t="";r._write=(a,c,i)=>{t+=a.toString(),i();};let{pipe:o}=n.renderToPipeableStream(e,{onShellReady:()=>{o(r),s(t);}});})}async function p(e,n){let{subject:s,template:r}=e,t=await r(n),o=await l(t);return {subject:s,html:o}}function g(){if(!process.env.MAIL_FROM)throw new Error("Mail from address has not been set");let e=/^(?<name>[^<]+)<(?<email>[^>]+)>$/u.exec(process.env.MAIL_FROM);if(!e?.groups?.name||!e?.groups?.email)throw new Error('Mail from address is not the correct format. It should be "Name <email>".');return {email:e.groups.email.trim(),name:e.groups.name.trim()}}async function u(e){if(!process.env.MAIL_API_KEY)throw new Error("Mail API key has not been set");let[n,s]=process.env.MAIL_API_KEY.split("."),r=Array.isArray(e.to)?e.to.map(t=>({email:t})):[{email:e.to}];try{return (await(await fetch(`https://sandbox.api.mailtrap.io/api/send/${n}`,{method:"POST",headers:{"Api-Token":s,"Content-Type":"application/json"},body:JSON.stringify({attachments:e.attachments,bcc:e.bcc?.map(a=>({email:a})),cc:e.cc?.map(a=>({email:a})),from:e.from,html:e.html,subject:e.subject,to:r})})).json()).success}catch{return !1}}async function h(e,n,s,r,t){if(!process.env.MAIL_API_KEY)throw new Error("Mail API key has not been set");let o=g(),{subject:a,html:c}=await p(e,n),i={attachments:t,bcc:r?.bcc,cc:r?.cc,from:o,html:c,subject:a,to:s};return u(i)}
|
|
2
|
+
export{b as createMail,p as getMail,h as sendMail};//# sourceMappingURL=index.js.map
|
|
3
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/mail/MailService.ts"],"names":["createMail","subject","template","renderMail","element","ReactDOMServer","resolve","ws","stream","content","chunk","enc","next","pipe","getMail","mail","data","html","getSenderDetails","matches","sendDevelopmentMail","sendObject","id","key","to","email","sendMail","options","attachments","from"],"mappings":"sBASO,SAASA,CACZC,CAAAA,CAAAA,CACAC,EACa,CACb,OAAO,CAAE,OAAA,CAAAD,EAAS,QAAAC,CAAAA,CAAS,CAC/B,CAEA,eAAeC,CAAWC,CAAAA,CAAAA,CAA8C,CACpE,IAAMC,GAAkB,MAAM,OAAO,kBAAkB,CAAA,EAAG,QAE1D,OAAO,IAAI,OAASC,CAAAA,CAAAA,EAAY,CAC5B,IAAMC,CAAAA,CAAK,IAAIC,CAAO,CAAA,QAAA,CAClBC,EAAU,EAEdF,CAAAA,CAAAA,CAAG,MAAS,CAAA,CACRG,EACAC,CACAC,CAAAA,CAAAA,GACO,CACPH,CAAAA,EAAWC,EAAM,QAAS,EAAA,CAC1BE,CAAK,GACT,EAEA,GAAM,CAAE,KAAAC,CAAK,CAAA,CAAIR,EAAe,sBAAuBD,CAAAA,CAAAA,CAAS,CAC5D,YAAA,CAAc,IAAM,CAChBS,CAAAA,CAAKN,CAAE,CAAA,CACPD,EAAQG,CAAO,EACnB,CACJ,CAAC,EACL,CAAC,CACL,CAEA,eAAsBK,CAAAA,CAClBC,EACAC,CAC0C,CAAA,CAC1C,GAAM,CAAE,QAAAf,CAAS,CAAA,QAAA,CAAAC,CAAS,CAAA,CAAIa,EAExBX,CAAU,CAAA,MAAMF,CAASc,CAAAA,CAAI,EAC7BC,CAAO,CAAA,MAAMd,EAAWC,CAAO,CAAA,CAErC,OAAO,CACH,OAAA,CAAAH,CACA,CAAA,IAAA,CAAAgB,CACJ,CACJ,CAEA,SAASC,CAAAA,EAAoD,CACzD,GAAI,CAAC,OAAQ,CAAA,GAAA,CAAI,UACb,MAAM,IAAI,MAAM,oCAAoC,CAAA,CAGxD,IAAMC,CAAU,CAAA,oCAAA,CAAqC,IAAK,CAAA,OAAA,CAAQ,IAAI,SAAS,CAAA,CAE/E,GAAI,CAACA,GAAS,MAAQ,EAAA,IAAA,EAAQ,CAACA,CAA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CACJ,CAAC,CACL,CAAC,CAAA,EAC4B,MACjB,EAAA,OAChB,CAAc,KAAA,CACV,OAAO,CACX,CAAA,CACJ,CAuCA,eAAsBE,EAClBX,CACAC,CAAAA,CAAAA,CACAQ,CACAG,CAAAA,CAAAA,CACAC,EACgB,CAChB,GAAI,CAAC,OAAQ,CAAA,GAAA,CAAI,aACb,MAAM,IAAI,KAAM,CAAA,+BAA+B,EAGnD,IAAMC,CAAAA,CAAOX,CAAiB,EAAA,CACxB,CAAE,OAAAjB,CAAAA,CAAAA,CAAS,IAAAgB,CAAAA,CAAK,EAAI,MAAMH,CAAAA,CAAQC,EAAMC,CAAI,CAAA,CAE5CK,EAA6B,CAC/B,WAAA,CAAAO,CACA,CAAA,GAAA,CAAKD,GAAS,GACd,CAAA,EAAA,CAAIA,CAAS,EAAA,EAAA,CACb,KAAAE,CACA,CAAA,IAAA,CAAAZ,CACA,CAAA,OAAA,CAAAhB,EACA,EAAAuB,CAAAA,CACJ,EAOA,OAAOJ,CAAAA,CAAoBC,CAAU,CACzC","file":"index.js","sourcesContent":["// import sgMail from '@sendgrid/mail';\n\nimport stream from 'node:stream';\n\nexport interface MailObject<T extends object> {\n subject: string;\n template: (data: T) => Promise<React.ReactElement> | React.ReactElement;\n}\n\nexport function createMail<T extends object>(\n subject: string,\n template: (data: T) => Promise<React.ReactElement> | React.ReactElement\n): MailObject<T> {\n return { subject, template };\n}\n\nasync function renderMail(element: React.ReactElement): Promise<string> {\n const ReactDOMServer = (await import('react-dom/server')).default;\n\n return new Promise((resolve) => {\n const ws = new stream.Writable();\n let content = '';\n\n ws._write = <T extends { toString: () => string }>( // eslint-disable-line no-underscore-dangle\n chunk: T,\n enc: BufferEncoding,\n next: (error?: Error | null) => void\n ): void => {\n content += chunk.toString();\n next();\n };\n\n const { pipe } = ReactDOMServer.renderToPipeableStream(element, {\n onShellReady: () => {\n pipe(ws);\n resolve(content);\n },\n });\n });\n}\n\nexport async function getMail<T extends object>(\n mail: MailObject<T>,\n data: T\n): Promise<{ subject: string; html: string }> {\n const { subject, template } = mail;\n\n const element = await template(data);\n const html = await renderMail(element);\n\n return {\n subject,\n html,\n };\n}\n\nfunction getSenderDetails(): { email: string; name: string } {\n if (!process.env.MAIL_FROM) {\n throw new Error('Mail from address has not been set');\n }\n\n const matches = /^(?<name>[^<]+)<(?<email>[^>]+)>$/u.exec(process.env.MAIL_FROM);\n\n if (!matches?.groups?.name || !matches?.groups?.email) {\n throw new Error(\n 'Mail from address is not the correct format. It should be \"Name <email>\".'\n );\n }\n\n return {\n email: matches.groups.email.trim(),\n name: matches.groups.name.trim(),\n };\n}\n\ninterface SendMailObject {\n attachments?: { content: string; filename: string; type: string }[];\n bcc?: string[];\n cc?: string[];\n from: { email: string; name: string };\n html: string;\n subject: string;\n to: string[] | string;\n}\n\nasync function sendDevelopmentMail(sendObject: SendMailObject): Promise<boolean> {\n if (!process.env.MAIL_API_KEY) {\n throw new Error('Mail API key has not been set');\n }\n\n /*\n * The account id and api key are both in the MAIL_API_KEY variable, separated by a `.`. We need\n * to split them.\n */\n\n const [id, key] = process.env.MAIL_API_KEY.split('.');\n\n const to = Array.isArray(sendObject.to)\n ? sendObject.to.map((email) => ({ email }))\n : [{ email: sendObject.to }];\n\n try {\n const response = await fetch(`https://sandbox.api.mailtrap.io/api/send/${id}`, {\n method: 'POST',\n headers: { 'Api-Token': key, 'Content-Type': 'application/json' },\n body: JSON.stringify({\n attachments: sendObject.attachments,\n bcc: sendObject.bcc?.map((email) => ({ email })),\n cc: sendObject.cc?.map((email) => ({ email })),\n from: sendObject.from,\n html: sendObject.html,\n subject: sendObject.subject,\n to,\n }),\n });\n const json = (await response.json()) as { success: boolean };\n return json.success;\n } catch (err) {\n return false;\n }\n}\n\n// async function sendProductionMail<T extends object>(\n// mail: Promise<MailFn<T>>,\n// data: T,\n// to: string\n// ): Promise<boolean> {\n// if (process.env.NODE_ENV === 'production') {\n// throw new Error('Trying to run production mail in a development environment');\n// }\n\n// if (!process.env.MAIL_ENABLE_PRODUCTION) {\n// throw new Error(\n// 'Mail has not been enabled in production. Please add MAIL_ENABLE_PRODUCTION to your environment variables.'\n// );\n// }\n\n// if (!process.env.MAIL_API_KEY) {\n// throw new Error('Mail API key has not been set');\n// }\n\n// sgMail.setApiKey(process.env.MAIL_API_KEY);\n\n// try {\n// const response = await sgMail.send({\n// to,\n// from,\n// subject,\n// html,\n// });\n// console.log(response);\n\n// return true;\n// } catch (err) {\n// console.log('err', err);\n// return false;\n// }\n// }\n\nexport async function sendMail<T extends object>(\n mail: MailObject<T>,\n data: T,\n to: string[] | string,\n options?: { cc?: string[]; bcc?: string[] },\n attachments?: { content: string; filename: string; type: string }[]\n): Promise<boolean> {\n if (!process.env.MAIL_API_KEY) {\n throw new Error('Mail API key has not been set');\n }\n\n const from = getSenderDetails();\n const { subject, html } = await getMail(mail, data);\n\n const sendObject: SendMailObject = {\n attachments,\n bcc: options?.bcc,\n cc: options?.cc,\n from,\n html,\n subject,\n to,\n };\n\n /*\n * For now, just send the email in development.\n * @TODO: Implement the production email sending.\n */\n\n return sendDevelopmentMail(sendObject);\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var server=require('next/server');var c="/auth/login";function p(e){return e.headers.get("accept")==="application/json"}function r(e,t){return t.headers.set("x-origin",e.nextUrl.origin),t.headers.set("x-pathname",e.nextUrl.pathname),t.headers.set("x-search-params",e.nextUrl.searchParams.toString()),t}function x(e){return e.toString().replace(e.origin,"")}function o(e,t=c){return e.nextUrl.pathname===t?r(e,server.NextResponse.next()):r(e,p(e)?server.NextResponse.json({error:"Unauthorized"},{status:401}):server.NextResponse.redirect(`${e.nextUrl.origin}${t}?r=${encodeURIComponent(x(e.nextUrl))}`))}function l(){let e=new Headers;return process.env.VERCEL_AUTOMATION_BYPASS_SECRET&&e.append("x-vercel-protection-bypass",process.env.VERCEL_AUTOMATION_BYPASS_SECRET),{headers:e}}async function d(e,t){if(e.nextUrl.pathname==="/api/session")return r(e,t?t():server.NextResponse.next());let i=e.cookies.get(process.env.AUTH_COOKIE_NAME||"auth_session")?.value||"";try{let s=await(await fetch(`${e.nextUrl.origin}/api/session?id=${i}&pathname=${e.nextUrl.pathname}`,l())).json();return s.redirect===null?r(e,t?t():server.NextResponse.next()):o(e,s.redirect)}catch{return o(e)}}exports.handleMiddleware=d;//# sourceMappingURL=middleware.cjs.map
|
|
2
|
+
//# sourceMappingURL=middleware.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/middleware.ts"],"names":["DEFAULT_REDIRECT","isJsonRequest","request","applyHeaders","response","getRelativeUrl","url","redirect","pathname","NextResponse","bypassProtection","headers","handleMiddleware","nextFn","sessionID","json"],"mappings":"+CAGA,IAAMA,CAAAA,CAAmB,cAEzB,SAASC,CAAAA,CAAcC,CAA+B,CAAA,CAClD,OAAOA,CAAAA,CAAQ,QAAQ,GAAI,CAAA,QAAQ,CAAM,GAAA,kBAC7C,CAEA,SAASC,EAAaD,CAAsBE,CAAAA,CAAAA,CAAsC,CAC9E,OAAAA,CAAS,CAAA,OAAA,CAAQ,IAAI,UAAYF,CAAAA,CAAAA,CAAQ,OAAQ,CAAA,MAAM,CACvDE,CAAAA,CAAAA,CAAS,QAAQ,GAAI,CAAA,YAAA,CAAcF,CAAQ,CAAA,OAAA,CAAQ,QAAQ,CAAA,CAC3DE,EAAS,OAAQ,CAAA,GAAA,CAAI,iBAAmBF,CAAAA,CAAAA,CAAQ,OAAQ,CAAA,YAAA,CAAa,UAAU,CAAA,CACxEE,CACX,CAEA,SAASC,CAAAA,CAAeC,EAAqC,CACzD,OAAOA,CAAI,CAAA,QAAA,EAAW,CAAA,OAAA,CAAQA,EAAI,MAAQ,CAAA,EAAE,CAChD,CAEA,SAASC,CAAAA,CAASL,EAAsBM,CAAWR,CAAAA,CAAAA,CAAgC,CAC/E,OAAIE,CAAQ,CAAA,OAAA,CAAQ,WAAaM,CACtBL,CAAAA,CAAAA,CAAaD,CAASO,C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A,GAAa,IACXZ,CAAAA,CAAAA,CAAaD,EAASW,CAASA,CAAAA,CAAAA,EAAWJ,CAAAA,mBAAAA,CAAa,IAAK,EAAC,EAGjEF,CAASL,CAAAA,CAAAA,CAASa,CAAK,CAAA,QAAQ,CAC1C,CAAA,KAAc,CACV,OAAOR,CAAAA,CAASL,CAAO,CAC3B,CACJ","file":"middleware.cjs","sourcesContent":["import { NextResponse } from 'next/server';\nimport type { NextRequest } from 'next/server';\n\nconst DEFAULT_REDIRECT = '/auth/login';\n\nfunction isJsonRequest(request: NextRequest): boolean {\n return request.headers.get('accept') === 'application/json';\n}\n\nfunction applyHeaders(request: NextRequest, response: NextResponse): NextResponse {\n response.headers.set('x-origin', request.nextUrl.origin);\n response.headers.set('x-pathname', request.nextUrl.pathname);\n response.headers.set('x-search-params', request.nextUrl.searchParams.toString());\n return response;\n}\n\nfunction getRelativeUrl(url: NextRequest['nextUrl']): string {\n return url.toString().replace(url.origin, '');\n}\n\nfunction redirect(request: NextRequest, pathname = DEFAULT_REDIRECT): NextResponse {\n if (request.nextUrl.pathname === pathname) {\n return applyHeaders(request, NextResponse.next());\n }\n\n return applyHeaders(\n request,\n isJsonRequest(request)\n ? NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n : NextResponse.redirect(\n `${request.nextUrl.origin}${pathname}?r=${encodeURIComponent(\n getRelativeUrl(request.nextUrl)\n )}`\n )\n );\n}\n\n/*\n * When deployed to Vercel in a preview environment, we need to bypass the protection when fetching\n * the session from the API.\n */\nfunction bypassProtection(): RequestInit {\n const headers = new Headers();\n\n if (process.env.VERCEL_AUTOMATION_BYPASS_SECRET) {\n headers.append('x-vercel-protection-bypass', process.env.VERCEL_AUTOMATION_BYPASS_SECRET);\n }\n\n return { headers };\n}\n\nexport async function handleMiddleware(\n request: NextRequest,\n nextFn?: () => NextResponse\n): Promise<NextResponse> {\n // If the URL is /api/session, we should just return the response, otherwise we end up in a loop\n if (request.nextUrl.pathname === '/api/session') {\n return applyHeaders(request, nextFn ? nextFn() : NextResponse.next());\n }\n\n const sessionID =\n request.cookies.get(process.env.AUTH_COOKIE_NAME || 'auth_session')?.value || '';\n\n try {\n const session = await fetch(\n `${request.nextUrl.origin}/api/session?id=${sessionID}&pathname=${request.nextUrl.pathname}`,\n bypassProtection()\n );\n const json = (await session.json()) as { redirect: string | null };\n\n if (json.redirect === null) {\n return applyHeaders(request, nextFn ? nextFn() : NextResponse.next());\n }\n\n return redirect(request, json.redirect);\n } catch (err) {\n return redirect(request);\n }\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {NextResponse}from'next/server';var c="/auth/login";function p(e){return e.headers.get("accept")==="application/json"}function r(e,t){return t.headers.set("x-origin",e.nextUrl.origin),t.headers.set("x-pathname",e.nextUrl.pathname),t.headers.set("x-search-params",e.nextUrl.searchParams.toString()),t}function x(e){return e.toString().replace(e.origin,"")}function o(e,t=c){return e.nextUrl.pathname===t?r(e,NextResponse.next()):r(e,p(e)?NextResponse.json({error:"Unauthorized"},{status:401}):NextResponse.redirect(`${e.nextUrl.origin}${t}?r=${encodeURIComponent(x(e.nextUrl))}`))}function l(){let e=new Headers;return process.env.VERCEL_AUTOMATION_BYPASS_SECRET&&e.append("x-vercel-protection-bypass",process.env.VERCEL_AUTOMATION_BYPASS_SECRET),{headers:e}}async function d(e,t){if(e.nextUrl.pathname==="/api/session")return r(e,t?t():NextResponse.next());let i=e.cookies.get(process.env.AUTH_COOKIE_NAME||"auth_session")?.value||"";try{let s=await(await fetch(`${e.nextUrl.origin}/api/session?id=${i}&pathname=${e.nextUrl.pathname}`,l())).json();return s.redirect===null?r(e,t?t():NextResponse.next()):o(e,s.redirect)}catch{return o(e)}}export{d as handleMiddleware};//# sourceMappingURL=middleware.js.map
|
|
2
|
+
//# sourceMappingURL=middleware.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/middleware.ts"],"names":["DEFAULT_REDIRECT","isJsonRequest","request","applyHeaders","response","getR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MA,SAASQ,CAAAA,EAAgC,CACrC,IAAMC,CAAU,CAAA,IAAI,QAEpB,OAAI,OAAA,CAAQ,GAAI,CAAA,+BAAA,EACZA,CAAQ,CAAA,MAAA,CAAO,6BAA8B,OAAQ,CAAA,GAAA,CAAI,+BAA+B,CAAA,CAGrF,CAAE,OAAA,CAAAA,CAAQ,CACrB,CAEA,eAAsBC,CAAAA,CAClBV,CACAW,CAAAA,CAAAA,CACqB,CAErB,GAAIX,CAAAA,CAAQ,OAAQ,CAAA,QAAA,GAAa,cAC7B,CAAA,OAAOC,EAAaD,CAASW,CAAAA,CAAAA,CAASA,CAAO,EAAA,CAAIJ,YAAa,CAAA,IAAA,EAAM,CAGxE,CAAA,IAAMK,CACFZ,CAAAA,CAAAA,CAAQ,OAAQ,CAAA,GAAA,CAAI,QAAQ,GAAI,CAAA,gBAAA,EAAoB,cAAc,CAAA,EAAG,KAAS,EAAA,EAAA,CAElF,GAAI,CAKA,IAAMa,CAAQ,CAAA,KAAA,CAJE,MAAM,KAAA,CAClB,GAAGb,CAAQ,CAAA,OAAA,CAAQ,MAAM,CAAA,gBAAA,EAAmBY,CAAS,CAAA,UAAA,EAAaZ,EAAQ,OAAQ,CAAA,QAAQ,CAC1FQ,CAAAA,CAAAA,CAAAA,EACJ,CAAA,EAC4B,MAE5B,CAAA,OAAIK,CAAK,CAAA,QAAA,GAAa,IACXZ,CAAAA,CAAAA,CAAaD,EAASW,CAASA,CAAAA,CAAAA,EAAWJ,CAAAA,YAAAA,CAAa,IAAK,EAAC,EAGjEF,CAASL,CAAAA,CAAAA,CAASa,CAAK,CAAA,QAAQ,CAC1C,CAAA,KAAc,CACV,OAAOR,CAAAA,CAASL,CAAO,CAC3B,CACJ","file":"middleware.js","sourcesContent":["import { NextResponse } from 'next/server';\nimport type { NextRequest } from 'next/server';\n\nconst DEFAULT_REDIRECT = '/auth/login';\n\nfunction isJsonRequest(request: NextRequest): boolean {\n return request.headers.get('accept') === 'application/json';\n}\n\nfunction applyHeaders(request: NextRequest, response: NextResponse): NextResponse {\n response.headers.set('x-origin', request.nextUrl.origin);\n response.headers.set('x-pathname', request.nextUrl.pathname);\n response.headers.set('x-search-params', request.nextUrl.searchParams.toString());\n return response;\n}\n\nfunction getRelativeUrl(url: NextRequest['nextUrl']): string {\n return url.toString().replace(url.origin, '');\n}\n\nfunction redirect(request: NextRequest, pathname = DEFAULT_REDIRECT): NextResponse {\n if (request.nextUrl.pathname === pathname) {\n return applyHeaders(request, NextResponse.next());\n }\n\n return applyHeaders(\n request,\n isJsonRequest(request)\n ? NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n : NextResponse.redirect(\n `${request.nextUrl.origin}${pathname}?r=${encodeURIComponent(\n getRelativeUrl(request.nextUrl)\n )}`\n )\n );\n}\n\n/*\n * When deployed to Vercel in a preview environment, we need to bypass the protection when fetching\n * the session from the API.\n */\nfunction bypassProtection(): RequestInit {\n const headers = new Headers();\n\n if (process.env.VERCEL_AUTOMATION_BYPASS_SECRET) {\n headers.append('x-vercel-protection-bypass', process.env.VERCEL_AUTOMATION_BYPASS_SECRET);\n }\n\n return { headers };\n}\n\nexport async function handleMiddleware(\n request: NextRequest,\n nextFn?: () => NextResponse\n): Promise<NextResponse> {\n // If the URL is /api/session, we should just return the response, otherwise we end up in a loop\n if (request.nextUrl.pathname === '/api/session') {\n return applyHeaders(request, nextFn ? nextFn() : NextResponse.next());\n }\n\n const sessionID =\n request.cookies.get(process.env.AUTH_COOKIE_NAME || 'auth_session')?.value || '';\n\n try {\n const session = await fetch(\n `${request.nextUrl.origin}/api/session?id=${sessionID}&pathname=${request.nextUrl.pathname}`,\n bypassProtection()\n );\n const json = (await session.json()) as { redirect: string | null };\n\n if (json.redirect === null) {\n return applyHeaders(request, nextFn ? nextFn() : NextResponse.next());\n }\n\n return redirect(request, json.redirect);\n } catch (err) {\n return redirect(request);\n }\n}\n"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var headers=require('next/headers');async function s(){let t=process.env.SZ_ORIGIN;if(t)return t;let r=(await headers.headers()).get("x-origin");if(r)return r;let n=(await headers.headers()).get("x-forwarded-proto"),e=(await headers.headers()).get("x-forwarded-host");if(n&&e)return `${n}://${e}`;throw new Error("No origin could be determined")}async function u(){let t=(await headers.headers()).get("x-pathname");if(t)return t;throw new Error("No pathname could be determined. Please make sure middleware is being applied to the current request.")}async function a(t){let r=await s();if(!t)return r;let e=r.startsWith("https://")?"https://":"http://",i=`${r.replace(/^https?:\/\//u,"")}/${t}`.replace(/\/+/gu,"/");return `${e}${i}`}async function p(t){return a(t)}
|
|
2
|
+
exports.getOrigin=s;exports.getPathname=u;exports.getURL=p;exports.makeURL=a;//# sourceMappingURL=index.cjs.map
|
|
3
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/url/URLService.ts"],"names":["getOrigin","envOrigin","origin","headers","proto","host","getPathname","pathname","makeURL","protocol","cleanURL","getURL"],"mappings":"iDAkBA,eAAsBA,CAA6B,EAAA,CAC/C,IAAMC,CAAAA,CAAY,OAAQ,CAAA,GAAA,CAAI,SAE9B,CAAA,GAAIA,CACA,CAAA,OAAOA,CAGX,CAAA,IAAMC,CAAU,CAAA,CAAA,MAAMC,eAAQ,EAAA,EAAG,GAAI,CAAA,UAAU,CAE/C,CAAA,GAAID,CACA,CAAA,OAAOA,CAGX,CAAA,IAAME,GAAS,MAAMD,eAAAA,EAAW,EAAA,GAAA,CAAI,mBAAmB,CAAA,CACjDE,CAAQ,CAAA,CAAA,MAAMF,eAAQ,EAAA,EAAG,GAAI,CAAA,kBAAkB,CAErD,CAAA,GAAIC,CAASC,EAAAA,CAAAA,CACT,OAAO,CAAA,EAAGD,CAAK,CAAA,GAAA,EAAMC,CAAI,CAAA,CAAA,CAG7B,MAAM,IAAI,KAAM,CAAA,+BAA+B,CACnD,CAEA,eAAsBC,CAAAA,EAA+B,CACjD,IAAMC,GAAY,MAAMJ,eAAAA,EAAW,EAAA,GAAA,CAAI,YAAY,CAAA,CAEnD,GAAII,CAAAA,CACA,OAAOA,CAAAA,CAGX,MAAM,IAAI,KACN,CAAA,uGACJ,CACJ,CAUA,eAAsBC,CAAAA,CAAQD,CAAoC,CAAA,CAC9D,IAAML,CAAAA,CAAS,MAAMF,CAAAA,EAErB,CAAA,GAAI,CAACO,CAAAA,CACD,OAAOL,CAAAA,CAKX,IAAMO,CAAAA,CAFWP,EAAO,UAAW,CAAA,UAAU,CAEjB,CAAA,UAAA,CAAa,SAGnCQ,CAAAA,CAAAA,CAAW,CAFaR,EAAAA,CAAAA,CAAO,OAAQ,CAAA,eAAA,CAAiB,EAAE,CAEvB,CAAIK,CAAAA,EAAAA,CAAQ,CAAG,CAAA,CAAA,OAAA,CAAQ,OAAS,CAAA,GAAG,CAC5E,CAAA,OAAO,CAAGE,EAAAA,CAAQ,CAAGC,EAAAA,CAAQ,CACjC,CAAA,CAKA,eAAsBC,CAAAA,CAAOJ,CAAoC,CAAA,CAC7D,OAAOC,CAAAA,CAAQD,CAAQ,CAC3B","file":"index.cjs","sourcesContent":["import { headers } from 'next/headers';\n\n/**\n * Uses a number of methods to determine the current origin.\n *\n * First, it checks if an `x-origin` header. This will have been set by the `handleMiddleware`\n * function, further up the chain. For more information on how it is being set, see the\n * `middleware` documentation.\n *\n * There are some situations where middleware is not being applied, such as API routes (because the\n * redirection is not necessary, and API routes handle their own authentication). In these cases,\n * this function tries to piece together the origin from the `x-forwarded-proto` and\n * `x-forwarded-host` headers.\n *\n * Finally, if the origin cannot be determined, an error is thrown.\n *\n * @returns The origin of the current request.\n */\nexport async function getOrigin(): Promise<string> {\n const envOrigin = process.env.SZ_ORIGIN;\n\n if (envOrigin) {\n return envOrigin;\n }\n\n const origin = (await headers()).get('x-origin');\n\n if (origin) {\n return origin;\n }\n\n const proto = (await headers()).get('x-forwarded-proto');\n const host = (await headers()).get('x-forwarded-host');\n\n if (proto && host) {\n return `${proto}://${host}`;\n }\n\n throw new Error('No origin could be determined');\n}\n\nexport async function getPathname(): Promise<string> {\n const pathname = (await headers()).get('x-pathname');\n\n if (pathname) {\n return pathname;\n }\n\n throw new Error(\n 'No pathname could be determined. Please make sure middleware is being applied to the current request.'\n );\n}\n\n/**\n * Builds a URL from the current origin and a given pathname. For more information on how the origin\n * is determined, see the `getOrigin` function. This function then just concatenates the origin and\n * the pathname, and performs some cleanup to ensure the URL is valid.\n *\n * @param pathname\n * @returns The URL, with the origin and pathname combined.\n */\nexport async function makeURL(pathname?: string): Promise<string> {\n const origin = await getOrigin();\n\n if (!pathname) {\n return origin;\n }\n\n const isSecure = origin.startsWith('https://');\n\n const protocol = isSecure ? 'https://' : 'http://';\n const originWithoutProtocol = origin.replace(/^https?:\\/\\//u, '');\n\n const cleanURL = `${originWithoutProtocol}/${pathname}`.replace(/\\/+/gu, '/');\n return `${protocol}${cleanURL}`;\n}\n\n/**\n * @deprecated Use `makeURL` instead.\n */\nexport async function getURL(pathname?: string): Promise<string> {\n return makeURL(pathname);\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Uses a number of methods to determine the current origin.
|
|
3
|
+
*
|
|
4
|
+
* First, it checks if an `x-origin` header. This will have been set by the `handleMiddleware`
|
|
5
|
+
* function, further up the chain. For more information on how it is being set, see the
|
|
6
|
+
* `middleware` documentation.
|
|
7
|
+
*
|
|
8
|
+
* There are some situations where middleware is not being applied, such as API routes (because the
|
|
9
|
+
* redirection is not necessary, and API routes handle their own authentication). In these cases,
|
|
10
|
+
* this function tries to piece together the origin from the `x-forwarded-proto` and
|
|
11
|
+
* `x-forwarded-host` headers.
|
|
12
|
+
*
|
|
13
|
+
* Finally, if the origin cannot be determined, an error is thrown.
|
|
14
|
+
*
|
|
15
|
+
* @returns The origin of the current request.
|
|
16
|
+
*/
|
|
17
|
+
declare function getOrigin(): Promise<string>;
|
|
18
|
+
declare function getPathname(): Promise<string>;
|
|
19
|
+
/**
|
|
20
|
+
* Builds a URL from the current origin and a given pathname. For more information on how the origin
|
|
21
|
+
* is determined, see the `getOrigin` function. This function then just concatenates the origin and
|
|
22
|
+
* the pathname, and performs some cleanup to ensure the URL is valid.
|
|
23
|
+
*
|
|
24
|
+
* @param pathname
|
|
25
|
+
* @returns The URL, with the origin and pathname combined.
|
|
26
|
+
*/
|
|
27
|
+
declare function makeURL(pathname?: string): Promise<string>;
|
|
28
|
+
/**
|
|
29
|
+
* @deprecated Use `makeURL` instead.
|
|
30
|
+
*/
|
|
31
|
+
declare function getURL(pathname?: string): Promise<string>;
|
|
32
|
+
|
|
33
|
+
export { getOrigin, getPathname, getURL, makeURL };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Uses a number of methods to determine the current origin.
|
|
3
|
+
*
|
|
4
|
+
* First, it checks if an `x-origin` header. This will have been set by the `handleMiddleware`
|
|
5
|
+
* function, further up the chain. For more information on how it is being set, see the
|
|
6
|
+
* `middleware` documentation.
|
|
7
|
+
*
|
|
8
|
+
* There are some situations where middleware is not being applied, such as API routes (because the
|
|
9
|
+
* redirection is not necessary, and API routes handle their own authentication). In these cases,
|
|
10
|
+
* this function tries to piece together the origin from the `x-forwarded-proto` and
|
|
11
|
+
* `x-forwarded-host` headers.
|
|
12
|
+
*
|
|
13
|
+
* Finally, if the origin cannot be determined, an error is thrown.
|
|
14
|
+
*
|
|
15
|
+
* @returns The origin of the current request.
|
|
16
|
+
*/
|
|
17
|
+
declare function getOrigin(): Promise<string>;
|
|
18
|
+
declare function getPathname(): Promise<string>;
|
|
19
|
+
/**
|
|
20
|
+
* Builds a URL from the current origin and a given pathname. For more information on how the origin
|
|
21
|
+
* is determined, see the `getOrigin` function. This function then just concatenates the origin and
|
|
22
|
+
* the pathname, and performs some cleanup to ensure the URL is valid.
|
|
23
|
+
*
|
|
24
|
+
* @param pathname
|
|
25
|
+
* @returns The URL, with the origin and pathname combined.
|
|
26
|
+
*/
|
|
27
|
+
declare function makeURL(pathname?: string): Promise<string>;
|
|
28
|
+
/**
|
|
29
|
+
* @deprecated Use `makeURL` instead.
|
|
30
|
+
*/
|
|
31
|
+
declare function getURL(pathname?: string): Promise<string>;
|
|
32
|
+
|
|
33
|
+
export { getOrigin, getPathname, getURL, makeURL };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {headers}from'next/headers';async function s(){let t=process.env.SZ_ORIGIN;if(t)return t;let r=(await headers()).get("x-origin");if(r)return r;let n=(await headers()).get("x-forwarded-proto"),e=(await headers()).get("x-forwarded-host");if(n&&e)return `${n}://${e}`;throw new Error("No origin could be determined")}async function u(){let t=(await headers()).get("x-pathname");if(t)return t;throw new Error("No pathname could be determined. Please make sure middleware is being applied to the current request.")}async function a(t){let r=await s();if(!t)return r;let e=r.startsWith("https://")?"https://":"http://",i=`${r.replace(/^https?:\/\//u,"")}/${t}`.replace(/\/+/gu,"/");return `${e}${i}`}async function p(t){return a(t)}
|
|
2
|
+
export{s as getOrigin,u as getPathname,p as getURL,a as makeURL};//# sourceMappingURL=index.js.map
|
|
3
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/url/URLService.ts"],"names":["getOrigin","envOrigin","origin","headers","proto","host","getPathname","pathname","makeURL","protocol","cleanURL","getURL"],"mappings":"mCAkBA,eAAsBA,CAA6B,EAAA,CAC/C,IAAMC,CAAAA,CAAY,OAAQ,CAAA,GAAA,CAAI,SAE9B,CAAA,GAAIA,CACA,CAAA,OAAOA,CAGX,CAAA,IAAMC,CAAU,CAAA,CAAA,MAAMC,OAAQ,EAAA,EAAG,GAAI,CAAA,UAAU,CAE/C,CAAA,GAAID,CACA,CAAA,OAAOA,CAGX,CAAA,IAAME,GAAS,MAAMD,OAAAA,EAAW,EAAA,GAAA,CAAI,mBAAmB,CAAA,CACjDE,CAAQ,CAAA,CAAA,MAAMF,OAAQ,EAAA,EAAG,GAAI,CAAA,kBAAkB,CAErD,CAAA,GAAIC,CAASC,EAAAA,CAAAA,CACT,OAAO,CAAA,EAAGD,CAAK,CAAA,GAAA,EAAMC,CAAI,CAAA,CAAA,CAG7B,MAAM,IAAI,KAAM,CAAA,+BAA+B,CACnD,CAEA,eAAsBC,CAAAA,EAA+B,CACjD,IAAMC,GAAY,MAAMJ,OAAAA,EAAW,EAAA,GAAA,CAAI,YAAY,CAAA,CAEnD,GAAII,CAAAA,CACA,OAAOA,CAAAA,CAGX,MAAM,IAAI,KACN,CAAA,uGACJ,CACJ,CAUA,eAAsBC,CAAAA,CAAQD,CAAoC,CAAA,CAC9D,IAAML,CAAAA,CAAS,MAAMF,CAAAA,EAErB,CAAA,GAAI,CAACO,CAAAA,CACD,OAAOL,CAAAA,CAKX,IAAMO,CAAAA,CAFWP,EAAO,UAAW,CAAA,UAAU,CAEjB,CAAA,UAAA,CAAa,SAGnCQ,CAAAA,CAAAA,CAAW,CAFaR,EAAAA,CAAAA,CAAO,OAAQ,CAAA,eAAA,CAAiB,EAAE,CAEvB,CAAIK,CAAAA,EAAAA,CAAQ,CAAG,CAAA,CAAA,OAAA,CAAQ,OAAS,CAAA,GAAG,CAC5E,CAAA,OAAO,CAAGE,EAAAA,CAAQ,CAAGC,EAAAA,CAAQ,CACjC,CAAA,CAKA,eAAsBC,CAAAA,CAAOJ,CAAoC,CAAA,CAC7D,OAAOC,CAAAA,CAAQD,CAAQ,CAC3B","file":"index.js","sourcesContent":["import { headers } from 'next/headers';\n\n/**\n * Uses a number of methods to determine the current origin.\n *\n * First, it checks if an `x-origin` header. This will have been set by the `handleMiddleware`\n * function, further up the chain. For more information on how it is being set, see the\n * `middleware` documentation.\n *\n * There are some situations where middleware is not being applied, such as API routes (because the\n * redirection is not necessary, and API routes handle their own authentication). In these cases,\n * this function tries to piece together the origin from the `x-forwarded-proto` and\n * `x-forwarded-host` headers.\n *\n * Finally, if the origin cannot be determined, an error is thrown.\n *\n * @returns The origin of the current request.\n */\nexport async function getOrigin(): Promise<string> {\n const envOrigin = process.env.SZ_ORIGIN;\n\n if (envOrigin) {\n return envOrigin;\n }\n\n const origin = (await headers()).get('x-origin');\n\n if (origin) {\n return origin;\n }\n\n const proto = (await headers()).get('x-forwarded-proto');\n const host = (await headers()).get('x-forwarded-host');\n\n if (proto && host) {\n return `${proto}://${host}`;\n }\n\n throw new Error('No origin could be determined');\n}\n\nexport async function getPathname(): Promise<string> {\n const pathname = (await headers()).get('x-pathname');\n\n if (pathname) {\n return pathname;\n }\n\n throw new Error(\n 'No pathname could be determined. Please make sure middleware is being applied to the current request.'\n );\n}\n\n/**\n * Builds a URL from the current origin and a given pathname. For more information on how the origin\n * is determined, see the `getOrigin` function. This function then just concatenates the origin and\n * the pathname, and performs some cleanup to ensure the URL is valid.\n *\n * @param pathname\n * @returns The URL, with the origin and pathname combined.\n */\nexport async function makeURL(pathname?: string): Promise<string> {\n const origin = await getOrigin();\n\n if (!pathname) {\n return origin;\n }\n\n const isSecure = origin.startsWith('https://');\n\n const protocol = isSecure ? 'https://' : 'http://';\n const originWithoutProtocol = origin.replace(/^https?:\\/\\//u, '');\n\n const cleanURL = `${originWithoutProtocol}/${pathname}`.replace(/\\/+/gu, '/');\n return `${protocol}${cleanURL}`;\n}\n\n/**\n * @deprecated Use `makeURL` instead.\n */\nexport async function getURL(pathname?: string): Promise<string> {\n return makeURL(pathname);\n}\n"]}
|
package/forms.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export * from './dist/forms/index';
|
package/jest.config.js
ADDED
package/lists.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export * from './dist/lists/index';
|
package/mail.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export * from './dist/mail/index';
|
package/middleware.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export * from './dist/middleware';
|
package/next-env.d.ts
ADDED
package/package.json
CHANGED
|
@@ -1,65 +1,97 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sqrzro/server",
|
|
3
|
-
"version": "2.0.0-
|
|
3
|
+
"version": "2.0.0-r19.1",
|
|
4
|
+
"type": "module",
|
|
4
5
|
"main": "dist/index.js",
|
|
5
6
|
"types": "dist/index.d.ts",
|
|
6
7
|
"license": "ISC",
|
|
8
|
+
"exports": {
|
|
9
|
+
"./auth": {
|
|
10
|
+
"types": "./dist/auth/index.d.ts",
|
|
11
|
+
"import": "./dist/auth/index.js",
|
|
12
|
+
"require": "./dist/auth/index.cjs"
|
|
13
|
+
},
|
|
14
|
+
"./cache": {
|
|
15
|
+
"types": "./dist/cache/index.d.ts",
|
|
16
|
+
"import": "./dist/cache/index.js",
|
|
17
|
+
"require": "./dist/cache/index.cjs"
|
|
18
|
+
},
|
|
19
|
+
"./forms": {
|
|
20
|
+
"types": "./dist/forms/index.d.ts",
|
|
21
|
+
"import": "./dist/forms/index.js",
|
|
22
|
+
"require": "./dist/forms/index.cjs"
|
|
23
|
+
},
|
|
24
|
+
"./lists": {
|
|
25
|
+
"types": "./dist/lists/index.d.ts",
|
|
26
|
+
"import": "./dist/lists/index.js",
|
|
27
|
+
"require": "./dist/lists/index.cjs"
|
|
28
|
+
},
|
|
29
|
+
"./mail": {
|
|
30
|
+
"types": "./dist/mail/index.d.ts",
|
|
31
|
+
"import": "./dist/mail/index.js",
|
|
32
|
+
"require": "./dist/mail/index.cjs"
|
|
33
|
+
},
|
|
34
|
+
"./middleware": {
|
|
35
|
+
"types": "./dist/middleware.d.ts",
|
|
36
|
+
"import": "./dist/middleware.js",
|
|
37
|
+
"require": "./dist/middleware.cjs"
|
|
38
|
+
},
|
|
39
|
+
"./schema": {
|
|
40
|
+
"types": "./dist/database/schema.d.ts",
|
|
41
|
+
"import": "./dist/database/schema.js",
|
|
42
|
+
"require": "./dist/database/schema.cjs"
|
|
43
|
+
},
|
|
44
|
+
"./url": {
|
|
45
|
+
"types": "./dist/url/index.d.ts",
|
|
46
|
+
"import": "./dist/url/index.js",
|
|
47
|
+
"require": "./dist/url/index.cjs"
|
|
48
|
+
}
|
|
49
|
+
},
|
|
7
50
|
"files": [
|
|
8
|
-
"
|
|
9
|
-
"
|
|
10
|
-
"
|
|
11
|
-
"cache.js",
|
|
12
|
-
"database.d.ts",
|
|
13
|
-
"database.js",
|
|
14
|
-
"forms.d.ts",
|
|
15
|
-
"forms.js",
|
|
16
|
-
"lists.d.ts",
|
|
17
|
-
"lists.js",
|
|
18
|
-
"mail.d.ts",
|
|
19
|
-
"mail.js",
|
|
20
|
-
"middleware.d.ts",
|
|
21
|
-
"middleware.js",
|
|
22
|
-
"schema.d.ts",
|
|
23
|
-
"schema.js",
|
|
24
|
-
"url.d.ts",
|
|
25
|
-
"url.js"
|
|
51
|
+
"dist/**/*",
|
|
52
|
+
"*.js",
|
|
53
|
+
"*.d.ts"
|
|
26
54
|
],
|
|
27
55
|
"dependencies": {
|
|
28
|
-
"@lucia-auth/adapter-drizzle": "^1.0
|
|
29
|
-
"@
|
|
30
|
-
"@sqrzro/
|
|
56
|
+
"@lucia-auth/adapter-drizzle": "^1.1.0",
|
|
57
|
+
"@sendgrid/mail": "^8.1.4",
|
|
58
|
+
"@sqrzro/interfaces": "r19",
|
|
59
|
+
"@sqrzro/utility": "r19",
|
|
31
60
|
"bcryptjs": "^2.4.3",
|
|
32
|
-
"drizzle-orm": "^0.
|
|
33
|
-
"joi": "^17.
|
|
34
|
-
"
|
|
35
|
-
"
|
|
36
|
-
"next": "^14.0.0",
|
|
61
|
+
"drizzle-orm": "^0.38.3",
|
|
62
|
+
"joi": "^17.13.3",
|
|
63
|
+
"lucia": "^3.2.2",
|
|
64
|
+
"next": "^15.1.3",
|
|
37
65
|
"otplib": "^12.0.1",
|
|
38
|
-
"
|
|
39
|
-
"
|
|
40
|
-
"
|
|
41
|
-
"
|
|
66
|
+
"path-to-regexp": "^6.3.0",
|
|
67
|
+
"postgres": "^3.4.5",
|
|
68
|
+
"qrcode": "^1.5.4",
|
|
69
|
+
"react": "^19.0.0",
|
|
70
|
+
"react-dom": "^19.0.0",
|
|
71
|
+
"redis": "^4.7.0"
|
|
42
72
|
},
|
|
43
73
|
"devDependencies": {
|
|
44
|
-
"@sqrzro/eslint-plugin": "
|
|
45
|
-
"@sqrzro/prettier-config": "
|
|
74
|
+
"@sqrzro/eslint-plugin": "r19",
|
|
75
|
+
"@sqrzro/prettier-config": "r19",
|
|
46
76
|
"@types/bcryptjs": "^2.4.6",
|
|
47
|
-
"@types/jest": "^29.5.
|
|
77
|
+
"@types/jest": "^29.5.14",
|
|
78
|
+
"@types/node": "^22.10.5",
|
|
48
79
|
"@types/qrcode": "^1.5.5",
|
|
49
|
-
"@types/react
|
|
50
|
-
"
|
|
80
|
+
"@types/react": "^19.0.2",
|
|
81
|
+
"@types/react-dom": "^19.0.0",
|
|
82
|
+
"eslint": "^8.57.1",
|
|
51
83
|
"jest": "^29.7.0",
|
|
52
|
-
"
|
|
53
|
-
"
|
|
54
|
-
"
|
|
55
|
-
"
|
|
56
|
-
"
|
|
57
|
-
"typescript": "^5.
|
|
84
|
+
"prettier": "^3.4.2",
|
|
85
|
+
"rimraf": "^4.4.1",
|
|
86
|
+
"ts-jest": "^29.2.5",
|
|
87
|
+
"tslib": "^2.8.1",
|
|
88
|
+
"tsup": "^8.3.5",
|
|
89
|
+
"typescript": "^5.7.2"
|
|
58
90
|
},
|
|
59
91
|
"scripts": {
|
|
60
|
-
"build": "pnpm clean &&
|
|
92
|
+
"build": "pnpm clean && tsup",
|
|
61
93
|
"clean": "rimraf ./dist",
|
|
62
|
-
"dev": "
|
|
94
|
+
"dev": "tsup --watch",
|
|
63
95
|
"lint": "tsc --noEmit && eslint \"./src/**/*.ts\"",
|
|
64
96
|
"prettier": "prettier --write \"./src/**/*.ts\"",
|
|
65
97
|
"start": "pnpm dev",
|
package/schema.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export * from './dist/database/schema';
|
package/url.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export * from './dist/url/index';
|
package/database.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './dist/database/index';
|
package/database.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
module.exports = require('./dist/database/index');
|