@instincthub/react-ui 0.3.3 → 0.5.0
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/README.md +3 -11
- package/dist/src/components/forms/uploads/FileUploader.cjs +1 -1
- package/dist/src/components/forms/uploads/FileUploader.js +1 -1
- package/dist/src/components/forms/uploads/IhubFileUploader.cjs +1 -1
- package/dist/src/components/forms/uploads/IhubFileUploader.js +1 -1
- package/dist/src/components/forms/uploads/S3MultiUploader.cjs +1 -1
- package/dist/src/components/forms/uploads/S3MultiUploader.js +1 -1
- package/dist/src/components/forms/uploads/presignedPut.cjs +2 -0
- package/dist/src/components/forms/uploads/presignedPut.cjs.map +1 -0
- package/dist/src/components/forms/uploads/presignedPut.js +2 -0
- package/dist/src/components/forms/uploads/presignedPut.js.map +1 -0
- package/dist/src/components/lib/index.cjs +1 -1
- package/dist/src/components/lib/index.cjs.map +1 -1
- package/dist/src/components/lib/index.js +1 -1
- package/dist/src/components/lib/index.js.map +1 -1
- package/dist/src/components/lib/paystack.cjs +1 -1
- package/dist/src/components/lib/paystack.cjs.map +1 -1
- package/dist/src/components/lib/paystack.js +1 -1
- package/dist/src/components/lib/paystack.js.map +1 -1
- package/dist/src/components/ui/ComponentLists.cjs +1 -1
- package/dist/src/components/ui/ComponentLists.js +1 -1
- package/dist/src/components/ui/editor/ihub-editor/types.cjs.map +1 -1
- package/dist/src/components/ui/editor/ihub-editor/types.js.map +1 -1
- package/dist/src/components/ui/editor/ihub-editor/upload/uploadFile.cjs +1 -1
- package/dist/src/components/ui/editor/ihub-editor/upload/uploadFile.cjs.map +1 -1
- package/dist/src/components/ui/editor/ihub-editor/upload/uploadFile.js +1 -1
- package/dist/src/components/ui/editor/ihub-editor/upload/uploadFile.js.map +1 -1
- package/dist/src/types/components/forms/uploads/FileUploader.d.ts +9 -2
- package/dist/src/types/components/forms/uploads/IhubFileUploader.d.ts +6 -3
- package/dist/src/types/components/forms/uploads/presignedPut.d.ts +13 -0
- package/dist/src/types/components/lib/paystack.d.ts +48 -12
- package/dist/src/types/components/ui/editor/ihub-editor/types.d.ts +3 -10
- package/dist/src/types/types/index.d.ts +39 -4
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +1 -3
- package/dist/src/components/forms/uploads/uploadedFileUrl.cjs +0 -2
- package/dist/src/components/forms/uploads/uploadedFileUrl.cjs.map +0 -1
- package/dist/src/components/forms/uploads/uploadedFileUrl.js +0 -2
- package/dist/src/components/forms/uploads/uploadedFileUrl.js.map +0 -1
- package/dist/src/components/ui/editor/ihub-editor/upload/s3Direct.cjs +0 -2
- package/dist/src/components/ui/editor/ihub-editor/upload/s3Direct.cjs.map +0 -1
- package/dist/src/components/ui/editor/ihub-editor/upload/s3Direct.js +0 -2
- package/dist/src/components/ui/editor/ihub-editor/upload/s3Direct.js.map +0 -1
- package/dist/src/types/components/ui/editor/ihub-editor/upload/s3Direct.d.ts +0 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uploadFile.cjs","sources":["../../../../../../../src/components/ui/editor/ihub-editor/upload/uploadFile.ts"],"sourcesContent":["import { reqOptions } from \"../../../../lib/helpFunction\";\nimport type {\n FileUploadHandler,\n IHubEditorUploadConfig,\n MediaKind,\n UploadedFileResult,\n} from \"../types\";\nimport { DEFAULT_MAX_SIZE_MB, KIND_LABEL } from \"./mediaKinds\";\nimport { directS3Upload, isDirectS3Configured } from \"./s3Direct\";\n\nexport type EditorUploader = (\n file: File,\n kind: MediaKind,\n onProgress?: (percent: number) => void\n) => Promise<UploadedFileResult>;\n\nexport interface UploaderSources {\n onFileUpload?: FileUploadHandler;\n onImageUpload?: (file: File) => Promise<string>;\n upload?: IHubEditorUploadConfig;\n}\n\nexport class UploadNotConfiguredError extends Error {\n constructor() {\n super(\"Uploads are not configured for this editor. Paste a link instead.\");\n this.name = \"UploadNotConfiguredError\";\n }\n}\n\nconst PRESIGN_ENV = process.env.NEXT_PUBLIC_IHUB_EDITOR_PRESIGN_URL || \"\";\nconst ENDPOINT_ENV = process.env.NEXT_PUBLIC_IHUB_EDITOR_UPLOAD_URL || \"\";\nconst DIRECT_S3_ENV = process.env.NEXT_PUBLIC_IHUB_EDITOR_DIRECT_S3 === \"true\";\n\n/** Direct browser → S3 exposes the secret key, so it only runs when explicitly enabled. */\nfunction directS3Enabled(config: IHubEditorUploadConfig): boolean {\n const optedIn = config.directS3 ?? DIRECT_S3_ENV;\n return optedIn === true && isDirectS3Configured();\n}\n\nconst URL_KEYS = [\"url\", \"cdnUrl\", \"cdn_url\", \"location\", \"file_url\", \"file\", \"src\"];\n\n/** Find the uploaded file's URL in an arbitrary API response. */\nexport function extractUrl(payload: unknown): string | null {\n if (!payload) return null;\n if (typeof payload === \"string\") return /^(https?:)?\\/\\//.test(payload) ? payload : null;\n if (typeof payload !== \"object\") return null;\n const record = payload as Record<string, unknown>;\n for (const key of URL_KEYS) {\n const value = record[key];\n if (typeof value === \"string\" && value) return value;\n }\n for (const nested of [\"data\", \"result\", \"file\"]) {\n if (record[nested] && typeof record[nested] === \"object\") {\n const found = extractUrl(record[nested]);\n if (found) return found;\n }\n }\n return null;\n}\n\nexport function validateFileSize(file: File, kind: MediaKind, config?: IHubEditorUploadConfig): void {\n const limit = config?.maxSizeMB?.[kind] ?? DEFAULT_MAX_SIZE_MB[kind];\n if (limit > 0 && file.size > limit * 1024 * 1024) {\n throw new Error(`This ${KIND_LABEL[kind]} is larger than the ${limit} MB limit.`);\n }\n}\n\nfunction normaliseResult(result: string | UploadedFileResult, file: File): UploadedFileResult {\n const base = typeof result === \"string\" ? { url: result } : result;\n if (!base?.url) throw new Error(\"The upload handler did not return a URL.\");\n return { name: file.name, size: file.size, mime: file.type, ...base };\n}\n\n/** XHR wrapper so uploads can report real progress. */\nexport function sendWithProgress(\n method: string,\n url: string,\n body: Document | XMLHttpRequestBodyInit,\n headers: Record<string, string>,\n onProgress?: (percent: number) => void\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.upload.onprogress = (event) => {\n if (event.lengthComputable) onProgress?.(Math.round((event.loaded / event.total) * 100));\n };\n xhr.onload = () => {\n if (xhr.status >= 200 && xhr.status < 300) resolve(xhr.responseText);\n else reject(new Error(`Upload failed (HTTP ${xhr.status}).`));\n };\n xhr.onerror = () => reject(new Error(\"Network error during upload.\"));\n xhr.ontimeout = () => reject(new Error(\"Upload timed out.\"));\n xhr.open(method, url);\n Object.entries(headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));\n xhr.send(body);\n });\n}\n\nasync function uploadViaPresign(\n file: File,\n kind: MediaKind,\n config: IHubEditorUploadConfig,\n presignUrl: string,\n onProgress?: (percent: number) => void\n): Promise<UploadedFileResult> {\n let presign = config.getPresignedUrl ? await config.getPresignedUrl(file, kind) : null;\n if (!presign) {\n const body = JSON.stringify({ filename: file.name, content_type: file.type, size: file.size, kind });\n const res = await fetch(presignUrl, reqOptions(\"POST\", body, config.token ?? null, \"json\", config.channel ?? null) as RequestInit);\n if (!res.ok) throw new Error(`Could not get an upload URL (HTTP ${res.status}).`);\n presign = await res.json();\n }\n if (!presign?.url || !presign.cdnUrl) throw new Error(\"The presign response is missing url or cdnUrl.\");\n const contentType = presign.contentType || file.type || \"application/octet-stream\";\n const extra = Object.fromEntries(\n Object.entries(presign.headers || {}).filter(([name]) => name.toLowerCase() !== \"content-type\")\n );\n await sendWithProgress(\"PUT\", presign.url, file, { \"Content-Type\": contentType, ...extra }, onProgress);\n return { url: presign.cdnUrl, name: file.name, size: file.size, mime: contentType };\n}\n\nasync function uploadViaEndpoint(\n file: File,\n kind: MediaKind,\n config: IHubEditorUploadConfig,\n endpoint: string,\n onProgress?: (percent: number) => void\n): Promise<UploadedFileResult> {\n const form = new FormData();\n form.append(config.fieldName || \"file\", file);\n form.append(\"name\", file.name);\n form.append(\"kind\", kind);\n Object.entries(config.extraFields || {}).forEach(([key, value]) => form.append(key, value));\n const { headers } = reqOptions(\"POST\", form, config.token ?? null, false, config.channel ?? null) as {\n headers: Record<string, string>;\n };\n const text = await sendWithProgress(\"POST\", endpoint, form, headers || {}, onProgress);\n let payload: unknown = text;\n try {\n payload = JSON.parse(text);\n } catch {\n // plain-text response: treat as URL below\n }\n const url = extractUrl(payload);\n if (!url) throw new Error(\"The upload endpoint response did not include a file URL.\");\n return { url, name: file.name, size: file.size, mime: file.type };\n}\n\n/** Build the uploader used by every media block, following the documented resolution order. */\nexport function createUploader(sources: UploaderSources): EditorUploader {\n return async (file, kind, onProgress) => {\n const config = sources.upload || {};\n validateFileSize(file, kind, config);\n\n if (sources.onFileUpload) {\n const result = await sources.onFileUpload(file, { kind, onProgress: onProgress || (() => undefined) });\n return normaliseResult(result, file);\n }\n if (kind === \"image\" && sources.onImageUpload) {\n return normaliseResult(await sources.onImageUpload(file), file);\n }\n const presignUrl = config.presignEndpoint || PRESIGN_ENV;\n if (config.getPresignedUrl || presignUrl) {\n return uploadViaPresign(file, kind, config, presignUrl, onProgress);\n }\n const endpoint = config.endpoint || ENDPOINT_ENV;\n if (endpoint) return uploadViaEndpoint(file, kind, config, endpoint, onProgress);\n if (directS3Enabled(config)) {\n return directS3Upload(file, config.s3Folder, onProgress);\n }\n throw new UploadNotConfiguredError();\n };\n}\n\n/** True when at least one upload strategy is available. */\nexport function canUpload(sources: UploaderSources, kind: MediaKind): boolean {\n const config = sources.upload || {};\n return Boolean(\n sources.onFileUpload ||\n (kind === \"image\" && sources.onImageUpload) ||\n config.getPresignedUrl ||\n config.presignEndpoint ||\n PRESIGN_ENV ||\n config.endpoint ||\n ENDPOINT_ENV ||\n directS3Enabled(config)\n );\n}\n"],"names":["UploadNotConfiguredError","_Error","_this","_classCallCheck","_callSuper","callSuper","name","_inherits","_createClass","_wrapNativeSuper","Error","PRESIGN_ENV","process","env","NEXT_PUBLIC_IHUB_EDITOR_PRESIGN_URL","ENDPOINT_ENV","NEXT_PUBLIC_IHUB_EDITOR_UPLOAD_URL","DIRECT_S3_ENV","NEXT_PUBLIC_IHUB_EDITOR_DIRECT_S3","directS3Enabled","config","_config$directS","directS3","isDirectS3Configured","URL_KEYS","extractUrl","payload","test","_typeof","_step","record","_iterator","_createForOfIteratorHelper","createForOfIteratorHelper","s","n","done","value","err","e","f","_i","_arr","length","nested","found","validateFileSize","file","kind","_config$maxSizeMB$kin","_config$maxSizeMB","limit","maxSizeMB","DEFAULT_MAX_SIZE_MB","size","concat","KIND_LABEL","normaliseResult","result","base","url","_objectSpread","mime","type","sendWithProgress","method","body","headers","onProgress","Promise","resolve","reject","xhr","XMLHttpRequest","upload","onprogress","event","lengthComputable","Math","round","loaded","total","onload","status","responseText","onerror","ontimeout","open","Object","entries","forEach","_ref","_ref2","_slicedToArray","setRequestHeader","send","uploadViaPresign","_x","_x2","_x3","_x4","_x5","_uploadViaPresign","apply","this","arguments","_asyncToGenerator","asyncToGenerator","_regenerator","m","_callee2","presignUrl","_presign","presign","_config$token","_config$channel","res","contentType","extra","_t2","w","_context2","getPresignedUrl","v","JSON","stringify","filename","content_type","fetch","reqOptions","token","channel","ok","json","cdnUrl","fromEntries","filter","_ref4","toLowerCase","a","uploadViaEndpoint","_x6","_x7","_x8","_x9","_x0","_uploadViaEndpoint","_callee3","endpoint","_config$token2","_config$channel2","form","_reqOptions","text","_context3","FormData","append","fieldName","extraFields","_ref6","_ref7","key","parse","_unused","sources","Boolean","onFileUpload","onImageUpload","presignEndpoint","_ref3","_callee","_t","_context","directS3Upload","s3Folder","_x1","_x10","_x11"],"mappings":"sPAsBaA,WAAyBC,GACpC,SAAAD,IAAA,IAAAE,EAEyC,OAFzCC,sBAAAH,IACEE,EAAAE,EAAAC,UAAAL,KAAAA,GAAM,uEACDM,KAAO,2BAA2BJ,CACzC,CAAC,OAAAK,WAAAP,EAAAC,GAAAO,EAAAA,YAAAR,EAAA,EAAAS,EAAAA,gBAJ2CC,QAOxCC,EAAcC,QAAQC,IAAIC,qCAAuC,GACjEC,EAAeH,QAAQC,IAAIG,oCAAsC,GACjEC,EAAkE,SA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A1F,OAANV,EAAMkH,EAAAjD,EAAAiD,EAAAjC,EAAA,EACLlF,EAAgBC,EAAQX,IAAK,KAAA,EAAA,GAEzB,UAATC,IAAoBoH,EAAQG,cAAa,CAAAK,EAAAzI,EAAA,EAAA,KAAA,CACrB,OADqBwI,EACpClH,EAAemH,EAAAzI,EAAA,EAAOiI,EAAQG,cAAcxH,GAAK,KAAA,EAAA,OAAA6H,EAAAjC,EAAAgC,EAAAA,EAAAC,EAAAjD,EAAE5E,IAAI,KAAA,EAER,GAAlDgE,EAAa3F,EAAOoJ,iBAAmB7J,GACzCS,EAAOsG,kBAAmBX,EAAU,CAAA6D,EAAAzI,EAAA,EAAA,KAAA,CAAA,OAAAyI,EAAAjC,EAAA,EAC/B3C,EAAiBjD,EAAMC,EAAM5B,EAAQ2F,EAAY3C,IAAW,KAAA,EAErB,KAA1CgF,EAAWhI,EAAOgI,UAAYrI,GACxB,CAAA6J,EAAAzI,EAAA,EAAA,KAAA,CAAA,OAAAyI,EAAAjC,EAAA,EAASC,EAAkB7F,EAAMC,EAAM5B,EAAQgI,EAAUhF,IAAW,KAAA,EAAA,IAC5EjD,EAAgBC,GAAO,CAAAwJ,EAAAzI,EAAA,EAAA,KAAA,CAAA,OAAAyI,EAAAjC,EAAA,EAClBkC,EAAcA,eAAC9H,EAAM3B,EAAO0J,SAAU1G,IAAW,KAAA,EAAA,MAEpD,IAAIpE,EAA0B,KAAA,EAAA,OAAA4K,EAAAjC,EAAA,GAAA,EAAA+B,EACrC,IAAA,OAAA,SAAAK,EAAAC,EAAAC,GAAA,OAAAR,EAAAlE,MAAAC,KAAAC,UAAA,CAAA,CArBD,EAsBF"}
|
|
1
|
+
{"version":3,"file":"uploadFile.cjs","sources":["../../../../../../../src/components/ui/editor/ihub-editor/upload/uploadFile.ts"],"sourcesContent":["import { reqOptions } from \"../../../../lib/helpFunction\";\nimport type {\n FileUploadHandler,\n IHubEditorUploadConfig,\n MediaKind,\n UploadedFileResult,\n} from \"../types\";\nimport { DEFAULT_MAX_SIZE_MB, KIND_LABEL } from \"./mediaKinds\";\n\nexport type EditorUploader = (\n file: File,\n kind: MediaKind,\n onProgress?: (percent: number) => void\n) => Promise<UploadedFileResult>;\n\nexport interface UploaderSources {\n onFileUpload?: FileUploadHandler;\n onImageUpload?: (file: File) => Promise<string>;\n upload?: IHubEditorUploadConfig;\n}\n\nexport class UploadNotConfiguredError extends Error {\n constructor() {\n super(\"Uploads are not configured for this editor. Paste a link instead.\");\n this.name = \"UploadNotConfiguredError\";\n }\n}\n\nconst PRESIGN_ENV = process.env.NEXT_PUBLIC_IHUB_EDITOR_PRESIGN_URL || \"\";\nconst ENDPOINT_ENV = process.env.NEXT_PUBLIC_IHUB_EDITOR_UPLOAD_URL || \"\";\n\nconst URL_KEYS = [\"url\", \"cdnUrl\", \"cdn_url\", \"location\", \"file_url\", \"file\", \"src\"];\n\n/** Find the uploaded file's URL in an arbitrary API response. */\nexport function extractUrl(payload: unknown): string | null {\n if (!payload) return null;\n if (typeof payload === \"string\") return /^(https?:)?\\/\\//.test(payload) ? payload : null;\n if (typeof payload !== \"object\") return null;\n const record = payload as Record<string, unknown>;\n for (const key of URL_KEYS) {\n const value = record[key];\n if (typeof value === \"string\" && value) return value;\n }\n for (const nested of [\"data\", \"result\", \"file\"]) {\n if (record[nested] && typeof record[nested] === \"object\") {\n const found = extractUrl(record[nested]);\n if (found) return found;\n }\n }\n return null;\n}\n\nexport function validateFileSize(file: File, kind: MediaKind, config?: IHubEditorUploadConfig): void {\n const limit = config?.maxSizeMB?.[kind] ?? DEFAULT_MAX_SIZE_MB[kind];\n if (limit > 0 && file.size > limit * 1024 * 1024) {\n throw new Error(`This ${KIND_LABEL[kind]} is larger than the ${limit} MB limit.`);\n }\n}\n\nfunction normaliseResult(result: string | UploadedFileResult, file: File): UploadedFileResult {\n const base = typeof result === \"string\" ? { url: result } : result;\n if (!base?.url) throw new Error(\"The upload handler did not return a URL.\");\n return { name: file.name, size: file.size, mime: file.type, ...base };\n}\n\n/** XHR wrapper so uploads can report real progress. */\nexport function sendWithProgress(\n method: string,\n url: string,\n body: Document | XMLHttpRequestBodyInit,\n headers: Record<string, string>,\n onProgress?: (percent: number) => void\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.upload.onprogress = (event) => {\n if (event.lengthComputable) onProgress?.(Math.round((event.loaded / event.total) * 100));\n };\n xhr.onload = () => {\n if (xhr.status >= 200 && xhr.status < 300) resolve(xhr.responseText);\n else reject(new Error(`Upload failed (HTTP ${xhr.status}).`));\n };\n xhr.onerror = () => reject(new Error(\"Network error during upload.\"));\n xhr.ontimeout = () => reject(new Error(\"Upload timed out.\"));\n xhr.open(method, url);\n Object.entries(headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));\n xhr.send(body);\n });\n}\n\nasync function uploadViaPresign(\n file: File,\n kind: MediaKind,\n config: IHubEditorUploadConfig,\n presignUrl: string,\n onProgress?: (percent: number) => void\n): Promise<UploadedFileResult> {\n let presign = config.getPresignedUrl ? await config.getPresignedUrl(file, kind) : null;\n if (!presign) {\n const body = JSON.stringify({ filename: file.name, content_type: file.type, size: file.size, kind });\n const res = await fetch(presignUrl, reqOptions(\"POST\", body, config.token ?? null, \"json\", config.channel ?? null) as RequestInit);\n if (!res.ok) throw new Error(`Could not get an upload URL (HTTP ${res.status}).`);\n presign = await res.json();\n }\n if (!presign?.url || !presign.cdnUrl) throw new Error(\"The presign response is missing url or cdnUrl.\");\n const contentType = presign.contentType || file.type || \"application/octet-stream\";\n const extra = Object.fromEntries(\n Object.entries(presign.headers || {}).filter(([name]) => name.toLowerCase() !== \"content-type\")\n );\n await sendWithProgress(\"PUT\", presign.url, file, { \"Content-Type\": contentType, ...extra }, onProgress);\n return { url: presign.cdnUrl, name: file.name, size: file.size, mime: contentType };\n}\n\nasync function uploadViaEndpoint(\n file: File,\n kind: MediaKind,\n config: IHubEditorUploadConfig,\n endpoint: string,\n onProgress?: (percent: number) => void\n): Promise<UploadedFileResult> {\n const form = new FormData();\n form.append(config.fieldName || \"file\", file);\n form.append(\"name\", file.name);\n form.append(\"kind\", kind);\n Object.entries(config.extraFields || {}).forEach(([key, value]) => form.append(key, value));\n const { headers } = reqOptions(\"POST\", form, config.token ?? null, false, config.channel ?? null) as {\n headers: Record<string, string>;\n };\n const text = await sendWithProgress(\"POST\", endpoint, form, headers || {}, onProgress);\n let payload: unknown = text;\n try {\n payload = JSON.parse(text);\n } catch {\n // plain-text response: treat as URL below\n }\n const url = extractUrl(payload);\n if (!url) throw new Error(\"The upload endpoint response did not include a file URL.\");\n return { url, name: file.name, size: file.size, mime: file.type };\n}\n\n/** Build the uploader used by every media block, following the documented resolution order. */\nexport function createUploader(sources: UploaderSources): EditorUploader {\n return async (file, kind, onProgress) => {\n const config = sources.upload || {};\n validateFileSize(file, kind, config);\n\n if (sources.onFileUpload) {\n const result = await sources.onFileUpload(file, { kind, onProgress: onProgress || (() => undefined) });\n return normaliseResult(result, file);\n }\n if (kind === \"image\" && sources.onImageUpload) {\n return normaliseResult(await sources.onImageUpload(file), file);\n }\n const presignUrl = config.presignEndpoint || PRESIGN_ENV;\n if (config.getPresignedUrl || presignUrl) {\n return uploadViaPresign(file, kind, config, presignUrl, onProgress);\n }\n const endpoint = config.endpoint || ENDPOINT_ENV;\n if (endpoint) return uploadViaEndpoint(file, kind, config, endpoint, onProgress);\n throw new UploadNotConfiguredError();\n };\n}\n\n/** True when at least one upload strategy is available. */\nexport function canUpload(sources: UploaderSources, kind: MediaKind): boolean {\n const config = sources.upload || {};\n return Boolean(\n sources.onFileUpload ||\n (kind === \"image\" && sources.onImageUpload) ||\n config.getPresignedUrl ||\n config.presignEndpoint ||\n PRESIGN_ENV ||\n config.endpoint ||\n ENDPOINT_ENV\n );\n}\n"],"names":["UploadNotConfiguredError","_Error","_this","_classCallCheck","_callSuper","callSuper","name","_inherits","_createClass","_wrapNativeSuper","Error","PRESIGN_ENV","process","env","NEXT_PUBLIC_IHUB_EDITOR_PRESIGN_URL","ENDPOINT_ENV","NEXT_PUBLIC_IHUB_EDITOR_UPLOAD_URL","URL_KEYS","extractUrl","payload","test","_typeof","_step","record","_iterator","_createForOfIteratorHelper","createForOfIteratorHelper","s","n","done","value","err","e","f","_i","_arr","length","nested","found","validateFileSize","file","kind","config","_config$maxSizeMB$kin","_config$maxSizeMB","limit","maxSizeMB","DEFAULT_MAX_SIZE_MB","size","concat","KIND_LABEL","normaliseResult","result","base","url","_objectSpread","mime","type","sendWithProgress","method","body","headers","onProgress","Promise","resolve","reject","xhr","XMLHttpRequest","upload","onprogress","event","lengthComputable","Math","round","loaded","total","onload","status","responseText","onerror","ontimeout","open","Object","entries","forEach","_ref","_ref2","_slicedToArray","setRequestHeader","send","uploadViaPresign","_x","_x2","_x3","_x4","_x5","_uploadViaPresign","apply","this","arguments","_asyncToGenerator","asyncToGenerator","_regenerator","m","_callee2","presignUrl","_presign","presign","_config$token","_config$channel","res","contentType","extra","_t2","w","_context2","getPresignedUrl","v","JSON","stringify","filename","content_type","fetch","reqOptions","token","channel","ok","json","cdnUrl","fromEntries","filter","_ref4","toLowerCase","a","uploadViaEndpoint","_x6","_x7","_x8","_x9","_x0","_uploadViaEndpoint","_callee3","endpoint","_config$token2","_config$channel2","form","_reqOptions","text","_context3","FormData","append","fieldName","extraFields","_ref6","_ref7","key","parse","_unused","sources","Boolean","onFileUpload","onImageUpload","presignEndpoint","_ref3","_callee","_t","_context","_x1","_x10","_x11"],"mappings":"0NAqBaA,WAAyBC,GACpC,SAAAD,IAAA,IAAAE,EAEyC,OAFzCC,sBAAAH,IACEE,EAAAE,EAAAC,UAAAL,KAAAA,GAAM,uEACDM,KAAO,2BAA2BJ,CACzC,CAAC,OAAAK,WAAAP,EAAAC,GAAAO,EAAAA,YAAAR,EAAA,EAAAS,EAAAA,gBAJ2CC,QAOxCC,EAAcC,QAAQC,IAAIC,qCAAuC,GACjEC,EAAeH,QAAQC,IAAIG,oCAAsC,GAEjEC,EAAW,CAAC,MAAO,S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AAQG,cAAczH,GAAK,KAAA,EAAA,OAAA8H,EAAAjC,EAAAgC,EAAAA,EAAAC,EAAAjD,EAAE7E,IAAI,KAAA,EAER,GAAlDiE,EAAa/D,EAAOwH,iBAAmBvJ,GACzC+B,EAAO0E,kBAAmBX,EAAU,CAAA6D,EAAA1I,EAAA,EAAA,KAAA,CAAA,OAAA0I,EAAAjC,EAAA,EAC/B3C,EAAiBlD,EAAMC,EAAMC,EAAQ+D,EAAY3C,IAAW,KAAA,EAErB,KAA1CgF,EAAWpG,EAAOoG,UAAY/H,GACxB,CAAAuJ,EAAA1I,EAAA,EAAA,KAAA,CAAA,OAAA0I,EAAAjC,EAAA,EAASC,EAAkB9F,EAAMC,EAAMC,EAAQoG,EAAUhF,IAAW,KAAA,EAAA,MAC1E,IAAI9D,EAA0B,KAAA,EAAA,OAAAsK,EAAAjC,EAAA,GAAA,EAAA+B,EACrC,IAAA,OAAA,SAAAG,EAAAC,EAAAC,GAAA,OAAAN,EAAAlE,MAAAC,KAAAC,UAAA,CAAA,CAlBD,EAmBF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{asyncToGenerator as e,regenerator as n,inherits as r,createClass as t,wrapNativeSuper as a,objectSpread2 as o,slicedToArray as i,classCallCheck as u,callSuper as
|
|
1
|
+
import{asyncToGenerator as e,regenerator as n,inherits as r,createClass as t,wrapNativeSuper as a,objectSpread2 as o,slicedToArray as i,classCallCheck as u,callSuper as l,typeof as s,createForOfIteratorHelper as c}from"../../../../../../_virtual/_rollupPluginBabelHelpers.js";import{reqOptions as p}from"../../../../lib/helpFunction.js";import{DEFAULT_MAX_SIZE_MB as f,KIND_LABEL as d}from"./mediaKinds.js";var m=function(e){function n(){var e;return u(this,n),(e=l(this,n,["Uploads are not configured for this editor. Paste a link instead."])).name="UploadNotConfiguredError",e}return r(n,e),t(n)}(a(Error)),h=process.env.NEXT_PUBLIC_IHUB_EDITOR_PRESIGN_URL||"",v=process.env.NEXT_PUBLIC_IHUB_EDITOR_UPLOAD_URL||"",g=["url","cdnUrl","cdn_url","location","file_url","file","src"];function U(e){if(!e)return null;if("string"==typeof e)return/^(https?:)?\/\//.test(e)?e:null;if("object"!==s(e))return null;var n,r=e,t=c(g);try{for(t.s();!(n=t.n()).done;){var a=r[n.value];if("string"==typeof a&&a)return a}}catch(e){t.e(e)}finally{t.f()}for(var o=0,i=["data","result","file"];o<i.length;o++){var u=i[o];if(r[u]&&"object"===s(r[u])){var l=U(r[u]);if(l)return l}}return null}function w(e,n,r){var t,a,o=null!==(t=null==r||null===(a=r.maxSizeMB)||void 0===a?void 0:a[n])&&void 0!==t?t:f[n];if(o>0&&e.size>1024*o*1024)throw new Error("This ".concat(d[n]," is larger than the ").concat(o," MB limit."))}function y(e,n){var r="string"==typeof e?{url:e}:e;if(null==r||!r.url)throw new Error("The upload handler did not return a URL.");return o({name:n.name,size:n.size,mime:n.type},r)}function T(e,n,r,t,a){return new Promise(function(o,u){var l=new XMLHttpRequest;l.upload.onprogress=function(e){e.lengthComputable&&(null==a||a(Math.round(e.loaded/e.total*100)))},l.onload=function(){l.status>=200&&l.status<300?o(l.responseText):u(new Error("Upload failed (HTTP ".concat(l.status,").")))},l.onerror=function(){return u(new Error("Network error during upload."))},l.ontimeout=function(){return u(new Error("Upload timed out."))},l.open(e,n),Object.entries(t).forEach(function(e){var n=i(e,2),r=n[0],t=n[1];return l.setRequestHeader(r,t)}),l.send(r)})}function b(e,n,r,t,a){return E.apply(this,arguments)}function E(){return(E=e(n().m(function e(r,t,a,u,l){var s,c,f,d,m,h,v,g,U;return n().w(function(e){for(;;)switch(e.n){case 0:if(!a.getPresignedUrl){e.n=2;break}return e.n=1,a.getPresignedUrl(r,t);case 1:U=e.v,e.n=3;break;case 2:U=null;case 3:if(c=U){e.n=7;break}return m=JSON.stringify({filename:r.name,content_type:r.type,size:r.size,kind:t}),e.n=4,fetch(u,p("POST",m,null!==(f=a.token)&&void 0!==f?f:null,"json",null!==(d=a.channel)&&void 0!==d?d:null));case 4:if((h=e.v).ok){e.n=5;break}throw new Error("Could not get an upload URL (HTTP ".concat(h.status,")."));case 5:return e.n=6,h.json();case 6:c=e.v;case 7:if(null!==(s=c)&&void 0!==s&&s.url&&c.cdnUrl){e.n=8;break}throw new Error("The presign response is missing url or cdnUrl.");case 8:return v=c.contentType||r.type||"application/octet-stream",g=Object.fromEntries(Object.entries(c.headers||{}).filter(function(e){return"content-type"!==i(e,1)[0].toLowerCase()})),e.n=9,T("PUT",c.url,r,o({"Content-Type":v},g),l);case 9:return e.a(2,{url:c.cdnUrl,name:r.name,size:r.size,mime:v})}},e)}))).apply(this,arguments)}function k(e,n,r,t,a){return P.apply(this,arguments)}function P(){return(P=e(n().m(function e(r,t,a,o,u){var l,s,c,f,d,m,h,v;return n().w(function(e){for(;;)switch(e.n){case 0:return(c=new FormData).append(a.fieldName||"file",r),c.append("name",r.name),c.append("kind",t),Object.entries(a.extraFields||{}).forEach(function(e){var n=i(e,2),r=n[0],t=n[1];return c.append(r,t)}),f=p("POST",c,null!==(l=a.token)&&void 0!==l?l:null,!1,null!==(s=a.channel)&&void 0!==s?s:null),d=f.headers,e.n=1,T("POST",o,c,d||{},u);case 1:m=e.v,h=m;try{h=JSON.parse(m)}catch(e){}if(v=U(h)){e.n=2;break}throw new Error("The upload endpoint response did not include a file URL.");case 2:return e.a(2,{url:v,name:r.name,size:r.size,mime:r.type})}},e)}))).apply(this,arguments)}function _(r){return function(){var t=e(n().m(function e(t,a,o){var i,u,l,s,c;return n().w(function(e){for(;;)switch(e.n){case 0:if(i=r.upload||{},w(t,a,i),!r.onFileUpload){e.n=2;break}return e.n=1,r.onFileUpload(t,{kind:a,onProgress:o||function(){}});case 1:return u=e.v,e.a(2,y(u,t));case 2:if("image"!==a||!r.onImageUpload){e.n=4;break}return c=y,e.n=3,r.onImageUpload(t);case 3:return e.a(2,c(e.v,t));case 4:if(l=i.presignEndpoint||h,!i.getPresignedUrl&&!l){e.n=5;break}return e.a(2,b(t,a,i,l,o));case 5:if(!(s=i.endpoint||v)){e.n=6;break}return e.a(2,k(t,a,i,s,o));case 6:throw new m;case 7:return e.a(2)}},e)}));return function(e,n,r){return t.apply(this,arguments)}}()}function O(e,n){var r=e.upload||{};return Boolean(e.onFileUpload||"image"===n&&e.onImageUpload||r.getPresignedUrl||r.presignEndpoint||h||r.endpoint||v)}export{m as UploadNotConfiguredError,O as canUpload,_ as createUploader,U as extractUrl,T as sendWithProgress,w as validateFileSize};
|
|
2
2
|
//# sourceMappingURL=uploadFile.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uploadFile.js","sources":["../../../../../../../src/components/ui/editor/ihub-editor/upload/uploadFile.ts"],"sourcesContent":["import { reqOptions } from \"../../../../lib/helpFunction\";\nimport type {\n FileUploadHandler,\n IHubEditorUploadConfig,\n MediaKind,\n UploadedFileResult,\n} from \"../types\";\nimport { DEFAULT_MAX_SIZE_MB, KIND_LABEL } from \"./mediaKinds\";\nimport { directS3Upload, isDirectS3Configured } from \"./s3Direct\";\n\nexport type EditorUploader = (\n file: File,\n kind: MediaKind,\n onProgress?: (percent: number) => void\n) => Promise<UploadedFileResult>;\n\nexport interface UploaderSources {\n onFileUpload?: FileUploadHandler;\n onImageUpload?: (file: File) => Promise<string>;\n upload?: IHubEditorUploadConfig;\n}\n\nexport class UploadNotConfiguredError extends Error {\n constructor() {\n super(\"Uploads are not configured for this editor. Paste a link instead.\");\n this.name = \"UploadNotConfiguredError\";\n }\n}\n\nconst PRESIGN_ENV = process.env.NEXT_PUBLIC_IHUB_EDITOR_PRESIGN_URL || \"\";\nconst ENDPOINT_ENV = process.env.NEXT_PUBLIC_IHUB_EDITOR_UPLOAD_URL || \"\";\nconst DIRECT_S3_ENV = process.env.NEXT_PUBLIC_IHUB_EDITOR_DIRECT_S3 === \"true\";\n\n/** Direct browser → S3 exposes the secret key, so it only runs when explicitly enabled. */\nfunction directS3Enabled(config: IHubEditorUploadConfig): boolean {\n const optedIn = config.directS3 ?? DIRECT_S3_ENV;\n return optedIn === true && isDirectS3Configured();\n}\n\nconst URL_KEYS = [\"url\", \"cdnUrl\", \"cdn_url\", \"location\", \"file_url\", \"file\", \"src\"];\n\n/** Find the uploaded file's URL in an arbitrary API response. */\nexport function extractUrl(payload: unknown): string | null {\n if (!payload) return null;\n if (typeof payload === \"string\") return /^(https?:)?\\/\\//.test(payload) ? payload : null;\n if (typeof payload !== \"object\") return null;\n const record = payload as Record<string, unknown>;\n for (const key of URL_KEYS) {\n const value = record[key];\n if (typeof value === \"string\" && value) return value;\n }\n for (const nested of [\"data\", \"result\", \"file\"]) {\n if (record[nested] && typeof record[nested] === \"object\") {\n const found = extractUrl(record[nested]);\n if (found) return found;\n }\n }\n return null;\n}\n\nexport function validateFileSize(file: File, kind: MediaKind, config?: IHubEditorUploadConfig): void {\n const limit = config?.maxSizeMB?.[kind] ?? DEFAULT_MAX_SIZE_MB[kind];\n if (limit > 0 && file.size > limit * 1024 * 1024) {\n throw new Error(`This ${KIND_LABEL[kind]} is larger than the ${limit} MB limit.`);\n }\n}\n\nfunction normaliseResult(result: string | UploadedFileResult, file: File): UploadedFileResult {\n const base = typeof result === \"string\" ? { url: result } : result;\n if (!base?.url) throw new Error(\"The upload handler did not return a URL.\");\n return { name: file.name, size: file.size, mime: file.type, ...base };\n}\n\n/** XHR wrapper so uploads can report real progress. */\nexport function sendWithProgress(\n method: string,\n url: string,\n body: Document | XMLHttpRequestBodyInit,\n headers: Record<string, string>,\n onProgress?: (percent: number) => void\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.upload.onprogress = (event) => {\n if (event.lengthComputable) onProgress?.(Math.round((event.loaded / event.total) * 100));\n };\n xhr.onload = () => {\n if (xhr.status >= 200 && xhr.status < 300) resolve(xhr.responseText);\n else reject(new Error(`Upload failed (HTTP ${xhr.status}).`));\n };\n xhr.onerror = () => reject(new Error(\"Network error during upload.\"));\n xhr.ontimeout = () => reject(new Error(\"Upload timed out.\"));\n xhr.open(method, url);\n Object.entries(headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));\n xhr.send(body);\n });\n}\n\nasync function uploadViaPresign(\n file: File,\n kind: MediaKind,\n config: IHubEditorUploadConfig,\n presignUrl: string,\n onProgress?: (percent: number) => void\n): Promise<UploadedFileResult> {\n let presign = config.getPresignedUrl ? await config.getPresignedUrl(file, kind) : null;\n if (!presign) {\n const body = JSON.stringify({ filename: file.name, content_type: file.type, size: file.size, kind });\n const res = await fetch(presignUrl, reqOptions(\"POST\", body, config.token ?? null, \"json\", config.channel ?? null) as RequestInit);\n if (!res.ok) throw new Error(`Could not get an upload URL (HTTP ${res.status}).`);\n presign = await res.json();\n }\n if (!presign?.url || !presign.cdnUrl) throw new Error(\"The presign response is missing url or cdnUrl.\");\n const contentType = presign.contentType || file.type || \"application/octet-stream\";\n const extra = Object.fromEntries(\n Object.entries(presign.headers || {}).filter(([name]) => name.toLowerCase() !== \"content-type\")\n );\n await sendWithProgress(\"PUT\", presign.url, file, { \"Content-Type\": contentType, ...extra }, onProgress);\n return { url: presign.cdnUrl, name: file.name, size: file.size, mime: contentType };\n}\n\nasync function uploadViaEndpoint(\n file: File,\n kind: MediaKind,\n config: IHubEditorUploadConfig,\n endpoint: string,\n onProgress?: (percent: number) => void\n): Promise<UploadedFileResult> {\n const form = new FormData();\n form.append(config.fieldName || \"file\", file);\n form.append(\"name\", file.name);\n form.append(\"kind\", kind);\n Object.entries(config.extraFields || {}).forEach(([key, value]) => form.append(key, value));\n const { headers } = reqOptions(\"POST\", form, config.token ?? null, false, config.channel ?? null) as {\n headers: Record<string, string>;\n };\n const text = await sendWithProgress(\"POST\", endpoint, form, headers || {}, onProgress);\n let payload: unknown = text;\n try {\n payload = JSON.parse(text);\n } catch {\n // plain-text response: treat as URL below\n }\n const url = extractUrl(payload);\n if (!url) throw new Error(\"The upload endpoint response did not include a file URL.\");\n return { url, name: file.name, size: file.size, mime: file.type };\n}\n\n/** Build the uploader used by every media block, following the documented resolution order. */\nexport function createUploader(sources: UploaderSources): EditorUploader {\n return async (file, kind, onProgress) => {\n const config = sources.upload || {};\n validateFileSize(file, kind, config);\n\n if (sources.onFileUpload) {\n const result = await sources.onFileUpload(file, { kind, onProgress: onProgress || (() => undefined) });\n return normaliseResult(result, file);\n }\n if (kind === \"image\" && sources.onImageUpload) {\n return normaliseResult(await sources.onImageUpload(file), file);\n }\n const presignUrl = config.presignEndpoint || PRESIGN_ENV;\n if (config.getPresignedUrl || presignUrl) {\n return uploadViaPresign(file, kind, config, presignUrl, onProgress);\n }\n const endpoint = config.endpoint || ENDPOINT_ENV;\n if (endpoint) return uploadViaEndpoint(file, kind, config, endpoint, onProgress);\n if (directS3Enabled(config)) {\n return directS3Upload(file, config.s3Folder, onProgress);\n }\n throw new UploadNotConfiguredError();\n };\n}\n\n/** True when at least one upload strategy is available. */\nexport function canUpload(sources: UploaderSources, kind: MediaKind): boolean {\n const config = sources.upload || {};\n return Boolean(\n sources.onFileUpload ||\n (kind === \"image\" && sources.onImageUpload) ||\n config.getPresignedUrl ||\n config.presignEndpoint ||\n PRESIGN_ENV ||\n config.endpoint ||\n ENDPOINT_ENV ||\n directS3Enabled(config)\n );\n}\n"],"names":["UploadNotConfiguredError","_Error","_this","_classCallCheck","_callSuper","name","_inherits","_createClass","_wrapNativeSuper","Error","PRESIGN_ENV","process","env","NEXT_PUBLIC_IHUB_EDITOR_PRESIGN_URL","ENDPOINT_ENV","NEXT_PUBLIC_IHUB_EDITOR_UPLOAD_URL","DIRECT_S3_ENV","NEXT_PUBLIC_IHUB_EDITOR_DIRECT_S3","directS3Enabled","config","_config$directS","directS3","isDirectS3Configured","URL_KEYS","extractUrl","payload","test","_typeof","_step","record","_iterator","_createForOfIteratorHelper","s","n","done","value","err","e","f","_i","_arr","length","nested","found","validateFileSize","file","kind","_config$maxSizeMB$kin","_config$maxSizeMB","limit","maxSizeMB","DEFAULT_MAX_SIZE_MB","size","concat","KIND_LABEL","normaliseResult","result","base","url","_objectSpread","mime","type","sendWithProgress","method","body","headers","onProgress","Promise","resolve","reject","xhr","XMLHttpRequest","upload","onprogress","event","lengthComputable","Math","round","loaded","total","onload","status","responseText","onerror","ontimeout","open","Object","entries","forEach","_ref","_ref2","_slicedToArray","setRequestHeader","send","uploadViaPresign","_x","_x2","_x3","_x4","_x5","_uploadViaPresign","apply","this","arguments","_asyncToGenerator","_regenerator","m","_callee2","presignUrl","_presign","presign","_config$token","_config$channel","res","contentType","extra","_t2","w","_context2","getPresignedUrl","v","JSON","stringify","filename","content_type","fetch","reqOptions","token","channel","ok","json","cdnUrl","fromEntries","filter","_ref4","toLowerCase","a","uploadViaEndpoint","_x6","_x7","_x8","_x9","_x0","_uploadViaEndpoint","_callee3","endpoint","_config$token2","_config$channel2","form","_reqOptions","text","_context3","FormData","append","fieldName","extraFields","_ref6","_ref7","key","parse","_unused","createUploader","sources","_ref3","_callee","_t","_context","onFileUpload","onImageUpload","presignEndpoint","directS3Upload","s3Folder","_x1","_x10","_x11","canUpload","Boolean"],"mappings":"geAsBaA,IAAAA,WAAyBC,GACpC,SAAAD,IAAA,IAAAE,EAEyC,OAFzCC,OAAAH,IACEE,EAAAE,EAAAJ,KAAAA,GAAM,uEACDK,KAAO,2BAA2BH,CACzC,CAAC,OAAAI,EAAAN,EAAAC,GAAAM,EAAAP,EAAA,EAAAQ,EAJ2CC,QAOxCC,EAAcC,QAAQC,IAAIC,qCAAuC,GACjEC,EAAeH,QAAQC,IAAIG,oCAAsC,GACjEC,EAAkE,SAAlDL,QAAQC,IAAIK,kCAGlC,SAASC,EAAgBC,GAA8B,IAAAC,EAErD,OAAmB,KADY,QAAlBA,EAAGD,EAAOE,gBAAQ,IAAAD,EAAAA,EAAIJ,IACRM,GAC7B,CAEA,IAAMC,EAAW,CAAC,MAAO,SAAU,UAAW,WAAY,WAAY,OAAQ,OAGxE,SAAUC,EAAWC,GACzB,IAAKA,EAAS,OAAO,KACrB,GAAuB,iBAAZA,EAAsB,MAAO,kBAAkBC,KAAK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AMC,EAAM3B,EAAQ8H,EAAU/E,IAAW,KAAA,EAAA,IAC5EhD,EAAgBC,GAAO,CAAAmJ,EAAArI,EAAA,EAAA,KAAA,CAAA,OAAAqI,EAAA9B,EAAA,EAClBkC,EAAe7H,EAAM1B,EAAOwJ,SAAUzG,IAAW,KAAA,EAAA,MAEpD,IAAIlE,EAA0B,KAAA,EAAA,OAAAsK,EAAA9B,EAAA,GAAA,EAAA4B,EACrC,IAAA,OAAA,SAAAQ,EAAAC,EAAAC,GAAA,OAAAX,EAAA9D,MAAAC,KAAAC,UAAA,CAAA,CArBD,EAsBF,CAGgB,SAAAwE,EAAUb,EAA0BpH,GAClD,IAAM3B,EAAS+I,EAAQ1F,QAAU,GACjC,OAAOwG,QACLd,EAAQK,cACI,UAATzH,GAAoBoH,EAAQM,eAC7BrJ,EAAOoG,iBACPpG,EAAOsJ,iBACP/J,GACAS,EAAO8H,UACPnI,GACAI,EAAgBC,GAEtB"}
|
|
1
|
+
{"version":3,"file":"uploadFile.js","sources":["../../../../../../../src/components/ui/editor/ihub-editor/upload/uploadFile.ts"],"sourcesContent":["import { reqOptions } from \"../../../../lib/helpFunction\";\nimport type {\n FileUploadHandler,\n IHubEditorUploadConfig,\n MediaKind,\n UploadedFileResult,\n} from \"../types\";\nimport { DEFAULT_MAX_SIZE_MB, KIND_LABEL } from \"./mediaKinds\";\n\nexport type EditorUploader = (\n file: File,\n kind: MediaKind,\n onProgress?: (percent: number) => void\n) => Promise<UploadedFileResult>;\n\nexport interface UploaderSources {\n onFileUpload?: FileUploadHandler;\n onImageUpload?: (file: File) => Promise<string>;\n upload?: IHubEditorUploadConfig;\n}\n\nexport class UploadNotConfiguredError extends Error {\n constructor() {\n super(\"Uploads are not configured for this editor. Paste a link instead.\");\n this.name = \"UploadNotConfiguredError\";\n }\n}\n\nconst PRESIGN_ENV = process.env.NEXT_PUBLIC_IHUB_EDITOR_PRESIGN_URL || \"\";\nconst ENDPOINT_ENV = process.env.NEXT_PUBLIC_IHUB_EDITOR_UPLOAD_URL || \"\";\n\nconst URL_KEYS = [\"url\", \"cdnUrl\", \"cdn_url\", \"location\", \"file_url\", \"file\", \"src\"];\n\n/** Find the uploaded file's URL in an arbitrary API response. */\nexport function extractUrl(payload: unknown): string | null {\n if (!payload) return null;\n if (typeof payload === \"string\") return /^(https?:)?\\/\\//.test(payload) ? payload : null;\n if (typeof payload !== \"object\") return null;\n const record = payload as Record<string, unknown>;\n for (const key of URL_KEYS) {\n const value = record[key];\n if (typeof value === \"string\" && value) return value;\n }\n for (const nested of [\"data\", \"result\", \"file\"]) {\n if (record[nested] && typeof record[nested] === \"object\") {\n const found = extractUrl(record[nested]);\n if (found) return found;\n }\n }\n return null;\n}\n\nexport function validateFileSize(file: File, kind: MediaKind, config?: IHubEditorUploadConfig): void {\n const limit = config?.maxSizeMB?.[kind] ?? DEFAULT_MAX_SIZE_MB[kind];\n if (limit > 0 && file.size > limit * 1024 * 1024) {\n throw new Error(`This ${KIND_LABEL[kind]} is larger than the ${limit} MB limit.`);\n }\n}\n\nfunction normaliseResult(result: string | UploadedFileResult, file: File): UploadedFileResult {\n const base = typeof result === \"string\" ? { url: result } : result;\n if (!base?.url) throw new Error(\"The upload handler did not return a URL.\");\n return { name: file.name, size: file.size, mime: file.type, ...base };\n}\n\n/** XHR wrapper so uploads can report real progress. */\nexport function sendWithProgress(\n method: string,\n url: string,\n body: Document | XMLHttpRequestBodyInit,\n headers: Record<string, string>,\n onProgress?: (percent: number) => void\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.upload.onprogress = (event) => {\n if (event.lengthComputable) onProgress?.(Math.round((event.loaded / event.total) * 100));\n };\n xhr.onload = () => {\n if (xhr.status >= 200 && xhr.status < 300) resolve(xhr.responseText);\n else reject(new Error(`Upload failed (HTTP ${xhr.status}).`));\n };\n xhr.onerror = () => reject(new Error(\"Network error during upload.\"));\n xhr.ontimeout = () => reject(new Error(\"Upload timed out.\"));\n xhr.open(method, url);\n Object.entries(headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));\n xhr.send(body);\n });\n}\n\nasync function uploadViaPresign(\n file: File,\n kind: MediaKind,\n config: IHubEditorUploadConfig,\n presignUrl: string,\n onProgress?: (percent: number) => void\n): Promise<UploadedFileResult> {\n let presign = config.getPresignedUrl ? await config.getPresignedUrl(file, kind) : null;\n if (!presign) {\n const body = JSON.stringify({ filename: file.name, content_type: file.type, size: file.size, kind });\n const res = await fetch(presignUrl, reqOptions(\"POST\", body, config.token ?? null, \"json\", config.channel ?? null) as RequestInit);\n if (!res.ok) throw new Error(`Could not get an upload URL (HTTP ${res.status}).`);\n presign = await res.json();\n }\n if (!presign?.url || !presign.cdnUrl) throw new Error(\"The presign response is missing url or cdnUrl.\");\n const contentType = presign.contentType || file.type || \"application/octet-stream\";\n const extra = Object.fromEntries(\n Object.entries(presign.headers || {}).filter(([name]) => name.toLowerCase() !== \"content-type\")\n );\n await sendWithProgress(\"PUT\", presign.url, file, { \"Content-Type\": contentType, ...extra }, onProgress);\n return { url: presign.cdnUrl, name: file.name, size: file.size, mime: contentType };\n}\n\nasync function uploadViaEndpoint(\n file: File,\n kind: MediaKind,\n config: IHubEditorUploadConfig,\n endpoint: string,\n onProgress?: (percent: number) => void\n): Promise<UploadedFileResult> {\n const form = new FormData();\n form.append(config.fieldName || \"file\", file);\n form.append(\"name\", file.name);\n form.append(\"kind\", kind);\n Object.entries(config.extraFields || {}).forEach(([key, value]) => form.append(key, value));\n const { headers } = reqOptions(\"POST\", form, config.token ?? null, false, config.channel ?? null) as {\n headers: Record<string, string>;\n };\n const text = await sendWithProgress(\"POST\", endpoint, form, headers || {}, onProgress);\n let payload: unknown = text;\n try {\n payload = JSON.parse(text);\n } catch {\n // plain-text response: treat as URL below\n }\n const url = extractUrl(payload);\n if (!url) throw new Error(\"The upload endpoint response did not include a file URL.\");\n return { url, name: file.name, size: file.size, mime: file.type };\n}\n\n/** Build the uploader used by every media block, following the documented resolution order. */\nexport function createUploader(sources: UploaderSources): EditorUploader {\n return async (file, kind, onProgress) => {\n const config = sources.upload || {};\n validateFileSize(file, kind, config);\n\n if (sources.onFileUpload) {\n const result = await sources.onFileUpload(file, { kind, onProgress: onProgress || (() => undefined) });\n return normaliseResult(result, file);\n }\n if (kind === \"image\" && sources.onImageUpload) {\n return normaliseResult(await sources.onImageUpload(file), file);\n }\n const presignUrl = config.presignEndpoint || PRESIGN_ENV;\n if (config.getPresignedUrl || presignUrl) {\n return uploadViaPresign(file, kind, config, presignUrl, onProgress);\n }\n const endpoint = config.endpoint || ENDPOINT_ENV;\n if (endpoint) return uploadViaEndpoint(file, kind, config, endpoint, onProgress);\n throw new UploadNotConfiguredError();\n };\n}\n\n/** True when at least one upload strategy is available. */\nexport function canUpload(sources: UploaderSources, kind: MediaKind): boolean {\n const config = sources.upload || {};\n return Boolean(\n sources.onFileUpload ||\n (kind === \"image\" && sources.onImageUpload) ||\n config.getPresignedUrl ||\n config.presignEndpoint ||\n PRESIGN_ENV ||\n config.endpoint ||\n ENDPOINT_ENV\n );\n}\n"],"names":["UploadNotConfiguredError","_Error","_this","_classCallCheck","_callSuper","name","_inherits","_createClass","_wrapNativeSuper","Error","PRESIGN_ENV","process","env","NEXT_PUBLIC_IHUB_EDITOR_PRESIGN_URL","ENDPOINT_ENV","NEXT_PUBLIC_IHUB_EDITOR_UPLOAD_URL","URL_KEYS","extractUrl","payload","test","_typeof","_step","record","_iterator","_createForOfIteratorHelper","s","n","done","value","err","e","f","_i","_arr","length","nested","found","validateFileSize","file","kind","config","_config$maxSizeMB$kin","_config$maxSizeMB","limit","maxSizeMB","DEFAULT_MAX_SIZE_MB","size","concat","KIND_LABEL","normaliseResult","result","base","url","_objectSpread","mime","type","sendWithProgress","method","body","headers","onProgress","Promise","resolve","reject","xhr","XMLHttpRequest","upload","onprogress","event","lengthComputable","Math","round","loaded","total","onload","status","responseText","onerror","ontimeout","open","Object","entries","forEach","_ref","_ref2","_slicedToArray","setRequestHeader","send","uploadViaPresign","_x","_x2","_x3","_x4","_x5","_uploadViaPresign","apply","this","arguments","_asyncToGenerator","_regenerator","m","_callee2","presignUrl","_presign","presign","_config$token","_config$channel","res","contentType","extra","_t2","w","_context2","getPresignedUrl","v","JSON","stringify","filename","content_type","fetch","reqOptions","token","channel","ok","json","cdnUrl","fromEntries","filter","_ref4","toLowerCase","a","uploadViaEndpoint","_x6","_x7","_x8","_x9","_x0","_uploadViaEndpoint","_callee3","endpoint","_config$token2","_config$channel2","form","_reqOptions","text","_context3","FormData","append","fieldName","extraFields","_ref6","_ref7","key","parse","_unused","createUploader","sources","_ref3","_callee","_t","_context","onFileUpload","onImageUpload","presignEndpoint","_x1","_x10","_x11","canUpload","Boolean"],"mappings":"uZAqBaA,IAAAA,WAAyBC,GACpC,SAAAD,IAAA,IAAAE,EAEyC,OAFzCC,OAAAH,IACEE,EAAAE,EAAAJ,KAAAA,GAAM,uEACDK,KAAO,2BAA2BH,CACzC,CAAC,OAAAI,EAAAN,EAAAC,GAAAM,EAAAP,EAAA,EAAAQ,EAJ2CC,QAOxCC,EAAcC,QAAQC,IAAIC,qCAAuC,GACjEC,EAAeH,QAAQC,IAAIG,oCAAsC,GAEjEC,EAAW,CAAC,MAAO,SAAU,UAAW,WAAY,WAAY,OAAQ,OAGxE,SAAUC,EAAWC,GACzB,IAAKA,EAAS,OAAO,KACrB,GAAuB,iBAAZA,EAAsB,MAAO,kBAAkBC,KAAKD,GAAWA,EAAU,KACpF,GAAuB,WAAnBE,EAAOF,GAAsB,OAAO,KACxC,IAC0BG,EADpBC,EAASJ,EAAmCK,EAAAC,EAChCR,GAAQ,IAA1B,IAAAO,EAAAE,MAAAJ,EAAAE,EAAAG,KAAAC,MAA4B,CAAA,IACpBC,EAAQN,EADFD,EAAAO,OAEZ,GAAqB,iBAAVA,GAAsBA,EAAO,OAAOA,CAChD,CAAA,CAAA,MAAAC,GAAAN,EAAAO,EAAAD,EAAA,CAAA,QAAAN,EAAAQ,GAAA,CACD,IAAA,I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AQM,eAC7B1H,EAAOyE,iBACPzE,EAAO2H,iBACPzJ,GACA8B,EAAOmG,UACP7H,EAEN"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import React from "react";
|
|
2
|
+
import type { PresignedUploadResult } from "@/types";
|
|
2
3
|
interface S3UploadResponse {
|
|
3
|
-
bucket
|
|
4
|
+
bucket?: string;
|
|
4
5
|
title: string;
|
|
5
6
|
key: string;
|
|
6
7
|
content_type: string;
|
|
@@ -10,8 +11,13 @@ interface S3UploadResponse {
|
|
|
10
11
|
interface FileUploaderProps {
|
|
11
12
|
/** Function called when files are selected */
|
|
12
13
|
onFilesSelected?: (files: File[]) => void;
|
|
13
|
-
/** Function called when upload is triggered */
|
|
14
|
+
/** Function called when upload is triggered (replaces the built-in upload) */
|
|
14
15
|
onUpload?: (files: File[]) => Promise<void>;
|
|
16
|
+
/**
|
|
17
|
+
* Built-in upload: asks YOUR server for a presigned PUT URL, then uploads
|
|
18
|
+
* straight to the bucket. The browser never holds bucket credentials.
|
|
19
|
+
*/
|
|
20
|
+
getPresignedUrl?: (file: File) => Promise<PresignedUploadResult>;
|
|
15
21
|
/** Maximum number of files allowed */
|
|
16
22
|
maxFiles?: number;
|
|
17
23
|
/** Maximum file size in bytes */
|
|
@@ -48,6 +54,7 @@ interface FileUploaderProps {
|
|
|
48
54
|
names?: string;
|
|
49
55
|
module?: string;
|
|
50
56
|
step?: string;
|
|
57
|
+
/** @deprecated Ignored since 0.5.0: the server builds the object key. */
|
|
51
58
|
username?: string | null;
|
|
52
59
|
setResponse?: (response: S3UploadResponse) => void;
|
|
53
60
|
setValues?: (name: string, value: string) => void;
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { FileUploaderType } from "@/types";
|
|
2
2
|
/**
|
|
3
3
|
* A modern file uploader component with drag and drop support.
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
*
|
|
5
|
+
* Uploads straight to the bucket with a presigned PUT URL from the
|
|
6
|
+
* consumer's `getPresignedUrl` (the browser never holds bucket keys),
|
|
7
|
+
* optionally saves a DB record, and on remove deletes the record and calls
|
|
8
|
+
* `deleteFile` so the consumer's server can delete the object.
|
|
6
9
|
*/
|
|
7
|
-
export default function IhubFileUploader({ header, label, accept, maxFileSize, name, module, step,
|
|
10
|
+
export default function IhubFileUploader({ header, label, accept, maxFileSize, name, module, step, onUploadComplete, setValues, setModules, setSteps, className, saveEndpoint, deleteEndpoint, token, getPresignedUrl, deleteFile, onRemove, }: FileUploaderType): import("react/jsx-runtime").JSX.Element;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { PresignedUploadResult } from "@/types";
|
|
2
|
+
/**
|
|
3
|
+
* Upload a file to a presigned PUT URL, reporting progress via XHR.
|
|
4
|
+
*
|
|
5
|
+
* The uploaders never hold bucket credentials: the consumer's
|
|
6
|
+
* `getPresignedUrl(file)` asks its own server for a short-lived URL, and this
|
|
7
|
+
* sends the bytes. `contentType` and any `headers` must match what the server
|
|
8
|
+
* signed, so they are sent verbatim.
|
|
9
|
+
*/
|
|
10
|
+
export declare function uploadToPresignedUrl(url: string, file: File, contentType: string, onProgress: (pct: number) => void, headers?: Record<string, string>): Promise<void>;
|
|
11
|
+
/** Presign with the consumer's function, then PUT. Resolves with the presign result. */
|
|
12
|
+
export declare function presignAndUpload(file: File, getPresignedUrl: (file: File) => Promise<PresignedUploadResult>, onProgress: (pct: number) => void): Promise<PresignedUploadResult>;
|
|
13
|
+
export declare const UPLOADS_NOT_CONFIGURED = "Uploads are not configured: pass getPresignedUrl (a function that asks your server for a presigned PUT URL).";
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import { PaystackConfigObjectType, PaystackConfigType, PaystackResponseType, PaymentContextType } from "@/types";
|
|
1
|
+
import { PaystackConfigObjectType, PaystackConfigType, PaystackResponseType, PaymentContextType, SavedCardChargeOptionsType } from "@/types";
|
|
2
|
+
/** Paystack inline v2 script, needed for server-initialised transactions. */
|
|
3
|
+
export declare const PAYSTACK_INLINE_V2_URL = "https://js.paystack.co/v2/inline.js";
|
|
2
4
|
/**
|
|
3
5
|
* Context for processing payments
|
|
4
6
|
* @property {Event | null} [e] - The event object that triggered the payment
|
|
@@ -17,17 +19,50 @@ import { PaystackConfigObjectType, PaystackConfigType, PaystackResponseType, Pay
|
|
|
17
19
|
* @property {number} [gatwayCharges] - Payment gateway charges percentage
|
|
18
20
|
*/
|
|
19
21
|
/**
|
|
20
|
-
* Configures the Paystack
|
|
22
|
+
* Configures the Paystack popup data.
|
|
23
|
+
*
|
|
24
|
+
* Only the PUBLIC key (`NEXT_PUBLIC_PAYSTACK_PUBLIC_KEY`) is ever read here.
|
|
25
|
+
* The secret key must never reach the browser: anything a `NEXT_PUBLIC_*`
|
|
26
|
+
* variable holds is inlined into the shipped JavaScript.
|
|
21
27
|
* @param obj - Object containing payment details
|
|
22
28
|
* @returns PaystackConfig - Configured payment data
|
|
23
29
|
*/
|
|
24
30
|
export declare const paystackDataConfig: (obj: PaystackConfigObjectType) => PaystackConfigType;
|
|
25
31
|
/**
|
|
26
|
-
* Charges
|
|
27
|
-
*
|
|
28
|
-
*
|
|
32
|
+
* Charges the logged-in user's saved card THROUGH THE APP'S SERVER.
|
|
33
|
+
*
|
|
34
|
+
* The browser never calls Paystack's charge_authorization API and never sends
|
|
35
|
+
* an authorization code or an amount the server trusts. It POSTs only what
|
|
36
|
+
* identifies the purchase (`body`, e.g. the saved payment method id, the item
|
|
37
|
+
* and a coupon code) to `chargeUrl`; the server looks the card up by the
|
|
38
|
+
* logged-in user, prices the item itself and charges it with its own secret
|
|
39
|
+
* key. The server is expected to answer with the Paystack transaction object
|
|
40
|
+
* (`status`, `reference`, `amount`, ...), optionally wrapped in `data`.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* const res = await chargeAuthorization({
|
|
45
|
+
* chargeUrl: `${API_HOST_URL}payments/${channel}/paystack/charge-saved-card/`,
|
|
46
|
+
* token,
|
|
47
|
+
* body: { payment_method_id: card.id, item_type: "course", item_id: course.id },
|
|
48
|
+
* });
|
|
49
|
+
* if (res.status === "success") recordPayment(res);
|
|
50
|
+
* ```
|
|
51
|
+
* @param options - Server endpoint, auth token and purchase identifiers
|
|
52
|
+
* @returns Promise with the transaction data (status "failed" on error)
|
|
53
|
+
*/
|
|
54
|
+
export declare const chargeAuthorization: (options: SavedCardChargeOptionsType) => Promise<any>;
|
|
55
|
+
/**
|
|
56
|
+
* Opens the Paystack popup for a transaction the app's SERVER initialised
|
|
57
|
+
* (POST /transaction/initialize with the secret key), so amount, email and
|
|
58
|
+
* metadata are fixed server-side and cannot be changed in the browser.
|
|
59
|
+
*
|
|
60
|
+
* Uses Paystack inline v2 (`resumeTransaction`). The v2 script is loaded on
|
|
61
|
+
* demand when it is not already on the page.
|
|
62
|
+
* @param accessCode - `access_code` returned by the server's initialize call
|
|
63
|
+
* @returns Promise with the payment response (`status: "canceled"` on close)
|
|
29
64
|
*/
|
|
30
|
-
export declare const
|
|
65
|
+
export declare const payWithAccessCode: (accessCode: string) => Promise<PaystackResponseType>;
|
|
31
66
|
/**
|
|
32
67
|
* Initiates payment with Paystack popup
|
|
33
68
|
* @param config - Payment configuration
|
|
@@ -51,18 +86,19 @@ export declare const payWithPaystack: (config: PaystackConfigType) => Promise<Pa
|
|
|
51
86
|
* email: "user@example.com",
|
|
52
87
|
* amount: 1000,
|
|
53
88
|
* currency: "NGN",
|
|
54
|
-
* authorization_code: "1234567890",
|
|
55
89
|
* first_name: "John",
|
|
56
90
|
* last_name: "Doe",
|
|
57
91
|
* email: "user@example.com",
|
|
58
92
|
* },
|
|
59
93
|
* coupon: "1234567890",
|
|
60
94
|
* gatwayCharges: 10,
|
|
61
|
-
* paymentMethod:
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
* }
|
|
95
|
+
* paymentMethod: savedCard, // from user-payment-method-list
|
|
96
|
+
* // Saved cards are charged by YOUR server, never from the browser.
|
|
97
|
+
* // Without savedCardCharge the user always gets the Paystack popup.
|
|
98
|
+
* savedCardCharge: {
|
|
99
|
+
* chargeUrl: `${API_HOST_URL}payments/${channel}/paystack/charge-saved-card/`,
|
|
100
|
+
* token,
|
|
101
|
+
* body: { item_type: "course", item_id: "123" },
|
|
66
102
|
* },
|
|
67
103
|
* handleDBAction: (data: any) => {
|
|
68
104
|
* console.log(data);
|
|
@@ -32,9 +32,9 @@ export interface EditorPresignResult {
|
|
|
32
32
|
* 1. `onFileUpload` prop (or `onImageUpload` for images)
|
|
33
33
|
* 2. `getPresignedUrl` / `presignEndpoint` / NEXT_PUBLIC_IHUB_EDITOR_PRESIGN_URL
|
|
34
34
|
* 3. `endpoint` / NEXT_PUBLIC_IHUB_EDITOR_UPLOAD_URL (multipart POST, Leadboard style)
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
35
|
+
*
|
|
36
|
+
* There is no direct browser-to-S3 option: that needs the bucket secret in
|
|
37
|
+
* the browser. It was removed in 0.5.0.
|
|
38
38
|
*/
|
|
39
39
|
export interface IHubEditorUploadConfig {
|
|
40
40
|
/** Bearer token sent with presign / endpoint requests via reqOptions. */
|
|
@@ -50,13 +50,6 @@ export interface IHubEditorUploadConfig {
|
|
|
50
50
|
fieldName?: string;
|
|
51
51
|
/** Extra multipart fields sent with the file. */
|
|
52
52
|
extraFields?: Record<string, string>;
|
|
53
|
-
/**
|
|
54
|
-
* Opt in to direct browser → S3 uploads with the NEXT_PUBLIC_AWS_* keys.
|
|
55
|
-
* Defaults to NEXT_PUBLIC_IHUB_EDITOR_DIRECT_S3 === "true". Prefer a presign endpoint.
|
|
56
|
-
*/
|
|
57
|
-
directS3?: boolean;
|
|
58
|
-
/** Folder/prefix for direct S3 uploads (default NEXT_PUBLIC_IHUB_EDITOR_S3_FOLDER or "editor"). */
|
|
59
|
-
s3Folder?: string;
|
|
60
53
|
/** Max upload size per kind in MB. */
|
|
61
54
|
maxSizeMB?: Partial<Record<MediaKind, number>>;
|
|
62
55
|
}
|
|
@@ -168,8 +168,14 @@ export interface FileUploaderType {
|
|
|
168
168
|
module?: string;
|
|
169
169
|
/** Step identifier for setting values */
|
|
170
170
|
step?: string;
|
|
171
|
-
/**
|
|
171
|
+
/** @deprecated Ignored since 0.5.0: the server builds the object key. */
|
|
172
172
|
username?: string | null;
|
|
173
|
+
/**
|
|
174
|
+
* Required to upload. Asks YOUR server for a short-lived presigned PUT URL;
|
|
175
|
+
* the browser never holds bucket credentials. Same contract as
|
|
176
|
+
* S3MultiUploader's `getPresignedUrl`.
|
|
177
|
+
*/
|
|
178
|
+
getPresignedUrl?: (file: File) => Promise<PresignedUploadResult>;
|
|
173
179
|
/** Callback for handling the upload response */
|
|
174
180
|
onUploadComplete?: (response: S3UploadResponseType) => void;
|
|
175
181
|
/** Callback for setting values */
|
|
@@ -186,7 +192,12 @@ export interface FileUploaderType {
|
|
|
186
192
|
deleteEndpoint?: string;
|
|
187
193
|
/** Auth token for API calls (used with reqOptions for saveEndpoint/deleteEndpoint). */
|
|
188
194
|
token?: string | null;
|
|
189
|
-
/**
|
|
195
|
+
/**
|
|
196
|
+
* Called when the user removes an uploaded file, so your server can delete
|
|
197
|
+
* the object (e.g. DELETE /api/uploads/<key>). Errors are logged, not thrown.
|
|
198
|
+
*/
|
|
199
|
+
deleteFile?: (response: S3UploadResponseType) => Promise<void>;
|
|
200
|
+
/** @deprecated Ignored since 0.5.0: pass `deleteFile` to delete objects. */
|
|
190
201
|
enableS3Delete?: boolean;
|
|
191
202
|
/** Callback when a file is removed (after DB + S3 delete). Receives the S3UploadResponseType of the removed file. */
|
|
192
203
|
onRemove?: (response: S3UploadResponseType) => void;
|
|
@@ -586,6 +597,11 @@ export interface PaystackMetadataType {
|
|
|
586
597
|
[key: string]: any;
|
|
587
598
|
}
|
|
588
599
|
export interface PaystackConfigObjectType {
|
|
600
|
+
/**
|
|
601
|
+
* @deprecated Ignored since 0.4.0. Saved cards are charged by the app's
|
|
602
|
+
* server (see `PaymentContextType.savedCardCharge`), which looks the card up
|
|
603
|
+
* itself; the browser no longer handles authorization codes.
|
|
604
|
+
*/
|
|
589
605
|
authorization_code?: string;
|
|
590
606
|
email: string;
|
|
591
607
|
first_name: string;
|
|
@@ -605,8 +621,7 @@ export interface PaystackConfigType {
|
|
|
605
621
|
currency: string;
|
|
606
622
|
amount: number;
|
|
607
623
|
reference?: string;
|
|
608
|
-
|
|
609
|
-
publicKey?: string | undefined;
|
|
624
|
+
/** Paystack PUBLIC key (pk_...). Never put a secret key in browser code. */
|
|
610
625
|
key?: string | undefined;
|
|
611
626
|
callback_url?: string;
|
|
612
627
|
metadata?: PaystackMetadataType;
|
|
@@ -661,6 +676,26 @@ export interface PaymentContextType {
|
|
|
661
676
|
defaultMsg?: string;
|
|
662
677
|
gatwayCharges?: number;
|
|
663
678
|
openConfirm?: boolean;
|
|
679
|
+
/**
|
|
680
|
+
* Server endpoint that charges `paymentMethod`. When omitted, saved cards
|
|
681
|
+
* are not offered and the Paystack popup is used.
|
|
682
|
+
*/
|
|
683
|
+
savedCardCharge?: SavedCardChargeOptionsType;
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* Options for charging a saved card through the app's own server.
|
|
687
|
+
* The server looks the card up by the logged-in user and prices the item;
|
|
688
|
+
* the browser sends identifiers only.
|
|
689
|
+
*/
|
|
690
|
+
export interface SavedCardChargeOptionsType {
|
|
691
|
+
/** Absolute URL of the server endpoint that performs the charge. */
|
|
692
|
+
chargeUrl: string;
|
|
693
|
+
/** Bearer token of the logged-in user. */
|
|
694
|
+
token?: string | null;
|
|
695
|
+
/** Optional channel header passed to `reqOptions`. */
|
|
696
|
+
channel?: string | null;
|
|
697
|
+
/** Purchase identifiers, e.g. payment_method_id, item_type, item_id, coupon. */
|
|
698
|
+
body?: Record<string, any>;
|
|
664
699
|
}
|
|
665
700
|
export interface PaymentReferenceType {
|
|
666
701
|
reference: string;
|