/* eslint-disable no-lone-blocks */ /* eslint-disable multiline-comment-style */ import type fs from 'fs-extra' import type { SandstoneCommands } from 'sandstone/commands/commands' import { type Node, type SandstoneCore } from 'sandstone/core' import type { ResourcePath, SandstonePack } from 'sandstone/pack' import type { PackType } from 'sandstone/pack/packType' import type { BASIC_CONFLICT_STRATEGIES, LiteralUnion, MakeInstanceCallable, NamespacedString } from 'sandstone/utils' import type { NBTSerializable } from 'sandstone/arguments/nbt' import { getSandstoneContext, hasContext } from 'sandstone/context' import { RESOURCE_PATHS } from 'sandstone/arguments/generated/resource-paths' export type ResourceClassArguments = { /** * Whether the associated Node should be added to Sandstone Core. */ addToSandstoneCore: boolean /** * Whether the resource has been created explicitely by a user, or automatically generated by Sandstone. */ creator: 'user' | 'sandstone' /** * What to do if another resource of the same type has the same name. * * - `throw`: Throw an error. * - `replace`: Replace silently the old resource with the new one. * - `ignore`: Keep silently the old resource, discarding the new one. * - `append`: Append the new resource entries to the old one. * - `prepend`: Prepend the new resource entries to the old one. * - `rename`: Rename the new file to an iterating number (ie. func1, func2, func3) */ // eslint-disable-next-line max-len onConflict?: ConflictType extends 'default' ? BASIC_CONFLICT_STRATEGIES : BASIC_CONFLICT_STRATEGIES | 'append' | 'prepend' /** * Overrides the default pack for the resource. */ packType?: PackType } export type ResourceNode> = Node & { resource: T } export type ResourceNodeConstructor = new (sandstoneCore: SandstoneCore, resource: any) => N export abstract class ResourceClass> implements NBTSerializable { /* @internal */ node: N packType /* @internal */ fileExtension /* @internal */ fileEncoding /* @internal */ creator: NonNullable['creator']> /* @internal */ commands: SandstoneCommands pack: SandstonePack path /* @internal */ addToSandstoneCore: boolean onConflict: LiteralUnion /* @internal */ renameIndex = 2 // eslint-disable-next-line max-len constructor( protected core: SandstoneCore, file: { packType: PackType; extension?: string; encoding?: fs.EncodingOption | false }, NodeType: ResourceNodeConstructor, readonly _resourceType: string, path: ResourcePath, args: ResourceClassArguments, ) { this.node = new NodeType(core, this) this.packType = args.packType || file.packType this.fileExtension = file.extension || 'json' this.fileEncoding = file.encoding ?? 'utf8' this.pack = core.pack this.commands = core.pack.commands this.path = path this.addToSandstoneCore = args.addToSandstoneCore this.creator = args.creator ?? 'sandstone' // Get conflict strategies from context if available, otherwise use defaults const conflictStrategies = hasContext() ? getSandstoneContext().conflictStrategies : undefined const scopedStrategy = conflictStrategies?.[_resourceType] as LiteralUnion | undefined const defaultStrategy = conflictStrategies?.default as LiteralUnion | undefined this.onConflict = args.onConflict ?? scopedStrategy ?? defaultStrategy ?? 'throw' } protected handleConflicts() { const conflict = this.core.resourceNodes.get(this.node) let add = false if (conflict) { const oldResource = conflict.resource const newResource = this.node.resource switch (this.onConflict) { case 'throw': { throw new Error( `Created a ${this._resourceType} with the duplicate name ${newResource.name}, and onConflict was set to "throw".`, ) } case 'replace': { this.core.resourceNodes.delete(conflict) add = true } break case 'warn': { console.warn( [ 'Warning:', `Tried to create a ${this._resourceType} named "${newResource.name}", but found an already existing one.`, 'The new one has replaced the old one. To remove this warning, please change the options of the resource to { onConflict: \'/* other option */\' }.', ].join('\n'), ) this.core.resourceNodes.delete(conflict) add = true } break case 'rename': { this.path[this.path.length - 1] += oldResource.renameIndex.toString() // Future resources clashing on the same name will have a higher index oldResource.renameIndex += 1 add = true } break case 'prepend': { ;(oldResource as unknown as ListResource).unshift(newResource) } break case 'append': { ;(oldResource as unknown as ListResource).push(newResource) } break default: break } } else { add = true } if (this.addToSandstoneCore && add) { this.core.resourceNodes.add(this.node) } } protected getNode = () => this.node get name(): NamespacedString | `${string}:${string}` { return `${this.path[0]}:${this.path.slice( this._resourceType in RESOURCE_PATHS ? RESOURCE_PATHS[this._resourceType as keyof typeof RESOURCE_PATHS].path.length + 1 : 2 ).join('/')}` as NamespacedString } get namespace(): string { return this.path[0] } generate = () => {} toString(): string { return this.name } toNBT(): string { return `'${this.name}'` } /** * @internal */ toJSON(): any { return this.name } } export abstract class CallableResourceClass> extends ResourceClass { // This is the resource, but as a callable private _that: MakeInstanceCallable | undefined protected get asCallable() { if (!this._that) { throw new Error('Class has not been made callable.') } return this._that } abstract __call__: (...args: any) => any } export abstract class ListResource extends ResourceClass { public push(..._args: any[]) {} public unshift(..._args: any[]) {} } export abstract class JsonResource extends ResourceClass { json: unknown = {} } export abstract class TextResource extends ResourceClass { text: unknown = '' } export abstract class BinaryResource extends ResourceClass { buffer: Promise | ArrayBuffer | Buffer = {} as unknown as ArrayBuffer } /** * A Map-like structure to store ResourceNodes, allowing for easy iteration and management of resources. * It uses the resource's path + packType as the key, ensuring that resources with the same path are treated as the same resource. */ export class ResourceNodesMap { private nodes = new Map() constructor(iterable: Iterable = []) { for (const value of iterable) { this.add(value) } } forEach(callback: (value: T) => void): void { this.nodes.forEach((value) => { callback(value) }) } private getKey(value: T): string { return `${value.resource.packType.constructor.name}|${value.resource.path.join('/')}|${value.resource.fileExtension}` } add(value: T): this { this.nodes.set(this.getKey(value), value) return this } delete(value: T): boolean { return this.nodes.delete(this.getKey(value)) } clear(): void { this.nodes.clear() } [Symbol.iterator](): Iterator { return this.nodes.values()[Symbol.iterator]() } get size(): number { return this.nodes.size } /** * Check if a resource node is present in the set, **based on its path and packType**, and returns it. * @param node The resource node to check. * @returns The resource node if it exists, otherwise `undefined`. */ get(node: T): T | undefined { return this.nodes.get(this.getKey(node)) } } export function jsonStringify(json: any, resourceType: keyof typeof RESOURCE_PATHS) { return JSON.stringify( json, function (this, key, value) { // Currently unused, I might need to replace this with something more robust if ( (typeof value === 'object' || typeof value === 'function') && value.constructor.name !== 'Object' && 'toResourceJSON' in value ) { return value.toResourceJSON(key, this, resourceType, json) } return value }, 2, ) }