let wasm;

const cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });

cachedTextDecoder.decode();

let cachedUint8Memory0 = null;

function getUint8Memory0() {
    if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) {
        cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer);
    }
    return cachedUint8Memory0;
}

function getStringFromWasm0(ptr, len) {
    return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
}

const heap = new Array(128).fill(undefined);

heap.push(undefined, null, true, false);

let heap_next = heap.length;

function addHeapObject(obj) {
    if (heap_next === heap.length) heap.push(heap.length + 1);
    const idx = heap_next;
    heap_next = heap[idx];

    heap[idx] = obj;
    return idx;
}

function getObject(idx) { return heap[idx]; }

let WASM_VECTOR_LEN = 0;

const cachedTextEncoder = new TextEncoder('utf-8');

const encodeString = (typeof cachedTextEncoder.encodeInto === 'function'
    ? function (arg, view) {
    return cachedTextEncoder.encodeInto(arg, view);
}
    : function (arg, view) {
    const buf = cachedTextEncoder.encode(arg);
    view.set(buf);
    return {
        read: arg.length,
        written: buf.length
    };
});

function passStringToWasm0(arg, malloc, realloc) {

    if (realloc === undefined) {
        const buf = cachedTextEncoder.encode(arg);
        const ptr = malloc(buf.length);
        getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf);
        WASM_VECTOR_LEN = buf.length;
        return ptr;
    }

    let len = arg.length;
    let ptr = malloc(len);

    const mem = getUint8Memory0();

    let offset = 0;

    for (; offset < len; offset++) {
        const code = arg.charCodeAt(offset);
        if (code > 0x7F) break;
        mem[ptr + offset] = code;
    }

    if (offset !== len) {
        if (offset !== 0) {
            arg = arg.slice(offset);
        }
        ptr = realloc(ptr, len, len = offset + arg.length * 3);
        const view = getUint8Memory0().subarray(ptr + offset, ptr + len);
        const ret = encodeString(arg, view);

        offset += ret.written;
    }

    WASM_VECTOR_LEN = offset;
    return ptr;
}

let cachedInt32Memory0 = null;

function getInt32Memory0() {
    if (cachedInt32Memory0 === null || cachedInt32Memory0.byteLength === 0) {
        cachedInt32Memory0 = new Int32Array(wasm.memory.buffer);
    }
    return cachedInt32Memory0;
}

let stack_pointer = 128;

function addBorrowedObject(obj) {
    if (stack_pointer == 1) throw new Error('out of js stack');
    heap[--stack_pointer] = obj;
    return stack_pointer;
}

function dropObject(idx) {
    if (idx < 132) return;
    heap[idx] = heap_next;
    heap_next = idx;
}

function takeObject(idx) {
    const ret = getObject(idx);
    dropObject(idx);
    return ret;
}
/**
* @param {any} data_type_obj
* @returns {any}
*/
function validateDataType(data_type_obj) {
    try {
        const ret = wasm.validateDataType(addBorrowedObject(data_type_obj));
        return takeObject(ret);
    } finally {
        heap[stack_pointer++] = undefined;
    }
}

/**
* @param {any} entity_type_obj
* @returns {any}
*/
function validateEntityType(entity_type_obj) {
    try {
        const ret = wasm.validateEntityType(addBorrowedObject(entity_type_obj));
        return takeObject(ret);
    } finally {
        heap[stack_pointer++] = undefined;
    }
}

/**
* @param {any} property_type_obj
* @returns {any}
*/
function validatePropertyType(property_type_obj) {
    try {
        const ret = wasm.validatePropertyType(addBorrowedObject(property_type_obj));
        return takeObject(ret);
    } finally {
        heap[stack_pointer++] = undefined;
    }
}

async function load(module, imports) {
    if (typeof Response === 'function' && module instanceof Response) {
        if (typeof WebAssembly.instantiateStreaming === 'function') {
            try {
                return await WebAssembly.instantiateStreaming(module, imports);

            } catch (e) {
                if (module.headers.get('Content-Type') != 'application/wasm') {
                    console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);

                } else {
                    throw e;
                }
            }
        }

        const bytes = await module.arrayBuffer();
        return await WebAssembly.instantiate(bytes, imports);

    } else {
        const instance = await WebAssembly.instantiate(module, imports);

        if (instance instanceof WebAssembly.Instance) {
            return { instance, module };

        } else {
            return instance;
        }
    }
}

