Maybe this post can give you some inspiration. To set the metadata you probably need to include a library, like xmldom.
The code I wrote is for setting layer metadata though, which is a bit less complicated I assume since I’m omitting the correct XMP format/structure. Layer metadata is just undefined or an empty object (I don’t remember), so I can simply set it to any stringified json.
The document metadata has a fixed structure though, so you should be careful to respect that when setting metadata. It’s definitely possible with the mentioned library though.