import fs from"node:fs";import path from"node:path";import{cleanHTML}from"./validators.mjs";import Files from"../files/files.mjs";import{fromUuid}from"../core/utils.mjs";import{randomID}from"../../common/utils/helpers.mjs";import{EmbeddedCollectionField,EmbeddedDocumentField,FilePathField}from"../../common/data/fields.mjs";export function sanitizeFilePathField(e,{assetPath:t,document:i,documentId:n,fieldPath:o,user:r}={}){if(null==e||""===e)return e;if(this.texture&&e.startsWith("#"))return e;if("string"!=typeof e)return null;if(this.base64)return e;const a=e.match(/^data:([a-z]+)\/([a-z0-9]+);base64,(.*)/);if(!a)return e;if(r&&!r.can("FILES_UPLOAD"))throw new Error(`You lack FILES_UPLOAD permission and may not upload base64 data to the ${this.name} field.`);const[s,d]=a.slice(2,4);n??=i._id;const l=`${[n,...o].filterJoin("-")}.${s}`,m=path.join(t,l);return fs.mkdirSync(t,{recursive:!0}),fs.writeFileSync(m,Buffer.from(d,"base64")),global.logger.info(`Extracted base64 asset: "${m}"`),Files.standardizePath(path.relative(global.paths.data,m))}export async function handleDocumentAssetUpload(e,t){const i=await fromUuid(e),n=i.constructor.extractedAssetPath,o=t.name.split("."),r=o.pop();return t.name=`${o.join(".")}-${randomID()}.${r}`,t.name=i.parent?[i.parent.id,i.collectionName,i.id,t.name].join("-"):t.name,fs.mkdirSync(n,{recursive:!0}),Files.standardizePath(path.relative(global.paths.data,n))}export function sanitizeHTMLField(e,t={}){return null==e||""===e?e:"string"!=typeof e?"":cleanHTML(e)}export function sanitizeEmbeddedCollectionField(e,t={}){const i=t.document?.[t.fieldPath.at(-1)];for(const[n,o]of e.entries()){const r=i?.get(o._id),a={document:r,documentId:o._id,fieldPath:t.fieldPath.concat([o._id])};i&&!r&&(a.creation=!0),e[n]=this.model.sanitizeUserInput(o,{...t,...a})}return e}export function sanitizeEmbeddedDocumentField(e,t={}){const i=t.document?.[t.fieldPath.at(-1)];return this.model.sanitizeUserInput(e,{...t,document:i,documentId:e?._id})}export function sanitizeDocumentOwnershipField(e,{creation:t,document:i,fieldPath:n,user:o}={}){if(!1!==o?.isGM)return e;let r=!1;for(const[n,a]of Object.entries(e))a!==i?.ownership[n]&&("default"===n?t||(r=!0):n!==o.id&&(t?delete e[n]:r=!0));if(r)throw new Error(`The "${n.join(".")}" field may only be modified by a GM or Assistant GM user.`);return e}export function sanitizeDocumentAuthorField(e,{creation:t,fieldPath:i,user:n}={}){if(t&&!1===n?.isGM)return n.id;if(!1===n?.isGM)throw new Error(`The "${i.join(".")}" field may only be modified by a GM or Assistant GM user.`);return e}