function getImports() {
    const imports = {};
    imports.wbg = {};
    imports.wbg.__wbindgen_json_parse = function(arg0, arg1) {
        const ret = JSON.parse(getStringFromWasm0(arg0, arg1));
        return addHeapObject(ret);
    };
    imports.wbg.__wbindgen_json_serialize = function(arg0, arg1) {
        const obj = getObject(arg1);
        const ret = JSON.stringify(obj === undefined ? null : obj);
        const ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
        const len0 = WASM_VECTOR_LEN;
        getInt32Memory0()[arg0 / 4 + 1] = len0;
        getInt32Memory0()[arg0 / 4 + 0] = ptr0;
    };
    imports.wbg.__wbindgen_throw = function(arg0, arg1) {
        throw new Error(getStringFromWasm0(arg0, arg1));
    };

    return imports;
}

function finalizeInit(instance, module) {
    wasm = instance.exports;
    init.__wbindgen_wasm_module = module;
    cachedInt32Memory0 = null;
    cachedUint8Memory0 = null;


    return wasm;
}

function initSync(module) {
    const imports = getImports();

    if (!(module instanceof WebAssembly.Module)) {
        module = new WebAssembly.Module(module);
    }

    const instance = new WebAssembly.Instance(module, imports);

    return finalizeInit(instance, module);
}

async function init(input) {
    if (typeof input === 'undefined') {
        input = new URL('type-system_bg.wasm', "");
    }
    const imports = getImports();

    if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) {
        input = fetch(input);
    }

    const { instance, module } = await load(await input, imports);

    return finalizeInit(instance, module);
}

let initialized = undefined;
class TypeSystemInitializer {
    constructor() { }
}
/**
 * Initializes the package. There is a one time global setup fee (sub 30ms), but subsequent
 * requests to initialize will be instantaneous, so it's not imperative to reuse the same parser.
 */
TypeSystemInitializer.initialize = async (options) => {
    if (initialized === undefined) {
        const loadModule = options ?? (undefined);
        initialized = init(loadModule).then(() => undefined);
    }
    await initialized;
    return new TypeSystemInitializer();
};

/**
 * Returns all the IDs of all types referenced in a given property type.
 *
 * @param {EntityType} entityType
 */
const getReferencedIdsFromEntityType = (entityType) => {
    const constrainsPropertiesOnPropertyTypes = new Set();
    const constrainsLinksOnEntityTypes = new Set();
    const constrainsLinkDestinationsOnEntityTypes = new Set();
    for (const propertyDefinition of Object.values(entityType.properties)) {
        if ("items" in propertyDefinition) {
            constrainsPropertiesOnPropertyTypes.add(propertyDefinition.items.$ref);
        }
        else {
            constrainsPropertiesOnPropertyTypes.add(propertyDefinition.$ref);
        }
    }
    // for (const inheritedEntityType of entityType.allOf ?? []) {
    //   values.push(inheritedEntityType.$ref)
    // }
    for (const [linkTypeId, linkDefinition] of Object.entries(entityType.links ?? {})) {
        /** @todo - if we had the `typedEntries` helper here we wouldn't need this cast */
        constrainsLinksOnEntityTypes.add(linkTypeId);
        if (linkDefinition.items.oneOf !== undefined) {
            linkDefinition.items.oneOf
                .map((oneOfEntry) => oneOfEntry.$ref)
                .forEach((ele) => constrainsLinkDestinationsOnEntityTypes.add(ele));
        }
    }
    return {
        constrainsPropertiesOnPropertyTypes: [
            ...constrainsPropertiesOnPropertyTypes,
        ],
        constrainsLinksOnEntityTypes: [...constrainsLinksOnEntityTypes],
        constrainsLinkDestinationsOnEntityTypes: [
            ...constrainsLinkDestinationsOnEntityTypes,
        ],
    };
};

/**
 * Type guard to determine if a given {@link PropertyValues} is an array definition.
 *
 * @param {PropertyValues} propertyValues
 */
const isPropertyValuesArray = (propertyValues) => "type" in propertyValues && propertyValues.type === "array";
/**
 * Returns all the IDs of all types referenced in a given property type.
 *
 * @param {PropertyType} propertyType
 */
