"""APMSG asset ZIP + manifest builder. Python 3, standard library only. Choose a folder containing only files intended for buyers. Never point this at an entire development repo. Nothing is executed, fetched or sent to APMSG. """ import argparse import hashlib import json import pathlib import re import stat import shutil import zipfile def build(source, metadata, output): source, output = pathlib.Path(source).resolve(), pathlib.Path(output).resolve() if output == source or source in output.parents: raise ValueError('Output must be outside the buyer-files folder') data = json.loads(pathlib.Path(metadata).read_text(encoding='utf-8-sig')) if not re.fullmatch(r'seller-[a-f0-9]{24}', data.get('slug', '')): raise ValueError('Copy the exact seller draft slug from APMSG') if not re.fullmatch(r'(0|[1-9]\d{0,5})\.(0|[1-9]\d{0,5})\.(0|[1-9]\d{0,5})', data.get('version', '')): raise ValueError('Version must be major.minor.patch, for example 1.0.0') allowed = {'.glb','.gltf','.obj','.fbx','.blend','.stl','.png','.jpg','.jpeg','.webp','.tga','.wav','.ogg','.bin','.mtl','.txt','.md','.json'} files, total, folded = [], 0, set() for file in sorted(source.rglob('*')): if file.is_symlink() or getattr(file.lstat(), 'st_file_attributes', 0) & 1024: raise ValueError('Links and reparse points are not allowed') if file.is_dir(): continue if not stat.S_ISREG(file.stat().st_mode): raise ValueError('Only regular files are allowed') name = file.relative_to(source).as_posix() if name != 'LICENSE' and file.suffix.lower() not in allowed: raise ValueError('Unsupported buyer file: ' + name) if name.casefold() in folded or any(part.startswith('.') or ':' in part or part.endswith((' ', '.')) for part in name.split('/')): raise ValueError('Unsafe or duplicate filename: ' + name) folded.add(name.casefold()) total += file.stat().st_size if len(files) >= 4000 or total > 2*1024*1024*1024 or file.stat().st_size > 128*1024*1024: raise ValueError('Package exceeds the published size or entry limits') files.append((name, file)) if not {'README.md', 'LICENSE'} <= {n for n,_ in files}: raise ValueError('README.md and LICENSE are required') output.mkdir(parents=True, exist_ok=True) archive = output / (data['slug'] + '-' + data['version'] + '.zip') manifest = archive.with_suffix('.json') if archive.exists() or manifest.exists(): raise ValueError('Output already exists; use a new output directory') try: with zipfile.ZipFile(archive, 'x') as z: for name, source_file in files: info = zipfile.ZipInfo(name, date_time=(2026,1,1,0,0,0)) info.create_system = 3 info.external_attr = (stat.S_IFREG | 0o644) << 16 # Stored entries avoid surprising high expansion ratios. with source_file.open("rb") as source_stream, z.open(info, "w", force_zip64=True) as dest: shutil.copyfileobj(source_stream,dest,1024*1024) size = archive.stat().st_size if size > 1024*1024*1024: raise ValueError('ZIP exceeds 1 GiB; split the collection') inventory = {} for name, source_file in files: with source_file.open('rb') as stream: inventory[name] = hashlib.file_digest(stream,'sha256').hexdigest() with archive.open('rb') as stream: digest = hashlib.file_digest(stream,'sha256').hexdigest() result = {k: data[k] for k in ('slug','version','changelog','asset')} result.update(schemaVersion=1, kind='asset', capabilities=['game-asset'], permissions=[], files=inventory, licenseSha256=inventory['LICENSE'], bytes=size, sha256=digest) with manifest.open('x', encoding='utf-8') as f: json.dump(result, f, ensure_ascii=False, indent=2) return {'archive':str(archive), 'manifest':str(manifest), 'sha256':result['sha256'], 'bytes':size} except BaseException: archive.unlink(missing_ok=True) raise def describe_archive(archive, metadata, output): """Describe an existing native Skirmforge ZIP without changing any ZIP byte.""" archive=pathlib.Path(archive).resolve();output=pathlib.Path(output).resolve() if archive.stat().st_size>1024*1024*1024:raise ValueError('ZIP exceeds 1 GiB') data=json.loads(pathlib.Path(metadata).read_text(encoding='utf-8-sig')) if not re.fullmatch(r'seller-[a-f0-9]{24}',data.get('slug','')):raise ValueError('Copy the seller draft slug') with zipfile.ZipFile(archive) as z: if len(z.infolist())>4000 or sum(e.file_size for e in z.infolist())>2*1024*1024*1024:raise ValueError('ZIP expansion limit') inventory={} for entry in z.infolist(): if entry.is_dir():continue if entry.file_size>128*1024*1024 or entry.filename in inventory:raise ValueError('File limit or duplicate') with z.open(entry) as stream:inventory[entry.filename]=hashlib.file_digest(stream,'sha256').hexdigest() if z.getinfo('skirmforge-pack.json').file_size>4*1024*1024:raise ValueError('Native manifest limit') native=json.loads(z.read('skirmforge-pack.json')) if native.get('schemaId')!='skirmforge-pack/1' or native.get('files')!={k:v for k,v in inventory.items() if k!='skirmforge-pack.json'}:raise ValueError('Native inventory mismatch') if data['version']!=native['version']:raise ValueError('Use the native pack version') data['asset'].update(type='asset-pack',skirmforgePack=True,entrypoints=[n for n in inventory if n.startswith(('models/','game/')) and n.endswith('.glb')]) with archive.open('rb') as stream:digest=hashlib.file_digest(stream,'sha256').hexdigest() result={k:data[k] for k in ('slug','version','changelog','asset')} result.update(schemaVersion=1,kind='asset',capabilities=['game-asset','skirmforge-pack'],permissions=[],files=inventory,licenseFile='LICENSE.txt',licenseSha256=inventory['LICENSE.txt'],bytes=archive.stat().st_size,sha256=digest) output.mkdir(parents=True,exist_ok=True) manifest=output/(data['slug']+'-'+data['version']+'.json') with manifest.open('x',encoding='utf-8') as f:json.dump(result,f,ensure_ascii=False,indent=2) return {'archive':str(archive),'manifest':str(manifest),'sha256':digest,'bytes':result['bytes']} if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) source=parser.add_mutually_exclusive_group(required=True) source.add_argument('--source') source.add_argument('--archive', help='An existing native Skirmforge pack; ZIP stays byte-for-byte unchanged') parser.add_argument('--metadata', required=True) parser.add_argument('--output', required=True) args = parser.parse_args() print(json.dumps(build(args.source,args.metadata,args.output) if args.source else describe_archive(args.archive,args.metadata,args.output),indent=2))