const getReferencedIdsFromPropertyType = (propertyType) => {
    const recurseOneOf = (oneOf) => {
        const constrainsValuesOnDataTypes = new Set();
        const constrainsPropertiesOnPropertyTypes = new Set();
        for (const oneOfValue of oneOf) {
            if (isPropertyValuesArray(oneOfValue)) {
                const nestedIds = recurseOneOf(oneOfValue.items.oneOf);
                nestedIds.constrainsPropertiesOnPropertyTypes.forEach((ele) => constrainsPropertiesOnPropertyTypes.add(ele));
                nestedIds.constrainsValuesOnDataTypes.forEach((ele) => constrainsValuesOnDataTypes.add(ele));
            }
            else if ("properties" in oneOfValue) {
                // property type object definition
                for (const propertyDefinition of Object.values(oneOfValue.properties)) {
                    if ("items" in propertyDefinition) {
                        constrainsPropertiesOnPropertyTypes.add(propertyDefinition.items.$ref);
                    }
                    else {
                        constrainsPropertiesOnPropertyTypes.add(propertyDefinition.$ref);
                    }
                }
            }
            else {
                // data type reference
                constrainsValuesOnDataTypes.add(oneOfValue.$ref);
            }
        }
        return { constrainsValuesOnDataTypes, constrainsPropertiesOnPropertyTypes };
    };
    const { constrainsValuesOnDataTypes, constrainsPropertiesOnPropertyTypes } = recurseOneOf(propertyType.oneOf);
    return {
        constrainsValuesOnDataTypes: [...constrainsValuesOnDataTypes],
        constrainsPropertiesOnPropertyTypes: [
            ...constrainsPropertiesOnPropertyTypes,
        ],
    };
};

/**
 * Checks if a given URL string is a valid base URL.
 *
 * @param {BaseUri} uri - The URL string.
 * @returns {(Result<BaseUri, ParseBaseUriError>)} - an Ok with an inner of the string as a
 * BaseUri if valid, or an Err with an inner ParseBaseUriError
 */
const validateBaseUri = (uri) => {
    try {
        void new URL(uri);
        if (uri.endsWith("/")) {
            return {
                type: "Ok",
                inner: uri,
            };
        }
        else {
            return {
                type: "Err",
                inner: { reason: "MissingTrailingSlash" },
            };
        }
    }
    catch (err) {
        return {
            type: "Err",
            inner: { reason: "UrlParseError", inner: JSON.stringify(err) },
        };
    }
};
const versionedUriRegExp = /(.+\/)v\/(\d+)(.*)/;
/**
 * Checks if a given URL string is a Block Protocol compliant Versioned URI.
 *
 * @param {string} uri - The URL string.
 * @returns {(Result<VersionedUri, ParseVersionedUriError>)} - an Ok with an inner of the string
 as
 * a VersionedUri if valid, or an Err with an inner ParseVersionedUriError
 */
const validateVersionedUri = (uri) => {
    const groups = versionedUriRegExp.exec(uri);
    if (groups === null) {
        return {
            type: "Err",
            inner: { reason: "IncorrectFormatting" },
        };
    }
    else {
        const [_match, baseUri, version, trailingContent] = groups;
        if (trailingContent) {
            return {
                type: "Err",
                inner: { reason: "AdditionalEndContent" },
            };
        }
        if (!version) {
            return {
                type: "Err",
                inner: { reason: "MissingVersion" },
            };
        }
        if (!baseUri) {
            return {
                type: "Err",
                inner: { reason: "MissingBaseUri" },
            };
        }
        const validBaseUriResult = validateBaseUri(baseUri);
        if (validBaseUriResult.type === "Err") {
            return {
                type: "Err",
                inner: { reason: "InvalidBaseUri", inner: validBaseUriResult.inner },
            };
        }
        const versionNumber = Number(version);
        if (!Number.isInteger(versionNumber) || versionNumber < 0) {
            return {
                type: "Err",
                inner: {
                    reason: "InvalidVersion",
                    inner: `\`${version}\` is not a valid non-negative integer`,
                },
            };
        }
        return { type: "Ok", inner: uri };
    }
};
/**
 * Extracts the base URI from a Versioned URI.
 *
 * @param {VersionedUri} uri - The versioned URI.
 * @throws if the versioned URI is invalid.
 */
const extractBaseUri = (uri) => {
    const groups = versionedUriRegExp.exec(uri);
    if (groups === null) {
        throw new Error(`Not a valid VersionedUri: ${uri}`);
    }
    const [_match, baseUri, _version] = groups;
    if (baseUri === undefined) {
        throw new Error(`Not a valid VersionedUri: ${uri}`);
    }
    return baseUri;
};
/**
 * Extracts the version from a Versioned URI.
 *
 * @param {VersionedUri} uri - The versioned URI.
 * @throws if the versioned URI is invalid.
 */
const extractVersion = (uri) => {
    const groups = versionedUriRegExp.exec(uri);
    if (groups === null) {
        throw new Error(`Not a valid VersionedUri: ${uri}`);
    }
    const [_match, _baseUri, version] = groups;
    return Number(version);
};

export { TypeSystemInitializer, extractBaseUri, extractVersion, getReferencedIdsFromEntityType, getReferencedIdsFromPropertyType, initSync, isPropertyValuesArray, validateBaseUri, validateDataType, validateEntityType, validatePropertyType, validateVersionedUri };
