@imgly/plugin-ai-image-generation-web 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/middleware.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/response.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/node_modules/@fal-ai/client/package.json", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/runtime.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/config.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/utils.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/request.ts", "../../../../node_modules/.pnpm/eventsource-parser@1.1.2/node_modules/eventsource-parser/src/parse.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/auth.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/streaming.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/queue.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/utils/utf8.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/ExtData.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/DecodeError.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/utils/int.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/timestamp.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/ExtensionCodec.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/utils/typedArrays.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/Encoder.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/encode.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/utils/prettyByte.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/CachedKeyDecoder.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/Decoder.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/decode.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/utils/stream.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/decodeAsync.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/index.ts", "../../../../node_modules/.pnpm/robot3@0.4.1/node_modules/robot3/dist/machine.js", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/realtime.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/storage.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/client.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/types/common.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/index.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/icons/formats.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/assetSources/CustomAssetSource.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/assetSources/IndexedDBAssetSource.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/assetSources/AggregatedAssetSource.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/metadata/Metadata.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_freeGlobal.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_root.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Symbol.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getRawTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_objectToString.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGetTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isObjectLike.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isObject.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isFunction.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_coreJsData.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isMasked.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_toSource.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsNative.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getValue.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getNative.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_WeakMap.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isIndex.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/eq.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isLength.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArrayLike.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isPrototype.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseTimes.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsArguments.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArguments.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/stubFalse.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isBuffer.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsTypedArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseUnary.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nodeUtil.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isTypedArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayLikeKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_overArg.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/keys.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeCreate.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Hash.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_assocIndexOf.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_ListCache.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Map.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isKeyable.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getMapData.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_MapCache.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayPush.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Stack.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayFilter.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/stubArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getSymbols.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGetAllKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getAllKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_DataView.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Promise.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Set.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Uint8Array.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setCacheAdd.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setCacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_SetCache.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arraySome.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalArrays.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapToArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setToArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalByTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalObjects.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsEqualDeep.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsEqual.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isEqual.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/metadata/FillProcessingMetadata.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/fillProcessing.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/constants.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/initializeFillProcessing.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/registerFillProcessingComponents.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/colors.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/upload.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/uuid.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/images.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/index.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/common/renderImageUrlProperty.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/openapi/dereferenceDocument.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/openapi/isOpenAPISchema.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/openapi/getProperties.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/utils.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/openapi/renderProperty.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/previewUri.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/getAssetResultForPlaceholder.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/getAssetResultForGenerated.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/middleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/loggingMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/icons/formats.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/assetSources/CustomAssetSource.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/assetSources/IndexedDBAssetSource.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/assetSources/AggregatedAssetSource.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/metadata/Metadata.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_freeGlobal.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_root.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Symbol.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getRawTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_objectToString.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGetTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isObjectLike.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isObject.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isFunction.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_coreJsData.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isMasked.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_toSource.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsNative.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getValue.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getNative.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_WeakMap.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isIndex.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/eq.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isLength.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArrayLike.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isPrototype.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseTimes.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsArguments.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArguments.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/stubFalse.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isBuffer.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsTypedArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseUnary.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nodeUtil.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isTypedArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayLikeKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_overArg.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/keys.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeCreate.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Hash.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_assocIndexOf.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_ListCache.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Map.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isKeyable.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getMapData.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_MapCache.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayPush.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Stack.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayFilter.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/stubArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getSymbols.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGetAllKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getAllKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_DataView.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Promise.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Set.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Uint8Array.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setCacheAdd.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setCacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_SetCache.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arraySome.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalArrays.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapToArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setToArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalByTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalObjects.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsEqualDeep.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsEqual.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isEqual.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/metadata/FillProcessingMetadata.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/fillProcessing.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/constants.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/initializeFillProcessing.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/registerFillProcessingComponents.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/colors.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/upload.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/uuid.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/images.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/index.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/dryRunMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/generate.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/handleGenerationError.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/renderGenerationComponents.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/registerPanelInputSchema.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/registerPanelInputCustom.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/icons.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/getQuickActionMenu.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/utils.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/highlightBlocksMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/pendingMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/lockMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/consumeGeneratedResult.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/editModeMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/generate.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/registerQuickActionMenuComponent.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/initProvider.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/uploadMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/rateLimitMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/registerDockComponent.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionBasePrompt.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionBaseButton.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionBaseSelect.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionEditTextStyle.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/enableImageFill.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionChangeImage.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionImageVariant.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionSwapImageBackground.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/index.ts", "../../src/fal-ai/RecraftV3.json", "../../src/fal-ai/RecraftV3.constants.ts", "../../src/fal-ai/createImageProvider.ts", "../../src/fal-ai/utils.ts", "../../src/fal-ai/RecraftV3.ts", "../../src/fal-ai/GeminiFlashEdit.json", "../../src/fal-ai/GeminiFlashEdit.ts", "../../src/fal-ai/index.ts"],
4
- "sourcesContent": ["/**\n * A request configuration object.\n *\n * **Note:** This is a simplified version of the `RequestConfig` type from the\n * `fetch` API. It contains only the properties that are relevant for the\n * fal client. It also works around the fact that the `fetch` API `Request`\n * does not support mutability, its clone method has critical limitations\n * to our use case.\n */\nexport type RequestConfig = {\n url: string;\n method: string;\n headers?: Record<string, string | string[]>;\n};\n\nexport type RequestMiddleware = (\n request: RequestConfig,\n) => Promise<RequestConfig>;\n\n/**\n * Setup a execution chain of middleware functions.\n *\n * @param middlewares one or more middleware functions.\n * @returns a middleware function that executes the given middlewares in order.\n */\nexport function withMiddleware(\n ...middlewares: RequestMiddleware[]\n): RequestMiddleware {\n const isDefined = (middleware: RequestMiddleware): boolean =>\n typeof middleware === \"function\";\n\n return async (config: RequestConfig) => {\n let currentConfig = { ...config };\n for (const middleware of middlewares.filter(isDefined)) {\n currentConfig = await middleware(currentConfig);\n }\n return currentConfig;\n };\n}\n\nexport type RequestProxyConfig = {\n targetUrl: string;\n};\n\nexport const TARGET_URL_HEADER = \"x-fal-target-url\";\n\nexport function withProxy(config: RequestProxyConfig): RequestMiddleware {\n const passthrough = (requestConfig: RequestConfig) =>\n Promise.resolve(requestConfig);\n // when running on the server, we don't need to proxy the request\n if (typeof window === \"undefined\") {\n return passthrough;\n }\n // if x-fal-target-url is already set, we skip it\n return (requestConfig) =>\n requestConfig.headers && TARGET_URL_HEADER in requestConfig\n ? passthrough(requestConfig)\n : Promise.resolve({\n ...requestConfig,\n url: config.targetUrl,\n headers: {\n ...(requestConfig.headers || {}),\n [TARGET_URL_HEADER]: requestConfig.url,\n },\n });\n}\n", "import { RequiredConfig } from \"./config\";\nimport { Result, ValidationErrorInfo } from \"./types/common\";\n\nexport type ResponseHandler<Output> = (response: Response) => Promise<Output>;\n\nconst REQUEST_ID_HEADER = \"x-fal-request-id\";\n\nexport type ResponseHandlerCreator<Output> = (\n config: RequiredConfig,\n) => ResponseHandler<Output>;\n\ntype ApiErrorArgs = {\n message: string;\n status: number;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n body?: any;\n};\n\nexport class ApiError<Body> extends Error {\n public readonly status: number;\n public readonly body: Body;\n constructor({ message, status, body }: ApiErrorArgs) {\n super(message);\n this.name = \"ApiError\";\n this.status = status;\n this.body = body;\n }\n}\n\ntype ValidationErrorBody = {\n detail: ValidationErrorInfo[];\n};\n\nexport class ValidationError extends ApiError<ValidationErrorBody> {\n constructor(args: ApiErrorArgs) {\n super(args);\n this.name = \"ValidationError\";\n }\n\n get fieldErrors(): ValidationErrorInfo[] {\n // NOTE: this is a hack to support both FastAPI/Pydantic errors\n // and some custom 422 errors that might not be in the Pydantic format.\n if (typeof this.body.detail === \"string\") {\n return [\n {\n loc: [\"body\"],\n msg: this.body.detail,\n type: \"value_error\",\n },\n ];\n }\n return this.body.detail || [];\n }\n\n getFieldErrors(field: string): ValidationErrorInfo[] {\n return this.fieldErrors.filter(\n (error) => error.loc[error.loc.length - 1] === field,\n );\n }\n}\n\nexport async function defaultResponseHandler<Output>(\n response: Response,\n): Promise<Output> {\n const { status, statusText } = response;\n const contentType = response.headers.get(\"Content-Type\") ?? \"\";\n if (!response.ok) {\n if (contentType.includes(\"application/json\")) {\n const body = await response.json();\n const ErrorType = status === 422 ? ValidationError : ApiError;\n throw new ErrorType({\n message: body.message || statusText,\n status,\n body,\n });\n }\n throw new ApiError({ message: `HTTP ${status}: ${statusText}`, status });\n }\n if (contentType.includes(\"application/json\")) {\n return response.json() as Promise<Output>;\n }\n if (contentType.includes(\"text/html\")) {\n return response.text() as Promise<Output>;\n }\n if (contentType.includes(\"application/octet-stream\")) {\n return response.arrayBuffer() as Promise<Output>;\n }\n // TODO convert to either number or bool automatically\n return response.text() as Promise<Output>;\n}\n\nexport async function resultResponseHandler<Output>(\n response: Response,\n): Promise<Result<Output>> {\n const data = await defaultResponseHandler<Output>(response);\n return {\n data,\n requestId: response.headers.get(REQUEST_ID_HEADER) || \"\",\n } satisfies Result<Output>;\n}\n", "{\n \"name\": \"@fal-ai/client\",\n \"description\": \"The fal.ai client for JavaScript and TypeScript\",\n \"version\": \"1.3.0\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/fal-ai/fal-js.git\",\n \"directory\": \"libs/client\"\n },\n \"keywords\": [\n \"fal\",\n \"client\",\n \"ai\",\n \"ml\",\n \"typescript\"\n ],\n \"exports\": {\n \".\": \"./src/index.js\",\n \"./endpoints\": \"./src/types/endpoints.js\"\n },\n \"typesVersions\": {\n \"*\": {\n \"endpoints\": [\n \"src/types/endpoints.d.ts\"\n ]\n }\n },\n \"main\": \"./src/index.js\",\n \"types\": \"./src/index.d.ts\",\n \"dependencies\": {\n \"@msgpack/msgpack\": \"^3.0.0-beta2\",\n \"eventsource-parser\": \"^1.1.2\",\n \"robot3\": \"^0.4.1\"\n },\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"type\": \"commonjs\"\n}\n", "/* eslint-disable @typescript-eslint/no-var-requires */\n\nexport function isBrowser(): boolean {\n return (\n typeof window !== \"undefined\" && typeof window.document !== \"undefined\"\n );\n}\n\nlet memoizedUserAgent: string | null = null;\n\nexport function getUserAgent(): string {\n if (memoizedUserAgent !== null) {\n return memoizedUserAgent;\n }\n const packageInfo = require(\"../package.json\");\n memoizedUserAgent = `${packageInfo.name}/${packageInfo.version}`;\n return memoizedUserAgent;\n}\n", "import {\n withMiddleware,\n withProxy,\n type RequestMiddleware,\n} from \"./middleware\";\nimport type { ResponseHandler } from \"./response\";\nimport { defaultResponseHandler } from \"./response\";\nimport { isBrowser } from \"./runtime\";\n\nexport type CredentialsResolver = () => string | undefined;\n\ntype FetchType = typeof fetch;\n\nexport function resolveDefaultFetch(): FetchType {\n if (typeof fetch === \"undefined\") {\n throw new Error(\n \"Your environment does not support fetch. Please provide your own fetch implementation.\",\n );\n }\n return fetch;\n}\n\nexport type Config = {\n /**\n * The credentials to use for the fal client. When using the\n * client in the browser, it's recommended to use a proxy server to avoid\n * exposing the credentials in the client's environment.\n *\n * By default it tries to use the `FAL_KEY` environment variable, when\n * `process.env` is defined.\n *\n * @see https://fal.ai/docs/model-endpoints/server-side\n * @see #suppressLocalCredentialsWarning\n */\n credentials?: undefined | string | CredentialsResolver;\n /**\n * Suppresses the warning when the fal credentials are exposed in the\n * browser's environment. Make sure you understand the security implications\n * before enabling this option.\n */\n suppressLocalCredentialsWarning?: boolean;\n /**\n * The URL of the proxy server to use for the client requests. The proxy\n * server should forward the requests to the fal api.\n */\n proxyUrl?: string;\n /**\n * The request middleware to use for the client requests. By default it\n * doesn't apply any middleware.\n */\n requestMiddleware?: RequestMiddleware;\n /**\n * The response handler to use for the client requests. By default it uses\n * a built-in response handler that returns the JSON response.\n */\n responseHandler?: ResponseHandler<any>;\n /**\n * The fetch implementation to use for the client requests. By default it uses\n * the global `fetch` function.\n */\n fetch?: FetchType;\n};\n\nexport type RequiredConfig = Required<Config>;\n\n/**\n * Checks if the required FAL environment variables are set.\n *\n * @returns `true` if the required environment variables are set,\n * `false` otherwise.\n */\nfunction hasEnvVariables(): boolean {\n return (\n typeof process !== \"undefined\" &&\n process.env &&\n (typeof process.env.FAL_KEY !== \"undefined\" ||\n (typeof process.env.FAL_KEY_ID !== \"undefined\" &&\n typeof process.env.FAL_KEY_SECRET !== \"undefined\"))\n );\n}\n\nexport const credentialsFromEnv: CredentialsResolver = () => {\n if (!hasEnvVariables()) {\n return undefined;\n }\n\n if (typeof process.env.FAL_KEY !== \"undefined\") {\n return process.env.FAL_KEY;\n }\n\n return process.env.FAL_KEY_ID\n ? `${process.env.FAL_KEY_ID}:${process.env.FAL_KEY_SECRET}`\n : undefined;\n};\n\nconst DEFAULT_CONFIG: Partial<Config> = {\n credentials: credentialsFromEnv,\n suppressLocalCredentialsWarning: false,\n requestMiddleware: (request) => Promise.resolve(request),\n responseHandler: defaultResponseHandler,\n};\n\n/**\n * Configures the fal client.\n *\n * @param config the new configuration.\n */\nexport function createConfig(config: Config): RequiredConfig {\n let configuration = {\n ...DEFAULT_CONFIG,\n ...config,\n fetch: config.fetch ?? resolveDefaultFetch(),\n } as RequiredConfig;\n if (config.proxyUrl) {\n configuration = {\n ...configuration,\n requestMiddleware: withMiddleware(\n configuration.requestMiddleware,\n withProxy({ targetUrl: config.proxyUrl }),\n ),\n };\n }\n const { credentials: resolveCredentials, suppressLocalCredentialsWarning } =\n configuration;\n const credentials =\n typeof resolveCredentials === \"function\"\n ? resolveCredentials()\n : resolveCredentials;\n if (isBrowser() && credentials && !suppressLocalCredentialsWarning) {\n console.warn(\n \"The fal credentials are exposed in the browser's environment. \" +\n \"That's not recommended for production use cases.\",\n );\n }\n return configuration;\n}\n\n/**\n * @returns the URL of the fal REST api endpoint.\n */\nexport function getRestApiUrl(): string {\n return \"https://rest.alpha.fal.ai\";\n}\n", "export function ensureEndpointIdFormat(id: string): string {\n const parts = id.split(\"/\");\n if (parts.length > 1) {\n return id;\n }\n const [, appOwner, appId] = /^([0-9]+)-([a-zA-Z0-9-]+)$/.exec(id) || [];\n if (appOwner && appId) {\n return `${appOwner}/${appId}`;\n }\n throw new Error(\n `Invalid app id: ${id}. Must be in the format <appOwner>/<appId>`,\n );\n}\n\nconst ENDPOINT_NAMESPACES = [\"workflows\", \"comfy\"] as const;\n\ntype EndpointNamespace = (typeof ENDPOINT_NAMESPACES)[number];\n\nexport type EndpointId = {\n readonly owner: string;\n readonly alias: string;\n readonly path?: string;\n readonly namespace?: EndpointNamespace;\n};\n\nexport function parseEndpointId(id: string): EndpointId {\n const normalizedId = ensureEndpointIdFormat(id);\n const parts = normalizedId.split(\"/\");\n if (ENDPOINT_NAMESPACES.includes(parts[0] as any)) {\n return {\n owner: parts[1],\n alias: parts[2],\n path: parts.slice(3).join(\"/\") || undefined,\n namespace: parts[0] as EndpointNamespace,\n };\n }\n return {\n owner: parts[0],\n alias: parts[1],\n path: parts.slice(2).join(\"/\") || undefined,\n };\n}\n\nexport function isValidUrl(url: string) {\n try {\n const { host } = new URL(url);\n return /(fal\\.(ai|run))$/.test(host);\n } catch (_) {\n return false;\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function throttle<T extends (...args: any[]) => any>(\n func: T,\n limit: number,\n leading = false,\n): (...funcArgs: Parameters<T>) => ReturnType<T> | void {\n let lastFunc: NodeJS.Timeout | null;\n let lastRan: number;\n\n return (...args: Parameters<T>): ReturnType<T> | void => {\n if (!lastRan && leading) {\n func(...args);\n lastRan = Date.now();\n } else {\n if (lastFunc) {\n clearTimeout(lastFunc);\n }\n\n lastFunc = setTimeout(\n () => {\n if (Date.now() - lastRan >= limit) {\n func(...args);\n lastRan = Date.now();\n }\n },\n limit - (Date.now() - lastRan),\n );\n }\n };\n}\n\nlet isRunningInReact: boolean | undefined;\n\n/**\n * Not really the most optimal way to detect if we're running in React,\n * but the idea here is that we can support multiple rendering engines\n * (starting with React), with all their peculiarities, without having\n * to add a dependency or creating custom integrations (e.g. custom hooks).\n *\n * Yes, a bit of magic to make things works out-of-the-box.\n * @returns `true` if running in React, `false` otherwise.\n */\nexport function isReact() {\n if (isRunningInReact === undefined) {\n const stack = new Error().stack;\n isRunningInReact =\n !!stack &&\n (stack.includes(\"node_modules/react-dom/\") ||\n stack.includes(\"node_modules/next/\"));\n }\n return isRunningInReact;\n}\n\n/**\n * Check if a value is a plain object.\n * @param value - The value to check.\n * @returns `true` if the value is a plain object, `false` otherwise.\n */\nexport function isPlainObject(value: any): boolean {\n return !!value && Object.getPrototypeOf(value) === Object.prototype;\n}\n", "import { RequiredConfig } from \"./config\";\nimport { ResponseHandler } from \"./response\";\nimport { getUserAgent, isBrowser } from \"./runtime\";\nimport { RunOptions, UrlOptions } from \"./types/common\";\nimport { ensureEndpointIdFormat, isValidUrl } from \"./utils\";\n\nconst isCloudflareWorkers =\n typeof navigator !== \"undefined\" &&\n navigator?.userAgent === \"Cloudflare-Workers\";\n\ntype RequestOptions = {\n responseHandler?: ResponseHandler<any>;\n};\n\ntype RequestParams<Input = any> = {\n method?: string;\n targetUrl: string;\n input?: Input;\n config: RequiredConfig;\n options?: RequestOptions & RequestInit;\n headers?: Record<string, string>;\n};\n\nexport async function dispatchRequest<Input, Output>(\n params: RequestParams<Input>,\n): Promise<Output> {\n const { targetUrl, input, config, options = {} } = params;\n const {\n credentials: credentialsValue,\n requestMiddleware,\n responseHandler,\n fetch,\n } = config;\n const userAgent = isBrowser() ? {} : { \"User-Agent\": getUserAgent() };\n const credentials =\n typeof credentialsValue === \"function\"\n ? credentialsValue()\n : credentialsValue;\n\n const { method, url, headers } = await requestMiddleware({\n method: (params.method ?? options.method ?? \"post\").toUpperCase(),\n url: targetUrl,\n headers: params.headers,\n });\n const authHeader = credentials ? { Authorization: `Key ${credentials}` } : {};\n const requestHeaders = {\n ...authHeader,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n ...userAgent,\n ...(headers ?? {}),\n } as HeadersInit;\n\n const { responseHandler: customResponseHandler, ...requestInit } = options;\n const response = await fetch(url, {\n ...requestInit,\n method,\n headers: {\n ...requestHeaders,\n ...(requestInit.headers ?? {}),\n },\n ...(!isCloudflareWorkers && { mode: \"cors\" }),\n signal: options.signal,\n body:\n method.toLowerCase() !== \"get\" && input\n ? JSON.stringify(input)\n : undefined,\n });\n const handleResponse = customResponseHandler ?? responseHandler;\n return await handleResponse(response);\n}\n\n/**\n * Builds the final url to run the function based on its `id` or alias and\n * a the options from `RunOptions<Input>`.\n *\n * @private\n * @param id the function id or alias\n * @param options the run options\n * @returns the final url to run the function\n */\nexport function buildUrl<Input>(\n id: string,\n options: RunOptions<Input> & UrlOptions = {},\n): string {\n const method = (options.method ?? \"post\").toLowerCase();\n const path = (options.path ?? \"\").replace(/^\\//, \"\").replace(/\\/{2,}/, \"/\");\n const input = options.input;\n const params = {\n ...(options.query || {}),\n ...(method === \"get\" ? input : {}),\n };\n\n const queryParams =\n Object.keys(params).length > 0\n ? `?${new URLSearchParams(params).toString()}`\n : \"\";\n\n // if a fal url is passed, just use it\n if (isValidUrl(id)) {\n const url = id.endsWith(\"/\") ? id : `${id}/`;\n return `${url}${path}${queryParams}`;\n }\n\n const appId = ensureEndpointIdFormat(id);\n const subdomain = options.subdomain ? `${options.subdomain}.` : \"\";\n const url = `https://${subdomain}fal.run/${appId}/${path}`;\n return `${url.replace(/\\/$/, \"\")}${queryParams}`;\n}\n", "/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n *\n * Based on code from the {@link https://github.com/EventSource/eventsource | EventSource module},\n * which is licensed under the MIT license. And copyrighted the EventSource GitHub organisation.\n */\nimport type {EventSourceParseCallback, EventSourceParser} from './types.js'\n\n/**\n * Creates a new EventSource parser.\n *\n * @param onParse - Callback to invoke when a new event is parsed, or a new reconnection interval\n * has been sent from the server\n *\n * @returns A new EventSource parser, with `parse` and `reset` methods.\n * @public\n */\nexport function createParser(onParse: EventSourceParseCallback): EventSourceParser {\n // Processing state\n let isFirstChunk: boolean\n let buffer: string\n let startingPosition: number\n let startingFieldLength: number\n\n // Event state\n let eventId: string | undefined\n let eventName: string | undefined\n let data: string\n\n reset()\n return {feed, reset}\n\n function reset(): void {\n isFirstChunk = true\n buffer = ''\n startingPosition = 0\n startingFieldLength = -1\n\n eventId = undefined\n eventName = undefined\n data = ''\n }\n\n function feed(chunk: string): void {\n buffer = buffer ? buffer + chunk : chunk\n\n // Strip any UTF8 byte order mark (BOM) at the start of the stream.\n // Note that we do not strip any non - UTF8 BOM, as eventsource streams are\n // always decoded as UTF8 as per the specification.\n if (isFirstChunk && hasBom(buffer)) {\n buffer = buffer.slice(BOM.length)\n }\n\n isFirstChunk = false\n\n // Set up chunk-specific processing state\n const length = buffer.length\n let position = 0\n let discardTrailingNewline = false\n\n // Read the current buffer byte by byte\n while (position < length) {\n // EventSource allows for carriage return + line feed, which means we\n // need to ignore a linefeed character if the previous character was a\n // carriage return\n // @todo refactor to reduce nesting, consider checking previous byte?\n // @todo but consider multiple chunks etc\n if (discardTrailingNewline) {\n if (buffer[position] === '\\n') {\n ++position\n }\n discardTrailingNewline = false\n }\n\n let lineLength = -1\n let fieldLength = startingFieldLength\n let character: string\n\n for (let index = startingPosition; lineLength < 0 && index < length; ++index) {\n character = buffer[index]\n if (character === ':' && fieldLength < 0) {\n fieldLength = index - position\n } else if (character === '\\r') {\n discardTrailingNewline = true\n lineLength = index - position\n } else if (character === '\\n') {\n lineLength = index - position\n }\n }\n\n if (lineLength < 0) {\n startingPosition = length - position\n startingFieldLength = fieldLength\n break\n } else {\n startingPosition = 0\n startingFieldLength = -1\n }\n\n parseEventStreamLine(buffer, position, fieldLength, lineLength)\n\n position += lineLength + 1\n }\n\n if (position === length) {\n // If we consumed the entire buffer to read the event, reset the buffer\n buffer = ''\n } else if (position > 0) {\n // If there are bytes left to process, set the buffer to the unprocessed\n // portion of the buffer only\n buffer = buffer.slice(position)\n }\n }\n\n function parseEventStreamLine(\n lineBuffer: string,\n index: number,\n fieldLength: number,\n lineLength: number,\n ) {\n if (lineLength === 0) {\n // We reached the last line of this event\n if (data.length > 0) {\n onParse({\n type: 'event',\n id: eventId,\n event: eventName || undefined,\n data: data.slice(0, -1), // remove trailing newline\n })\n\n data = ''\n eventId = undefined\n }\n eventName = undefined\n return\n }\n\n const noValue = fieldLength < 0\n const field = lineBuffer.slice(index, index + (noValue ? lineLength : fieldLength))\n let step = 0\n\n if (noValue) {\n step = lineLength\n } else if (lineBuffer[index + fieldLength + 1] === ' ') {\n step = fieldLength + 2\n } else {\n step = fieldLength + 1\n }\n\n const position = index + step\n const valueLength = lineLength - step\n const value = lineBuffer.slice(position, position + valueLength).toString()\n\n if (field === 'data') {\n data += value ? `${value}\\n` : '\\n'\n } else if (field === 'event') {\n eventName = value\n } else if (field === 'id' && !value.includes('\\u0000')) {\n eventId = value\n } else if (field === 'retry') {\n const retry = parseInt(value, 10)\n if (!Number.isNaN(retry)) {\n onParse({type: 'reconnect-interval', value: retry})\n }\n }\n }\n}\n\nconst BOM = [239, 187, 191]\n\nfunction hasBom(buffer: string) {\n return BOM.every((charCode: number, index: number) => buffer.charCodeAt(index) === charCode)\n}\n", "import { getRestApiUrl, RequiredConfig } from \"./config\";\nimport { dispatchRequest } from \"./request\";\nimport { parseEndpointId } from \"./utils\";\n\nexport const TOKEN_EXPIRATION_SECONDS = 120;\n\n/**\n * Get a token to connect to the realtime endpoint.\n */\nexport async function getTemporaryAuthToken(\n app: string,\n config: RequiredConfig,\n): Promise<string> {\n const appId = parseEndpointId(app);\n const token: string | object = await dispatchRequest<any, string>({\n method: \"POST\",\n targetUrl: `${getRestApiUrl()}/tokens/`,\n config,\n input: {\n allowed_apps: [appId.alias],\n token_expiration: TOKEN_EXPIRATION_SECONDS,\n },\n });\n // keep this in case the response was wrapped (old versions of the proxy do that)\n // should be safe to remove in the future\n if (typeof token !== \"string\" && token[\"detail\"]) {\n return token[\"detail\"];\n }\n return token;\n}\n", "import { createParser } from \"eventsource-parser\";\nimport { getTemporaryAuthToken } from \"./auth\";\nimport { RequiredConfig } from \"./config\";\nimport { buildUrl, dispatchRequest } from \"./request\";\nimport { ApiError, defaultResponseHandler } from \"./response\";\nimport { type StorageClient } from \"./storage\";\nimport { EndpointType, InputType, OutputType } from \"./types/client\";\n\nexport type StreamingConnectionMode = \"client\" | \"server\";\n\nconst CONTENT_TYPE_EVENT_STREAM = \"text/event-stream\";\n\n/**\n * The stream API options. It requires the API input and also\n * offers configuration options.\n */\nexport type StreamOptions<Input> = {\n /**\n * The endpoint URL. If not provided, it will be generated from the\n * `endpointId` and the `queryParams`.\n */\n readonly url?: string;\n\n /**\n * The API input payload.\n */\n readonly input?: Input;\n\n /**\n * The query parameters to be sent with the request.\n */\n readonly queryParams?: Record<string, string>;\n\n /**\n * The maximum time interval in milliseconds between stream chunks. Defaults to 15s.\n */\n readonly timeout?: number;\n\n /**\n * Whether it should auto-upload File-like types to fal's storage\n * or not.\n */\n readonly autoUpload?: boolean;\n\n /**\n * The HTTP method, defaults to `post`;\n */\n readonly method?: \"get\" | \"post\" | \"put\" | \"delete\" | string;\n\n /**\n * The content type the client accepts as response.\n * By default this is set to `text/event-stream`.\n */\n readonly accept?: string;\n\n /**\n * The streaming connection mode. This is used to determine\n * whether the streaming will be done from the browser itself (client)\n * or through your own server, either when running on NodeJS or when\n * using a proxy that supports streaming.\n *\n * It defaults to `server`. Set to `client` if your server proxy doesn't\n * support streaming.\n */\n readonly connectionMode?: StreamingConnectionMode;\n\n /**\n * The signal to abort the request.\n */\n readonly signal?: AbortSignal;\n};\n\nconst EVENT_STREAM_TIMEOUT = 15 * 1000;\n\ntype FalStreamEventType = \"data\" | \"error\" | \"done\";\n\ntype EventHandler<T = any> = (event: T) => void;\n\n/**\n * The class representing a streaming response. With t\n */\nexport class FalStream<Input, Output> {\n // properties\n config: RequiredConfig;\n endpointId: string;\n url: string;\n options: StreamOptions<Input>;\n\n // support for event listeners\n private listeners: Map<FalStreamEventType, EventHandler[]> = new Map();\n private buffer: Output[] = [];\n\n // local state\n private currentData: Output | undefined = undefined;\n private lastEventTimestamp = 0;\n private streamClosed = false;\n private donePromise: Promise<Output>;\n\n private abortController = new AbortController();\n\n constructor(\n endpointId: string,\n config: RequiredConfig,\n options: StreamOptions<Input>,\n ) {\n this.endpointId = endpointId;\n this.config = config;\n this.url =\n options.url ??\n buildUrl(endpointId, {\n path: \"/stream\",\n query: options.queryParams,\n });\n this.options = options;\n this.donePromise = new Promise<Output>((resolve, reject) => {\n if (this.streamClosed) {\n reject(\n new ApiError({\n message: \"Streaming connection is already closed.\",\n status: 400,\n body: undefined,\n }),\n );\n }\n this.signal.addEventListener(\"abort\", () => {\n resolve(this.currentData ?? ({} as Output));\n });\n this.on(\"done\", (data) => {\n this.streamClosed = true;\n resolve(data);\n });\n this.on(\"error\", (error) => {\n this.streamClosed = true;\n reject(error);\n });\n });\n // if a abort signal was passed, sync it with the internal one\n if (options.signal) {\n options.signal.addEventListener(\"abort\", () => {\n this.abortController.abort();\n });\n }\n\n // start the streaming request\n this.start().catch(this.handleError);\n }\n\n private start = async () => {\n const { endpointId, options } = this;\n const { input, method = \"post\", connectionMode = \"server\" } = options;\n try {\n if (connectionMode === \"client\") {\n // if we are in the browser, we need to get a temporary token\n // to authenticate the request\n const token = await getTemporaryAuthToken(endpointId, this.config);\n const { fetch } = this.config;\n const parsedUrl = new URL(this.url);\n parsedUrl.searchParams.set(\"fal_jwt_token\", token);\n const response = await fetch(parsedUrl.toString(), {\n method: method.toUpperCase(),\n headers: {\n accept: options.accept ?? CONTENT_TYPE_EVENT_STREAM,\n \"content-type\": \"application/json\",\n },\n body: input && method !== \"get\" ? JSON.stringify(input) : undefined,\n signal: this.abortController.signal,\n });\n return await this.handleResponse(response);\n }\n return await dispatchRequest({\n method: method.toUpperCase(),\n targetUrl: this.url,\n input,\n config: this.config,\n options: {\n headers: {\n accept: options.accept ?? CONTENT_TYPE_EVENT_STREAM,\n },\n responseHandler: this.handleResponse,\n signal: this.abortController.signal,\n },\n });\n } catch (error) {\n this.handleError(error);\n }\n };\n\n private handleResponse = async (response: Response) => {\n if (!response.ok) {\n try {\n // we know the response failed, call the response handler\n // so the exception gets converted to ApiError correctly\n await defaultResponseHandler(response);\n } catch (error) {\n this.emit(\"error\", error);\n }\n return;\n }\n\n const body = response.body;\n if (!body) {\n this.emit(\n \"error\",\n new ApiError({\n message: \"Response body is empty.\",\n status: 400,\n body: undefined,\n }),\n );\n return;\n }\n\n const isEventStream = (\n response.headers.get(\"content-type\") ?? \"\"\n ).startsWith(CONTENT_TYPE_EVENT_STREAM);\n // any response that is not a text/event-stream will be handled as a binary stream\n if (!isEventStream) {\n const reader = body.getReader();\n const emitRawChunk = () => {\n reader.read().then(({ done, value }) => {\n if (done) {\n this.emit(\"done\", this.currentData);\n return;\n }\n this.currentData = value as Output;\n this.emit(\"data\", value);\n emitRawChunk();\n });\n };\n emitRawChunk();\n return;\n }\n\n const decoder = new TextDecoder(\"utf-8\");\n const reader = response.body.getReader();\n\n const parser = createParser((event) => {\n if (event.type === \"event\") {\n const data = event.data;\n\n try {\n const parsedData = JSON.parse(data);\n this.buffer.push(parsedData);\n this.currentData = parsedData;\n this.emit(\"data\", parsedData);\n\n // also emit 'message'for backwards compatibility\n this.emit(\"message\" as any, parsedData);\n } catch (e) {\n this.emit(\"error\", e);\n }\n }\n });\n\n const timeout = this.options.timeout ?? EVENT_STREAM_TIMEOUT;\n\n const readPartialResponse = async () => {\n const { value, done } = await reader.read();\n this.lastEventTimestamp = Date.now();\n\n parser.feed(decoder.decode(value));\n\n if (Date.now() - this.lastEventTimestamp > timeout) {\n this.emit(\n \"error\",\n new ApiError({\n message: `Event stream timed out after ${(timeout / 1000).toFixed(0)} seconds with no messages.`,\n status: 408,\n }),\n );\n }\n\n if (!done) {\n readPartialResponse().catch(this.handleError);\n } else {\n this.emit(\"done\", this.currentData);\n }\n };\n\n readPartialResponse().catch(this.handleError);\n return;\n };\n\n private handleError = (error: any) => {\n // In case AbortError is thrown but the signal is marked as aborted\n // it means the user called abort() and we should not emit an error\n // as it's expected behavior\n // See note on: https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort\n if (error.name === \"AbortError\" || this.signal.aborted) {\n return;\n }\n const apiError =\n error instanceof ApiError\n ? error\n : new ApiError({\n message: error.message ?? \"An unknown error occurred\",\n status: 500,\n });\n this.emit(\"error\", apiError);\n return;\n };\n\n public on = (type: FalStreamEventType, listener: EventHandler) => {\n if (!this.listeners.has(type)) {\n this.listeners.set(type, []);\n }\n this.listeners.get(type)?.push(listener);\n };\n\n private emit = (type: FalStreamEventType, event: any) => {\n const listeners = this.listeners.get(type) || [];\n for (const listener of listeners) {\n listener(event);\n }\n };\n\n async *[Symbol.asyncIterator]() {\n let running = true;\n const stopAsyncIterator = () => (running = false);\n this.on(\"error\", stopAsyncIterator);\n this.on(\"done\", stopAsyncIterator);\n while (running || this.buffer.length > 0) {\n const data = this.buffer.shift();\n if (data) {\n yield data;\n }\n\n // the short timeout ensures the while loop doesn't block other\n // frames getting executed concurrently\n await new Promise((resolve) => setTimeout(resolve, 16));\n }\n }\n\n /**\n * Gets a reference to the `Promise` that indicates whether the streaming\n * is done or not. Developers should always call this in their apps to ensure\n * the request is over.\n *\n * An alternative to this, is to use `on('done')` in case your application\n * architecture works best with event listeners.\n *\n * @returns the promise that resolves when the request is done.\n */\n public done = async () => this.donePromise;\n\n /**\n * Aborts the streaming request.\n *\n * **Note:** This method is noop in case the request is already done.\n *\n * @param reason optional cause for aborting the request.\n */\n public abort = (reason?: string | Error) => {\n if (!this.streamClosed) {\n this.abortController.abort(reason);\n }\n };\n\n /**\n * Gets the `AbortSignal` instance that can be used to listen for abort events.\n *\n * **Note:** this signal is internal to the `FalStream` instance. If you pass your\n * own abort signal, the `FalStream` will listen to it and abort it appropriately.\n *\n * @returns the `AbortSignal` instance.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal\n */\n public get signal() {\n return this.abortController.signal;\n }\n}\n\n/**\n * The streaming client interface.\n */\nexport interface StreamingClient {\n /**\n * Calls a fal app that supports streaming and provides a streaming-capable\n * object as a result, that can be used to get partial results through either\n * `AsyncIterator` or through an event listener.\n *\n * @param endpointId the endpoint id, e.g. `fal-ai/llavav15-13b`.\n * @param options the request options, including the input payload.\n * @returns the `FalStream` instance.\n */\n stream<Id extends EndpointType>(\n endpointId: Id,\n options: StreamOptions<InputType<Id>>,\n ): Promise<FalStream<InputType<Id>, OutputType<Id>>>;\n}\n\ntype StreamingClientDependencies = {\n config: RequiredConfig;\n storage: StorageClient;\n};\n\nexport function createStreamingClient({\n config,\n storage,\n}: StreamingClientDependencies): StreamingClient {\n return {\n async stream<Id extends EndpointType>(\n endpointId: Id,\n options: StreamOptions<InputType<Id>>,\n ) {\n const input = options.input\n ? await storage.transformInput(options.input)\n : undefined;\n return new FalStream<InputType<Id>, OutputType<Id>>(endpointId, config, {\n ...options,\n input: input as InputType<Id>,\n });\n },\n };\n}\n", "import { RequiredConfig } from \"./config\";\nimport { buildUrl, dispatchRequest } from \"./request\";\nimport { resultResponseHandler } from \"./response\";\nimport { StorageClient } from \"./storage\";\nimport { FalStream, StreamingConnectionMode } from \"./streaming\";\nimport { EndpointType, InputType, OutputType } from \"./types/client\";\nimport {\n CompletedQueueStatus,\n InQueueQueueStatus,\n QueueStatus,\n RequestLog,\n Result,\n RunOptions,\n} from \"./types/common\";\nimport { parseEndpointId } from \"./utils\";\n\nexport type QueuePriority = \"low\" | \"normal\";\nexport type QueueStatusSubscriptionOptions = QueueStatusOptions &\n Omit<QueueSubscribeOptions, \"onEnqueue\" | \"webhookUrl\">;\n\ntype TimeoutId = ReturnType<typeof setTimeout> | undefined;\n\nconst DEFAULT_POLL_INTERVAL = 500;\n\n/**\n * Options for subscribing to the request queue.\n */\nexport type QueueSubscribeOptions = {\n /**\n * The mode to use for subscribing to updates. It defaults to `polling`.\n * You can also use client-side streaming by setting it to `streaming`.\n *\n * **Note:** Streaming is currently experimental and once stable, it will\n * be the default mode.\n *\n * @see pollInterval\n */\n mode?: \"polling\" | \"streaming\";\n\n /**\n * Callback function that is called when a request is enqueued.\n * @param requestId - The unique identifier for the enqueued request.\n */\n onEnqueue?: (requestId: string) => void;\n\n /**\n * Callback function that is called when the status of the queue changes.\n * @param status - The current status of the queue.\n */\n onQueueUpdate?: (status: QueueStatus) => void;\n\n /**\n * If `true`, the response will include the logs for the request.\n * Defaults to `false`.\n */\n logs?: boolean;\n\n /**\n * The timeout (in milliseconds) for the request. If the request is not\n * completed within this time, the subscription will be cancelled.\n *\n * Keep in mind that although the client resolves the function on a timeout,\n * and will try to cancel the request on the server, the server might not be\n * able to cancel the request if it's already running.\n *\n * Note: currently, the timeout is not enforced and the default is `undefined`.\n * This behavior might change in the future.\n */\n timeout?: number;\n\n /**\n * The URL to send a webhook notification to when the request is completed.\n * @see WebHookResponse\n */\n webhookUrl?: string;\n\n /**\n * The priority of the request. It defaults to `normal`.\n * @see QueuePriority\n */\n priority?: QueuePriority;\n} & (\n | {\n mode?: \"polling\";\n /**\n * The interval (in milliseconds) at which to poll for updates.\n * If not provided, a default value of `500` will be used.\n *\n * This value is ignored if `mode` is set to `streaming`.\n */\n pollInterval?: number;\n }\n | {\n mode: \"streaming\";\n\n /**\n * The connection mode to use for streaming updates. It defaults to `server`.\n * Set to `client` if your server proxy doesn't support streaming.\n */\n connectionMode?: StreamingConnectionMode;\n }\n);\n\n/**\n * Options for submitting a request to the queue.\n */\nexport type SubmitOptions<Input> = RunOptions<Input> & {\n /**\n * The URL to send a webhook notification to when the request is completed.\n * @see WebHookResponse\n */\n webhookUrl?: string;\n\n /**\n * The priority of the request. It defaults to `normal`.\n * @see QueuePriority\n */\n priority?: QueuePriority;\n};\n\ntype BaseQueueOptions = {\n /**\n * The unique identifier for the enqueued request.\n */\n requestId: string;\n\n /**\n * The signal to abort the request.\n */\n abortSignal?: AbortSignal;\n};\n\nexport type QueueStatusOptions = BaseQueueOptions & {\n /**\n * If `true`, the response will include the logs for the request.\n * Defaults to `false`.\n */\n logs?: boolean;\n};\n\nexport type QueueStatusStreamOptions = QueueStatusOptions & {\n /**\n * The connection mode to use for streaming updates. It defaults to `server`.\n * Set to `client` if your server proxy doesn't support streaming.\n */\n connectionMode?: StreamingConnectionMode;\n};\n\n/**\n * Represents a request queue with methods for submitting requests,\n * checking their status, retrieving results, and subscribing to updates.\n */\nexport interface QueueClient {\n /**\n * Submits a request to the queue.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run.\n * @returns A promise that resolves to the result of enqueuing the request.\n */\n submit<Id extends EndpointType>(\n endpointId: Id,\n options: SubmitOptions<InputType<Id>>,\n ): Promise<InQueueQueueStatus>;\n\n /**\n * Retrieves the status of a specific request in the queue.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run.\n * @returns A promise that resolves to the status of the request.\n */\n status(endpointId: string, options: QueueStatusOptions): Promise<QueueStatus>;\n\n /**\n * Subscribes to updates for a specific request in the queue using HTTP streaming events.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run and how updates are received.\n * @returns The streaming object that can be used to listen for updates.\n */\n streamStatus(\n endpointId: string,\n options: QueueStatusStreamOptions,\n ): Promise<FalStream<unknown, QueueStatus>>;\n\n /**\n * Subscribes to updates for a specific request in the queue using polling or streaming.\n * See `options.mode` for more details.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run and how updates are received.\n * @returns A promise that resolves to the final status of the request.\n */\n subscribeToStatus(\n endpointId: string,\n options: QueueStatusSubscriptionOptions,\n ): Promise<CompletedQueueStatus>;\n\n /**\n * Retrieves the result of a specific request from the queue.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run.\n * @returns A promise that resolves to the result of the request.\n */\n result<Id extends EndpointType>(\n endpointId: Id,\n options: BaseQueueOptions,\n ): Promise<Result<OutputType<Id>>>;\n\n /**\n * Cancels a request in the queue.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request\n * is run and how updates are received.\n * @returns A promise that resolves once the request is cancelled.\n * @throws {Error} If the request cannot be cancelled.\n */\n cancel(endpointId: string, options: BaseQueueOptions): Promise<void>;\n}\n\ntype QueueClientDependencies = {\n config: RequiredConfig;\n storage: StorageClient;\n};\n\nexport const createQueueClient = ({\n config,\n storage,\n}: QueueClientDependencies): QueueClient => {\n const ref: QueueClient = {\n async submit<Input>(\n endpointId: string,\n options: SubmitOptions<Input>,\n ): Promise<InQueueQueueStatus> {\n const { webhookUrl, priority, ...runOptions } = options;\n const input = options.input\n ? await storage.transformInput(options.input)\n : undefined;\n return dispatchRequest<Input, InQueueQueueStatus>({\n method: options.method,\n targetUrl: buildUrl(endpointId, {\n ...runOptions,\n subdomain: \"queue\",\n query: webhookUrl ? { fal_webhook: webhookUrl } : undefined,\n }),\n headers: {\n \"x-fal-queue-priority\": priority ?? \"normal\",\n },\n input: input as Input,\n config,\n options: {\n signal: options.abortSignal,\n },\n });\n },\n async status(\n endpointId: string,\n { requestId, logs = false, abortSignal }: QueueStatusOptions,\n ): Promise<QueueStatus> {\n const appId = parseEndpointId(endpointId);\n const prefix = appId.namespace ? `${appId.namespace}/` : \"\";\n return dispatchRequest<unknown, QueueStatus>({\n method: \"get\",\n targetUrl: buildUrl(`${prefix}${appId.owner}/${appId.alias}`, {\n subdomain: \"queue\",\n query: { logs: logs ? \"1\" : \"0\" },\n path: `/requests/${requestId}/status`,\n }),\n config,\n options: {\n signal: abortSignal,\n },\n });\n },\n\n async streamStatus(\n endpointId: string,\n { requestId, logs = false, connectionMode }: QueueStatusStreamOptions,\n ): Promise<FalStream<unknown, QueueStatus>> {\n const appId = parseEndpointId(endpointId);\n const prefix = appId.namespace ? `${appId.namespace}/` : \"\";\n\n const queryParams = {\n logs: logs ? \"1\" : \"0\",\n };\n\n const url = buildUrl(`${prefix}${appId.owner}/${appId.alias}`, {\n subdomain: \"queue\",\n path: `/requests/${requestId}/status/stream`,\n query: queryParams,\n });\n\n return new FalStream<unknown, QueueStatus>(endpointId, config, {\n url,\n method: \"get\",\n connectionMode,\n queryParams,\n });\n },\n\n async subscribeToStatus(\n endpointId,\n options,\n ): Promise<CompletedQueueStatus> {\n const requestId = options.requestId;\n const timeout = options.timeout;\n let timeoutId: TimeoutId = undefined;\n\n const handleCancelError = () => {\n // Ignore errors as the client will follow through with the timeout\n // regardless of the server response. In case cancelation fails, we\n // still want to reject the promise and consider the client call canceled.\n };\n if (options.mode === \"streaming\") {\n const status = await ref.streamStatus(endpointId, {\n requestId,\n logs: options.logs,\n connectionMode:\n \"connectionMode\" in options\n ? (options.connectionMode as StreamingConnectionMode)\n : undefined,\n });\n const logs: RequestLog[] = [];\n if (timeout) {\n timeoutId = setTimeout(() => {\n status.abort();\n ref.cancel(endpointId, { requestId }).catch(handleCancelError);\n // TODO this error cannot bubble up to the user since it's thrown in\n // a closure in the global scope due to setTimeout behavior.\n // User will get a platform error instead. We should find a way to\n // make this behavior aligned with polling.\n throw new Error(\n `Client timed out waiting for the request to complete after ${timeout}ms`,\n );\n }, timeout);\n }\n status.on(\"data\", (data: QueueStatus) => {\n if (options.onQueueUpdate) {\n // accumulate logs to match previous polling behavior\n if (\n \"logs\" in data &&\n Array.isArray(data.logs) &&\n data.logs.length > 0\n ) {\n logs.push(...data.logs);\n }\n options.onQueueUpdate(\"logs\" in data ? { ...data, logs } : data);\n }\n });\n const doneStatus = await status.done();\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n return doneStatus as CompletedQueueStatus;\n }\n // default to polling until status streaming is stable and faster\n return new Promise<CompletedQueueStatus>((resolve, reject) => {\n let pollingTimeoutId: TimeoutId;\n // type resolution isn't great in this case, so check for its presence\n // and and type so the typechecker behaves as expected\n const pollInterval =\n \"pollInterval\" in options && typeof options.pollInterval === \"number\"\n ? (options.pollInterval ?? DEFAULT_POLL_INTERVAL)\n : DEFAULT_POLL_INTERVAL;\n\n const clearScheduledTasks = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n if (pollingTimeoutId) {\n clearTimeout(pollingTimeoutId);\n }\n };\n if (timeout) {\n timeoutId = setTimeout(() => {\n clearScheduledTasks();\n ref.cancel(endpointId, { requestId }).catch(handleCancelError);\n reject(\n new Error(\n `Client timed out waiting for the request to complete after ${timeout}ms`,\n ),\n );\n }, timeout);\n }\n const poll = async () => {\n try {\n const requestStatus = await ref.status(endpointId, {\n requestId,\n logs: options.logs ?? false,\n abortSignal: options.abortSignal,\n });\n if (options.onQueueUpdate) {\n options.onQueueUpdate(requestStatus);\n }\n if (requestStatus.status === \"COMPLETED\") {\n clearScheduledTasks();\n resolve(requestStatus);\n return;\n }\n pollingTimeoutId = setTimeout(poll, pollInterval);\n } catch (error) {\n clearScheduledTasks();\n reject(error);\n }\n };\n poll().catch(reject);\n });\n },\n\n async result<Output>(\n endpointId: string,\n { requestId, abortSignal }: BaseQueueOptions,\n ): Promise<Result<Output>> {\n const appId = parseEndpointId(endpointId);\n const prefix = appId.namespace ? `${appId.namespace}/` : \"\";\n return dispatchRequest<unknown, Result<Output>>({\n method: \"get\",\n targetUrl: buildUrl(`${prefix}${appId.owner}/${appId.alias}`, {\n subdomain: \"queue\",\n path: `/requests/${requestId}`,\n }),\n config: {\n ...config,\n responseHandler: resultResponseHandler,\n },\n options: {\n signal: abortSignal,\n },\n });\n },\n\n async cancel(\n endpointId: string,\n { requestId, abortSignal }: BaseQueueOptions,\n ): Promise<void> {\n const appId = parseEndpointId(endpointId);\n const prefix = appId.namespace ? `${appId.namespace}/` : \"\";\n await dispatchRequest<unknown, void>({\n method: \"put\",\n targetUrl: buildUrl(`${prefix}${appId.owner}/${appId.alias}`, {\n subdomain: \"queue\",\n path: `/requests/${requestId}/cancel`,\n }),\n config,\n options: {\n signal: abortSignal,\n },\n });\n },\n };\n return ref;\n};\n", "export function utf8Count(str: string): number {\n const strLength = str.length;\n\n let byteLength = 0;\n let pos = 0;\n while (pos < strLength) {\n let value = str.charCodeAt(pos++);\n\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n byteLength++;\n continue;\n } else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n byteLength += 2;\n } else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n const extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n byteLength += 3;\n } else {\n // 4-byte\n byteLength += 4;\n }\n }\n }\n return byteLength;\n}\n\nexport function utf8EncodeJs(str: string, output: Uint8Array, outputOffset: number): void {\n const strLength = str.length;\n let offset = outputOffset;\n let pos = 0;\n while (pos < strLength) {\n let value = str.charCodeAt(pos++);\n\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n output[offset++] = value;\n continue;\n } else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n output[offset++] = ((value >> 6) & 0x1f) | 0xc0;\n } else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n const extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n output[offset++] = ((value >> 12) & 0x0f) | 0xe0;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n } else {\n // 4-byte\n output[offset++] = ((value >> 18) & 0x07) | 0xf0;\n output[offset++] = ((value >> 12) & 0x3f) | 0x80;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n }\n }\n\n output[offset++] = (value & 0x3f) | 0x80;\n }\n}\n\n// TextEncoder and TextDecoder are standardized in whatwg encoding:\n// https://encoding.spec.whatwg.org/\n// and available in all the modern browsers:\n// https://caniuse.com/textencoder\n// They are available in Node.js since v12 LTS as well:\n// https://nodejs.org/api/globals.html#textencoder\n\nconst sharedTextEncoder = new TextEncoder();\n\n// This threshold should be determined by benchmarking, which might vary in engines and input data.\n// Run `npx ts-node benchmark/encode-string.ts` for details.\nconst TEXT_ENCODER_THRESHOLD = 50;\n\nexport function utf8EncodeTE(str: string, output: Uint8Array, outputOffset: number): void {\n sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));\n}\n\nexport function utf8Encode(str: string, output: Uint8Array, outputOffset: number): void {\n if (str.length > TEXT_ENCODER_THRESHOLD) {\n utf8EncodeTE(str, output, outputOffset);\n } else {\n utf8EncodeJs(str, output, outputOffset);\n }\n}\n\nconst CHUNK_SIZE = 0x1_000;\n\nexport function utf8DecodeJs(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n let offset = inputOffset;\n const end = offset + byteLength;\n\n const units: Array<number> = [];\n let result = \"\";\n while (offset < end) {\n const byte1 = bytes[offset++]!;\n if ((byte1 & 0x80) === 0) {\n // 1 byte\n units.push(byte1);\n } else if ((byte1 & 0xe0) === 0xc0) {\n // 2 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n units.push(((byte1 & 0x1f) << 6) | byte2);\n } else if ((byte1 & 0xf0) === 0xe0) {\n // 3 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n const byte3 = bytes[offset++]! & 0x3f;\n units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);\n } else if ((byte1 & 0xf8) === 0xf0) {\n // 4 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n const byte3 = bytes[offset++]! & 0x3f;\n const byte4 = bytes[offset++]! & 0x3f;\n let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;\n if (unit > 0xffff) {\n unit -= 0x10000;\n units.push(((unit >>> 10) & 0x3ff) | 0xd800);\n unit = 0xdc00 | (unit & 0x3ff);\n }\n units.push(unit);\n } else {\n units.push(byte1);\n }\n\n if (units.length >= CHUNK_SIZE) {\n result += String.fromCharCode(...units);\n units.length = 0;\n }\n }\n\n if (units.length > 0) {\n result += String.fromCharCode(...units);\n }\n\n return result;\n}\n\nconst sharedTextDecoder = new TextDecoder();\n\n// This threshold should be determined by benchmarking, which might vary in engines and input data.\n// Run `npx ts-node benchmark/decode-string.ts` for details.\nconst TEXT_DECODER_THRESHOLD = 200;\n\nexport function utf8DecodeTD(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n const stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);\n return sharedTextDecoder.decode(stringBytes);\n}\n\nexport function utf8Decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n if (byteLength > TEXT_DECODER_THRESHOLD) {\n return utf8DecodeTD(bytes, inputOffset, byteLength);\n } else {\n return utf8DecodeJs(bytes, inputOffset, byteLength);\n }\n}\n", "/**\n * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.\n */\nexport class ExtData {\n readonly type: number;\n readonly data: Uint8Array | ((pos: number) => Uint8Array);\n\n constructor(type: number, data: Uint8Array | ((pos: number) => Uint8Array)) {\n this.type = type;\n this.data = data;\n }\n}\n", "export class DecodeError extends Error {\n constructor(message: string) {\n super(message);\n\n // fix the prototype chain in a cross-platform way\n const proto: typeof DecodeError.prototype = Object.create(DecodeError.prototype);\n Object.setPrototypeOf(this, proto);\n\n Object.defineProperty(this, \"name\", {\n configurable: true,\n enumerable: false,\n value: DecodeError.name,\n });\n }\n}\n", "// Integer Utility\n\nexport const UINT32_MAX = 0xffff_ffff;\n\n// DataView extension to handle int64 / uint64,\n// where the actual range is 53-bits integer (a.k.a. safe integer)\n\nexport function setUint64(view: DataView, offset: number, value: number): void {\n const high = value / 0x1_0000_0000;\n const low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\n\nexport function setInt64(view: DataView, offset: number, value: number): void {\n const high = Math.floor(value / 0x1_0000_0000);\n const low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\n\nexport function getInt64(view: DataView, offset: number): number {\n const high = view.getInt32(offset);\n const low = view.getUint32(offset + 4);\n return high * 0x1_0000_0000 + low;\n}\n\nexport function getUint64(view: DataView, offset: number): number {\n const high = view.getUint32(offset);\n const low = view.getUint32(offset + 4);\n return high * 0x1_0000_0000 + low;\n}\n", "// https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type\nimport { DecodeError } from \"./DecodeError.ts\";\nimport { getInt64, setInt64 } from \"./utils/int.ts\";\n\nexport const EXT_TIMESTAMP = -1;\n\nexport type TimeSpec = {\n sec: number;\n nsec: number;\n};\n\nconst TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int\nconst TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int\n\nexport function encodeTimeSpecToTimestamp({ sec, nsec }: TimeSpec): Uint8Array {\n if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {\n // Here sec >= 0 && nsec >= 0\n if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {\n // timestamp 32 = { sec32 (unsigned) }\n const rv = new Uint8Array(4);\n const view = new DataView(rv.buffer);\n view.setUint32(0, sec);\n return rv;\n } else {\n // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }\n const secHigh = sec / 0x100000000;\n const secLow = sec & 0xffffffff;\n const rv = new Uint8Array(8);\n const view = new DataView(rv.buffer);\n // nsec30 | secHigh2\n view.setUint32(0, (nsec << 2) | (secHigh & 0x3));\n // secLow32\n view.setUint32(4, secLow);\n return rv;\n }\n } else {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n const rv = new Uint8Array(12);\n const view = new DataView(rv.buffer);\n view.setUint32(0, nsec);\n setInt64(view, 4, sec);\n return rv;\n }\n}\n\nexport function encodeDateToTimeSpec(date: Date): TimeSpec {\n const msec = date.getTime();\n const sec = Math.floor(msec / 1e3);\n const nsec = (msec - sec * 1e3) * 1e6;\n\n // Normalizes { sec, nsec } to ensure nsec is unsigned.\n const nsecInSec = Math.floor(nsec / 1e9);\n return {\n sec: sec + nsecInSec,\n nsec: nsec - nsecInSec * 1e9,\n };\n}\n\nexport function encodeTimestampExtension(object: unknown): Uint8Array | null {\n if (object instanceof Date) {\n const timeSpec = encodeDateToTimeSpec(object);\n return encodeTimeSpecToTimestamp(timeSpec);\n } else {\n return null;\n }\n}\n\nexport function decodeTimestampToTimeSpec(data: Uint8Array): TimeSpec {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n // data may be 32, 64, or 96 bits\n switch (data.byteLength) {\n case 4: {\n // timestamp 32 = { sec32 }\n const sec = view.getUint32(0);\n const nsec = 0;\n return { sec, nsec };\n }\n case 8: {\n // timestamp 64 = { nsec30, sec34 }\n const nsec30AndSecHigh2 = view.getUint32(0);\n const secLow32 = view.getUint32(4);\n const sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;\n const nsec = nsec30AndSecHigh2 >>> 2;\n return { sec, nsec };\n }\n case 12: {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n\n const sec = getInt64(view, 4);\n const nsec = view.getUint32(0);\n return { sec, nsec };\n }\n default:\n throw new DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);\n }\n}\n\nexport function decodeTimestampExtension(data: Uint8Array): Date {\n const timeSpec = decodeTimestampToTimeSpec(data);\n return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);\n}\n\nexport const timestampExtension = {\n type: EXT_TIMESTAMP,\n encode: encodeTimestampExtension,\n decode: decodeTimestampExtension,\n};\n", "// ExtensionCodec to handle MessagePack extensions\n\nimport { ExtData } from \"./ExtData.ts\";\nimport { timestampExtension } from \"./timestamp.ts\";\n\nexport type ExtensionDecoderType<ContextType> = (\n data: Uint8Array,\n extensionType: number,\n context: ContextType,\n) => unknown;\n\nexport type ExtensionEncoderType<ContextType> = (\n input: unknown,\n context: ContextType,\n) => Uint8Array | ((dataPos: number) => Uint8Array) | null;\n\n// immutable interface to ExtensionCodec\nexport type ExtensionCodecType<ContextType> = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __brand?: ContextType;\n tryToEncode(object: unknown, context: ContextType): ExtData | null;\n decode(data: Uint8Array, extType: number, context: ContextType): unknown;\n};\n\nexport class ExtensionCodec<ContextType = undefined> implements ExtensionCodecType<ContextType> {\n public static readonly defaultCodec: ExtensionCodecType<undefined> = new ExtensionCodec();\n\n // ensures ExtensionCodecType<X> matches ExtensionCodec<X>\n // this will make type errors a lot more clear\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __brand?: ContextType;\n\n // built-in extensions\n private readonly builtInEncoders: Array<ExtensionEncoderType<ContextType> | undefined | null> = [];\n private readonly builtInDecoders: Array<ExtensionDecoderType<ContextType> | undefined | null> = [];\n\n // custom extensions\n private readonly encoders: Array<ExtensionEncoderType<ContextType> | undefined | null> = [];\n private readonly decoders: Array<ExtensionDecoderType<ContextType> | undefined | null> = [];\n\n public constructor() {\n this.register(timestampExtension);\n }\n\n public register({\n type,\n encode,\n decode,\n }: {\n type: number;\n encode: ExtensionEncoderType<ContextType>;\n decode: ExtensionDecoderType<ContextType>;\n }): void {\n if (type >= 0) {\n // custom extensions\n this.encoders[type] = encode;\n this.decoders[type] = decode;\n } else {\n // built-in extensions\n const index = -1 - type;\n this.builtInEncoders[index] = encode;\n this.builtInDecoders[index] = decode;\n }\n }\n\n public tryToEncode(object: unknown, context: ContextType): ExtData | null {\n // built-in extensions\n for (let i = 0; i < this.builtInEncoders.length; i++) {\n const encodeExt = this.builtInEncoders[i];\n if (encodeExt != null) {\n const data = encodeExt(object, context);\n if (data != null) {\n const type = -1 - i;\n return new ExtData(type, data);\n }\n }\n }\n\n // custom extensions\n for (let i = 0; i < this.encoders.length; i++) {\n const encodeExt = this.encoders[i];\n if (encodeExt != null) {\n const data = encodeExt(object, context);\n if (data != null) {\n const type = i;\n return new ExtData(type, data);\n }\n }\n }\n\n if (object instanceof ExtData) {\n // to keep ExtData as is\n return object;\n }\n return null;\n }\n\n public decode(data: Uint8Array, type: number, context: ContextType): unknown {\n const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];\n if (decodeExt) {\n return decodeExt(data, type, context);\n } else {\n // decode() does not fail, returns ExtData instead.\n return new ExtData(type, data);\n }\n }\n}\n", "function isArrayBufferLike(buffer: unknown): buffer is ArrayBufferLike {\n return (\n buffer instanceof ArrayBuffer || (typeof SharedArrayBuffer !== \"undefined\" && buffer instanceof SharedArrayBuffer)\n );\n}\n\nexport function ensureUint8Array(\n buffer: ArrayLike<number> | Uint8Array<ArrayBufferLike> | ArrayBufferView | ArrayBufferLike,\n): Uint8Array<ArrayBufferLike> {\n if (buffer instanceof Uint8Array) {\n return buffer;\n } else if (ArrayBuffer.isView(buffer)) {\n return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n } else if (isArrayBufferLike(buffer)) {\n return new Uint8Array(buffer);\n } else {\n // ArrayLike<number>\n return Uint8Array.from(buffer);\n }\n}\n", "import { utf8Count, utf8Encode } from \"./utils/utf8.ts\";\nimport { ExtensionCodec, ExtensionCodecType } from \"./ExtensionCodec.ts\";\nimport { setInt64, setUint64 } from \"./utils/int.ts\";\nimport { ensureUint8Array } from \"./utils/typedArrays.ts\";\nimport type { ExtData } from \"./ExtData.ts\";\nimport type { ContextOf } from \"./context.ts\";\n\nexport const DEFAULT_MAX_DEPTH = 100;\nexport const DEFAULT_INITIAL_BUFFER_SIZE = 2048;\n\nexport type EncoderOptions<ContextType = undefined> = Partial<\n Readonly<{\n extensionCodec: ExtensionCodecType<ContextType>;\n\n /**\n * Encodes bigint as Int64 or Uint64 if it's set to true.\n * {@link forceIntegerToFloat} does not affect bigint.\n * Depends on ES2020's {@link DataView#setBigInt64} and\n * {@link DataView#setBigUint64}.\n *\n * Defaults to false.\n */\n useBigInt64: boolean;\n\n /**\n * The maximum depth in nested objects and arrays.\n *\n * Defaults to 100.\n */\n maxDepth: number;\n\n /**\n * The initial size of the internal buffer.\n *\n * Defaults to 2048.\n */\n initialBufferSize: number;\n\n /**\n * If `true`, the keys of an object is sorted. In other words, the encoded\n * binary is canonical and thus comparable to another encoded binary.\n *\n * Defaults to `false`. If enabled, it spends more time in encoding objects.\n */\n sortKeys: boolean;\n /**\n * If `true`, non-integer numbers are encoded in float32, not in float64 (the default).\n *\n * Only use it if precisions don't matter.\n *\n * Defaults to `false`.\n */\n forceFloat32: boolean;\n\n /**\n * If `true`, an object property with `undefined` value are ignored.\n * e.g. `{ foo: undefined }` will be encoded as `{}`, as `JSON.stringify()` does.\n *\n * Defaults to `false`. If enabled, it spends more time in encoding objects.\n */\n ignoreUndefined: boolean;\n\n /**\n * If `true`, integer numbers are encoded as floating point numbers,\n * with the `forceFloat32` option taken into account.\n *\n * Defaults to `false`.\n */\n forceIntegerToFloat: boolean;\n }>\n> &\n ContextOf<ContextType>;\n\nexport class Encoder<ContextType = undefined> {\n private readonly extensionCodec: ExtensionCodecType<ContextType>;\n private readonly context: ContextType;\n private readonly useBigInt64: boolean;\n private readonly maxDepth: number;\n private readonly initialBufferSize: number;\n private readonly sortKeys: boolean;\n private readonly forceFloat32: boolean;\n private readonly ignoreUndefined: boolean;\n private readonly forceIntegerToFloat: boolean;\n\n private pos: number;\n private view: DataView;\n private bytes: Uint8Array;\n\n private entered = false;\n\n public constructor(options?: EncoderOptions<ContextType>) {\n this.extensionCodec = options?.extensionCodec ?? (ExtensionCodec.defaultCodec as ExtensionCodecType<ContextType>);\n this.context = (options as { context: ContextType } | undefined)?.context as ContextType; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined\n\n this.useBigInt64 = options?.useBigInt64 ?? false;\n this.maxDepth = options?.maxDepth ?? DEFAULT_MAX_DEPTH;\n this.initialBufferSize = options?.initialBufferSize ?? DEFAULT_INITIAL_BUFFER_SIZE;\n this.sortKeys = options?.sortKeys ?? false;\n this.forceFloat32 = options?.forceFloat32 ?? false;\n this.ignoreUndefined = options?.ignoreUndefined ?? false;\n this.forceIntegerToFloat = options?.forceIntegerToFloat ?? false;\n\n this.pos = 0;\n this.view = new DataView(new ArrayBuffer(this.initialBufferSize));\n this.bytes = new Uint8Array(this.view.buffer);\n }\n\n private clone() {\n // Because of slightly special argument `context`,\n // type assertion is needed.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return new Encoder<ContextType>({\n extensionCodec: this.extensionCodec,\n context: this.context,\n useBigInt64: this.useBigInt64,\n maxDepth: this.maxDepth,\n initialBufferSize: this.initialBufferSize,\n sortKeys: this.sortKeys,\n forceFloat32: this.forceFloat32,\n ignoreUndefined: this.ignoreUndefined,\n forceIntegerToFloat: this.forceIntegerToFloat,\n } as any);\n }\n\n private reinitializeState() {\n this.pos = 0;\n }\n\n /**\n * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.\n *\n * @returns Encodes the object and returns a shared reference the encoder's internal buffer.\n */\n public encodeSharedRef(object: unknown): Uint8Array {\n if (this.entered) {\n const instance = this.clone();\n return instance.encodeSharedRef(object);\n }\n\n try {\n this.entered = true;\n\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.subarray(0, this.pos);\n } finally {\n this.entered = false;\n }\n }\n\n /**\n * @returns Encodes the object and returns a copy of the encoder's internal buffer.\n */\n public encode(object: unknown): Uint8Array {\n if (this.entered) {\n const instance = this.clone();\n return instance.encode(object);\n }\n\n try {\n this.entered = true;\n\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.slice(0, this.pos);\n } finally {\n this.entered = false;\n }\n }\n\n private doEncode(object: unknown, depth: number): void {\n if (depth > this.maxDepth) {\n throw new Error(`Too deep objects in depth ${depth}`);\n }\n\n if (object == null) {\n this.encodeNil();\n } else if (typeof object === \"boolean\") {\n this.encodeBoolean(object);\n } else if (typeof object === \"number\") {\n if (!this.forceIntegerToFloat) {\n this.encodeNumber(object);\n } else {\n this.encodeNumberAsFloat(object);\n }\n } else if (typeof object === \"string\") {\n this.encodeString(object);\n } else if (this.useBigInt64 && typeof object === \"bigint\") {\n this.encodeBigInt64(object);\n } else {\n this.encodeObject(object, depth);\n }\n }\n\n private ensureBufferSizeToWrite(sizeToWrite: number) {\n const requiredSize = this.pos + sizeToWrite;\n\n if (this.view.byteLength < requiredSize) {\n this.resizeBuffer(requiredSize * 2);\n }\n }\n\n private resizeBuffer(newSize: number) {\n const newBuffer = new ArrayBuffer(newSize);\n const newBytes = new Uint8Array(newBuffer);\n const newView = new DataView(newBuffer);\n\n newBytes.set(this.bytes);\n\n this.view = newView;\n this.bytes = newBytes;\n }\n\n private encodeNil() {\n this.writeU8(0xc0);\n }\n\n private encodeBoolean(object: boolean) {\n if (object === false) {\n this.writeU8(0xc2);\n } else {\n this.writeU8(0xc3);\n }\n }\n\n private encodeNumber(object: number): void {\n if (!this.forceIntegerToFloat && Number.isSafeInteger(object)) {\n if (object >= 0) {\n if (object < 0x80) {\n // positive fixint\n this.writeU8(object);\n } else if (object < 0x100) {\n // uint 8\n this.writeU8(0xcc);\n this.writeU8(object);\n } else if (object < 0x10000) {\n // uint 16\n this.writeU8(0xcd);\n this.writeU16(object);\n } else if (object < 0x100000000) {\n // uint 32\n this.writeU8(0xce);\n this.writeU32(object);\n } else if (!this.useBigInt64) {\n // uint 64\n this.writeU8(0xcf);\n this.writeU64(object);\n } else {\n this.encodeNumberAsFloat(object);\n }\n } else {\n if (object >= -0x20) {\n // negative fixint\n this.writeU8(0xe0 | (object + 0x20));\n } else if (object >= -0x80) {\n // int 8\n this.writeU8(0xd0);\n this.writeI8(object);\n } else if (object >= -0x8000) {\n // int 16\n this.writeU8(0xd1);\n this.writeI16(object);\n } else if (object >= -0x80000000) {\n // int 32\n this.writeU8(0xd2);\n this.writeI32(object);\n } else if (!this.useBigInt64) {\n // int 64\n this.writeU8(0xd3);\n this.writeI64(object);\n } else {\n this.encodeNumberAsFloat(object);\n }\n }\n } else {\n this.encodeNumberAsFloat(object);\n }\n }\n\n private encodeNumberAsFloat(object: number): void {\n if (this.forceFloat32) {\n // float 32\n this.writeU8(0xca);\n this.writeF32(object);\n } else {\n // float 64\n this.writeU8(0xcb);\n this.writeF64(object);\n }\n }\n\n private encodeBigInt64(object: bigint): void {\n if (object >= BigInt(0)) {\n // uint 64\n this.writeU8(0xcf);\n this.writeBigUint64(object);\n } else {\n // int 64\n this.writeU8(0xd3);\n this.writeBigInt64(object);\n }\n }\n\n private writeStringHeader(byteLength: number) {\n if (byteLength < 32) {\n // fixstr\n this.writeU8(0xa0 + byteLength);\n } else if (byteLength < 0x100) {\n // str 8\n this.writeU8(0xd9);\n this.writeU8(byteLength);\n } else if (byteLength < 0x10000) {\n // str 16\n this.writeU8(0xda);\n this.writeU16(byteLength);\n } else if (byteLength < 0x100000000) {\n // str 32\n this.writeU8(0xdb);\n this.writeU32(byteLength);\n } else {\n throw new Error(`Too long string: ${byteLength} bytes in UTF-8`);\n }\n }\n\n private encodeString(object: string) {\n const maxHeaderSize = 1 + 4;\n\n const byteLength = utf8Count(object);\n this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n this.writeStringHeader(byteLength);\n utf8Encode(object, this.bytes, this.pos);\n this.pos += byteLength;\n }\n\n private encodeObject(object: unknown, depth: number) {\n // try to encode objects with custom codec first of non-primitives\n const ext = this.extensionCodec.tryToEncode(object, this.context);\n if (ext != null) {\n this.encodeExtension(ext);\n } else if (Array.isArray(object)) {\n this.encodeArray(object, depth);\n } else if (ArrayBuffer.isView(object)) {\n this.encodeBinary(object);\n } else if (typeof object === \"object\") {\n this.encodeMap(object as Record<string, unknown>, depth);\n } else {\n // symbol, function and other special object come here unless extensionCodec handles them.\n throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`);\n }\n }\n\n private encodeBinary(object: ArrayBufferView) {\n const size = object.byteLength;\n if (size < 0x100) {\n // bin 8\n this.writeU8(0xc4);\n this.writeU8(size);\n } else if (size < 0x10000) {\n // bin 16\n this.writeU8(0xc5);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // bin 32\n this.writeU8(0xc6);\n this.writeU32(size);\n } else {\n throw new Error(`Too large binary: ${size}`);\n }\n const bytes = ensureUint8Array(object);\n this.writeU8a(bytes);\n }\n\n private encodeArray(object: Array<unknown>, depth: number) {\n const size = object.length;\n if (size < 16) {\n // fixarray\n this.writeU8(0x90 + size);\n } else if (size < 0x10000) {\n // array 16\n this.writeU8(0xdc);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // array 32\n this.writeU8(0xdd);\n this.writeU32(size);\n } else {\n throw new Error(`Too large array: ${size}`);\n }\n for (const item of object) {\n this.doEncode(item, depth + 1);\n }\n }\n\n private countWithoutUndefined(object: Record<string, unknown>, keys: ReadonlyArray<string>): number {\n let count = 0;\n\n for (const key of keys) {\n if (object[key] !== undefined) {\n count++;\n }\n }\n\n return count;\n }\n\n private encodeMap(object: Record<string, unknown>, depth: number) {\n const keys = Object.keys(object);\n if (this.sortKeys) {\n keys.sort();\n }\n\n const size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;\n\n if (size < 16) {\n // fixmap\n this.writeU8(0x80 + size);\n } else if (size < 0x10000) {\n // map 16\n this.writeU8(0xde);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // map 32\n this.writeU8(0xdf);\n this.writeU32(size);\n } else {\n throw new Error(`Too large map object: ${size}`);\n }\n\n for (const key of keys) {\n const value = object[key];\n\n if (!(this.ignoreUndefined && value === undefined)) {\n this.encodeString(key);\n this.doEncode(value, depth + 1);\n }\n }\n }\n\n private encodeExtension(ext: ExtData) {\n if (typeof ext.data === \"function\") {\n const data = ext.data(this.pos + 6);\n const size = data.length;\n\n if (size >= 0x100000000) {\n throw new Error(`Too large extension object: ${size}`);\n }\n\n this.writeU8(0xc9);\n this.writeU32(size);\n this.writeI8(ext.type);\n this.writeU8a(data);\n return;\n }\n\n const size = ext.data.length;\n if (size === 1) {\n // fixext 1\n this.writeU8(0xd4);\n } else if (size === 2) {\n // fixext 2\n this.writeU8(0xd5);\n } else if (size === 4) {\n // fixext 4\n this.writeU8(0xd6);\n } else if (size === 8) {\n // fixext 8\n this.writeU8(0xd7);\n } else if (size === 16) {\n // fixext 16\n this.writeU8(0xd8);\n } else if (size < 0x100) {\n // ext 8\n this.writeU8(0xc7);\n this.writeU8(size);\n } else if (size < 0x10000) {\n // ext 16\n this.writeU8(0xc8);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // ext 32\n this.writeU8(0xc9);\n this.writeU32(size);\n } else {\n throw new Error(`Too large extension object: ${size}`);\n }\n this.writeI8(ext.type);\n this.writeU8a(ext.data);\n }\n\n private writeU8(value: number) {\n this.ensureBufferSizeToWrite(1);\n\n this.view.setUint8(this.pos, value);\n this.pos++;\n }\n\n private writeU8a(values: ArrayLike<number>) {\n const size = values.length;\n this.ensureBufferSizeToWrite(size);\n\n this.bytes.set(values, this.pos);\n this.pos += size;\n }\n\n private writeI8(value: number) {\n this.ensureBufferSizeToWrite(1);\n\n this.view.setInt8(this.pos, value);\n this.pos++;\n }\n\n private writeU16(value: number) {\n this.ensureBufferSizeToWrite(2);\n\n this.view.setUint16(this.pos, value);\n this.pos += 2;\n }\n\n private writeI16(value: number) {\n this.ensureBufferSizeToWrite(2);\n\n this.view.setInt16(this.pos, value);\n this.pos += 2;\n }\n\n private writeU32(value: number) {\n this.ensureBufferSizeToWrite(4);\n\n this.view.setUint32(this.pos, value);\n this.pos += 4;\n }\n\n private writeI32(value: number) {\n this.ensureBufferSizeToWrite(4);\n\n this.view.setInt32(this.pos, value);\n this.pos += 4;\n }\n\n private writeF32(value: number) {\n this.ensureBufferSizeToWrite(4);\n\n this.view.setFloat32(this.pos, value);\n this.pos += 4;\n }\n\n private writeF64(value: number) {\n this.ensureBufferSizeToWrite(8);\n\n this.view.setFloat64(this.pos, value);\n this.pos += 8;\n }\n\n private writeU64(value: number) {\n this.ensureBufferSizeToWrite(8);\n\n setUint64(this.view, this.pos, value);\n this.pos += 8;\n }\n\n private writeI64(value: number) {\n this.ensureBufferSizeToWrite(8);\n\n setInt64(this.view, this.pos, value);\n this.pos += 8;\n }\n\n private writeBigUint64(value: bigint) {\n this.ensureBufferSizeToWrite(8);\n\n this.view.setBigUint64(this.pos, value);\n this.pos += 8;\n }\n\n private writeBigInt64(value: bigint) {\n this.ensureBufferSizeToWrite(8);\n\n this.view.setBigInt64(this.pos, value);\n this.pos += 8;\n }\n}\n", "import { Encoder } from \"./Encoder.ts\";\nimport type { EncoderOptions } from \"./Encoder.ts\";\nimport type { SplitUndefined } from \"./context.ts\";\n\n/**\n * It encodes `value` in the MessagePack format and\n * returns a byte buffer.\n *\n * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.\n */\nexport function encode<ContextType = undefined>(\n value: unknown,\n options?: EncoderOptions<SplitUndefined<ContextType>>,\n): Uint8Array {\n const encoder = new Encoder(options);\n return encoder.encodeSharedRef(value);\n}\n", "export function prettyByte(byte: number): string {\n return `${byte < 0 ? \"-\" : \"\"}0x${Math.abs(byte).toString(16).padStart(2, \"0\")}`;\n}\n", "import { utf8DecodeJs } from \"./utils/utf8.ts\";\n\nconst DEFAULT_MAX_KEY_LENGTH = 16;\nconst DEFAULT_MAX_LENGTH_PER_KEY = 16;\n\nexport interface KeyDecoder {\n canBeCached(byteLength: number): boolean;\n decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string;\n}\ninterface KeyCacheRecord {\n readonly bytes: Uint8Array;\n readonly str: string;\n}\n\nexport class CachedKeyDecoder implements KeyDecoder {\n hit = 0;\n miss = 0;\n private readonly caches: Array<Array<KeyCacheRecord>>;\n private readonly maxKeyLength: number;\n private readonly maxLengthPerKey: number;\n\n constructor(maxKeyLength = DEFAULT_MAX_KEY_LENGTH, maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY) {\n this.maxKeyLength = maxKeyLength;\n this.maxLengthPerKey = maxLengthPerKey;\n\n // avoid `new Array(N)`, which makes a sparse array,\n // because a sparse array is typically slower than a non-sparse array.\n this.caches = [];\n for (let i = 0; i < this.maxKeyLength; i++) {\n this.caches.push([]);\n }\n }\n\n public canBeCached(byteLength: number): boolean {\n return byteLength > 0 && byteLength <= this.maxKeyLength;\n }\n\n private find(bytes: Uint8Array, inputOffset: number, byteLength: number): string | null {\n const records = this.caches[byteLength - 1]!;\n\n FIND_CHUNK: for (const record of records) {\n const recordBytes = record.bytes;\n\n for (let j = 0; j < byteLength; j++) {\n if (recordBytes[j] !== bytes[inputOffset + j]) {\n continue FIND_CHUNK;\n }\n }\n return record.str;\n }\n return null;\n }\n\n private store(bytes: Uint8Array, value: string) {\n const records = this.caches[bytes.length - 1]!;\n const record: KeyCacheRecord = { bytes, str: value };\n\n if (records.length >= this.maxLengthPerKey) {\n // `records` are full!\n // Set `record` to an arbitrary position.\n records[(Math.random() * records.length) | 0] = record;\n } else {\n records.push(record);\n }\n }\n\n public decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n const cachedValue = this.find(bytes, inputOffset, byteLength);\n if (cachedValue != null) {\n this.hit++;\n return cachedValue;\n }\n this.miss++;\n\n const str = utf8DecodeJs(bytes, inputOffset, byteLength);\n // Ensure to copy a slice of bytes because the bytes may be a NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.\n const slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);\n this.store(slicedCopyOfBytes, str);\n return str;\n }\n}\n", "import { prettyByte } from \"./utils/prettyByte.ts\";\nimport { ExtensionCodec, ExtensionCodecType } from \"./ExtensionCodec.ts\";\nimport { getInt64, getUint64, UINT32_MAX } from \"./utils/int.ts\";\nimport { utf8Decode } from \"./utils/utf8.ts\";\nimport { ensureUint8Array } from \"./utils/typedArrays.ts\";\nimport { CachedKeyDecoder, KeyDecoder } from \"./CachedKeyDecoder.ts\";\nimport { DecodeError } from \"./DecodeError.ts\";\nimport type { ContextOf } from \"./context.ts\";\n\nexport type DecoderOptions<ContextType = undefined> = Readonly<\n Partial<{\n extensionCodec: ExtensionCodecType<ContextType>;\n\n /**\n * Decodes Int64 and Uint64 as bigint if it's set to true.\n * Depends on ES2020's {@link DataView#getBigInt64} and\n * {@link DataView#getBigUint64}.\n *\n * Defaults to false.\n */\n useBigInt64: boolean;\n\n /**\n * By default, string values will be decoded as UTF-8 strings. However, if this option is true,\n * string values will be returned as Uint8Arrays without additional decoding.\n *\n * This is useful if the strings may contain invalid UTF-8 sequences.\n *\n * Note that this option only applies to string values, not map keys. Additionally, when\n * enabled, raw string length is limited by the maxBinLength option.\n */\n rawStrings: boolean;\n\n /**\n * Maximum string length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxStrLength: number;\n /**\n * Maximum binary length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxBinLength: number;\n /**\n * Maximum array length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxArrayLength: number;\n /**\n * Maximum map length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxMapLength: number;\n /**\n * Maximum extension length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxExtLength: number;\n\n /**\n * An object key decoder. Defaults to the shared instance of {@link CachedKeyDecoder}.\n * `null` is a special value to disable the use of the key decoder at all.\n */\n keyDecoder: KeyDecoder | null;\n\n /**\n * A function to convert decoded map key to a valid JS key type.\n * \n * Defaults to a function that throws an error if the key is not a string or a number.\n */\n mapKeyConverter: (key: unknown) => MapKeyType;\n }>\n> &\n ContextOf<ContextType>;\n\nconst STATE_ARRAY = \"array\";\nconst STATE_MAP_KEY = \"map_key\";\nconst STATE_MAP_VALUE = \"map_value\";\n\ntype MapKeyType = string | number;\n\nconst mapKeyConverter = (key: unknown): MapKeyType => {\n if (typeof key === \"string\" || typeof key === \"number\") {\n return key;\n }\n throw new DecodeError(\"The type of key must be string or number but \" + typeof key);\n};\n\ntype StackMapState = {\n type: typeof STATE_MAP_KEY | typeof STATE_MAP_VALUE;\n size: number;\n key: MapKeyType | null;\n readCount: number;\n map: Record<string, unknown>;\n};\n\ntype StackArrayState = {\n type: typeof STATE_ARRAY;\n size: number;\n array: Array<unknown>;\n position: number;\n};\n\nclass StackPool {\n private readonly stack: Array<StackState> = [];\n private stackHeadPosition = -1;\n\n public get length(): number {\n return this.stackHeadPosition + 1;\n }\n\n public top(): StackState | undefined {\n return this.stack[this.stackHeadPosition];\n }\n\n public pushArrayState(size: number) {\n const state = this.getUninitializedStateFromPool() as StackArrayState;\n\n state.type = STATE_ARRAY;\n state.position = 0;\n state.size = size;\n state.array = new Array(size);\n }\n\n public pushMapState(size: number) {\n const state = this.getUninitializedStateFromPool() as StackMapState;\n\n state.type = STATE_MAP_KEY;\n state.readCount = 0;\n state.size = size;\n state.map = {};\n }\n\n private getUninitializedStateFromPool() {\n this.stackHeadPosition++;\n\n if (this.stackHeadPosition === this.stack.length) {\n const partialState: Partial<StackState> = {\n type: undefined,\n size: 0,\n array: undefined,\n position: 0,\n readCount: 0,\n map: undefined,\n key: null,\n };\n\n this.stack.push(partialState as StackState);\n }\n\n return this.stack[this.stackHeadPosition];\n }\n\n public release(state: StackState): void {\n const topStackState = this.stack[this.stackHeadPosition];\n\n if (topStackState !== state) {\n throw new Error(\"Invalid stack state. Released state is not on top of the stack.\");\n }\n\n if (state.type === STATE_ARRAY) {\n const partialState = state as Partial<StackArrayState>;\n partialState.size = 0;\n partialState.array = undefined;\n partialState.position = 0;\n partialState.type = undefined;\n }\n\n if (state.type === STATE_MAP_KEY || state.type === STATE_MAP_VALUE) {\n const partialState = state as Partial<StackMapState>;\n partialState.size = 0;\n partialState.map = undefined;\n partialState.readCount = 0;\n partialState.type = undefined;\n }\n\n this.stackHeadPosition--;\n }\n\n public reset(): void {\n this.stack.length = 0;\n this.stackHeadPosition = -1;\n }\n}\n\ntype StackState = StackArrayState | StackMapState;\n\nconst HEAD_BYTE_REQUIRED = -1;\n\nconst EMPTY_VIEW = new DataView<ArrayBufferLike>(new ArrayBuffer(0));\nconst EMPTY_BYTES = new Uint8Array<ArrayBufferLike>(EMPTY_VIEW.buffer);\n\ntry {\n // IE11: The spec says it should throw RangeError,\n // IE11: but in IE11 it throws TypeError.\n EMPTY_VIEW.getInt8(0);\n} catch (e) {\n if (!(e instanceof RangeError)) {\n throw new Error(\n \"This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access\",\n );\n }\n}\n\nconst MORE_DATA = new RangeError(\"Insufficient data\");\n\nconst sharedCachedKeyDecoder = new CachedKeyDecoder();\n\nexport class Decoder<ContextType = undefined> {\n private readonly extensionCodec: ExtensionCodecType<ContextType>;\n private readonly context: ContextType;\n private readonly useBigInt64: boolean;\n private readonly rawStrings: boolean;\n private readonly maxStrLength: number;\n private readonly maxBinLength: number;\n private readonly maxArrayLength: number;\n private readonly maxMapLength: number;\n private readonly maxExtLength: number;\n private readonly keyDecoder: KeyDecoder | null;\n private readonly mapKeyConverter: (key: unknown) => MapKeyType;\n\n private totalPos = 0;\n private pos = 0;\n\n private view = EMPTY_VIEW;\n private bytes = EMPTY_BYTES;\n private headByte = HEAD_BYTE_REQUIRED;\n private readonly stack = new StackPool();\n\n private entered = false;\n\n public constructor(options?: DecoderOptions<ContextType>) {\n this.extensionCodec = options?.extensionCodec ?? (ExtensionCodec.defaultCodec as ExtensionCodecType<ContextType>);\n this.context = (options as { context: ContextType } | undefined)?.context as ContextType; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined\n\n this.useBigInt64 = options?.useBigInt64 ?? false;\n this.rawStrings = options?.rawStrings ?? false;\n this.maxStrLength = options?.maxStrLength ?? UINT32_MAX;\n this.maxBinLength = options?.maxBinLength ?? UINT32_MAX;\n this.maxArrayLength = options?.maxArrayLength ?? UINT32_MAX;\n this.maxMapLength = options?.maxMapLength ?? UINT32_MAX;\n this.maxExtLength = options?.maxExtLength ?? UINT32_MAX;\n this.keyDecoder = options?.keyDecoder !== undefined ? options.keyDecoder : sharedCachedKeyDecoder;\n this.mapKeyConverter = options?.mapKeyConverter ?? mapKeyConverter;\n }\n\n private clone(): Decoder<ContextType> {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return new Decoder({\n extensionCodec: this.extensionCodec,\n context: this.context,\n useBigInt64: this.useBigInt64,\n rawStrings: this.rawStrings,\n maxStrLength: this.maxStrLength,\n maxBinLength: this.maxBinLength,\n maxArrayLength: this.maxArrayLength,\n maxMapLength: this.maxMapLength,\n maxExtLength: this.maxExtLength,\n keyDecoder: this.keyDecoder,\n } as any);\n }\n\n private reinitializeState() {\n this.totalPos = 0;\n this.headByte = HEAD_BYTE_REQUIRED;\n this.stack.reset();\n\n // view, bytes, and pos will be re-initialized in setBuffer()\n }\n\n private setBuffer(buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike): void {\n const bytes = ensureUint8Array(buffer);\n this.bytes = bytes;\n this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n this.pos = 0;\n }\n\n private appendBuffer(buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike): void {\n if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {\n this.setBuffer(buffer);\n } else {\n const remainingData = this.bytes.subarray(this.pos);\n const newData = ensureUint8Array(buffer);\n\n // concat remainingData + newData\n const newBuffer = new Uint8Array(remainingData.length + newData.length);\n newBuffer.set(remainingData);\n newBuffer.set(newData, remainingData.length);\n this.setBuffer(newBuffer);\n }\n }\n\n private hasRemaining(size: number) {\n return this.view.byteLength - this.pos >= size;\n }\n\n private createExtraByteError(posToShow: number): Error {\n const { view, pos } = this;\n return new RangeError(`Extra ${view.byteLength - pos} of ${view.byteLength} byte(s) found at buffer[${posToShow}]`);\n }\n\n /**\n * @throws {@link DecodeError}\n * @throws {@link RangeError}\n */\n public decode(buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike): unknown {\n if (this.entered) {\n const instance = this.clone();\n return instance.decode(buffer);\n }\n\n try {\n this.entered = true;\n\n this.reinitializeState();\n this.setBuffer(buffer);\n\n const object = this.doDecodeSync();\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.pos);\n }\n return object;\n } finally {\n this.entered = false;\n }\n }\n\n public *decodeMulti(buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike): Generator<unknown, void, unknown> {\n if (this.entered) {\n const instance = this.clone();\n yield* instance.decodeMulti(buffer);\n return;\n }\n\n try {\n this.entered = true;\n\n this.reinitializeState();\n this.setBuffer(buffer);\n\n while (this.hasRemaining(1)) {\n yield this.doDecodeSync();\n }\n } finally {\n this.entered = false;\n }\n }\n\n public async decodeAsync(stream: AsyncIterable<ArrayLike<number> | ArrayBufferView | ArrayBufferLike>): Promise<unknown> {\n if (this.entered) {\n const instance = this.clone();\n return instance.decodeAsync(stream);\n }\n\n try {\n this.entered = true;\n\n let decoded = false;\n let object: unknown;\n for await (const buffer of stream) {\n if (decoded) {\n this.entered = false;\n throw this.createExtraByteError(this.totalPos);\n }\n\n this.appendBuffer(buffer);\n\n try {\n object = this.doDecodeSync();\n decoded = true;\n } catch (e) {\n if (!(e instanceof RangeError)) {\n throw e; // rethrow\n }\n // fallthrough\n }\n this.totalPos += this.pos;\n }\n\n if (decoded) {\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.totalPos);\n }\n return object;\n }\n\n const { headByte, pos, totalPos } = this;\n throw new RangeError(\n `Insufficient data in parsing ${prettyByte(headByte)} at ${totalPos} (${pos} in the current buffer)`,\n );\n } finally {\n this.entered = false;\n }\n }\n\n public decodeArrayStream(\n stream: AsyncIterable<ArrayLike<number> | ArrayBufferView | ArrayBufferLike>,\n ): AsyncGenerator<unknown, void, unknown> {\n return this.decodeMultiAsync(stream, true);\n }\n\n public decodeStream(stream: AsyncIterable<ArrayLike<number> | ArrayBufferView | ArrayBufferLike>): AsyncGenerator<unknown, void, unknown> {\n return this.decodeMultiAsync(stream, false);\n }\n\n private async *decodeMultiAsync(stream: AsyncIterable<ArrayLike<number> | ArrayBufferView | ArrayBufferLike>, isArray: boolean): AsyncGenerator<unknown, void, unknown> {\n if (this.entered) {\n const instance = this.clone();\n yield* instance.decodeMultiAsync(stream, isArray);\n return;\n }\n\n try {\n this.entered = true;\n\n let isArrayHeaderRequired = isArray;\n let arrayItemsLeft = -1;\n\n for await (const buffer of stream) {\n if (isArray && arrayItemsLeft === 0) {\n throw this.createExtraByteError(this.totalPos);\n }\n\n this.appendBuffer(buffer);\n\n if (isArrayHeaderRequired) {\n arrayItemsLeft = this.readArraySize();\n isArrayHeaderRequired = false;\n this.complete();\n }\n\n try {\n while (true) {\n yield this.doDecodeSync();\n if (--arrayItemsLeft === 0) {\n break;\n }\n }\n } catch (e) {\n if (!(e instanceof RangeError)) {\n throw e; // rethrow\n }\n // fallthrough\n }\n this.totalPos += this.pos;\n }\n } finally {\n this.entered = false;\n }\n }\n\n private doDecodeSync(): unknown {\n DECODE: while (true) {\n const headByte = this.readHeadByte();\n let object: unknown;\n\n if (headByte >= 0xe0) {\n // negative fixint (111x xxxx) 0xe0 - 0xff\n object = headByte - 0x100;\n } else if (headByte < 0xc0) {\n if (headByte < 0x80) {\n // positive fixint (0xxx xxxx) 0x00 - 0x7f\n object = headByte;\n } else if (headByte < 0x90) {\n // fixmap (1000 xxxx) 0x80 - 0x8f\n const size = headByte - 0x80;\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte < 0xa0) {\n // fixarray (1001 xxxx) 0x90 - 0x9f\n const size = headByte - 0x90;\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else {\n // fixstr (101x xxxx) 0xa0 - 0xbf\n const byteLength = headByte - 0xa0;\n object = this.decodeString(byteLength, 0);\n }\n } else if (headByte === 0xc0) {\n // nil\n object = null;\n } else if (headByte === 0xc2) {\n // false\n object = false;\n } else if (headByte === 0xc3) {\n // true\n object = true;\n } else if (headByte === 0xca) {\n // float 32\n object = this.readF32();\n } else if (headByte === 0xcb) {\n // float 64\n object = this.readF64();\n } else if (headByte === 0xcc) {\n // uint 8\n object = this.readU8();\n } else if (headByte === 0xcd) {\n // uint 16\n object = this.readU16();\n } else if (headByte === 0xce) {\n // uint 32\n object = this.readU32();\n } else if (headByte === 0xcf) {\n // uint 64\n if (this.useBigInt64) {\n object = this.readU64AsBigInt();\n } else {\n object = this.readU64();\n }\n } else if (headByte === 0xd0) {\n // int 8\n object = this.readI8();\n } else if (headByte === 0xd1) {\n // int 16\n object = this.readI16();\n } else if (headByte === 0xd2) {\n // int 32\n object = this.readI32();\n } else if (headByte === 0xd3) {\n // int 64\n if (this.useBigInt64) {\n object = this.readI64AsBigInt();\n } else {\n object = this.readI64();\n }\n } else if (headByte === 0xd9) {\n // str 8\n const byteLength = this.lookU8();\n object = this.decodeString(byteLength, 1);\n } else if (headByte === 0xda) {\n // str 16\n const byteLength = this.lookU16();\n object = this.decodeString(byteLength, 2);\n } else if (headByte === 0xdb) {\n // str 32\n const byteLength = this.lookU32();\n object = this.decodeString(byteLength, 4);\n } else if (headByte === 0xdc) {\n // array 16\n const size = this.readU16();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else if (headByte === 0xdd) {\n // array 32\n const size = this.readU32();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else if (headByte === 0xde) {\n // map 16\n const size = this.readU16();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte === 0xdf) {\n // map 32\n const size = this.readU32();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte === 0xc4) {\n // bin 8\n const size = this.lookU8();\n object = this.decodeBinary(size, 1);\n } else if (headByte === 0xc5) {\n // bin 16\n const size = this.lookU16();\n object = this.decodeBinary(size, 2);\n } else if (headByte === 0xc6) {\n // bin 32\n const size = this.lookU32();\n object = this.decodeBinary(size, 4);\n } else if (headByte === 0xd4) {\n // fixext 1\n object = this.decodeExtension(1, 0);\n } else if (headByte === 0xd5) {\n // fixext 2\n object = this.decodeExtension(2, 0);\n } else if (headByte === 0xd6) {\n // fixext 4\n object = this.decodeExtension(4, 0);\n } else if (headByte === 0xd7) {\n // fixext 8\n object = this.decodeExtension(8, 0);\n } else if (headByte === 0xd8) {\n // fixext 16\n object = this.decodeExtension(16, 0);\n } else if (headByte === 0xc7) {\n // ext 8\n const size = this.lookU8();\n object = this.decodeExtension(size, 1);\n } else if (headByte === 0xc8) {\n // ext 16\n const size = this.lookU16();\n object = this.decodeExtension(size, 2);\n } else if (headByte === 0xc9) {\n // ext 32\n const size = this.lookU32();\n object = this.decodeExtension(size, 4);\n } else {\n throw new DecodeError(`Unrecognized type byte: ${prettyByte(headByte)}`);\n }\n\n this.complete();\n\n const stack = this.stack;\n while (stack.length > 0) {\n // arrays and maps\n const state = stack.top()!;\n if (state.type === STATE_ARRAY) {\n state.array[state.position] = object;\n state.position++;\n if (state.position === state.size) {\n object = state.array;\n stack.release(state);\n } else {\n continue DECODE;\n }\n } else if (state.type === STATE_MAP_KEY) {\n if (object === \"__proto__\") {\n throw new DecodeError(\"The key __proto__ is not allowed\");\n }\n\n state.key = this.mapKeyConverter(object);\n state.type = STATE_MAP_VALUE;\n continue DECODE;\n } else {\n // it must be `state.type === State.MAP_VALUE` here\n\n state.map[state.key!] = object;\n state.readCount++;\n\n if (state.readCount === state.size) {\n object = state.map;\n stack.release(state);\n } else {\n state.key = null;\n state.type = STATE_MAP_KEY;\n continue DECODE;\n }\n }\n }\n\n return object;\n }\n }\n\n private readHeadByte(): number {\n if (this.headByte === HEAD_BYTE_REQUIRED) {\n this.headByte = this.readU8();\n // console.log(\"headByte\", prettyByte(this.headByte));\n }\n\n return this.headByte;\n }\n\n private complete(): void {\n this.headByte = HEAD_BYTE_REQUIRED;\n }\n\n private readArraySize(): number {\n const headByte = this.readHeadByte();\n\n switch (headByte) {\n case 0xdc:\n return this.readU16();\n case 0xdd:\n return this.readU32();\n default: {\n if (headByte < 0xa0) {\n return headByte - 0x90;\n } else {\n throw new DecodeError(`Unrecognized array type byte: ${prettyByte(headByte)}`);\n }\n }\n }\n }\n\n private pushMapState(size: number) {\n if (size > this.maxMapLength) {\n throw new DecodeError(`Max length exceeded: map length (${size}) > maxMapLengthLength (${this.maxMapLength})`);\n }\n\n this.stack.pushMapState(size);\n }\n\n private pushArrayState(size: number) {\n if (size > this.maxArrayLength) {\n throw new DecodeError(`Max length exceeded: array length (${size}) > maxArrayLength (${this.maxArrayLength})`);\n }\n\n this.stack.pushArrayState(size);\n }\n\n private decodeString(byteLength: number, headerOffset: number): string | Uint8Array {\n if (!this.rawStrings || this.stateIsMapKey()) {\n return this.decodeUtf8String(byteLength, headerOffset);\n }\n return this.decodeBinary(byteLength, headerOffset);\n }\n\n /**\n * @throws {@link RangeError}\n */\n private decodeUtf8String(byteLength: number, headerOffset: number): string {\n if (byteLength > this.maxStrLength) {\n throw new DecodeError(\n `Max length exceeded: UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`,\n );\n }\n\n if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {\n throw MORE_DATA;\n }\n\n const offset = this.pos + headerOffset;\n let object: string;\n if (this.stateIsMapKey() && this.keyDecoder?.canBeCached(byteLength)) {\n object = this.keyDecoder.decode(this.bytes, offset, byteLength);\n } else {\n object = utf8Decode(this.bytes, offset, byteLength);\n }\n this.pos += headerOffset + byteLength;\n return object;\n }\n\n private stateIsMapKey(): boolean {\n if (this.stack.length > 0) {\n const state = this.stack.top()!;\n return state.type === STATE_MAP_KEY;\n }\n return false;\n }\n\n /**\n * @throws {@link RangeError}\n */\n private decodeBinary(byteLength: number, headOffset: number): Uint8Array {\n if (byteLength > this.maxBinLength) {\n throw new DecodeError(`Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`);\n }\n\n if (!this.hasRemaining(byteLength + headOffset)) {\n throw MORE_DATA;\n }\n\n const offset = this.pos + headOffset;\n const object = this.bytes.subarray(offset, offset + byteLength);\n this.pos += headOffset + byteLength;\n return object;\n }\n\n private decodeExtension(size: number, headOffset: number): unknown {\n if (size > this.maxExtLength) {\n throw new DecodeError(`Max length exceeded: ext length (${size}) > maxExtLength (${this.maxExtLength})`);\n }\n\n const extType = this.view.getInt8(this.pos + headOffset);\n const data = this.decodeBinary(size, headOffset + 1 /* extType */);\n return this.extensionCodec.decode(data, extType, this.context);\n }\n\n private lookU8() {\n return this.view.getUint8(this.pos);\n }\n\n private lookU16() {\n return this.view.getUint16(this.pos);\n }\n\n private lookU32() {\n return this.view.getUint32(this.pos);\n }\n\n private readU8(): number {\n const value = this.view.getUint8(this.pos);\n this.pos++;\n return value;\n }\n\n private readI8(): number {\n const value = this.view.getInt8(this.pos);\n this.pos++;\n return value;\n }\n\n private readU16(): number {\n const value = this.view.getUint16(this.pos);\n this.pos += 2;\n return value;\n }\n\n private readI16(): number {\n const value = this.view.getInt16(this.pos);\n this.pos += 2;\n return value;\n }\n\n private readU32(): number {\n const value = this.view.getUint32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readI32(): number {\n const value = this.view.getInt32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readU64(): number {\n const value = getUint64(this.view, this.pos);\n this.pos += 8;\n return value;\n }\n\n private readI64(): number {\n const value = getInt64(this.view, this.pos);\n this.pos += 8;\n return value;\n }\n\n private readU64AsBigInt(): bigint {\n const value = this.view.getBigUint64(this.pos);\n this.pos += 8;\n return value;\n }\n\n private readI64AsBigInt(): bigint {\n const value = this.view.getBigInt64(this.pos);\n this.pos += 8;\n return value;\n }\n\n private readF32() {\n const value = this.view.getFloat32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readF64() {\n const value = this.view.getFloat64(this.pos);\n this.pos += 8;\n return value;\n }\n}\n", "import { Decoder } from \"./Decoder.ts\";\nimport type { DecoderOptions } from \"./Decoder.ts\";\nimport type { SplitUndefined } from \"./context.ts\";\n\n/**\n * It decodes a single MessagePack object in a buffer.\n *\n * This is a synchronous decoding function.\n * See other variants for asynchronous decoding: {@link decodeAsync}, {@link decodeStream}, or {@link decodeArrayStream}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decode<ContextType = undefined>(\n buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): unknown {\n const decoder = new Decoder(options);\n return decoder.decode(buffer);\n}\n\n/**\n * It decodes multiple MessagePack objects in a buffer.\n * This is corresponding to {@link decodeMultiStream}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMulti<ContextType = undefined>(\n buffer: ArrayLike<number> | BufferSource,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): Generator<unknown, void, unknown> {\n const decoder = new Decoder(options);\n return decoder.decodeMulti(buffer);\n}\n", "// utility for whatwg streams\n\n// The living standard of whatwg streams says\n// ReadableStream is also AsyncIterable, but\n// as of June 2019, no browser implements it.\n// See https://streams.spec.whatwg.org/ for details\nexport type ReadableStreamLike<T> = AsyncIterable<T> | ReadableStream<T>;\n\nexport function isAsyncIterable<T>(object: ReadableStreamLike<T>): object is AsyncIterable<T> {\n return (object as any)[Symbol.asyncIterator] != null;\n}\n\nexport async function* asyncIterableFromStream<T>(stream: ReadableStream<T>): AsyncIterable<T> {\n const reader = stream.getReader();\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nexport function ensureAsyncIterable<T>(streamLike: ReadableStreamLike<T>): AsyncIterable<T> {\n if (isAsyncIterable(streamLike)) {\n return streamLike;\n } else {\n return asyncIterableFromStream(streamLike);\n }\n}\n", "import { Decoder } from \"./Decoder.ts\";\nimport { ensureAsyncIterable } from \"./utils/stream.ts\";\nimport type { DecoderOptions } from \"./Decoder.ts\";\nimport type { ReadableStreamLike } from \"./utils/stream.ts\";\nimport type { SplitUndefined } from \"./context.ts\";\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport async function decodeAsync<ContextType = undefined>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): Promise<unknown> {\n const stream = ensureAsyncIterable(streamLike);\n const decoder = new Decoder(options);\n return decoder.decodeAsync(stream);\n}\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeArrayStream<ContextType>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): AsyncGenerator<unknown, void, unknown> {\n const stream = ensureAsyncIterable(streamLike);\n const decoder = new Decoder(options);\n return decoder.decodeArrayStream(stream);\n}\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMultiStream<ContextType>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): AsyncGenerator<unknown, void, unknown> {\n const stream = ensureAsyncIterable(streamLike);\n const decoder = new Decoder(options);\n return decoder.decodeStream(stream);\n}\n", "// Main Functions:\n\nimport { encode } from \"./encode.ts\";\nexport { encode };\n\nimport { decode, decodeMulti } from \"./decode.ts\";\nexport { decode, decodeMulti };\n\nimport { decodeAsync, decodeArrayStream, decodeMultiStream } from \"./decodeAsync.ts\";\nexport { decodeAsync, decodeArrayStream, decodeMultiStream };\n\nimport { Decoder } from \"./Decoder.ts\";\nexport { Decoder };\nimport type { DecoderOptions } from \"./Decoder.ts\";\nexport type { DecoderOptions };\nimport { DecodeError } from \"./DecodeError.ts\";\nexport { DecodeError };\n\nimport { Encoder } from \"./Encoder.ts\";\nexport { Encoder };\nimport type { EncoderOptions } from \"./Encoder.ts\";\nexport type { EncoderOptions };\n\n// Utilities for Extension Types:\n\nimport { ExtensionCodec } from \"./ExtensionCodec.ts\";\nexport { ExtensionCodec };\nimport type { ExtensionCodecType, ExtensionDecoderType, ExtensionEncoderType } from \"./ExtensionCodec.ts\";\nexport type { ExtensionCodecType, ExtensionDecoderType, ExtensionEncoderType };\nimport { ExtData } from \"./ExtData.ts\";\nexport { ExtData };\n\nimport {\n EXT_TIMESTAMP,\n encodeDateToTimeSpec,\n encodeTimeSpecToTimestamp,\n decodeTimestampToTimeSpec,\n encodeTimestampExtension,\n decodeTimestampExtension,\n} from \"./timestamp.ts\";\nexport {\n EXT_TIMESTAMP,\n encodeDateToTimeSpec,\n encodeTimeSpecToTimestamp,\n decodeTimestampToTimeSpec,\n encodeTimestampExtension,\n decodeTimestampExtension,\n};\n", "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction valueEnumerable(value) {\n return { enumerable: true, value };\n}\n\nfunction valueEnumerableWritable(value) {\n return { enumerable: true, writable: true, value };\n}\n\nlet d = {};\nlet truthy = () => true;\nlet empty = () => ({});\nlet identity = a => a;\nlet callBoth = (par, fn, self, args) => par.apply(self, args) && fn.apply(self, args);\nlet callForward = (par, fn, self, [a, b]) => fn.call(self, par.call(self, a, b), b);\nlet create = (a, b) => Object.freeze(Object.create(a, b));\n\nfunction stack(fns, def, caller) {\n return fns.reduce((par, fn) => {\n return function(...args) {\n return caller(par, fn, this, args);\n };\n }, def);\n}\n\nfunction fnType(fn) {\n return create(this, { fn: valueEnumerable(fn) });\n}\n\nlet reduceType = {};\nlet reduce = fnType.bind(reduceType);\nlet action = fn => reduce((ctx, ev) => !!~fn(ctx, ev) && ctx);\n\nlet guardType = {};\nlet guard = fnType.bind(guardType);\n\nfunction filter(Type, arr) {\n return arr.filter(value => Type.isPrototypeOf(value));\n}\n\nfunction makeTransition(from, to, ...args) {\n let guards = stack(filter(guardType, args).map(t => t.fn), truthy, callBoth);\n let reducers = stack(filter(reduceType, args).map(t => t.fn), identity, callForward);\n return create(this, {\n from: valueEnumerable(from),\n to: valueEnumerable(to),\n guards: valueEnumerable(guards),\n reducers: valueEnumerable(reducers)\n });\n}\n\nlet transitionType = {};\nlet immediateType = {};\nlet transition = makeTransition.bind(transitionType);\nlet immediate = makeTransition.bind(immediateType, null);\n\nfunction enterImmediate(machine, service, event) {\n return transitionTo(service, machine, event, this.immediates) || machine;\n}\n\nfunction transitionsToMap(transitions) {\n let m = new Map();\n for(let t of transitions) {\n if(!m.has(t.from)) m.set(t.from, []);\n m.get(t.from).push(t);\n }\n return m;\n}\n\nlet stateType = { enter: identity };\nfunction state(...args) {\n let transitions = filter(transitionType, args);\n let immediates = filter(immediateType, args);\n let desc = {\n final: valueEnumerable(args.length === 0),\n transitions: valueEnumerable(transitionsToMap(transitions))\n };\n if(immediates.length) {\n desc.immediates = valueEnumerable(immediates);\n desc.enter = valueEnumerable(enterImmediate);\n }\n return create(stateType, desc);\n}\n\nlet invokeFnType = {\n enter(machine2, service, event) {\n let rn = this.fn.call(service, service.context, event);\n if(machine.isPrototypeOf(rn))\n return create(invokeMachineType, {\n machine: valueEnumerable(rn),\n transitions: valueEnumerable(this.transitions)\n }).enter(machine2, service, event)\n rn.then(data => service.send({ type: 'done', data }))\n .catch(error => service.send({ type: 'error', error }));\n return machine2;\n }\n};\nlet invokeMachineType = {\n enter(machine, service, event) {\n service.child = interpret(this.machine, s => {\n service.onChange(s);\n if(service.child == s && s.machine.state.value.final) {\n delete service.child;\n service.send({ type: 'done', data: s.context });\n }\n }, service.context, event);\n if(service.child.machine.state.value.final) {\n let data = service.child.context;\n delete service.child;\n return transitionTo(service, machine, { type: 'done', data }, this.transitions.get('done'));\n }\n return machine;\n }\n};\nfunction invoke(fn, ...transitions) {\n let t = valueEnumerable(transitionsToMap(transitions));\n return machine.isPrototypeOf(fn) ?\n create(invokeMachineType, {\n machine: valueEnumerable(fn),\n transitions: t\n }) :\n create(invokeFnType, {\n fn: valueEnumerable(fn),\n transitions: t\n });\n}\n\nlet machine = {\n get state() {\n return {\n name: this.current,\n value: this.states[this.current]\n };\n }\n};\n\nfunction createMachine(current, states, contextFn = empty) {\n if(typeof current !== 'string') {\n contextFn = states || empty;\n states = current;\n current = Object.keys(states)[0];\n }\n if(d._create) d._create(current, states);\n return create(machine, {\n context: valueEnumerable(contextFn),\n current: valueEnumerable(current),\n states: valueEnumerable(states)\n });\n}\n\nfunction transitionTo(service, machine, fromEvent, candidates) {\n let { context } = service;\n for(let { to, guards, reducers } of candidates) { \n if(guards(context, fromEvent)) {\n service.context = reducers.call(service, context, fromEvent);\n\n let original = machine.original || machine;\n let newMachine = create(original, {\n current: valueEnumerable(to),\n original: { value: original }\n });\n\n if (d._onEnter) d._onEnter(machine, to, service.context, context, fromEvent);\n let state = newMachine.state.value;\n return state.enter(newMachine, service, fromEvent);\n }\n }\n}\n\nfunction send(service, event) {\n let eventName = event.type || event;\n let { machine } = service;\n let { value: state, name: currentStateName } = machine.state;\n \n if(state.transitions.has(eventName)) {\n return transitionTo(service, machine, event, state.transitions.get(eventName)) || machine;\n } else {\n if(d._send) d._send(eventName, currentStateName);\n }\n return machine;\n}\n\nlet service = {\n send(event) {\n this.machine = send(this, event);\n \n // TODO detect change\n this.onChange(this);\n }\n};\n\nfunction interpret(machine, onChange, initialContext, event) {\n let s = Object.create(service, {\n machine: valueEnumerableWritable(machine),\n context: valueEnumerableWritable(machine.context(initialContext, event)),\n onChange: valueEnumerable(onChange)\n });\n s.send = s.send.bind(s);\n s.machine = s.machine.state.value.enter(s.machine, s, event);\n return s;\n}\n\nexports.action = action;\nexports.createMachine = createMachine;\nexports.d = d;\nexports.guard = guard;\nexports.immediate = immediate;\nexports.interpret = interpret;\nexports.invoke = invoke;\nexports.reduce = reduce;\nexports.state = state;\nexports.transition = transition;\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { decode, encode } from \"@msgpack/msgpack\";\nimport {\n ContextFunction,\n InterpretOnChangeFunction,\n Service,\n createMachine,\n guard,\n immediate,\n interpret,\n reduce,\n state,\n transition,\n} from \"robot3\";\nimport { TOKEN_EXPIRATION_SECONDS, getTemporaryAuthToken } from \"./auth\";\nimport { RequiredConfig } from \"./config\";\nimport { ApiError } from \"./response\";\nimport { isBrowser } from \"./runtime\";\nimport { ensureEndpointIdFormat, isReact, throttle } from \"./utils\";\n\n// Define the context\ninterface Context {\n token?: string;\n enqueuedMessage?: any;\n websocket?: WebSocket;\n error?: Error;\n}\n\nconst initialState: ContextFunction<Context> = () => ({\n enqueuedMessage: undefined,\n});\n\ntype SendEvent = { type: \"send\"; message: any };\ntype AuthenticatedEvent = { type: \"authenticated\"; token: string };\ntype InitiateAuthEvent = { type: \"initiateAuth\" };\ntype UnauthorizedEvent = { type: \"unauthorized\"; error: Error };\ntype ConnectedEvent = { type: \"connected\"; websocket: WebSocket };\ntype ConnectionClosedEvent = {\n type: \"connectionClosed\";\n code: number;\n reason: string;\n};\n\ntype Event =\n | SendEvent\n | AuthenticatedEvent\n | InitiateAuthEvent\n | UnauthorizedEvent\n | ConnectedEvent\n | ConnectionClosedEvent;\n\nfunction hasToken(context: Context): boolean {\n return context.token !== undefined;\n}\n\nfunction noToken(context: Context): boolean {\n return !hasToken(context);\n}\n\nfunction enqueueMessage(context: Context, event: SendEvent): Context {\n return {\n ...context,\n enqueuedMessage: event.message,\n };\n}\n\nfunction closeConnection(context: Context): Context {\n if (context.websocket && context.websocket.readyState === WebSocket.OPEN) {\n context.websocket.close();\n }\n return {\n ...context,\n websocket: undefined,\n };\n}\n\nfunction sendMessage(context: Context, event: SendEvent): Context {\n if (context.websocket && context.websocket.readyState === WebSocket.OPEN) {\n if (event.message instanceof Uint8Array) {\n context.websocket.send(event.message);\n } else {\n context.websocket.send(encode(event.message));\n }\n\n return {\n ...context,\n enqueuedMessage: undefined,\n };\n }\n return {\n ...context,\n enqueuedMessage: event.message,\n };\n}\n\nfunction expireToken(context: Context): Context {\n return {\n ...context,\n token: undefined,\n };\n}\n\nfunction setToken(context: Context, event: AuthenticatedEvent): Context {\n return {\n ...context,\n token: event.token,\n };\n}\n\nfunction connectionEstablished(\n context: Context,\n event: ConnectedEvent,\n): Context {\n return {\n ...context,\n websocket: event.websocket,\n };\n}\n\n// State machine\nconst connectionStateMachine = createMachine(\n \"idle\",\n {\n idle: state(\n transition(\"send\", \"connecting\", reduce(enqueueMessage)),\n transition(\"expireToken\", \"idle\", reduce(expireToken)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n connecting: state(\n transition(\"connecting\", \"connecting\"),\n transition(\"connected\", \"active\", reduce(connectionEstablished)),\n transition(\"connectionClosed\", \"idle\", reduce(closeConnection)),\n transition(\"send\", \"connecting\", reduce(enqueueMessage)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n immediate(\"authRequired\", guard(noToken)),\n ),\n authRequired: state(\n transition(\"initiateAuth\", \"authInProgress\"),\n transition(\"send\", \"authRequired\", reduce(enqueueMessage)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n authInProgress: state(\n transition(\"authenticated\", \"connecting\", reduce(setToken)),\n transition(\n \"unauthorized\",\n \"idle\",\n reduce(expireToken),\n reduce(closeConnection),\n ),\n transition(\"send\", \"authInProgress\", reduce(enqueueMessage)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n active: state(\n transition(\"send\", \"active\", reduce(sendMessage)),\n transition(\"unauthorized\", \"idle\", reduce(expireToken)),\n transition(\"connectionClosed\", \"idle\", reduce(closeConnection)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n failed: state(\n transition(\"send\", \"failed\"),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n },\n initialState,\n);\n\ntype WithRequestId = {\n request_id: string;\n};\n\n/**\n * A connection object that allows you to `send` request payloads to a\n * realtime endpoint.\n */\nexport interface RealtimeConnection<Input> {\n send(input: Input & Partial<WithRequestId>): void;\n\n close(): void;\n}\n\n/**\n * Options for connecting to the realtime endpoint.\n */\nexport interface RealtimeConnectionHandler<Output> {\n /**\n * The connection key. This is used to reuse the same connection\n * across multiple calls to `connect`. This is particularly useful in\n * contexts where the connection is established as part of a component\n * lifecycle (e.g. React) and the component is re-rendered multiple times.\n */\n connectionKey?: string;\n\n /**\n * If `true`, the connection will only be established on the client side.\n * This is useful for frameworks that reuse code for both server-side\n * rendering and client-side rendering (e.g. Next.js).\n *\n * This is set to `true` by default when running on React in the server.\n * Otherwise, it is set to `false`.\n *\n * Note that more SSR frameworks might be automatically detected\n * in the future. In the meantime, you can set this to `true` when needed.\n */\n clientOnly?: boolean;\n\n /**\n * The throtle duration in milliseconds. This is used to throtle the\n * calls to the `send` function. Realtime apps usually react to user\n * input, which can be very frequent (e.g. fast typing or mouse/drag movements).\n *\n * The default value is `128` milliseconds.\n */\n throttleInterval?: number;\n\n /**\n * Configures the maximum amount of frames to store in memory before starting to drop\n * old ones for in favor of the newer ones. It must be between `1` and `60`.\n *\n * The recommended is `2`. The default is `undefined` so it can be determined\n * by the app (normally is set to the recommended setting).\n */\n maxBuffering?: number;\n\n /**\n * Callback function that is called when a result is received.\n * @param result - The result of the request.\n */\n onResult(result: Output & WithRequestId): void;\n\n /**\n * Callback function that is called when an error occurs.\n * @param error - The error that occurred.\n */\n onError?(error: ApiError<any>): void;\n}\n\nexport interface RealtimeClient {\n /**\n * Connect to the realtime endpoint. The default implementation uses\n * WebSockets to connect to fal function endpoints that support WSS.\n *\n * @param app the app alias or identifier.\n * @param handler the connection handler.\n */\n connect<Input = any, Output = any>(\n app: string,\n handler: RealtimeConnectionHandler<Output>,\n ): RealtimeConnection<Input>;\n}\n\ntype RealtimeUrlParams = {\n token: string;\n maxBuffering?: number;\n};\n\nfunction buildRealtimeUrl(\n app: string,\n { token, maxBuffering }: RealtimeUrlParams,\n): string {\n if (maxBuffering !== undefined && (maxBuffering < 1 || maxBuffering > 60)) {\n throw new Error(\"The `maxBuffering` must be between 1 and 60 (inclusive)\");\n }\n const queryParams = new URLSearchParams({\n fal_jwt_token: token,\n });\n if (maxBuffering !== undefined) {\n queryParams.set(\"max_buffering\", maxBuffering.toFixed(0));\n }\n const appId = ensureEndpointIdFormat(app);\n return `wss://fal.run/${appId}/realtime?${queryParams.toString()}`;\n}\n\nconst DEFAULT_THROTTLE_INTERVAL = 128;\n\nfunction isUnauthorizedError(message: any): boolean {\n // TODO we need better protocol definition with error codes\n return message[\"status\"] === \"error\" && message[\"error\"] === \"Unauthorized\";\n}\n\n/**\n * See https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1\n */\nconst WebSocketErrorCodes = {\n NORMAL_CLOSURE: 1000,\n GOING_AWAY: 1001,\n};\n\ntype ConnectionStateMachine = Service<typeof connectionStateMachine> & {\n throttledSend: (\n event: Event,\n payload?: any,\n ) => void | Promise<void> | undefined;\n};\n\ntype ConnectionOnChange = InterpretOnChangeFunction<\n typeof connectionStateMachine\n>;\n\ntype RealtimeConnectionCallback = Pick<\n RealtimeConnectionHandler<any>,\n \"onResult\" | \"onError\"\n>;\n\nconst connectionCache = new Map<string, ConnectionStateMachine>();\nconst connectionCallbacks = new Map<string, RealtimeConnectionCallback>();\nfunction reuseInterpreter(\n key: string,\n throttleInterval: number,\n onChange: ConnectionOnChange,\n) {\n if (!connectionCache.has(key)) {\n const machine = interpret(connectionStateMachine, onChange);\n connectionCache.set(key, {\n ...machine,\n throttledSend:\n throttleInterval > 0\n ? throttle(machine.send, throttleInterval, true)\n : machine.send,\n });\n }\n return connectionCache.get(key) as ConnectionStateMachine;\n}\n\nconst noop = () => {\n /* No-op */\n};\n\n/**\n * A no-op connection that does not send any message.\n * Useful on the frameworks that reuse code for both ssr and csr (e.g. Next)\n * so the call when doing ssr has no side-effects.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst NoOpConnection: RealtimeConnection<any> = {\n send: noop,\n close: noop,\n};\n\nfunction isSuccessfulResult(data: any): boolean {\n return (\n data.status !== \"error\" &&\n data.type !== \"x-fal-message\" &&\n !isFalErrorResult(data)\n );\n}\n\ntype FalErrorResult = {\n type: \"x-fal-error\";\n error: string;\n reason: string;\n};\n\nfunction isFalErrorResult(data: any): data is FalErrorResult {\n return data.type === \"x-fal-error\";\n}\n\ntype RealtimeClientDependencies = {\n config: RequiredConfig;\n};\n\nexport function createRealtimeClient({\n config,\n}: RealtimeClientDependencies): RealtimeClient {\n return {\n connect<Input, Output>(\n app: string,\n handler: RealtimeConnectionHandler<Output>,\n ): RealtimeConnection<Input> {\n const {\n // if running on React in the server, set clientOnly to true by default\n clientOnly = isReact() && !isBrowser(),\n connectionKey = crypto.randomUUID(),\n maxBuffering,\n throttleInterval = DEFAULT_THROTTLE_INTERVAL,\n } = handler;\n if (clientOnly && !isBrowser()) {\n return NoOpConnection;\n }\n\n let previousState: string | undefined;\n\n // Although the state machine is cached so we don't open multiple connections,\n // we still need to update the callbacks so we can call the correct references\n // when the state machine is reused. This is needed because the callbacks\n // are passed as part of the handler object, which can be different across\n // different calls to `connect`.\n connectionCallbacks.set(connectionKey, {\n onError: handler.onError,\n onResult: handler.onResult,\n });\n const getCallbacks = () =>\n connectionCallbacks.get(connectionKey) as RealtimeConnectionCallback;\n const stateMachine = reuseInterpreter(\n connectionKey,\n throttleInterval,\n ({ context, machine, send }) => {\n const { enqueuedMessage, token } = context;\n if (machine.current === \"active\" && enqueuedMessage) {\n send({ type: \"send\", message: enqueuedMessage });\n }\n if (\n machine.current === \"authRequired\" &&\n token === undefined &&\n previousState !== machine.current\n ) {\n send({ type: \"initiateAuth\" });\n getTemporaryAuthToken(app, config)\n .then((token) => {\n send({ type: \"authenticated\", token });\n const tokenExpirationTimeout = Math.round(\n TOKEN_EXPIRATION_SECONDS * 0.9 * 1000,\n );\n setTimeout(() => {\n send({ type: \"expireToken\" });\n }, tokenExpirationTimeout);\n })\n .catch((error) => {\n send({ type: \"unauthorized\", error });\n });\n }\n if (\n machine.current === \"connecting\" &&\n previousState !== machine.current &&\n token !== undefined\n ) {\n const ws = new WebSocket(\n buildRealtimeUrl(app, { token, maxBuffering }),\n );\n ws.onopen = () => {\n send({ type: \"connected\", websocket: ws });\n };\n ws.onclose = (event) => {\n if (event.code !== WebSocketErrorCodes.NORMAL_CLOSURE) {\n const { onError = noop } = getCallbacks();\n onError(\n new ApiError({\n message: `Error closing the connection: ${event.reason}`,\n status: event.code,\n }),\n );\n }\n send({ type: \"connectionClosed\", code: event.code });\n };\n ws.onerror = (event) => {\n // TODO specify error protocol for identified errors\n const { onError = noop } = getCallbacks();\n onError(new ApiError({ message: \"Unknown error\", status: 500 }));\n };\n ws.onmessage = (event) => {\n const { onResult } = getCallbacks();\n\n // Handle binary messages as msgpack messages\n if (event.data instanceof ArrayBuffer) {\n const result = decode(new Uint8Array(event.data));\n onResult(result);\n return;\n }\n if (event.data instanceof Uint8Array) {\n const result = decode(event.data);\n onResult(result);\n return;\n }\n if (event.data instanceof Blob) {\n event.data.arrayBuffer().then((buffer) => {\n const result = decode(new Uint8Array(buffer));\n onResult(result);\n });\n return;\n }\n\n // Otherwise handle strings as plain JSON messages\n const data = JSON.parse(event.data);\n\n // Drop messages that are not related to the actual result.\n // In the future, we might want to handle other types of messages.\n // TODO: specify the fal ws protocol format\n if (isUnauthorizedError(data)) {\n send({\n type: \"unauthorized\",\n error: new Error(\"Unauthorized\"),\n });\n return;\n }\n if (isSuccessfulResult(data)) {\n onResult(data);\n return;\n }\n if (isFalErrorResult(data)) {\n if (data.error === \"TIMEOUT\") {\n // Timeout error messages just indicate that the connection hasn't\n // received an incoming message for a while. We don't need to\n // handle them as errors.\n return;\n }\n const { onError = noop } = getCallbacks();\n onError(\n new ApiError({\n message: `${data.error}: ${data.reason}`,\n // TODO better error status code\n status: 400,\n body: data,\n }),\n );\n return;\n }\n };\n }\n previousState = machine.current;\n },\n );\n\n const send = (input: Input & Partial<WithRequestId>) => {\n // Use throttled send to avoid sending too many messages\n stateMachine.throttledSend({\n type: \"send\",\n message: input,\n });\n };\n\n const close = () => {\n stateMachine.send({ type: \"close\" });\n };\n\n return {\n send,\n close,\n };\n },\n };\n}\n", "import { getRestApiUrl, RequiredConfig } from \"./config\";\nimport { dispatchRequest } from \"./request\";\nimport { isPlainObject } from \"./utils\";\n/**\n * File support for the client. This interface establishes the contract for\n * uploading files to the server and transforming the input to replace file\n * objects with URLs.\n */\nexport interface StorageClient {\n /**\n * Upload a file to the server. Returns the URL of the uploaded file.\n * @param file the file to upload\n * @param options optional parameters, such as custom file name\n * @returns the URL of the uploaded file\n */\n upload: (file: Blob) => Promise<string>;\n\n /**\n * Transform the input to replace file objects with URLs. This is used\n * to transform the input before sending it to the server and ensures\n * that the server receives URLs instead of file objects.\n *\n * @param input the input to transform.\n * @returns the transformed input.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n transformInput: (input: Record<string, any>) => Promise<Record<string, any>>;\n}\n\ntype InitiateUploadResult = {\n file_url: string;\n upload_url: string;\n};\n\ntype InitiateUploadData = {\n file_name: string;\n content_type: string | null;\n};\n\n/**\n * Get the file extension from the content type. This is used to generate\n * a file name if the file name is not provided.\n *\n * @param contentType the content type of the file.\n * @returns the file extension or `bin` if the content type is not recognized.\n */\nfunction getExtensionFromContentType(contentType: string): string {\n const [_, fileType] = contentType.split(\"/\");\n return fileType.split(/[-;]/)[0] ?? \"bin\";\n}\n\n/**\n * Initiate the upload of a file to the server. This returns the URL to upload\n * the file to and the URL of the file once it is uploaded.\n */\nasync function initiateUpload(\n file: Blob,\n config: RequiredConfig,\n contentType: string,\n): Promise<InitiateUploadResult> {\n const filename =\n file.name || `${Date.now()}.${getExtensionFromContentType(contentType)}`;\n\n return await dispatchRequest<InitiateUploadData, InitiateUploadResult>({\n method: \"POST\",\n // NOTE: We want to test V3 without making it the default at the API level\n targetUrl: `${getRestApiUrl()}/storage/upload/initiate?storage_type=fal-cdn-v3`,\n input: {\n content_type: contentType,\n file_name: filename,\n },\n config,\n });\n}\n\n/**\n * Initiate the multipart upload of a file to the server. This returns the URL to upload\n * the file to and the URL of the file once it is uploaded.\n */\nasync function initiateMultipartUpload(\n file: Blob,\n config: RequiredConfig,\n contentType: string,\n): Promise<InitiateUploadResult> {\n const filename =\n file.name || `${Date.now()}.${getExtensionFromContentType(contentType)}`;\n\n return await dispatchRequest<InitiateUploadData, InitiateUploadResult>({\n method: \"POST\",\n targetUrl: `${getRestApiUrl()}/storage/upload/initiate-multipart?storage_type=fal-cdn-v3`,\n input: {\n content_type: contentType,\n file_name: filename,\n },\n config,\n });\n}\n\ntype MultipartObject = {\n partNumber: number;\n etag: string;\n};\n\nasync function partUploadRetries(\n uploadUrl: string,\n chunk: Blob,\n config: RequiredConfig,\n tries = 3,\n): Promise<MultipartObject> {\n if (tries === 0) {\n throw new Error(\"Part upload failed, retries exhausted\");\n }\n\n const { fetch, responseHandler } = config;\n\n try {\n const response = await fetch(uploadUrl, {\n method: \"PUT\",\n body: chunk,\n });\n\n return (await responseHandler(response)) as MultipartObject;\n } catch (error) {\n return await partUploadRetries(uploadUrl, chunk, config, tries - 1);\n }\n}\n\nasync function multipartUpload(\n file: Blob,\n config: RequiredConfig,\n): Promise<string> {\n const { fetch, responseHandler } = config;\n const contentType = file.type || \"application/octet-stream\";\n const { upload_url: uploadUrl, file_url: url } =\n await initiateMultipartUpload(file, config, contentType);\n\n // Break the file into 10MB chunks\n const chunkSize = 10 * 1024 * 1024;\n const chunks = Math.ceil(file.size / chunkSize);\n\n const parsedUrl = new URL(uploadUrl);\n\n const responses: MultipartObject[] = [];\n\n for (let i = 0; i < chunks; i++) {\n const start = i * chunkSize;\n const end = Math.min(start + chunkSize, file.size);\n\n const chunk = file.slice(start, end);\n\n const partNumber = i + 1;\n // {uploadUrl}/{part_number}?uploadUrlParams=...\n const partUploadUrl = `${parsedUrl.origin}${parsedUrl.pathname}/${partNumber}${parsedUrl.search}`;\n\n responses.push(await partUploadRetries(partUploadUrl, chunk, config));\n }\n\n // Complete the upload\n const completeUrl = `${parsedUrl.origin}${parsedUrl.pathname}/complete${parsedUrl.search}`;\n const response = await fetch(completeUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n parts: responses.map((mpart) => ({\n partNumber: mpart.partNumber,\n etag: mpart.etag,\n })),\n }),\n });\n await responseHandler(response);\n\n return url;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype KeyValuePair = [string, any];\n\ntype StorageClientDependencies = {\n config: RequiredConfig;\n};\n\nexport function createStorageClient({\n config,\n}: StorageClientDependencies): StorageClient {\n const ref: StorageClient = {\n upload: async (file: Blob) => {\n // Check for 90+ MB file size to do multipart upload\n if (file.size > 90 * 1024 * 1024) {\n return await multipartUpload(file, config);\n }\n\n const contentType = file.type || \"application/octet-stream\";\n\n const { fetch, responseHandler } = config;\n const { upload_url: uploadUrl, file_url: url } = await initiateUpload(\n file,\n config,\n contentType,\n );\n const response = await fetch(uploadUrl, {\n method: \"PUT\",\n body: file,\n headers: {\n \"Content-Type\": file.type || \"application/octet-stream\",\n },\n });\n await responseHandler(response);\n return url;\n },\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n transformInput: async (input: any): Promise<any> => {\n if (Array.isArray(input)) {\n return Promise.all(input.map((item) => ref.transformInput(item)));\n } else if (input instanceof Blob) {\n return await ref.upload(input);\n } else if (isPlainObject(input)) {\n const inputObject = input as Record<string, any>;\n const promises = Object.entries(inputObject).map(\n async ([key, value]): Promise<KeyValuePair> => {\n return [key, await ref.transformInput(value)];\n },\n );\n const results = await Promise.all(promises);\n return Object.fromEntries(results);\n }\n // Return the input as is if it's neither an object nor a file/blob/data URI\n return input;\n },\n };\n return ref;\n}\n", "import { Config, createConfig } from \"./config\";\nimport { createQueueClient, QueueClient, QueueSubscribeOptions } from \"./queue\";\nimport { createRealtimeClient, RealtimeClient } from \"./realtime\";\nimport { buildUrl, dispatchRequest } from \"./request\";\nimport { resultResponseHandler } from \"./response\";\nimport { createStorageClient, StorageClient } from \"./storage\";\nimport { createStreamingClient, StreamingClient } from \"./streaming\";\nimport { EndpointType, InputType, OutputType } from \"./types/client\";\nimport { Result, RunOptions } from \"./types/common\";\n\n/**\n * The main client type, it provides access to simple API model usage,\n * as well as access to the `queue` and `storage` APIs.\n *\n * @see createFalClient\n */\nexport interface FalClient {\n /**\n * The queue client to interact with the queue API.\n */\n readonly queue: QueueClient;\n\n /**\n * The realtime client to interact with the realtime API\n * and receive updates in real-time.\n * @see #RealtimeClient\n * @see #RealtimeClient.connect\n */\n readonly realtime: RealtimeClient;\n\n /**\n * The storage client to interact with the storage API.\n */\n readonly storage: StorageClient;\n\n /**\n * The streaming client to interact with the streaming API.\n * @see #stream\n */\n readonly streaming: StreamingClient;\n\n /**\n * Runs a fal endpoint identified by its `endpointId`.\n *\n * @param endpointId The endpoint id, e.g. `fal-ai/fast-sdxl`.\n * @param options The request options, including the input payload.\n * @returns A promise that resolves to the result of the request once it's completed.\n *\n * @note\n * We **do not recommend** this use for most use cases as it will block the client\n * until the response is received. Moreover, if the connection is closed before\n * the response is received, the request will be lost. Instead, we recommend\n * using the `subscribe` method for most use cases.\n */\n run<Id extends EndpointType>(\n endpointId: Id,\n options: RunOptions<InputType<Id>>,\n ): Promise<Result<OutputType<Id>>>;\n\n /**\n * Subscribes to updates for a specific request in the queue.\n *\n * @param endpointId - The ID of the API endpoint.\n * @param options - Options to configure how the request is run and how updates are received.\n * @returns A promise that resolves to the result of the request once it's completed.\n */\n subscribe<Id extends EndpointType>(\n endpointId: Id,\n options: RunOptions<InputType<Id>> & QueueSubscribeOptions,\n ): Promise<Result<OutputType<Id>>>;\n\n /**\n * Calls a fal app that supports streaming and provides a streaming-capable\n * object as a result, that can be used to get partial results through either\n * `AsyncIterator` or through an event listener.\n *\n * @param endpointId the endpoint id, e.g. `fal-ai/llavav15-13b`.\n * @param options the request options, including the input payload.\n * @returns the `FalStream` instance.\n */\n stream: StreamingClient[\"stream\"];\n}\n\n/**\n * Creates a new reference of the `FalClient`.\n * @param userConfig Optional configuration to override the default settings.\n * @returns a new instance of the `FalClient`.\n */\nexport function createFalClient(userConfig: Config = {}): FalClient {\n const config = createConfig(userConfig);\n const storage = createStorageClient({ config });\n const queue = createQueueClient({ config, storage });\n const streaming = createStreamingClient({ config, storage });\n const realtime = createRealtimeClient({ config });\n return {\n queue,\n realtime,\n storage,\n streaming,\n stream: streaming.stream,\n async run<Id extends EndpointType>(\n endpointId: Id,\n options: RunOptions<InputType<Id>> = {},\n ): Promise<Result<OutputType<Id>>> {\n const input = options.input\n ? await storage.transformInput(options.input)\n : undefined;\n return dispatchRequest<InputType<Id>, Result<OutputType<Id>>>({\n method: options.method,\n targetUrl: buildUrl(endpointId, options),\n input: input as InputType<Id>,\n config: {\n ...config,\n responseHandler: resultResponseHandler,\n },\n options: {\n signal: options.abortSignal,\n },\n });\n },\n subscribe: async (endpointId, options) => {\n const { request_id: requestId } = await queue.submit(endpointId, options);\n if (options.onEnqueue) {\n options.onEnqueue(requestId);\n }\n await queue.subscribeToStatus(endpointId, { requestId, ...options });\n return queue.result(endpointId, { requestId });\n },\n };\n}\n", "/**\n * Represents an API result, containing the data,\n * the request ID and any other relevant information.\n */\nexport type Result<T> = {\n data: T;\n requestId: string;\n};\n\n/**\n * The function input and other configuration when running\n * the function, such as the HTTP method to use.\n */\nexport type RunOptions<Input> = {\n /**\n * The function input. It will be submitted either as query params\n * or the body payload, depending on the `method`.\n */\n readonly input?: Input;\n\n /**\n * The HTTP method, defaults to `post`;\n */\n readonly method?: \"get\" | \"post\" | \"put\" | \"delete\" | string;\n\n /**\n * The abort signal to cancel the request.\n */\n readonly abortSignal?: AbortSignal;\n};\n\nexport type UrlOptions = {\n /**\n * If `true`, the function will use the queue to run the function\n * asynchronously and return the result in a separate call. This\n * influences how the URL is built.\n */\n readonly subdomain?: string;\n\n /**\n * The query parameters to include in the URL.\n */\n readonly query?: Record<string, string>;\n\n /**\n * The path to append to the function URL.\n */\n path?: string;\n};\n\nexport type RequestLog = {\n message: string;\n level: \"STDERR\" | \"STDOUT\" | \"ERROR\" | \"INFO\" | \"WARN\" | \"DEBUG\";\n source: \"USER\";\n timestamp: string; // Using string to represent date-time format, but you could also use 'Date' type if you're going to construct Date objects.\n};\n\nexport type Metrics = {\n inference_time: number | null;\n};\n\ninterface BaseQueueStatus {\n status: \"IN_QUEUE\" | \"IN_PROGRESS\" | \"COMPLETED\";\n request_id: string;\n}\n\nexport interface InQueueQueueStatus extends BaseQueueStatus {\n status: \"IN_QUEUE\";\n queue_position: number;\n response_url: string;\n}\n\nexport interface InProgressQueueStatus extends BaseQueueStatus {\n status: \"IN_PROGRESS\";\n response_url: string;\n logs: RequestLog[];\n}\n\nexport interface CompletedQueueStatus extends BaseQueueStatus {\n status: \"COMPLETED\";\n response_url: string;\n logs: RequestLog[];\n metrics?: Metrics;\n}\n\nexport type QueueStatus =\n | InProgressQueueStatus\n | CompletedQueueStatus\n | InQueueQueueStatus;\n\nexport function isQueueStatus(obj: any): obj is QueueStatus {\n return obj && obj.status && obj.response_url;\n}\n\nexport function isCompletedQueueStatus(obj: any): obj is CompletedQueueStatus {\n return isQueueStatus(obj) && obj.status === \"COMPLETED\";\n}\n\nexport type ValidationErrorInfo = {\n msg: string;\n loc: Array<string | number>;\n type: string;\n};\n\n/**\n * Represents the response from a WebHook request.\n * This is a union type that varies based on the `status` property.\n *\n * @template Payload - The type of the payload in the response. It defaults to `any`,\n * allowing for flexibility in specifying the structure of the payload.\n */\nexport type WebHookResponse<Payload = any> =\n | {\n /** Indicates a successful response. */\n status: \"OK\";\n /** The payload of the response, structure determined by the Payload type. */\n payload: Payload;\n /** Error is never present in a successful response. */\n error: never;\n /** The unique identifier for the request. */\n request_id: string;\n }\n | {\n /** Indicates an unsuccessful response. */\n status: \"ERROR\";\n /** The payload of the response, structure determined by the Payload type. */\n payload: Payload;\n /** Description of the error that occurred. */\n error: string;\n /** The unique identifier for the request. */\n request_id: string;\n };\n", "import { createFalClient, type FalClient } from \"./client\";\nimport { Config } from \"./config\";\nimport { StreamOptions } from \"./streaming\";\nimport { EndpointType, InputType } from \"./types/client\";\nimport { RunOptions } from \"./types/common\";\n\nexport { createFalClient, type FalClient } from \"./client\";\nexport { withMiddleware, withProxy } from \"./middleware\";\nexport type { RequestMiddleware } from \"./middleware\";\nexport type { QueueClient } from \"./queue\";\nexport type { RealtimeClient } from \"./realtime\";\nexport { ApiError, ValidationError } from \"./response\";\nexport type { ResponseHandler } from \"./response\";\nexport type { StorageClient } from \"./storage\";\nexport type { FalStream, StreamingClient } from \"./streaming\";\nexport * from \"./types/common\";\nexport type {\n QueueStatus,\n ValidationErrorInfo,\n WebHookResponse,\n} from \"./types/common\";\nexport { parseEndpointId } from \"./utils\";\n\ntype SingletonFalClient = {\n config(config: Config): void;\n} & FalClient;\n\n/**\n * Creates a singleton instance of the client. This is useful as a compatibility\n * layer for existing code that uses the clients version prior to 1.0.0.\n */\nexport const fal: SingletonFalClient = (function createSingletonFalClient() {\n let currentInstance: FalClient = createFalClient();\n return {\n config(config: Config) {\n currentInstance = createFalClient(config);\n },\n get queue() {\n return currentInstance.queue;\n },\n get realtime() {\n return currentInstance.realtime;\n },\n get storage() {\n return currentInstance.storage;\n },\n get streaming() {\n return currentInstance.streaming;\n },\n run<Id extends EndpointType>(id: Id, options: RunOptions<InputType<Id>>) {\n return currentInstance.run<Id>(id, options);\n },\n subscribe<Id extends EndpointType>(\n endpointId: Id,\n options: RunOptions<InputType<Id>>,\n ) {\n return currentInstance.subscribe<Id>(endpointId, options);\n },\n stream<Id extends EndpointType>(\n endpointId: Id,\n options: StreamOptions<InputType<Id>>,\n ) {\n return currentInstance.stream<Id>(endpointId, options);\n },\n } satisfies SingletonFalClient;\n})();\n", "export default `\n<svg>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratioFree\"\n >\n <path d=\"M7 6C6.44772 6 6 6.44772 6 7V9.22222H4V7C4 5.34315 5.34315 4 7 4H9.22222V6H7Z\" fill=\"currentColor\"/>\n <path d=\"M17 6H14.7778V4H17C18.6569 4 20 5.34315 20 7V9.22222H18V7C18 6.44772 17.5523 6 17 6Z\" fill=\"currentColor\"/>\n <path d=\"M6 14.7778V17C6 17.5523 6.44772 18 7 18H9.22222V20H7C5.34315 20 4 18.6569 4 17V14.7778H6Z\" fill=\"currentColor\"/>\n <path d=\"M18 17V14.7778H20V17C20 18.6569 18.6569 20 17 20H14.7778V18H17C17.5523 18 18 17.5523 18 17Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio4by3\"\n >\n <path d=\"M6.5 13H8V15H10V16.5H6.5V13Z\" fill=\"currentColor\"/>\n <path d=\"M14 9V7.5H17.5V11H16V9H14Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M6 4C4.34315 4 3 5.34315 3 7V17C3 18.6569 4.34315 20 6 20H18C19.6569 20 21 18.6569 21 17V7C21 5.34315 19.6569 4 18 4H6ZM5 7C5 6.44772 5.44772 6 6 6H18C18.5523 6 19 6.44772 19 7V17C19 17.5523 18.5523 18 18 18H6C5.44772 18 5 17.5523 5 17V7Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio16by9\"\n >\n <path d=\"M4.5 13H6V15H8V16.5H4.5V13Z\" fill=\"currentColor\"/>\n <path d=\"M16 9V7.5H19.5V11H18V9H16Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M4 4C2.34315 4 1 5.34315 1 7V17C1 18.6569 2.34315 20 4 20H20C21.6569 20 23 18.6569 23 17V7C23 5.34315 21.6569 4 20 4H4ZM3 7C3 6.44772 3.44772 6 4 6H20C20.5523 6 21 6.44772 21 7V17C21 17.5523 20.5523 18 20 18H4C3.44772 18 3 17.5523 3 17V7Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio9by16\"\n >\n <path d=\"M7.5 16H9V18H11V19.5H7.5V16Z\" fill=\"currentColor\"/>\n <path d=\"M13 6V4.5H16.5V8H15V6H13Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M4 20C4 21.6569 5.34315 23 7 23H17C18.6569 23 20 21.6569 20 20V4C20 2.34315 18.6569 1 17 1H7C5.34315 1 4 2.34315 4 4V20ZM7 21C6.44772 21 6 20.5523 6 20V4C6 3.44772 6.44772 3 7 3H17C17.5523 3 18 3.44772 18 4V20C18 20.5523 17.5523 21 17 21H7Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio3by4\"\n >\n <path d=\"M11 17.5V16H9V14H7.5V17.5H11Z\" fill=\"currentColor\"/>\n <path d=\"M15 10H16.5V6.5H13V8H15V10Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M20 18C20 19.6569 18.6569 21 17 21H7C5.34315 21 4 19.6569 4 18V6C4 4.34315 5.34315 3 7 3H17C18.6569 3 20 4.34315 20 6V18ZM17 19C17.5523 19 18 18.5523 18 18V6C18 5.44772 17.5523 5 17 5H7C6.44771 5 6 5.44771 6 6V18C6 18.5523 6.44772 19 7 19H17Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio1by1\"\n >\n <path d=\"M17.4142 8.00009L16 6.58587L14.2929 8.29298L15.7071 9.70719L17.4142 8.00009Z\" fill=\"currentColor\"/>\n <path d=\"M13.0404 12.3739L15.0404 10.3739L13.6262 8.95965L11.6262 10.9596L13.0404 12.3739Z\" fill=\"currentColor\"/>\n <path d=\"M10.3737 15.0405L12.3737 13.0405L10.9595 11.6263L8.95953 13.6263L10.3737 15.0405Z\" fill=\"currentColor\"/>\n <path d=\"M9.70708 15.7072L8.29286 14.293L6.58576 16.0001L7.99997 17.4143L9.70708 15.7072Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M7 4C5.34315 4 4 5.34315 4 7V17C4 18.6569 5.34315 20 7 20H17C18.6569 20 20 18.6569 20 17V7C20 5.34315 18.6569 4 17 4H7ZM6 7C6 6.44772 6.44772 6 7 6H17C17.5523 6 18 6.44772 18 7V17C18 17.5523 17.5523 18 17 18H7C6.44772 18 6 17.5523 6 17V7Z\" fill=\"currentColor\"/>\n </symbol>\n</svg>\n`;\n", "import type {\n AssetDefinition,\n AssetQueryData,\n AssetResult,\n AssetSource,\n AssetsQueryResult\n} from '@cesdk/engine';\n\n/**\n * Simplified value type for select inputs that can be converted to asset definitions\n */\nexport type SelectValue = {\n id: string;\n label: string;\n thumbUri?: string;\n};\n\n/**\n * A custom AssetSource implementation that manages assets from an array\n * and provides additional functionality like to mark assets as active or changing\n * labels.\n */\nexport class CustomAssetSource implements AssetSource {\n /** The unique id of the asset source */\n id: string;\n\n /** Array of assets to be served by this source */\n private assets: AssetDefinition[];\n\n /** Set of IDs for active assets */\n private activeAssetIds: Set<string>;\n\n /**\n * Creates a new instance of CustomAssetSource\n *\n * @param id - The unique identifier for this asset source\n * @param assets - Array of asset definitions or SelectValue objects to include in this source\n */\n constructor(id: string, assets: (AssetDefinition | SelectValue)[] = []) {\n this.id = id;\n this.assets = assets.map((asset) => {\n // Check if the asset is a SelectValue by looking for the label property as a string\n if (\n typeof (asset as SelectValue).label === 'string' &&\n !(\n (asset as AssetDefinition).label &&\n typeof (asset as AssetDefinition).label === 'object'\n )\n ) {\n const selectValue = asset as SelectValue;\n // Convert SelectValue to AssetDefinition\n return {\n id: selectValue.id,\n label: { en: selectValue.label },\n meta: selectValue.thumbUri\n ? { thumbUri: selectValue.thumbUri }\n : undefined\n } as AssetDefinition;\n }\n return asset as AssetDefinition;\n });\n this.activeAssetIds = new Set<string>();\n }\n\n /**\n * Find assets based on the provided query data\n * Supports pagination, searching, filtering, and active-first sorting\n *\n * @param queryData - Query parameters to filter and sort assets\n * @returns Promise with the query results\n */\n async findAssets(\n queryData: AssetQueryData\n ): Promise<AssetsQueryResult | undefined> {\n const {\n page,\n perPage,\n locale = 'en',\n sortActiveFirst,\n query,\n tags,\n groups,\n excludeGroups,\n sortingOrder,\n sortKey\n } = queryData;\n\n // Start with all assets\n let filteredAssets = [...this.assets];\n\n // Filter by groups if provided\n if (groups && groups.length > 0) {\n filteredAssets = filteredAssets.filter(\n (asset) =>\n asset.groups && groups.some((group) => asset.groups?.includes(group))\n );\n }\n\n // Filter out excluded groups if provided\n if (excludeGroups && excludeGroups.length > 0) {\n filteredAssets = filteredAssets.filter(\n (asset) =>\n !asset.groups ||\n !excludeGroups.some((group) => asset.groups?.includes(group))\n );\n }\n\n // Filter by query (search in label and tags)\n if (query) {\n const lowerQuery = query.toLowerCase();\n filteredAssets = filteredAssets.filter((asset) => {\n const label = asset.label?.[locale]?.toLowerCase();\n const assetTags = asset.tags?.[locale] || [];\n\n return (\n (label && label.includes(lowerQuery)) ||\n assetTags.some((tag) => tag.toLowerCase().includes(lowerQuery))\n );\n });\n }\n\n // Filter by exact tags if provided\n if (tags && tags.length > 0) {\n const tagArray = Array.isArray(tags) ? tags : [tags];\n filteredAssets = filteredAssets.filter((asset) => {\n const assetTags = asset.tags?.[locale] || [];\n return tagArray.some((tag) => assetTags.includes(tag));\n });\n }\n\n // Sort by active first if requested\n if (sortActiveFirst) {\n filteredAssets.sort((a, b) => {\n const aActive = this.activeAssetIds.has(a.id);\n const bActive = this.activeAssetIds.has(b.id);\n\n if (aActive && !bActive) return -1;\n if (!aActive && bActive) return 1;\n return 0;\n });\n }\n\n // Sort by sortKey if provided\n if (sortKey && sortKey !== 'id') {\n filteredAssets.sort((a, b) => {\n // Sort by metadata field\n const aValue = a.meta?.[sortKey];\n const bValue = b.meta?.[sortKey];\n\n if (aValue === undefined) return 1;\n if (bValue === undefined) return -1;\n\n if (typeof aValue === 'string' && typeof bValue === 'string') {\n return sortingOrder === 'Descending'\n ? bValue.localeCompare(aValue)\n : aValue.localeCompare(bValue);\n }\n\n if (typeof aValue === 'number' && typeof bValue === 'number') {\n return sortingOrder === 'Descending'\n ? bValue - aValue\n : aValue - bValue;\n }\n\n return 0;\n });\n } else if (sortKey === 'id') {\n // Sort by id\n filteredAssets.sort((a, b) => {\n return sortingOrder === 'Descending'\n ? b.id.localeCompare(a.id)\n : a.id.localeCompare(b.id);\n });\n }\n\n // Calculate pagination\n const total = filteredAssets.length;\n const startIndex = page * perPage;\n const endIndex = startIndex + perPage;\n const paginatedAssets = filteredAssets.slice(startIndex, endIndex);\n\n // Transform AssetDefinition objects to AssetResult objects\n const resultAssets: AssetResult[] = paginatedAssets.map((asset) => {\n return {\n id: asset.id,\n groups: asset.groups,\n meta: asset.meta,\n payload: asset.payload,\n locale,\n label: asset.label?.[locale],\n tags: asset.tags?.[locale],\n active: this.activeAssetIds.has(asset.id)\n };\n });\n\n // Calculate next page if there are more assets\n const nextPage = endIndex < total ? page + 1 : undefined;\n\n return {\n assets: resultAssets,\n currentPage: page,\n nextPage,\n total\n };\n }\n\n updateLabel(assetId: string, label: string, locale: string): void {\n this.assets.forEach((asset) => {\n if (asset.id === assetId) {\n asset.label = asset.label || {};\n asset.label[locale] = label;\n }\n });\n }\n\n /**\n * Set an asset as active by its ID\n *\n * @param assetId - The ID of the asset to mark as active\n */\n setAssetActive(assetId: string): void {\n this.activeAssetIds.add(assetId);\n }\n\n /**\n * Set multiple assets as active by their IDs\n *\n * @param assetIds - Array of asset IDs to mark as active\n */\n setAssetsActive(assetIds: string[]): void {\n assetIds.forEach((id) => this.activeAssetIds.add(id));\n }\n\n /**\n * Set an asset as inactive by its ID\n *\n * @param assetId - The ID of the asset to mark as inactive\n */\n setAssetInactive(assetId: string): void {\n this.activeAssetIds.delete(assetId);\n }\n\n /**\n * Clear all active assets\n */\n clearActiveAssets(): void {\n this.activeAssetIds.clear();\n }\n\n /**\n * Check if an asset is marked as active\n *\n * @param assetId - The ID of the asset to check\n * @returns True if the asset is active, false otherwise\n */\n isAssetActive(assetId: string): boolean {\n return this.activeAssetIds.has(assetId);\n }\n\n /**\n * Add an asset to this source\n *\n * @param asset - The asset definition to add\n */\n addAsset(asset: AssetDefinition): void {\n // Check if asset with this ID already exists\n const existingIndex = this.assets.findIndex((a) => a.id === asset.id);\n if (existingIndex >= 0) {\n // Replace existing asset\n this.assets[existingIndex] = asset;\n } else {\n // Add new asset\n this.assets.push(asset);\n }\n }\n\n /**\n * Remove an asset from this source\n *\n * @param assetId - The ID of the asset to remove\n */\n removeAsset(assetId: string): void {\n const index = this.assets.findIndex((asset) => asset.id === assetId);\n if (index !== -1) {\n this.assets.splice(index, 1);\n this.activeAssetIds.delete(assetId);\n }\n }\n\n /**\n * Get all available groups from the assets\n *\n * @returns Array of unique group names\n */\n async getGroups(): Promise<string[]> {\n const groups = new Set<string>();\n this.assets.forEach((asset) => {\n if (asset.groups) {\n asset.groups.forEach((group) => groups.add(group));\n }\n });\n return Array.from(groups);\n }\n\n /**\n * Returns the supported MIME types for this asset source\n *\n * @returns Array of supported MIME types\n */\n getSupportedMimeTypes(): string[] {\n return [\n 'image/jpeg',\n 'image/png',\n 'image/svg+xml',\n 'image/webp',\n 'video/mp4',\n 'audio/mpeg'\n ];\n }\n}\n\n/**\n * Helper function to create a CustomAssetSource instance\n *\n * @param id - The unique identifier for this asset source\n * @param assets - Array of asset definitions or SelectValue objects to include in this source\n * @returns A new CustomAssetSource instance\n */\nexport function createCustomAssetSource(\n id: string,\n assets: (AssetDefinition | SelectValue)[] = []\n): CustomAssetSource {\n return new CustomAssetSource(id, assets);\n}\n\nexport default CustomAssetSource;\n", "/* eslint-disable no-console */\nimport {\n CreativeEngine,\n type AssetDefinition,\n type AssetQueryData,\n type AssetResult,\n type AssetSource,\n type AssetsQueryResult\n} from '@cesdk/cesdk-js';\n\ntype BlobEntry = {\n id: string;\n blob: Blob;\n};\n\n// Asset definition with meta containing insertedAt timestamp\ntype AssetEntryWithMeta = AssetDefinition;\n\n/**\n * IndexedDBAssetSource implements the AssetSource interface using IndexedDB as the storage backend.\n */\nexport class IndexedDBAssetSource implements AssetSource {\n /** The unique id of the API */\n public readonly id: string;\n\n public readonly engine: CreativeEngine;\n\n private readonly dbName: string;\n\n private readonly dbVersion: number;\n\n private readonly assetStoreName: string = 'assets';\n\n private readonly blobStoreName: string = 'blobs';\n\n private db: IDBDatabase | null = null;\n\n /**\n * Creates a new IndexedDBAssetSource\n *\n * @param id - The unique identifier for this asset source\n * @param {Object} [options] - Optional configuration options.\n * @param {string} [options.dbName] - The name of the database.\n * @param {number} [options.dbVersion] - The version number of the database.\n */\n constructor(\n id: string,\n engine: CreativeEngine,\n options?: {\n dbName?: string;\n dbVersion?: number;\n }\n ) {\n this.id = id;\n this.engine = engine;\n this.dbName = options?.dbName ?? `ly.img.assetSource/${id}`;\n this.dbVersion = options?.dbVersion ?? 1;\n }\n\n /**\n * Initialize the database connection and create object stores if needed\n */\n public async initialize(): Promise<void> {\n if (this.db) {\n return;\n }\n\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(this.dbName, this.dbVersion);\n\n request.onerror = (event) => {\n reject(\n new Error(\n `Failed to open IndexedDB: ${(event.target as IDBRequest).error}`\n )\n );\n };\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n\n // Create asset store if it doesn't exist\n if (!db.objectStoreNames.contains(this.assetStoreName)) {\n db.createObjectStore(this.assetStoreName, {\n keyPath: 'id'\n });\n }\n // Create blob store if it doesn't exist\n if (!db.objectStoreNames.contains(this.blobStoreName)) {\n db.createObjectStore(this.blobStoreName, {\n keyPath: 'id'\n });\n }\n };\n\n request.onsuccess = (event) => {\n this.db = (event.target as IDBOpenDBRequest).result;\n resolve();\n };\n });\n }\n\n /**\n * Close the database connection\n */\n public close(): void {\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n }\n\n /**\n * Find all assets for the given type and the provided query data.\n *\n * @param queryData - The query parameters for filtering assets\n * @param insertionSortOrder - Optional parameter to sort by insertion time: 'asc' for oldest first, 'desc' for newest first (default)\n * @returns A promise that resolves to the query results or undefined if there was an error\n */\n public async findAssets(\n queryData: AssetQueryData\n ): Promise<AssetsQueryResult | undefined> {\n await this.initialize();\n\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n try {\n // Get all assets from the store with specified insertion order\n const assetDefinitions = await this.getAllAssets('asc');\n\n let assetResults = assetDefinitions.reduce((acc, assetDefinition) => {\n const locale = queryData.locale ?? 'en';\n let label = '';\n let tags: string[] = [];\n\n // Handle localized label if available\n if (\n assetDefinition.label != null &&\n typeof assetDefinition.label === 'object' &&\n assetDefinition.label[locale]\n ) {\n label = assetDefinition.label[locale];\n }\n\n // Handle localized tags if available\n if (\n assetDefinition.tags != null &&\n typeof assetDefinition.tags === 'object' &&\n assetDefinition.tags[locale]\n ) {\n tags = assetDefinition.tags[locale];\n }\n\n const result: AssetResult = {\n ...assetDefinition,\n label,\n tags\n };\n\n if (this.filterAsset(result, queryData)) {\n acc.push(result);\n }\n\n return acc;\n }, [] as AssetResult[]);\n\n assetResults = await this.restoreBlobUrls(assetResults);\n\n // Apply sorting\n assetResults = this.sortAssets(assetResults, queryData);\n\n // Apply pagination\n const { page, perPage } = queryData;\n const startIndex = page * perPage;\n const endIndex = startIndex + perPage;\n const paginatedAssets = assetResults.slice(startIndex, endIndex);\n\n // Determine if there's a next page\n const nextPage = endIndex < assetResults.length ? page + 1 : undefined;\n\n const result = {\n assets: paginatedAssets,\n currentPage: page,\n nextPage,\n total: assetResults.length\n };\n\n return result;\n } catch (error) {\n console.error('Error finding assets:', error);\n return undefined;\n }\n }\n\n public async getGroups(): Promise<string[]> {\n await this.initialize();\n\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.assetStoreName, 'readonly');\n const store = transaction.objectStore(this.assetStoreName);\n const request = store.getAll();\n\n request.onsuccess = () => {\n const allGroups = new Set<string>();\n\n // Extract all groups from all assets\n (request.result as AssetResult[]).forEach((asset) => {\n if (asset.groups && Array.isArray(asset.groups)) {\n asset.groups.forEach((group) => allGroups.add(group));\n }\n });\n\n const uniqueGroups = [...allGroups];\n resolve(uniqueGroups);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get groups: ${request.error}`));\n };\n });\n }\n\n /**\n * Adds the given asset to this source. Part of the AssetSource interface.\n *\n * @param asset - The asset definition to add\n */\n public addAsset(asset: AssetDefinition): void {\n this.initialize()\n .then(async () => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.assetStoreName,\n 'readwrite'\n );\n const assetStore = transaction.objectStore(this.assetStoreName);\n\n const blobsToStore = new Set<string>();\n processBlobUrls(asset, (value) => {\n blobsToStore.add(value);\n });\n\n setTimeout(() => {\n this.storeBlobUrls([...blobsToStore]);\n });\n\n // Ensure asset has meta object with insertedAt timestamp\n const assetWithMeta: AssetEntryWithMeta = {\n ...asset,\n meta: {\n ...asset.meta,\n insertedAt: asset.meta?.insertedAt || Date.now()\n }\n };\n\n // Store the asset in the database\n assetStore.put(assetWithMeta);\n\n transaction.onerror = () => {\n console.error(`Failed to add asset: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n /**\n * Removes the given asset from this source. Part of the AssetSource interface.\n *\n * @param assetId - The ID of the asset to remove\n */\n public async removeAsset(assetId: string): Promise<void> {\n const asset = await this.getAsset(assetId);\n\n return this.initialize()\n .then(() => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.assetStoreName,\n 'readwrite'\n );\n const store = transaction.objectStore(this.assetStoreName);\n store.delete(assetId);\n\n transaction.oncomplete = () => {\n processBlobUrls(asset, (value) => {\n this.removeBlob(value);\n });\n this.engine.asset.assetSourceContentsChanged(this.id);\n };\n\n transaction.onerror = () => {\n console.error(`Failed to remove asset: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n /**\n * Removes the given asset from this source. Part of the AssetSource interface.\n *\n * @param assetId - The ID of the asset to remove\n */\n public async removeBlob(blobId: string): Promise<void> {\n return this.initialize()\n .then(() => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.blobStoreName,\n 'readwrite'\n );\n const store = transaction.objectStore(this.blobStoreName);\n store.delete(blobId);\n\n transaction.onerror = () => {\n console.error(`Failed to remove blob: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n /**\n * Get all assets from the database sorted by insertion order (newest to oldest)\n *\n * @param sortOrder - Optional parameter to specify sort order: 'asc' for oldest first, 'desc' for newest first (default)\n * @returns A promise that resolves to an array of all assets\n */\n private async getAllAssets(\n sortOrder: 'asc' | 'desc' = 'desc'\n ): Promise<AssetDefinition[]> {\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.assetStoreName, 'readonly');\n const store = transaction.objectStore(this.assetStoreName);\n const request = store.getAll();\n\n request.onsuccess = () => {\n const assets = request.result as AssetEntryWithMeta[];\n\n // Sort by insertion timestamp\n assets.sort((a, b) => {\n // Default to current time if insertedAt is missing (for backward compatibility)\n // First check in meta.insertedAt, then fallback to legacy _insertedAt for backward compatibility\n const timeA =\n a.meta?.insertedAt || (a as any)._insertedAt || Date.now();\n const timeB =\n b.meta?.insertedAt || (b as any)._insertedAt || Date.now();\n\n // Sort based on requested order\n return sortOrder === 'asc'\n ? timeA - timeB // oldest first\n : timeB - timeA; // newest first (default)\n });\n\n resolve(assets);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get assets: ${request.error}`));\n };\n });\n }\n\n // Retrieve a blob by ID\n async getAsset(id: string): Promise<AssetResult | undefined> {\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.assetStoreName, 'readonly');\n const store = transaction.objectStore(this.assetStoreName);\n const request = store.get(id);\n\n request.onsuccess = () => {\n resolve(request.result as AssetResult);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get blob: ${request.error}`));\n };\n });\n }\n\n // Retrieve a blob by ID\n async getBlob(id: string): Promise<BlobEntry | undefined> {\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.blobStoreName, 'readonly');\n const store = transaction.objectStore(this.blobStoreName);\n const request = store.get(id);\n\n request.onsuccess = () => {\n resolve(request.result as BlobEntry);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get blob: ${request.error}`));\n };\n });\n }\n\n async createBlobUrlFromStore(blobUrl: string): Promise<string> {\n const blobEntry = await this.getBlob(blobUrl);\n if (blobEntry != null) {\n return URL.createObjectURL(blobEntry.blob);\n }\n return blobUrl;\n }\n\n async storeBlobUrls(urls: string[]): Promise<void> {\n const blobsToStore: { [key: string]: Blob } = {};\n await Promise.all(\n urls.map(async (blobUrl) => {\n const blobResponse = await fetch(blobUrl);\n const blob = await blobResponse.blob();\n blobsToStore[blobUrl] = blob;\n })\n );\n\n return this.initialize()\n .then(async () => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.blobStoreName,\n 'readwrite'\n );\n const blobStore = transaction.objectStore(this.blobStoreName);\n\n // Store the asset in the database\n Object.entries(blobsToStore).forEach(([key, blob]) => {\n const asset: BlobEntry = { id: key, blob };\n blobStore.put(asset);\n });\n\n transaction.onerror = () => {\n console.error(`Failed to add blobs: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n async restoreBlobUrls(assets: AssetResult[]): Promise<AssetResult[]> {\n const blobReplaced: { [key: string]: string } = {};\n const blobUrls: Set<string> = new Set();\n processBlobUrls(assets, (value) => {\n blobUrls.add(value);\n });\n\n await Promise.all(\n [...blobUrls].map(async (value) => {\n const newUrl = await this.createBlobUrlFromStore(value);\n blobReplaced[value] = newUrl;\n })\n );\n\n return processBlobUrls(assets, (value) => {\n return blobReplaced[value] ?? value;\n });\n }\n\n /**\n * Returns if the given asset should be filtered based on query data\n *\n * @param asset - The asset to filter\n * @param queryData - The query parameters to filter by\n * @returns true if the asset should be included, false otherwise\n */\n private filterAsset(asset: AssetResult, queryData: AssetQueryData): boolean {\n const { query, tags, groups, excludeGroups } = queryData;\n\n // Filter by query string (search on label and tags)\n if (query && query.trim() !== '') {\n const lowerQuery = query.trim().toLowerCase().split(' ');\n\n const lowerLabel = asset.label?.toLowerCase() ?? '';\n const lowerTags = asset.tags?.map((tag) => tag.toLowerCase()) ?? [];\n\n const matchLabelOrTag = lowerQuery.every((word) => {\n return (\n lowerLabel.includes(word) ||\n lowerTags.some((tag) => tag.includes(word))\n );\n });\n\n if (!matchLabelOrTag) {\n return false;\n }\n }\n\n // Filter by exact tags if provided by the query\n if (tags) {\n const tagList = Array.isArray(tags) ? tags : [tags];\n if (\n tagList.length > 0 &&\n (!asset.tags || !tagList.every((tag) => asset.tags?.includes(tag)))\n ) {\n return false;\n }\n }\n\n // Filter by groups\n if (groups && groups.length > 0) {\n if (\n !asset.groups ||\n !groups.some((group) => asset.groups?.includes(group))\n ) {\n return false;\n }\n }\n\n // Filter by excluded groups\n if (excludeGroups && excludeGroups.length > 0) {\n if (\n asset.groups &&\n asset.groups.some((group) => excludeGroups.includes(group))\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Sort assets based on query data\n *\n * @param assets - The assets to sort\n * @param queryData - The query parameters with sorting information\n * @returns The sorted assets\n */\n private sortAssets(\n assets: AssetResult[],\n queryData: AssetQueryData\n ): AssetResult[] {\n const { sortingOrder, sortKey, sortActiveFirst } = queryData;\n\n // Clone the array to avoid modifying the original\n const sortedAssets = [...assets];\n\n // If no sorting order specified or set to 'None', return the current order\n if (!sortingOrder || sortingOrder === 'None') {\n return sortedAssets;\n }\n\n // Sort by the specified key\n if (sortKey) {\n sortedAssets.sort((a, b) => {\n let valueA;\n let valueB;\n\n if (sortKey === 'id') {\n valueA = a.id;\n valueB = b.id;\n } else {\n // Handle metadata sorting (assuming metadata is stored in a 'metadata' field)\n valueA = a.meta?.[sortKey] ?? null;\n valueB = b.meta?.[sortKey] ?? null;\n }\n\n // Handle null/undefined values\n if (valueA === null || valueA === undefined)\n return sortingOrder === 'Ascending' ? -1 : 1;\n if (valueB === null || valueB === undefined)\n return sortingOrder === 'Ascending' ? 1 : -1;\n\n // Compare values based on sorting order\n if (typeof valueA === 'string' && typeof valueB === 'string') {\n return sortingOrder === 'Ascending'\n ? valueA.localeCompare(valueB)\n : valueB.localeCompare(valueA);\n } else {\n return sortingOrder === 'Ascending'\n ? valueA < valueB\n ? -1\n : valueA > valueB\n ? 1\n : 0\n : valueA > valueB\n ? -1\n : valueA < valueB\n ? 1\n : 0;\n }\n });\n } else if (sortingOrder === 'Descending') {\n // If no sort key is specified, and sorting order set\n // to Descending, just reverse original order\n sortedAssets.reverse();\n }\n\n // Sort by active first if requested\n if (sortActiveFirst) {\n sortedAssets.sort((a, b) => {\n if (a.active && !b.active) return -1;\n if (!a.active && b.active) return 1;\n return 0;\n });\n }\n\n return sortedAssets;\n }\n}\n\n/**\n * Goes through an object and calls a callback for every string value that starts with 'blob:'\n * The callback can return a string to replace the original value\n * @param obj The object to traverse\n * @param callback Function to call when a blob URL is found, can return a replacement value\n * @param path Current path in the object (used for recursion)\n * @returns The modified object (or the original if no replacements were made)\n */\nfunction processBlobUrls<T>(\n obj: T,\n callback: (value: string, path: string) => string | void,\n path: string = ''\n): T {\n // Return the object as is if it's null or not an object\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n for (let index = 0; index < obj.length; index++) {\n const currentPath = path ? `${path}[${index}]` : `[${index}]`;\n\n if (typeof obj[index] === 'string' && obj[index].startsWith('blob:')) {\n const replacement = callback(obj[index], currentPath);\n if (typeof replacement === 'string') {\n obj[index] = replacement;\n }\n } else {\n obj[index] = processBlobUrls(obj[index], callback, currentPath);\n }\n }\n return obj;\n }\n\n // Handle regular objects\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key];\n const currentPath = path ? `${path}.${key}` : key;\n\n if (typeof value === 'string' && value.startsWith('blob:')) {\n const replacement = callback(value, currentPath);\n if (typeof replacement === 'string') {\n // @ts-ignore\n obj[key] = replacement;\n }\n } else {\n obj[key] = processBlobUrls(value, callback, currentPath);\n }\n }\n }\n\n return obj;\n}\n\nexport default IndexedDBAssetSource;\n", "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport type {\n AssetDefinition,\n AssetQueryData,\n AssetResult,\n AssetSource,\n AssetsQueryResult\n} from '@cesdk/cesdk-js';\nimport CreativeEditorSDK from '@cesdk/cesdk-js';\n\n/**\n * AggregatedAssetSource implements the AssetSource interface by aggregating\n * multiple asset sources via the cesdk API and combining their results.\n *\n * This asset source is read-only - it does not support adding or removing assets.\n */\nexport class AggregatedAssetSource implements AssetSource {\n /** The unique id of the asset source */\n public readonly id: string;\n\n /** The Creative Editor SDK instance */\n private cesdk: CreativeEditorSDK;\n\n /** The IDs of asset sources to aggregate */\n private assetSourceIds: string[];\n\n /**\n * Creates a new AggregatedAssetSource\n *\n * @param id - The unique identifier for this asset source\n * @param cesdk - The Creative Editor SDK instance\n * @param assetSourceIds - The IDs of asset sources to aggregate\n */\n constructor(id: string, cesdk: CreativeEditorSDK, assetSourceIds: string[]) {\n this.id = id;\n this.cesdk = cesdk;\n this.assetSourceIds = assetSourceIds;\n }\n\n /**\n * Find assets across all aggregated sources based on the provided query data\n * Results are sorted by the insertedAt timestamp in meta field\n *\n * @param queryData - Query parameters to filter and sort assets\n * @returns Promise with the query results\n */\n async findAssets(\n queryData: AssetQueryData\n ): Promise<AssetsQueryResult | undefined> {\n try {\n // Query all asset sources via cesdk\n const queryPromises = this.assetSourceIds.map((sourceId) =>\n this.cesdk.engine.asset.findAssets(sourceId, {\n ...queryData,\n // Increase page size to get all assets from each source\n // We'll handle pagination after merging\n perPage: 9999,\n page: 0\n })\n );\n\n // Wait for all queries to complete\n const results = await Promise.all(queryPromises);\n\n // Combine all assets from all sources\n let allAssets: AssetResult[] = [];\n results.forEach((result) => {\n if (result?.assets) {\n allAssets = allAssets.concat(result.assets);\n }\n });\n\n // Sort by insertedAt timestamp\n allAssets.sort((a, b) => {\n const timeA = (a.meta?.insertedAt as number) || 0;\n const timeB = (b.meta?.insertedAt as number) || 0;\n\n // Sort newest first (descending)\n return timeB - timeA;\n });\n\n // Apply pagination after merging\n const { page, perPage } = queryData;\n const startIndex = page * perPage;\n const endIndex = startIndex + perPage;\n const paginatedAssets = allAssets.slice(startIndex, endIndex);\n\n // Calculate if there is a next page\n const nextPage = endIndex < allAssets.length ? page + 1 : undefined;\n\n return {\n assets: paginatedAssets,\n currentPage: page,\n nextPage,\n total: allAssets.length\n };\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Error finding assets:', error);\n return undefined;\n }\n }\n\n /**\n * Retrieves all groups from all aggregated asset sources using cesdk\n * @returns Promise with an array of unique group names\n */\n async getGroups(): Promise<string[]> {\n const groupPromises = this.assetSourceIds.map((sourceId) =>\n this.cesdk.engine.asset.getGroups(sourceId)\n );\n\n const groupArrays = await Promise.all(groupPromises);\n\n // Combine and deduplicate groups\n const uniqueGroups = new Set<string>();\n groupArrays.forEach((groups) => {\n groups.forEach((group) => uniqueGroups.add(group));\n });\n\n return Array.from(uniqueGroups);\n }\n\n /**\n * This operation is not supported in AggregatedAssetSource\n * @throws Error - This method is not supported\n */\n addAsset(_asset: AssetDefinition): void {\n throw new Error('AggregatedAssetSource does not support adding assets');\n }\n\n /**\n * This operation is not supported in AggregatedAssetSource\n * @throws Error - This method is not supported\n */\n removeAsset(_assetId: string): void {\n throw new Error('AggregatedAssetSource does not support removing assets');\n }\n}\n\n/**\n * Helper function to create an AggregatedAssetSource instance\n *\n * @param id - The unique identifier for this asset source\n * @param cesdk - The Creative Editor SDK instance\n * @param assetSourceIds - The IDs of asset sources to aggregate\n * @returns A new AggregatedAssetSource instance\n */\nexport function createAggregatedAssetSource(\n id: string,\n cesdk: CreativeEditorSDK,\n assetSourceIds: string[]\n): AggregatedAssetSource {\n return new AggregatedAssetSource(id, cesdk, assetSourceIds);\n}\n\nexport default AggregatedAssetSource;\n", "import { type CreativeEngine } from '@cesdk/cesdk-js';\n\nclass Metadata<V> {\n engine: CreativeEngine;\n\n key: string;\n\n constructor(engine: CreativeEngine, key: string) {\n this.engine = engine;\n this.key = key;\n }\n\n hasData(blockId: number): boolean {\n return (\n this.engine.block.isValid(blockId) &&\n this.engine.block.hasMetadata(blockId, this.key)\n );\n }\n\n get(blockId: number): V | undefined {\n if (this.hasData(blockId)) {\n return JSON.parse(this.engine.block.getMetadata(blockId, this.key));\n }\n return undefined;\n }\n\n set(blockId: number, value: V) {\n this.engine.block.setMetadata(blockId, this.key, JSON.stringify(value));\n }\n\n clear(blockId: number) {\n if (this.engine.block.hasMetadata(blockId, this.key)) {\n this.engine.block.removeMetadata(blockId, this.key);\n }\n }\n}\n\nexport default Metadata;\n", "/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nexport default root;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n", "import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n", "import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\n", "/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n", "/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n", "/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nexport default isFunction;\n", "import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n", "import coreJsData from './_coreJsData.js';\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nexport default isMasked;\n", "/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n", "import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nexport default baseIsNative;\n", "/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n", "import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nexport default getNative;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n", "/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n", "import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nexport default isArrayLike;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n", "/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nexport default baseIsArguments;\n", "import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nexport default isArguments;\n", "/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n", "import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n", "import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nexport default baseIsTypedArray;\n", "/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nexport default nodeUtil;\n", "import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nexport default isTypedArray;\n", "import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default arrayLikeKeys;\n", "/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n", "import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n", "import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeys;\n", "import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nexport default keys;\n", "import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n", "import nativeCreate from './_nativeCreate.js';\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nexport default hashClear;\n", "/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nexport default hashGet;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nexport default hashHas;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nexport default hashSet;\n", "import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nexport default Hash;\n", "/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n", "import eq from './eq.js';\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nexport default assocIndexOf;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nexport default listCacheDelete;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nexport default listCacheGet;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nexport default listCacheHas;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nexport default listCacheSet;\n", "import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nexport default ListCache;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n", "import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nexport default mapCacheClear;\n", "/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n", "import isKeyable from './_isKeyable.js';\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nexport default getMapData;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default mapCacheDelete;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nexport default mapCacheGet;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nexport default mapCacheHas;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nexport default mapCacheSet;\n", "import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nexport default MapCache;\n", "/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n", "import ListCache from './_ListCache.js';\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nexport default stackClear;\n", "/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n", "/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n", "/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n", "import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nexport default stackSet;\n", "import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nexport default Stack;\n", "/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n", "/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n", "import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nexport default getSymbols;\n", "import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nexport default baseGetAllKeys;\n", "import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nexport default getAllKeys;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n", "import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nexport default getTag;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\n", "/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n", "/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n", "import MapCache from './_MapCache.js';\nimport setCacheAdd from './_setCacheAdd.js';\nimport setCacheHas from './_setCacheHas.js';\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nexport default SetCache;\n", "/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n", "/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n", "import SetCache from './_SetCache.js';\nimport arraySome from './_arraySome.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nexport default equalArrays;\n", "/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n", "/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n", "import Symbol from './_Symbol.js';\nimport Uint8Array from './_Uint8Array.js';\nimport eq from './eq.js';\nimport equalArrays from './_equalArrays.js';\nimport mapToArray from './_mapToArray.js';\nimport setToArray from './_setToArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nexport default equalByTag;\n", "import getAllKeys from './_getAllKeys.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nexport default equalObjects;\n", "import Stack from './_Stack.js';\nimport equalArrays from './_equalArrays.js';\nimport equalByTag from './_equalByTag.js';\nimport equalObjects from './_equalObjects.js';\nimport getTag from './_getTag.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nexport default baseIsEqualDeep;\n", "import baseIsEqualDeep from './_baseIsEqualDeep.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nexport default baseIsEqual;\n", "import baseIsEqual from './_baseIsEqual.js';\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\nexport default isEqual;\n", "import { isEqual } from 'lodash-es';\n\nimport Metadata from './Metadata';\nimport {\n PluginStatusError,\n PluginStatusMetadata,\n PluginStatusProcessed,\n PluginStatusProcessing\n} from './types';\n\nclass ImageProcessingMetadata extends Metadata<PluginStatusMetadata> {\n get(blockId: number): PluginStatusMetadata {\n return super.get(blockId) ?? { status: 'IDLE' };\n }\n\n /**\n * Detect if the block has been duplicated with processed or processing\n * fill processing. In that case the processing state is still\n * valid, but blockId and fillId have changed.\n */\n isDuplicate(blockId: number): boolean {\n if (!this.engine.block.isValid(blockId)) return false;\n\n const metadata = this.get(blockId);\n\n if (\n metadata.status === 'IDLE' ||\n metadata.status === 'PENDING' ||\n metadata.status === 'ERROR'\n )\n return false;\n\n if (!this.engine.block.hasFill(blockId)) return false;\n const fillId = this.engine.block.getFill(blockId);\n\n // It cannot be a duplicate if the blockId or fillId are the same\n if (metadata.blockId === blockId || metadata.fillId === fillId)\n return false;\n\n return true;\n }\n\n /**\n * Fixes the metadata if the block has been duplicated, i.e. the blockId and\n * fillId will be updated to the current block/fill.\n *\n * Please note: Call this method only on duplicates (see isDuplicate).\n */\n fixDuplicate(blockId: number) {\n const fillId = this.engine.block.getFill(blockId);\n const metadata = this.get(blockId);\n if (\n metadata.status === 'IDLE' ||\n metadata.status === 'PENDING' ||\n metadata.status === 'ERROR'\n )\n return;\n this.set(blockId, {\n ...metadata,\n blockId,\n fillId\n });\n\n // If it is currently processing the best we can do is to just recover\n // the initial image data, since no processing will update this block and\n // it will be stuck in the processing state.\n if (metadata.status === 'PROCESSING') {\n this.recoverInitialImageData(blockId);\n this.clear(blockId);\n }\n }\n\n /**\n * Check if the image has a consisten metadata state. A inconsistent state is\n * caused by outside changes of the fill data.\n *\n * @returns true if the metadata is consistent, false otherwise\n */\n isConsistent(blockId: number): boolean {\n // In case the block was removed, we just abort and mark it\n // as reset by returning true\n if (!this.engine.block.isValid(blockId)) return false;\n const metadata = this.get(blockId);\n if (metadata.status === 'IDLE' || metadata.status === 'PENDING')\n return true;\n\n if (!this.engine.block.hasFill(blockId)) return false;\n const fillId = this.engine.block.getFill(blockId);\n if (fillId == null) return false;\n\n if (blockId !== metadata.blockId || fillId !== metadata.fillId)\n return false;\n\n const sourceSet = this.engine.block.getSourceSet(\n fillId,\n 'fill/image/sourceSet'\n );\n const imageFileURI = this.engine.block.getString(\n fillId,\n 'fill/image/imageFileURI'\n );\n\n if (\n sourceSet.length === 0 &&\n !imageFileURI &&\n metadata.status === 'PROCESSING'\n ) {\n // While we process it is OK to have no image file URI and no source set\n // (which we cleared to show the spinning loader)\n return true;\n }\n\n // Source sets have precedence over imageFileURI so if we have a source set,\n // we only need to check if it has changed to something else.\n if (sourceSet?.length > 0) {\n const initialSourceSet = metadata.initialSourceSet;\n // If we have already processed the image, we need to check if the source set\n // we need to check against both source sets, the removed and the initial\n if (metadata.status !== 'PROCESSED') {\n if (!isEqual(sourceSet, initialSourceSet)) {\n return false;\n }\n }\n } else {\n if (metadata.status !== 'PROCESSED') {\n if (imageFileURI !== metadata.initialImageFileURI) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Recover the initial values to avoid the loading spinner and have the same\n * state as before the fill processing was started.\n */\n recoverInitialImageData(blockId: number) {\n const blockApi = this.engine.block;\n if (!blockApi.hasFill(blockId)) return; // Nothing to recover (no fill anymore)\n\n const metadata = this.get(blockId);\n\n if (metadata.status === 'PENDING' || metadata.status === 'IDLE') {\n return;\n }\n\n const initialSourceSet = metadata.initialSourceSet;\n const initialImageFileURI = metadata.initialImageFileURI;\n const initialPreviewFileURI = metadata.initialPreviewFileURI;\n\n const fillId = this.getValidFill(blockId, metadata);\n if (fillId == null) return;\n\n if (initialImageFileURI) {\n this.engine.block.setString(\n fillId,\n 'fill/image/imageFileURI',\n initialImageFileURI\n );\n }\n if (initialPreviewFileURI) {\n this.engine.block.setString(\n fillId,\n 'fill/image/previewFileURI',\n initialPreviewFileURI\n );\n }\n if (initialSourceSet.length > 0) {\n this.engine.block.setSourceSet(\n fillId,\n 'fill/image/sourceSet',\n initialSourceSet\n );\n }\n }\n\n /**\n * Returns the fill id of the block if it has a valid fill that was used for\n * fill processing. Returns undefined otherwise.\n */\n private getValidFill(\n blockId: number,\n metadata: PluginStatusProcessing | PluginStatusError | PluginStatusProcessed\n ): number | undefined {\n if (\n !this.engine.block.isValid(blockId) ||\n !this.engine.block.hasFill(blockId) ||\n blockId !== metadata.blockId\n ) {\n return undefined;\n }\n const fillId = this.engine.block.getFill(blockId);\n if (fillId !== metadata.fillId) {\n return undefined;\n }\n\n return fillId;\n }\n}\n\nexport default ImageProcessingMetadata;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { FillProcessingMetadata } from '..';\nimport {\n PluginStatusProcessed,\n PluginStatusProcessing\n} from '../metadata/types';\n\ninterface FillProcessor<T> {\n processFill(metadataState: PluginStatusProcessing): Promise<T>;\n\n commitProcessing(\n data: T,\n metadataState: PluginStatusProcessed\n ): number | void;\n}\n\nasync function fillProcessing<T>(\n blockId: number,\n cesdk: CreativeEditorSDK,\n metadata: FillProcessingMetadata,\n processor: FillProcessor<T>\n) {\n const blockApi = cesdk.engine.block;\n if (!blockApi.hasFill(blockId))\n throw new Error('Block does not support fill');\n\n const fillId = blockApi.getFill(blockId);\n\n // Get the current image URI and source set as initial values.\n const initialSourceSet = blockApi.getSourceSet(\n fillId,\n 'fill/image/sourceSet'\n );\n const initialImageFileURI = blockApi.getString(\n fillId,\n 'fill/image/imageFileURI'\n );\n const initialPreviewFileURI = blockApi.getString(\n fillId,\n 'fill/image/previewFileURI'\n );\n try {\n cesdk.engine.block.setState(fillId, {\n type: 'Pending',\n progress: 0\n });\n\n const status: PluginStatusProcessing = {\n ...metadata.get(blockId),\n version: PLUGIN_VERSION,\n initialSourceSet,\n initialImageFileURI,\n initialPreviewFileURI,\n blockId,\n fillId,\n status: 'PROCESSING'\n };\n\n metadata.set(blockId, status);\n\n const processedData = await processor.processFill(status);\n // Check for externally changed state while we were applying the mask and\n // do not proceed if the state was reset.\n if (\n metadata.get(blockId).status !== 'PROCESSING' ||\n !metadata.isConsistent(blockId)\n )\n return;\n\n // Check for externally changed state while we were uploading and\n // do not proceed if the state was reset.\n if (\n metadata.get(blockId).status !== 'PROCESSING' ||\n !metadata.isConsistent(blockId)\n )\n return;\n\n if (processedData == null) return;\n\n const metadataStateProcessed: PluginStatusProcessed = {\n version: PLUGIN_VERSION,\n initialSourceSet,\n initialImageFileURI,\n initialPreviewFileURI,\n blockId,\n fillId,\n status: 'PROCESSED'\n };\n\n const blockIdOrVoid = processor.commitProcessing(\n processedData,\n metadataStateProcessed\n );\n\n // If a new block was created, we do not update the metadata.\n if (blockIdOrVoid == null || blockIdOrVoid === blockId) {\n metadata.set(blockId, metadataStateProcessed);\n }\n\n // Finally, create an undo step\n cesdk.engine.editor.addUndoStep();\n } catch (error) {\n if (cesdk.engine.block.isValid(blockId)) {\n metadata.set(blockId, {\n version: PLUGIN_VERSION,\n initialSourceSet,\n initialImageFileURI,\n initialPreviewFileURI,\n blockId,\n fillId,\n status: 'ERROR'\n });\n\n metadata.recoverInitialImageData(blockId);\n }\n\n if (\n error != null &&\n typeof error === 'object' &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n const message =\n error.message === 'signal timed out'\n ? 'Processing canceled due to timeout'\n : error.message;\n cesdk.ui.showNotification({\n type: 'error',\n message\n });\n }\n\n // eslint-disable-next-line no-console\n console.log(error);\n } finally {\n if (cesdk.engine.block.isValid(fillId)) {\n cesdk.engine.block.setState(fillId, { type: 'Ready' });\n }\n }\n}\n\nexport default fillProcessing;\n", "export function getFeatureId(pluginId: string): string {\n return `${pluginId}.fillProcessing.feature`;\n}\n\nexport function getCanvasMenuComponentIds(pluginId: string): string[] {\n return [`${pluginId}.canvasMenu`, `${pluginId}.fillProcessing.canvasMenu`];\n}\n\nexport function getDockComponentIds(pluginId: string): string[] {\n return [`${pluginId}.dock`, `${pluginId}.fillProcessing.dock`];\n}\n\nexport function getInspectorBarComponentIds(pluginId: string): string[] {\n return [\n `${pluginId}.inspectorBar`,\n `${pluginId}.fillProcessing.inspectorBar`\n ];\n}\n\nexport function getNavigationBarComponentIds(pluginId: string): string[] {\n return [\n `${pluginId}.navigationBar`,\n `${pluginId}.fillProcessing.navigationBar`\n ];\n}\n\nexport function getCanvasBarComponentIds(pluginId: string): string[] {\n return [`${pluginId}.canvasBar`, `${pluginId}.fillProcessing.canvasBar`];\n}\n\nexport function getI18nCanvasMenuLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.canvasMenu.button.label`;\n}\n\nexport function getI18nDockLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.dock.button.label`;\n}\n\nexport function getI18nInspectorBarLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.inspectorBar.button.label`;\n}\n\nexport function getI18nNavigationBarLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.navigationBar.button.label`;\n}\n\nexport function getI18nCanvasBarLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.canvasBar.button.label`;\n}\n", "import type CreativeEditorSDK from '@cesdk/cesdk-js';\n\nimport { FillProcessingMetadata } from '..';\nimport { getFeatureId } from './constants';\n\nexport default function handleFillProcessing(\n cesdk: CreativeEditorSDK,\n {\n pluginId,\n process\n }: {\n pluginId: string;\n icon?: string;\n process: (blockId: number, metadata: FillProcessingMetadata) => void;\n }\n): {\n featureId: string;\n} {\n const featureId = getFeatureId(pluginId);\n\n const metadata = new FillProcessingMetadata(cesdk.engine, pluginId);\n\n enableFeatures(cesdk, metadata, featureId);\n\n cesdk.engine.event.subscribe([], async (events) => {\n events.forEach((e) => {\n const id = e.block;\n if (!cesdk.engine.block.isValid(id) || !metadata.hasData(id)) {\n return;\n }\n\n if (e.type === 'Created') {\n if (metadata.isDuplicate(id)) {\n metadata.fixDuplicate(id);\n }\n } else if (e.type === 'Updated') {\n switch (metadata.get(id).status) {\n case 'PENDING': {\n if (\n cesdk.feature.isEnabled(featureId, {\n engine: cesdk.engine\n }) &&\n cesdk.engine.block.isAllowedByScope(id, 'fill/change') &&\n cesdk.engine.block.getState(id).type !== 'Pending'\n ) {\n process(id, metadata);\n }\n break;\n }\n\n case 'PROCESSING':\n case 'PROCESSED': {\n if (!metadata.isConsistent(id)) {\n metadata.clear(id);\n }\n break;\n }\n\n default: {\n // We do not care about other states\n }\n }\n }\n });\n });\n\n return { featureId };\n}\n\n/**\n * Defines the feature that determines in which context (on which block)\n * fill processing is allowed/enabled.\n */\nfunction enableFeatures(\n cesdk: CreativeEditorSDK,\n metadata: FillProcessingMetadata,\n featureId: string\n) {\n cesdk.feature.enable(featureId, ({ engine }) => {\n const selectedIds = engine.block.findAllSelected();\n if (selectedIds.length !== 1) {\n return false;\n }\n const [selectedId] = selectedIds;\n\n if (!cesdk.engine.block.isVisible(selectedId)) return false;\n\n if (cesdk.engine.block.hasFill(selectedId)) {\n const kind = cesdk.engine.block.getKind(selectedId);\n if (kind === 'sticker') return false;\n\n const fillId = cesdk.engine.block.getFill(selectedId);\n const fillType = cesdk.engine.block.getType(fillId);\n\n if (fillType !== '//ly.img.ubq/fill/image') {\n return false;\n }\n\n const fileUri = engine.block.getString(fillId, 'fill/image/imageFileURI');\n const sourceSet = engine.block.getSourceSet(\n fillId,\n 'fill/image/sourceSet'\n );\n\n if (sourceSet.length > 0 || fileUri !== '') return true;\n\n // If we are in a processing state we do not have a imageFileURI or\n // source set set (to show the loading spinner), but the feature is still\n // enabled.\n return metadata.get(selectedId).status === 'PROCESSING';\n }\n\n return false;\n });\n}\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { FillProcessingMetadata } from '..';\nimport {\n getCanvasBarComponentIds,\n getCanvasMenuComponentIds,\n getDockComponentIds,\n getFeatureId,\n getI18nCanvasBarLabel,\n getI18nCanvasMenuLabel,\n getI18nDockLabel,\n getI18nInspectorBarLabel,\n getI18nNavigationBarLabel,\n getInspectorBarComponentIds,\n getNavigationBarComponentIds\n} from './constants';\n\nexport type Location =\n | 'inspectorBar'\n | 'navigationBar'\n | 'canvasBarTop'\n | 'canvasBarBottom'\n | 'canvasMenu'\n | 'dock';\n\n/**\n * Registers the components that can be used to process the fill of\n * a block.\n */\nexport default function registerFillProcessingComponents(\n cesdk: CreativeEditorSDK,\n options: {\n pluginId: string;\n icon?: string;\n locations?: Location | Location[];\n }\n): {\n canvasMenuComponentId: string;\n dockComponentId: string;\n\n translationsKeys: {\n inspectorBarLabel: string;\n navigationBarLabel: string;\n canvasBarLabel: string;\n canvasMenuLabel: string;\n dockLabel: string;\n };\n} {\n const { pluginId, locations } = options;\n const metadata = new FillProcessingMetadata(cesdk.engine, pluginId);\n\n const canvasMenuLabel = getI18nCanvasMenuLabel(pluginId);\n const canvasMenuComponentIds = getCanvasMenuComponentIds(pluginId);\n const canvasMenuComponentId = canvasMenuComponentIds[0];\n\n const dockLabel = getI18nDockLabel(pluginId);\n const dockComponentIds = getDockComponentIds(pluginId);\n const dockComponentId = dockComponentIds[0];\n\n const inspectorBarLabel = getI18nInspectorBarLabel(pluginId);\n const inspectorBarComponentIds = getInspectorBarComponentIds(pluginId);\n const inspectorBarComponentId = inspectorBarComponentIds[0];\n\n const navigationBarLabel = getI18nNavigationBarLabel(pluginId);\n const navigationBarComponentIds = getNavigationBarComponentIds(pluginId);\n const navigationBarComponentId = navigationBarComponentIds[0];\n\n const canvasBarLabel = getI18nCanvasBarLabel(pluginId);\n const canvasBarComponentIds = getCanvasBarComponentIds(pluginId);\n const canvasBarComponentId = canvasBarComponentIds[0];\n\n const featureId = getFeatureId(pluginId);\n\n if (locations?.includes('inspectorBar')) {\n cesdk.ui.setInspectorBarOrder([\n inspectorBarComponentId,\n ...cesdk.ui.getInspectorBarOrder()\n ]);\n }\n\n if (locations?.includes('navigationBar')) {\n cesdk.ui.setNavigationBarOrder([\n navigationBarComponentId,\n ...cesdk.ui.getNavigationBarOrder()\n ]);\n }\n\n if (locations?.includes('canvasBarTop')) {\n cesdk.ui.setCanvasBarOrder(\n [canvasBarComponentId, ...cesdk.ui.getCanvasBarOrder('top')],\n 'top'\n );\n }\n\n if (locations?.includes('canvasBarBottom')) {\n cesdk.ui.setCanvasBarOrder(\n [canvasBarComponentId, ...cesdk.ui.getCanvasBarOrder('bottom')],\n 'bottom'\n );\n }\n\n if (locations?.includes('canvasMenu')) {\n cesdk.ui.setCanvasMenuOrder([\n canvasMenuComponentId,\n ...cesdk.ui.getCanvasMenuOrder()\n ]);\n }\n\n if (locations?.includes('dock')) {\n cesdk.ui.setDockOrder([...cesdk.ui.getDockOrder(), dockComponentId]);\n }\n\n cesdk.ui.registerComponent(\n dockComponentIds,\n ({ builder: { Button }, engine }) => {\n const [id] = engine.block.findAllSelected();\n\n let isDisabled = false;\n let isLoading = false;\n let loadingProgress: number | undefined;\n\n if (id == null) {\n isDisabled = true;\n }\n\n if (\n !isDisabled &&\n !cesdk.feature.isEnabled(featureId, {\n engine\n })\n ) {\n isDisabled = true;\n }\n\n if (\n !isDisabled &&\n !cesdk.engine.block.isAllowedByScope(id, 'fill/change')\n ) {\n isDisabled = true;\n }\n\n if (!isDisabled && engine.block.getState(id)?.type === 'Pending') {\n isDisabled = true;\n }\n\n if (!isDisabled) {\n const currentMetadata = metadata.get(id);\n\n isLoading = currentMetadata.status === 'PROCESSING';\n isDisabled =\n currentMetadata.status === 'PENDING' ||\n currentMetadata.status === 'PROCESSING';\n\n if (\n currentMetadata.status === 'PROCESSING' &&\n currentMetadata.progress\n ) {\n const { current, total } = currentMetadata.progress;\n loadingProgress = (current / total) * 100;\n }\n }\n\n const buttonId = `${dockComponentId}.button`;\n Button(buttonId, {\n label: dockLabel,\n icon: options.icon,\n isLoading,\n isDisabled,\n loadingProgress,\n onClick: () => {\n const currentMetadata = metadata.get(id);\n\n if (\n currentMetadata.status === 'IDLE' ||\n currentMetadata.status === 'ERROR' ||\n currentMetadata.status === 'PROCESSED'\n ) {\n metadata.set(id, {\n status: 'PENDING'\n });\n }\n }\n });\n }\n );\n\n const buttonComponents: {\n componentIds: string[];\n label: string;\n variant: 'plain' | 'regular';\n }[] = [\n {\n componentIds: inspectorBarComponentIds,\n variant: 'plain',\n label: inspectorBarLabel\n },\n {\n componentIds: navigationBarComponentIds,\n variant: 'regular',\n label: navigationBarLabel\n },\n {\n componentIds: canvasBarComponentIds,\n variant: 'regular',\n label: canvasBarLabel\n },\n {\n componentIds: canvasMenuComponentIds,\n variant: 'plain',\n label: canvasMenuLabel\n }\n ];\n\n buttonComponents.forEach(({ componentIds, label, variant }) => {\n const componentId = componentIds[0];\n cesdk.ui.registerComponent(\n componentIds,\n ({ builder: { Button }, engine }) => {\n if (\n !cesdk.feature.isEnabled(featureId, {\n engine\n })\n ) {\n return;\n }\n\n const [id] = engine.block.findAllSelected();\n\n if (!cesdk.engine.block.isAllowedByScope(id, 'fill/change')) return;\n\n const currentMetadata = metadata.get(id);\n\n const isLoading = currentMetadata.status === 'PROCESSING';\n const isDisabled =\n currentMetadata.status === 'PENDING' ||\n currentMetadata.status === 'PROCESSING' ||\n engine.block.getState(id)?.type === 'Pending';\n\n let loadingProgress: number | undefined;\n if (isLoading && currentMetadata.progress) {\n const { current, total } = currentMetadata.progress;\n loadingProgress = (current / total) * 100;\n }\n\n const buttonId = `${componentId}.button`;\n Button(buttonId, {\n icon: options.icon,\n label,\n variant,\n isLoading,\n isDisabled,\n loadingProgress,\n onClick: () => {\n if (\n currentMetadata.status === 'IDLE' ||\n currentMetadata.status === 'ERROR' ||\n currentMetadata.status === 'PROCESSED'\n ) {\n metadata.set(id, {\n status: 'PENDING'\n });\n }\n }\n });\n }\n );\n });\n\n return {\n canvasMenuComponentId,\n dockComponentId,\n translationsKeys: {\n inspectorBarLabel,\n navigationBarLabel,\n canvasBarLabel,\n canvasMenuLabel,\n dockLabel\n }\n };\n}\n", "import { type RGBAColor } from '@cesdk/cesdk-js';\n\nconst HEX_COLOR_PATTERN = new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/, 'i');\nconst HEX_SINGLE_CHAR_COMPONENTS_PATTERN = new RegExp(/[A-Fa-f0-9]{1}/, 'g');\nconst HEX_DOUBLE_CHAR_COMPONENTS_PATTERN = new RegExp(/[A-Fa-f0-9]{2}/, 'g');\n\n/** @public */\nexport const rgbaToHex = (rgba: RGBAColor, includeAlpha = false): string => {\n const { r, g, b, a } = rgba;\n const rByte = Math.round(255 * r);\n const gByte = Math.round(255 * g);\n const bByte = Math.round(255 * b);\n const aByte = Math.round(255 * a);\n const byteToHex = (byte: number) => {\n return byte.toString(16).padStart(2, '0');\n };\n return `#${byteToHex(rByte)}${byteToHex(gByte)}${byteToHex(bByte)}${\n includeAlpha ? byteToHex(aByte) : ''\n }`;\n};\n\n/** @public */\nexport const hexToRgba = (hexString: string): RGBAColor => {\n const rgbaHexToColor = (\n r: string,\n g: string,\n b: string,\n a: string | undefined,\n max: number\n ) => {\n return {\n r: parseInt(r, 16) / max,\n g: parseInt(g, 16) / max,\n b: parseInt(b, 16) / max,\n a: a === undefined ? 1 : parseInt(a, 16) / max\n };\n };\n\n if (hexString.startsWith('#')) {\n if (hexString.length === 4 || hexString.length === 5) {\n const hexMatch = hexString.match(HEX_SINGLE_CHAR_COMPONENTS_PATTERN);\n if (hexMatch) {\n const [r, g, b, a] = hexMatch;\n return rgbaHexToColor(r, g, b, a, 15);\n }\n }\n if (hexString.length === 7 || hexString.length === 8) {\n const hexMatch = hexString.match(HEX_DOUBLE_CHAR_COMPONENTS_PATTERN);\n if (hexMatch) {\n const [r, g, b, a] = hexMatch;\n return rgbaHexToColor(r, g, b, a, 255);\n }\n }\n }\n\n throw new Error(\n 'Invalid hex string! Allowed RGB formats are \"#FFF\" and \"#FFFFFF\". Allowed RGBA formats are \"#FFFF\" and \"#FFFFFFFF'\n );\n};\n\n/** @public */\nexport const isValidHexColor = (hexString: string): boolean => {\n return HEX_COLOR_PATTERN.test(hexString);\n};\n", "import type CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { CreativeEngine } from '@cesdk/cesdk-js';\n\n/**\n * Uploads a blob with the help of CE.SDK\n */\nexport async function uploadBlob(\n blob: Blob,\n initialUri: string,\n cesdk: CreativeEditorSDK\n) {\n const pathname = new URL(initialUri).pathname;\n const parts = pathname.split('/');\n const extension = mimeTypeToExtension(blob.type);\n const filename = parts[parts.length - 1]?.split('.')?.[0] ?? 'asset';\n const filenameWithExtension = `${filename}.${extension}`;\n\n const uploadedAssets = await cesdk.unstable_upload(\n new File([blob], filenameWithExtension, { type: blob.type }),\n () => {\n // TODO Delegate process to UI component\n }\n );\n\n const url = uploadedAssets.meta?.uri;\n if (url == null) {\n throw new Error('Could not upload processed fill');\n }\n return url;\n}\n\n/**\n * Returns the file extension for a given mime type.\n */\nexport function mimeTypeToExtension(mimeType: string): string {\n const extensions: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'image/svg+xml': 'svg'\n };\n return extensions[mimeType] ?? 'png';\n}\n\nexport async function fetchImageBlob(uri: string): Promise<Blob> {\n return fetch(uri).then((response) => response.blob());\n}\n\n/**\n * Converts a buffer URI to a object url.\n */\nexport async function bufferURIToObjectURL(\n uri: string,\n engine: CreativeEngine\n): Promise<string> {\n if (uri.startsWith('buffer:')) {\n const mimeType = await engine.editor.getMimeType(uri);\n const length = engine.editor.getBufferLength(uri);\n const data = engine.editor.getBufferData(uri, 0, length);\n const blob = new Blob([data], { type: mimeType });\n return URL.createObjectURL(blob);\n } else {\n return uri;\n }\n}\n", "function uuid4() {\n /* eslint-disable no-bitwise */\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n /* eslint-enable no-bitwise */\n });\n}\n\nexport default uuid4;\n", "import { bufferURIToObjectURL } from './upload';\nimport { type CreativeEngine } from '@cesdk/cesdk-js';\n\n/**\n * Get the dimensions of an image from its URL\n *\n * @param url - The URL of the image\n * @returns A promise that resolves to an object containing the width and height of the image\n */\nexport async function getImageDimensionsFromURL(\n url: string,\n engine: CreativeEngine\n): Promise<{ width: number; height: number }> {\n const resolvedUrl = await bufferURIToObjectURL(url, engine);\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => {\n resolve({ width: img.width, height: img.height });\n };\n img.onerror = reject;\n img.src = resolvedUrl;\n });\n}\n\n/**\n * Get the URI of an image from a block ID, either the first source of a source set or\n * the image file URI. Will handle buffer URIs and convert them to object URLs.\n */\nexport async function getImageUri(\n blockId: number,\n engine: CreativeEngine,\n options?: { throwErrorIfSvg?: boolean }\n): Promise<string> {\n let uri;\n const fillBlock = engine.block.getFill(blockId);\n const sourceSet = engine.block.getSourceSet(\n fillBlock,\n 'fill/image/sourceSet'\n );\n const [source] = sourceSet;\n if (source == null) {\n uri = engine.block.getString(fillBlock, 'fill/image/imageFileURI');\n if (uri == null) throw new Error('No image source/uri found');\n } else {\n uri = source.uri;\n }\n\n // Check if the image is SVG (not supported)\n if (options?.throwErrorIfSvg) {\n const mimeType = await engine.editor.getMimeType(uri);\n if (mimeType === 'image/svg+xml') {\n throw new Error('SVG images are not supported');\n }\n }\n\n return bufferURIToObjectURL(uri, engine);\n}\n", "import formatsIconSprite from './icons/formats';\n\nconst Icons = {\n Formats: formatsIconSprite\n};\n\nexport { Icons };\n\nexport { CustomAssetSource } from './assetSources/CustomAssetSource';\n\nexport { IndexedDBAssetSource } from './assetSources/IndexedDBAssetSource';\n\nexport { AggregatedAssetSource } from './assetSources/AggregatedAssetSource';\n\nexport { default as Metadata } from './metadata/Metadata';\n\nexport { default as FillProcessingMetadata } from './metadata/FillProcessingMetadata';\n\nexport { default as fillProcessing } from './processing/fillProcessing';\n\nexport { default as initializeFillProcessing } from './processing/initializeFillProcessing';\n\nexport { default as registerFillProcessingComponents } from './processing/registerFillProcessingComponents';\n\nexport { type Optional } from './types/Optional';\n\nexport {\n type Location,\n type UserInterfaceConfiguration\n} from './types/UserInterfaceConfiguration';\n\nexport { hexToRgba, isValidHexColor, rgbaToHex } from './utils/colors';\n\nexport {\n uploadBlob,\n fetchImageBlob,\n bufferURIToObjectURL,\n mimeTypeToExtension\n} from './utils/upload';\n\nexport { default as uuid } from './utils/uuid';\n\nexport { getImageDimensionsFromURL, getImageUri } from './utils/images';\n", "import CreativeEditorSDK, { AssetResult } from '@cesdk/cesdk-js';\nimport { RenderCustomProperty } from '../generation/provider';\n\n/**\n * Provides render function for a image url property that allows\n * to select an image from the library with a MediaPreview\n *\n * By default this expects the property key to be `image_url`. This can be changed in the options.\n */\nfunction renderImageUrlProperty(\n provderId: string,\n options: {\n cesdk: CreativeEditorSDK;\n propertyKey?: string;\n defaultUrl?: string;\n }\n): RenderCustomProperty {\n const { cesdk } = options;\n const propertyKey = options.propertyKey ?? 'image_url';\n\n createPanels(provderId, cesdk);\n\n const customProperties: RenderCustomProperty = {\n [propertyKey]: (context, property) => {\n const {\n builder,\n experimental: { global },\n payload\n } = context;\n const defaultUrl = payload?.url ?? options.defaultUrl;\n const stateValue = global<string>(\n `${provderId}.${property.id}`,\n defaultUrl\n );\n\n builder.MediaPreview(property.id, {\n preview: {\n type: 'image',\n uri: stateValue.value\n },\n action: {\n label: 'Select Image',\n onClick: () => {\n if (cesdk == null) return;\n\n const panelId = getImageSelectionPanelId(provderId);\n cesdk.ui.openPanel(panelId, {\n payload: {\n onSelect: (assetResult: AssetResult) => {\n if (assetResult.meta?.uri != null) {\n stateValue.setValue(assetResult.meta?.uri);\n }\n }\n }\n });\n }\n }\n });\n\n return () => {\n return {\n id: property.id,\n type: 'string',\n value: stateValue.value\n };\n };\n }\n };\n\n return customProperties;\n}\n\nfunction createPanels(providerId: string, cesdk?: CreativeEditorSDK) {\n if (cesdk == null) return;\n\n cesdk.ui.registerPanel<{\n onSelect: (assetResult: AssetResult) => void;\n }>(getImageSelectionPanelId(providerId), ({ builder, payload }) => {\n builder.Library(`${providerId}.library.image`, {\n entries: ['ly.img.image'],\n onSelect: async (asset) => {\n const uri = asset?.meta?.uri;\n if (uri == null) return;\n\n const mimeType = await cesdk.engine.editor.getMimeType(uri);\n if (mimeType === 'image/svg+xml') {\n cesdk.ui.showNotification({\n type: 'warning',\n message:\n 'SVG images are not supported. Please choose a different image.'\n });\n } else if (mimeType.startsWith('image/')) {\n payload?.onSelect(asset);\n cesdk?.ui.closePanel(getImageSelectionPanelId(providerId));\n } else {\n cesdk.ui.showNotification({\n type: 'warning',\n message: `Only images are supported. Found '${mimeType}'. Please choose a different image.`\n });\n }\n }\n });\n });\n}\n\nfunction getImageSelectionPanelId(providerId: string) {\n return `ly.img.ai/${providerId}.imageSelection`;\n}\n\nexport default renderImageUrlProperty;\n", "import { type OpenAPIV3 } from 'openapi-types';\n\n/**\n * Resolves a JSON reference path within a document\n * @param document The OpenAPI document\n * @param refPath The reference path (e.g. \"#/components/schemas/MySchema\")\n * @returns The resolved object from the document\n */\nexport function resolveReference(\n document: OpenAPIV3.Document,\n refPath: string\n): unknown {\n // Only handle internal references\n if (!refPath.startsWith('#/')) {\n throw new Error(`External references are not supported: ${refPath}`);\n }\n\n // Remove the leading #/\n const path = refPath.substring(2).split('/');\n let current: any = document;\n\n // Navigate through the path\n for (const segment of path) {\n if (current === undefined || current === null) {\n throw new Error(`Invalid reference path: ${refPath}`);\n }\n current = current[segment];\n }\n\n if (current === undefined) {\n throw new Error(`Reference not found: ${refPath}`);\n }\n\n return current;\n}\n\n/**\n * Recursively dereferences all $ref properties in an object\n * @param document The original document for resolving references\n * @param obj The object to dereference\n * @param visited Set of visited objects to prevent circular references\n * @returns The dereferenced object\n */\nfunction dereferenceObject(\n document: OpenAPIV3.Document,\n obj: any,\n visited = new Set<any>()\n): any {\n // Handle null or undefined\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n // If we've seen this object before, return it to avoid circular references\n if (visited.has(obj)) {\n return obj;\n }\n\n // Add the current object to the visited set\n visited.add(obj);\n\n // Handle $ref\n if (obj.$ref && typeof obj.$ref === 'string') {\n // Get the referenced object\n const referenced = resolveReference(document, obj.$ref);\n // Dereference the referenced object\n const dereferenced = dereferenceObject(document, referenced, visited);\n\n // Merge other properties from the original object\n const result = { ...dereferenced };\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key) && key !== '$ref') {\n result[key] = dereferenceObject(document, obj[key], visited);\n }\n }\n return result;\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return obj.map((item) => dereferenceObject(document, item, visited));\n }\n\n // Handle objects\n if (typeof obj === 'object') {\n const result: any = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = dereferenceObject(document, obj[key], visited);\n }\n }\n return result;\n }\n\n // Return primitives as is\n return obj;\n}\n\n/**\n * Dereferences all $ref properties in an OpenAPI document\n * @param document The OpenAPI document to dereference\n * @returns A new document with all references resolved\n */\nexport default function dereferenceDocument(\n document: OpenAPIV3.Document\n): OpenAPIV3.Document {\n return dereferenceObject(document, { ...document }) as OpenAPIV3.Document;\n}\n", "import { OpenAPIV3 } from 'openapi-types';\n\n/**\n * Checks if an unknown object is an OpenAPI schema (first level only)\n *\n * @param obj - The object to check (potentially undefined)\n * @param debug - If true, log the reason when validation fails\n * @returns A boolean indicating whether the object is an OpenAPI schema\n */\nexport function isOpenAPISchema(\n obj: unknown,\n debug: boolean = false\n): obj is OpenAPIV3.SchemaObject {\n // Helper function to log debug messages and return false\n const fail = (reason: string): false => {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(`OpenAPI Schema validation failed: ${reason}`);\n }\n return false;\n };\n\n // Check if obj is an object and not null\n if (typeof obj !== 'object' || obj === null) {\n return fail(\n `Input is ${obj === null ? 'null' : typeof obj}, not an object`\n );\n }\n\n const schema = obj as Record<string, any>;\n\n // Basic property validation - most schemas have at least one of these properties\n const hasSchemaTypeProperties =\n typeof schema.type === 'string' ||\n Array.isArray(schema.enum) ||\n typeof schema.properties === 'object' ||\n typeof schema.items === 'object' ||\n typeof schema.allOf === 'object' ||\n typeof schema.anyOf === 'object' ||\n typeof schema.oneOf === 'object' ||\n typeof schema.not === 'object';\n\n if (!hasSchemaTypeProperties) {\n return fail(\n 'Missing required schema-defining properties (type, enum, properties, items, allOf, anyOf, oneOf, not)'\n );\n }\n\n // If it has a type, validate it's one of the allowed OpenAPI schema types\n if (schema.type !== undefined) {\n const validTypes = [\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'array',\n 'object',\n 'null'\n ];\n\n // Type can be a string or an array of strings\n if (typeof schema.type === 'string') {\n if (!validTypes.includes(schema.type)) {\n return fail(\n `Invalid type: ${schema.type}. Must be one of ${validTypes.join(\n ', '\n )}`\n );\n }\n } else if (Array.isArray(schema.type)) {\n for (const type of schema.type) {\n if (typeof type !== 'string' || !validTypes.includes(type)) {\n return fail(\n `Array of types contains invalid value: ${type}. Must be one of ${validTypes.join(\n ', '\n )}`\n );\n }\n }\n } else {\n return fail(\n `Type must be a string or array of strings, got ${typeof schema.type}`\n );\n }\n }\n\n // If it has items (for array type), validate that items is an object (without recursion)\n if (schema.items !== undefined) {\n if (typeof schema.items !== 'object' || schema.items === null) {\n return fail(\n `Items must be an object, got ${\n schema.items === null ? 'null' : typeof schema.items\n }`\n );\n }\n }\n\n // If it has properties (for object type), validate that properties is an object (without recursion)\n if (schema.properties !== undefined) {\n if (typeof schema.properties !== 'object' || schema.properties === null) {\n return fail(\n `Properties must be an object, got ${\n schema.properties === null ? 'null' : typeof schema.properties\n }`\n );\n }\n }\n\n // Check if advanced schema constructs are valid (without recursion)\n const schemaArrays = ['allOf', 'anyOf', 'oneOf'];\n for (const arrayType of schemaArrays) {\n if (schema[arrayType] !== undefined) {\n if (!Array.isArray(schema[arrayType])) {\n return fail(\n `${arrayType} must be an array, got ${typeof schema[arrayType]}`\n );\n }\n\n // Just check that each item is an object (without recursion)\n for (let i = 0; i < schema[arrayType].length; i++) {\n const subSchema = schema[arrayType][i];\n if (typeof subSchema !== 'object' || subSchema === null) {\n return fail(\n `Item ${i} in ${arrayType} must be an object, got ${\n subSchema === null ? 'null' : typeof subSchema\n }`\n );\n }\n }\n }\n }\n\n // Check if 'not' is an object\n if (schema.not !== undefined) {\n if (typeof schema.not !== 'object' || schema.not === null) {\n return fail(\n `'not' must be an object, got ${\n schema.not === null ? 'null' : typeof schema.not\n }`\n );\n }\n }\n\n // If we have additionalProperties, make sure it's a boolean or an object\n if (schema.additionalProperties !== undefined) {\n if (\n typeof schema.additionalProperties !== 'boolean' &&\n (typeof schema.additionalProperties !== 'object' ||\n schema.additionalProperties === null)\n ) {\n return fail(\n `additionalProperties must be a boolean or an object, got ${\n schema.additionalProperties === null\n ? 'null'\n : typeof schema.additionalProperties\n }`\n );\n }\n }\n\n // Check basic format if present (for string type)\n if (schema.format !== undefined && typeof schema.format !== 'string') {\n return fail(`format must be a string, got ${typeof schema.format}`);\n }\n\n // Check number constraints\n const numberConstraints = [\n 'minimum',\n 'maximum',\n 'exclusiveMinimum',\n 'exclusiveMaximum',\n 'multipleOf'\n ];\n for (const constraint of numberConstraints) {\n if (\n schema[constraint] !== undefined &&\n typeof schema[constraint] !== 'number'\n ) {\n return fail(\n `${constraint} must be a number, got ${typeof schema[constraint]}`\n );\n }\n }\n\n // Check string constraints\n if (\n schema.minLength !== undefined &&\n (typeof schema.minLength !== 'number' || schema.minLength < 0)\n ) {\n return fail(\n `minLength must be a non-negative number, got ${\n typeof schema.minLength === 'number'\n ? schema.minLength\n : typeof schema.minLength\n }`\n );\n }\n if (\n schema.maxLength !== undefined &&\n (typeof schema.maxLength !== 'number' || schema.maxLength < 0)\n ) {\n return fail(\n `maxLength must be a non-negative number, got ${\n typeof schema.maxLength === 'number'\n ? schema.maxLength\n : typeof schema.maxLength\n }`\n );\n }\n if (schema.pattern !== undefined && typeof schema.pattern !== 'string') {\n return fail(`pattern must be a string, got ${typeof schema.pattern}`);\n }\n\n // Check array constraints\n if (\n schema.minItems !== undefined &&\n (typeof schema.minItems !== 'number' || schema.minItems < 0)\n ) {\n return fail(\n `minItems must be a non-negative number, got ${\n typeof schema.minItems === 'number'\n ? schema.minItems\n : typeof schema.minItems\n }`\n );\n }\n if (\n schema.maxItems !== undefined &&\n (typeof schema.maxItems !== 'number' || schema.maxItems < 0)\n ) {\n return fail(\n `maxItems must be a non-negative number, got ${\n typeof schema.maxItems === 'number'\n ? schema.maxItems\n : typeof schema.maxItems\n }`\n );\n }\n if (\n schema.uniqueItems !== undefined &&\n typeof schema.uniqueItems !== 'boolean'\n ) {\n return fail(\n `uniqueItems must be a boolean, got ${typeof schema.uniqueItems}`\n );\n }\n\n // Check object constraints\n if (\n schema.minProperties !== undefined &&\n (typeof schema.minProperties !== 'number' || schema.minProperties < 0)\n ) {\n return fail(\n `minProperties must be a non-negative number, got ${\n typeof schema.minProperties === 'number'\n ? schema.minProperties\n : typeof schema.minProperties\n }`\n );\n }\n if (\n schema.maxProperties !== undefined &&\n (typeof schema.maxProperties !== 'number' || schema.maxProperties < 0)\n ) {\n return fail(\n `maxProperties must be a non-negative number, got ${\n typeof schema.maxProperties === 'number'\n ? schema.maxProperties\n : typeof schema.maxProperties\n }`\n );\n }\n if (schema.required !== undefined) {\n if (!Array.isArray(schema.required)) {\n return fail(`required must be an array, got ${typeof schema.required}`);\n }\n for (let i = 0; i < schema.required.length; i++) {\n const prop = schema.required[i];\n if (typeof prop !== 'string') {\n return fail(\n `Item ${i} in required array must be a string, got ${typeof prop}`\n );\n }\n }\n }\n\n // It has passed all the first-level checks\n return true;\n}\n", "import { OpenAPIV3 } from 'openapi-types';\nimport { OutputKind, PanelInputSchema } from '../provider';\nimport { Property } from './types';\n\nfunction getProperties<K extends OutputKind, I>(\n inputSchema: OpenAPIV3.SchemaObject,\n panelInput: PanelInputSchema<K, I>\n): Property[] {\n if (inputSchema.properties == null) {\n throw new Error('Input schema must have properties');\n }\n\n const properties: Property[] = [];\n\n const orderedProperties = getOrderedProperties(inputSchema, panelInput);\n if (orderedProperties != null) {\n return orderedProperties;\n } else {\n Object.entries(inputSchema.properties).forEach((property) => {\n const id = property[0];\n const schema = property[1] as OpenAPIV3.SchemaObject;\n properties.push({ id, schema });\n });\n }\n\n return properties;\n}\n\nfunction getOrderedProperties<K extends OutputKind, I>(\n inputSchema: OpenAPIV3.SchemaObject,\n panelInput: PanelInputSchema<K, I>\n): Property[] | undefined {\n if (panelInput.orderExtensionKeyword == null) {\n return undefined;\n }\n const properties: Property[] = [];\n\n if (\n typeof panelInput.orderExtensionKeyword !== 'string' &&\n !Array.isArray(panelInput.orderExtensionKeyword)\n ) {\n throw new Error(\n 'orderExtensionKeyword must be a string or an array of strings'\n );\n }\n\n const orderExtensionKeywords =\n typeof panelInput.orderExtensionKeyword === 'string'\n ? [panelInput.orderExtensionKeyword]\n : panelInput.orderExtensionKeyword;\n\n const orderExtensionKeyword = orderExtensionKeywords.find(\n (extensionKeyword) => {\n return extensionKeyword in inputSchema;\n }\n );\n\n if (orderExtensionKeyword == null) {\n return undefined;\n }\n const order =\n // @ts-ignore\n inputSchema[orderExtensionKeyword] as string[];\n\n if (order == null || Array.isArray(order) === false) {\n throw new Error(\n `Extension keyword ${orderExtensionKeyword} must be an array of strings`\n );\n }\n\n [...new Set(order)].forEach((orderKey) => {\n const property = inputSchema.properties?.[orderKey];\n if (property != null) {\n properties.push({\n id: orderKey,\n schema: property as OpenAPIV3.SchemaObject\n });\n }\n });\n\n if (properties.length === 0) {\n throw new Error(\n `Could not find any properties with order extension keyword(s) ${orderExtensionKeywords.join(\n ', '\n )}`\n );\n }\n return properties;\n}\n\nexport default getProperties;\n", "import CreativeEditorSDK, { AssetResult } from '@cesdk/cesdk-js';\nimport { GenerationResult, Output } from './generation/provider';\n\nexport const AI_PANEL_ID_PREFIX = 'ly.img.ai';\n\nconst TEMP_ASSET_SOURCE_ID = 'ly.img.ai/temp';\n\n/**\n * Adding asset to the scene.\n *\n * NOTE: Will use a temporary asset source so that\n * our asset source middleware trigger. This is necessary since there is\n * a lot of extra logic in the video middlewares regarding trim, position etc.\n *\n * These will only trigger via an asset source, not by calling\n * `defaultApplyAsset` directly.\n */\nexport async function addAssetToScene(\n cesdk: CreativeEditorSDK,\n assetResult: AssetResult\n) {\n if (!cesdk.engine.asset.findAllSources().includes(TEMP_ASSET_SOURCE_ID)) {\n cesdk.engine.asset.addLocalSource(TEMP_ASSET_SOURCE_ID);\n }\n\n return cesdk.engine.asset.apply(TEMP_ASSET_SOURCE_ID, assetResult);\n}\n\n/**\n * Returns a consistent panel ID for a provider ID\n */\nexport function getPanelId(providerId: string): string {\n return `${AI_PANEL_ID_PREFIX}/${providerId}`;\n}\n\nexport default getPanelId;\n/**\n * Extracts a readable error message from an unknown error\n *\n * @param error The error caught in a try/catch block\n * @param fallbackMessage Optional fallback message if error is not an Error object\n * @returns A string representation of the error\n */\nexport function extractErrorMessage(\n error: unknown,\n fallbackMessage = 'We encountered an unknown error while generating the asset. Please try again.'\n): string {\n if (error === null) {\n return fallbackMessage;\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n if (typeof error === 'object') {\n // Try to get message property if it exists\n const errorObj = error as Record<string, unknown>;\n if ('message' in errorObj && typeof errorObj.message === 'string') {\n return errorObj.message;\n }\n if ('cause' in errorObj && typeof errorObj.cause === 'string') {\n return errorObj.cause;\n }\n\n /*\n * Elevenlabs for instance uses the following structure for errors:\n * {\n * \"detail\": {\n * \"status\": \"error_code\",\n * \"message\": \"Explanation of the rate limit issue.\"\n * }\n * }\n */\n if (\n 'detail' in errorObj &&\n typeof errorObj.detail === 'object' &&\n errorObj.detail !== null &&\n 'message' in errorObj.detail &&\n typeof errorObj.detail.message === 'string'\n ) {\n return errorObj.detail.message;\n }\n\n /*\n * Used by e.g. Anthropic\n */\n if (\n 'error' in errorObj &&\n typeof errorObj.error === 'object' &&\n errorObj.error !== null &&\n 'message' in errorObj.error &&\n typeof errorObj.error.message === 'string'\n ) {\n return errorObj.error.message;\n }\n\n return fallbackMessage;\n }\n\n if (typeof error === 'string') {\n return error;\n }\n\n // For any other type, convert to string\n return String(error) || fallbackMessage;\n}\n\n/**\n * Generates a random UUID v4\n */\nexport function uuid4() {\n /* eslint-disable no-bitwise */\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n /* eslint-enable no-bitwise */\n });\n}\n\n/**\n * Gets the duration of a video from a URL\n * @param url - The URL of the video\n * @returns A promise that resolves to the duration of the video in seconds\n */\nexport function getDurationForVideo(url: string): Promise<number> {\n return new Promise((resolve, reject) => {\n try {\n const video = document.createElement('video');\n video.style.display = 'none';\n\n // Set up event handlers\n video.addEventListener('loadedmetadata', () => {\n if (video.duration === Infinity) {\n // Some videos might initially report Infinity\n video.currentTime = 1e101;\n // Wait for currentTime to update\n setTimeout(() => {\n video.currentTime = 0;\n resolve(video.duration);\n document.body.removeChild(video);\n }, 50);\n } else {\n resolve(video.duration);\n document.body.removeChild(video);\n }\n });\n\n video.addEventListener('error', () => {\n document.body.removeChild(video);\n reject(new Error(`Failed to load video from ${url}`));\n });\n\n // Set source and begin loading\n video.src = url;\n document.body.appendChild(video);\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n * Gets a thumbnail image from a video URL\n * @param url - The URL of the video\n * @param seekTime - Time in seconds to capture the thumbnail (default: 0)\n * @param format - Image format for the thumbnail (default: 'image/jpeg')\n * @param quality - Image quality between 0 and 1 (default: 0.8)\n * @returns A promise that resolves to the thumbnail data URL\n */\nexport function getThumbnailForVideo(\n url: string,\n seekTime = 0,\n format = 'image/jpeg',\n quality = 0.8\n): Promise<string> {\n return new Promise((resolve, reject) => {\n try {\n const video = document.createElement('video');\n // Set crossOrigin to anonymous to prevent tainted canvas issues\n video.crossOrigin = 'anonymous';\n video.style.display = 'none';\n\n // Set up event handlers\n video.addEventListener('loadedmetadata', () => {\n // Seek to the specified time\n video.currentTime = Math.min(seekTime, video.duration);\n\n video.addEventListener(\n 'seeked',\n () => {\n // Create a canvas to draw the video frame\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n\n // Draw the video frame to the canvas\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n document.body.removeChild(video);\n reject(new Error('Failed to create canvas context'));\n return;\n }\n\n ctx.drawImage(video, 0, 0, canvas.width, canvas.height);\n\n try {\n // Convert canvas to data URL\n const dataURL = canvas.toDataURL(format, quality);\n // Clean up\n document.body.removeChild(video);\n resolve(dataURL);\n } catch (e) {\n document.body.removeChild(video);\n reject(\n new Error(\n `Failed to create thumbnail: ${\n e instanceof Error ? e.message : String(e)\n }`\n )\n );\n }\n },\n { once: true }\n );\n });\n\n video.addEventListener('error', () => {\n document.body.removeChild(video);\n reject(new Error(`Failed to load video from ${url}`));\n });\n\n // Set source and begin loading\n video.src = url;\n document.body.appendChild(video);\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n * Converts an ID string to a human-readable label\n * @param id - The ID string to convert\n * @returns A human-readable label derived from the ID\n *\n * Examples:\n * - snake_case_id \u2192 Snake Case Id\n * - kebab-case-id \u2192 Kebab Case Id\n * - camelCaseId \u2192 Camel Case Id\n * - PascalCaseId \u2192 Pascal Case Id\n */\nexport function getLabelFromId(id: string): string {\n if (!id) return '';\n\n // Handle snake_case, kebab-case, camelCase, and PascalCase\n return (\n id\n // Replace underscores and hyphens with spaces (for snake_case and kebab-case)\n .replace(/[_-]/g, ' ')\n // Add spaces before uppercase letters (for camelCase and PascalCase)\n .replace(/([A-Z])/g, ' $1')\n // Trim any extra spaces and ensure first letter is capitalized\n .trim()\n .split(' ')\n .filter((word) => word.length > 0) // Remove empty strings from multiple spaces\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(' ')\n );\n}\n\n/**\n * Type guard to check if a value is an AsyncGenerator rather than a Promise\n *\n * @param value - Value of type Promise<O> | AsyncGenerator<O, C>\n * @returns Boolean indicating if the value is an AsyncGenerator\n */\nexport function isAsyncGenerator<O extends Output, C>(\n value: GenerationResult<O, C>\n): value is AsyncGenerator<O, C> {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'next' in value &&\n 'return' in value &&\n 'throw' in value &&\n typeof value.next === 'function' &&\n typeof value.return === 'function' &&\n typeof value.throw === 'function' &&\n Symbol.asyncIterator in value &&\n typeof value[Symbol.asyncIterator] === 'function'\n );\n}\n\nexport function isAbortError(error: unknown): error is Error {\n return error instanceof Error && error.name === 'AbortError';\n}\n", "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { BuilderRenderFunctionContext } from '@cesdk/cesdk-js';\nimport {\n EnumValue,\n ExtensionImglyBuilder,\n GetPropertyInput,\n Property,\n PropertyInput\n} from './types';\nimport Provider, { Output, OutputKind, PanelInputSchema } from '../provider';\nimport { InitProviderConfiguration, UIOptions } from '../types';\nimport { OpenAPIV3 } from 'openapi-types';\nimport getProperties from './getProperties';\nimport { getLabelFromId } from '../../utils';\n\nfunction renderProperty<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n property: Property,\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): GetPropertyInput | undefined {\n const type = property.schema.type;\n\n if (\n panelInput.renderCustomProperty != null &&\n panelInput.renderCustomProperty[property.id] != null\n ) {\n return panelInput.renderCustomProperty[property.id](context, property);\n }\n\n switch (type) {\n case 'string': {\n if (property.schema.enum != null) {\n return renderEnumProperty(\n context,\n property,\n provider,\n panelInput,\n options,\n config\n );\n } else {\n return renderStringProperty(\n context,\n property,\n provider,\n panelInput,\n options,\n config\n );\n }\n }\n\n case 'boolean': {\n return renderBooleanProperty(\n context,\n property,\n provider,\n panelInput,\n options,\n config\n );\n }\n\n case 'number':\n case 'integer': {\n return renderIntegerProperty(\n context,\n property,\n provider,\n panelInput,\n options,\n config\n );\n }\n\n case 'object': {\n return renderObjectProperty(\n context,\n property,\n provider,\n panelInput,\n options,\n config\n );\n }\n\n case 'array': {\n // not supported yet\n break;\n }\n\n case undefined: {\n if (\n property.schema.anyOf != null &&\n Array.isArray(property.schema.anyOf)\n ) {\n return renderAnyOfProperty(\n context,\n property,\n provider,\n panelInput,\n options,\n config\n );\n }\n break;\n }\n\n default: {\n // eslint-disable-next-line no-console\n console.error(`Unsupported property type: ${type}`);\n }\n }\n}\n\nfunction renderObjectProperty<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n property: Property,\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): GetPropertyInput {\n const properties = getProperties(property.schema ?? {}, panelInput);\n\n const childInputs = properties.reduce((acc, childProperty) => {\n const getInput = renderProperty(\n context,\n childProperty,\n provider,\n panelInput,\n options,\n config\n );\n if (getInput != null) {\n acc[childProperty.id] = getInput();\n }\n return acc;\n }, {} as Record<string, PropertyInput>);\n\n return () => ({\n id: property.id,\n type: 'object',\n value: childInputs\n });\n}\n\nfunction renderStringProperty<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n property: Property,\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): GetPropertyInput {\n const {\n builder,\n experimental: { global }\n } = context;\n const { id: propertyId } = property;\n\n const id = `${provider.id}.${propertyId}`;\n const inputLabel = property.schema.title ?? id;\n\n const propertyState = global(id, property.schema.default ?? '');\n\n const extension = getImglyExtensionBuilder(property.schema);\n const builderComponent =\n extension?.component != null && extension?.component === 'TextArea'\n ? 'TextArea'\n : 'TextInput';\n\n builder[builderComponent](id, {\n inputLabel,\n placeholder: options.i18n?.prompt,\n ...propertyState\n });\n\n return () => ({\n id: property.id,\n type: 'string',\n value: propertyState.value\n });\n}\n\nfunction renderEnumProperty<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n property: Property,\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): GetPropertyInput {\n const {\n builder,\n experimental: { global }\n } = context;\n const { id: propertyId } = property;\n\n const id = `${provider.id}.${propertyId}`;\n const inputLabel = property.schema.title ?? id;\n\n const labels: Record<string, string> =\n property.schema.enum != null &&\n 'x-imgly-enum-labels' in property.schema.enum &&\n typeof property.schema.enum['x-imgly-enum-labels'] === 'object'\n ? (property.schema.enum['x-imgly-enum-labels'] as Record<string, string>)\n : 'x-imgly-enum-labels' in property.schema &&\n typeof property.schema['x-imgly-enum-labels'] === 'object'\n ? (property.schema['x-imgly-enum-labels'] as Record<string, string>)\n : {};\n\n const icons: Record<string, string> =\n 'x-imgly-enum-icons' in property.schema &&\n typeof property.schema['x-imgly-enum-icons'] === 'object'\n ? (property.schema['x-imgly-enum-icons'] as Record<string, string>)\n : {};\n\n const values: EnumValue[] = (property.schema.enum ?? []).map((valueId) => ({\n id: valueId,\n label: labels[valueId] ?? getLabelFromId(valueId),\n icon: icons[valueId]\n }));\n const defaultValue =\n property.schema.default != null\n ? values.find((v) => v.id === property.schema.default) ?? values[0]\n : values[0];\n\n const propertyState = global<EnumValue>(id, defaultValue);\n\n builder.Select(id, {\n inputLabel,\n values,\n ...propertyState\n });\n\n return () => ({\n id: property.id,\n type: 'string',\n value: propertyState.value.id\n });\n}\n\nfunction renderBooleanProperty<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n property: Property,\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): GetPropertyInput {\n const {\n builder,\n experimental: { global }\n } = context;\n const { id: propertyId } = property;\n\n const id = `${provider.id}.${propertyId}`;\n const inputLabel = property.schema.title ?? id;\n\n const defaultValue = !!property.schema.default;\n const propertyState = global<boolean>(id, defaultValue);\n\n builder.Checkbox(id, {\n inputLabel,\n ...propertyState\n });\n\n return () => ({\n id: property.id,\n type: 'boolean',\n value: propertyState.value\n });\n}\n\nfunction renderIntegerProperty<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n property: Property,\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): GetPropertyInput {\n const {\n builder,\n experimental: { global }\n } = context;\n const { id: propertyId } = property;\n\n const id = `${provider.id}.${propertyId}`;\n const inputLabel = property.schema.title ?? id;\n\n const minValue = property.schema.minimum;\n const maxValue = property.schema.maximum;\n\n let defaultValue = property.schema.default;\n if (defaultValue == null) {\n if (minValue != null) {\n defaultValue = minValue;\n } else if (maxValue != null) {\n defaultValue = maxValue;\n } else {\n defaultValue = 0;\n }\n }\n\n const propertyState = global<number>(id, defaultValue);\n\n if (minValue != null && maxValue != null) {\n let step = property.schema.type === 'number' ? 0.1 : 1;\n if (\n 'x-imgly-step' in property.schema &&\n typeof property.schema['x-imgly-step'] === 'number'\n ) {\n step = property.schema['x-imgly-step'];\n }\n\n builder.Slider(id, {\n inputLabel,\n min: minValue,\n max: maxValue,\n step,\n ...propertyState\n });\n } else {\n builder.NumberInput(id, {\n inputLabel,\n min: minValue,\n max: maxValue,\n ...propertyState\n });\n }\n\n return () => ({\n id: property.id,\n type: 'integer',\n value: propertyState.value\n });\n}\n\nfunction renderAnyOfProperty<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n property: Property,\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): GetPropertyInput | undefined {\n const {\n builder,\n experimental: { global }\n } = context;\n const { id: propertyId } = property;\n\n const id = `${provider.id}.${propertyId}`;\n const inputLabel = property.schema.title ?? id;\n\n const anyOf = (property.schema.anyOf ?? []) as OpenAPIV3.SchemaObject[];\n\n const values: EnumValue[] = [];\n\n const conditionalRender: Record<string, () => GetPropertyInput> = {};\n const conditionalInputs: Record<string, () => PropertyInput> = {};\n\n anyOf.forEach((anySchema, index) => {\n const label = anySchema.title ?? 'common.custom';\n const schemaId = `${provider.id}.${propertyId}.anyOf[${index}]`;\n\n const labels: Record<string, string> =\n 'x-imgly-enum-labels' in property.schema &&\n typeof property.schema['x-imgly-enum-labels'] === 'object'\n ? (property.schema['x-imgly-enum-labels'] as Record<string, string>)\n : {};\n\n const icons: Record<string, string> =\n 'x-imgly-enum-icons' in property.schema &&\n typeof property.schema['x-imgly-enum-icons'] === 'object'\n ? (property.schema['x-imgly-enum-icons'] as Record<string, string>)\n : {};\n\n if (anySchema.type === 'string') {\n if (anySchema.enum != null) {\n anySchema.enum.forEach((valueId) => {\n values.push({\n id: valueId,\n label: labels[valueId] ?? getLabelFromId(valueId),\n icon: icons[valueId]\n });\n });\n } else {\n conditionalRender[schemaId] = () => {\n return renderStringProperty(\n context,\n { id: schemaId, schema: { ...anySchema, title: label } },\n provider,\n panelInput,\n options,\n config\n );\n };\n\n values.push({\n id: schemaId,\n label: labels[label] ?? label,\n icon: icons[label]\n });\n }\n } else if (anySchema.type === 'boolean') {\n conditionalRender[schemaId] = () => {\n return renderBooleanProperty(\n context,\n { id: schemaId, schema: { ...anySchema, title: label } },\n provider,\n panelInput,\n options,\n config\n );\n };\n\n values.push({\n id: schemaId,\n label: labels[label] ?? label,\n icon: icons[label]\n });\n } else if (anySchema.type === 'integer') {\n conditionalRender[schemaId] = () => {\n return renderIntegerProperty(\n context,\n { id: schemaId, schema: { ...anySchema, title: label } },\n provider,\n panelInput,\n options,\n config\n );\n };\n\n values.push({\n id: schemaId,\n label: labels[label] ?? label,\n icon: icons[label]\n });\n } else if (anySchema.type === 'array') {\n // not supported yet\n } else if (anySchema.type === 'object') {\n conditionalRender[schemaId] = () => {\n return renderObjectProperty(\n context,\n { id: schemaId, schema: { ...anySchema, title: label } },\n provider,\n panelInput,\n options,\n config\n );\n };\n\n values.push({\n id: schemaId,\n label: labels[label] ?? label,\n icon: icons[label]\n });\n }\n });\n\n const defaultValue =\n property.schema.default != null\n ? values.find((value) => value.id === property.schema.default) ??\n values[0]\n : values[0];\n\n const propertyState = global<EnumValue>(id, defaultValue);\n\n builder.Select(id, {\n inputLabel,\n values,\n ...propertyState\n });\n\n if (propertyState.value.id in conditionalRender) {\n const inputs = conditionalRender[propertyState.value.id]();\n conditionalInputs[propertyState.value.id] = inputs;\n }\n\n return () => {\n const conditionalInput = conditionalInputs[propertyState.value.id];\n\n if (conditionalInput != null) {\n return {\n ...conditionalInput(),\n id: property.id\n };\n }\n\n return {\n id: property.id,\n type: 'string',\n value: propertyState.value.id\n };\n };\n}\n\nfunction getImglyExtensionBuilder(\n schema: OpenAPIV3.SchemaObject\n): ExtensionImglyBuilder | undefined {\n if ('x-imgly-builder' in schema) {\n const extension = schema['x-imgly-builder'] as ExtensionImglyBuilder;\n return extension;\n }\n\n return undefined;\n}\n\nexport default renderProperty;\n", "const previewUri =\n 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3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AxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==';\n\nexport default previewUri;\n", "import { type AssetResult } from '@cesdk/cesdk-js';\nimport { type OutputKind, GetBlockInputResult, InputByKind } from './provider';\nimport previewUri from './previewUri';\n\nfunction getAssetResultForPlaceholder<K extends OutputKind>(\n id: string,\n kind: K,\n blockInput: GetBlockInputResult<K>\n): AssetResult {\n switch (kind) {\n case 'image': {\n return getImageAssetResultForPlaceholder(\n id,\n blockInput[kind] as InputByKind['image']\n );\n }\n case 'video': {\n return getVideoAssetResultForPlaceholder(\n id,\n blockInput[kind] as InputByKind['video']\n );\n }\n\n default: {\n throw new Error(\n `Unsupported output kind for creating placeholder block: ${kind}`\n );\n }\n }\n}\n\nfunction getImageAssetResultForPlaceholder(\n id: string,\n input: InputByKind['image']\n): AssetResult {\n const width = input.width;\n const height = input.height;\n return {\n id,\n meta: {\n previewUri,\n fillType: '//ly.img.ubq/fill/image',\n kind: 'image',\n\n width,\n height\n }\n };\n}\n\nfunction getVideoAssetResultForPlaceholder(\n id: string,\n input: InputByKind['video']\n): AssetResult {\n const width = input.width;\n const height = input.height;\n return {\n id,\n label: input.label,\n meta: {\n previewUri,\n mimeType: 'video/mp4',\n kind: 'video',\n fillType: '//ly.img.ubq/fill/video',\n\n duration: input.duration.toString(),\n\n width,\n height\n }\n };\n}\n\nexport default getAssetResultForPlaceholder;\n", "import { type AssetResult } from '@cesdk/cesdk-js';\nimport {\n type OutputKind,\n AudioOutput,\n GetBlockInputResult,\n ImageOutput,\n InputByKind,\n Output,\n VideoOutput\n} from './provider';\nimport { getThumbnailForVideo } from '../utils';\n\nasync function getAssetResultForGenerated<K extends OutputKind>(\n id: string,\n kind: K,\n blockInputs: GetBlockInputResult<K>,\n output: Output\n): Promise<AssetResult> {\n switch (kind) {\n case 'image': {\n if (output.kind !== 'image') {\n throw new Error(\n `Output kind does not match the expected type: ${output.kind} (expected: image)`\n );\n }\n\n return getImageAssetResultForGenerated(\n id,\n blockInputs[kind] as InputByKind['image'],\n output\n );\n }\n\n case 'video': {\n if (output.kind !== 'video') {\n throw new Error(\n `Output kind does not match the expected type: ${output.kind} (expected: video)`\n );\n }\n\n return getVideoAssetResultForGenerated(\n id,\n blockInputs[kind] as InputByKind['video'],\n output\n );\n }\n\n case 'audio': {\n if (output.kind !== 'audio') {\n throw new Error(\n `Output kind does not match the expected type: ${output.kind} (expected: audio)`\n );\n }\n\n return getAudioAssetResultForGenerated(\n id,\n blockInputs[kind] as InputByKind['audio'],\n output\n );\n }\n\n default: {\n throw new Error(\n `Unsupported output kind for creating placeholder block: ${kind}`\n );\n }\n }\n}\n\nfunction getImageAssetResultForGenerated(\n id: string,\n input: InputByKind['image'],\n output: ImageOutput\n): AssetResult {\n const width = input.width;\n const height = input.height;\n return {\n id,\n label: input.label,\n meta: {\n uri: output.url,\n thumbUri: output.url,\n fillType: '//ly.img.ubq/fill/image',\n kind: 'image',\n\n width,\n height\n },\n payload: {\n sourceSet: [\n {\n uri: output.url,\n width,\n height\n }\n ]\n }\n };\n}\n\nasync function getVideoAssetResultForGenerated(\n id: string,\n input: InputByKind['video'],\n output: VideoOutput\n): Promise<AssetResult> {\n const width = input.width;\n const height = input.height;\n\n const thumbUri = await getThumbnailForVideo(output.url, 0);\n\n return {\n id,\n label: input.label,\n meta: {\n uri: output.url,\n thumbUri,\n\n mimeType: 'video/mp4',\n kind: 'video',\n fillType: '//ly.img.ubq/fill/video',\n\n duration: input.duration.toString(),\n\n width,\n height\n }\n };\n}\n\nfunction getAudioAssetResultForGenerated(\n id: string,\n input: InputByKind['audio'],\n output: AudioOutput\n): AssetResult {\n return {\n id,\n label: input.label,\n meta: {\n uri: output.url,\n thumbUri: output.thumbnailUrl,\n blockType: '//ly.img.ubq/audio',\n mimeType: 'audio/x-m4a',\n duration: output.duration.toString()\n }\n };\n}\n\nexport default getAssetResultForGenerated;\n", "import { GenerationOptions, GenerationResult, Output } from '../provider';\n\n/**\n * Result of the generation with a dispose function to clean up\n */\nexport interface DisposableGenerationResult<O extends Output> {\n /**\n * The actual generation result\n */\n result: GenerationResult<O>;\n\n /**\n * Function to dispose/clean up resources created during generation\n * This should be called when the generation is cancelled or completely\n * finished including the confirmation of the generation if applicable.\n */\n dispose: () => Promise<void>;\n}\n\n/**\n * Define the type for middleware functions\n */\nexport type Middleware<I, O extends Output> = (\n input: I,\n options: GenerationOptions & {\n /**\n * The block ids the generation is applied on\n * If this value is undefined, the selected blocks will be used.\n * Setting this value to null will explicitly tell every\n * middleware that no block shall be used.\n */\n blockIds?: number[] | null;\n\n /**\n * Adds a disposer function to this genereation which is called\n * when the generation is cancelled or completely finished\n * including the confirmation of the generation if applicable.\n */\n addDisposer: (dispose: () => Promise<void>) => void;\n },\n next: (input: I, options: GenerationOptions) => Promise<GenerationResult<O>>\n) => Promise<GenerationResult<O>>;\n\nexport function composeMiddlewares<I, O extends Output>(\n middlewares: (Middleware<I, O> | false | undefined | null)[]\n) {\n // Filter out false, undefined, and null middlewares\n const validMiddlewares = middlewares.filter(\n (middleware): middleware is Middleware<I, O> => !!middleware\n );\n // Start with the base handler\n return (\n baseHandler: (\n input: I,\n options: GenerationOptions\n ) => Promise<GenerationResult<O>>\n ) => {\n // We need to build a chain where each step is a function with the signature:\n // (input, options) => Promise<Result>\n\n // The composed function that will be returned\n return async (\n input: I,\n options: GenerationOptions\n ): Promise<DisposableGenerationResult<O>> => {\n // Store disposer functions that will be called when dispose() is called\n const disposers: Array<() => Promise<void>> = [];\n\n // Function to add a disposer\n const addDisposer = (dispose: () => Promise<void>) => {\n disposers.push(dispose);\n };\n\n // Define a function to process each middleware in sequence\n const runMiddleware = async (\n index: number,\n currentInput: I,\n currentOptions: GenerationOptions\n ): Promise<GenerationResult<O>> => {\n // If we've processed all middlewares, call the base handler\n if (index >= validMiddlewares.length) {\n return baseHandler(currentInput, currentOptions);\n }\n\n // Get the current middleware\n const currentMiddleware = validMiddlewares[index];\n\n // Create a next function for this middleware that calls the next middleware in line\n const next = async (\n nextInput: I,\n nextOptions: GenerationOptions\n ): Promise<GenerationResult<O>> => {\n return runMiddleware(index + 1, nextInput, nextOptions);\n };\n\n // Enhanced options with addDisposer\n const enhancedOptions = {\n ...currentOptions,\n addDisposer\n };\n\n // Call the current middleware with the input, enhanced options, and next function\n return currentMiddleware(currentInput, enhancedOptions, next);\n };\n\n // Create enhanced options with addDisposer for base handler as well\n const enhancedOptions = {\n ...options,\n addDisposer\n };\n\n // Run the middleware chain\n const result = await runMiddleware(0, input, enhancedOptions);\n\n // Create the dispose function that will call all collected disposers in reverse order\n const dispose = async (): Promise<void> => {\n // Execute disposers in reverse order (last added, first disposed)\n /* eslint-disable no-await-in-loop */\n for (let i = disposers.length - 1; i >= 0; i--) {\n try {\n await disposers[i]();\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Error in disposer:', error);\n }\n }\n // Clear the disposers array after all are executed\n disposers.length = 0;\n };\n\n // Return both the result and the dispose function\n return {\n result,\n dispose\n };\n };\n };\n}\n", "/* eslint-disable no-console */\nimport { GenerationResult, Output } from '../provider';\nimport { Middleware } from './middleware';\n\nfunction loggingMiddleware<I, O extends Output>() {\n const middleware: Middleware<I, O> = async (input, options, next) => {\n console.group('[GENERATION]');\n console.log(`Generating with input:`, JSON.stringify(input, null, 2));\n let result: GenerationResult<O> | undefined;\n const start = Date.now();\n try {\n result = await next(input, options);\n return result;\n } finally {\n if (result != null) {\n console.log(`Generation took ${Date.now() - start}ms`);\n console.log(`Generation result:`, JSON.stringify(result, null, 2));\n }\n console.groupEnd();\n }\n };\n\n return middleware;\n}\n\nexport default loggingMiddleware;\n", "export default `\n<svg>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratioFree\"\n >\n <path d=\"M7 6C6.44772 6 6 6.44772 6 7V9.22222H4V7C4 5.34315 5.34315 4 7 4H9.22222V6H7Z\" fill=\"currentColor\"/>\n <path d=\"M17 6H14.7778V4H17C18.6569 4 20 5.34315 20 7V9.22222H18V7C18 6.44772 17.5523 6 17 6Z\" fill=\"currentColor\"/>\n <path d=\"M6 14.7778V17C6 17.5523 6.44772 18 7 18H9.22222V20H7C5.34315 20 4 18.6569 4 17V14.7778H6Z\" fill=\"currentColor\"/>\n <path d=\"M18 17V14.7778H20V17C20 18.6569 18.6569 20 17 20H14.7778V18H17C17.5523 18 18 17.5523 18 17Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio4by3\"\n >\n <path d=\"M6.5 13H8V15H10V16.5H6.5V13Z\" fill=\"currentColor\"/>\n <path d=\"M14 9V7.5H17.5V11H16V9H14Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M6 4C4.34315 4 3 5.34315 3 7V17C3 18.6569 4.34315 20 6 20H18C19.6569 20 21 18.6569 21 17V7C21 5.34315 19.6569 4 18 4H6ZM5 7C5 6.44772 5.44772 6 6 6H18C18.5523 6 19 6.44772 19 7V17C19 17.5523 18.5523 18 18 18H6C5.44772 18 5 17.5523 5 17V7Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio16by9\"\n >\n <path d=\"M4.5 13H6V15H8V16.5H4.5V13Z\" fill=\"currentColor\"/>\n <path d=\"M16 9V7.5H19.5V11H18V9H16Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M4 4C2.34315 4 1 5.34315 1 7V17C1 18.6569 2.34315 20 4 20H20C21.6569 20 23 18.6569 23 17V7C23 5.34315 21.6569 4 20 4H4ZM3 7C3 6.44772 3.44772 6 4 6H20C20.5523 6 21 6.44772 21 7V17C21 17.5523 20.5523 18 20 18H4C3.44772 18 3 17.5523 3 17V7Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio9by16\"\n >\n <path d=\"M7.5 16H9V18H11V19.5H7.5V16Z\" fill=\"currentColor\"/>\n <path d=\"M13 6V4.5H16.5V8H15V6H13Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M4 20C4 21.6569 5.34315 23 7 23H17C18.6569 23 20 21.6569 20 20V4C20 2.34315 18.6569 1 17 1H7C5.34315 1 4 2.34315 4 4V20ZM7 21C6.44772 21 6 20.5523 6 20V4C6 3.44772 6.44772 3 7 3H17C17.5523 3 18 3.44772 18 4V20C18 20.5523 17.5523 21 17 21H7Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio3by4\"\n >\n <path d=\"M11 17.5V16H9V14H7.5V17.5H11Z\" fill=\"currentColor\"/>\n <path d=\"M15 10H16.5V6.5H13V8H15V10Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M20 18C20 19.6569 18.6569 21 17 21H7C5.34315 21 4 19.6569 4 18V6C4 4.34315 5.34315 3 7 3H17C18.6569 3 20 4.34315 20 6V18ZM17 19C17.5523 19 18 18.5523 18 18V6C18 5.44772 17.5523 5 17 5H7C6.44771 5 6 5.44771 6 6V18C6 18.5523 6.44772 19 7 19H17Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio1by1\"\n >\n <path d=\"M17.4142 8.00009L16 6.58587L14.2929 8.29298L15.7071 9.70719L17.4142 8.00009Z\" fill=\"currentColor\"/>\n <path d=\"M13.0404 12.3739L15.0404 10.3739L13.6262 8.95965L11.6262 10.9596L13.0404 12.3739Z\" fill=\"currentColor\"/>\n <path d=\"M10.3737 15.0405L12.3737 13.0405L10.9595 11.6263L8.95953 13.6263L10.3737 15.0405Z\" fill=\"currentColor\"/>\n <path d=\"M9.70708 15.7072L8.29286 14.293L6.58576 16.0001L7.99997 17.4143L9.70708 15.7072Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M7 4C5.34315 4 4 5.34315 4 7V17C4 18.6569 5.34315 20 7 20H17C18.6569 20 20 18.6569 20 17V7C20 5.34315 18.6569 4 17 4H7ZM6 7C6 6.44772 6.44772 6 7 6H17C17.5523 6 18 6.44772 18 7V17C18 17.5523 17.5523 18 17 18H7C6.44772 18 6 17.5523 6 17V7Z\" fill=\"currentColor\"/>\n </symbol>\n</svg>\n`;\n", "import type {\n AssetDefinition,\n AssetQueryData,\n AssetResult,\n AssetSource,\n AssetsQueryResult\n} from '@cesdk/engine';\n\n/**\n * Simplified value type for select inputs that can be converted to asset definitions\n */\nexport type SelectValue = {\n id: string;\n label: string;\n thumbUri?: string;\n};\n\n/**\n * A custom AssetSource implementation that manages assets from an array\n * and provides additional functionality like to mark assets as active or changing\n * labels.\n */\nexport class CustomAssetSource implements AssetSource {\n /** The unique id of the asset source */\n id: string;\n\n /** Array of assets to be served by this source */\n private assets: AssetDefinition[];\n\n /** Set of IDs for active assets */\n private activeAssetIds: Set<string>;\n\n /**\n * Creates a new instance of CustomAssetSource\n *\n * @param id - The unique identifier for this asset source\n * @param assets - Array of asset definitions or SelectValue objects to include in this source\n */\n constructor(id: string, assets: (AssetDefinition | SelectValue)[] = []) {\n this.id = id;\n this.assets = assets.map((asset) => {\n // Check if the asset is a SelectValue by looking for the label property as a string\n if (\n typeof (asset as SelectValue).label === 'string' &&\n !(\n (asset as AssetDefinition).label &&\n typeof (asset as AssetDefinition).label === 'object'\n )\n ) {\n const selectValue = asset as SelectValue;\n // Convert SelectValue to AssetDefinition\n return {\n id: selectValue.id,\n label: { en: selectValue.label },\n meta: selectValue.thumbUri\n ? { thumbUri: selectValue.thumbUri }\n : undefined\n } as AssetDefinition;\n }\n return asset as AssetDefinition;\n });\n this.activeAssetIds = new Set<string>();\n }\n\n /**\n * Find assets based on the provided query data\n * Supports pagination, searching, filtering, and active-first sorting\n *\n * @param queryData - Query parameters to filter and sort assets\n * @returns Promise with the query results\n */\n async findAssets(\n queryData: AssetQueryData\n ): Promise<AssetsQueryResult | undefined> {\n const {\n page,\n perPage,\n locale = 'en',\n sortActiveFirst,\n query,\n tags,\n groups,\n excludeGroups,\n sortingOrder,\n sortKey\n } = queryData;\n\n // Start with all assets\n let filteredAssets = [...this.assets];\n\n // Filter by groups if provided\n if (groups && groups.length > 0) {\n filteredAssets = filteredAssets.filter(\n (asset) =>\n asset.groups && groups.some((group) => asset.groups?.includes(group))\n );\n }\n\n // Filter out excluded groups if provided\n if (excludeGroups && excludeGroups.length > 0) {\n filteredAssets = filteredAssets.filter(\n (asset) =>\n !asset.groups ||\n !excludeGroups.some((group) => asset.groups?.includes(group))\n );\n }\n\n // Filter by query (search in label and tags)\n if (query) {\n const lowerQuery = query.toLowerCase();\n filteredAssets = filteredAssets.filter((asset) => {\n const label = asset.label?.[locale]?.toLowerCase();\n const assetTags = asset.tags?.[locale] || [];\n\n return (\n (label && label.includes(lowerQuery)) ||\n assetTags.some((tag) => tag.toLowerCase().includes(lowerQuery))\n );\n });\n }\n\n // Filter by exact tags if provided\n if (tags && tags.length > 0) {\n const tagArray = Array.isArray(tags) ? tags : [tags];\n filteredAssets = filteredAssets.filter((asset) => {\n const assetTags = asset.tags?.[locale] || [];\n return tagArray.some((tag) => assetTags.includes(tag));\n });\n }\n\n // Sort by active first if requested\n if (sortActiveFirst) {\n filteredAssets.sort((a, b) => {\n const aActive = this.activeAssetIds.has(a.id);\n const bActive = this.activeAssetIds.has(b.id);\n\n if (aActive && !bActive) return -1;\n if (!aActive && bActive) return 1;\n return 0;\n });\n }\n\n // Sort by sortKey if provided\n if (sortKey && sortKey !== 'id') {\n filteredAssets.sort((a, b) => {\n // Sort by metadata field\n const aValue = a.meta?.[sortKey];\n const bValue = b.meta?.[sortKey];\n\n if (aValue === undefined) return 1;\n if (bValue === undefined) return -1;\n\n if (typeof aValue === 'string' && typeof bValue === 'string') {\n return sortingOrder === 'Descending'\n ? bValue.localeCompare(aValue)\n : aValue.localeCompare(bValue);\n }\n\n if (typeof aValue === 'number' && typeof bValue === 'number') {\n return sortingOrder === 'Descending'\n ? bValue - aValue\n : aValue - bValue;\n }\n\n return 0;\n });\n } else if (sortKey === 'id') {\n // Sort by id\n filteredAssets.sort((a, b) => {\n return sortingOrder === 'Descending'\n ? b.id.localeCompare(a.id)\n : a.id.localeCompare(b.id);\n });\n }\n\n // Calculate pagination\n const total = filteredAssets.length;\n const startIndex = page * perPage;\n const endIndex = startIndex + perPage;\n const paginatedAssets = filteredAssets.slice(startIndex, endIndex);\n\n // Transform AssetDefinition objects to AssetResult objects\n const resultAssets: AssetResult[] = paginatedAssets.map((asset) => {\n return {\n id: asset.id,\n groups: asset.groups,\n meta: asset.meta,\n payload: asset.payload,\n locale,\n label: asset.label?.[locale],\n tags: asset.tags?.[locale],\n active: this.activeAssetIds.has(asset.id)\n };\n });\n\n // Calculate next page if there are more assets\n const nextPage = endIndex < total ? page + 1 : undefined;\n\n return {\n assets: resultAssets,\n currentPage: page,\n nextPage,\n total\n };\n }\n\n updateLabel(assetId: string, label: string, locale: string): void {\n this.assets.forEach((asset) => {\n if (asset.id === assetId) {\n asset.label = asset.label || {};\n asset.label[locale] = label;\n }\n });\n }\n\n /**\n * Set an asset as active by its ID\n *\n * @param assetId - The ID of the asset to mark as active\n */\n setAssetActive(assetId: string): void {\n this.activeAssetIds.add(assetId);\n }\n\n /**\n * Set multiple assets as active by their IDs\n *\n * @param assetIds - Array of asset IDs to mark as active\n */\n setAssetsActive(assetIds: string[]): void {\n assetIds.forEach((id) => this.activeAssetIds.add(id));\n }\n\n /**\n * Set an asset as inactive by its ID\n *\n * @param assetId - The ID of the asset to mark as inactive\n */\n setAssetInactive(assetId: string): void {\n this.activeAssetIds.delete(assetId);\n }\n\n /**\n * Clear all active assets\n */\n clearActiveAssets(): void {\n this.activeAssetIds.clear();\n }\n\n /**\n * Check if an asset is marked as active\n *\n * @param assetId - The ID of the asset to check\n * @returns True if the asset is active, false otherwise\n */\n isAssetActive(assetId: string): boolean {\n return this.activeAssetIds.has(assetId);\n }\n\n /**\n * Add an asset to this source\n *\n * @param asset - The asset definition to add\n */\n addAsset(asset: AssetDefinition): void {\n // Check if asset with this ID already exists\n const existingIndex = this.assets.findIndex((a) => a.id === asset.id);\n if (existingIndex >= 0) {\n // Replace existing asset\n this.assets[existingIndex] = asset;\n } else {\n // Add new asset\n this.assets.push(asset);\n }\n }\n\n /**\n * Remove an asset from this source\n *\n * @param assetId - The ID of the asset to remove\n */\n removeAsset(assetId: string): void {\n const index = this.assets.findIndex((asset) => asset.id === assetId);\n if (index !== -1) {\n this.assets.splice(index, 1);\n this.activeAssetIds.delete(assetId);\n }\n }\n\n /**\n * Get all available groups from the assets\n *\n * @returns Array of unique group names\n */\n async getGroups(): Promise<string[]> {\n const groups = new Set<string>();\n this.assets.forEach((asset) => {\n if (asset.groups) {\n asset.groups.forEach((group) => groups.add(group));\n }\n });\n return Array.from(groups);\n }\n\n /**\n * Returns the supported MIME types for this asset source\n *\n * @returns Array of supported MIME types\n */\n getSupportedMimeTypes(): string[] {\n return [\n 'image/jpeg',\n 'image/png',\n 'image/svg+xml',\n 'image/webp',\n 'video/mp4',\n 'audio/mpeg'\n ];\n }\n}\n\n/**\n * Helper function to create a CustomAssetSource instance\n *\n * @param id - The unique identifier for this asset source\n * @param assets - Array of asset definitions or SelectValue objects to include in this source\n * @returns A new CustomAssetSource instance\n */\nexport function createCustomAssetSource(\n id: string,\n assets: (AssetDefinition | SelectValue)[] = []\n): CustomAssetSource {\n return new CustomAssetSource(id, assets);\n}\n\nexport default CustomAssetSource;\n", "/* eslint-disable no-console */\nimport {\n CreativeEngine,\n type AssetDefinition,\n type AssetQueryData,\n type AssetResult,\n type AssetSource,\n type AssetsQueryResult\n} from '@cesdk/cesdk-js';\n\ntype BlobEntry = {\n id: string;\n blob: Blob;\n};\n\n// Asset definition with meta containing insertedAt timestamp\ntype AssetEntryWithMeta = AssetDefinition;\n\n/**\n * IndexedDBAssetSource implements the AssetSource interface using IndexedDB as the storage backend.\n */\nexport class IndexedDBAssetSource implements AssetSource {\n /** The unique id of the API */\n public readonly id: string;\n\n public readonly engine: CreativeEngine;\n\n private readonly dbName: string;\n\n private readonly dbVersion: number;\n\n private readonly assetStoreName: string = 'assets';\n\n private readonly blobStoreName: string = 'blobs';\n\n private db: IDBDatabase | null = null;\n\n /**\n * Creates a new IndexedDBAssetSource\n *\n * @param id - The unique identifier for this asset source\n * @param {Object} [options] - Optional configuration options.\n * @param {string} [options.dbName] - The name of the database.\n * @param {number} [options.dbVersion] - The version number of the database.\n */\n constructor(\n id: string,\n engine: CreativeEngine,\n options?: {\n dbName?: string;\n dbVersion?: number;\n }\n ) {\n this.id = id;\n this.engine = engine;\n this.dbName = options?.dbName ?? `ly.img.assetSource/${id}`;\n this.dbVersion = options?.dbVersion ?? 1;\n }\n\n /**\n * Initialize the database connection and create object stores if needed\n */\n public async initialize(): Promise<void> {\n if (this.db) {\n return;\n }\n\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(this.dbName, this.dbVersion);\n\n request.onerror = (event) => {\n reject(\n new Error(\n `Failed to open IndexedDB: ${(event.target as IDBRequest).error}`\n )\n );\n };\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n\n // Create asset store if it doesn't exist\n if (!db.objectStoreNames.contains(this.assetStoreName)) {\n db.createObjectStore(this.assetStoreName, {\n keyPath: 'id'\n });\n }\n // Create blob store if it doesn't exist\n if (!db.objectStoreNames.contains(this.blobStoreName)) {\n db.createObjectStore(this.blobStoreName, {\n keyPath: 'id'\n });\n }\n };\n\n request.onsuccess = (event) => {\n this.db = (event.target as IDBOpenDBRequest).result;\n resolve();\n };\n });\n }\n\n /**\n * Close the database connection\n */\n public close(): void {\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n }\n\n /**\n * Find all assets for the given type and the provided query data.\n *\n * @param queryData - The query parameters for filtering assets\n * @param insertionSortOrder - Optional parameter to sort by insertion time: 'asc' for oldest first, 'desc' for newest first (default)\n * @returns A promise that resolves to the query results or undefined if there was an error\n */\n public async findAssets(\n queryData: AssetQueryData\n ): Promise<AssetsQueryResult | undefined> {\n await this.initialize();\n\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n try {\n // Get all assets from the store with specified insertion order\n const assetDefinitions = await this.getAllAssets('asc');\n\n let assetResults = assetDefinitions.reduce((acc, assetDefinition) => {\n const locale = queryData.locale ?? 'en';\n let label = '';\n let tags: string[] = [];\n\n // Handle localized label if available\n if (\n assetDefinition.label != null &&\n typeof assetDefinition.label === 'object' &&\n assetDefinition.label[locale]\n ) {\n label = assetDefinition.label[locale];\n }\n\n // Handle localized tags if available\n if (\n assetDefinition.tags != null &&\n typeof assetDefinition.tags === 'object' &&\n assetDefinition.tags[locale]\n ) {\n tags = assetDefinition.tags[locale];\n }\n\n const result: AssetResult = {\n ...assetDefinition,\n label,\n tags\n };\n\n if (this.filterAsset(result, queryData)) {\n acc.push(result);\n }\n\n return acc;\n }, [] as AssetResult[]);\n\n assetResults = await this.restoreBlobUrls(assetResults);\n\n // Apply sorting\n assetResults = this.sortAssets(assetResults, queryData);\n\n // Apply pagination\n const { page, perPage } = queryData;\n const startIndex = page * perPage;\n const endIndex = startIndex + perPage;\n const paginatedAssets = assetResults.slice(startIndex, endIndex);\n\n // Determine if there's a next page\n const nextPage = endIndex < assetResults.length ? page + 1 : undefined;\n\n const result = {\n assets: paginatedAssets,\n currentPage: page,\n nextPage,\n total: assetResults.length\n };\n\n return result;\n } catch (error) {\n console.error('Error finding assets:', error);\n return undefined;\n }\n }\n\n public async getGroups(): Promise<string[]> {\n await this.initialize();\n\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.assetStoreName, 'readonly');\n const store = transaction.objectStore(this.assetStoreName);\n const request = store.getAll();\n\n request.onsuccess = () => {\n const allGroups = new Set<string>();\n\n // Extract all groups from all assets\n (request.result as AssetResult[]).forEach((asset) => {\n if (asset.groups && Array.isArray(asset.groups)) {\n asset.groups.forEach((group) => allGroups.add(group));\n }\n });\n\n const uniqueGroups = [...allGroups];\n resolve(uniqueGroups);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get groups: ${request.error}`));\n };\n });\n }\n\n /**\n * Adds the given asset to this source. Part of the AssetSource interface.\n *\n * @param asset - The asset definition to add\n */\n public addAsset(asset: AssetDefinition): void {\n this.initialize()\n .then(async () => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.assetStoreName,\n 'readwrite'\n );\n const assetStore = transaction.objectStore(this.assetStoreName);\n\n const blobsToStore = new Set<string>();\n processBlobUrls(asset, (value) => {\n blobsToStore.add(value);\n });\n\n setTimeout(() => {\n this.storeBlobUrls([...blobsToStore]);\n });\n\n // Ensure asset has meta object with insertedAt timestamp\n const assetWithMeta: AssetEntryWithMeta = {\n ...asset,\n meta: {\n ...asset.meta,\n insertedAt: asset.meta?.insertedAt || Date.now()\n }\n };\n\n // Store the asset in the database\n assetStore.put(assetWithMeta);\n\n transaction.onerror = () => {\n console.error(`Failed to add asset: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n /**\n * Removes the given asset from this source. Part of the AssetSource interface.\n *\n * @param assetId - The ID of the asset to remove\n */\n public async removeAsset(assetId: string): Promise<void> {\n const asset = await this.getAsset(assetId);\n\n return this.initialize()\n .then(() => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.assetStoreName,\n 'readwrite'\n );\n const store = transaction.objectStore(this.assetStoreName);\n store.delete(assetId);\n\n transaction.oncomplete = () => {\n processBlobUrls(asset, (value) => {\n this.removeBlob(value);\n });\n this.engine.asset.assetSourceContentsChanged(this.id);\n };\n\n transaction.onerror = () => {\n console.error(`Failed to remove asset: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n /**\n * Removes the given asset from this source. Part of the AssetSource interface.\n *\n * @param assetId - The ID of the asset to remove\n */\n public async removeBlob(blobId: string): Promise<void> {\n return this.initialize()\n .then(() => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.blobStoreName,\n 'readwrite'\n );\n const store = transaction.objectStore(this.blobStoreName);\n store.delete(blobId);\n\n transaction.onerror = () => {\n console.error(`Failed to remove blob: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n /**\n * Get all assets from the database sorted by insertion order (newest to oldest)\n *\n * @param sortOrder - Optional parameter to specify sort order: 'asc' for oldest first, 'desc' for newest first (default)\n * @returns A promise that resolves to an array of all assets\n */\n private async getAllAssets(\n sortOrder: 'asc' | 'desc' = 'desc'\n ): Promise<AssetDefinition[]> {\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.assetStoreName, 'readonly');\n const store = transaction.objectStore(this.assetStoreName);\n const request = store.getAll();\n\n request.onsuccess = () => {\n const assets = request.result as AssetEntryWithMeta[];\n\n // Sort by insertion timestamp\n assets.sort((a, b) => {\n // Default to current time if insertedAt is missing (for backward compatibility)\n // First check in meta.insertedAt, then fallback to legacy _insertedAt for backward compatibility\n const timeA =\n a.meta?.insertedAt || (a as any)._insertedAt || Date.now();\n const timeB =\n b.meta?.insertedAt || (b as any)._insertedAt || Date.now();\n\n // Sort based on requested order\n return sortOrder === 'asc'\n ? timeA - timeB // oldest first\n : timeB - timeA; // newest first (default)\n });\n\n resolve(assets);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get assets: ${request.error}`));\n };\n });\n }\n\n // Retrieve a blob by ID\n async getAsset(id: string): Promise<AssetResult | undefined> {\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.assetStoreName, 'readonly');\n const store = transaction.objectStore(this.assetStoreName);\n const request = store.get(id);\n\n request.onsuccess = () => {\n resolve(request.result as AssetResult);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get blob: ${request.error}`));\n };\n });\n }\n\n // Retrieve a blob by ID\n async getBlob(id: string): Promise<BlobEntry | undefined> {\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.blobStoreName, 'readonly');\n const store = transaction.objectStore(this.blobStoreName);\n const request = store.get(id);\n\n request.onsuccess = () => {\n resolve(request.result as BlobEntry);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get blob: ${request.error}`));\n };\n });\n }\n\n async createBlobUrlFromStore(blobUrl: string): Promise<string> {\n const blobEntry = await this.getBlob(blobUrl);\n if (blobEntry != null) {\n return URL.createObjectURL(blobEntry.blob);\n }\n return blobUrl;\n }\n\n async storeBlobUrls(urls: string[]): Promise<void> {\n const blobsToStore: { [key: string]: Blob } = {};\n await Promise.all(\n urls.map(async (blobUrl) => {\n const blobResponse = await fetch(blobUrl);\n const blob = await blobResponse.blob();\n blobsToStore[blobUrl] = blob;\n })\n );\n\n return this.initialize()\n .then(async () => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.blobStoreName,\n 'readwrite'\n );\n const blobStore = transaction.objectStore(this.blobStoreName);\n\n // Store the asset in the database\n Object.entries(blobsToStore).forEach(([key, blob]) => {\n const asset: BlobEntry = { id: key, blob };\n blobStore.put(asset);\n });\n\n transaction.onerror = () => {\n console.error(`Failed to add blobs: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n async restoreBlobUrls(assets: AssetResult[]): Promise<AssetResult[]> {\n const blobReplaced: { [key: string]: string } = {};\n const blobUrls: Set<string> = new Set();\n processBlobUrls(assets, (value) => {\n blobUrls.add(value);\n });\n\n await Promise.all(\n [...blobUrls].map(async (value) => {\n const newUrl = await this.createBlobUrlFromStore(value);\n blobReplaced[value] = newUrl;\n })\n );\n\n return processBlobUrls(assets, (value) => {\n return blobReplaced[value] ?? value;\n });\n }\n\n /**\n * Returns if the given asset should be filtered based on query data\n *\n * @param asset - The asset to filter\n * @param queryData - The query parameters to filter by\n * @returns true if the asset should be included, false otherwise\n */\n private filterAsset(asset: AssetResult, queryData: AssetQueryData): boolean {\n const { query, tags, groups, excludeGroups } = queryData;\n\n // Filter by query string (search on label and tags)\n if (query && query.trim() !== '') {\n const lowerQuery = query.trim().toLowerCase().split(' ');\n\n const lowerLabel = asset.label?.toLowerCase() ?? '';\n const lowerTags = asset.tags?.map((tag) => tag.toLowerCase()) ?? [];\n\n const matchLabelOrTag = lowerQuery.every((word) => {\n return (\n lowerLabel.includes(word) ||\n lowerTags.some((tag) => tag.includes(word))\n );\n });\n\n if (!matchLabelOrTag) {\n return false;\n }\n }\n\n // Filter by exact tags if provided by the query\n if (tags) {\n const tagList = Array.isArray(tags) ? tags : [tags];\n if (\n tagList.length > 0 &&\n (!asset.tags || !tagList.every((tag) => asset.tags?.includes(tag)))\n ) {\n return false;\n }\n }\n\n // Filter by groups\n if (groups && groups.length > 0) {\n if (\n !asset.groups ||\n !groups.some((group) => asset.groups?.includes(group))\n ) {\n return false;\n }\n }\n\n // Filter by excluded groups\n if (excludeGroups && excludeGroups.length > 0) {\n if (\n asset.groups &&\n asset.groups.some((group) => excludeGroups.includes(group))\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Sort assets based on query data\n *\n * @param assets - The assets to sort\n * @param queryData - The query parameters with sorting information\n * @returns The sorted assets\n */\n private sortAssets(\n assets: AssetResult[],\n queryData: AssetQueryData\n ): AssetResult[] {\n const { sortingOrder, sortKey, sortActiveFirst } = queryData;\n\n // Clone the array to avoid modifying the original\n const sortedAssets = [...assets];\n\n // If no sorting order specified or set to 'None', return the current order\n if (!sortingOrder || sortingOrder === 'None') {\n return sortedAssets;\n }\n\n // Sort by the specified key\n if (sortKey) {\n sortedAssets.sort((a, b) => {\n let valueA;\n let valueB;\n\n if (sortKey === 'id') {\n valueA = a.id;\n valueB = b.id;\n } else {\n // Handle metadata sorting (assuming metadata is stored in a 'metadata' field)\n valueA = a.meta?.[sortKey] ?? null;\n valueB = b.meta?.[sortKey] ?? null;\n }\n\n // Handle null/undefined values\n if (valueA === null || valueA === undefined)\n return sortingOrder === 'Ascending' ? -1 : 1;\n if (valueB === null || valueB === undefined)\n return sortingOrder === 'Ascending' ? 1 : -1;\n\n // Compare values based on sorting order\n if (typeof valueA === 'string' && typeof valueB === 'string') {\n return sortingOrder === 'Ascending'\n ? valueA.localeCompare(valueB)\n : valueB.localeCompare(valueA);\n } else {\n return sortingOrder === 'Ascending'\n ? valueA < valueB\n ? -1\n : valueA > valueB\n ? 1\n : 0\n : valueA > valueB\n ? -1\n : valueA < valueB\n ? 1\n : 0;\n }\n });\n } else if (sortingOrder === 'Descending') {\n // If no sort key is specified, and sorting order set\n // to Descending, just reverse original order\n sortedAssets.reverse();\n }\n\n // Sort by active first if requested\n if (sortActiveFirst) {\n sortedAssets.sort((a, b) => {\n if (a.active && !b.active) return -1;\n if (!a.active && b.active) return 1;\n return 0;\n });\n }\n\n return sortedAssets;\n }\n}\n\n/**\n * Goes through an object and calls a callback for every string value that starts with 'blob:'\n * The callback can return a string to replace the original value\n * @param obj The object to traverse\n * @param callback Function to call when a blob URL is found, can return a replacement value\n * @param path Current path in the object (used for recursion)\n * @returns The modified object (or the original if no replacements were made)\n */\nfunction processBlobUrls<T>(\n obj: T,\n callback: (value: string, path: string) => string | void,\n path: string = ''\n): T {\n // Return the object as is if it's null or not an object\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n for (let index = 0; index < obj.length; index++) {\n const currentPath = path ? `${path}[${index}]` : `[${index}]`;\n\n if (typeof obj[index] === 'string' && obj[index].startsWith('blob:')) {\n const replacement = callback(obj[index], currentPath);\n if (typeof replacement === 'string') {\n obj[index] = replacement;\n }\n } else {\n obj[index] = processBlobUrls(obj[index], callback, currentPath);\n }\n }\n return obj;\n }\n\n // Handle regular objects\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key];\n const currentPath = path ? `${path}.${key}` : key;\n\n if (typeof value === 'string' && value.startsWith('blob:')) {\n const replacement = callback(value, currentPath);\n if (typeof replacement === 'string') {\n // @ts-ignore\n obj[key] = replacement;\n }\n } else {\n obj[key] = processBlobUrls(value, callback, currentPath);\n }\n }\n }\n\n return obj;\n}\n\nexport default IndexedDBAssetSource;\n", "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport type {\n AssetDefinition,\n AssetQueryData,\n AssetResult,\n AssetSource,\n AssetsQueryResult\n} from '@cesdk/cesdk-js';\nimport CreativeEditorSDK from '@cesdk/cesdk-js';\n\n/**\n * AggregatedAssetSource implements the AssetSource interface by aggregating\n * multiple asset sources via the cesdk API and combining their results.\n *\n * This asset source is read-only - it does not support adding or removing assets.\n */\nexport class AggregatedAssetSource implements AssetSource {\n /** The unique id of the asset source */\n public readonly id: string;\n\n /** The Creative Editor SDK instance */\n private cesdk: CreativeEditorSDK;\n\n /** The IDs of asset sources to aggregate */\n private assetSourceIds: string[];\n\n /**\n * Creates a new AggregatedAssetSource\n *\n * @param id - The unique identifier for this asset source\n * @param cesdk - The Creative Editor SDK instance\n * @param assetSourceIds - The IDs of asset sources to aggregate\n */\n constructor(id: string, cesdk: CreativeEditorSDK, assetSourceIds: string[]) {\n this.id = id;\n this.cesdk = cesdk;\n this.assetSourceIds = assetSourceIds;\n }\n\n /**\n * Find assets across all aggregated sources based on the provided query data\n * Results are sorted by the insertedAt timestamp in meta field\n *\n * @param queryData - Query parameters to filter and sort assets\n * @returns Promise with the query results\n */\n async findAssets(\n queryData: AssetQueryData\n ): Promise<AssetsQueryResult | undefined> {\n try {\n // Query all asset sources via cesdk\n const queryPromises = this.assetSourceIds.map((sourceId) =>\n this.cesdk.engine.asset.findAssets(sourceId, {\n ...queryData,\n // Increase page size to get all assets from each source\n // We'll handle pagination after merging\n perPage: 9999,\n page: 0\n })\n );\n\n // Wait for all queries to complete\n const results = await Promise.all(queryPromises);\n\n // Combine all assets from all sources\n let allAssets: AssetResult[] = [];\n results.forEach((result) => {\n if (result?.assets) {\n allAssets = allAssets.concat(result.assets);\n }\n });\n\n // Sort by insertedAt timestamp\n allAssets.sort((a, b) => {\n const timeA = (a.meta?.insertedAt as number) || 0;\n const timeB = (b.meta?.insertedAt as number) || 0;\n\n // Sort newest first (descending)\n return timeB - timeA;\n });\n\n // Apply pagination after merging\n const { page, perPage } = queryData;\n const startIndex = page * perPage;\n const endIndex = startIndex + perPage;\n const paginatedAssets = allAssets.slice(startIndex, endIndex);\n\n // Calculate if there is a next page\n const nextPage = endIndex < allAssets.length ? page + 1 : undefined;\n\n return {\n assets: paginatedAssets,\n currentPage: page,\n nextPage,\n total: allAssets.length\n };\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Error finding assets:', error);\n return undefined;\n }\n }\n\n /**\n * Retrieves all groups from all aggregated asset sources using cesdk\n * @returns Promise with an array of unique group names\n */\n async getGroups(): Promise<string[]> {\n const groupPromises = this.assetSourceIds.map((sourceId) =>\n this.cesdk.engine.asset.getGroups(sourceId)\n );\n\n const groupArrays = await Promise.all(groupPromises);\n\n // Combine and deduplicate groups\n const uniqueGroups = new Set<string>();\n groupArrays.forEach((groups) => {\n groups.forEach((group) => uniqueGroups.add(group));\n });\n\n return Array.from(uniqueGroups);\n }\n\n /**\n * This operation is not supported in AggregatedAssetSource\n * @throws Error - This method is not supported\n */\n addAsset(_asset: AssetDefinition): void {\n throw new Error('AggregatedAssetSource does not support adding assets');\n }\n\n /**\n * This operation is not supported in AggregatedAssetSource\n * @throws Error - This method is not supported\n */\n removeAsset(_assetId: string): void {\n throw new Error('AggregatedAssetSource does not support removing assets');\n }\n}\n\n/**\n * Helper function to create an AggregatedAssetSource instance\n *\n * @param id - The unique identifier for this asset source\n * @param cesdk - The Creative Editor SDK instance\n * @param assetSourceIds - The IDs of asset sources to aggregate\n * @returns A new AggregatedAssetSource instance\n */\nexport function createAggregatedAssetSource(\n id: string,\n cesdk: CreativeEditorSDK,\n assetSourceIds: string[]\n): AggregatedAssetSource {\n return new AggregatedAssetSource(id, cesdk, assetSourceIds);\n}\n\nexport default AggregatedAssetSource;\n", "import { type CreativeEngine } from '@cesdk/cesdk-js';\n\nclass Metadata<V> {\n engine: CreativeEngine;\n\n key: string;\n\n constructor(engine: CreativeEngine, key: string) {\n this.engine = engine;\n this.key = key;\n }\n\n hasData(blockId: number): boolean {\n return (\n this.engine.block.isValid(blockId) &&\n this.engine.block.hasMetadata(blockId, this.key)\n );\n }\n\n get(blockId: number): V | undefined {\n if (this.hasData(blockId)) {\n return JSON.parse(this.engine.block.getMetadata(blockId, this.key));\n }\n return undefined;\n }\n\n set(blockId: number, value: V) {\n this.engine.block.setMetadata(blockId, this.key, JSON.stringify(value));\n }\n\n clear(blockId: number) {\n if (this.engine.block.hasMetadata(blockId, this.key)) {\n this.engine.block.removeMetadata(blockId, this.key);\n }\n }\n}\n\nexport default Metadata;\n", "/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nexport default root;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n", "import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n", "import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\n", "/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n", "/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n", "/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nexport default isFunction;\n", "import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n", "import coreJsData from './_coreJsData.js';\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nexport default isMasked;\n", "/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n", "import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nexport default baseIsNative;\n", "/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n", "import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nexport default getNative;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n", "/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n", "import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nexport default isArrayLike;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n", "/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nexport default baseIsArguments;\n", "import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nexport default isArguments;\n", "/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n", "import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n", "import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nexport default baseIsTypedArray;\n", "/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nexport default nodeUtil;\n", "import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nexport default isTypedArray;\n", "import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default arrayLikeKeys;\n", "/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n", "import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n", "import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeys;\n", "import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nexport default keys;\n", "import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n", "import nativeCreate from './_nativeCreate.js';\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nexport default hashClear;\n", "/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nexport default hashGet;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nexport default hashHas;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nexport default hashSet;\n", "import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nexport default Hash;\n", "/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n", "import eq from './eq.js';\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nexport default assocIndexOf;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nexport default listCacheDelete;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nexport default listCacheGet;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nexport default listCacheHas;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nexport default listCacheSet;\n", "import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nexport default ListCache;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n", "import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nexport default mapCacheClear;\n", "/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n", "import isKeyable from './_isKeyable.js';\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nexport default getMapData;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default mapCacheDelete;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nexport default mapCacheGet;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nexport default mapCacheHas;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nexport default mapCacheSet;\n", "import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nexport default MapCache;\n", "/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n", "import ListCache from './_ListCache.js';\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nexport default stackClear;\n", "/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n", "/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n", "/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n", "import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nexport default stackSet;\n", "import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nexport default Stack;\n", "/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n", "/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n", "import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nexport default getSymbols;\n", "import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nexport default baseGetAllKeys;\n", "import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nexport default getAllKeys;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n", "import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nexport default getTag;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\n", "/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n", "/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n", "import MapCache from './_MapCache.js';\nimport setCacheAdd from './_setCacheAdd.js';\nimport setCacheHas from './_setCacheHas.js';\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nexport default SetCache;\n", "/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n", "/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n", "import SetCache from './_SetCache.js';\nimport arraySome from './_arraySome.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nexport default equalArrays;\n", "/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n", "/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n", "import Symbol from './_Symbol.js';\nimport Uint8Array from './_Uint8Array.js';\nimport eq from './eq.js';\nimport equalArrays from './_equalArrays.js';\nimport mapToArray from './_mapToArray.js';\nimport setToArray from './_setToArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nexport default equalByTag;\n", "import getAllKeys from './_getAllKeys.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nexport default equalObjects;\n", "import Stack from './_Stack.js';\nimport equalArrays from './_equalArrays.js';\nimport equalByTag from './_equalByTag.js';\nimport equalObjects from './_equalObjects.js';\nimport getTag from './_getTag.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nexport default baseIsEqualDeep;\n", "import baseIsEqualDeep from './_baseIsEqualDeep.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nexport default baseIsEqual;\n", "import baseIsEqual from './_baseIsEqual.js';\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\nexport default isEqual;\n", "import { isEqual } from 'lodash-es';\n\nimport Metadata from './Metadata';\nimport {\n PluginStatusError,\n PluginStatusMetadata,\n PluginStatusProcessed,\n PluginStatusProcessing\n} from './types';\n\nclass ImageProcessingMetadata extends Metadata<PluginStatusMetadata> {\n get(blockId: number): PluginStatusMetadata {\n return super.get(blockId) ?? { status: 'IDLE' };\n }\n\n /**\n * Detect if the block has been duplicated with processed or processing\n * fill processing. In that case the processing state is still\n * valid, but blockId and fillId have changed.\n */\n isDuplicate(blockId: number): boolean {\n if (!this.engine.block.isValid(blockId)) return false;\n\n const metadata = this.get(blockId);\n\n if (\n metadata.status === 'IDLE' ||\n metadata.status === 'PENDING' ||\n metadata.status === 'ERROR'\n )\n return false;\n\n if (!this.engine.block.hasFill(blockId)) return false;\n const fillId = this.engine.block.getFill(blockId);\n\n // It cannot be a duplicate if the blockId or fillId are the same\n if (metadata.blockId === blockId || metadata.fillId === fillId)\n return false;\n\n return true;\n }\n\n /**\n * Fixes the metadata if the block has been duplicated, i.e. the blockId and\n * fillId will be updated to the current block/fill.\n *\n * Please note: Call this method only on duplicates (see isDuplicate).\n */\n fixDuplicate(blockId: number) {\n const fillId = this.engine.block.getFill(blockId);\n const metadata = this.get(blockId);\n if (\n metadata.status === 'IDLE' ||\n metadata.status === 'PENDING' ||\n metadata.status === 'ERROR'\n )\n return;\n this.set(blockId, {\n ...metadata,\n blockId,\n fillId\n });\n\n // If it is currently processing the best we can do is to just recover\n // the initial image data, since no processing will update this block and\n // it will be stuck in the processing state.\n if (metadata.status === 'PROCESSING') {\n this.recoverInitialImageData(blockId);\n this.clear(blockId);\n }\n }\n\n /**\n * Check if the image has a consisten metadata state. A inconsistent state is\n * caused by outside changes of the fill data.\n *\n * @returns true if the metadata is consistent, false otherwise\n */\n isConsistent(blockId: number): boolean {\n // In case the block was removed, we just abort and mark it\n // as reset by returning true\n if (!this.engine.block.isValid(blockId)) return false;\n const metadata = this.get(blockId);\n if (metadata.status === 'IDLE' || metadata.status === 'PENDING')\n return true;\n\n if (!this.engine.block.hasFill(blockId)) return false;\n const fillId = this.engine.block.getFill(blockId);\n if (fillId == null) return false;\n\n if (blockId !== metadata.blockId || fillId !== metadata.fillId)\n return false;\n\n const sourceSet = this.engine.block.getSourceSet(\n fillId,\n 'fill/image/sourceSet'\n );\n const imageFileURI = this.engine.block.getString(\n fillId,\n 'fill/image/imageFileURI'\n );\n\n if (\n sourceSet.length === 0 &&\n !imageFileURI &&\n metadata.status === 'PROCESSING'\n ) {\n // While we process it is OK to have no image file URI and no source set\n // (which we cleared to show the spinning loader)\n return true;\n }\n\n // Source sets have precedence over imageFileURI so if we have a source set,\n // we only need to check if it has changed to something else.\n if (sourceSet?.length > 0) {\n const initialSourceSet = metadata.initialSourceSet;\n // If we have already processed the image, we need to check if the source set\n // we need to check against both source sets, the removed and the initial\n if (metadata.status !== 'PROCESSED') {\n if (!isEqual(sourceSet, initialSourceSet)) {\n return false;\n }\n }\n } else {\n if (metadata.status !== 'PROCESSED') {\n if (imageFileURI !== metadata.initialImageFileURI) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Recover the initial values to avoid the loading spinner and have the same\n * state as before the fill processing was started.\n */\n recoverInitialImageData(blockId: number) {\n const blockApi = this.engine.block;\n if (!blockApi.hasFill(blockId)) return; // Nothing to recover (no fill anymore)\n\n const metadata = this.get(blockId);\n\n if (metadata.status === 'PENDING' || metadata.status === 'IDLE') {\n return;\n }\n\n const initialSourceSet = metadata.initialSourceSet;\n const initialImageFileURI = metadata.initialImageFileURI;\n const initialPreviewFileURI = metadata.initialPreviewFileURI;\n\n const fillId = this.getValidFill(blockId, metadata);\n if (fillId == null) return;\n\n if (initialImageFileURI) {\n this.engine.block.setString(\n fillId,\n 'fill/image/imageFileURI',\n initialImageFileURI\n );\n }\n if (initialPreviewFileURI) {\n this.engine.block.setString(\n fillId,\n 'fill/image/previewFileURI',\n initialPreviewFileURI\n );\n }\n if (initialSourceSet.length > 0) {\n this.engine.block.setSourceSet(\n fillId,\n 'fill/image/sourceSet',\n initialSourceSet\n );\n }\n }\n\n /**\n * Returns the fill id of the block if it has a valid fill that was used for\n * fill processing. Returns undefined otherwise.\n */\n private getValidFill(\n blockId: number,\n metadata: PluginStatusProcessing | PluginStatusError | PluginStatusProcessed\n ): number | undefined {\n if (\n !this.engine.block.isValid(blockId) ||\n !this.engine.block.hasFill(blockId) ||\n blockId !== metadata.blockId\n ) {\n return undefined;\n }\n const fillId = this.engine.block.getFill(blockId);\n if (fillId !== metadata.fillId) {\n return undefined;\n }\n\n return fillId;\n }\n}\n\nexport default ImageProcessingMetadata;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { FillProcessingMetadata } from '..';\nimport {\n PluginStatusProcessed,\n PluginStatusProcessing\n} from '../metadata/types';\n\ninterface FillProcessor<T> {\n processFill(metadataState: PluginStatusProcessing): Promise<T>;\n\n commitProcessing(\n data: T,\n metadataState: PluginStatusProcessed\n ): number | void;\n}\n\nasync function fillProcessing<T>(\n blockId: number,\n cesdk: CreativeEditorSDK,\n metadata: FillProcessingMetadata,\n processor: FillProcessor<T>\n) {\n const blockApi = cesdk.engine.block;\n if (!blockApi.hasFill(blockId))\n throw new Error('Block does not support fill');\n\n const fillId = blockApi.getFill(blockId);\n\n // Get the current image URI and source set as initial values.\n const initialSourceSet = blockApi.getSourceSet(\n fillId,\n 'fill/image/sourceSet'\n );\n const initialImageFileURI = blockApi.getString(\n fillId,\n 'fill/image/imageFileURI'\n );\n const initialPreviewFileURI = blockApi.getString(\n fillId,\n 'fill/image/previewFileURI'\n );\n try {\n cesdk.engine.block.setState(fillId, {\n type: 'Pending',\n progress: 0\n });\n\n const status: PluginStatusProcessing = {\n ...metadata.get(blockId),\n version: PLUGIN_VERSION,\n initialSourceSet,\n initialImageFileURI,\n initialPreviewFileURI,\n blockId,\n fillId,\n status: 'PROCESSING'\n };\n\n metadata.set(blockId, status);\n\n const processedData = await processor.processFill(status);\n // Check for externally changed state while we were applying the mask and\n // do not proceed if the state was reset.\n if (\n metadata.get(blockId).status !== 'PROCESSING' ||\n !metadata.isConsistent(blockId)\n )\n return;\n\n // Check for externally changed state while we were uploading and\n // do not proceed if the state was reset.\n if (\n metadata.get(blockId).status !== 'PROCESSING' ||\n !metadata.isConsistent(blockId)\n )\n return;\n\n if (processedData == null) return;\n\n const metadataStateProcessed: PluginStatusProcessed = {\n version: PLUGIN_VERSION,\n initialSourceSet,\n initialImageFileURI,\n initialPreviewFileURI,\n blockId,\n fillId,\n status: 'PROCESSED'\n };\n\n const blockIdOrVoid = processor.commitProcessing(\n processedData,\n metadataStateProcessed\n );\n\n // If a new block was created, we do not update the metadata.\n if (blockIdOrVoid == null || blockIdOrVoid === blockId) {\n metadata.set(blockId, metadataStateProcessed);\n }\n\n // Finally, create an undo step\n cesdk.engine.editor.addUndoStep();\n } catch (error) {\n if (cesdk.engine.block.isValid(blockId)) {\n metadata.set(blockId, {\n version: PLUGIN_VERSION,\n initialSourceSet,\n initialImageFileURI,\n initialPreviewFileURI,\n blockId,\n fillId,\n status: 'ERROR'\n });\n\n metadata.recoverInitialImageData(blockId);\n }\n\n if (\n error != null &&\n typeof error === 'object' &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n const message =\n error.message === 'signal timed out'\n ? 'Processing canceled due to timeout'\n : error.message;\n cesdk.ui.showNotification({\n type: 'error',\n message\n });\n }\n\n // eslint-disable-next-line no-console\n console.log(error);\n } finally {\n if (cesdk.engine.block.isValid(fillId)) {\n cesdk.engine.block.setState(fillId, { type: 'Ready' });\n }\n }\n}\n\nexport default fillProcessing;\n", "export function getFeatureId(pluginId: string): string {\n return `${pluginId}.fillProcessing.feature`;\n}\n\nexport function getCanvasMenuComponentIds(pluginId: string): string[] {\n return [`${pluginId}.canvasMenu`, `${pluginId}.fillProcessing.canvasMenu`];\n}\n\nexport function getDockComponentIds(pluginId: string): string[] {\n return [`${pluginId}.dock`, `${pluginId}.fillProcessing.dock`];\n}\n\nexport function getInspectorBarComponentIds(pluginId: string): string[] {\n return [\n `${pluginId}.inspectorBar`,\n `${pluginId}.fillProcessing.inspectorBar`\n ];\n}\n\nexport function getNavigationBarComponentIds(pluginId: string): string[] {\n return [\n `${pluginId}.navigationBar`,\n `${pluginId}.fillProcessing.navigationBar`\n ];\n}\n\nexport function getCanvasBarComponentIds(pluginId: string): string[] {\n return [`${pluginId}.canvasBar`, `${pluginId}.fillProcessing.canvasBar`];\n}\n\nexport function getI18nCanvasMenuLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.canvasMenu.button.label`;\n}\n\nexport function getI18nDockLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.dock.button.label`;\n}\n\nexport function getI18nInspectorBarLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.inspectorBar.button.label`;\n}\n\nexport function getI18nNavigationBarLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.navigationBar.button.label`;\n}\n\nexport function getI18nCanvasBarLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.canvasBar.button.label`;\n}\n", "import type CreativeEditorSDK from '@cesdk/cesdk-js';\n\nimport { FillProcessingMetadata } from '..';\nimport { getFeatureId } from './constants';\n\nexport default function handleFillProcessing(\n cesdk: CreativeEditorSDK,\n {\n pluginId,\n process\n }: {\n pluginId: string;\n icon?: string;\n process: (blockId: number, metadata: FillProcessingMetadata) => void;\n }\n): {\n featureId: string;\n} {\n const featureId = getFeatureId(pluginId);\n\n const metadata = new FillProcessingMetadata(cesdk.engine, pluginId);\n\n enableFeatures(cesdk, metadata, featureId);\n\n cesdk.engine.event.subscribe([], async (events) => {\n events.forEach((e) => {\n const id = e.block;\n if (!cesdk.engine.block.isValid(id) || !metadata.hasData(id)) {\n return;\n }\n\n if (e.type === 'Created') {\n if (metadata.isDuplicate(id)) {\n metadata.fixDuplicate(id);\n }\n } else if (e.type === 'Updated') {\n switch (metadata.get(id).status) {\n case 'PENDING': {\n if (\n cesdk.feature.isEnabled(featureId, {\n engine: cesdk.engine\n }) &&\n cesdk.engine.block.isAllowedByScope(id, 'fill/change') &&\n cesdk.engine.block.getState(id).type !== 'Pending'\n ) {\n process(id, metadata);\n }\n break;\n }\n\n case 'PROCESSING':\n case 'PROCESSED': {\n if (!metadata.isConsistent(id)) {\n metadata.clear(id);\n }\n break;\n }\n\n default: {\n // We do not care about other states\n }\n }\n }\n });\n });\n\n return { featureId };\n}\n\n/**\n * Defines the feature that determines in which context (on which block)\n * fill processing is allowed/enabled.\n */\nfunction enableFeatures(\n cesdk: CreativeEditorSDK,\n metadata: FillProcessingMetadata,\n featureId: string\n) {\n cesdk.feature.enable(featureId, ({ engine }) => {\n const selectedIds = engine.block.findAllSelected();\n if (selectedIds.length !== 1) {\n return false;\n }\n const [selectedId] = selectedIds;\n\n if (!cesdk.engine.block.isVisible(selectedId)) return false;\n\n if (cesdk.engine.block.hasFill(selectedId)) {\n const kind = cesdk.engine.block.getKind(selectedId);\n if (kind === 'sticker') return false;\n\n const fillId = cesdk.engine.block.getFill(selectedId);\n const fillType = cesdk.engine.block.getType(fillId);\n\n if (fillType !== '//ly.img.ubq/fill/image') {\n return false;\n }\n\n const fileUri = engine.block.getString(fillId, 'fill/image/imageFileURI');\n const sourceSet = engine.block.getSourceSet(\n fillId,\n 'fill/image/sourceSet'\n );\n\n if (sourceSet.length > 0 || fileUri !== '') return true;\n\n // If we are in a processing state we do not have a imageFileURI or\n // source set set (to show the loading spinner), but the feature is still\n // enabled.\n return metadata.get(selectedId).status === 'PROCESSING';\n }\n\n return false;\n });\n}\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { FillProcessingMetadata } from '..';\nimport {\n getCanvasBarComponentIds,\n getCanvasMenuComponentIds,\n getDockComponentIds,\n getFeatureId,\n getI18nCanvasBarLabel,\n getI18nCanvasMenuLabel,\n getI18nDockLabel,\n getI18nInspectorBarLabel,\n getI18nNavigationBarLabel,\n getInspectorBarComponentIds,\n getNavigationBarComponentIds\n} from './constants';\n\nexport type Location =\n | 'inspectorBar'\n | 'navigationBar'\n | 'canvasBarTop'\n | 'canvasBarBottom'\n | 'canvasMenu'\n | 'dock';\n\n/**\n * Registers the components that can be used to process the fill of\n * a block.\n */\nexport default function registerFillProcessingComponents(\n cesdk: CreativeEditorSDK,\n options: {\n pluginId: string;\n icon?: string;\n locations?: Location | Location[];\n }\n): {\n canvasMenuComponentId: string;\n dockComponentId: string;\n\n translationsKeys: {\n inspectorBarLabel: string;\n navigationBarLabel: string;\n canvasBarLabel: string;\n canvasMenuLabel: string;\n dockLabel: string;\n };\n} {\n const { pluginId, locations } = options;\n const metadata = new FillProcessingMetadata(cesdk.engine, pluginId);\n\n const canvasMenuLabel = getI18nCanvasMenuLabel(pluginId);\n const canvasMenuComponentIds = getCanvasMenuComponentIds(pluginId);\n const canvasMenuComponentId = canvasMenuComponentIds[0];\n\n const dockLabel = getI18nDockLabel(pluginId);\n const dockComponentIds = getDockComponentIds(pluginId);\n const dockComponentId = dockComponentIds[0];\n\n const inspectorBarLabel = getI18nInspectorBarLabel(pluginId);\n const inspectorBarComponentIds = getInspectorBarComponentIds(pluginId);\n const inspectorBarComponentId = inspectorBarComponentIds[0];\n\n const navigationBarLabel = getI18nNavigationBarLabel(pluginId);\n const navigationBarComponentIds = getNavigationBarComponentIds(pluginId);\n const navigationBarComponentId = navigationBarComponentIds[0];\n\n const canvasBarLabel = getI18nCanvasBarLabel(pluginId);\n const canvasBarComponentIds = getCanvasBarComponentIds(pluginId);\n const canvasBarComponentId = canvasBarComponentIds[0];\n\n const featureId = getFeatureId(pluginId);\n\n if (locations?.includes('inspectorBar')) {\n cesdk.ui.setInspectorBarOrder([\n inspectorBarComponentId,\n ...cesdk.ui.getInspectorBarOrder()\n ]);\n }\n\n if (locations?.includes('navigationBar')) {\n cesdk.ui.setNavigationBarOrder([\n navigationBarComponentId,\n ...cesdk.ui.getNavigationBarOrder()\n ]);\n }\n\n if (locations?.includes('canvasBarTop')) {\n cesdk.ui.setCanvasBarOrder(\n [canvasBarComponentId, ...cesdk.ui.getCanvasBarOrder('top')],\n 'top'\n );\n }\n\n if (locations?.includes('canvasBarBottom')) {\n cesdk.ui.setCanvasBarOrder(\n [canvasBarComponentId, ...cesdk.ui.getCanvasBarOrder('bottom')],\n 'bottom'\n );\n }\n\n if (locations?.includes('canvasMenu')) {\n cesdk.ui.setCanvasMenuOrder([\n canvasMenuComponentId,\n ...cesdk.ui.getCanvasMenuOrder()\n ]);\n }\n\n if (locations?.includes('dock')) {\n cesdk.ui.setDockOrder([...cesdk.ui.getDockOrder(), dockComponentId]);\n }\n\n cesdk.ui.registerComponent(\n dockComponentIds,\n ({ builder: { Button }, engine }) => {\n const [id] = engine.block.findAllSelected();\n\n let isDisabled = false;\n let isLoading = false;\n let loadingProgress: number | undefined;\n\n if (id == null) {\n isDisabled = true;\n }\n\n if (\n !isDisabled &&\n !cesdk.feature.isEnabled(featureId, {\n engine\n })\n ) {\n isDisabled = true;\n }\n\n if (\n !isDisabled &&\n !cesdk.engine.block.isAllowedByScope(id, 'fill/change')\n ) {\n isDisabled = true;\n }\n\n if (!isDisabled && engine.block.getState(id)?.type === 'Pending') {\n isDisabled = true;\n }\n\n if (!isDisabled) {\n const currentMetadata = metadata.get(id);\n\n isLoading = currentMetadata.status === 'PROCESSING';\n isDisabled =\n currentMetadata.status === 'PENDING' ||\n currentMetadata.status === 'PROCESSING';\n\n if (\n currentMetadata.status === 'PROCESSING' &&\n currentMetadata.progress\n ) {\n const { current, total } = currentMetadata.progress;\n loadingProgress = (current / total) * 100;\n }\n }\n\n const buttonId = `${dockComponentId}.button`;\n Button(buttonId, {\n label: dockLabel,\n icon: options.icon,\n isLoading,\n isDisabled,\n loadingProgress,\n onClick: () => {\n const currentMetadata = metadata.get(id);\n\n if (\n currentMetadata.status === 'IDLE' ||\n currentMetadata.status === 'ERROR' ||\n currentMetadata.status === 'PROCESSED'\n ) {\n metadata.set(id, {\n status: 'PENDING'\n });\n }\n }\n });\n }\n );\n\n const buttonComponents: {\n componentIds: string[];\n label: string;\n variant: 'plain' | 'regular';\n }[] = [\n {\n componentIds: inspectorBarComponentIds,\n variant: 'plain',\n label: inspectorBarLabel\n },\n {\n componentIds: navigationBarComponentIds,\n variant: 'regular',\n label: navigationBarLabel\n },\n {\n componentIds: canvasBarComponentIds,\n variant: 'regular',\n label: canvasBarLabel\n },\n {\n componentIds: canvasMenuComponentIds,\n variant: 'plain',\n label: canvasMenuLabel\n }\n ];\n\n buttonComponents.forEach(({ componentIds, label, variant }) => {\n const componentId = componentIds[0];\n cesdk.ui.registerComponent(\n componentIds,\n ({ builder: { Button }, engine }) => {\n if (\n !cesdk.feature.isEnabled(featureId, {\n engine\n })\n ) {\n return;\n }\n\n const [id] = engine.block.findAllSelected();\n\n if (!cesdk.engine.block.isAllowedByScope(id, 'fill/change')) return;\n\n const currentMetadata = metadata.get(id);\n\n const isLoading = currentMetadata.status === 'PROCESSING';\n const isDisabled =\n currentMetadata.status === 'PENDING' ||\n currentMetadata.status === 'PROCESSING' ||\n engine.block.getState(id)?.type === 'Pending';\n\n let loadingProgress: number | undefined;\n if (isLoading && currentMetadata.progress) {\n const { current, total } = currentMetadata.progress;\n loadingProgress = (current / total) * 100;\n }\n\n const buttonId = `${componentId}.button`;\n Button(buttonId, {\n icon: options.icon,\n label,\n variant,\n isLoading,\n isDisabled,\n loadingProgress,\n onClick: () => {\n if (\n currentMetadata.status === 'IDLE' ||\n currentMetadata.status === 'ERROR' ||\n currentMetadata.status === 'PROCESSED'\n ) {\n metadata.set(id, {\n status: 'PENDING'\n });\n }\n }\n });\n }\n );\n });\n\n return {\n canvasMenuComponentId,\n dockComponentId,\n translationsKeys: {\n inspectorBarLabel,\n navigationBarLabel,\n canvasBarLabel,\n canvasMenuLabel,\n dockLabel\n }\n };\n}\n", "import { type RGBAColor } from '@cesdk/cesdk-js';\n\nconst HEX_COLOR_PATTERN = new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/, 'i');\nconst HEX_SINGLE_CHAR_COMPONENTS_PATTERN = new RegExp(/[A-Fa-f0-9]{1}/, 'g');\nconst HEX_DOUBLE_CHAR_COMPONENTS_PATTERN = new RegExp(/[A-Fa-f0-9]{2}/, 'g');\n\n/** @public */\nexport const rgbaToHex = (rgba: RGBAColor, includeAlpha = false): string => {\n const { r, g, b, a } = rgba;\n const rByte = Math.round(255 * r);\n const gByte = Math.round(255 * g);\n const bByte = Math.round(255 * b);\n const aByte = Math.round(255 * a);\n const byteToHex = (byte: number) => {\n return byte.toString(16).padStart(2, '0');\n };\n return `#${byteToHex(rByte)}${byteToHex(gByte)}${byteToHex(bByte)}${\n includeAlpha ? byteToHex(aByte) : ''\n }`;\n};\n\n/** @public */\nexport const hexToRgba = (hexString: string): RGBAColor => {\n const rgbaHexToColor = (\n r: string,\n g: string,\n b: string,\n a: string | undefined,\n max: number\n ) => {\n return {\n r: parseInt(r, 16) / max,\n g: parseInt(g, 16) / max,\n b: parseInt(b, 16) / max,\n a: a === undefined ? 1 : parseInt(a, 16) / max\n };\n };\n\n if (hexString.startsWith('#')) {\n if (hexString.length === 4 || hexString.length === 5) {\n const hexMatch = hexString.match(HEX_SINGLE_CHAR_COMPONENTS_PATTERN);\n if (hexMatch) {\n const [r, g, b, a] = hexMatch;\n return rgbaHexToColor(r, g, b, a, 15);\n }\n }\n if (hexString.length === 7 || hexString.length === 8) {\n const hexMatch = hexString.match(HEX_DOUBLE_CHAR_COMPONENTS_PATTERN);\n if (hexMatch) {\n const [r, g, b, a] = hexMatch;\n return rgbaHexToColor(r, g, b, a, 255);\n }\n }\n }\n\n throw new Error(\n 'Invalid hex string! Allowed RGB formats are \"#FFF\" and \"#FFFFFF\". Allowed RGBA formats are \"#FFFF\" and \"#FFFFFFFF'\n );\n};\n\n/** @public */\nexport const isValidHexColor = (hexString: string): boolean => {\n return HEX_COLOR_PATTERN.test(hexString);\n};\n", "import type CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { CreativeEngine } from '@cesdk/cesdk-js';\n\n/**\n * Uploads a blob with the help of CE.SDK\n */\nexport async function uploadBlob(\n blob: Blob,\n initialUri: string,\n cesdk: CreativeEditorSDK\n) {\n const pathname = new URL(initialUri).pathname;\n const parts = pathname.split('/');\n const extension = mimeTypeToExtension(blob.type);\n const filename = parts[parts.length - 1]?.split('.')?.[0] ?? 'asset';\n const filenameWithExtension = `${filename}.${extension}`;\n\n const uploadedAssets = await cesdk.unstable_upload(\n new File([blob], filenameWithExtension, { type: blob.type }),\n () => {\n // TODO Delegate process to UI component\n }\n );\n\n const url = uploadedAssets.meta?.uri;\n if (url == null) {\n throw new Error('Could not upload processed fill');\n }\n return url;\n}\n\n/**\n * Returns the file extension for a given mime type.\n */\nexport function mimeTypeToExtension(mimeType: string): string {\n const extensions: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'image/svg+xml': 'svg'\n };\n return extensions[mimeType] ?? 'png';\n}\n\nexport async function fetchImageBlob(uri: string): Promise<Blob> {\n return fetch(uri).then((response) => response.blob());\n}\n\n/**\n * Converts a buffer URI to a object url.\n */\nexport async function bufferURIToObjectURL(\n uri: string,\n engine: CreativeEngine\n): Promise<string> {\n if (uri.startsWith('buffer:')) {\n const mimeType = await engine.editor.getMimeType(uri);\n const length = engine.editor.getBufferLength(uri);\n const data = engine.editor.getBufferData(uri, 0, length);\n const blob = new Blob([data], { type: mimeType });\n return URL.createObjectURL(blob);\n } else {\n return uri;\n }\n}\n", "function uuid4() {\n /* eslint-disable no-bitwise */\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n /* eslint-enable no-bitwise */\n });\n}\n\nexport default uuid4;\n", "import { bufferURIToObjectURL } from './upload';\nimport { type CreativeEngine } from '@cesdk/cesdk-js';\n\n/**\n * Get the dimensions of an image from its URL\n *\n * @param url - The URL of the image\n * @returns A promise that resolves to an object containing the width and height of the image\n */\nexport async function getImageDimensionsFromURL(\n url: string,\n engine: CreativeEngine\n): Promise<{ width: number; height: number }> {\n const resolvedUrl = await bufferURIToObjectURL(url, engine);\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => {\n resolve({ width: img.width, height: img.height });\n };\n img.onerror = reject;\n img.src = resolvedUrl;\n });\n}\n\n/**\n * Get the URI of an image from a block ID, either the first source of a source set or\n * the image file URI. Will handle buffer URIs and convert them to object URLs.\n */\nexport async function getImageUri(\n blockId: number,\n engine: CreativeEngine,\n options?: { throwErrorIfSvg?: boolean }\n): Promise<string> {\n let uri;\n const fillBlock = engine.block.getFill(blockId);\n const sourceSet = engine.block.getSourceSet(\n fillBlock,\n 'fill/image/sourceSet'\n );\n const [source] = sourceSet;\n if (source == null) {\n uri = engine.block.getString(fillBlock, 'fill/image/imageFileURI');\n if (uri == null) throw new Error('No image source/uri found');\n } else {\n uri = source.uri;\n }\n\n // Check if the image is SVG (not supported)\n if (options?.throwErrorIfSvg) {\n const mimeType = await engine.editor.getMimeType(uri);\n if (mimeType === 'image/svg+xml') {\n throw new Error('SVG images are not supported');\n }\n }\n\n return bufferURIToObjectURL(uri, engine);\n}\n", "import formatsIconSprite from './icons/formats';\n\nconst Icons = {\n Formats: formatsIconSprite\n};\n\nexport { Icons };\n\nexport { CustomAssetSource } from './assetSources/CustomAssetSource';\n\nexport { IndexedDBAssetSource } from './assetSources/IndexedDBAssetSource';\n\nexport { AggregatedAssetSource } from './assetSources/AggregatedAssetSource';\n\nexport { default as Metadata } from './metadata/Metadata';\n\nexport { default as FillProcessingMetadata } from './metadata/FillProcessingMetadata';\n\nexport { default as fillProcessing } from './processing/fillProcessing';\n\nexport { default as initializeFillProcessing } from './processing/initializeFillProcessing';\n\nexport { default as registerFillProcessingComponents } from './processing/registerFillProcessingComponents';\n\nexport { type Optional } from './types/Optional';\n\nexport {\n type Location,\n type UserInterfaceConfiguration\n} from './types/UserInterfaceConfiguration';\n\nexport { hexToRgba, isValidHexColor, rgbaToHex } from './utils/colors';\n\nexport {\n uploadBlob,\n fetchImageBlob,\n bufferURIToObjectURL,\n mimeTypeToExtension\n} from './utils/upload';\n\nexport { default as uuid } from './utils/uuid';\n\nexport { getImageDimensionsFromURL, getImageUri } from './utils/images';\n", "/* eslint-disable no-console */\nimport { getImageDimensionsFromURL, getImageUri } from '@imgly/plugin-utils';\nimport {\n type Output,\n type OutputKind,\n type GetBlockInputResult,\n VideoOutput,\n ImageOutput,\n GenerationOptions\n} from '../provider';\nimport { Middleware } from './middleware';\n\ninterface DryRunOptions<K extends OutputKind> {\n kind: K;\n\n // Is only defined with generation from a panel where we create a complete new block\n blockInputs?: GetBlockInputResult<K>;\n\n // Is only defined with quick action generation on a given block(s).\n blockIds?: number[];\n}\n\nfunction dryRunMiddleware<I, K extends OutputKind, O extends Output>(\n options: DryRunOptions<K>\n) {\n const middleware: Middleware<I, O> = async (\n generationInput,\n generationOptions\n ) => {\n console.log(\n `[DRY RUN]: Requesting dummy AI generation for kind '${options.kind}' with inputs: `,\n JSON.stringify(generationInput, undefined, 2)\n );\n await wait(2000);\n const output = await getDryRunOutput(\n generationInput,\n options,\n generationOptions\n );\n return output as O;\n };\n\n return middleware;\n}\n\nasync function getDryRunOutput<K extends OutputKind, I>(\n generationInput: I,\n options: DryRunOptions<K>,\n generationOptions: GenerationOptions\n): Promise<Output> {\n switch (options.kind) {\n case 'image': {\n return getImageDryRunOutput(\n generationInput,\n options as DryRunOptions<'image'>,\n generationOptions\n );\n }\n case 'video': {\n return getVideoDryRunOutput(\n generationInput,\n options as DryRunOptions<'video'>,\n generationOptions\n );\n }\n\n default: {\n throw new Error(\n `Unsupported output kind for creating dry run output: ${options.kind}`\n );\n }\n }\n}\n\nasync function getImageDryRunOutput<I>(\n generationInput: I,\n options: DryRunOptions<'image'>,\n { engine }: GenerationOptions\n): Promise<ImageOutput> {\n let width;\n let height;\n\n const prompt: string =\n generationInput != null &&\n typeof generationInput === 'object' &&\n 'prompt' in generationInput &&\n typeof generationInput.prompt === 'string'\n ? generationInput.prompt\n : 'AI Generated Image';\n\n // If prompt includes something that looks like a dimension\n // e.g. 512x512, 1024x768, etc. than we will use this as the\n // output image size for testing purposes.\n const promptDimension = prompt.match(/(\\d+)x(\\d+)/);\n if (promptDimension != null) {\n width = parseInt(promptDimension[1], 10);\n height = parseInt(promptDimension[2], 10);\n } else {\n if (options.blockInputs != null) {\n width = options.blockInputs.image.width;\n height = options.blockInputs.image.height;\n }\n if (\n options.blockIds != null &&\n Array.isArray(options.blockIds) &&\n options.blockIds.length > 0\n ) {\n const [blockId] = options.blockIds;\n const url = await getImageUri(blockId, engine);\n const dimension = await getImageDimensionsFromURL(url, engine);\n width = dimension.width;\n height = dimension.height;\n } else {\n width = 512;\n height = 512;\n }\n }\n\n const url = `https://placehold.co/${width}x${height}/000000/FFF?text=${prompt\n .replace(' ', '+')\n .replace('\\n', '+')}`;\n\n return {\n kind: 'image',\n url\n };\n}\n\nasync function getVideoDryRunOutput<I>(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _generationInput: I,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _options: DryRunOptions<'video'>,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _generationOptions: GenerationOptions\n): Promise<VideoOutput> {\n return Promise.resolve({\n kind: 'video',\n url: 'https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4'\n });\n}\n\nasync function wait(ms: number) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nexport default dryRunMiddleware;\n", "/* eslint-disable no-console */\nimport type { AssetDefinition, AssetResult } from '@cesdk/cesdk-js';\nimport {\n addAssetToScene,\n isAbortError,\n isAsyncGenerator,\n uuid4\n} from '../utils';\nimport type Provider from './provider';\nimport {\n type GetInput,\n type GetBlockInput,\n OutputKind,\n type Output\n} from './provider';\nimport { InitProviderConfiguration, UIOptions } from './types';\nimport CreativeEditorSDK from '@cesdk/cesdk-js';\nimport getAssetResultForPlaceholder from './getAssetResultForPlaceholder';\nimport getAssetResultForGenerated from './getAssetResultForGenerated';\nimport { composeMiddlewares } from './middleware/middleware';\nimport loggingMiddleware from './middleware/loggingMiddleware';\nimport dryRunMiddleware from './middleware/dryRunMiddleware';\n\ntype Result<O> = { status: 'success'; output: O } | { status: 'aborted' };\n\n/**\n * Generate content using the provider with the given input\n */\nasync function generate<K extends OutputKind, I, O extends Output>(\n kind: K,\n getInput: GetInput<I>,\n getBlockInput: GetBlockInput<K, I>,\n provider: Provider<K, I, O>,\n options: UIOptions & {\n createPlaceholderBlock?: boolean;\n },\n config: InitProviderConfiguration,\n abortSignal: AbortSignal\n): Promise<Result<O>> {\n const { cesdk, createPlaceholderBlock, historyAssetSourceId } = options;\n\n let placeholderBlock: number | undefined;\n\n try {\n if (config.debug) console.group(`Starting Generation for '${kind}'`);\n\n const inputs = getInput();\n const blockInputs = await getBlockInput(inputs.input);\n const assetId = uuid4();\n let assetResult: AssetResult;\n\n // Create a placeholder block\n if (createPlaceholderBlock) {\n assetResult = getAssetResultForPlaceholder(assetId, kind, blockInputs);\n\n if (config.debug)\n console.log(\n 'Adding as asset to scene:',\n JSON.stringify(assetResult, undefined, 2)\n );\n\n placeholderBlock = await addAssetToScene(cesdk, assetResult);\n // This is a workaround. The middleware in the video timeline\n // is calling APIs that will render the block in an error\n // state if it does not have an URI set. It's difficult to\n // recover from that. A bug report has been created for this.\n // As a workaround: Duplicating the block will remove the error state\n // but you will still see an error in the web console.\n // TODO: Remove this workaround when the bug is fixed.\n if (placeholderBlock != null && provider.kind === 'video') {\n const positionX = cesdk.engine.block.getPositionX(placeholderBlock);\n const positionY = cesdk.engine.block.getPositionY(placeholderBlock);\n const duplicated = cesdk.engine.block.duplicate(placeholderBlock);\n cesdk.engine.block.setPositionX(duplicated, positionX);\n cesdk.engine.block.setPositionY(duplicated, positionY);\n cesdk.engine.block.destroy(placeholderBlock);\n placeholderBlock = duplicated;\n }\n // placeholderBlock = await options.engine.asset.defaultApplyAsset(\n // assetResult\n // );\n\n if (checkAbortSignal(cesdk, abortSignal, placeholderBlock))\n return { status: 'aborted' };\n\n if (placeholderBlock == null)\n throw new Error('Could not create placeholder block');\n\n cesdk.engine.block.setState(placeholderBlock, {\n type: 'Pending',\n progress: 0\n });\n }\n\n // Trigger the generation\n const composedMiddlewares = composeMiddlewares<I, O>([\n ...(provider.output.middleware ?? []),\n config.debug ? loggingMiddleware() : undefined,\n config.dryRun\n ? dryRunMiddleware({ kind: provider.kind, blockInputs })\n : undefined\n ]);\n\n const { result: output } = await composedMiddlewares(\n provider.output.generate\n )(inputs.input, {\n abortSignal,\n engine: options.engine,\n cesdk\n });\n\n if (isAsyncGenerator(output)) {\n throw new Error('Streaming generation is not supported yet from a panel');\n }\n\n if (checkAbortSignal(cesdk, abortSignal, placeholderBlock))\n return { status: 'aborted' };\n\n if (output == null) throw new Error('Generation failed');\n\n if (config.debug)\n console.log('Generated output:', JSON.stringify(output, undefined, 2));\n\n let generatedAssetResult: AssetResult | undefined;\n if (\n placeholderBlock != null &&\n cesdk.engine.block.isValid(placeholderBlock)\n ) {\n generatedAssetResult = await getAssetResultForGenerated(\n assetId,\n kind,\n blockInputs,\n output\n );\n if (config.debug)\n console.log(\n 'Updating asset in scene:',\n JSON.stringify(generatedAssetResult, undefined, 2)\n );\n\n await cesdk.engine.asset.defaultApplyAssetToBlock(\n generatedAssetResult,\n placeholderBlock\n );\n }\n\n if (checkAbortSignal(cesdk, abortSignal, placeholderBlock))\n return { status: 'aborted' };\n\n if (historyAssetSourceId != null) {\n if (generatedAssetResult == null) {\n generatedAssetResult = await getAssetResultForGenerated(\n assetId,\n kind,\n blockInputs,\n output\n );\n if (checkAbortSignal(cesdk, abortSignal, placeholderBlock))\n return { status: 'aborted' };\n }\n const assetDefinition: AssetDefinition = {\n ...generatedAssetResult,\n id: `${Date.now()}-${generatedAssetResult.id}`,\n label:\n generatedAssetResult.label != null\n ? {\n en: generatedAssetResult.label\n }\n : {},\n tags: {}\n };\n\n cesdk.engine.asset.addAssetToSource(\n historyAssetSourceId,\n assetDefinition\n );\n }\n\n if (\n placeholderBlock != null &&\n cesdk.engine.block.isValid(placeholderBlock)\n ) {\n cesdk.engine.block.setState(placeholderBlock, {\n type: 'Ready'\n });\n }\n return { status: 'success', output };\n } catch (error) {\n if (\n placeholderBlock != null &&\n cesdk.engine.block.isValid(placeholderBlock)\n ) {\n if (isAbortError(error)) {\n cesdk.engine.block.destroy(placeholderBlock);\n } else {\n cesdk.engine.block.setState(placeholderBlock, {\n type: 'Error',\n error: 'Unknown'\n });\n }\n }\n throw error;\n } finally {\n if (config.debug) console.groupEnd();\n }\n}\n\n/**\n * Check the given abort signal and destroy the placeholder block if it is aborted.\n * @returns `true` if the signal is aborted, `false` otherwise.\n */\nfunction checkAbortSignal(\n cesdk: CreativeEditorSDK,\n abortSignal: AbortSignal,\n placeholderBlock?: number\n) {\n if (abortSignal.aborted) {\n if (\n placeholderBlock != null &&\n cesdk.engine.block.isValid(placeholderBlock)\n ) {\n cesdk.engine.block.destroy(placeholderBlock);\n }\n return true;\n }\n return false;\n}\n\nexport default generate;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport Provider, { GetInput, Output, OutputKind } from './provider';\nimport { InitProviderConfiguration } from './types';\nimport { extractErrorMessage } from '../utils';\n\nfunction handleGenerationError<K extends OutputKind, I, O extends Output>(\n error: unknown,\n options: {\n cesdk: CreativeEditorSDK;\n provider: Provider<K, I, O>;\n getInput?: GetInput<I>;\n },\n config: InitProviderConfiguration\n) {\n const { cesdk, provider, getInput } = options;\n\n if (config.onError != null && typeof config.onError === 'function') {\n config.onError(error);\n } else {\n // eslint-disable-next-line no-console\n console.error('Generation failed:', error);\n const shown = showErrorNotification(\n cesdk,\n provider.output.notification,\n () => ({\n input: getInput?.().input,\n error\n })\n );\n if (!shown) {\n cesdk.ui.showNotification({\n type: 'error',\n message: extractErrorMessage(error)\n });\n }\n }\n}\n\nfunction showErrorNotification<I, O extends Output>(\n cesdk: CreativeEditorSDK,\n notifications: Provider<any, I, O>['output']['notification'],\n createContext: () => { input?: I; error: unknown }\n): boolean {\n const errorNotification = notifications?.error;\n if (errorNotification == null) return false;\n\n const showOnSuccess =\n typeof errorNotification.show === 'function'\n ? errorNotification.show(createContext())\n : errorNotification.show;\n\n if (!showOnSuccess) return false;\n\n const message =\n typeof errorNotification.message === 'function'\n ? errorNotification.message(createContext())\n : errorNotification.message ?? 'common.ai-generation.failed';\n\n const action =\n errorNotification.action != null\n ? {\n label:\n typeof errorNotification.action.label === 'function'\n ? errorNotification.action.label(createContext())\n : errorNotification.action.label,\n onClick: () => {\n errorNotification?.action?.onClick(createContext());\n }\n }\n : undefined;\n\n cesdk.ui.showNotification({\n type: 'error',\n message,\n action\n });\n return true;\n}\n\nexport default handleGenerationError;\n", "import CreativeEditorSDK, {\n type BuilderRenderFunctionContext\n} from '@cesdk/cesdk-js';\nimport type Provider from './provider';\nimport {\n type GetInput,\n type OutputKind,\n type Output,\n type GetBlockInput\n} from './provider';\nimport { InitProviderConfiguration, UIOptions } from './types';\nimport generate from './generate';\nimport { isAbortError } from '../utils';\nimport handleGenerationError from './handleGenerationError';\n\nexport function isGeneratingStateKey(providerId: string): string {\n return `${providerId}.generating`;\n}\n\nexport function abortGenerationStateKey(providerId: string): string {\n return `${providerId}.abort`;\n}\n\n/**\n * Renders the generation UI components and sets up event handlers\n */\nfunction renderGenerationComponents<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n provider: Provider<K, I, O>,\n getInput: GetInput<I>,\n getBlockInput: GetBlockInput<K, I>,\n options: UIOptions & {\n createPlaceholderBlock?: boolean;\n includeHistoryLibrary?: boolean;\n requiredInputs?: string[];\n },\n config: InitProviderConfiguration\n): void {\n const { builder, experimental } = context;\n const { cesdk, includeHistoryLibrary = true } = options;\n const {\n id: providerId,\n output: { abortable }\n } = provider;\n const abortState = experimental.global<() => void>(\n abortGenerationStateKey(providerId),\n () => {}\n );\n const generatingState = experimental.global<boolean>(\n isGeneratingStateKey(providerId),\n false\n );\n\n let abortController: AbortController | undefined;\n const canAbortNow = generatingState.value && abortable;\n const abort = () => {\n if (canAbortNow) {\n abortState.value();\n generatingState.setValue(false);\n abortState.setValue(() => {});\n }\n };\n\n let isDisabled: boolean | undefined;\n if (options.requiredInputs != null && options.requiredInputs.length > 0) {\n const inputs = getInput();\n isDisabled = options.requiredInputs.every((input) => {\n // @ts-ignore\n const hasInput = !inputs.input[input];\n return hasInput;\n });\n }\n\n const confirmCancelDialogId = experimental.global<string | undefined>(\n `${providerId}.confirmationDialogId`,\n undefined\n );\n\n builder.Section(`${providerId}.generate.section`, {\n children: () => {\n builder.Button(`${providerId}.generate`, {\n label: [\n 'common.ai-generation.generate',\n `panel.${providerId}.generate`\n ],\n isLoading: generatingState.value,\n color: 'accent',\n isDisabled,\n suffix: canAbortNow\n ? {\n icon: '@imgly/Cross',\n color: 'danger',\n tooltip: [`panel.${providerId}.abort`, 'common.cancel'],\n onClick: () => {\n const confirmationDialogId = cesdk.ui.showDialog({\n type: 'warning',\n content: 'panel.ly.img.ai.generation.confirmCancel.content',\n cancel: {\n label: 'common.close',\n onClick: ({ id }) => {\n cesdk.ui.closeDialog(id);\n confirmCancelDialogId.setValue(undefined);\n }\n },\n actions: {\n label: 'panel.ly.img.ai.generation.confirmCancel.confirm',\n color: 'danger',\n onClick: ({ id }) => {\n abort();\n cesdk.ui.closeDialog(id);\n confirmCancelDialogId.setValue(undefined);\n }\n }\n });\n confirmCancelDialogId.setValue(confirmationDialogId);\n }\n }\n : undefined,\n onClick: async () => {\n abortController = new AbortController();\n const abortSignal = abortController.signal;\n\n const triggerGeneration = async () => {\n try {\n generatingState.setValue(true);\n abortState.setValue(() => {\n if (config.debug)\n // eslint-disable-next-line no-console\n console.log('Aborting generation');\n abortController?.abort();\n });\n\n const result = await generate(\n provider.kind,\n getInput,\n getBlockInput,\n provider,\n options,\n config,\n abortSignal\n );\n\n if (result.status === 'aborted') {\n return;\n }\n\n const notification = provider.output.notification;\n showSuccessNotification(cesdk, notification, () => ({\n input: getInput().input,\n output: result.output\n }));\n } catch (error) {\n // Do not treat abort errors as errors\n if (isAbortError(error)) {\n return;\n }\n\n handleGenerationError(\n error,\n {\n cesdk,\n provider,\n getInput\n },\n config\n );\n } finally {\n abortController = undefined;\n generatingState.setValue(false);\n abortState.setValue(() => {});\n\n if (confirmCancelDialogId.value != null) {\n cesdk.ui.closeDialog(confirmCancelDialogId.value);\n confirmCancelDialogId.setValue(undefined);\n }\n }\n };\n\n if (config.middleware != null) {\n await config.middleware(triggerGeneration, {\n provider,\n abort\n });\n } else {\n await triggerGeneration();\n }\n }\n });\n if (provider.output.generationHintText != null) {\n builder.Text(`${providerId}.generation-hint`, {\n align: 'center',\n content: provider.output.generationHintText\n });\n }\n }\n });\n\n if (includeHistoryLibrary && options.historyAssetLibraryEntryId != null) {\n builder.Library(`${providerId}.history.library`, {\n entries: [options.historyAssetLibraryEntryId]\n });\n }\n}\n\nfunction showSuccessNotification<I, O extends Output>(\n cesdk: CreativeEditorSDK,\n notifications: Provider<any, I, O>['output']['notification'],\n createContext: () => { input: I; output: O }\n): boolean {\n const successNotification = notifications?.success;\n if (successNotification == null) return false;\n\n const showOnSuccess =\n typeof successNotification.show === 'function'\n ? successNotification.show(createContext())\n : successNotification.show;\n\n if (!showOnSuccess) return false;\n\n const message =\n typeof successNotification.message === 'function'\n ? successNotification.message(createContext())\n : successNotification.message ?? 'common.ai-generation.success';\n\n const action =\n successNotification.action != null\n ? {\n label:\n typeof successNotification.action.label === 'function'\n ? successNotification.action.label(createContext())\n : successNotification.action.label,\n onClick: () => {\n successNotification?.action?.onClick(createContext());\n }\n }\n : undefined;\n\n cesdk.ui.showNotification({\n type: 'success',\n message,\n action,\n duration: successNotification.duration\n });\n return true;\n}\n\nexport default renderGenerationComponents;\n", "import { OpenAPIV3 } from 'openapi-types';\nimport dereferenceDocument, {\n resolveReference\n} from './openapi/dereferenceDocument';\nimport {\n type OutputKind,\n type Output,\n type PanelInputSchema\n} from './provider';\nimport type Provider from './provider';\nimport { InitProviderConfiguration, UIOptions } from './types';\nimport { isOpenAPISchema } from './openapi/isOpenAPISchema';\nimport { GetPropertyInput, PropertyInput } from './openapi/types';\nimport renderProperty from './openapi/renderProperty';\nimport renderGenerationComponents from './renderGenerationComponents';\nimport getProperties from './openapi/getProperties';\nimport { BuilderRenderFunction } from '@cesdk/cesdk-js';\nimport { getPanelId } from '../utils';\n\n/**\n * Registers a schema-based panel input for a provider\n */\nasync function registerPanelInputSchema<\n K extends OutputKind,\n I,\n O extends Output\n>(\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): Promise<BuilderRenderFunction<any>> {\n const { cesdk } = options;\n const { id: providerId } = provider;\n\n if (config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n `Registering schema-based panel input for provider ${providerId}`\n );\n }\n\n const schemaDocument = dereferenceDocument(panelInput.document);\n const resolvedInputReference = resolveReference(\n schemaDocument,\n panelInput.inputReference\n );\n\n if (!isOpenAPISchema(resolvedInputReference, config.debug)) {\n throw new Error(\n `Input reference '${panelInput.inputReference}' does not resolve to a valid OpenAPI schema`\n );\n }\n\n const inputSchema: OpenAPIV3.SchemaObject = resolvedInputReference;\n const properties = getProperties(inputSchema, panelInput);\n\n const builderRenderFunction: BuilderRenderFunction<any> = (context) => {\n const { builder } = context;\n\n const getInputs: GetPropertyInput[] = [];\n builder.Section(`${providerId}.schema.section`, {\n children: () => {\n properties.forEach((property) => {\n const getInput = renderProperty(\n context,\n property,\n provider,\n panelInput,\n options,\n config\n );\n if (getInput != null) {\n if (Array.isArray(getInput)) {\n getInputs.push(...getInput);\n } else {\n getInputs.push(getInput);\n }\n }\n });\n }\n });\n\n const inputs = getInputs.map((getInput) => {\n const input = getInput();\n return input;\n });\n\n const resolveInput = (input: PropertyInput) => {\n if (input.type === 'object') {\n return Object.entries(input.value).reduce((acc, [key, value]) => {\n acc[key] = resolveInput(value);\n\n return acc;\n }, {} as Record<string, any>);\n }\n\n return input.value;\n };\n const input = inputs.reduce((acc, propertyInput) => {\n acc[propertyInput.id] = resolveInput(propertyInput);\n return acc;\n }, {} as Record<string, any>) as I;\n\n renderGenerationComponents(\n context,\n provider,\n () => {\n return { input };\n },\n () => {\n return panelInput.getBlockInput(input);\n },\n {\n ...options,\n requiredInputs: inputSchema.required,\n createPlaceholderBlock: panelInput.userFlow === 'placeholder'\n },\n config\n );\n };\n\n cesdk.ui.registerPanel(getPanelId(providerId), builderRenderFunction);\n return builderRenderFunction;\n}\n\nexport default registerPanelInputSchema;\n", "import { BuilderRenderFunction } from '@cesdk/cesdk-js';\nimport type Provider from './provider';\nimport { OutputKind, PanelInputCustom, type Output } from './provider';\nimport renderGenerationComponents, {\n isGeneratingStateKey\n} from './renderGenerationComponents';\nimport { InitProviderConfiguration, UIOptions } from './types';\nimport { getPanelId } from '../utils';\n\nasync function registerPanelInputCustom<\n K extends OutputKind,\n I,\n O extends Output\n>(\n provider: Provider<K, I, O>,\n panelInput: PanelInputCustom<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): Promise<BuilderRenderFunction<any>> {\n const { cesdk } = options;\n const { id: providerId } = provider;\n\n const render = panelInput.render;\n\n const builderRenderFunction: BuilderRenderFunction<any> = (context) => {\n const { state } = context;\n\n const isGenerating = state(isGeneratingStateKey(providerId), {\n isGenerating: false,\n abort: () => {}\n }).value.isGenerating;\n\n const { getInput, getBlockInput } = render(context, {\n cesdk,\n isGenerating\n });\n renderGenerationComponents(\n context,\n provider,\n getInput,\n getBlockInput,\n {\n ...options,\n includeHistoryLibrary: panelInput.includeHistoryLibrary ?? true,\n createPlaceholderBlock: panelInput.userFlow === 'placeholder'\n },\n config\n );\n\n return getInput;\n };\n\n cesdk.ui.registerPanel(getPanelId(providerId), builderRenderFunction);\n\n return builderRenderFunction;\n}\n\nexport default registerPanelInputCustom;\n", "export const PLUGIN_ICON_SET_ID = '@imgly/plugin-ai-generation';\n\nexport const ICON_SPRITE = `\n<svg>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/Sparkle\"\n >\n <path d=\"M5.35545 2.06745C5.24149 1.72556 4.7579 1.72556 4.64394 2.06745L4.05898 3.82232C4.02166 3.93429 3.9338 4.02215 3.82184 4.05948L2.06694 4.64459C1.72506 4.75858 1.72509 5.24217 2.06699 5.3561L3.82179 5.9409C3.93378 5.97822 4.02166 6.06609 4.05899 6.17808L4.64394 7.93291C4.7579 8.2748 5.24149 8.2748 5.35545 7.93291L5.9404 6.17806C5.97773 6.06608 6.06559 5.97821 6.17757 5.94089L7.93242 5.35594C8.27431 5.24198 8.27431 4.75839 7.93242 4.64442L6.17757 4.05947C6.06559 4.02215 5.97773 3.93428 5.9404 3.8223L5.35545 2.06745Z\" fill=\"currentColor\"/>\n<path d=\"M17.9632 3.23614C17.8026 2.80788 17.1968 2.80788 17.0362 3.23614L16.0787 5.78951C16.0285 5.92337 15.9229 6.02899 15.789 6.07918L13.2356 7.0367C12.8074 7.19729 12.8074 7.80307 13.2356 7.96366L15.789 8.92118C15.9229 8.97138 16.0285 9.077 16.0787 9.21085L17.0362 11.7642C17.1968 12.1925 17.8026 12.1925 17.9632 11.7642L18.9207 9.21086C18.9709 9.077 19.0765 8.97138 19.2104 8.92118L21.7637 7.96366C22.192 7.80307 22.192 7.1973 21.7637 7.0367L19.2104 6.07918C19.0765 6.02899 18.9709 5.92337 18.9207 5.78951L17.9632 3.23614Z\" fill=\"currentColor\"/>\n<path d=\"M9.30058 7.82012C9.54712 7.1791 10.454 7.1791 10.7006 7.82012L12.3809 12.189C12.4571 12.3871 12.6136 12.5436 12.8117 12.6198L17.1806 14.3001C17.8216 14.5466 17.8216 15.4536 17.1806 15.7001L12.8117 17.3804C12.6136 17.4566 12.4571 17.6131 12.3809 17.8112L10.7006 22.1801C10.454 22.8211 9.54712 22.8211 9.30058 22.1801L7.62024 17.8112C7.54406 17.6131 7.38754 17.4566 7.18947 17.3804L2.82061 15.7001C2.17959 15.4536 2.17959 14.5466 2.82061 14.3001L7.18947 12.6198C7.38754 12.5436 7.54406 12.3871 7.62024 12.189L9.30058 7.82012Z\" fill=\"currentColor\"/>\n\n </symbol>\n\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"${PLUGIN_ICON_SET_ID}/image\"\n >\n <path d=\"M3 16.5V18C3 19.6569 4.34315 21 6 21H18C19.6569 21 21 19.6569 21 18V6C21 4.34315 19.6569 3 18 3L17.999 5C18.5513 5 19 5.44772 19 6V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V16.5H3Z\" fill=\"currentColor\"/>\n<path d=\"M13.0982 0.884877C12.9734 0.568323 12.5254 0.568322 12.4005 0.884876L11.7485 2.53819C11.7104 2.63483 11.6339 2.71134 11.5372 2.74945L9.8839 3.40151C9.56735 3.52636 9.56734 3.97436 9.8839 4.09921L11.5372 4.75126C11.6339 4.78938 11.7104 4.86588 11.7485 4.96253L12.4005 6.61584C12.5254 6.93239 12.9734 6.9324 13.0982 6.61584L13.7503 4.96253C13.7884 4.86588 13.8649 4.78938 13.9616 4.75126L15.6149 4.09921C15.9314 3.97436 15.9314 3.52636 15.6149 3.40151L13.9616 2.74945C13.8649 2.71134 13.7884 2.63483 13.7503 2.53819L13.0982 0.884877Z\" fill=\"currentColor\"/>\n<path d=\"M6.40053 5.38488C6.52538 5.06832 6.97338 5.06832 7.09823 5.38488L8.17455 8.11392C8.21267 8.21057 8.28917 8.28707 8.38582 8.32519L11.1149 9.40151C11.4314 9.52636 11.4314 9.97436 11.1149 10.0992L8.38582 11.1755C8.28917 11.2136 8.21267 11.2901 8.17455 11.3868L7.09823 14.1158C6.97338 14.4324 6.52538 14.4324 6.40053 14.1158L5.32421 11.3868C5.2861 11.2901 5.20959 11.2136 5.11295 11.1755L2.3839 10.0992C2.06735 9.97436 2.06735 9.52636 2.3839 9.40151L5.11295 8.32519C5.20959 8.28707 5.2861 8.21057 5.32421 8.11392L6.40053 5.38488Z\" fill=\"currentColor\"/>\n<path d=\"M18.9994 16.5008V18.0004C18.9994 18.5526 18.5517 19.0004 17.9994 19.0004H9.33302L14.3753 11.4369C14.6722 10.9916 15.3266 10.9916 15.6234 11.4369L18.9994 16.5008Z\" fill=\"currentColor\"/>\n\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"${PLUGIN_ICON_SET_ID}/video\"\n >\n<path d=\"M6 3C4.34315 3 3 4.34315 3 6V18C3 19.6569 4.34315 21 6 21H18C19.6569 21 21 19.6569 21 18V16.5H19V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V6C5 5.44772 5.44772 5 6 5V3Z\" fill=\"currentColor\"/>\n<path d=\"M10.9025 0.8839C11.0273 0.567345 11.4753 0.567346 11.6002 0.883901L12.2522 2.53721C12.2904 2.63386 12.3669 2.71036 12.4635 2.74848L14.1168 3.40053C14.4334 3.52538 14.4334 3.97338 14.1168 4.09823L12.4635 4.75029C12.3669 4.7884 12.2904 4.86491 12.2522 4.96155L11.6002 6.61486C11.4753 6.93142 11.0273 6.93142 10.9025 6.61486L10.2504 4.96155C10.2123 4.86491 10.1358 4.7884 10.0392 4.75029L8.38585 4.09823C8.0693 3.97338 8.0693 3.52538 8.38585 3.40053L10.0392 2.74848C10.1358 2.71036 10.2123 2.63386 10.2504 2.53721L10.9025 0.8839Z\" fill=\"currentColor\"/>\n<path d=\"M18.9019 3.3845C19.0267 3.06795 19.4747 3.06795 19.5996 3.3845L20.6759 6.11355C20.714 6.2102 20.7905 6.2867 20.8872 6.32482L23.6162 7.40114C23.9328 7.52598 23.9328 7.97399 23.6162 8.09883L20.8872 9.17515C20.7905 9.21327 20.714 9.28977 20.6759 9.38642L19.5996 12.1155C19.4747 12.432 19.0267 12.432 18.9019 12.1155L17.8255 9.38642C17.7874 9.28977 17.7109 9.21327 17.6143 9.17515L14.8852 8.09883C14.5687 7.97399 14.5687 7.52598 14.8852 7.40114L17.6143 6.32482C17.7109 6.2867 17.7874 6.2102 17.8255 6.11355L18.9019 3.3845Z\" fill=\"currentColor\"/>\n<path d=\"M14.9994 13.2862C15.5089 12.8859 15.5089 12.1141 14.9995 11.7137L10.618 8.27047C9.96188 7.75485 9.00011 8.22225 9.00011 9.05673L9.00011 15.9429C9.00011 16.7773 9.96185 17.2448 10.618 16.7292L14.9994 13.2862Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"${PLUGIN_ICON_SET_ID}/audio\"\n >\n <path d=\"M6 3.80273C4.2066 4.84016 3 6.77919 3 9.00004V12.8153C3 15.931 5.39501 18.4873 8.44444 18.7436V20.9645C8.44444 22.2198 9.89427 22.9198 10.8773 22.1392L15.1265 18.7647H15.5C17.8285 18.7647 19.8472 17.4384 20.8417 15.5H18.4187C17.6889 16.2784 16.6512 16.7647 15.5 16.7647H14.9522C14.6134 16.7647 14.2846 16.8794 14.0193 17.0901L10.4444 19.929V18.2597C10.4444 17.4341 9.77513 16.7647 8.9495 16.7647C7.80494 16.7647 6.77409 16.2779 6.05276 15.5H6V15.4419C5.37798 14.7439 5 13.8237 5 12.8153V9.00004C5 7.98559 5.37764 7.05935 6 6.35422V3.80273Z\" fill=\"currentColor\"/>\n<path d=\"M11.6002 1.8839C11.4753 1.56735 11.0273 1.56735 10.9025 1.8839L10.2504 3.53721C10.2123 3.63386 10.1358 3.71036 10.0392 3.74848L8.38585 4.40053C8.0693 4.52538 8.0693 4.97338 8.38585 5.09823L10.0392 5.75029C10.1358 5.7884 10.2123 5.86491 10.2504 5.96155L10.9025 7.61486C11.0273 7.93142 11.4753 7.93142 11.6002 7.61486L12.2522 5.96155C12.2904 5.86491 12.3669 5.7884 12.4635 5.75029L14.1168 5.09823C14.4334 4.97338 14.4334 4.52538 14.1168 4.40053L12.4635 3.74848C12.3669 3.71036 12.2904 3.63386 12.2522 3.53721L11.6002 1.8839Z\" fill=\"currentColor\"/>\n<path d=\"M19.5996 4.3845C19.4747 4.06795 19.0267 4.06795 18.9019 4.3845L17.8255 7.11355C17.7874 7.2102 17.7109 7.2867 17.6143 7.32482L14.8852 8.40114C14.5687 8.52598 14.5687 8.97399 14.8852 9.09883L17.6143 10.1752C17.7109 10.2133 17.7874 10.2898 17.8255 10.3864L18.9019 13.1155C19.0267 13.432 19.4747 13.432 19.5996 13.1155L20.6759 10.3864C20.714 10.2898 20.7905 10.2133 20.8872 10.1752L23.6162 9.09883C23.9328 8.97399 23.9328 8.52598 23.6162 8.40114L20.8872 7.32482C20.7905 7.2867 20.714 7.2102 20.6759 7.11355L19.5996 4.3845Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/MixingPlate\"\n >\n <path d=\"M9.75 9C10.5784 9 11.25 8.32843 11.25 7.5C11.25 6.67157 10.5784 6 9.75 6C8.92157 6 8.25 6.67157 8.25 7.5C8.25 8.32843 8.92157 9 9.75 9Z\" fill=\"currentColor\"/>\n<path d=\"M7 13C7.82843 13 8.5 12.3284 8.5 11.5C8.5 10.6716 7.82843 10 7 10C6.17157 10 5.5 10.6716 5.5 11.5C5.5 12.3284 6.17157 13 7 13Z\" fill=\"currentColor\"/>\n<path d=\"M15.75 7.5C15.75 8.32843 15.0784 9 14.25 9C13.4216 9 12.75 8.32843 12.75 7.5C12.75 6.67157 13.4216 6 14.25 6C15.0784 6 15.75 6.67157 15.75 7.5Z\" fill=\"currentColor\"/>\n<path d=\"M17 13C17.8284 13 18.5 12.3284 18.5 11.5C18.5 10.6716 17.8284 10 17 10C16.1716 10 15.5 10.6716 15.5 11.5C15.5 12.3284 16.1716 13 17 13Z\" fill=\"currentColor\"/>\n<path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M8.26309 2.77709C10.6681 1.77921 13.4829 1.7322 15.9209 2.64297C18.1572 3.47923 20.0876 5.09285 21.1766 7.28598C22.3395 9.62772 22.4889 13.1077 20.3864 15.2982C19.2693 16.4621 17.7657 16.9982 16.0026 16.9997C15.7897 16.9997 15.5555 16.9864 15.3497 16.9745C15.309 16.9722 15.2694 16.9699 15.2313 16.9679C14.9817 16.9542 14.761 16.9455 14.5569 16.9539C14.124 16.9718 13.9598 17.0612 13.89 17.1324C13.718 17.3081 13.6946 17.6672 13.8854 17.8895C14.2899 18.3608 14.5016 18.9277 14.5016 19.5497C14.5016 20.2206 14.3086 20.9011 13.7542 21.3896C13.2471 21.837 12.6082 21.9997 11.9635 21.9997C10.6049 21.9997 9.31155 21.7367 8.0934 21.2067C6.89058 20.6831 5.84501 19.9687 4.94363 19.0666C4.04281 18.1651 3.31836 17.107 2.79369 15.8978C1.72761 13.4409 1.72662 10.5261 2.81247 8.07034C3.88024 5.65548 5.84206 3.78161 8.26309 2.77709ZM15.2207 4.51639C13.2556 3.78239 10.9651 3.82132 9.02956 4.62439C7.06888 5.43791 5.49559 6.94785 4.64163 8.87914C3.78373 10.8194 3.78253 13.1522 4.62841 15.1017C5.05312 16.0805 5.63511 16.9291 6.35838 17.6529C7.08102 18.3761 7.91671 18.9484 8.89123 19.3728C9.8492 19.7895 10.87 19.9997 11.9635 19.9997C12.2815 19.9997 12.394 19.9225 12.431 19.8899L12.4319 19.8891C12.4367 19.8849 12.4487 19.8743 12.4631 19.8359C12.4799 19.7911 12.5016 19.7024 12.5016 19.5497C12.5016 19.4091 12.4633 19.3034 12.3677 19.192C11.5353 18.222 11.5272 16.6868 12.4611 15.7331C13.0741 15.1071 13.8844 14.98 14.4745 14.9556C14.7819 14.943 15.085 14.9568 15.3409 14.9709C15.3906 14.9736 15.4379 14.9763 15.4832 14.9788C15.6876 14.9904 15.8508 14.9997 16.0009 14.9997C17.3405 14.9986 18.2792 14.6054 18.9435 13.9133C20.2633 12.5382 20.3186 10.055 19.3853 8.1755C18.5436 6.48051 17.0293 5.19281 15.2207 4.51639Z\" fill=\"currentColor\"/>\n\n </symbol>\n</svg>\n`;\n\nexport default ICON_SPRITE;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { QuickActionId, QuickActionMenu } from './types';\nimport { Output, QuickAction } from '../provider';\n\nconst QUICK_ACTION_ORDER_KEY_PREFIX = 'ly.img.ai.quickAction.order';\n\nconst QUICK_ACTION_REGISTRY_PREFIX = 'ly.img.ai.quickAction.actions';\n\n/**\n * Returns an object representing the quick action menu. Can be called and\n * retrieved multiple times.\n *\n * It's backed up by the global state.\n */\nfunction getQuickActionMenu(cesdk: CreativeEditorSDK, id: string) {\n const quickActionMenu: QuickActionMenu = {\n id,\n setQuickActionMenuOrder: (quickActionIds: string[]) => {\n cesdk.ui.experimental.setGlobalStateValue<QuickActionId[]>(\n `${QUICK_ACTION_ORDER_KEY_PREFIX}.${id}`,\n quickActionIds\n );\n },\n getQuickActionMenuOrder: () => {\n return cesdk.ui.experimental.getGlobalStateValue<QuickActionId[]>(\n `${QUICK_ACTION_ORDER_KEY_PREFIX}.${id}`,\n []\n );\n },\n registerQuickAction: <I, O extends Output>(\n quickAction: QuickAction<I, O>\n ) => {\n if (\n !cesdk.ui.experimental.hasGlobalStateValue(\n `${QUICK_ACTION_REGISTRY_PREFIX}.${id}`\n )\n ) {\n cesdk.ui.experimental.setGlobalStateValue<{\n [key: string]: QuickAction<I, O>;\n }>(`${QUICK_ACTION_REGISTRY_PREFIX}.${id}`, {\n [quickAction.id]: quickAction\n });\n } else {\n const entries = cesdk.ui.experimental.getGlobalStateValue(\n `${QUICK_ACTION_REGISTRY_PREFIX}.${id}`,\n {}\n );\n cesdk.ui.experimental.setGlobalStateValue(\n `${QUICK_ACTION_REGISTRY_PREFIX}.${id}`,\n {\n ...entries,\n [quickAction.id]: quickAction\n }\n );\n }\n },\n\n getQuickAction: <I, O extends Output>(quickActionId: string) => {\n const entries = cesdk.ui.experimental.getGlobalStateValue<{\n [key: string]: QuickAction<I, O>;\n }>(`${QUICK_ACTION_REGISTRY_PREFIX}.${id}`, {});\n\n return entries[quickActionId];\n }\n };\n return quickActionMenu;\n}\n\nexport default getQuickActionMenu;\n", "import { Output, QuickAction } from '../provider';\n\nexport const INFERENCE_AI_EDIT_MODE = 'ly.img.ai.inference.editMode';\n\nexport const INFERENCE_AI_METADATA_KEY = 'ly.img.ai.inference.metadata';\n\nexport const INFERENCE_CONFIRMATION_COMPONENT_ID =\n 'ly.img.ai.inference.confirmation.canvasMenu';\n\nexport function getFeatureIdForQuickAction(options: {\n quickActionId: string;\n quickActionMenuId: string;\n}) {\n return `ly.img.ai.quickAction.${options.quickActionMenuId}.${options.quickActionId}`;\n}\n\n/**\n * Removes all two following `ly.img.separator` entries from the quick\n * actions array or if it is first or last in the array.\n */\nexport function removeDuplicatedSeparators<I, O extends Output>(\n quickActions: (QuickAction<I, O> | 'ly.img.separator')[]\n): (QuickAction<I, O> | 'ly.img.separator')[] {\n if (quickActions.length === 0) {\n return [];\n }\n\n // Create a new array for the result\n const result = [...quickActions];\n\n // Remove separators at the beginning\n while (result.length > 0 && result[0] === 'ly.img.separator') {\n result.shift();\n }\n\n // Remove separators at the end\n while (\n result.length > 0 &&\n result[result.length - 1] === 'ly.img.separator'\n ) {\n result.pop();\n }\n\n // Remove consecutive separators\n return result.reduce<(QuickAction<I, O> | 'ly.img.separator')[]>(\n (acc, current) => {\n // Skip if current is a separator and previous was also a separator\n if (\n current === 'ly.img.separator' &&\n acc.length > 0 &&\n acc[acc.length - 1] === 'ly.img.separator'\n ) {\n return acc;\n }\n\n acc.push(current);\n return acc;\n },\n []\n );\n}\n", "import { Middleware } from './middleware';\nimport { Output } from '../provider';\n\n/**\n * Highlights the blocks while the middleware is running.\n *\n * - Sets the blocks to always on top\n * - Disables clipping of the parent of the blocks so it is visible\n */\nfunction highlightBlocksMiddleware<I, O extends Output>({\n alwaysOnTop = true,\n disableClipping = true\n}: {\n /**\n * Until disposed, should the block be always on top to be visible?\n *\n * @default true\n */\n alwaysOnTop?: boolean;\n\n /**\n * If true, the clipping of the parent of the affected blocks will be\n * temporarily disabled until unlocked.\n *\n * @default true\n */\n disableClipping?: boolean;\n}): Middleware<I, O> {\n const middleware: Middleware<I, O> = async (input, options, next) => {\n const wasAlwaysOnTop: Record<number, boolean> = {};\n const parentClipping: Record<number, boolean> = {};\n\n const blockIds =\n alwaysOnTop || disableClipping\n ? options.blockIds ?? options.engine.block.findAllSelected()\n : [];\n\n blockIds.forEach((blockId) => {\n if (options.engine.block.isValid(blockId))\n if (alwaysOnTop) {\n wasAlwaysOnTop[blockId] = options.engine.block.isAlwaysOnTop(blockId);\n options.engine.block.setAlwaysOnTop(blockId, true);\n }\n if (disableClipping) {\n const parent = options.engine.block.getParent(blockId);\n if (\n parent != null &&\n options.engine.block.getType(parent) !== '//ly.img.ubq/scene'\n ) {\n parentClipping[parent] = options.engine.block.isClipped(parent);\n options.engine.block.setClipped(parent, false);\n }\n }\n });\n\n options.addDisposer(async () => {\n blockIds.forEach((blockId) => {\n if (options.engine.block.isValid(blockId))\n if (alwaysOnTop) {\n options.engine.block.setAlwaysOnTop(\n blockId,\n wasAlwaysOnTop[blockId]\n );\n }\n if (disableClipping) {\n const parent = options.engine.block.getParent(blockId);\n if (\n parent != null &&\n options.engine.block.getType(parent) !== '//ly.img.ubq/scene'\n ) {\n if (parentClipping[parent] != null) {\n options.engine.block.setClipped(parent, parentClipping[parent]);\n }\n }\n }\n });\n });\n const result = await next(input, options);\n\n return result;\n };\n\n return middleware;\n}\n\nexport default highlightBlocksMiddleware;\n", "import { Middleware } from './middleware';\nimport { Output } from '../provider';\n\n/**\n * Sets the blocks to a pending state while the middleware is running.\n */\nfunction pendingMiddleware<I, O extends Output>({\n pending = true\n}: {\n /**\n * Should the blocks be set to a pending state?\n *\n * @default true\n */\n pending?: boolean;\n}): Middleware<I, O> {\n const middleware: Middleware<I, O> = async (input, options, next) => {\n const blockIds = pending\n ? options.blockIds ?? options.engine.block.findAllSelected()\n : [];\n\n try {\n blockIds.forEach((blockId) => {\n if (options.engine.block.isValid(blockId))\n options.engine.block.setState(blockId, {\n type: 'Pending',\n progress: 0\n });\n });\n const result = await next(input, options);\n\n return result;\n } finally {\n blockIds.forEach((blockId) => {\n if (options.engine.block.isValid(blockId))\n options.engine.block.setState(blockId, { type: 'Ready' });\n });\n }\n };\n\n return middleware;\n}\n\nexport default pendingMiddleware;\n", "import { Middleware } from './middleware';\nimport { Output } from '../provider';\nimport { CreativeEngine } from '@cesdk/cesdk-js';\nimport { isAbortError } from '../../utils';\n\n/**\n * Highlights the blocks while the middleware is running.\n */\nfunction lockMiddleware<I, O extends Output>({\n editMode,\n automaticallyUnlock = false\n}: {\n /**\n * The edit mode to lock the selection to.\n */\n editMode: string;\n\n /**\n * Should the selection be automatically unlocked after the function completes?\n * Otherwise the returned unlock function must be called manually.\n *\n * @default false\n */\n automaticallyUnlock?: boolean;\n}): Middleware<I, O> {\n const middleware: Middleware<I, O> = async (input, options, next) => {\n const blockIds = options.blockIds ?? options.engine.block.findAllSelected();\n\n let unlock: () => void = () => {};\n if (!automaticallyUnlock) {\n options.addDisposer(async () => {\n if (unlock != null) {\n unlock();\n }\n });\n }\n try {\n unlock = lockSelectionInEditMode(options.engine, blockIds, editMode);\n const result = await next(input, options);\n return result;\n } catch (error) {\n if (isAbortError(error)) {\n unlock();\n }\n throw error;\n } finally {\n if (automaticallyUnlock) {\n unlock();\n }\n }\n };\n\n return middleware;\n}\n\n/**\n * Locks the selection to the given block ids with the given edit mode.\n *\n * @returns A function to unlock the selection. Will set the edit mode back to what it was before the lock.\n */\nfunction lockSelectionInEditMode(\n engine: CreativeEngine,\n blockIdsToLockOn: number[],\n editModeToLock: string\n) {\n const globalScopeBeforeLock = engine.editor.getGlobalScope('editor/select');\n const editModeBeforeLock = engine.editor.getEditMode();\n selectOnlyBlockIds();\n engine.editor.setGlobalScope('editor/select', 'Deny');\n engine.editor.setEditMode(editModeToLock);\n const lockedHistory = engine.editor.createHistory();\n const historyBeforeLock = engine.editor.getActiveHistory();\n engine.editor.setActiveHistory(lockedHistory);\n\n function selectOnlyBlockIds() {\n engine.block.findAllSelected().forEach((currentlySelectedBlockId) => {\n if (!blockIdsToLockOn.includes(currentlySelectedBlockId)) {\n engine.block.setSelected(currentlySelectedBlockId, false);\n }\n });\n\n blockIdsToLockOn.forEach((blockId) => {\n engine.block.setSelected(blockId, true);\n });\n }\n\n const stateChangeDisposer = engine.editor.onStateChanged(() => {\n const editMode = engine.editor.getEditMode();\n if (editMode !== editModeToLock) {\n engine.editor.setEditMode(editModeToLock);\n }\n });\n\n const selectionDisposer = engine.block.onSelectionChanged(selectOnlyBlockIds);\n\n const dispose = () => {\n if (globalScopeBeforeLock != null) {\n engine.editor.setGlobalScope('editor/select', globalScopeBeforeLock);\n }\n\n engine.editor.setEditMode(editModeBeforeLock);\n engine.editor.setActiveHistory(historyBeforeLock);\n engine.editor.destroyHistory(lockedHistory);\n\n selectionDisposer();\n stateChangeDisposer();\n };\n\n return dispose;\n}\n\nexport default lockMiddleware;\n", "import type CreativeEditorSDK from '@cesdk/cesdk-js';\nimport {\n GenerationResult,\n ImageOutput,\n TextOutput,\n type Output,\n type OutputKind\n} from '../provider';\nimport { ApplyCallbacks } from './types';\nimport {\n getImageDimensionsFromURL,\n mimeTypeToExtension\n} from '@imgly/plugin-utils';\nimport { isAsyncGenerator } from '../../utils';\n\ntype ConsumeGeneratedResultOptions = {\n kind: OutputKind;\n blockIds: number[];\n cesdk: CreativeEditorSDK;\n abortSignal: AbortSignal;\n};\n\ntype ReturnValue<O extends Output> = {\n consumedGenerationResult: O;\n applyCallbacks: ApplyCallbacks;\n};\n\n/**\n * This method is used in the quick action menu to handle the result of the generation\n * and providing methods for the comparision of the result.\n *\n * Different output kinds require different handling. E.g. the text generation\n * is streamed to the text block, while the image generation is applied to the fill\n * block with a source set and the same crop applied.\n */\nfunction consumeGeneratedResult<O extends Output>(\n result: GenerationResult<O>,\n options: ConsumeGeneratedResultOptions\n): Promise<ReturnValue<O>> {\n switch (options.kind) {\n case 'text':\n return getApplyCallbacksForText(result, options);\n case 'image':\n return getApplyCallbacksForImage(result, options);\n case 'video':\n return getApplyCallbacksForVideo(result, options);\n case 'audio':\n return getApplyCallbacksForAudio(result, options);\n default:\n throw new Error(\n `Unsupported output kind for quick actions: ${options.kind}`\n );\n }\n}\n\nasync function getApplyCallbacksForText<O extends Output>(\n generationResult: GenerationResult<O>,\n options: ConsumeGeneratedResultOptions\n): Promise<ReturnValue<O>> {\n const { cesdk, blockIds, abortSignal } = options;\n\n const beforeTexts = blockIds.map((blockId) => {\n return cesdk.engine.block.getString(blockId, 'text/text');\n });\n\n let output: O | undefined;\n if (isAsyncGenerator(generationResult)) {\n let inferredText = '';\n for await (const chunk of generationResult) {\n if (abortSignal.aborted) {\n break;\n }\n if (typeof chunk === 'string') {\n inferredText = chunk;\n } else if (chunk.kind === 'text') {\n inferredText = chunk.text;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-loop-func\n blockIds.forEach((blockId) => {\n cesdk.engine.block.setString(blockId, 'text/text', inferredText);\n });\n\n const textOutput: TextOutput = {\n kind: 'text',\n text: inferredText\n };\n output = textOutput as O;\n }\n } else {\n output = generationResult;\n }\n\n if (output == null || output.kind !== 'text') {\n throw new Error('Output kind from generation is not text');\n }\n\n const onAfter = () => {\n options.blockIds.forEach((blockId) => {\n options.cesdk.engine.block.setString(blockId, 'text/text', output.text);\n });\n };\n const onBefore = () => {\n options.blockIds.forEach((blockId, i) => {\n options.cesdk.engine.block.setString(\n blockId,\n 'text/text',\n beforeTexts[i]\n );\n });\n };\n const onCancel = onBefore;\n const onApply = () => {\n onAfter();\n options.cesdk.engine.editor.addUndoStep();\n };\n\n return {\n consumedGenerationResult: output,\n applyCallbacks: {\n onBefore,\n onAfter,\n onCancel,\n onApply\n }\n };\n}\n\nasync function getApplyCallbacksForImage<O extends Output>(\n generationResult: GenerationResult<O>,\n options: ConsumeGeneratedResultOptions\n): Promise<ReturnValue<O>> {\n const { cesdk, blockIds, abortSignal } = options;\n if (blockIds.length !== 1) {\n throw new Error('Only one block is supported for image generation');\n }\n\n const [block] = blockIds;\n const fillBlock = cesdk.engine.block.getFill(block);\n const sourceSetBefore = cesdk.engine.block.getSourceSet(\n fillBlock,\n 'fill/image/sourceSet'\n );\n const [sourceBefore] = sourceSetBefore;\n let uriBefore: string | undefined;\n if (sourceBefore == null) {\n uriBefore = cesdk.engine.block.getString(\n fillBlock,\n 'fill/image/imageFileURI'\n );\n }\n\n const mimeType = await cesdk.engine.editor.getMimeType(\n sourceBefore?.uri ?? uriBefore\n );\n const originalDimension = await getImageDimensionsFromURL(\n sourceBefore?.uri ?? uriBefore,\n options.cesdk.engine\n );\n const originalAspectRatio =\n originalDimension.width / originalDimension.height;\n abortSignal.throwIfAborted();\n\n if (mimeType === 'image/svg+xml') {\n throw new Error('SVG images are not supported');\n }\n\n const cropScaleX = cesdk.engine.block.getCropScaleX(block);\n const cropScaleY = cesdk.engine.block.getCropScaleY(block);\n const cropTranslationX = cesdk.engine.block.getCropTranslationX(block);\n const cropTranslationY = cesdk.engine.block.getCropTranslationY(block);\n const cropRotation = cesdk.engine.block.getCropRotation(block);\n\n const applyCrop = () => {\n cesdk.engine.block.setCropScaleX(block, cropScaleX);\n cesdk.engine.block.setCropScaleY(block, cropScaleY);\n cesdk.engine.block.setCropTranslationX(block, cropTranslationX);\n cesdk.engine.block.setCropTranslationY(block, cropTranslationY);\n cesdk.engine.block.setCropRotation(block, cropRotation);\n };\n\n if (isAsyncGenerator(generationResult)) {\n throw new Error('Streaming generation is not supported yet from a panel');\n }\n\n if (\n generationResult.kind !== 'image' ||\n typeof generationResult.url !== 'string'\n ) {\n throw new Error('Output kind from generation is not an image');\n }\n\n const url = (generationResult as ImageOutput).url;\n const generatedMimeType = await cesdk.engine.editor.getMimeType(url);\n\n const uri = await reuploadImage(cesdk, url, generatedMimeType);\n const generatedDimension = await getImageDimensionsFromURL(\n uri,\n options.cesdk.engine\n );\n const generatedAspectRatio =\n generatedDimension.width / generatedDimension.height;\n\n const differentAspectRatio =\n Math.abs(originalAspectRatio - generatedAspectRatio) > 0.001;\n\n const sourceSetAfter = sourceBefore\n ? [\n {\n uri,\n width: sourceBefore.width,\n height: sourceBefore.height\n }\n ]\n : undefined;\n const uriAfter = uri;\n\n if (sourceSetAfter == null) {\n cesdk.engine.block.setString(\n fillBlock,\n 'fill/image/imageFileURI',\n uriAfter\n );\n } else {\n cesdk.engine.block.setSourceSet(\n fillBlock,\n 'fill/image/sourceSet',\n sourceSetAfter\n );\n }\n if (differentAspectRatio) {\n cesdk.engine.block.setContentFillMode(block, 'Cover');\n } else {\n applyCrop();\n }\n\n const onBefore = () => {\n if (sourceSetBefore == null || sourceSetBefore.length === 0) {\n if (uriBefore == null) {\n throw new Error('No image URI found');\n }\n cesdk.engine.block.setString(\n fillBlock,\n 'fill/image/imageFileURI',\n uriBefore\n );\n } else {\n cesdk.engine.block.setSourceSet(\n fillBlock,\n 'fill/image/sourceSet',\n sourceSetBefore\n );\n }\n applyCrop();\n };\n const onAfter = () => {\n if (sourceSetAfter == null) {\n if (uriAfter == null) {\n throw new Error('No image URI found');\n }\n cesdk.engine.block.setString(\n fillBlock,\n 'fill/image/imageFileURI',\n uriAfter\n );\n } else {\n cesdk.engine.block.setSourceSet(\n fillBlock,\n 'fill/image/sourceSet',\n sourceSetAfter\n );\n }\n if (differentAspectRatio) {\n cesdk.engine.block.setContentFillMode(block, 'Cover');\n } else {\n applyCrop();\n }\n };\n const onCancel = () => {\n onBefore();\n };\n const onApply = () => {\n onAfter();\n options.cesdk.engine.editor.addUndoStep();\n };\n\n return {\n consumedGenerationResult: generationResult,\n applyCallbacks: {\n onBefore,\n onAfter,\n onCancel,\n onApply\n }\n };\n}\n\nasync function getApplyCallbacksForVideo<O extends Output>(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _result: GenerationResult<O>,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _options: ConsumeGeneratedResultOptions\n): Promise<ReturnValue<O>> {\n throw new Error('Function not implemented.');\n}\n\nasync function getApplyCallbacksForAudio<O extends Output>(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _result: GenerationResult<O>,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _options: ConsumeGeneratedResultOptions\n): Promise<ReturnValue<O>> {\n throw new Error('Function not implemented.');\n}\n\nasync function reuploadImage(\n cesdk: CreativeEditorSDK,\n url: string,\n mimeType: string\n): Promise<string> {\n const response = await fetch(url);\n const blob = await response.blob();\n const file = new File([blob], `image.${mimeTypeToExtension(mimeType)}`, {\n type: mimeType\n });\n const assetDefinition = await cesdk.unstable_upload(file, () => {});\n const uploadedUri = assetDefinition?.meta?.uri;\n if (uploadedUri != null) return uploadedUri;\n // eslint-disable-next-line no-console\n console.warn('Failed to upload image:', assetDefinition);\n return url;\n}\n\nexport default consumeGeneratedResult;\n", "import { Middleware } from './middleware';\nimport { Output } from '../provider';\nimport { CreativeEngine } from '@cesdk/cesdk-js';\nimport { isAbortError } from '../../utils';\n\n/**\n * For a given edit mode and block ids, this middleware will\n * ensure that as long as these blocks are selected, the edit mode is\n * set to the given edit mode and cannot be changed.\n *\n * The use-case is to show only the generation canvas menu during\n * the generation process.\n */\nfunction editModeMiddleware<I, O extends Output>({\n editMode,\n automaticallyUnlock = false,\n showNotification = true\n}: {\n /**\n * The edit mode to lock the selection to.\n */\n editMode: string;\n\n /**\n * Should the selection be automatically unlocked after the function completes?\n * Otherwise the returned unlock function must be called manually.\n *\n * @default false\n */\n automaticallyUnlock?: boolean;\n\n /**\n * Should the blocks be set when the generation is done\n *\n * @default true\n */\n showNotification?: boolean;\n}): Middleware<I, O> {\n const middleware: Middleware<I, O> = async (input, options, next) => {\n const blockIds = options.blockIds ?? options.engine.block.findAllSelected();\n\n let unlock: () => void = () => {};\n if (!automaticallyUnlock) {\n options.addDisposer(async () => {\n if (unlock != null) {\n unlock();\n }\n });\n }\n try {\n unlock = bindSelectionToEditMode(options.engine, blockIds, editMode);\n const result = await next(input, options);\n\n if (showNotification) {\n const currentlySelectedBlockIds =\n options.engine.block.findAllSelected();\n const blockIdsAreSelected = blockIds.some((blockId) => {\n return currentlySelectedBlockIds.includes(blockId);\n });\n\n if (!blockIdsAreSelected) {\n options.cesdk?.ui.showNotification({\n type: 'success',\n message: 'AI generation complete',\n action: {\n label: 'Select',\n onClick: () => {\n blockIds.forEach((blockId) => {\n options.engine.block.select(blockId);\n });\n }\n }\n });\n }\n }\n return result;\n } catch (error) {\n if (isAbortError(error)) {\n unlock();\n }\n throw error;\n } finally {\n if (automaticallyUnlock) {\n unlock();\n }\n }\n };\n\n return middleware;\n}\n\n/**\n * Locks the selection to the given block ids with the given edit mode.\n *\n * @returns A function to unlock the selection. Will set the edit mode back to what it was before the lock.\n */\nfunction bindSelectionToEditMode(\n engine: CreativeEngine,\n blockIdsToBind: number[],\n editModeToBindTo: string\n) {\n function isBoundBlockSelected() {\n const currentlySelectedBlockIds = engine.block.findAllSelected();\n return blockIdsToBind.some((blockId) => {\n return currentlySelectedBlockIds.includes(blockId);\n });\n }\n\n const stateChangeDisposer = engine.editor.onStateChanged(() => {\n const editMode = engine.editor.getEditMode();\n if (editMode !== editModeToBindTo && isBoundBlockSelected()) {\n engine.editor.setEditMode(editModeToBindTo);\n }\n });\n\n const selectionDisposer = engine.block.onSelectionChanged(() => {\n if (isBoundBlockSelected()) {\n engine.editor.setEditMode(editModeToBindTo);\n } else {\n engine.editor.setEditMode('Transform');\n }\n });\n\n if (isBoundBlockSelected()) {\n engine.editor.setEditMode(editModeToBindTo);\n }\n\n const dispose = () => {\n selectionDisposer();\n stateChangeDisposer();\n\n engine.editor.setEditMode('Transform');\n };\n\n return dispose;\n}\n\nexport default editModeMiddleware;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { InferenceMetadata, QuickActionMenu, ApplyCallbacks } from './types';\nimport { INFERENCE_AI_EDIT_MODE, INFERENCE_AI_METADATA_KEY } from './utils';\nimport { Metadata } from '@imgly/plugin-utils';\nimport Provider, {\n GenerationOptions,\n Output,\n OutputKind,\n QuickAction\n} from '../provider';\nimport { composeMiddlewares } from '../middleware/middleware';\nimport loggingMiddleware from '../middleware/loggingMiddleware';\nimport highlightBlocksMiddleware from '../middleware/highlightBlocksMiddleware';\nimport pendingMiddleware from '../middleware/pendingMiddleware';\nimport lockMiddleware from '../middleware/lockMiddleware';\nimport consumeGeneratedResult from './consumeGeneratedResult';\nimport editModeMiddleware from '../middleware/editModeMiddleware';\nimport { InitProviderConfiguration } from '../types';\nimport dryRunMiddleware from '../middleware/dryRunMiddleware';\n\nasync function generate<K extends OutputKind, I, O extends Output>(\n options: {\n input: I;\n blockIds: number[];\n cesdk: CreativeEditorSDK;\n quickAction: QuickAction<I, O>;\n quickActionMenu: QuickActionMenu;\n provider: Provider<K, I, O>;\n abortSignal: AbortSignal;\n confirmationComponentId: string;\n },\n config: InitProviderConfiguration\n): Promise<{\n dispose: () => void;\n returnValue: O;\n applyCallbacks?: ApplyCallbacks;\n}> {\n const {\n cesdk,\n input,\n blockIds,\n provider,\n quickAction,\n confirmationComponentId,\n abortSignal\n } = options;\n if (quickAction.confirmation) {\n cesdk.ui.setCanvasMenuOrder([confirmationComponentId], {\n editMode: INFERENCE_AI_EDIT_MODE\n });\n }\n\n const metadata = new Metadata<InferenceMetadata>(\n cesdk.engine,\n INFERENCE_AI_METADATA_KEY\n );\n blockIds.forEach((blockId) => {\n metadata.set(blockId, {\n status: 'processing',\n quickActionId: quickAction.id\n });\n });\n\n const generationOptions: GenerationOptions = {\n cesdk,\n engine: cesdk.engine,\n abortSignal\n };\n\n const composedMiddlewares = composeMiddlewares<I, O>([\n ...(provider.output.middleware ?? []),\n config.debug ? loggingMiddleware() : undefined,\n pendingMiddleware({}),\n ...(quickAction.confirmation\n ? [\n quickAction.lockDuringConfirmation\n ? lockMiddleware<I, O>({\n editMode: INFERENCE_AI_EDIT_MODE\n })\n : editModeMiddleware<I, O>({\n editMode: INFERENCE_AI_EDIT_MODE\n }),\n quickAction.confirmation && highlightBlocksMiddleware<I, O>({})\n ]\n : []),\n config.dryRun\n ? dryRunMiddleware({ kind: provider.kind, blockIds })\n : undefined\n ]);\n\n const { result: generationResult, dispose: generationDispose } =\n await composedMiddlewares(provider.output.generate)(\n input,\n generationOptions\n );\n\n const { consumedGenerationResult, applyCallbacks } =\n await consumeGeneratedResult(generationResult, {\n abortSignal,\n kind: provider.kind,\n blockIds,\n cesdk\n });\n\n if (quickAction.confirmation) {\n blockIds.forEach((blockId) => {\n metadata.set(blockId, {\n status: 'confirmation',\n quickActionId: quickAction.id\n });\n });\n } else {\n applyCallbacks.onApply();\n blockIds.forEach((blockId) => {\n metadata.clear(blockId);\n });\n }\n\n const dispose = () => {\n generationDispose();\n blockIds.forEach((blockId) => {\n metadata.clear(blockId);\n });\n };\n\n abortSignal.addEventListener('abort', dispose);\n\n return {\n dispose,\n returnValue: consumedGenerationResult,\n applyCallbacks\n };\n}\n\nexport default generate;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { InferenceMetadata, QuickActionMenu, ApplyCallbacks } from './types';\nimport {\n getFeatureIdForQuickAction,\n INFERENCE_AI_METADATA_KEY,\n removeDuplicatedSeparators\n} from './utils';\nimport { Metadata } from '@imgly/plugin-utils';\nimport Provider, { Output, OutputKind } from '../provider';\nimport { isAbortError } from '../../utils';\nimport { InitProviderConfiguration } from '../types';\nimport handleGenerationError from '../handleGenerationError';\nimport generate from './generate';\n\nfunction registerQuickActionMenuComponent<\n K extends OutputKind,\n I,\n O extends Output\n>(\n options: {\n cesdk: CreativeEditorSDK;\n quickActionMenu: QuickActionMenu;\n provider: Provider<K, I, O>;\n },\n config: InitProviderConfiguration\n) {\n const { cesdk, quickActionMenu, provider } = options;\n\n const prefix = `ly.img.ai.${quickActionMenu.id}`;\n const confirmationPrefix = `${prefix}.confirmation`;\n cesdk.setTranslations({\n en: {\n [`${confirmationPrefix}.apply`]: 'Apply',\n [`${confirmationPrefix}.before`]: 'Before',\n [`${confirmationPrefix}.after`]: 'After',\n [`${prefix}.cancel`]: 'Cancel',\n [`${prefix}.processing`]: 'Generating...'\n }\n });\n const confirmationComponentId = `${confirmationPrefix}.canvasnMenu`;\n\n const shared: {\n unlock: () => void;\n abort: () => void;\n applyCallbacks: ApplyCallbacks | undefined;\n } = {\n unlock: () => {},\n abort: () => {},\n applyCallbacks: undefined\n };\n\n const createAbortSignal = () => {\n const controller = new AbortController();\n const signal = controller.signal;\n shared.abort = () => {\n controller.abort();\n };\n return signal;\n };\n\n cesdk.ui.registerComponent(\n confirmationComponentId,\n ({ builder, engine, state }) => {\n const blockIds = engine.block.findAllSelected();\n if (blockIds.length === 0) return null;\n\n const md = new Metadata<InferenceMetadata>(\n cesdk.engine,\n INFERENCE_AI_METADATA_KEY\n );\n\n // All blocks must have the same metadata\n const metadata = md.get(blockIds[0]);\n if (metadata == null) return null;\n\n const clearMetadata = () => {\n blockIds.forEach((blockId) => {\n md.clear(blockId);\n });\n };\n\n switch (metadata.status) {\n case 'processing': {\n builder.Button(`${prefix}.spinner`, {\n label: [\n `ly.img.ai.inference.${metadata.quickActionId}.processing`,\n `${prefix}.cancel`\n ],\n isLoading: true\n });\n builder.Separator(`${prefix}.separator`);\n builder.Button(`${prefix}.cancel`, {\n icon: '@imgly/Cross',\n tooltip: `${prefix}.cancel`,\n onClick: () => {\n shared.abort();\n clearMetadata();\n }\n });\n\n break;\n }\n\n case 'confirmation': {\n const comparingState = state<'before' | 'after'>(\n `${confirmationPrefix}.comparing`,\n 'after'\n );\n\n const onCancel = shared.applyCallbacks?.onCancel;\n if (onCancel != null) {\n builder.Button(`${confirmationPrefix}.cancel`, {\n icon: '@imgly/Cross',\n tooltip: `${prefix}.cancel`,\n onClick: () => {\n shared.unlock();\n onCancel();\n clearMetadata();\n }\n });\n }\n\n const onBefore = shared.applyCallbacks?.onBefore;\n const onAfter = shared.applyCallbacks?.onAfter;\n\n if (onBefore != null && onAfter != null) {\n builder.ButtonGroup(`${confirmationPrefix}.compare`, {\n children: () => {\n builder.Button(`${confirmationPrefix}.compare.before`, {\n label: `${confirmationPrefix}.before`,\n variant: 'regular',\n isActive: comparingState.value === 'before',\n onClick: () => {\n onBefore();\n comparingState.setValue('before');\n }\n });\n builder.Button(`${confirmationPrefix}.compare.after`, {\n label: `${confirmationPrefix}.after`,\n variant: 'regular',\n isActive: comparingState.value === 'after',\n onClick: () => {\n onAfter();\n comparingState.setValue('after');\n }\n });\n }\n });\n }\n\n const onApply = shared.applyCallbacks?.onApply;\n if (onApply != null) {\n builder.Button(`${confirmationPrefix}.apply`, {\n icon: '@imgly/Checkmark',\n tooltip: `${confirmationPrefix}.apply`,\n color: 'accent',\n isDisabled: comparingState.value !== 'after',\n onClick: () => {\n shared.unlock();\n clearMetadata();\n\n // Activating the old history happens in the next update lop.\n // @ts-ignore\n cesdk.engine.editor._update();\n\n onApply();\n }\n });\n }\n\n break;\n }\n\n default: {\n // noop\n }\n }\n }\n );\n\n const canvasMenuComponentId = `${prefix}.canvasMenu`;\n cesdk.ui.registerComponent(canvasMenuComponentId, (context) => {\n const blockIds = context.engine.block.findAllSelected();\n\n let quickActions = quickActionMenu\n .getQuickActionMenuOrder()\n .map((quickActionId) => {\n if (quickActionId === 'ly.img.separator') return quickActionId;\n const quickAction = quickActionMenu.getQuickAction<I, O>(quickActionId);\n if (quickAction == null) return null;\n\n const isEnabled = cesdk.feature.isEnabled(\n getFeatureIdForQuickAction({\n quickActionId,\n quickActionMenuId: quickActionMenu.id\n }),\n {\n engine: context.engine\n }\n );\n if (!isEnabled) return null;\n\n const scopes = quickAction.scopes;\n if (scopes != null && scopes.length > 0) {\n const isAllowedByScopes = blockIds.every((blockId) => {\n return scopes.every((scope) => {\n return context.engine.block.isAllowedByScope(blockId, scope);\n });\n });\n if (!isAllowedByScopes) return null;\n }\n return quickAction;\n })\n .filter((entry) => entry != null);\n\n quickActions = removeDuplicatedSeparators(quickActions);\n\n if (\n quickActions.length === 0 ||\n quickActions.every((entry) => entry === 'ly.img.separator')\n ) {\n return null;\n }\n\n const { builder, experimental, state } = context;\n const toggleExpandedState = state<string | undefined>(\n `${prefix}.toggleExpandedState`,\n undefined\n );\n\n experimental.builder.Popover(`${prefix}.popover`, {\n icon: '@imgly/Sparkle',\n variant: 'plain',\n trailingIcon: null,\n children: ({ close }) => {\n builder.Section(`${prefix}.popover.section`, {\n children: () => {\n if (toggleExpandedState.value != null) {\n const expandStateForQuickActionId = toggleExpandedState.value;\n const quickAction = quickActionMenu.getQuickAction<I, O>(\n expandStateForQuickActionId\n );\n\n if (quickAction != null && quickAction.renderExpanded != null) {\n quickAction.renderExpanded(context, {\n blockIds,\n closeMenu: close,\n toggleExpand: () => {\n toggleExpandedState.setValue(undefined);\n },\n handleGenerationError: (error) => {\n handleGenerationError(\n error,\n {\n cesdk,\n provider\n },\n config\n );\n },\n generate: async (input, generateOptions) => {\n try {\n const { returnValue, applyCallbacks, dispose } =\n await generate(\n {\n input,\n quickAction,\n quickActionMenu,\n provider,\n cesdk,\n abortSignal: createAbortSignal(),\n blockIds: generateOptions?.blockIds ?? blockIds,\n confirmationComponentId\n },\n config\n );\n\n shared.unlock = dispose;\n shared.applyCallbacks = applyCallbacks;\n\n return returnValue;\n } catch (error) {\n if (!isAbortError(error)) {\n handleGenerationError(\n error,\n {\n cesdk,\n provider\n },\n config\n );\n }\n throw error;\n }\n }\n });\n\n return;\n }\n }\n\n experimental.builder.Menu(`${prefix}.menu`, {\n children: () => {\n quickActions.forEach((quickAction) => {\n if (quickAction === 'ly.img.separator') {\n builder.Separator(\n `${prefix}.separator.${Math.random().toString()}`\n );\n } else {\n quickAction.render(context, {\n blockIds,\n closeMenu: close,\n handleGenerationError: (error) => {\n handleGenerationError(\n error,\n {\n cesdk,\n provider\n },\n config\n );\n },\n toggleExpand: () => {\n toggleExpandedState.setValue(quickAction.id);\n },\n generate: async (input, generateOptions) => {\n try {\n const { returnValue, applyCallbacks, dispose } =\n await generate(\n {\n input,\n quickAction,\n quickActionMenu,\n provider,\n cesdk,\n abortSignal: createAbortSignal(),\n blockIds: generateOptions?.blockIds ?? blockIds,\n confirmationComponentId\n },\n config\n );\n\n shared.unlock = dispose;\n shared.applyCallbacks = applyCallbacks;\n return returnValue;\n } catch (error) {\n if (!isAbortError(error)) {\n handleGenerationError(\n error,\n {\n cesdk,\n provider\n },\n config\n );\n }\n throw error;\n }\n }\n });\n }\n });\n }\n });\n }\n });\n }\n });\n });\n\n return { canvasMenuComponentId };\n}\n\nexport default registerQuickActionMenuComponent;\n", "import type Provider from './provider';\nimport {\n OutputKind,\n PanelInput,\n QuickActionsInput,\n type Output\n} from './provider';\nimport registerPanelInputSchema from './registerPanelInputSchema';\nimport registerPanelInputCustom from './registerPanelInputCustom';\nimport { InitProviderConfiguration, Options, UIOptions } from './types';\nimport { BuilderRenderFunction, type CreativeEngine } from '@cesdk/cesdk-js';\nimport { IndexedDBAssetSource } from '@imgly/plugin-utils';\nimport icons from '../icons';\nimport getQuickActionMenu from './quickAction/getQuickActionMenu';\nimport { getFeatureIdForQuickAction } from './quickAction/utils';\nimport registerQuickActionMenuComponent from './quickAction/registerQuickActionMenuComponent';\nimport { QuickActionMenu } from './quickAction/types';\n\ntype RenderBuilderFunctions = {\n panel?: BuilderRenderFunction<any>;\n};\n\n/**\n * Initialize the provider. Based on the given options and configuration\n * it will register panels and components that is used to render\n * the provider in the UI.\n *\n * @param provider The provider to initialize.\n * @param options The options to use for the provider.\n * @param config The configuration to use for the provider.\n */\nasync function initProvider<K extends OutputKind, I, O extends Output>(\n provider: Provider<K, I, O>,\n options: Options,\n config: InitProviderConfiguration\n): Promise<{\n renderBuilderFunctions?: RenderBuilderFunctions;\n}> {\n await provider.initialize?.(options);\n const historyAssetSourceId = await initHistory(\n options.engine,\n provider.id,\n provider.output.history ?? '@imgly/local'\n );\n\n if (options.cesdk == null) {\n return {};\n }\n\n const historyAssetLibraryEntryId = historyAssetSourceId\n ? `${provider.id}.history.entry`\n : undefined;\n const uiOptions: UIOptions = {\n ...options,\n cesdk: options.cesdk,\n historyAssetSourceId,\n historyAssetLibraryEntryId,\n i18n: {\n prompt: 'common.ai-generation.prompt.placeholder'\n }\n };\n\n if (historyAssetLibraryEntryId != null && historyAssetSourceId != null) {\n options.cesdk.ui.addAssetLibraryEntry({\n id: historyAssetLibraryEntryId,\n sourceIds: [historyAssetSourceId],\n sortBy: {\n sortKey: 'insertedAt',\n sortingOrder: 'Descending'\n },\n canRemove: true,\n gridItemHeight: 'square',\n gridBackgroundType: 'cover'\n });\n }\n\n options.cesdk.i18n.setTranslations({\n en: {\n 'common.ai-generation.success': 'Generation Successful',\n 'common.ai-generation.failed': 'Generation Failed',\n 'common.ai-generation.generate': 'Generate',\n 'common.ai-generation.prompt.placeholder':\n 'Describe what you want to create...',\n [`panel.${provider.id}`]: getName(provider)\n }\n });\n\n // Avoid adding the icon set multiple times for different providers\n const globalStateIconSetAddedId = `@imgly/plugin-ai-generation.iconSetAdded`;\n if (\n !options.cesdk.ui.experimental.hasGlobalStateValue(\n globalStateIconSetAddedId\n )\n ) {\n options.cesdk.ui.addIconSet('@imgly/plugin-ai-generation', icons);\n options.cesdk.ui.experimental.setGlobalStateValue(\n globalStateIconSetAddedId,\n true\n );\n }\n\n const renderBuilderFunctions = await initInputs(provider, uiOptions, config);\n\n return {\n renderBuilderFunctions\n };\n}\n\nfunction getName(provider: Provider<any, any, any>): string {\n if (provider.name != null) return provider.name;\n switch (provider.kind) {\n case 'image':\n return 'Generate Image';\n case 'video':\n return 'Generate Video';\n case 'audio':\n return 'Generate Audio';\n default:\n return 'Generate Asset';\n }\n}\n\n/**\n * Initialize the history for the provider.\n */\nasync function initHistory(\n engine: CreativeEngine,\n providerId: string,\n history: undefined | false | '@imgly/local' | '@imgly/indexedDB' | string\n): Promise<string | undefined> {\n if (history == null || history === false) return undefined;\n\n if (history === '@imgly/local') {\n const historyId = `${providerId}.history`;\n engine.asset.addLocalSource(historyId);\n return historyId;\n }\n\n if (history === '@imgly/indexedDB') {\n const historyId = `${providerId}.history`;\n engine.asset.addSource(new IndexedDBAssetSource(historyId, engine));\n return historyId;\n }\n\n return history;\n}\n\nasync function initInputs<K extends OutputKind, I, O extends Output>(\n provider: Provider<K, I, O>,\n options: UIOptions,\n config: InitProviderConfiguration\n): Promise<{\n panel?: BuilderRenderFunction<any>;\n}> {\n const result: {\n panel?: BuilderRenderFunction<any>;\n } = {\n panel: undefined\n };\n\n if (provider.input?.panel != null) {\n result.panel = await initPanel(\n provider,\n provider.input.panel,\n options,\n config\n );\n }\n if (provider.input?.quickActions != null) {\n if (config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n `Initializing quick actions for provider '${provider.kind}' (${provider.id})`\n );\n }\n initQuickActions(provider, provider.input.quickActions, options, config);\n }\n\n return result;\n}\n\nasync function initPanel<K extends OutputKind, I, O extends Output>(\n provider: Provider<K, I, O>,\n panelInput: PanelInput<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): Promise<BuilderRenderFunction<any> | undefined> {\n switch (panelInput.type) {\n case 'custom': {\n return registerPanelInputCustom(provider, panelInput, options, config);\n }\n\n case 'schema': {\n return registerPanelInputSchema(provider, panelInput, options, config);\n }\n\n default: {\n if (config.debug) {\n // eslint-disable-next-line no-console\n console.warn(\n // @ts-ignore\n `Invalid panel input type '${panelInput.type}' - skipping`\n );\n }\n }\n }\n}\n\nasync function initQuickActions<K extends OutputKind, I, O extends Output>(\n provider: Provider<K, I, O>,\n quickActionsInput: QuickActionsInput<I, O>,\n options: UIOptions,\n config: InitProviderConfiguration\n) {\n const { cesdk } = options;\n\n const quickActionMenus: { [kind: string]: QuickActionMenu } = {};\n\n quickActionsInput.actions.forEach((quickAction) => {\n const quickActionMenuId = quickAction.kind ?? provider.kind;\n if (quickActionMenus[quickActionMenuId] == null) {\n quickActionMenus[quickActionMenuId] = getQuickActionMenu(\n cesdk,\n quickActionMenuId\n );\n }\n const quickActionMenu = quickActionMenus[quickActionMenuId];\n\n const enable = quickAction.enable ?? true;\n cesdk.feature.enable(\n getFeatureIdForQuickAction({\n quickActionId: quickAction.id,\n quickActionMenuId\n }),\n enable\n );\n quickActionMenu.registerQuickAction(quickAction);\n if (config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n `Registered quick action: '${quickAction.id}' (v${quickAction.version}) to menu '${quickActionMenuId}'`\n );\n }\n });\n\n Object.values(quickActionMenus).forEach((quickActionMenu) => {\n const { canvasMenuComponentId } = registerQuickActionMenuComponent(\n {\n cesdk,\n quickActionMenu,\n provider\n },\n config\n );\n if (config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n `Registered quick action menu component: ${canvasMenuComponentId}`\n );\n }\n });\n}\n\nexport default initProvider;\n", "import { isAsyncGenerator } from '../../utils';\nimport { GenerationResult, Output } from '../provider';\nimport { Middleware } from './middleware';\n\n/**\n * Middleware to upload the output of a generation process.\n *\n * Sometimes it is not possible to use the result of a provider or\n * not even allowed to use it directly. This middleware allows you to upload\n * the result of a generation process to a server or a cloud storage.\n *\n * @param upload The function to upload the output. It should return a promise\n */\nfunction uploadMiddleware<I, O extends Output>(\n upload: (output: O) => Promise<O>\n) {\n const middleware: Middleware<I, O> = async (input, options, next) => {\n const result: GenerationResult<O> | undefined = await next(input, options);\n if (isAsyncGenerator(result)) {\n // No reupload needed, just return the async generator\n return result;\n }\n\n const uploaded = await upload(result);\n return uploaded;\n };\n\n return middleware;\n}\n\nexport default uploadMiddleware;\n", "import { GenerationOptions, Output } from '../provider';\nimport { Middleware } from './middleware';\n\nexport interface RateLimitOptions<I> {\n /**\n * Maximum number of requests allowed in the time window\n */\n maxRequests: number;\n\n /**\n * Time window in milliseconds\n */\n timeWindowMs: number;\n\n /**\n * Optional key function or string to create different rate limits for different inputs\n * - If not provided, all requests share the same 'global' rate limit\n * - If a string is provided, that string is used as a static key\n * - If a function is provided, it generates a key based on input and options\n */\n keyFn?: string | ((input: I, options: GenerationOptions) => string);\n\n /**\n * Callback function that is called when rate limit is exceeded\n * Return value determines if the operation should be rejected (throw error) or allowed\n * If true is returned, the operation will proceed despite exceeding the rate limit\n * If false or undefined is returned, the operation will be rejected with a default error\n */\n onRateLimitExceeded?: (\n input: I,\n options: GenerationOptions,\n rateLimitInfo: {\n key: string;\n currentCount: number;\n maxRequests: number;\n timeWindowMs: number;\n remainingTimeMs: number;\n }\n ) => boolean | Promise<boolean> | void;\n\n /**\n * Optional database name for the IndexedDB store\n * If not provided, a default name will be used\n */\n dbName?: string;\n\n /**\n * Disable the rate limit middleware\n */\n disable?: boolean;\n}\n\n// Store for tracking requests per key\ninterface RequestTracker {\n timestamps: number[];\n lastCleanup: number;\n}\n\n// In-memory fallback store for rate limits for environments without IndexedDB\n// Export for testing purposes\n// This is now a Map of middleware instances to their respective stores\n// The key can be either a symbol (for unique instances with prefix) or a string (for shared instances without prefix)\nexport const inMemoryStores: Map<\n symbol | string,\n Record<string, RequestTracker>\n> = new Map();\n\n/**\n * IndexedDB store for rate limiting\n */\nclass RateLimitStore {\n private db: IDBDatabase | null = null;\n\n private readonly dbName: string;\n\n private readonly storeName: string;\n\n private readonly dbVersion: number = 1;\n\n private isInitializing: boolean = false;\n\n private initPromise: Promise<void> | null = null;\n\n private readonly instanceId: symbol | string;\n\n constructor(\n instanceId: symbol | string,\n dbName?: string,\n storeName?: string\n ) {\n this.instanceId = instanceId;\n this.dbName = dbName ?? 'ly.img.ai.rateLimit';\n this.storeName = storeName ?? 'rateLimits';\n }\n\n /**\n * Initialize the database connection\n */\n async initialize(): Promise<void> {\n if (this.db) {\n return;\n }\n\n if (this.isInitializing) {\n return this.initPromise!;\n }\n\n this.isInitializing = true;\n this.initPromise = new Promise<void>((resolve, reject) => {\n try {\n const request = indexedDB.open(this.dbName, this.dbVersion);\n\n request.onerror = (event) => {\n this.isInitializing = false;\n\n // eslint-disable-next-line no-console\n console.error('Failed to open IndexedDB for rate limiting:', event);\n reject(new Error('Failed to open IndexedDB for rate limiting'));\n };\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n if (!db.objectStoreNames.contains(this.storeName)) {\n db.createObjectStore(this.storeName, { keyPath: 'id' });\n }\n };\n\n request.onsuccess = (event) => {\n this.db = (event.target as IDBOpenDBRequest).result;\n this.isInitializing = false;\n resolve();\n };\n } catch (error) {\n this.isInitializing = false;\n // eslint-disable-next-line no-console\n console.error('Error initializing IndexedDB:', error);\n reject(error);\n }\n });\n\n return this.initPromise;\n }\n\n /**\n * Get a request tracker by key\n */\n async getTracker(key: string): Promise<RequestTracker | null> {\n try {\n await this.initialize();\n\n // Create a combined key that includes the instance ID to ensure isolation\n const instanceIdStr =\n typeof this.instanceId === 'symbol'\n ? this.instanceId.description || ''\n : this.instanceId;\n const combinedKey = `${instanceIdStr}_${key}`;\n\n return await new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.storeName, 'readonly');\n const store = transaction.objectStore(this.storeName);\n const request = store.get(combinedKey);\n\n request.onsuccess = () => {\n if (request.result) {\n resolve(request.result.data);\n } else {\n resolve(null);\n }\n };\n\n request.onerror = () => {\n // eslint-disable-next-line no-console\n console.error(\n `Failed to get tracker for key ${combinedKey}:`,\n request.error\n );\n reject(request.error);\n };\n });\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Error getting tracker from IndexedDB:', error);\n return Promise.reject(error);\n }\n }\n\n /**\n * Save a request tracker by key\n */\n async saveTracker(key: string, tracker: RequestTracker): Promise<void> {\n try {\n await this.initialize();\n\n // Create a combined key that includes the instance ID to ensure isolation\n const instanceIdStr =\n typeof this.instanceId === 'symbol'\n ? this.instanceId.description || ''\n : this.instanceId;\n const combinedKey = `${instanceIdStr}_${key}`;\n\n return await new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.storeName, 'readwrite');\n const store = transaction.objectStore(this.storeName);\n store.put({ id: combinedKey, data: tracker });\n\n transaction.oncomplete = () => {\n resolve();\n };\n\n transaction.onerror = () => {\n // eslint-disable-next-line no-console\n console.error(\n `Failed to save tracker for key ${combinedKey}:`,\n transaction.error\n );\n reject(transaction.error);\n };\n });\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Error saving tracker to IndexedDB:', error);\n return Promise.reject(error);\n }\n }\n\n /**\n * Check if IndexedDB is available\n */\n static isAvailable(): boolean {\n return typeof indexedDB !== 'undefined';\n }\n\n /**\n * Close the database connection\n */\n close(): void {\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n }\n}\n\n/**\n * Middleware that implements rate limiting for AI generation requests\n * Uses IndexedDB for storage when available, with in-memory fallback\n * Each middleware instance has its own isolated set of rate limits\n */\nfunction rateLimitMiddleware<I, O extends Output>(\n middlewareOptions: RateLimitOptions<I>\n) {\n const {\n maxRequests,\n timeWindowMs,\n keyFn = () => 'global',\n onRateLimitExceeded,\n dbName\n } = middlewareOptions;\n\n // Create an identifier for this middleware instance based on its configuration\n // This ensures persistence across page reloads and sharing between identical configurations\n const configStr = `rate-limit-middleware-${maxRequests}-${timeWindowMs}`;\n\n // Use a string key for the configuration so identical configurations share the same limits\n const instanceId = configStr;\n\n // Create the store with the instance ID\n const useIndexedDB = RateLimitStore.isAvailable();\n const store = useIndexedDB ? new RateLimitStore(instanceId, dbName) : null;\n\n // Initialize this middleware's in-memory store\n if (!inMemoryStores.has(instanceId)) {\n inMemoryStores.set(instanceId, {});\n }\n // Get this middleware's in-memory store\n const inMemoryStore = inMemoryStores.get(instanceId)!;\n\n const middleware: Middleware<I, O> = async (input, options, next) => {\n if (middlewareOptions.disable) {\n return next(input, options);\n }\n // Get rate limit key based on input using the provided keyFn\n // If keyFn is a string, use it directly; otherwise call the function\n const key = typeof keyFn === 'string' ? keyFn : keyFn(input, options);\n const now = Date.now();\n\n let tracker: RequestTracker;\n\n // Get tracker from IndexedDB or create a new one\n if (useIndexedDB && store) {\n try {\n const storedTracker = await store.getTracker(key);\n if (storedTracker) {\n tracker = storedTracker;\n } else {\n tracker = {\n timestamps: [],\n lastCleanup: now\n };\n }\n } catch (error) {\n // Fallback to in-memory store if IndexedDB fails\n // eslint-disable-next-line no-console\n console.error(\n 'IndexedDB access failed, using in-memory fallback:',\n error\n );\n if (!inMemoryStore[key]) {\n inMemoryStore[key] = {\n timestamps: [],\n lastCleanup: now\n };\n }\n tracker = inMemoryStore[key];\n }\n } else {\n // Use in-memory store if IndexedDB is not available\n if (!inMemoryStore[key]) {\n inMemoryStore[key] = {\n timestamps: [],\n lastCleanup: now\n };\n }\n tracker = inMemoryStore[key];\n }\n\n // Clean up old timestamps that are outside the time window\n if (now - tracker.lastCleanup > timeWindowMs) {\n tracker.timestamps = tracker.timestamps.filter(\n (timestamp) => now - timestamp < timeWindowMs\n );\n tracker.lastCleanup = now;\n }\n\n // Check if rate limit is exceeded\n if (tracker.timestamps.length >= maxRequests) {\n // Calculate the time until the oldest request expires\n const oldestTimestamp = Math.min(...tracker.timestamps);\n const remainingTimeMs = Math.max(\n 0,\n timeWindowMs - (now - oldestTimestamp)\n );\n\n // Call the rate limit exceeded callback if provided\n if (onRateLimitExceeded) {\n const rateLimitInfo = {\n key, // This is the baseKey from keyFn\n currentCount: tracker.timestamps.length,\n maxRequests,\n timeWindowMs,\n remainingTimeMs\n };\n\n // If callback returns true, allow the request to proceed\n const shouldProceed = await onRateLimitExceeded(\n input,\n options,\n rateLimitInfo\n );\n if (!shouldProceed) {\n // The callback should indicate the error, so we throw\n // an abort error instead of a generic error to indicate\n // the generation was aborted and we do not show any further\n // error notification.\n throw new DOMException(\n 'Operation aborted: Rate limit exceeded',\n 'AbortError'\n );\n }\n } else {\n // Default behavior: throw an error\n throw new Error('Rate limit exceeded. Please try again later.');\n }\n }\n\n // Add current timestamp to the tracker\n tracker.timestamps.push(now);\n\n // Save the updated tracker\n if (useIndexedDB && store) {\n try {\n await store.saveTracker(key, tracker);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to save tracker to IndexedDB:', error);\n // In case of IndexedDB failure, update the in-memory store as fallback\n inMemoryStore[key] = tracker;\n }\n } else {\n inMemoryStore[key] = tracker;\n }\n\n // Continue with the next middleware\n return next(input, options);\n };\n\n return middleware;\n}\n\nexport default rateLimitMiddleware;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\n\n/**\n * Registers a dock component for AI generation that opens\n * the AI generation panel and closes any other AI panels.\n */\nfunction registerDockComponent(options: {\n cesdk: CreativeEditorSDK;\n panelId: string;\n}) {\n const { cesdk, panelId } = options;\n if (panelId.startsWith('ly.img.ai/')) {\n // eslint-disable-next-line no-console\n console.warn(\n `Dock components for AI generation should open a panel with an id starting with \"ly.img.ai/\" \u2013 \"${panelId}\" was provided.`\n );\n }\n\n const dockComponentId = `${panelId}.dock`;\n cesdk.ui.registerComponent(dockComponentId, ({ builder }) => {\n const isOpen = cesdk.ui.isPanelOpen(panelId);\n\n builder.Button(`${panelId}.dock.button`, {\n label: `${panelId}.dock.label`,\n isSelected: isOpen,\n icon: '@imgly/Sparkle',\n onClick: () => {\n cesdk.ui.findAllPanels().forEach((panel) => {\n if (panel.startsWith('ly.img.ai/')) {\n cesdk.ui.closePanel(panel);\n }\n if (!isOpen && panel === '//ly.img.panel/assetLibrary') {\n cesdk.ui.closePanel(panel);\n }\n });\n\n if (!isOpen) {\n cesdk.ui.openPanel(panelId);\n } else {\n cesdk.ui.closePanel(panelId);\n }\n }\n });\n });\n}\n\nexport default registerDockComponent;\n", "import { ButtonOptions, TextAreaOptions } from '@cesdk/cesdk-js';\nimport { Output, QuickAction, QuickActionContext } from '../../provider';\n\n/**\n * Quick action base for quick actions that require a prompt.\n * Will render a text area for the prompt.\n */\nfunction QuickActionBasePrompt<I, O extends Output>(options: {\n buttonOptions?: ButtonOptions;\n textAreaOptions?: TextAreaOptions;\n quickAction: Omit<QuickAction<I, O>, 'render' | 'renderExpanded'>;\n onApply: (prompt: string, context: QuickActionContext<I, O>) => Promise<O>;\n}): QuickAction<I, O> {\n const id = options.quickAction.id;\n return {\n confirmation: true,\n lockDuringConfirmation: false,\n ...options.quickAction,\n render: ({ builder }, { toggleExpand }) => {\n builder.Button(`${id}.button`, {\n label: `ly.img.ai.quickAction.${id}`,\n icon: '@imgly/Sparkle',\n labelAlignment: 'left',\n variant: 'plain',\n ...options.buttonOptions,\n onClick: toggleExpand\n });\n },\n renderExpanded: ({ builder, state, experimental }, context) => {\n const promptState = state(`${id}.prompt`, '');\n\n builder.TextArea(`${id}.textarea`, {\n inputLabel: `ly.img.ai.quickAction.${id}.prompt.inputLabel`,\n placeholder: `ly.img.ai.quickAction.${id}.prompt.placeholder`,\n ...options.textAreaOptions,\n ...promptState\n });\n\n builder.Separator(`${id}.separator`);\n\n experimental.builder.ButtonRow(`${id}.footer`, {\n justifyContent: 'space-between',\n children: () => {\n builder.Button(`${id}.footer.cancel`, {\n label: 'common.back',\n icon: '@imgly/ChevronLeft',\n onClick: context.toggleExpand\n });\n\n builder.Button(`${id}.footer.apply`, {\n label: `ly.img.ai.quickAction.${id}.apply`,\n icon: '@imgly/MagicWand',\n color: 'accent',\n isDisabled: promptState.value.length === 0,\n onClick: async () => {\n try {\n const prompt = promptState.value;\n if (!prompt) return;\n\n options.onApply(prompt, context);\n context.toggleExpand();\n context.closeMenu();\n } catch (error) {\n context.handleGenerationError(error);\n }\n }\n });\n }\n });\n }\n };\n}\n\nexport default QuickActionBasePrompt;\n", "import { ButtonOptions } from '@cesdk/cesdk-js';\nimport { Output, QuickAction, QuickActionContext } from '../../provider';\n\n/**\n * Quick action base for quick actions to open a panel.\n */\nfunction QuickActionBaseButton<I, O extends Output>(options: {\n buttonOptions?: ButtonOptions;\n quickAction: Omit<QuickAction<I, O>, 'render' | 'renderExpanded'>;\n\n onClick: (context: QuickActionContext<I, O>) => Promise<void>;\n}): QuickAction<I, O> {\n const id = options.quickAction.id;\n return {\n confirmation: true,\n lockDuringConfirmation: false,\n ...options.quickAction,\n render: ({ builder }, context) => {\n builder.Button(`${id}.button`, {\n label: `ly.img.ai.quickAction.${id}`,\n icon: '@imgly/Sparkle',\n labelAlignment: 'left',\n variant: 'plain',\n ...options.buttonOptions,\n onClick: async () => {\n try {\n options.onClick(context);\n context.closeMenu();\n } catch (error) {\n context.handleGenerationError(error);\n }\n }\n });\n }\n };\n}\n\nexport default QuickActionBaseButton;\n", "import CreativeEditorSDK, { ButtonOptions } from '@cesdk/cesdk-js';\nimport { Output, QuickAction, QuickActionContext } from '../../provider';\nimport { getImageUri } from '@imgly/plugin-utils';\n\ninterface QuickActionBaseSelectItem {\n id: string;\n label: string;\n icon?: string;\n prompt: string;\n}\n\n/**\n * Quick action base for quick actions that require a selection of items.\n */\nfunction QuickActionBaseSelect<I, O extends Output>(options: {\n cesdk: CreativeEditorSDK;\n items: QuickActionBaseSelectItem[];\n buttonOptions?: ButtonOptions;\n quickAction: Omit<QuickAction<I, O>, 'render' | 'renderExpanded'>;\n mapInput?: (input: {\n item: QuickActionBaseSelectItem;\n uri: string;\n blockId: number;\n }) => I;\n onApply?: (\n options: { item: QuickActionBaseSelectItem; uri: string; blockId: number },\n context: QuickActionContext<I, O>\n ) => Promise<O>;\n}): QuickAction<I, O> {\n const id = options.quickAction.id;\n\n if (options.mapInput == null && options.onApply == null) {\n throw new Error(\n `QuickAction '${id}': Either mapInput or onApply must be provided to QuickActionChangeImage`\n );\n }\n\n if (options.mapInput != null && options.onApply != null) {\n throw new Error(\n `QuickAction '${id}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`\n );\n }\n\n return {\n ...options.quickAction,\n render: ({ builder, experimental }, context) => {\n experimental.builder.Popover(`${id}.popover`, {\n label: `ly.img.ai.quickAction.${id}`,\n icon: '@imgly/Appearance',\n labelAlignment: 'left',\n variant: 'plain',\n trailingIcon: '@imgly/ChevronRight',\n placement: 'right',\n ...options.buttonOptions,\n children: () => {\n builder.Section(`${id}.popover.section`, {\n children: () => {\n experimental.builder.Menu(`${id}.popover.menu`, {\n children: () => {\n options.items.forEach((item) => {\n builder.Button(`${id}.popover.menu.${item.id}`, {\n label: item.label,\n labelAlignment: 'left',\n variant: 'plain',\n icon: item.icon,\n onClick: async () => {\n const { generate, closeMenu, handleGenerationError } =\n context;\n try {\n closeMenu();\n const [blockId] =\n options.cesdk.engine.block.findAllSelected();\n const uri = await getImageUri(\n blockId,\n options.cesdk.engine,\n {\n throwErrorIfSvg: true\n }\n );\n\n if (options.mapInput) {\n const input = options.mapInput({\n item,\n uri,\n blockId\n });\n return await generate(input);\n } else if (options.onApply) {\n return await options.onApply(\n {\n item,\n uri,\n blockId\n },\n context\n );\n } else {\n throw new Error(\n 'Please provide either mapInput or onApply'\n );\n }\n } catch (error) {\n handleGenerationError(error);\n }\n }\n });\n });\n }\n });\n }\n });\n }\n });\n }\n };\n}\n\nexport default QuickActionBaseSelect;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { ImageOutput, QuickAction, QuickActionContext } from '../../provider';\nimport QuickActionBasePrompt from './QuickActionBasePrompt';\nimport { getImageUri } from '@imgly/plugin-utils';\n\nfunction QuickActionEditTextStyle<I, O extends ImageOutput>(options: {\n id?: string;\n cesdk: CreativeEditorSDK;\n mapInput?: (input: {\n prompt: string;\n uri: string;\n duplicatedBlockId: number;\n }) => I;\n onApply?: (\n options: { prompt: string; uri: string; duplicatedBlockId: number },\n context: QuickActionContext<I, O>\n ) => Promise<O>;\n}): QuickAction<I, O> {\n const id = options.id ?? 'changeToImage';\n\n if (options.mapInput == null && options.onApply == null) {\n throw new Error(\n `QuickAction '${id}': Either mapInput or onApply must be provided to QuickActionChangeImage`\n );\n }\n\n if (options.mapInput != null && options.onApply != null) {\n throw new Error(\n `QuickAction '${id}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`\n );\n }\n\n options.cesdk.i18n.setTranslations({\n en: {\n [`ly.img.ai.quickAction.${id}.apply`]: 'Change',\n [`ly.img.ai.quickAction.${id}`]: 'Change Text Style...',\n [`ly.img.ai.quickAction.${id}.prompt.inputLabel`]: 'Change Text Style...',\n [`ly.img.ai.quickAction.${id}.prompt.placeholder`]:\n 'e.g. add a 3d texture with wires...'\n }\n });\n\n return QuickActionBasePrompt<I, O>({\n buttonOptions: {\n icon: '@imgly/plugin-ai-generation/image'\n },\n quickAction: {\n kind: 'text',\n id,\n version: '1',\n confirmation: false,\n // scopes: ['fill/change'],\n enable: ({ engine }) => {\n const blockIds = engine.block.findAllSelected();\n if (blockIds == null || blockIds.length !== 1) return false;\n const [blockId] = blockIds;\n return engine.block.getType(blockId) === '//ly.img.ubq/text';\n }\n },\n onApply: async (prompt, context) => {\n const [blockId] = options.cesdk.engine.block.findAllSelected();\n const parentBlockId = options.cesdk.engine.block.getParent(blockId);\n if (parentBlockId == null) {\n throw new Error('Parent block not found');\n }\n\n const rasterized = await options.cesdk.engine.block.export(blockId);\n const rasterizedUri = URL.createObjectURL(rasterized);\n\n const width = options.cesdk.engine.block.getFrameWidth(blockId);\n const height = options.cesdk.engine.block.getFrameHeight(blockId);\n const positionX = options.cesdk.engine.block.getPositionX(blockId);\n const positionY = options.cesdk.engine.block.getPositionY(blockId);\n\n const shape = options.cesdk.engine.block.createShape('rect');\n const rasterizedBlock = options.cesdk.engine.block.create('graphic');\n options.cesdk.engine.block.setShape(rasterizedBlock, shape);\n options.cesdk.engine.block.appendChild(parentBlockId, rasterizedBlock);\n options.cesdk.engine.block.setWidth(rasterizedBlock, width);\n options.cesdk.engine.block.setHeight(rasterizedBlock, height);\n options.cesdk.engine.block.setPositionX(rasterizedBlock, positionX);\n options.cesdk.engine.block.setPositionY(rasterizedBlock, positionY);\n const fillBlock = options.cesdk.engine.block.createFill('image');\n\n options.cesdk.engine.block.setString(\n fillBlock,\n 'fill/image/imageFileURI',\n rasterizedUri\n );\n\n options.cesdk.engine.block.setFill(rasterizedBlock, fillBlock);\n\n options.cesdk.engine.block.destroy(blockId);\n options.cesdk.engine.block.setSelected(rasterizedBlock, true);\n\n const uri = await getImageUri(rasterizedBlock, options.cesdk.engine, {\n throwErrorIfSvg: true\n });\n\n if (options.mapInput) {\n const input = options.mapInput({\n prompt,\n uri,\n duplicatedBlockId: rasterizedBlock\n });\n return context.generate(input);\n } else if (options.onApply) {\n return options.onApply(\n {\n prompt,\n uri,\n duplicatedBlockId: rasterizedBlock\n },\n context\n );\n } else {\n throw new Error('Please provide either mapInput or onApply');\n }\n }\n });\n}\n\nexport default QuickActionEditTextStyle;\n", "import type CreativeEngine from '@cesdk/engine';\n\n/**\n * Enable function for a single image fill block selected.\n */\nfunction enableImageFill() {\n return ({ engine }: { engine: CreativeEngine }) => {\n const blockIds = engine.block.findAllSelected();\n if (blockIds == null || blockIds.length !== 1) return false;\n\n const [blockId] = blockIds;\n if (\n engine.block.getType(blockId) !== '//ly.img.ubq/graphic' &&\n !engine.block.supportsFill(blockId)\n ) {\n return false;\n }\n\n const fillBlock = engine.block.getFill(blockId);\n return engine.block.getType(fillBlock) === '//ly.img.ubq/fill/image';\n };\n}\n\nexport default enableImageFill;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { ImageOutput, QuickAction, QuickActionContext } from '../../provider';\nimport QuickActionBasePrompt from './QuickActionBasePrompt';\nimport enableImageFill from './enableImageFill';\nimport { getImageUri } from '@imgly/plugin-utils';\n\nfunction QuickActionChangeImage<I, O extends ImageOutput>(options: {\n id?: string;\n cesdk: CreativeEditorSDK;\n mapInput?: (input: { prompt: string; uri: string; blockId: number }) => I;\n onApply?: (\n options: { prompt: string; uri: string; blockId: number },\n context: QuickActionContext<I, O>\n ) => Promise<O>;\n}): QuickAction<I, O> {\n const id = options.id ?? 'changeImage';\n\n if (options.mapInput == null && options.onApply == null) {\n throw new Error(\n `QuickAction '${id}': Either mapInput or onApply must be provided to QuickActionChangeImage`\n );\n }\n\n if (options.mapInput != null && options.onApply != null) {\n throw new Error(\n `QuickAction '${id}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`\n );\n }\n\n options.cesdk.i18n.setTranslations({\n en: {\n [`ly.img.ai.quickAction.${id}.apply`]: 'Change',\n [`ly.img.ai.quickAction.${id}`]: 'Edit Image...',\n [`ly.img.ai.quickAction.${id}.prompt.inputLabel`]: 'Change image...',\n [`ly.img.ai.quickAction.${id}.prompt.placeholder`]:\n 'Describe what you want to change...'\n }\n });\n\n return QuickActionBasePrompt<I, O>({\n buttonOptions: {\n icon: '@imgly/plugin-ai-generation/image'\n },\n quickAction: {\n id,\n version: '1',\n confirmation: true,\n lockDuringConfirmation: false,\n scopes: ['fill/change'],\n enable: enableImageFill()\n },\n onApply: async (prompt, context) => {\n const [blockId] = options.cesdk.engine.block.findAllSelected();\n const uri = await getImageUri(blockId, options.cesdk.engine, {\n throwErrorIfSvg: true\n });\n\n if (options.mapInput) {\n const input = options.mapInput({ prompt, uri, blockId });\n return context.generate(input);\n } else if (options.onApply) {\n return options.onApply(\n {\n prompt,\n uri,\n blockId\n },\n context\n );\n } else {\n throw new Error('Please provide either mapInput or onApply');\n }\n }\n });\n}\n\nexport default QuickActionChangeImage;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { ImageOutput, QuickAction, QuickActionContext } from '../../provider';\nimport QuickActionBasePrompt from './QuickActionBasePrompt';\nimport enableImageFill from './enableImageFill';\nimport { getImageUri } from '@imgly/plugin-utils';\n\nfunction QuickActionImageVariant<I, O extends ImageOutput>(options: {\n id?: string;\n mapInput?: (input: {\n prompt: string;\n uri: string;\n duplicatedBlockId: number;\n }) => I;\n onApply?: (\n options: { prompt: string; uri: string; duplicatedBlockId: number },\n context: QuickActionContext<I, O>\n ) => Promise<O>;\n cesdk: CreativeEditorSDK;\n}): QuickAction<I, O> {\n const id = options.id ?? 'createVariant';\n\n if (options.mapInput == null && options.onApply == null) {\n throw new Error(\n `QuickAction '${id}': Either mapInput or onApply must be provided to QuickActionChangeImage`\n );\n }\n\n if (options.mapInput != null && options.onApply != null) {\n throw new Error(\n `QuickAction '${id}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`\n );\n }\n\n options.cesdk.i18n.setTranslations({\n en: {\n [`ly.img.ai.quickAction.${id}.apply`]: 'Create',\n [`ly.img.ai.quickAction.${id}`]: 'Create Variant...',\n [`ly.img.ai.quickAction.${id}.prompt.inputLabel`]:\n 'Describe Your Variant...',\n [`ly.img.ai.quickAction.${id}.prompt.placeholder`]:\n 'e.g., same character with arms raised'\n }\n });\n\n return QuickActionBasePrompt<I, O>({\n buttonOptions: {\n icon: '@imgly/ImageVariation'\n },\n quickAction: {\n id,\n version: '1',\n confirmation: false,\n lockDuringConfirmation: false,\n scopes: ['lifecycle/duplicate', 'fill/change'],\n enable: (context) => {\n if (!enableImageFill()(context)) return false;\n\n const [blockId] = context.engine.block.findAllSelected();\n if (\n !options.cesdk.feature.isEnabled('ly.img.duplicate', {\n engine: context.engine\n })\n ) {\n return false;\n }\n if (\n !context.engine.block.isAllowedByScope(blockId, 'lifecycle/duplicate')\n ) {\n return false;\n }\n\n const parent = context.engine.block.getParent(blockId);\n const isBackgroundClip =\n parent != null &&\n context.engine.block.getType(parent) === '//ly.img.ubq/track' &&\n context.engine.block.isPageDurationSource(parent);\n\n if (isBackgroundClip) {\n return false;\n }\n\n const blockType = context.engine.block.getType(blockId);\n if (blockType === '//ly.img.ubq/page') return false;\n return true;\n }\n },\n onApply: async (prompt, context) => {\n const engine = options.cesdk.engine;\n const [blockId] = engine.block.findAllSelected();\n\n // Duplicate the selected block\n const duplicated = engine.block.duplicate(blockId);\n engine.block.setSelected(blockId, false);\n engine.block.setSelected(duplicated, true);\n\n // Offset the duplicated block\n const parent = engine.block.getParent(duplicated);\n if (parent == null) throw new Error('Parent not found');\n\n const offsetFactor = 1.0;\n const parentWidth = engine.block.getWidth(parent);\n const parentHeight = engine.block.getHeight(parent);\n const offset = 0.02 * Math.min(parentWidth, parentHeight) * offsetFactor;\n\n engine.block.setPositionX(\n duplicated,\n engine.block.getPositionX(duplicated) + offset\n );\n engine.block.setPositionY(\n duplicated,\n engine.block.getPositionY(duplicated) + offset\n );\n\n // Get the source of the duplicated block\n const uri = await getImageUri(duplicated, options.cesdk.engine, {\n throwErrorIfSvg: true\n });\n\n if (options.mapInput) {\n const input = options.mapInput({\n prompt,\n uri,\n duplicatedBlockId: duplicated\n });\n return context.generate(input);\n } else if (options.onApply) {\n return options.onApply(\n {\n prompt,\n uri,\n duplicatedBlockId: duplicated\n },\n context\n );\n } else {\n throw new Error('Please provide either mapInput or onApply');\n }\n }\n });\n}\n\nexport default QuickActionImageVariant;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { ImageOutput, QuickAction, QuickActionContext } from '../../provider';\nimport { getImageUri } from '@imgly/plugin-utils';\nimport QuickActionBasePrompt from './QuickActionBasePrompt';\nimport enableImageFill from './enableImageFill';\n\nfunction QuickActionChangeImage<I, O extends ImageOutput>(options: {\n id?: string;\n mapInput?: (input: { prompt: string; uri: string; blockId: number }) => I;\n onApply?: (\n options: { prompt: string; uri: string; blockId: number },\n context: QuickActionContext<I, O>\n ) => Promise<O>;\n cesdk: CreativeEditorSDK;\n}): QuickAction<I, O> {\n const id = options.id ?? 'swapBackground';\n\n if (options.mapInput == null && options.onApply == null) {\n throw new Error(\n `QuickAction '${id}': Either mapInput or onApply must be provided to QuickActionChangeImage`\n );\n }\n\n if (options.mapInput != null && options.onApply != null) {\n throw new Error(\n `QuickAction '${id}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`\n );\n }\n\n options.cesdk.i18n.setTranslations({\n en: {\n [`ly.img.ai.quickAction.${id}.apply`]: 'Change',\n [`ly.img.ai.quickAction.${id}`]: 'Change Background...',\n [`ly.img.ai.quickAction.${id}.prompt.inputLabel`]: 'Change background...',\n [`ly.img.ai.quickAction.${id}.prompt.placeholder`]:\n 'Describe the background you want...'\n }\n });\n\n return QuickActionBasePrompt<I, O>({\n buttonOptions: {\n icon: '@imgly/plugin-ai-generation/image'\n },\n quickAction: {\n id,\n version: '1',\n confirmation: true,\n lockDuringConfirmation: false,\n scopes: ['fill/change'],\n enable: enableImageFill()\n },\n onApply: async (userPrompt, context) => {\n const [blockId] = options.cesdk.engine.block.findAllSelected();\n const uri = await getImageUri(blockId, options.cesdk.engine, {\n throwErrorIfSvg: true\n });\n\n const prompt = `Swap the background to ${userPrompt}`;\n if (options.mapInput) {\n const input = options.mapInput({ prompt, uri, blockId });\n return context.generate(input);\n } else if (options.onApply) {\n return options.onApply(\n {\n prompt,\n uri,\n blockId\n },\n context\n );\n } else {\n throw new Error('Please provide either mapInput or onApply');\n }\n }\n });\n}\n\nexport default QuickActionChangeImage;\n", "import renderImageUrlProperty from './common/renderImageUrlProperty';\n\nconst CommonProperties = {\n ImageUrl: renderImageUrlProperty\n};\n\nexport { CommonProperties };\n\nexport {\n type default as Provider,\n type ImageOutput,\n type VideoOutput,\n type TextOutput,\n type AudioOutput,\n type Output,\n type OutputKind,\n type PanelInputSchema,\n type RenderCustomProperty,\n type GetBlockInput,\n type GetBlockInputResult,\n type GetInput,\n type QuickAction,\n type QuickActionsInput\n} from './generation/provider';\nexport {\n type GetPropertyInput,\n type Property\n} from './generation/openapi/types';\nexport { default as initProvider } from './generation/initProvider';\nexport { type GenerationMiddleware } from './generation/types';\n\n// Export middleware\nexport {\n composeMiddlewares,\n type Middleware\n} from './generation/middleware/middleware';\nexport { default as loggingMiddleware } from './generation/middleware/loggingMiddleware';\nexport { default as uploadMiddleware } from './generation/middleware/uploadMiddleware';\nexport {\n default as rateLimitMiddleware,\n type RateLimitOptions\n} from './generation/middleware/rateLimitMiddleware';\n\nexport {\n getPanelId,\n getDurationForVideo,\n getThumbnailForVideo,\n getLabelFromId\n} from './utils';\n\nexport { default as registerDockComponent } from './registerDockComponent';\n\nexport { default as getQuickActionMenu } from './generation/quickAction/getQuickActionMenu';\nexport { default as registerQuickActionMenuComponent } from './generation/quickAction/registerQuickActionMenuComponent';\n\nexport { default as QuickActionBasePrompt } from './generation/quickAction/common/QuickActionBasePrompt';\nexport { default as QuickActionBaseButton } from './generation/quickAction/common/QuickActionBaseButton';\nexport { default as QuickActionBaseSelect } from './generation/quickAction/common/QuickActionBaseSelect';\n\nexport { default as QuickActionEditTextStyle } from './generation/quickAction/common/QuickActionEditTextStyle';\nexport { default as QuickActionChangeImage } from './generation/quickAction/common/QuickActionChangeImage';\nexport { default as QuickActionImageVariant } from './generation/quickAction/common/QuickActionImageVariant';\nexport { default as QuickActionSwapImageBackground } from './generation/quickAction/common/QuickActionSwapImageBackground';\n\nexport { default as enableQuickActionForImageFill } from './generation/quickAction/common/enableImageFill';\n\nexport {\n isGeneratingStateKey,\n abortGenerationStateKey\n} from './generation/renderGenerationComponents';\n", "{\n \"openapi\": \"3.0.0\",\n \"info\": {\n \"title\": \"Fal Queue API\",\n \"version\": \"1.0.0\",\n \"description\": \"The Fal Queue API.\"\n },\n \"components\": {\n \"securitySchemes\": {\n \"apiKeyAuth\": {\n \"type\": \"apiKey\",\n \"in\": \"header\",\n \"name\": \"Authorization\",\n \"description\": \"Fal Key\"\n }\n },\n \"schemas\": {\n \"QueueStatus\": {\n \"type\": \"object\",\n \"properties\": {\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\"IN_QUEUE\", \"IN_PROGRESS\", \"COMPLETED\"]\n },\n \"request_id\": { \"type\": \"string\", \"description\": \"The request id.\" },\n \"response_url\": {\n \"type\": \"string\",\n \"description\": \"The response url.\"\n },\n \"status_url\": { \"type\": \"string\", \"description\": \"The status url.\" },\n \"cancel_url\": { \"type\": \"string\", \"description\": \"The cancel url.\" },\n \"logs\": {\n \"type\": \"object\",\n \"description\": \"The logs.\",\n \"additionalProperties\": true\n },\n \"metrics\": {\n \"type\": \"object\",\n \"description\": \"The metrics.\",\n \"additionalProperties\": true\n },\n \"queue_position\": {\n \"type\": \"integer\",\n \"description\": \"The queue position.\"\n }\n },\n \"required\": [\"status\", \"request_id\"]\n },\n \"RecraftV3Input\": {\n \"title\": \"TextToImageInput\",\n \"type\": \"object\",\n \"properties\": {\n \"prompt\": {\n \"title\": \"Prompt\",\n \"type\": \"string\",\n \"x-imgly-builder\": {\n \"component\": \"TextArea\"\n }\n },\n \"image_size\": {\n \"anyOf\": [\n {\n \"enum\": [\n \"square_hd\",\n \"square\",\n \"portrait_4_3\",\n \"portrait_16_9\",\n \"landscape_4_3\",\n \"landscape_16_9\"\n ],\n \"type\": \"string\"\n },\n { \"$ref\": \"#/components/schemas/ImageSize\" }\n ],\n \"title\": \"Format\",\n \"default\": \"square_hd\",\n \"x-imgly-enum-labels\": {\n \"ImageSize\": \"Custom\",\n \"square_hd\": \"Square HD\",\n \"square\": \"Square\",\n \"portrait_4_3\": \"Portrait 4:3\",\n \"portrait_16_9\": \"Portrait 16:9\",\n \"landscape_4_3\": \"Landscape 4:3\",\n \"landscape_16_9\": \"Landscape 16:9\"\n },\n \"x-imgly-enum-icons\": {\n \"square\": \"@imgly/plugin/formats/ratio1by1\",\n \"square_hd\": \"@imgly/plugin/formats/ratio1by1\",\n \"portrait_4_3\": \"@imgly/plugin/formats/ratio3by4\",\n \"portrait_16_9\": \"@imgly/plugin/formats/ratio9by16\",\n \"landscape_4_3\": \"@imgly/plugin/formats/ratio4by3\",\n \"landscape_16_9\": \"@imgly/plugin/formats/ratio16by9\",\n \"ImageSize\": \"@imgly/plugin/formats/ratioFree\"\n }\n },\n \"style\": {\n \"enum\": [\n \"any\",\n \"realistic_image\",\n \"digital_illustration\",\n \"vector_illustration\",\n \"realistic_image/b_and_w\",\n \"realistic_image/hard_flash\",\n \"realistic_image/hdr\",\n \"realistic_image/natural_light\",\n \"realistic_image/studio_portrait\",\n \"realistic_image/enterprise\",\n \"realistic_image/motion_blur\",\n \"realistic_image/evening_light\",\n \"realistic_image/faded_nostalgia\",\n \"realistic_image/forest_life\",\n \"realistic_image/mystic_naturalism\",\n \"realistic_image/natural_tones\",\n \"realistic_image/organic_calm\",\n \"realistic_image/real_life_glow\",\n \"realistic_image/retro_realism\",\n \"realistic_image/retro_snapshot\",\n \"realistic_image/urban_drama\",\n \"realistic_image/village_realism\",\n \"realistic_image/warm_folk\",\n \"digital_illustration/pixel_art\",\n \"digital_illustration/hand_drawn\",\n \"digital_illustration/grain\",\n \"digital_illustration/infantile_sketch\",\n \"digital_illustration/2d_art_poster\",\n \"digital_illustration/handmade_3d\",\n \"digital_illustration/hand_drawn_outline\",\n \"digital_illustration/engraving_color\",\n \"digital_illustration/2d_art_poster_2\",\n \"digital_illustration/antiquarian\",\n \"digital_illustration/bold_fantasy\",\n \"digital_illustration/child_book\",\n \"digital_illustration/child_books\",\n \"digital_illustration/cover\",\n \"digital_illustration/crosshatch\",\n \"digital_illustration/digital_engraving\",\n \"digital_illustration/expressionism\",\n \"digital_illustration/freehand_details\",\n \"digital_illustration/grain_20\",\n \"digital_illustration/graphic_intensity\",\n \"digital_illustration/hard_comics\",\n \"digital_illustration/long_shadow\",\n \"digital_illustration/modern_folk\",\n \"digital_illustration/multicolor\",\n \"digital_illustration/neon_calm\",\n \"digital_illustration/noir\",\n \"digital_illustration/nostalgic_pastel\",\n \"digital_illustration/outline_details\",\n \"digital_illustration/pastel_gradient\",\n \"digital_illustration/pastel_sketch\",\n \"digital_illustration/pop_art\",\n \"digital_illustration/pop_renaissance\",\n \"digital_illustration/street_art\",\n \"digital_illustration/tablet_sketch\",\n \"digital_illustration/urban_glow\",\n \"digital_illustration/urban_sketching\",\n \"digital_illustration/vanilla_dreams\",\n \"digital_illustration/young_adult_book\",\n \"digital_illustration/young_adult_book_2\",\n \"vector_illustration/bold_stroke\",\n \"vector_illustration/chemistry\",\n \"vector_illustration/colored_stencil\",\n \"vector_illustration/contour_pop_art\",\n \"vector_illustration/cosmics\",\n \"vector_illustration/cutout\",\n \"vector_illustration/depressive\",\n \"vector_illustration/editorial\",\n \"vector_illustration/emotional_flat\",\n \"vector_illustration/infographical\",\n \"vector_illustration/marker_outline\",\n \"vector_illustration/mosaic\",\n \"vector_illustration/naivector\",\n \"vector_illustration/roundish_flat\",\n \"vector_illustration/segmented_colors\",\n \"vector_illustration/sharp_contrast\",\n \"vector_illustration/thin\",\n \"vector_illustration/vector_photo\",\n \"vector_illustration/vivid_shapes\",\n \"vector_illustration/engraving\",\n \"vector_illustration/line_art\",\n \"vector_illustration/line_circuit\",\n \"vector_illustration/linocut\"\n ],\n \"title\": \"Style\",\n \"type\": \"string\",\n \"description\": \"The style of the generated images. Vector images cost 2X as much.\",\n \"default\": \"realistic_image\"\n },\n \"colors\": {\n \"title\": \"Colors\",\n \"type\": \"array\",\n \"description\": \"An array of preferable colors\",\n \"items\": { \"$ref\": \"#/components/schemas/RGBColor\" },\n \"default\": []\n }\n },\n \"x-fal-order-properties\": [\"prompt\", \"style\", \"image_size\"],\n \"required\": [\"prompt\"]\n },\n \"RecraftV3Output\": {\n \"title\": \"TextToImageOutput\",\n \"type\": \"object\",\n \"properties\": {\n \"images\": {\n \"title\": \"Images\",\n \"type\": \"array\",\n \"items\": { \"$ref\": \"#/components/schemas/File\" }\n }\n },\n \"x-fal-order-properties\": [\"images\"],\n \"required\": [\"images\"]\n },\n \"ImageSize\": {\n \"title\": \"ImageSize\",\n \"type\": \"object\",\n \"properties\": {\n \"height\": {\n \"maximum\": 14142,\n \"type\": \"integer\",\n \"title\": \"Height\",\n \"description\": \"The height of the generated image.\",\n \"exclusiveMinimum\": 0,\n \"default\": 512\n },\n \"width\": {\n \"maximum\": 14142,\n \"type\": \"integer\",\n \"title\": \"Width\",\n \"description\": \"The width of the generated image.\",\n \"exclusiveMinimum\": 0,\n \"default\": 512\n }\n },\n \"x-fal-order-properties\": [\"width\", \"height\"]\n },\n \"RGBColor\": {\n \"title\": \"RGBColor\",\n \"type\": \"object\",\n \"properties\": {\n \"r\": {\n \"minimum\": 0,\n \"maximum\": 255,\n \"type\": \"integer\",\n \"title\": \"R\",\n \"description\": \"Red color value\",\n \"default\": 0\n },\n \"b\": {\n \"minimum\": 0,\n \"maximum\": 255,\n \"type\": \"integer\",\n \"title\": \"B\",\n \"description\": \"Blue color value\",\n \"default\": 0\n },\n \"g\": {\n \"minimum\": 0,\n \"maximum\": 255,\n \"type\": \"integer\",\n \"title\": \"G\",\n \"description\": \"Green color value\",\n \"default\": 0\n }\n },\n \"x-fal-order-properties\": [\"r\", \"g\", \"b\"]\n },\n \"File\": {\n \"title\": \"File\",\n \"type\": \"object\",\n \"properties\": {\n \"file_size\": {\n \"title\": \"File Size\",\n \"type\": \"integer\",\n \"description\": \"The size of the file in bytes.\"\n },\n \"file_name\": {\n \"title\": \"File Name\",\n \"type\": \"string\",\n \"description\": \"The name of the file. It will be auto-generated if not provided.\"\n },\n \"content_type\": {\n \"title\": \"Content Type\",\n \"type\": \"string\",\n \"description\": \"The mime type of the file.\"\n },\n \"url\": {\n \"title\": \"Url\",\n \"type\": \"string\",\n \"description\": \"The URL where the file can be downloaded from.\"\n },\n \"file_data\": {\n \"format\": \"binary\",\n \"title\": \"File Data\",\n \"type\": \"string\",\n \"description\": \"File data\"\n }\n },\n \"x-fal-order-properties\": [\n \"url\",\n \"content_type\",\n \"file_name\",\n \"file_size\",\n \"file_data\"\n ],\n \"required\": [\"url\"]\n }\n }\n },\n \"paths\": {\n \"/fal-ai/recraft-v3/requests/{request_id}/status\": {\n \"get\": {\n \"parameters\": [\n {\n \"name\": \"request_id\",\n \"in\": \"path\",\n \"required\": true,\n \"schema\": { \"type\": \"string\", \"description\": \"Request ID\" }\n },\n {\n \"name\": \"logs\",\n \"in\": \"query\",\n \"required\": false,\n \"schema\": {\n \"type\": \"number\",\n \"description\": \"Whether to include logs (`1`) in the response or not (`0`).\"\n }\n }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"The request status.\",\n \"content\": {\n \"application/json\": {\n \"schema\": { \"$ref\": \"#/components/schemas/QueueStatus\" }\n }\n }\n }\n }\n }\n },\n \"/fal-ai/recraft-v3/requests/{request_id}/cancel\": {\n \"put\": {\n \"parameters\": [\n {\n \"name\": \"request_id\",\n \"in\": \"path\",\n \"required\": true,\n \"schema\": { \"type\": \"string\", \"description\": \"Request ID\" }\n }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"The request was cancelled.\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"success\": {\n \"type\": \"boolean\",\n \"description\": \"Whether the request was cancelled successfully.\"\n }\n }\n }\n }\n }\n }\n }\n }\n },\n \"/fal-ai/recraft-v3\": {\n \"post\": {\n \"requestBody\": {\n \"required\": true,\n \"content\": {\n \"application/json\": {\n \"schema\": { \"$ref\": \"#/components/schemas/RecraftV3Input\" }\n }\n }\n },\n \"responses\": {\n \"200\": {\n \"description\": \"The request status.\",\n \"content\": {\n \"application/json\": {\n \"schema\": { \"$ref\": \"#/components/schemas/QueueStatus\" }\n }\n }\n }\n }\n }\n },\n \"/fal-ai/recraft-v3/requests/{request_id}\": {\n \"get\": {\n \"parameters\": [\n {\n \"name\": \"request_id\",\n \"in\": \"path\",\n \"required\": true,\n \"schema\": { \"type\": \"string\", \"description\": \"Request ID\" }\n }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"Result of the request.\",\n \"content\": {\n \"application/json\": {\n \"schema\": { \"$ref\": \"#/components/schemas/RecraftV3Output\" }\n }\n }\n }\n }\n }\n }\n },\n \"servers\": [{ \"url\": \"https://queue.fal.run\" }],\n \"security\": [{ \"apiKeyAuth\": [] }]\n}\n", "import { RecraftV3Input } from '@fal-ai/client/endpoints';\n\nconst ImageSizeEnumToSize: Record<string, { width: number; height: number }> = {\n square_hd: { width: 1024, height: 1024 },\n square: { width: 512, height: 512 },\n portrait_4_3: { width: 1024, height: 1365 },\n portrait_16_9: { width: 1024, height: 1820 },\n landscape_4_3: { width: 1365, height: 1024 },\n landscape_16_9: { width: 1820, height: 1024 }\n};\n\nexport function getImageDimensions(id: string): {\n width: number;\n height: number;\n} {\n return ImageSizeEnumToSize[id];\n}\n\nexport type StyleId = Extract<RecraftV3Input['style'], string>;\n\n// prettier-ignore\nexport const STYLES_IMAGE: { id: StyleId; label: string }[] = [\n // { id: 'any', label: 'Any' },\n { id: 'realistic_image', label: 'Realistic Image' },\n { id: 'digital_illustration', label: 'Digital Illustration' },\n { id: 'realistic_image/b_and_w', label: 'Black & White' },\n { id: 'realistic_image/hard_flash', label: 'Hard Flash' },\n { id: 'realistic_image/hdr', label: 'HDR' },\n { id: 'realistic_image/natural_light', label: 'Natural Light' },\n { id: 'realistic_image/studio_portrait', label: 'Studio Portrait' },\n { id: 'realistic_image/enterprise', label: 'Enterprise' },\n { id: 'realistic_image/motion_blur', label: 'Motion Blur' },\n { id: 'realistic_image/evening_light', label: 'Evening Light' },\n { id: 'realistic_image/faded_nostalgia', label: 'Faded Nostalgia' },\n { id: 'realistic_image/forest_life', label: 'Forest Life' },\n { id: 'realistic_image/mystic_naturalism', label: 'Mystic Naturalism' },\n { id: 'realistic_image/natural_tones', label: 'Natural Tones' },\n { id: 'realistic_image/organic_calm', label: 'Organic Calm' },\n { id: 'realistic_image/real_life_glow', label: 'Real Life Glow' },\n { id: 'realistic_image/retro_realism', label: 'Retro Realism' },\n { id: 'realistic_image/retro_snapshot', label: 'Retro Snapshot' },\n { id: 'realistic_image/urban_drama', label: 'Urban Drama' },\n { id: 'realistic_image/village_realism', label: 'Village Realism' },\n { id: 'realistic_image/warm_folk', label: 'Warm Folk' },\n { id: 'digital_illustration/pixel_art', label: 'Pixel Art' },\n { id: 'digital_illustration/hand_drawn', label: 'Hand Drawn' },\n { id: 'digital_illustration/grain', label: 'Grain' },\n { id: 'digital_illustration/infantile_sketch', label: 'Infantile Sketch' },\n { id: 'digital_illustration/2d_art_poster', label: '2D Art Poster' },\n { id: 'digital_illustration/handmade_3d', label: 'Handmade 3D' },\n { id: 'digital_illustration/hand_drawn_outline', label: 'Hand Drawn Outline' },\n { id: 'digital_illustration/engraving_color', label: 'Engraving Color' },\n { id: 'digital_illustration/2d_art_poster_2', label: '2D Art Poster 2' },\n { id: 'digital_illustration/antiquarian', label: 'Antiquarian' },\n { id: 'digital_illustration/bold_fantasy', label: 'Bold Fantasy' },\n { id: 'digital_illustration/child_book', label: 'Child Book' },\n { id: 'digital_illustration/child_books', label: 'Child Books' },\n { id: 'digital_illustration/cover', label: 'Cover' },\n { id: 'digital_illustration/crosshatch', label: 'Crosshatch' },\n { id: 'digital_illustration/digital_engraving', label: 'Digital Engraving' },\n { id: 'digital_illustration/expressionism', label: 'Expressionism' },\n { id: 'digital_illustration/freehand_details', label: 'Freehand Details' },\n { id: 'digital_illustration/grain_20', label: 'Grain 20' },\n { id: 'digital_illustration/graphic_intensity', label: 'Graphic Intensity' },\n { id: 'digital_illustration/hard_comics', label: 'Hard Comics' },\n { id: 'digital_illustration/long_shadow', label: 'Long Shadow' },\n { id: 'digital_illustration/modern_folk', label: 'Modern Folk' },\n { id: 'digital_illustration/multicolor', label: 'Multicolor' },\n { id: 'digital_illustration/neon_calm', label: 'Neon Calm' },\n { id: 'digital_illustration/noir', label: 'Noir' },\n { id: 'digital_illustration/nostalgic_pastel', label: 'Nostalgic Pastel' },\n { id: 'digital_illustration/outline_details', label: 'Outline Details' },\n { id: 'digital_illustration/pastel_gradient', label: 'Pastel Gradient' },\n { id: 'digital_illustration/pastel_sketch', label: 'Pastel Sketch' },\n { id: 'digital_illustration/pop_art', label: 'Pop Art' },\n { id: 'digital_illustration/pop_renaissance', label: 'Pop Renaissance' },\n { id: 'digital_illustration/street_art', label: 'Street Art' },\n { id: 'digital_illustration/tablet_sketch', label: 'Tablet Sketch' },\n { id: 'digital_illustration/urban_glow', label: 'Urban Glow' },\n { id: 'digital_illustration/urban_sketching', label: 'Urban Sketching' },\n { id: 'digital_illustration/vanilla_dreams', label: 'Vanilla Dreams' },\n { id: 'digital_illustration/young_adult_book', label: 'Young Adult Book' },\n { id: 'digital_illustration/young_adult_book_2', label: 'Young Adult Book 2' },\n];\n\nexport const STYLE_IMAGE_DEFAULT = STYLES_IMAGE[0];\n\n// prettier-ignore\nexport const STYLES_VECTOR: { id: StyleId; label: string }[] = [\n { id: 'vector_illustration', label: 'Vector Illustration' },\n { id: 'vector_illustration/bold_stroke', label: 'Bold Stroke' },\n { id: 'vector_illustration/chemistry', label: 'Chemistry' },\n { id: 'vector_illustration/colored_stencil', label: 'Colored Stencil' },\n { id: 'vector_illustration/contour_pop_art', label: 'Contour Pop Art' },\n { id: 'vector_illustration/cosmics', label: 'Cosmics' },\n { id: 'vector_illustration/cutout', label: 'Cutout' },\n { id: 'vector_illustration/depressive', label: 'Depressive' },\n { id: 'vector_illustration/editorial', label: 'Editorial' },\n { id: 'vector_illustration/emotional_flat', label: 'Emotional Flat' },\n { id: 'vector_illustration/infographical', label: 'Infographical' },\n { id: 'vector_illustration/marker_outline', label: 'Marker Outline' },\n { id: 'vector_illustration/mosaic', label: 'Mosaic' },\n { id: 'vector_illustration/naivector', label: 'Naive Vector' },\n { id: 'vector_illustration/roundish_flat', label: 'Roundish Flat' },\n { id: 'vector_illustration/segmented_colors', label: 'Segmented Colors' },\n { id: 'vector_illustration/sharp_contrast', label: 'Sharp Contrast' },\n { id: 'vector_illustration/thin', label: 'Thin' },\n { id: 'vector_illustration/vector_photo', label: 'Vector Photo' },\n { id: 'vector_illustration/vivid_shapes', label: 'Vivid Shapes' },\n { id: 'vector_illustration/engraving', label: 'Engraving' },\n { id: 'vector_illustration/line_art', label: 'Line Art' },\n { id: 'vector_illustration/line_circuit', label: 'Line Circuit' },\n { id: 'vector_illustration/linocut', label: 'Linocut' },\n];\n\nexport const STYLE_VECTOR_DEFAULT = STYLES_VECTOR[0];\n\n// prettier-ignore\nconst STYLE_THUMBNAILS: (baseURL: string) => ({ [key in StyleId]?: string }) = (baseURL) => ({\n'realistic_image': `${baseURL}/realistic_image.webp`,\n'digital_illustration': `${baseURL}/digital_illustration.webp`,\n'realistic_image/b_and_w': `${baseURL}/realistic_image_black_&_white.webp`,\n'realistic_image/hard_flash': `${baseURL}/realistic_image_hard_flash.webp`,\n'realistic_image/hdr': `${baseURL}/realistic_image_hdr.webp`,\n'realistic_image/natural_light': `${baseURL}/realistic_image_natural_light.webp`,\n'realistic_image/studio_portrait': `${baseURL}/realistic_image_studio_portrait.webp`,\n'realistic_image/enterprise': `${baseURL}/realistic_image_enterprise.webp`,\n'realistic_image/motion_blur': `${baseURL}/realistic_image_motion_blur.webp`,\n'digital_illustration/pixel_art': `${baseURL}/digital_illustration_pixel_art.webp`,\n'digital_illustration/hand_drawn': `${baseURL}/digital_illustration_hand_drawn.webp`,\n'digital_illustration/grain': `${baseURL}/digital_illustration_grain.webp`,\n'digital_illustration/infantile_sketch': `${baseURL}/digital_illustration_infantile_sketch.webp`,\n'digital_illustration/2d_art_poster': `${baseURL}/digital_illustration_2d_art_poster.webp`,\n'digital_illustration/handmade_3d': `${baseURL}/digital_illustration_handmade_3d.webp`,\n'digital_illustration/hand_drawn_outline': `${baseURL}/digital_illustration_handdrawn_outline.webp`,\n'digital_illustration/engraving_color': `${baseURL}/digital_illustration_engraving_color.webp`,\n'digital_illustration/2d_art_poster_2': `${baseURL}/digital_illustration_2d_artposter_2.webp`,\n'vector_illustration': `${baseURL}/vector_illustration.svg`,\n'vector_illustration/bold_stroke': `${baseURL}/vector_illustration_bold_stroke.svg`,\n'vector_illustration/chemistry': `${baseURL}/vector_illustration_chemistry.svg`,\n'vector_illustration/colored_stencil': `${baseURL}/vector_illustration_colored_stencil.svg`,\n'vector_illustration/contour_pop_art': `${baseURL}/vector_illustration_contour_pop_art.svg`,\n'vector_illustration/cosmics': `${baseURL}/vector_illustration_cosmics.svg`,\n'vector_illustration/cutout': `${baseURL}/vector_illustration_cutout.svg`,\n'vector_illustration/depressive': `${baseURL}/vector_illustration_depressive.svg`,\n'vector_illustration/editorial': `${baseURL}/vector_illustration_editorial.svg`,\n'vector_illustration/emotional_flat': `${baseURL}/vector_illustration_emotional_flat.svg`,\n'vector_illustration/infographical': `${baseURL}/vector_illustration_infographical.svg`,\n'vector_illustration/marker_outline': `${baseURL}/vector_illustration_marker_outline.svg`,\n'vector_illustration/mosaic': `${baseURL}/vector_illustration_mosaic.svg`,\n'vector_illustration/naivector': `${baseURL}/vector_illustration_naivector.svg`,\n'vector_illustration/roundish_flat': `${baseURL}/vector_illustration_roundish_flat.svg`,\n'vector_illustration/segmented_colors': `${baseURL}/vector_illustration_segmented_colors.svg`,\n'vector_illustration/sharp_contrast': `${baseURL}/vector_illustration_sharp_contrast.svg`,\n'vector_illustration/thin': `${baseURL}/vector_illustration_thin.svg`,\n'vector_illustration/vector_photo': `${baseURL}/vector_illustration_vector_photo.svg`,\n'vector_illustration/vivid_shapes': `${baseURL}/vector_illustration_vivid_shapes.svg`,\n'vector_illustration/engraving': `${baseURL}/vector_illustration_engraving.svg`,\n'vector_illustration/line_art': `${baseURL}/vector_illustration_line_art.svg`,\n'vector_illustration/line_circuit': `${baseURL}/vector_illustration_line_circuit.svg`,\n'vector_illustration/linocut': `${baseURL}/vector_illustration_linocut.svg`,\n'realistic_image/evening_light': `${baseURL}/realistic_image_evening_light.webp`,\n'realistic_image/faded_nostalgia': `${baseURL}/realistic_image_faded_nostalgia.webp`,\n'realistic_image/forest_life': `${baseURL}/realistic_image_forest_life.webp`,\n'realistic_image/mystic_naturalism': `${baseURL}/realistic_image_mystic_naturalism.webp`,\n'realistic_image/natural_tones': `${baseURL}/realistic_image_natural_tones.webp`,\n'realistic_image/organic_calm': `${baseURL}/realistic_image_organic_calm.webp`,\n'realistic_image/real_life_glow': `${baseURL}/realistic_image_real_life_glow.webp`,\n'realistic_image/retro_realism': `${baseURL}/realistic_image_retro_realism.webp`,\n'realistic_image/retro_snapshot': `${baseURL}/realistic_image_retro_snapshot.webp`,\n'realistic_image/urban_drama': `${baseURL}/realistic_image_urban_drama.webp`,\n'realistic_image/village_realism': `${baseURL}/realistic_image_village_realism.webp`,\n'realistic_image/warm_folk': `${baseURL}/realistic_image_warm_folk.webp`,\n'digital_illustration/antiquarian': `${baseURL}/digital_illustration_antiquarian.webp`,\n'digital_illustration/bold_fantasy': `${baseURL}/digital_illustration_bold_fantasy.webp`,\n'digital_illustration/child_book': `${baseURL}/digital_illustration_child_book.webp`,\n'digital_illustration/child_books': `${baseURL}/digital_illustration_child_books.webp`,\n'digital_illustration/cover': `${baseURL}/digital_illustration_cover.webp`,\n'digital_illustration/crosshatch': `${baseURL}/digital_illustration_crosshatch.webp`,\n'digital_illustration/digital_engraving': `${baseURL}/digital_illustration_digital_engraving.webp`,\n'digital_illustration/expressionism': `${baseURL}/digital_illustration_expressionism.webp`,\n'digital_illustration/freehand_details': `${baseURL}/digital_illustration_freehand_details.webp`,\n'digital_illustration/grain_20': `${baseURL}/digital_illustration_grain_20.webp`,\n'digital_illustration/graphic_intensity': `${baseURL}/digital_illustration_graphic_intensity.webp`,\n'digital_illustration/hard_comics': `${baseURL}/digital_illustration_hard_comics.webp`,\n'digital_illustration/long_shadow': `${baseURL}/digital_illustration_long_shadow.webp`,\n'digital_illustration/modern_folk': `${baseURL}/digital_illustration_modern_folk.webp`,\n'digital_illustration/multicolor': `${baseURL}/digital_illustration_multicolor.webp`,\n'digital_illustration/neon_calm': `${baseURL}/digital_illustration_neon_calm.webp`,\n'digital_illustration/noir': `${baseURL}/digital_illustration_noir.webp`,\n'digital_illustration/nostalgic_pastel': `${baseURL}/digital_illustration_nostalgic_pastel.webp`,\n'digital_illustration/outline_details': `${baseURL}/digital_illustration_outline_details.webp`,\n'digital_illustration/pastel_gradient': `${baseURL}/digital_illustration_pastel_gradient.webp`,\n'digital_illustration/pastel_sketch': `${baseURL}/digital_illustration_pastel_sketch.webp`,\n'digital_illustration/pop_art': `${baseURL}/digital_illustration_pop_art.webp`,\n'digital_illustration/pop_renaissance': `${baseURL}/digital_illustration_pop_renaissance.webp`,\n'digital_illustration/street_art': `${baseURL}/digital_illustration_street_art.webp`,\n'digital_illustration/tablet_sketch': `${baseURL}/digital_illustration_tablet_sketch.webp`,\n'digital_illustration/urban_glow': `${baseURL}/digital_illustration_urban_glow.webp`,\n'digital_illustration/urban_sketching': `${baseURL}/digital_illustration_urban_sketching.webp`,\n'digital_illustration/vanilla_dreams': `${baseURL}/digital_illustration_vanilla_dreams.webp`,\n'digital_illustration/young_adult_book': `${baseURL}/digital_illustration_young_adult_book.webp`,\n'digital_illustration/young_adult_book_2': `${baseURL}/digital_illustration_young_adult_book_2.webp`,\n})\n\nexport function getStyleThumbnail(\n id: StyleId,\n baseURL: string\n): string | undefined {\n return STYLE_THUMBNAILS(`${baseURL}thumbnails/`)[id];\n}\n", "import { type OpenAPIV3 } from 'openapi-types';\nimport CreativeEditorSDK, { CreativeEngine } from '@cesdk/cesdk-js';\nimport {\n ImageOutput,\n RenderCustomProperty,\n GetBlockInput,\n CommonProperties,\n Provider,\n QuickAction,\n loggingMiddleware,\n Middleware\n} from '@imgly/plugin-ai-generation-web';\nimport { fal } from '@fal-ai/client';\nimport { isCustomImageSize, uploadImageInputToFalIfNeeded } from './utils';\nimport { getImageDimensions } from './RecraftV3.constants';\n\ntype ImageProviderConfiguration = {\n proxyUrl: string;\n debug?: boolean;\n};\n\n/**\n * Creates a base provider from schema. This should work out of the box\n * but may be rough around the edges and should/can be further customized.\n */\nfunction createImageProvider<I extends Record<string, any>>(\n options: {\n modelKey: string;\n name?: string;\n schema: OpenAPIV3.Document;\n inputReference: string;\n useFlow?: 'placeholder' | 'generation-only';\n initialize?: (context: {\n cesdk?: CreativeEditorSDK;\n engine: CreativeEngine;\n }) => void;\n\n renderCustomProperty?: RenderCustomProperty;\n\n quickActions?: QuickAction<I, ImageOutput>[];\n getBlockInput?: GetBlockInput<'image', I>;\n getImageSize?: (input: I) => { width: number; height: number };\n\n middleware?: Middleware<I, ImageOutput>[];\n\n cesdk?: CreativeEditorSDK;\n },\n config: ImageProviderConfiguration\n): Provider<'image', I, { kind: 'image'; url: string }> {\n const middleware = options.middleware ?? [];\n if (config.debug) {\n middleware.unshift(loggingMiddleware<I, ImageOutput>());\n }\n\n const provider: Provider<'image', I, ImageOutput> = {\n id: options.modelKey,\n kind: 'image',\n name: options.name,\n initialize: async (context) => {\n fal.config({\n proxyUrl: config.proxyUrl\n });\n\n options.initialize?.(context);\n },\n input: {\n quickActions: {\n actions: options.quickActions ?? []\n },\n panel: {\n type: 'schema',\n document: options.schema,\n inputReference: options.inputReference,\n includeHistoryLibrary: true,\n orderExtensionKeyword: 'x-fal-order-properties',\n renderCustomProperty: {\n ...(options.cesdk != null\n ? CommonProperties.ImageUrl(options.modelKey, {\n cesdk: options.cesdk\n })\n : {}),\n ...options.renderCustomProperty\n },\n getBlockInput: (input) => {\n if (options.getBlockInput != null)\n return options.getBlockInput(input);\n if (options.getImageSize != null) {\n const { width, height } = options.getImageSize(input);\n return Promise.resolve({\n image: {\n width,\n height\n }\n });\n }\n if (input.image_size != null && isCustomImageSize(input.image_size)) {\n return Promise.resolve({\n image: {\n width: input.image_size.width ?? 512,\n height: input.image_size.height ?? 512\n }\n });\n }\n\n if (\n input.image_size != null &&\n typeof input.image_size === 'string'\n ) {\n const imageDimension = getImageDimensions(input.image_size);\n return Promise.resolve({\n image: imageDimension\n });\n }\n\n throw new Error('getBlockInput or getImageSize must be provided');\n },\n userFlow: options.useFlow ?? 'placeholder'\n }\n },\n output: {\n abortable: true,\n middleware,\n history: '@imgly/indexedDB',\n generate: async (\n input: I,\n { abortSignal }: { abortSignal?: AbortSignal }\n ) => {\n const image_url = await uploadImageInputToFalIfNeeded(\n input.image_url,\n options.cesdk\n );\n\n const response = await fal.subscribe(options.modelKey, {\n abortSignal,\n input: image_url != null ? { ...input, image_url } : input,\n logs: true\n });\n\n const images = response?.data?.images;\n if (images != null && Array.isArray(images)) {\n const image = images[0];\n const url: string = image?.url;\n if (url != null)\n return {\n kind: 'image',\n url\n };\n } else {\n const image = response?.data?.image;\n if (image != null) {\n const url = image?.url;\n if (url != null)\n return {\n kind: 'image',\n url\n };\n }\n }\n\n // eslint-disable-next-line no-console\n console.error(\n 'Cannot extract generated image from response:',\n response\n );\n throw new Error('Cannot find generated image');\n }\n }\n };\n\n if (config.debug)\n // eslint-disable-next-line no-console\n console.log('Created Provider:', provider);\n\n return provider;\n}\n\nexport default createImageProvider;\n", "import { fal } from '@fal-ai/client';\nimport { mimeTypeToExtension } from '@imgly/plugin-utils';\nimport CreativeEditorSDK from '@cesdk/cesdk-js';\n\ntype CustomImageSize = {\n width: number;\n height: number;\n};\n\nexport function isCustomImageSize(\n imageSize: any\n): imageSize is CustomImageSize {\n return (\n imageSize != null &&\n typeof imageSize !== 'string' &&\n 'width' in imageSize &&\n 'height' in imageSize\n );\n}\n\nexport async function uploadImageInputToFalIfNeeded(\n imageUrl?: string,\n cesdk?: CreativeEditorSDK\n): Promise<string | undefined> {\n if (imageUrl == null) return undefined;\n if (imageUrl.startsWith('blob:')) {\n const mimeType =\n cesdk != null\n ? await cesdk.engine.editor.getMimeType(imageUrl)\n : 'image/png';\n const imageUrlResponse = await fetch(imageUrl);\n const imageUrlBlob = await imageUrlResponse.blob();\n const imageUrlFile = new File(\n [imageUrlBlob],\n `image.${mimeTypeToExtension(mimeType)}`,\n {\n type: mimeType\n }\n );\n return fal.storage.upload(imageUrlFile);\n }\n if (cesdk != null && imageUrl.startsWith('buffer:')) {\n const mimeType = await cesdk.engine.editor.getMimeType(imageUrl);\n const length = cesdk.engine.editor.getBufferLength(imageUrl);\n const data = cesdk.engine.editor.getBufferData(imageUrl, 0, length);\n const imageUrlFile = new File(\n [data],\n `image.${mimeTypeToExtension(mimeType)}`,\n {\n type: mimeType\n }\n );\n return fal.storage.upload(imageUrlFile);\n }\n\n return imageUrl;\n}\n", "import { Icons, CustomAssetSource } from '@imgly/plugin-utils';\nimport {\n Middleware,\n type Provider,\n getPanelId\n} from '@imgly/plugin-ai-generation-web';\nimport { type RecraftV3Input } from '@fal-ai/client/endpoints';\nimport RecraftV3Schema from './RecraftV3.json';\nimport CreativeEditorSDK, { AssetResult } from '@cesdk/cesdk-js';\nimport {\n STYLES_IMAGE,\n STYLES_VECTOR,\n getImageDimensions,\n getStyleThumbnail\n} from './RecraftV3.constants';\nimport createImageProvider from './createImageProvider';\nimport { isCustomImageSize } from './utils';\n\ntype RecraftV3Output = {\n kind: 'image';\n url: string;\n};\n\nexport type StyleId = Extract<RecraftV3Input['style'], string>;\n\ntype GenerationType = 'image' | 'vector';\n\ntype StyleSelectionPayload = {\n onSelect: (asset: AssetResult) => Promise<void>;\n generationType: GenerationType;\n};\n\ntype ProviderConfiguration = {\n proxyUrl: string;\n debug?: boolean;\n middleware?: Middleware<RecraftV3Input, RecraftV3Output>[];\n\n /**\n * Base URL used for the UI assets used in the plugin.\n *\n * By default, we load the assets from the IMG.LY CDN You can copy the assets.\n * from the `/assets` folder to your own server and set the base URL to your server.\n */\n baseURL?: string;\n};\n\nlet imageStyleAssetSource: CustomAssetSource;\nlet vectorStyleAssetSource: CustomAssetSource;\n\nexport function RecraftV3(\n config: ProviderConfiguration\n): (context: {\n cesdk: CreativeEditorSDK;\n}) => Promise<Provider<'image', RecraftV3Input, RecraftV3Output>> {\n return async ({ cesdk }: { cesdk: CreativeEditorSDK }) => {\n return getProvider(cesdk, config);\n };\n}\n\nfunction getProvider(\n cesdk: CreativeEditorSDK,\n config: ProviderConfiguration\n): Provider<'image', RecraftV3Input, RecraftV3Output> {\n const modelKey = 'fal-ai/recraft-v3';\n const styleImageAssetSourceId = `${modelKey}/styles/image`;\n const styleVectorAssetSourceId = `${modelKey}/styles/vector`;\n const baseURL =\n config.baseURL ??\n 'https://cdn.img.ly/assets/plugins/plugin-ai-image-generation-web/v1/recraft-v3/';\n\n cesdk.ui.addIconSet('@imgly/plugin/formats', Icons.Formats);\n\n imageStyleAssetSource = new CustomAssetSource(\n styleImageAssetSourceId,\n STYLES_IMAGE.map(({ id, label }) => ({\n id,\n label,\n thumbUri: getStyleThumbnail(id, baseURL)\n }))\n );\n vectorStyleAssetSource = new CustomAssetSource(\n styleVectorAssetSourceId,\n STYLES_VECTOR.map(({ id, label }) => ({\n id,\n label,\n thumbUri: getStyleThumbnail(id, baseURL)\n }))\n );\n\n imageStyleAssetSource.setAssetActive('realistic_image');\n vectorStyleAssetSource.setAssetActive('vector_illustration');\n\n cesdk.engine.asset.addSource(imageStyleAssetSource);\n cesdk.engine.asset.addSource(vectorStyleAssetSource);\n\n cesdk.ui.addAssetLibraryEntry({\n id: styleImageAssetSourceId,\n sourceIds: [styleImageAssetSourceId],\n gridItemHeight: 'square',\n gridBackgroundType: 'cover',\n cardLabel: ({ label }) => label,\n cardLabelPosition: () => 'below'\n });\n\n cesdk.ui.addAssetLibraryEntry({\n id: styleVectorAssetSourceId,\n sourceIds: [styleVectorAssetSourceId],\n gridItemHeight: 'square',\n gridBackgroundType: 'cover',\n cardLabel: ({ label }) => label,\n cardLabelPosition: () => 'below'\n });\n\n cesdk.ui.registerPanel<StyleSelectionPayload>(\n `${getPanelId(modelKey)}.styleSelection`,\n ({ builder, payload }) => {\n if (payload == null) return null;\n\n const entries =\n payload.generationType === 'image'\n ? [styleImageAssetSourceId]\n : [styleVectorAssetSourceId];\n\n builder.Library(`${modelKey}.library.style`, {\n entries,\n onSelect: async (asset) => {\n payload.onSelect(asset);\n }\n });\n }\n );\n\n cesdk.i18n.setTranslations({\n en: {\n [`panel.${getPanelId('fal-ai/recraft-v3')}.styleSelection`]:\n 'Style Selection',\n [`${modelKey}.style`]: 'Style',\n [`${modelKey}.style.type`]: 'Type',\n [`${modelKey}.style.type.image`]: 'Image',\n [`${modelKey}.style.type.vector`]: 'Vector'\n }\n });\n\n return createImageProvider(\n {\n modelKey,\n // @ts-ignore\n schema: RecraftV3Schema,\n inputReference: '#/components/schemas/RecraftV3Input',\n middleware: config.middleware ?? [],\n userFlow: 'placeholder',\n renderCustomProperty: {\n style: ({ builder, state }, property) => {\n const typeState = state<GenerationType>('type', 'image');\n\n const styleImageState = state<{\n id: RecraftV3Input['style'];\n label: string;\n }>('style/image', {\n id: 'realistic_image',\n label: 'Realistic Image'\n });\n const styleVectorState = state<{\n id: RecraftV3Input['style'];\n label: string;\n }>('style/vector', {\n id: 'vector_illustration',\n label: 'Vector Illustration'\n });\n\n const styleState =\n typeState.value === 'image' ? styleImageState : styleVectorState;\n\n builder.ButtonGroup(`${property.id}.type`, {\n inputLabel: `${modelKey}.${property.id}.type`,\n children: () => {\n builder.Button(`${property.id}.type.image`, {\n label: `${modelKey}.${property.id}.type.image`,\n isActive: typeState.value === 'image',\n onClick: () => typeState.setValue('image')\n });\n builder.Button(`${property.id}.type.vector`, {\n label: `${modelKey}.${property.id}.type.vector`,\n isActive: typeState.value === 'vector',\n onClick: () => typeState.setValue('vector')\n });\n }\n });\n\n // Show the style library for the selected type.\n builder.Button(`${property.id}`, {\n inputLabel: `${modelKey}.${property.id}`,\n icon: '@imgly/Appearance',\n trailingIcon: '@imgly/ChevronRight',\n label: styleState.value.label,\n labelAlignment: 'left',\n onClick: () => {\n const payload: StyleSelectionPayload = {\n generationType: typeState.value,\n onSelect: async (asset) => {\n if (asset.id === 'back') {\n return;\n }\n\n const newValue: { id: StyleId; label: string } = {\n id: asset.id as StyleId,\n label: asset.label ?? asset.id\n };\n\n if (typeState.value === 'image') {\n imageStyleAssetSource.clearActiveAssets();\n imageStyleAssetSource.setAssetActive(asset.id);\n styleImageState.setValue(newValue);\n } else if (typeState.value === 'vector') {\n vectorStyleAssetSource.clearActiveAssets();\n vectorStyleAssetSource.setAssetActive(asset.id);\n styleVectorState.setValue(newValue);\n }\n\n cesdk.ui.closePanel(`${getPanelId(modelKey)}.styleSelection`);\n }\n };\n\n cesdk.ui.openPanel(`${getPanelId(modelKey)}.styleSelection`, {\n payload\n });\n }\n });\n\n return () => {\n return {\n id: property.id,\n type: 'string',\n value: styleState.value.id ?? 'realistic_image'\n };\n };\n }\n },\n getBlockInput: (input) => {\n if (isCustomImageSize(input.image_size)) {\n return Promise.resolve({\n image: {\n width: input.image_size.width ?? 512,\n height: input.image_size.height ?? 512\n }\n });\n }\n\n const imageDimension = getImageDimensions(\n (input.image_size as string) ?? 'square_hd'\n );\n\n return Promise.resolve({\n image: imageDimension\n });\n }\n },\n config\n );\n}\n\nexport default getProvider;\n", "{\n \"openapi\": \"3.0.0\",\n \"info\": {\n \"title\": \"Fal Queue API\",\n \"version\": \"1.0.0\",\n \"description\": \"The Fal Queue API.\"\n },\n \"components\": {\n \"securitySchemes\": {\n \"apiKeyAuth\": {\n \"type\": \"apiKey\",\n \"in\": \"header\",\n \"name\": \"Authorization\",\n \"description\": \"Fal Key\"\n }\n },\n \"schemas\": {\n \"QueueStatus\": {\n \"type\": \"object\",\n \"properties\": {\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\"IN_QUEUE\", \"IN_PROGRESS\", \"COMPLETED\"]\n },\n \"request_id\": { \"type\": \"string\", \"description\": \"The request id.\" },\n \"response_url\": {\n \"type\": \"string\",\n \"description\": \"The response url.\"\n },\n \"status_url\": { \"type\": \"string\", \"description\": \"The status url.\" },\n \"cancel_url\": { \"type\": \"string\", \"description\": \"The cancel url.\" },\n \"logs\": {\n \"type\": \"object\",\n \"description\": \"The logs.\",\n \"additionalProperties\": true\n },\n \"metrics\": {\n \"type\": \"object\",\n \"description\": \"The metrics.\",\n \"additionalProperties\": true\n },\n \"queue_position\": {\n \"type\": \"integer\",\n \"description\": \"The queue position.\"\n }\n },\n \"required\": [\"status\", \"request_id\"]\n },\n \"GeminiFlashEditInput\": {\n \"title\": \"GeminiImageRequest\",\n \"type\": \"object\",\n \"properties\": {\n \"prompt\": {\n \"maxLength\": 5000,\n \"type\": \"string\",\n \"title\": \"Prompt\",\n \"minLength\": 3,\n \"description\": \"The prompt for image generation or editing\",\n \"x-imgly-builder\": { \"component\": \"TextArea\" }\n },\n \"image_url\": {\n \"title\": \"Image Url\",\n \"type\": \"string\",\n \"description\": \"Optional URL of an input image for editing. If not provided, generates a new image.\"\n }\n },\n \"x-fal-order-properties\": [\"image_url\", \"prompt\"],\n \"required\": [\"prompt\", \"image_url\"]\n },\n \"GeminiFlashEditOutput\": {\n \"title\": \"GeminiImageOutput\",\n \"type\": \"object\",\n \"properties\": {\n \"description\": {\n \"title\": \"Description\",\n \"type\": \"string\",\n \"description\": \"Text description or response from Gemini\"\n },\n \"image\": {\n \"description\": \"The generated or edited image\",\n \"$ref\": \"#/components/schemas/Image\"\n }\n },\n \"x-fal-order-properties\": [\"image\", \"description\"],\n \"required\": [\"image\", \"description\"]\n },\n \"Image\": {\n \"title\": \"Image\",\n \"type\": \"object\",\n \"properties\": {\n \"file_size\": {\n \"anyOf\": [{ \"type\": \"integer\" }, { \"type\": \"null\" }],\n \"title\": \"File Size\",\n \"description\": \"The size of the file in bytes.\"\n },\n \"height\": {\n \"anyOf\": [{ \"type\": \"integer\" }, { \"type\": \"null\" }],\n \"title\": \"Height\",\n \"description\": \"The height of the image in pixels.\"\n },\n \"file_name\": {\n \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }],\n \"title\": \"File Name\",\n \"description\": \"The name of the file. It will be auto-generated if not provided.\"\n },\n \"content_type\": {\n \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }],\n \"title\": \"Content Type\",\n \"description\": \"The mime type of the file.\"\n },\n \"url\": {\n \"title\": \"Url\",\n \"type\": \"string\",\n \"description\": \"The URL where the file can be downloaded from.\"\n },\n \"width\": {\n \"anyOf\": [{ \"type\": \"integer\" }, { \"type\": \"null\" }],\n \"title\": \"Width\",\n \"description\": \"The width of the image in pixels.\"\n }\n },\n \"description\": \"Represents an image file.\",\n \"x-fal-order-properties\": [\n \"url\",\n \"content_type\",\n \"file_name\",\n \"file_size\",\n \"width\",\n \"height\"\n ],\n \"required\": [\"url\"]\n }\n }\n },\n \"paths\": {\n \"/fal-ai/gemini-flash-edit/requests/{request_id}/status\": {\n \"get\": {\n \"parameters\": [\n {\n \"name\": \"request_id\",\n \"in\": \"path\",\n \"required\": true,\n \"schema\": { \"type\": \"string\", \"description\": \"Request ID\" }\n },\n {\n \"name\": \"logs\",\n \"in\": \"query\",\n \"required\": false,\n \"schema\": {\n \"type\": \"number\",\n \"description\": \"Whether to include logs (`1`) in the response or not (`0`).\"\n }\n }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"The request status.\",\n \"content\": {\n \"application/json\": {\n \"schema\": { \"$ref\": \"#/components/schemas/QueueStatus\" }\n }\n }\n }\n }\n }\n },\n \"/fal-ai/gemini-flash-edit/requests/{request_id}/cancel\": {\n \"put\": {\n \"parameters\": [\n {\n \"name\": \"request_id\",\n \"in\": \"path\",\n \"required\": true,\n \"schema\": { \"type\": \"string\", \"description\": \"Request ID\" }\n }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"The request was cancelled.\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"success\": {\n \"type\": \"boolean\",\n \"description\": \"Whether the request was cancelled successfully.\"\n }\n }\n }\n }\n }\n }\n }\n }\n },\n \"/fal-ai/gemini-flash-edit\": {\n \"post\": {\n \"requestBody\": {\n \"required\": true,\n \"content\": {\n \"application/json\": {\n \"schema\": { \"$ref\": \"#/components/schemas/GeminiFlashEditInput\" }\n }\n }\n },\n \"responses\": {\n \"200\": {\n \"description\": \"The request status.\",\n \"content\": {\n \"application/json\": {\n \"schema\": { \"$ref\": \"#/components/schemas/QueueStatus\" }\n }\n }\n }\n }\n }\n },\n \"/fal-ai/gemini-flash-edit/requests/{request_id}\": {\n \"get\": {\n \"parameters\": [\n {\n \"name\": \"request_id\",\n \"in\": \"path\",\n \"required\": true,\n \"schema\": { \"type\": \"string\", \"description\": \"Request ID\" }\n }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"Result of the request.\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"$ref\": \"#/components/schemas/GeminiFlashEditOutput\"\n }\n }\n }\n }\n }\n }\n }\n },\n \"servers\": [{ \"url\": \"https://queue.fal.run\" }],\n \"security\": [{ \"apiKeyAuth\": [] }]\n}\n", "import {\n getQuickActionMenu,\n ImageOutput,\n Middleware,\n QuickAction,\n QuickActionBaseSelect,\n QuickActionSwapImageBackground,\n QuickActionChangeImage,\n QuickActionImageVariant,\n enableQuickActionForImageFill,\n type Provider\n} from '@imgly/plugin-ai-generation-web';\nimport schema from './GeminiFlashEdit.json';\nimport { getImageDimensionsFromURL } from '@imgly/plugin-utils';\nimport CreativeEditorSDK from '@cesdk/cesdk-js';\nimport createImageProvider from './createImageProvider';\n\ntype GeminiFlashEditInput = {\n prompt: string;\n image_url: string;\n};\n\ntype ProviderConfiguration = {\n proxyUrl: string;\n debug?: boolean;\n middleware?: Middleware<GeminiFlashEditInput, ImageOutput>[];\n};\n\nexport function GeminiFlashEdit(\n config: ProviderConfiguration\n): (context: {\n cesdk: CreativeEditorSDK;\n}) => Promise<Provider<'image', GeminiFlashEditInput, ImageOutput>> {\n return async ({ cesdk }: { cesdk: CreativeEditorSDK }) => {\n return getProvider(cesdk, config);\n };\n}\n\nfunction getProvider(\n cesdk: CreativeEditorSDK,\n config: ProviderConfiguration\n): Provider<'image', GeminiFlashEditInput, ImageOutput> {\n const modelKey = 'fal-ai/gemini-flash-edit';\n\n const quickActions = createGeminiFlashEditQuickActions(cesdk);\n const quickActionMenu = getQuickActionMenu(cesdk, 'image');\n\n quickActionMenu.setQuickActionMenuOrder([\n ...quickActionMenu.getQuickActionMenuOrder(),\n 'ly.img.separator',\n 'styleTransfer',\n 'artists',\n 'ly.img.separator',\n 'changeImage',\n 'createVariant'\n ]);\n\n return createImageProvider(\n {\n modelKey,\n name: 'Change Image',\n // @ts-ignore\n schema,\n inputReference: '#/components/schemas/GeminiFlashEditInput',\n cesdk,\n quickActions,\n middleware: config.middleware,\n getBlockInput: async (input) => {\n const { width, height } = await getImageDimensionsFromURL(\n input.image_url,\n cesdk.engine\n );\n return Promise.resolve({\n image: {\n width,\n height\n }\n });\n }\n },\n config\n );\n}\n\nfunction createGeminiFlashEditQuickActions(\n cesdk: CreativeEditorSDK\n): QuickAction<GeminiFlashEditInput, ImageOutput>[] {\n cesdk.i18n.setTranslations({\n en: {\n 'ly.img.ai.quickAction.styleTransfer': 'Change Art Style',\n 'ly.img.ai.quickAction.artists': 'Painted By'\n }\n });\n\n return [\n QuickActionSwapImageBackground<GeminiFlashEditInput, ImageOutput>({\n mapInput: (input) => ({ ...input, image_url: input.uri }),\n cesdk\n }),\n QuickActionChangeImage<GeminiFlashEditInput, ImageOutput>({\n mapInput: (input) => ({ ...input, image_url: input.uri }),\n cesdk\n }),\n QuickActionImageVariant<GeminiFlashEditInput, ImageOutput>({\n onApply: async ({ prompt, uri, duplicatedBlockId }, context) => {\n // Generate a variant for the duplicated block\n return context.generate(\n {\n prompt,\n image_url: uri\n },\n {\n blockIds: [duplicatedBlockId]\n }\n );\n },\n cesdk\n }),\n\n QuickActionBaseSelect<GeminiFlashEditInput, ImageOutput>({\n quickAction: {\n id: 'styleTransfer',\n version: '1',\n enable: enableQuickActionForImageFill(),\n scopes: ['fill/change'],\n confirmation: true,\n lockDuringConfirmation: false\n },\n mapInput: (input) => ({\n prompt: input.item.prompt,\n image_url: input.uri,\n blockId: input.blockId\n }),\n items: [\n {\n id: 'water',\n label: 'Watercolor Painting',\n prompt: 'Convert to watercolor painting.'\n },\n {\n id: 'oil',\n label: 'Oil Painting',\n prompt: 'Render in oil painting style.'\n },\n {\n id: 'charcoal',\n label: 'Charcoal Sketch',\n prompt: 'Transform into a charcoal sketch.'\n },\n {\n id: 'pencil',\n label: 'Pencil Drawing',\n prompt: 'Apply pencil drawing effect.'\n },\n {\n id: 'pastel',\n label: 'Pastel Artwork',\n prompt: 'Make it look like a pastel artwork.'\n },\n {\n id: 'ink',\n label: 'Ink Wash',\n prompt: 'Turn into a classic ink wash painting.'\n },\n {\n id: 'stained-glass',\n label: 'Stained Glass Window',\n prompt: 'Stylize as a stained glass window.'\n },\n {\n id: 'japanse',\n label: 'Japanese Woodblock Print',\n prompt: 'Repaint as a traditional Japanese woodblock print.'\n }\n ],\n cesdk\n }),\n\n QuickActionBaseSelect<GeminiFlashEditInput, ImageOutput>({\n quickAction: {\n id: 'artists',\n version: '1',\n enable: enableQuickActionForImageFill(),\n scopes: ['fill/change'],\n confirmation: true,\n lockDuringConfirmation: false\n },\n mapInput: (input) => ({\n prompt: input.item.prompt,\n image_url: input.uri,\n blockId: input.blockId\n }),\n items: [\n {\n id: 'van-gogh',\n label: 'Van Gogh',\n prompt:\n 'Render this image in the style of Vincent van Gogh, using expressive brushstrokes and swirling motion.'\n },\n {\n id: 'monet',\n label: 'Monet',\n prompt:\n 'Transform this image into the soft, impressionistic style of Claude Monet with natural light and delicate color blending.'\n },\n {\n id: 'picasso',\n label: 'Picasso',\n prompt:\n 'Apply a Pablo Picasso cubist style with abstract geometry and fragmented shapes.'\n },\n {\n id: 'dali',\n label: 'Dal\u00ED',\n prompt:\n \"Make this image resemble Salvador Dal\u00ED's surrealist style, with dreamlike distortion and soft shadows.\"\n },\n {\n id: 'matisse',\n label: 'Matisse',\n prompt:\n \"Stylize the image using Henri Matisse's bold colors and simplified, flowing shapes.\"\n },\n {\n id: 'warhol',\n label: 'Warhol',\n prompt:\n \"Convert this image into Andy Warhol's pop art style with flat colors, repetition, and bold outlines.\"\n },\n {\n id: 'michelangelo',\n label: 'Michelangelo',\n prompt:\n 'Render the image in the classical Renaissance style of Michelangelo, with dramatic anatomy and fresco-like detail.'\n },\n {\n id: 'da-vinci',\n label: 'Da Vinci',\n prompt:\n 'Make this image look like a Leonardo da Vinci painting, using soft transitions, balanced composition, and natural tones.'\n },\n {\n id: 'rembrandt',\n label: 'Rembrandt',\n prompt:\n \"Apply Rembrandt's style with rich contrast, warm tones, and dramatic use of light and shadow.\"\n },\n {\n id: 'mon-drain',\n label: 'Mondrian',\n prompt:\n \"Transform the image into Piet Mondrian's abstract geometric style with grids and primary colors.\"\n },\n {\n id: 'khalo',\n label: 'Frida Kahlo',\n prompt:\n 'Stylize this image in the expressive, symbolic style of Frida Kahlo with vivid colors and surreal framing.'\n },\n {\n id: 'hokusai',\n label: 'Hokusai',\n prompt:\n 'Render the image in the style of Hokusai, using bold outlines, flat color, and traditional Japanese woodblock aesthetics.'\n }\n ],\n cesdk\n })\n ];\n}\n\nexport default getProvider;\n", "import { RecraftV3 } from './RecraftV3';\nimport { GeminiFlashEdit } from './GeminiFlashEdit';\n\nconst FalAi = {\n RecraftV3,\n GeminiFlashEdit\n};\n\nexport default FalAi;\n"],
5
- "mappings": "o8BAyBAA,EAAA,eAAAC,GAqBAD,EAAA,UAAAE,GArBA,SAAgBD,MACXE,EAAgC,CAEnC,IAAMC,EAAaC,GACjB,OAAOA,GAAe,WAExB,OAAcC,GAAyBC,GAAA,KAAA,OAAA,OAAA,WAAA,CACrC,IAAIC,EAAa,OAAA,OAAA,CAAA,EAAQF,CAAM,EAC/B,QAAWD,KAAcF,EAAY,OAAOC,CAAS,EACnDI,EAAgB,MAAMH,EAAWG,CAAa,EAEhD,OAAOA,CACT,CAAC,CACH,CAMaR,EAAA,kBAAoB,mBAEjC,SAAgBE,GAAUI,EAA0B,CAClD,IAAMG,EAAeC,GACnB,QAAQ,QAAQA,CAAa,EAE/B,OAAI,OAAO,OAAW,IACbD,EAGDC,GACNA,EAAc,SAAWV,EAAA,qBAAqBU,EAC1CD,EAAYC,CAAa,EACzB,QAAQ,QAAO,OAAA,OAAA,OAAA,OAAA,CAAA,EACVA,CAAa,EAAA,CAChB,IAAKJ,EAAO,UACZ,QAAO,OAAA,OAAA,OAAA,OAAA,CAAA,EACDI,EAAc,SAAW,CAAA,CAAG,EAAA,CAChC,CAACV,EAAA,iBAAiB,EAAGU,EAAc,GAAG,CAAA,CAAA,CAAA,CAAA,CAGlD,ubCJAC,EAAA,uBAAAC,GA8BAD,EAAA,sBAAAE,GAtFA,IAAMC,GAAoB,mBAabC,GAAb,cAAoC,KAAK,CAGvC,YAAY,CAAE,QAAAC,EAAS,OAAAC,EAAQ,KAAAC,CAAI,EAAgB,CACjD,MAAMF,CAAO,EACb,K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c,CAAE,KAAQ,SAAU,YAAe,iBAAkB,EACnE,KAAQ,CACN,KAAQ,SACR,YAAe,YACf,qBAAwB,EAC1B,EACA,QAAW,CACT,KAAQ,SACR,YAAe,eACf,qBAAwB,EAC1B,EACA,eAAkB,CAChB,KAAQ,UACR,YAAe,qBACjB,CACF,EACA,SAAY,CAAC,SAAU,YAAY,CACrC,EACA,eAAkB,CAChB,MAAS,mBACT,KAAQ,SACR,WAAc,CACZ,OAAU,CACR,MAAS,SACT,KAAQ,SACR,kBAAmB,CACjB,UAAa,UACf,CACF,EACA,WAAc,CACZ,MAAS,CACP,CACE,KAAQ,CACN,YACA,SACA,eACA,gBACA,gBACA,gBACF,EACA,KAAQ,QACV,EACA,CAAE,KAAQ,gCAAiC,CAC7C,EACA,MAAS,SACT,QAAW,YACX,sBAAuB,CACrB,UAAa,SACb,UAAa,YACb,OAAU,SACV,aAAgB,eAChB,cAAiB,gBACjB,cAAiB,gBACjB,eAAkB,gBACpB,EACA,qBAAsB,CACpB,OAAU,kCACV,UAAa,kCACb,aAAgB,kCAChB,cAAiB,mCACjB,cAAiB,kCACjB,eAAkB,mCAClB,UAAa,iCACf,CACF,EACA,MAAS,CACP,KAAQ,CACN,MACA,kBACA,uBACA,sBACA,0BACA,6BACA,sBACA,gCACA,kCACA,6BACA,8BACA,gCACA,kCACA,8BACA,oCACA,gCACA,+BACA,iCACA,gCACA,iCACA,8BACA,kCACA,4BACA,iCACA,kCACA,6BACA,wCACA,qCACA,mCACA,0CACA,uCACA,uCACA,mCACA,oCACA,kCACA,mCACA,6BACA,kCACA,yCACA,qCACA,wCACA,gCACA,yCACA,mCACA,mCACA,mCACA,kCACA,iCACA,4BACA,wCACA,uCACA,uCACA,qCACA,+BACA,uCACA,kCACA,qCACA,kCACA,uCACA,sCACA,wCACA,0CACA,kCACA,gCACA,sCACA,sCACA,8BACA,6BACA,iCACA,gCACA,qCACA,oCACA,qCACA,6BACA,gCACA,oCACA,uCACA,qCACA,2BACA,mCACA,m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AAWA,EAAM,IACjB,QAASA,EAAM,OACjB,GACA,MAAO,CACL,CACE,GAAI,WACJ,MAAO,WACP,OACE,wGACJ,EACA,CACE,GAAI,QACJ,MAAO,QACP,OACE,2HACJ,EACA,CACE,GAAI,UACJ,MAAO,UACP,OACE,kFACJ,EACA,CACE,GAAI,OACJ,MAAO,UACP,OACE,2GACJ,EACA,CACE,GAAI,UACJ,MAAO,UACP,OACE,qFACJ,EACA,CACE,GAAI,SACJ,MAAO,SACP,OACE,sGACJ,EACA,CACE,GAAI,eACJ,MAAO,eACP,OACE,oHACJ,EACA,CACE,GAAI,WACJ,MAAO,WACP,OACE,0HACJ,EACA,CACE,GAAI,YACJ,MAAO,YACP,OACE,+FACJ,EACA,CACE,GAAI,YACJ,MAAO,WACP,OACE,kGACJ,EACA,CACE,GAAI,QACJ,MAAO,cACP,OACE,4GACJ,EACA,CACE,GAAI,UACJ,MAAO,UACP,OACE,2HACJ,CACF,EACA,MAAAT,CACF,CAAC,CACH,CACF,CC1QA,IAAMsB,GAAQ,CACZ,UAAAC,GACA,gBAAAC,EACF,EAEOC,GAAQH",
6
- "names": ["exports", "withMiddleware", "withProxy", "middlewares", "isDefined", "middleware", "config", "__awaiter", "currentConfig", "passthrough", "requestConfig", "exports", "defaultResponseHandler", "resultResponseHandler", "REQUEST_ID_HEADER", "ApiError", "message", "status", "body", "ValidationError", "args", "field", "error", "response", "statusText", "contentType", "_a", "ErrorType", "require_package", "__commonJSMin", "exports", "module", "exports", "isBrowser", "getUserAgent", "memoizedUserAgent", "packageInfo", "exports", "resolveDefaultFetch", "createConfig", "getRestApiUrl", "middleware_1", "response_1", "runtime_1", "hasEnvVariables", "credentialsFromEnv", "DEFAULT_CONFIG", "request", "config", "configuration", "_a", "resolveCredentials", "suppressLocalCredentialsWarning", "credentials", "exports", "ensureEndpointIdFormat", "parseEndpointId", "isValidUrl", "throttle", "isReact", "isPlainObject", "id", "appOwner", "appId", "ENDPOINT_NAMESPACES", "parts", "url", "host", "func", "limit", "leading", "lastFunc", "lastRan", "args", "isRunningInReact", "stack", "value", "exports", "dispatchRequest", "buildUrl", "runtime_1", "utils_1", "isCloudflareWorkers", "params", "targetUrl", "input", "config", "options", "credentialsValue", "requestMiddleware", "responseHandler", "fetch", "userAgent", "credentials", "method", "url", "headers", "_b", "_a", "authHeader", "requestHeaders", "customResponseHandler", "requestInit", "__rest", "response", "_c", "id", "path", "queryParams", "appId", "createParser", "onParse", "isFirstChunk", "buffer", "startingPosition", "startingFieldLength", "eventId", "eventName", "data", "reset", "feed", "chunk", "hasBom", "slice", "BOM", "length", "position", "discardTrailingNewline", "lineLength", "fieldLength", "character", "index", "parseEventStreamLine", "lineBuffer", "type", "id", "event", "noValue", "field", "step", "valueLength", "value", "toString", "concat", "includes", "retry", "parseInt", "Number", "isNaN", "every", "charCode", "charCodeAt", "exports", "getTemporaryAuthToken", "config_1", "request_1", "utils_1", "app", "config", "appId", "token", "exports", "createStreamingClient", "eventsource_parser_1", "auth_1", "request_1", "response_1", "CONTENT_TYPE_EVENT_STREAM", "EVENT_STREAM_TIMEOUT", "FalStream", "endpointId", "config", "options", "__awaiter", "input", "method", "connectionMode", "token", "fetch", "parsedUrl", "response", "_a", "_b", "error", "body", "reader", "emitRawChunk", "done", "value", "decoder", "parser", "event", "data", "parsedData", "e", "timeout", "readPartialResponse", "apiError", "type", "listener", "listeners", "reason", "resolve", "reject", "running", "stopAsyncIterator", "__await", "storage", "request_1", "response_1", "streaming_1", "utils_1", "DEFAULT_POLL_INTERVAL", "createQueueClient", "config", "storage", "ref", "endpointId", "options", "webhookUrl", "priority", "runOptions", "__rest", "input", "endpointId_1", "_a", "requestId", "logs", "abortSignal", "appId", "prefix", "connectionMode", "queryParams", "url", "timeout", "timeoutId", "handleCancelError", "status", "data", "doneStatus", "resolve", "reject", "pollingTimeoutId", "pollInterval", "clearScheduledTasks", "poll", "__awaiter", "requestStatus", "error", "exports", "exports", "utf8Count", "utf8EncodeJs", "utf8EncodeTE", "utf8Encode", "utf8DecodeJs", "utf8DecodeTD", "utf8Decode", "str", "strLength", "byteLength", "pos", "value", "extra", "output", "outputOffset", "offset", "sharedTextEncoder", "TEXT_ENCODER_THRESHOLD", "CHUNK_SIZE", "bytes", "inputOffset", "end", "units", "result", "byte1", "byte2", "byte3", "byte4", "unit", "sharedTextDecoder", "TEXT_DECODER_THRESHOLD", "stringBytes", "ExtData", "type", "data", "exports", "DecodeError", "_DecodeError", "message", "proto", "exports", "exports", "setUint64", "setInt64", "getInt64", "getUint64", "view", "offset", "value", "high", "low", "exports", "encodeTimeSpecToTimestamp", "encodeDateToTimeSpec", "encodeTimestampExtension", "decodeTimestampToTimeSpec", "decodeTimestampExtension", "DecodeError_ts_1", "int_ts_1", "TIMESTAMP32_MAX_SEC", "TIMESTAMP64_MAX_SEC", "sec", "nsec", "rv", "secHigh", "secLow", "view", "date", "msec", "nsecInSec", "object", "timeSpec", "data", "nsec30AndSecHigh2", "secLow32", "ExtData_ts_1", "timestamp_ts_1", "ExtensionCodec", "type", "encode", "decode", "index", "object", "context", "i", "encodeExt", "data", "decodeExt", "exports", "exports", "ensureUint8Array", "isArrayBufferLike", "buffer", "utf8_ts_1", "ExtensionCodec_ts_1", "int_ts_1", "typedArrays_ts_1", "exports", "Encoder", "_Encoder", "options", "object", "depth", "sizeToWrite", "requiredSize", "newSize", "newBuffer", "newBytes", "newView", "byteLength", "ext", "size", "bytes", "item", "keys", "count", "key", "value", "data", "values", "exports", "encode", "Encoder_ts_1", "value", "options", "exports", "prettyByte", "byte", "utf8_ts_1", "DEFAULT_MAX_KEY_LENGTH", "DEFAULT_MAX_LENGTH_PER_KEY", "CachedKeyDecoder", "maxKeyLength", "maxLengthPerKey", "i", "byteLength", "bytes", "inputOffset", "records", "FIND_CHUNK", "record", "recordBytes", "j", "value", "cachedValue", "str", "slicedCopyOfBytes", "exports", "prettyByte_ts_1", "ExtensionCodec_ts_1", "int_ts_1", "utf8_ts_1", "typedArrays_ts_1", "CachedKeyDecoder_ts_1", "DecodeError_ts_1", "STATE_ARRAY", "STATE_MAP_KEY", "STATE_MAP_VALUE", "mapKeyConverter", "key", "StackPool", "size", "state", "partialState", "HEAD_BYTE_REQUIRED", "EMPTY_VIEW", "EMPTY_BYTES", "MORE_DATA", "sharedCachedKeyDecoder", "Decoder", "_Decoder", "options", "buffer", "bytes", "remainingData", "newData", "newBuffer", "posToShow", "view", "pos", "object", "stream", "decoded", "e", "headByte", "totalPos", "isArray", "isArrayHeaderRequired", "arrayItemsLeft", "DECODE", "byteLength", "stack", "headerOffset", "offset", "headOffset", "extType", "data", "value", "exports", "exports", "decode", "decodeMulti", "Decoder_ts_1", "buffer", "options", "exports", "isAsyncIterable", "asyncIterableFromStream", "ensureAsyncIterable", "object", "stream", "reader", "done", "value", "streamLike", "exports", "decodeAsync", "decodeArrayStream", "decodeMultiStream", "Decoder_ts_1", "stream_ts_1", "streamLike", "options", "stream", "encode_ts_1", "exports", "decode_ts_1", "decodeAsync_ts_1", "Decoder_ts_1", "DecodeError_ts_1", "Encoder_ts_1", "ExtensionCodec_ts_1", "ExtData_ts_1", "timestamp_ts_1", "require_machine", "__commonJSMin", "exports", "valueEnumerable", "value", "valueEnumerableWritable", "d", "truthy", "empty", "identity", "a", "callBoth", "par", "fn", "self", "args", "callForward", "b", "create", "stack", "fns", "def", "caller", "fnType", "reduceType", "reduce", "action", "ctx", "ev", "guardType", "guard", "filter", "Type", "arr", "makeTransition", "from", "to", "guards", "t", "reducers", "transitionType", "immediateType", "transition", "immediate", "enterImmediate", "machine", "service", "event", "transitionTo", "transitionsToMap", "transitions", "m", "stateType", "state", "immediates", "desc", "invokeFnType", "machine2", "rn", "invokeMachineType", "data", "error", "interpret", "s", "invoke", "createMachine", "current", "states", "contextFn", "fromEvent", "candidates", "context", "original", "newMachine", "send", "eventName", "currentStateName", "onChange", "initialContext", "exports", "createRealtimeClient", "msgpack_1", "robot3_1", "auth_1", "response_1", "runtime_1", "utils_1", "initialState", "hasToken", "context", "noToken", "enqueueMessage", "event", "closeConnection", "sendMessage", "expireToken", "setToken", "connectionEstablished", "connectionStateMachine", "buildRealtimeUrl", "app", "token", "maxBuffering", "queryParams", "DEFAULT_THROTTLE_INTERVAL", "isUnauthorizedError", "message", "WebSocketErrorCodes", "connectionCache", "connectionCallbacks", "reuseInterpreter", "key", "throttleInterval", "onChange", "machine", "noop", "NoOpConnection", "isSuccessfulResult", "data", "isFalErrorResult", "config", "handler", "clientOnly", "connectionKey", "previousState", "getCallbacks", "stateMachine", "send", "enqueuedMessage", "tokenExpirationTimeout", "error", "ws", "onError", "onResult", "result", "buffer", "input", "exports", "createStorageClient", "config_1", "request_1", "utils_1", "getExtensionFromContentType", "contentType", "_", "fileType", "_a", "initiateUpload", "file", "config", "filename", "initiateMultipartUpload", "partUploadRetries", "uploadUrl_1", "chunk_1", "config_2", "uploadUrl", "chunk", "tries", "fetch", "responseHandler", "response", "multipartUpload", "url", "chunkSize", "chunks", "parsedUrl", "responses", "i", "start", "end", "partNumber", "partUploadUrl", "completeUrl", "mpart", "ref", "__awaiter", "input", "item", "promises", "key", "value", "results", "exports", "createFalClient", "config_1", "queue_1", "realtime_1", "request_1", "response_1", "storage_1", "streaming_1", "userConfig", "config", "storage", "queue", "streaming", "realtime", "endpointId_1", "endpointId", "options", "input", "__awaiter", "requestId", "exports", "isQueueStatus", "isCompletedQueueStatus", "obj", "client_1", "client_2", "exports", "middleware_1", "response_1", "__exportStar", "utils_1", "currentInstance", "config", "id", "options", "endpointId", "formats_default", "CustomAssetSource", "id", "assets", "asset", "selectValue", "queryData", "page", "perPage", "locale", "sortActiveFirst", "query", "tags", "groups", "excludeGroups", "sortingOrder", "sortKey", "filteredAssets", "group", "lowerQuery", "label", "assetTags", "tag", "tagArray", "a", "b", "aActive", "bActive", "aValue", "bValue", "total", "startIndex", "endIndex", "resultAssets", "nextPage", "assetId", "assetIds", "existingIndex", "index", "freeGlobal", "freeGlobal_default", "freeSelf", "root", "root_default", "Symbol", "Symbol_default", "objectProto", "hasOwnProperty", "nativeObjectToString", "symToStringTag", "getRawTag", "value", "isOwn", "tag", "unmasked", "result", "getRawTag_default", "objectToString", "objectToString_default", "nullTag", "undefinedTag", "baseGetTag", "baseGetTag_default", "isObjectLike", "isObjectLike_default", "isArray", "isObject", "value", "type", "isObject_default", "asyncTag", "funcTag", "genTag", "proxyTag", "isFunction", "tag", "baseGetTag_default", "isFunction_default", "coreJsData", "root_default", "coreJsData_default", "maskSrcKey", "uid", "isMasked", "func", "isMasked_default", "funcProto", "funcToString", "toSource", "toSource_default", "reRegExpChar", "reIsHostCtor", "objectProto", "hasOwnProperty", "reIsNative", "baseIsNative", "pattern", "baseIsNative_default", "getValue", "object", "key", "getValue_default", "getNative", "getNative_default", "WeakMap", "WeakMap_default", "eq", "value", "other", "eq_default", "MAX_SAFE_INTEGER", "isLength", "isLength_default", "objectProto", "argsTag", "baseIsArguments", "value", "isObjectLike_default", "baseGetTag_default", "baseIsArguments_default", "objectProto", "hasOwnProperty", "propertyIsEnumerable", "isArguments", "freeExports", "freeModule", "moduleExports", "Buffer", "root_default", "nativeIsBuffer", "argsTag", "arrayTag", "boolTag", "dateTag", "errorTag", "funcTag", "mapTag", "numberTag", "objectTag", "regexpTag", "setTag", "stringTag", "weakMapTag", "arrayBufferTag", "dataViewTag", "float32Tag", "float64Tag", "int8Tag", "int16Tag", "int32Tag", "uint8Tag", "uint8ClampedTag", "uint16Tag", "uint32Tag", "typedArrayTags", "baseIsTypedArray", "value", "isObjectLike_default", "isLength_default", "baseGetTag_default", "baseIsTypedArray_default", "baseUnary", "func", "baseUnary_default", "freeExports", "freeModule", "moduleExports", "freeProcess", "freeGlobal_default", "nodeUtil", "types", "nodeUtil_default", "nodeIsTypedArray", "isTypedArray", "objectProto", "hasOwnProperty", "overArg", "func", "transform", "arg", "overArg_default", "nativeKeys", "objectProto", "hasOwnProperty", "nativeCreate", "getNative_default", "nativeCreate_default", "hashClear", "hashClear_default", "hashDelete", "key", "result", "hashDelete_default", "HASH_UNDEFINED", "objectProto", "hasOwnProperty", "hashGet", "data", "hashGet_default", "hashHas", "hashHas_default", "hashSet", "value", "hashSet_default", "Hash", "entries", "index", "length", "entry", "Hash_default", "listCacheClear", "listCacheClear_default", "assocIndexOf", "array", "eq_default", "assocIndexOf_default", "arrayProto", "splice", "listCacheDelete", "lastIndex", "listCacheDelete_default", "listCacheGet", "listCacheGet_default", "listCacheHas", "listCacheHas_default", "listCacheSet", "listCacheSet_default", "ListCache", "ListCache_default", "Map", "root_default", "Map_default", "mapCacheClear", "mapCacheClear_default", "isKeyable", "type", "isKeyable_default", "getMapData", "map", "getMapData_default", "mapCacheDelete", "mapCacheDelete_default", "mapCacheGet", "mapCacheGet_default", "mapCacheHas", "mapCacheHas_default", "mapCacheSet", "size", "mapCacheSet_default", "MapCache", "MapCache_default", "stackClear", "ListCache_default", "stackClear_default", "stackDelete", "key", "data", "result", "stackDelete_default", "stackGet", "stackGet_default", "stackHas", "stackHas_default", "LARGE_ARRAY_SIZE", "stackSet", "value", "pairs", "Map_default", "MapCache_default", "stackSet_default", "Stack", "entries", "objectProto", "propertyIsEnumerable", "DataView", "getNative_default", "root_default", "DataView_default", "Promise", "Promise_default", "Set", "Set_default", "mapTag", "objectTag", "promiseTag", "setTag", "weakMapTag", "dataViewTag", "dataViewCtorString", "toSource_default", "mapCtorString", "Map_default", "promiseCtorString", "setCtorString", "weakMapCtorString", "WeakMap_default", "getTag", "baseGetTag_default", "value", "result", "Ctor", "ctorString", "Uint8Array", "root_default", "HASH_UNDEFINED", "setCacheAdd", "value", "setCacheAdd_default", "setCacheHas", "setCacheHas_default", "SetCache", "values", "index", "length", "MapCache_default", "symbolProto", "Symbol_default", "symbolValueOf", "objectProto", "hasOwnProperty", "objectProto", "hasOwnProperty", "HEX_COLOR_PATTERN", "HEX_SINGLE_CHAR_COMPONENTS_PATTERN", "HEX_DOUBLE_CHAR_COMPONENTS_PATTERN", "mimeTypeToExtension", "mimeType", "bufferURIToObjectURL", "uri", "engine", "mimeType", "length", "data", "blob", "getImageDimensionsFromURL", "url", "engine", "resolvedUrl", "bufferURIToObjectURL", "resolve", "reject", "img", "Icons", "formats_default", "renderImageUrlProperty", "provderId", "options", "cesdk", "propertyKey", "createPanels", "context", "property", "builder", "global", "payload", "defaultUrl", "stateValue", "panelId", "getImageSelectionPanelId", "assetResult", "providerId", "asset", "uri", "mimeType", "renderImageUrlProperty_default", "AI_PANEL_ID_PREFIX", "getPanelId", "providerId", "AI_PANEL_ID_PREFIX", "loggingMiddleware", "input", "options", "next", "result", "start", "loggingMiddleware_default", "freeGlobal", "freeGlobal_default", "freeSelf", "root", "root_default", "Symbol", "Symbol_default", "objectProto", "hasOwnProperty", "nativeObjectToString", "symToStringTag", "getRawTag", "value", "isOwn", "tag", "unmasked", "result", "getRawTag_default", "objectToString", "objectToString_default", "nullTag", "undefinedTag", "baseGetTag", "baseGetTag_default", "isObjectLike", "isObjectLike_default", "isArray", "isObject", "type", "isObject_default", "asyncTag", "funcTag", "genTag", "proxyTag", "isFunction", "isFunction_default", "coreJsData", "coreJsData_default", "maskSrcKey", "uid", "isMasked", "func", "isMasked_default", "funcProto", "funcToString", "toSource", "toSource_default", "reRegExpChar", "reIsHostCtor", "reIsNative", "baseIsNative", "pattern", "baseIsNative_default", "getValue", "object", "key", "getValue_default", "getNative", "getNative_default", "WeakMap", "WeakMap_default", "eq", "other", "eq_default", "MAX_SAFE_INTEGER", "isLength", "isLength_default", "argsTag", "baseIsArguments", "baseIsArguments_default", "propertyIsEnumerable", "isArguments", "freeExports", "freeModule", "moduleExports", "Buffer", "nativeIsBuffer", "arrayTag", "boolTag", "dateTag", "errorTag", "mapTag", "numberTag", "objectTag", "regexpTag", "setTag", "stringTag", "weakMapTag", "arrayBufferTag", "dataViewTag", "float32Tag", "float64Tag", "int8Tag", "int16Tag", "int32Tag", "uint8Tag", "uint8ClampedTag", "uint16Tag", "uint32Tag", "typedArrayTags", "baseIsTypedArray", "baseIsTypedArray_default", "baseUnary", "baseUnary_default", "freeProcess", "nodeUtil", "types", "nodeUtil_default", "nodeIsTypedArray", "isTypedArray", "overArg", "transform", "arg", "overArg_default", "nativeKeys", "nativeCreate", "nativeCreate_default", "hashClear", "hashClear_default", "hashDelete", "hashDelete_default", "HASH_UNDEFINED", "hashGet", "data", "hashGet_default", "hashHas", "hashHas_default", "hashSet", "hashSet_default", "Hash", "entries", "index", "length", "entry", "Hash_default", "listCacheClear", "listCacheClear_default", "assocIndexOf", "array", "assocIndexOf_default", "arrayProto", "splice", "listCacheDelete", "lastIndex", "listCacheDelete_default", "listCacheGet", "listCacheGet_default", "listCacheHas", "listCacheHas_default", "listCacheSet", "listCacheSet_default", "ListCache", "ListCache_default", "Map", "Map_default", "mapCacheClear", "mapCacheClear_default", "isKeyable", "isKeyable_default", "getMapData", "map", "getMapData_default", "mapCacheDelete", "mapCacheDelete_default", "mapCacheGet", "mapCacheGet_default", "mapCacheHas", "mapCacheHas_default", "mapCacheSet", "size", "mapCacheSet_default", "MapCache", "MapCache_default", "stackClear", "stackClear_default", "stackDelete", "stackDelete_default", "stackGet", "stackGet_default", "stackHas", "stackHas_default", "LARGE_ARRAY_SIZE", "stackSet", "pairs", "stackSet_default", "Stack", "DataView", "DataView_default", "Promise", "Promise_default", "Set", "Set_default", "promiseTag", "dataViewCtorString", "mapCtorString", "promiseCtorString", "setCtorString", "weakMapCtorString", "getTag", "Ctor", "ctorString", "Uint8Array", "setCacheAdd", "setCacheAdd_default", "setCacheHas", "setCacheHas_default", "SetCache", "values", "symbolProto", "symbolValueOf", "HEX_COLOR_PATTERN", "HEX_SINGLE_CHAR_COMPONENTS_PATTERN", "HEX_DOUBLE_CHAR_COMPONENTS_PATTERN", "bufferURIToObjectURL", "uri", "engine", "mimeType", "length", "data", "blob", "getImageUri", "blockId", "engine", "options", "uri", "fillBlock", "sourceSet", "source", "bufferURIToObjectURL", "PLUGIN_ICON_SET_ID", "ICON_SPRITE", "QUICK_ACTION_ORDER_KEY_PREFIX", "QUICK_ACTION_REGISTRY_PREFIX", "getQuickActionMenu", "cesdk", "id", "quickActionIds", "quickAction", "entries", "quickActionId", "getQuickActionMenu_default", "QuickActionBasePrompt", "options", "id", "builder", "toggleExpand", "state", "experimental", "context", "promptState", "prompt", "error", "QuickActionBasePrompt_default", "QuickActionBaseSelect", "options", "id", "builder", "experimental", "context", "item", "generate", "closeMenu", "handleGenerationError", "blockId", "uri", "Qs", "input", "error", "QuickActionBaseSelect_default", "enableImageFill", "engine", "blockIds", "blockId", "fillBlock", "enableImageFill_default", "QuickActionChangeImage", "options", "id", "QuickActionBasePrompt_default", "prompt", "context", "uri", "Qs", "input", "QuickActionChangeImage_default", "QuickActionImageVariant", "parent", "duplicated", "offsetFactor", "parentWidth", "parentHeight", "offset", "QuickActionImageVariant_default", "userPrompt", "QuickActionSwapImageBackground_default", "CommonProperties", "renderImageUrlProperty_default", "RecraftV3_default", "ImageSizeEnumToSize", "getImageDimensions", "id", "STYLES_IMAGE", "STYLE_IMAGE_DEFAULT", "STYLES_VECTOR", "STYLE_VECTOR_DEFAULT", "STYLE_THUMBNAILS", "baseURL", "getStyleThumbnail", "import_client", "import_client", "isCustomImageSize", "imageSize", "uploadImageInputToFalIfNeeded", "imageUrl", "cesdk", "mimeType", "imageUrlBlob", "imageUrlFile", "gr", "length", "data", "createImageProvider", "options", "config", "middleware", "U", "provider", "context", "cl", "input", "width", "height", "isCustomImageSize", "imageDimension", "getImageDimensions", "abortSignal", "image_url", "uploadImageInputToFalIfNeeded", "response", "images", "url", "image", "createImageProvider_default", "imageStyleAssetSource", "vectorStyleAssetSource", "RecraftV3", "config", "cesdk", "getProvider", "modelKey", "styleImageAssetSourceId", "styleVectorAssetSourceId", "baseURL", "Ru", "ye", "STYLES_IMAGE", "id", "label", "getStyleThumbnail", "STYLES_VECTOR", "_", "builder", "payload", "entries", "asset", "createImageProvider_default", "RecraftV3_default", "state", "property", "typeState", "styleImageState", "styleVectorState", "styleState", "newValue", "input", "isCustomImageSize", "imageDimension", "getImageDimensions", "GeminiFlashEdit_default", "GeminiFlashEdit", "config", "cesdk", "getProvider", "modelKey", "quickActions", "createGeminiFlashEditQuickActions", "quickActionMenu", "De", "createImageProvider_default", "GeminiFlashEdit_default", "input", "width", "height", "ks", "Ho", "Qo", "zo", "prompt", "uri", "duplicatedBlockId", "context", "Fo", "L", "FalAi", "RecraftV3", "GeminiFlashEdit", "fal_ai_default"]
3
+ "sources": ["../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/middleware.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/response.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/node_modules/@fal-ai/client/package.json", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/runtime.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/config.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/utils.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/request.ts", "../../../../node_modules/.pnpm/eventsource-parser@1.1.2/node_modules/eventsource-parser/src/parse.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/auth.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/streaming.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/queue.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/utils/utf8.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/ExtData.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/DecodeError.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/utils/int.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/timestamp.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/ExtensionCodec.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/utils/typedArrays.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/Encoder.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/encode.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/utils/prettyByte.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/CachedKeyDecoder.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/Decoder.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/decode.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/utils/stream.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/decodeAsync.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.1/node_modules/@msgpack/msgpack/src/index.ts", "../../../../node_modules/.pnpm/robot3@0.4.1/node_modules/robot3/dist/machine.js", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/realtime.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/storage.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/client.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/types/common.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.3.0/libs/client/src/index.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/icons/formats.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/assetSources/CustomAssetSource.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/assetSources/IndexedDBAssetSource.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/assetSources/AggregatedAssetSource.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/metadata/Metadata.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_freeGlobal.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_root.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Symbol.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getRawTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_objectToString.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGetTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isObjectLike.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isObject.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isFunction.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_coreJsData.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isMasked.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_toSource.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsNative.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getValue.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getNative.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_WeakMap.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isIndex.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/eq.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isLength.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArrayLike.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isPrototype.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseTimes.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsArguments.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArguments.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/stubFalse.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isBuffer.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsTypedArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseUnary.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nodeUtil.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isTypedArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayLikeKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_overArg.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/keys.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeCreate.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Hash.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_assocIndexOf.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_ListCache.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Map.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isKeyable.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getMapData.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_MapCache.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayPush.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Stack.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayFilter.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/stubArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getSymbols.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGetAllKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getAllKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_DataView.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Promise.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Set.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Uint8Array.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setCacheAdd.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setCacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_SetCache.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arraySome.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalArrays.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapToArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setToArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalByTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalObjects.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsEqualDeep.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsEqual.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isEqual.js", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/metadata/FillProcessingMetadata.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/fillProcessing.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/constants.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/initializeFillProcessing.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/registerFillProcessingComponents.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/colors.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/upload.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/uuid.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/images.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/isDefined.ts", "../../../../node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/index.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/common/renderImageUrlProperty.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/openapi/dereferenceDocument.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/openapi/isOpenAPISchema.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/openapi/getProperties.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/utils.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/openapi/renderProperty.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/previewUri.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/getAssetResultForPlaceholder.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/getAssetResultForGenerated.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/middleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/loggingMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/icons/formats.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/assetSources/CustomAssetSource.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/assetSources/IndexedDBAssetSource.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/assetSources/AggregatedAssetSource.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/metadata/Metadata.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_freeGlobal.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_root.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Symbol.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getRawTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_objectToString.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGetTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isObjectLike.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isObject.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isFunction.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_coreJsData.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isMasked.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_toSource.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsNative.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getValue.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getNative.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_WeakMap.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isIndex.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/eq.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isLength.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArrayLike.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isPrototype.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseTimes.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsArguments.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isArguments.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/stubFalse.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isBuffer.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsTypedArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseUnary.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nodeUtil.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isTypedArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayLikeKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_overArg.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/keys.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_nativeCreate.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_hashSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Hash.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_assocIndexOf.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_listCacheSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_ListCache.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Map.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_isKeyable.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getMapData.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapCacheSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_MapCache.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayPush.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackClear.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackDelete.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackGet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_stackSet.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Stack.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arrayFilter.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/stubArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getSymbols.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGetAllKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getAllKeys.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_DataView.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Promise.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Set.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_getTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_Uint8Array.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setCacheAdd.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setCacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_SetCache.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_arraySome.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_cacheHas.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalArrays.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_mapToArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_setToArray.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalByTag.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_equalObjects.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsEqualDeep.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseIsEqual.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isEqual.js", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/metadata/FillProcessingMetadata.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/fillProcessing.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/constants.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/initializeFillProcessing.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/processing/registerFillProcessingComponents.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/colors.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/upload.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/uuid.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/images.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/utils/isDefined.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/node_modules/.pnpm/@imgly+plugin-utils@file+packages+plugin-utils_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-utils/src/index.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/dryRunMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/generate.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/handleGenerationError.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/renderGenerationComponents.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/registerPanelInputSchema.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/registerPanelInputCustom.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/icons.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/getQuickActionMenu.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/utils.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/highlightBlocksMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/pendingMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/lockMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/consumeGeneratedResult.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/editModeMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/generate.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/registerQuickActionMenuComponent.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/initProvider.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/uploadMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/middleware/rateLimitMiddleware.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/registerDockComponent.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionBasePrompt.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionBaseButton.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionBaseSelect.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionBaseLibrary.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionEditTextStyle.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/enableImageFill.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionChangeImage.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionImageVariant.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionCombineImages.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/generation/quickAction/common/QuickActionSwapImageBackground.ts", "../../../../node_modules/.pnpm/@imgly+plugin-ai-generation-web@file+packages+plugin-ai-generation-web_@cesdk+cesdk-js@1.49.1_react@18.3.1_/node_modules/@imgly/plugin-ai-generation-web/src/index.ts", "../../src/fal-ai/RecraftV3.json", "../../src/fal-ai/RecraftV3.constants.ts", "../../src/fal-ai/createImageProvider.ts", "../../src/fal-ai/utils.ts", "../../src/fal-ai/RecraftV3.ts", "../../src/fal-ai/GeminiFlashEdit.json", "../../src/fal-ai/GeminiFlashEdit.ts", "../../src/fal-ai/index.ts"],
4
+ "sourcesContent": ["/**\n * A request configuration object.\n *\n * **Note:** This is a simplified version of the `RequestConfig` type from the\n * `fetch` API. It contains only the properties that are relevant for the\n * fal client. It also works around the fact that the `fetch` API `Request`\n * does not support mutability, its clone method has critical limitations\n * to our use case.\n */\nexport type RequestConfig = {\n url: string;\n method: string;\n headers?: Record<string, string | string[]>;\n};\n\nexport type RequestMiddleware = (\n request: RequestConfig,\n) => Promise<RequestConfig>;\n\n/**\n * Setup a execution chain of middleware functions.\n *\n * @param middlewares one or more middleware functions.\n * @returns a middleware function that executes the given middlewares in order.\n */\nexport function withMiddleware(\n ...middlewares: RequestMiddleware[]\n): RequestMiddleware {\n const isDefined = (middleware: RequestMiddleware): boolean =>\n typeof middleware === \"function\";\n\n return async (config: RequestConfig) => {\n let currentConfig = { ...config };\n for (const middleware of middlewares.filter(isDefined)) {\n currentConfig = await middleware(currentConfig);\n }\n return currentConfig;\n };\n}\n\nexport type RequestProxyConfig = {\n targetUrl: string;\n};\n\nexport const TARGET_URL_HEADER = \"x-fal-target-url\";\n\nexport function withProxy(config: RequestProxyConfig): RequestMiddleware {\n const passthrough = (requestConfig: RequestConfig) =>\n Promise.resolve(requestConfig);\n // when running on the server, we don't need to proxy the request\n if (typeof window === \"undefined\") {\n return passthrough;\n }\n // if x-fal-target-url is already set, we skip it\n return (requestConfig) =>\n requestConfig.headers && TARGET_URL_HEADER in requestConfig\n ? passthrough(requestConfig)\n : Promise.resolve({\n ...requestConfig,\n url: config.targetUrl,\n headers: {\n ...(requestConfig.headers || {}),\n [TARGET_URL_HEADER]: requestConfig.url,\n },\n });\n}\n", "import { RequiredConfig } from \"./config\";\nimport { Result, ValidationErrorInfo } from \"./types/common\";\n\nexport type ResponseHandler<Output> = (response: Response) => Promise<Output>;\n\nconst REQUEST_ID_HEADER = \"x-fal-request-id\";\n\nexport type ResponseHandlerCreator<Output> = (\n config: RequiredConfig,\n) => ResponseHandler<Output>;\n\ntype ApiErrorArgs = {\n message: string;\n status: number;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n body?: any;\n};\n\nexport class ApiError<Body> extends Error {\n public readonly status: number;\n public readonly body: Body;\n constructor({ message, status, body }: ApiErrorArgs) {\n super(message);\n this.name = \"ApiError\";\n this.status = status;\n this.body = body;\n }\n}\n\ntype ValidationErrorBody = {\n detail: ValidationErrorInfo[];\n};\n\nexport class ValidationError extends ApiError<ValidationErrorBody> {\n constructor(args: ApiErrorArgs) {\n super(args);\n this.name = \"ValidationError\";\n }\n\n get fieldErrors(): ValidationErrorInfo[] {\n // NOTE: this is a hack to support both FastAPI/Pydantic errors\n // and some custom 422 errors that might not be in the Pydantic format.\n if (typeof this.body.detail === \"string\") {\n return [\n {\n loc: [\"body\"],\n msg: this.body.detail,\n type: \"value_error\",\n },\n ];\n }\n return this.body.detail || [];\n }\n\n getFieldErrors(field: string): ValidationErrorInfo[] {\n return this.fieldErrors.filter(\n (error) => error.loc[error.loc.length - 1] === field,\n );\n }\n}\n\nexport async function defaultResponseHandler<Output>(\n response: Response,\n): Promise<Output> {\n const { status, statusText } = response;\n const contentType = response.headers.get(\"Content-Type\") ?? \"\";\n if (!response.ok) {\n if (contentType.includes(\"application/json\")) {\n const body = await response.json();\n const ErrorType = status === 422 ? ValidationError : ApiError;\n throw new ErrorType({\n message: body.message || statusText,\n status,\n body,\n });\n }\n throw new ApiError({ message: `HTTP ${status}: ${statusText}`, status });\n }\n if (contentType.includes(\"application/json\")) {\n return response.json() as Promise<Output>;\n }\n if (contentType.includes(\"text/html\")) {\n return response.text() as Promise<Output>;\n }\n if (contentType.includes(\"application/octet-stream\")) {\n return response.arrayBuffer() as Promise<Output>;\n }\n // TODO convert to either number or bool automatically\n return response.text() as Promise<Output>;\n}\n\nexport async function resultResponseHandler<Output>(\n response: Response,\n): Promise<Result<Output>> {\n const data = await defaultResponseHandler<Output>(response);\n return {\n data,\n requestId: response.headers.get(REQUEST_ID_HEADER) || \"\",\n } satisfies Result<Output>;\n}\n", "{\n \"name\": \"@fal-ai/client\",\n \"description\": \"The fal.ai client for JavaScript and TypeScript\",\n \"version\": \"1.3.0\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/fal-ai/fal-js.git\",\n \"directory\": \"libs/client\"\n },\n \"keywords\": [\n \"fal\",\n \"client\",\n \"ai\",\n \"ml\",\n \"typescript\"\n ],\n \"exports\": {\n \".\": \"./src/index.js\",\n \"./endpoints\": \"./src/types/endpoints.js\"\n },\n \"typesVersions\": {\n \"*\": {\n \"endpoints\": [\n \"src/types/endpoints.d.ts\"\n ]\n }\n },\n \"main\": \"./src/index.js\",\n \"types\": \"./src/index.d.ts\",\n \"dependencies\": {\n \"@msgpack/msgpack\": \"^3.0.0-beta2\",\n \"eventsource-parser\": \"^1.1.2\",\n \"robot3\": \"^0.4.1\"\n },\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"type\": \"commonjs\"\n}\n", "/* eslint-disable @typescript-eslint/no-var-requires */\n\nexport function isBrowser(): boolean {\n return (\n typeof window !== \"undefined\" && typeof window.document !== \"undefined\"\n );\n}\n\nlet memoizedUserAgent: string | null = null;\n\nexport function getUserAgent(): string {\n if (memoizedUserAgent !== null) {\n return memoizedUserAgent;\n }\n const packageInfo = require(\"../package.json\");\n memoizedUserAgent = `${packageInfo.name}/${packageInfo.version}`;\n return memoizedUserAgent;\n}\n", "import {\n withMiddleware,\n withProxy,\n type RequestMiddleware,\n} from \"./middleware\";\nimport type { ResponseHandler } from \"./response\";\nimport { defaultResponseHandler } from \"./response\";\nimport { isBrowser } from \"./runtime\";\n\nexport type CredentialsResolver = () => string | undefined;\n\ntype FetchType = typeof fetch;\n\nexport function resolveDefaultFetch(): FetchType {\n if (typeof fetch === \"undefined\") {\n throw new Error(\n \"Your environment does not support fetch. Please provide your own fetch implementation.\",\n );\n }\n return fetch;\n}\n\nexport type Config = {\n /**\n * The credentials to use for the fal client. When using the\n * client in the browser, it's recommended to use a proxy server to avoid\n * exposing the credentials in the client's environment.\n *\n * By default it tries to use the `FAL_KEY` environment variable, when\n * `process.env` is defined.\n *\n * @see https://fal.ai/docs/model-endpoints/server-side\n * @see #suppressLocalCredentialsWarning\n */\n credentials?: undefined | string | CredentialsResolver;\n /**\n * Suppresses the warning when the fal credentials are exposed in the\n * browser's environment. Make sure you understand the security implications\n * before enabling this option.\n */\n suppressLocalCredentialsWarning?: boolean;\n /**\n * The URL of the proxy server to use for the client requests. The proxy\n * server should forward the requests to the fal api.\n */\n proxyUrl?: string;\n /**\n * The request middleware to use for the client requests. By default it\n * doesn't apply any middleware.\n */\n requestMiddleware?: RequestMiddleware;\n /**\n * The response handler to use for the client requests. By default it uses\n * a built-in response handler that returns the JSON response.\n */\n responseHandler?: ResponseHandler<any>;\n /**\n * The fetch implementation to use for the client requests. By default it uses\n * the global `fetch` function.\n */\n fetch?: FetchType;\n};\n\nexport type RequiredConfig = Required<Config>;\n\n/**\n * Checks if the required FAL environment variables are set.\n *\n * @returns `true` if the required environment variables are set,\n * `false` otherwise.\n */\nfunction hasEnvVariables(): boolean {\n return (\n typeof process !== \"undefined\" &&\n process.env &&\n (typeof process.env.FAL_KEY !== \"undefined\" ||\n (typeof process.env.FAL_KEY_ID !== \"undefined\" &&\n typeof process.env.FAL_KEY_SECRET !== \"undefined\"))\n );\n}\n\nexport const credentialsFromEnv: CredentialsResolver = () => {\n if (!hasEnvVariables()) {\n return undefined;\n }\n\n if (typeof process.env.FAL_KEY !== \"undefined\") {\n return process.env.FAL_KEY;\n }\n\n return process.env.FAL_KEY_ID\n ? `${process.env.FAL_KEY_ID}:${process.env.FAL_KEY_SECRET}`\n : undefined;\n};\n\nconst DEFAULT_CONFIG: Partial<Config> = {\n credentials: credentialsFromEnv,\n suppressLocalCredentialsWarning: false,\n requestMiddleware: (request) => Promise.resolve(request),\n responseHandler: defaultResponseHandler,\n};\n\n/**\n * Configures the fal client.\n *\n * @param config the new configuration.\n */\nexport function createConfig(config: Config): RequiredConfig {\n let configuration = {\n ...DEFAULT_CONFIG,\n ...config,\n fetch: config.fetch ?? resolveDefaultFetch(),\n } as RequiredConfig;\n if (config.proxyUrl) {\n configuration = {\n ...configuration,\n requestMiddleware: withMiddleware(\n configuration.requestMiddleware,\n withProxy({ targetUrl: config.proxyUrl }),\n ),\n };\n }\n const { credentials: resolveCredentials, suppressLocalCredentialsWarning } =\n configuration;\n const credentials =\n typeof resolveCredentials === \"function\"\n ? resolveCredentials()\n : resolveCredentials;\n if (isBrowser() && credentials && !suppressLocalCredentialsWarning) {\n console.warn(\n \"The fal credentials are exposed in the browser's environment. \" +\n \"That's not recommended for production use cases.\",\n );\n }\n return configuration;\n}\n\n/**\n * @returns the URL of the fal REST api endpoint.\n */\nexport function getRestApiUrl(): string {\n return \"https://rest.alpha.fal.ai\";\n}\n", "export function ensureEndpointIdFormat(id: string): string {\n const parts = id.split(\"/\");\n if (parts.length > 1) {\n return id;\n }\n const [, appOwner, appId] = /^([0-9]+)-([a-zA-Z0-9-]+)$/.exec(id) || [];\n if (appOwner && appId) {\n return `${appOwner}/${appId}`;\n }\n throw new Error(\n `Invalid app id: ${id}. Must be in the format <appOwner>/<appId>`,\n );\n}\n\nconst ENDPOINT_NAMESPACES = [\"workflows\", \"comfy\"] as const;\n\ntype EndpointNamespace = (typeof ENDPOINT_NAMESPACES)[number];\n\nexport type EndpointId = {\n readonly owner: string;\n readonly alias: string;\n readonly path?: string;\n readonly namespace?: EndpointNamespace;\n};\n\nexport function parseEndpointId(id: string): EndpointId {\n const normalizedId = ensureEndpointIdFormat(id);\n const parts = normalizedId.split(\"/\");\n if (ENDPOINT_NAMESPACES.includes(parts[0] as any)) {\n return {\n owner: parts[1],\n alias: parts[2],\n path: parts.slice(3).join(\"/\") || undefined,\n namespace: parts[0] as EndpointNamespace,\n };\n }\n return {\n owner: parts[0],\n alias: parts[1],\n path: parts.slice(2).join(\"/\") || undefined,\n };\n}\n\nexport function isValidUrl(url: string) {\n try {\n const { host } = new URL(url);\n return /(fal\\.(ai|run))$/.test(host);\n } catch (_) {\n return false;\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function throttle<T extends (...args: any[]) => any>(\n func: T,\n limit: number,\n leading = false,\n): (...funcArgs: Parameters<T>) => ReturnType<T> | void {\n let lastFunc: NodeJS.Timeout | null;\n let lastRan: number;\n\n return (...args: Parameters<T>): ReturnType<T> | void => {\n if (!lastRan && leading) {\n func(...args);\n lastRan = Date.now();\n } else {\n if (lastFunc) {\n clearTimeout(lastFunc);\n }\n\n lastFunc = setTimeout(\n () => {\n if (Date.now() - lastRan >= limit) {\n func(...args);\n lastRan = Date.now();\n }\n },\n limit - (Date.now() - lastRan),\n );\n }\n };\n}\n\nlet isRunningInReact: boolean | undefined;\n\n/**\n * Not really the most optimal way to detect if we're running in React,\n * but the idea here is that we can support multiple rendering engines\n * (starting with React), with all their peculiarities, without having\n * to add a dependency or creating custom integrations (e.g. custom hooks).\n *\n * Yes, a bit of magic to make things works out-of-the-box.\n * @returns `true` if running in React, `false` otherwise.\n */\nexport function isReact() {\n if (isRunningInReact === undefined) {\n const stack = new Error().stack;\n isRunningInReact =\n !!stack &&\n (stack.includes(\"node_modules/react-dom/\") ||\n stack.includes(\"node_modules/next/\"));\n }\n return isRunningInReact;\n}\n\n/**\n * Check if a value is a plain object.\n * @param value - The value to check.\n * @returns `true` if the value is a plain object, `false` otherwise.\n */\nexport function isPlainObject(value: any): boolean {\n return !!value && Object.getPrototypeOf(value) === Object.prototype;\n}\n", "import { RequiredConfig } from \"./config\";\nimport { ResponseHandler } from \"./response\";\nimport { getUserAgent, isBrowser } from \"./runtime\";\nimport { RunOptions, UrlOptions } from \"./types/common\";\nimport { ensureEndpointIdFormat, isValidUrl } from \"./utils\";\n\nconst isCloudflareWorkers =\n typeof navigator !== \"undefined\" &&\n navigator?.userAgent === \"Cloudflare-Workers\";\n\ntype RequestOptions = {\n responseHandler?: ResponseHandler<any>;\n};\n\ntype RequestParams<Input = any> = {\n method?: string;\n targetUrl: string;\n input?: Input;\n config: RequiredConfig;\n options?: RequestOptions & RequestInit;\n headers?: Record<string, string>;\n};\n\nexport async function dispatchRequest<Input, Output>(\n params: RequestParams<Input>,\n): Promise<Output> {\n const { targetUrl, input, config, options = {} } = params;\n const {\n credentials: credentialsValue,\n requestMiddleware,\n responseHandler,\n fetch,\n } = config;\n const userAgent = isBrowser() ? {} : { \"User-Agent\": getUserAgent() };\n const credentials =\n typeof credentialsValue === \"function\"\n ? credentialsValue()\n : credentialsValue;\n\n const { method, url, headers } = await requestMiddleware({\n method: (params.method ?? options.method ?? \"post\").toUpperCase(),\n url: targetUrl,\n headers: params.headers,\n });\n const authHeader = credentials ? { Authorization: `Key ${credentials}` } : {};\n const requestHeaders = {\n ...authHeader,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n ...userAgent,\n ...(headers ?? {}),\n } as HeadersInit;\n\n const { responseHandler: customResponseHandler, ...requestInit } = options;\n const response = await fetch(url, {\n ...requestInit,\n method,\n headers: {\n ...requestHeaders,\n ...(requestInit.headers ?? {}),\n },\n ...(!isCloudflareWorkers && { mode: \"cors\" }),\n signal: options.signal,\n body:\n method.toLowerCase() !== \"get\" && input\n ? JSON.stringify(input)\n : undefined,\n });\n const handleResponse = customResponseHandler ?? responseHandler;\n return await handleResponse(response);\n}\n\n/**\n * Builds the final url to run the function based on its `id` or alias and\n * a the options from `RunOptions<Input>`.\n *\n * @private\n * @param id the function id or alias\n * @param options the run options\n * @returns the final url to run the function\n */\nexport function buildUrl<Input>(\n id: string,\n options: RunOptions<Input> & UrlOptions = {},\n): string {\n const method = (options.method ?? \"post\").toLowerCase();\n const path = (options.path ?? \"\").replace(/^\\//, \"\").replace(/\\/{2,}/, \"/\");\n const input = options.input;\n const params = {\n ...(options.query || {}),\n ...(method === \"get\" ? input : {}),\n };\n\n const queryParams =\n Object.keys(params).length > 0\n ? `?${new URLSearchParams(params).toString()}`\n : \"\";\n\n // if a fal url is passed, just use it\n if (isValidUrl(id)) {\n const url = id.endsWith(\"/\") ? id : `${id}/`;\n return `${url}${path}${queryParams}`;\n }\n\n const appId = ensureEndpointIdFormat(id);\n const subdomain = options.subdomain ? `${options.subdomain}.` : \"\";\n const url = `https://${subdomain}fal.run/${appId}/${path}`;\n return `${url.replace(/\\/$/, \"\")}${queryParams}`;\n}\n", "/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n *\n * Based on code from the {@link https://github.com/EventSource/eventsource | EventSource module},\n * which is licensed under the MIT license. And copyrighted the EventSource GitHub organisation.\n */\nimport type {EventSourceParseCallback, EventSourceParser} from './types.js'\n\n/**\n * Creates a new EventSource parser.\n *\n * @param onParse - Callback to invoke when a new event is parsed, or a new reconnection interval\n * has been sent from the server\n *\n * @returns A new EventSource parser, with `parse` and `reset` methods.\n * @public\n */\nexport function createParser(onParse: EventSourceParseCallback): EventSourceParser {\n // Processing state\n let isFirstChunk: boolean\n let buffer: string\n let startingPosition: number\n let startingFieldLength: number\n\n // Event state\n let eventId: string | undefined\n let eventName: string | undefined\n let data: string\n\n reset()\n return {feed, reset}\n\n function reset(): void {\n isFirstChunk = true\n buffer = ''\n startingPosition = 0\n startingFieldLength = -1\n\n eventId = undefined\n eventName = undefined\n data = ''\n }\n\n function feed(chunk: string): void {\n buffer = buffer ? buffer + chunk : chunk\n\n // Strip any UTF8 byte order mark (BOM) at the start of the stream.\n // Note that we do not strip any non - UTF8 BOM, as eventsource streams are\n // always decoded as UTF8 as per the specification.\n if (isFirstChunk && hasBom(buffer)) {\n buffer = buffer.slice(BOM.length)\n }\n\n isFirstChunk = false\n\n // Set up chunk-specific processing state\n const length = buffer.length\n let position = 0\n let discardTrailingNewline = false\n\n // Read the current buffer byte by byte\n while (position < length) {\n // EventSource allows for carriage return + line feed, which means we\n // need to ignore a linefeed character if the previous character was a\n // carriage return\n // @todo refactor to reduce nesting, consider checking previous byte?\n // @todo but consider multiple chunks etc\n if (discardTrailingNewline) {\n if (buffer[position] === '\\n') {\n ++position\n }\n discardTrailingNewline = false\n }\n\n let lineLength = -1\n let fieldLength = startingFieldLength\n let character: string\n\n for (let index = startingPosition; lineLength < 0 && index < length; ++index) {\n character = buffer[index]\n if (character === ':' && fieldLength < 0) {\n fieldLength = index - position\n } else if (character === '\\r') {\n discardTrailingNewline = true\n lineLength = index - position\n } else if (character === '\\n') {\n lineLength = index - position\n }\n }\n\n if (lineLength < 0) {\n startingPosition = length - position\n startingFieldLength = fieldLength\n break\n } else {\n startingPosition = 0\n startingFieldLength = -1\n }\n\n parseEventStreamLine(buffer, position, fieldLength, lineLength)\n\n position += lineLength + 1\n }\n\n if (position === length) {\n // If we consumed the entire buffer to read the event, reset the buffer\n buffer = ''\n } else if (position > 0) {\n // If there are bytes left to process, set the buffer to the unprocessed\n // portion of the buffer only\n buffer = buffer.slice(position)\n }\n }\n\n function parseEventStreamLine(\n lineBuffer: string,\n index: number,\n fieldLength: number,\n lineLength: number,\n ) {\n if (lineLength === 0) {\n // We reached the last line of this event\n if (data.length > 0) {\n onParse({\n type: 'event',\n id: eventId,\n event: eventName || undefined,\n data: data.slice(0, -1), // remove trailing newline\n })\n\n data = ''\n eventId = undefined\n }\n eventName = undefined\n return\n }\n\n const noValue = fieldLength < 0\n const field = lineBuffer.slice(index, index + (noValue ? lineLength : fieldLength))\n let step = 0\n\n if (noValue) {\n step = lineLength\n } else if (lineBuffer[index + fieldLength + 1] === ' ') {\n step = fieldLength + 2\n } else {\n step = fieldLength + 1\n }\n\n const position = index + step\n const valueLength = lineLength - step\n const value = lineBuffer.slice(position, position + valueLength).toString()\n\n if (field === 'data') {\n data += value ? `${value}\\n` : '\\n'\n } else if (field === 'event') {\n eventName = value\n } else if (field === 'id' && !value.includes('\\u0000')) {\n eventId = value\n } else if (field === 'retry') {\n const retry = parseInt(value, 10)\n if (!Number.isNaN(retry)) {\n onParse({type: 'reconnect-interval', value: retry})\n }\n }\n }\n}\n\nconst BOM = [239, 187, 191]\n\nfunction hasBom(buffer: string) {\n return BOM.every((charCode: number, index: number) => buffer.charCodeAt(index) === charCode)\n}\n", "import { getRestApiUrl, RequiredConfig } from \"./config\";\nimport { dispatchRequest } from \"./request\";\nimport { parseEndpointId } from \"./utils\";\n\nexport const TOKEN_EXPIRATION_SECONDS = 120;\n\n/**\n * Get a token to connect to the realtime endpoint.\n */\nexport async function getTemporaryAuthToken(\n app: string,\n config: RequiredConfig,\n): Promise<string> {\n const appId = parseEndpointId(app);\n const token: string | object = await dispatchRequest<any, string>({\n method: \"POST\",\n targetUrl: `${getRestApiUrl()}/tokens/`,\n config,\n input: {\n allowed_apps: [appId.alias],\n token_expiration: TOKEN_EXPIRATION_SECONDS,\n },\n });\n // keep this in case the response was wrapped (old versions of the proxy do that)\n // should be safe to remove in the future\n if (typeof token !== \"string\" && token[\"detail\"]) {\n return token[\"detail\"];\n }\n return token;\n}\n", "import { createParser } from \"eventsource-parser\";\nimport { getTemporaryAuthToken } from \"./auth\";\nimport { RequiredConfig } from \"./config\";\nimport { buildUrl, dispatchRequest } from \"./request\";\nimport { ApiError, defaultResponseHandler } from \"./response\";\nimport { type StorageClient } from \"./storage\";\nimport { EndpointType, InputType, OutputType } from \"./types/client\";\n\nexport type StreamingConnectionMode = \"client\" | \"server\";\n\nconst CONTENT_TYPE_EVENT_STREAM = \"text/event-stream\";\n\n/**\n * The stream API options. It requires the API input and also\n * offers configuration options.\n */\nexport type StreamOptions<Input> = {\n /**\n * The endpoint URL. If not provided, it will be generated from the\n * `endpointId` and the `queryParams`.\n */\n readonly url?: string;\n\n /**\n * The API input payload.\n */\n readonly input?: Input;\n\n /**\n * The query parameters to be sent with the request.\n */\n readonly queryParams?: Record<string, string>;\n\n /**\n * The maximum time interval in milliseconds between stream chunks. Defaults to 15s.\n */\n readonly timeout?: number;\n\n /**\n * Whether it should auto-upload File-like types to fal's storage\n * or not.\n */\n readonly autoUpload?: boolean;\n\n /**\n * The HTTP method, defaults to `post`;\n */\n readonly method?: \"get\" | \"post\" | \"put\" | \"delete\" | string;\n\n /**\n * The content type the client accepts as response.\n * By default this is set to `text/event-stream`.\n */\n readonly accept?: string;\n\n /**\n * The streaming connection mode. This is used to determine\n * whether the streaming will be done from the browser itself (client)\n * or through your own server, either when running on NodeJS or when\n * using a proxy that supports streaming.\n *\n * It defaults to `server`. Set to `client` if your server proxy doesn't\n * support streaming.\n */\n readonly connectionMode?: StreamingConnectionMode;\n\n /**\n * The signal to abort the request.\n */\n readonly signal?: AbortSignal;\n};\n\nconst EVENT_STREAM_TIMEOUT = 15 * 1000;\n\ntype FalStreamEventType = \"data\" | \"error\" | \"done\";\n\ntype EventHandler<T = any> = (event: T) => void;\n\n/**\n * The class representing a streaming response. With t\n */\nexport class FalStream<Input, Output> {\n // properties\n config: RequiredConfig;\n endpointId: string;\n url: string;\n options: StreamOptions<Input>;\n\n // support for event listeners\n private listeners: Map<FalStreamEventType, EventHandler[]> = new Map();\n private buffer: Output[] = [];\n\n // local state\n private currentData: Output | undefined = undefined;\n private lastEventTimestamp = 0;\n private streamClosed = false;\n private donePromise: Promise<Output>;\n\n private abortController = new AbortController();\n\n constructor(\n endpointId: string,\n config: RequiredConfig,\n options: StreamOptions<Input>,\n ) {\n this.endpointId = endpointId;\n this.config = config;\n this.url =\n options.url ??\n buildUrl(endpointId, {\n path: \"/stream\",\n query: options.queryParams,\n });\n this.options = options;\n this.donePromise = new Promise<Output>((resolve, reject) => {\n if (this.streamClosed) {\n reject(\n new ApiError({\n message: \"Streaming connection is already closed.\",\n status: 400,\n body: undefined,\n }),\n );\n }\n this.signal.addEventListener(\"abort\", () => {\n resolve(this.currentData ?? ({} as Output));\n });\n this.on(\"done\", (data) => {\n this.streamClosed = true;\n resolve(data);\n });\n this.on(\"error\", (error) => {\n this.streamClosed = true;\n reject(error);\n });\n });\n // if a abort signal was passed, sync it with the internal one\n if (options.signal) {\n options.signal.addEventListener(\"abort\", () => {\n this.abortController.abort();\n });\n }\n\n // start the streaming request\n this.start().catch(this.handleError);\n }\n\n private start = async () => {\n const { endpointId, options } = this;\n const { input, method = \"post\", connectionMode = \"server\" } = options;\n try {\n if (connectionMode === \"client\") {\n // if we are in the browser, we need to get a temporary token\n // to authenticate the request\n const token = await getTemporaryAuthToken(endpointId, this.config);\n const { fetch } = this.config;\n const parsedUrl = new URL(this.url);\n parsedUrl.searchParams.set(\"fal_jwt_token\", token);\n const response = await fetch(parsedUrl.toString(), {\n method: method.toUpperCase(),\n headers: {\n accept: options.accept ?? CONTENT_TYPE_EVENT_STREAM,\n \"content-type\": \"application/json\",\n },\n body: input && method !== \"get\" ? JSON.stringify(input) : undefined,\n signal: this.abortController.signal,\n });\n return await this.handleResponse(response);\n }\n return await dispatchRequest({\n method: method.toUpperCase(),\n targetUrl: this.url,\n input,\n config: this.config,\n options: {\n headers: {\n accept: options.accept ?? CONTENT_TYPE_EVENT_STREAM,\n },\n responseHandler: this.handleResponse,\n signal: this.abortController.signal,\n },\n });\n } catch (error) {\n this.handleError(error);\n }\n };\n\n private handleResponse = async (response: Response) => {\n if (!response.ok) {\n try {\n // we know the response failed, call the response handler\n // so the exception gets converted to ApiError correctly\n await defaultResponseHandler(response);\n } catch (error) {\n this.emit(\"error\", error);\n }\n return;\n }\n\n const body = response.body;\n if (!body) {\n this.emit(\n \"error\",\n new ApiError({\n message: \"Response body is empty.\",\n status: 400,\n body: undefined,\n }),\n );\n return;\n }\n\n const isEventStream = (\n response.headers.get(\"content-type\") ?? \"\"\n ).startsWith(CONTENT_TYPE_EVENT_STREAM);\n // any response that is not a text/event-stream will be handled as a binary stream\n if (!isEventStream) {\n const reader = body.getReader();\n const emitRawChunk = () => {\n reader.read().then(({ done, value }) => {\n if (done) {\n this.emit(\"done\", this.currentData);\n return;\n }\n this.currentData = value as Output;\n this.emit(\"data\", value);\n emitRawChunk();\n });\n };\n emitRawChunk();\n return;\n }\n\n const decoder = new TextDecoder(\"utf-8\");\n const reader = response.body.getReader();\n\n const parser = createParser((event) => {\n if (event.type === \"event\") {\n const data = event.data;\n\n try {\n const parsedData = JSON.parse(data);\n this.buffer.push(parsedData);\n this.currentData = parsedData;\n this.emit(\"data\", parsedData);\n\n // also emit 'message'for backwards compatibility\n this.emit(\"message\" as any, parsedData);\n } catch (e) {\n this.emit(\"error\", e);\n }\n }\n });\n\n const timeout = this.options.timeout ?? EVENT_STREAM_TIMEOUT;\n\n const readPartialResponse = async () => {\n const { value, done } = await reader.read();\n this.lastEventTimestamp = Date.now();\n\n parser.feed(decoder.decode(value));\n\n if (Date.now() - this.lastEventTimestamp > timeout) {\n this.emit(\n \"error\",\n new ApiError({\n message: `Event stream timed out after ${(timeout / 1000).toFixed(0)} seconds with no messages.`,\n status: 408,\n }),\n );\n }\n\n if (!done) {\n readPartialResponse().catch(this.handleError);\n } else {\n this.emit(\"done\", this.currentData);\n }\n };\n\n readPartialResponse().catch(this.handleError);\n return;\n };\n\n private handleError = (error: any) => {\n // In case AbortError is thrown but the signal is marked as aborted\n // it means the user called abort() and we should not emit an error\n // as it's expected behavior\n // See note on: https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort\n if (error.name === \"AbortError\" || this.signal.aborted) {\n return;\n }\n const apiError =\n error instanceof ApiError\n ? error\n : new ApiError({\n message: error.message ?? \"An unknown error occurred\",\n status: 500,\n });\n this.emit(\"error\", apiError);\n return;\n };\n\n public on = (type: FalStreamEventType, listener: EventHandler) => {\n if (!this.listeners.has(type)) {\n this.listeners.set(type, []);\n }\n this.listeners.get(type)?.push(listener);\n };\n\n private emit = (type: FalStreamEventType, event: any) => {\n const listeners = this.listeners.get(type) || [];\n for (const listener of listeners) {\n listener(event);\n }\n };\n\n async *[Symbol.asyncIterator]() {\n let running = true;\n const stopAsyncIterator = () => (running = false);\n this.on(\"error\", stopAsyncIterator);\n this.on(\"done\", stopAsyncIterator);\n while (running || this.buffer.length > 0) {\n const data = this.buffer.shift();\n if (data) {\n yield data;\n }\n\n // the short timeout ensures the while loop doesn't block other\n // frames getting executed concurrently\n await new Promise((resolve) => setTimeout(resolve, 16));\n }\n }\n\n /**\n * Gets a reference to the `Promise` that indicates whether the streaming\n * is done or not. Developers should always call this in their apps to ensure\n * the request is over.\n *\n * An alternative to this, is to use `on('done')` in case your application\n * architecture works best with event listeners.\n *\n * @returns the promise that resolves when the request is done.\n */\n public done = async () => this.donePromise;\n\n /**\n * Aborts the streaming request.\n *\n * **Note:** This method is noop in case the request is already done.\n *\n * @param reason optional cause for aborting the request.\n */\n public abort = (reason?: string | Error) => {\n if (!this.streamClosed) {\n this.abortController.abort(reason);\n }\n };\n\n /**\n * Gets the `AbortSignal` instance that can be used to listen for abort events.\n *\n * **Note:** this signal is internal to the `FalStream` instance. If you pass your\n * own abort signal, the `FalStream` will listen to it and abort it appropriately.\n *\n * @returns the `AbortSignal` instance.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal\n */\n public get signal() {\n return this.abortController.signal;\n }\n}\n\n/**\n * The streaming client interface.\n */\nexport interface StreamingClient {\n /**\n * Calls a fal app that supports streaming and provides a streaming-capable\n * object as a result, that can be used to get partial results through either\n * `AsyncIterator` or through an event listener.\n *\n * @param endpointId the endpoint id, e.g. `fal-ai/llavav15-13b`.\n * @param options the request options, including the input payload.\n * @returns the `FalStream` instance.\n */\n stream<Id extends EndpointType>(\n endpointId: Id,\n options: StreamOptions<InputType<Id>>,\n ): Promise<FalStream<InputType<Id>, OutputType<Id>>>;\n}\n\ntype StreamingClientDependencies = {\n config: RequiredConfig;\n storage: StorageClient;\n};\n\nexport function createStreamingClient({\n config,\n storage,\n}: StreamingClientDependencies): StreamingClient {\n return {\n async stream<Id extends EndpointType>(\n endpointId: Id,\n options: StreamOptions<InputType<Id>>,\n ) {\n const input = options.input\n ? await storage.transformInput(options.input)\n : undefined;\n return new FalStream<InputType<Id>, OutputType<Id>>(endpointId, config, {\n ...options,\n input: input as InputType<Id>,\n });\n },\n };\n}\n", "import { RequiredConfig } from \"./config\";\nimport { buildUrl, dispatchRequest } from \"./request\";\nimport { resultResponseHandler } from \"./response\";\nimport { StorageClient } from \"./storage\";\nimport { FalStream, StreamingConnectionMode } from \"./streaming\";\nimport { EndpointType, InputType, OutputType } from \"./types/client\";\nimport {\n CompletedQueueStatus,\n InQueueQueueStatus,\n QueueStatus,\n RequestLog,\n Result,\n RunOptions,\n} from \"./types/common\";\nimport { parseEndpointId } from \"./utils\";\n\nexport type QueuePriority = \"low\" | \"normal\";\nexport type QueueStatusSubscriptionOptions = QueueStatusOptions &\n Omit<QueueSubscribeOptions, \"onEnqueue\" | \"webhookUrl\">;\n\ntype TimeoutId = ReturnType<typeof setTimeout> | undefined;\n\nconst DEFAULT_POLL_INTERVAL = 500;\n\n/**\n * Options for subscribing to the request queue.\n */\nexport type QueueSubscribeOptions = {\n /**\n * The mode to use for subscribing to updates. It defaults to `polling`.\n * You can also use client-side streaming by setting it to `streaming`.\n *\n * **Note:** Streaming is currently experimental and once stable, it will\n * be the default mode.\n *\n * @see pollInterval\n */\n mode?: \"polling\" | \"streaming\";\n\n /**\n * Callback function that is called when a request is enqueued.\n * @param requestId - The unique identifier for the enqueued request.\n */\n onEnqueue?: (requestId: string) => void;\n\n /**\n * Callback function that is called when the status of the queue changes.\n * @param status - The current status of the queue.\n */\n onQueueUpdate?: (status: QueueStatus) => void;\n\n /**\n * If `true`, the response will include the logs for the request.\n * Defaults to `false`.\n */\n logs?: boolean;\n\n /**\n * The timeout (in milliseconds) for the request. If the request is not\n * completed within this time, the subscription will be cancelled.\n *\n * Keep in mind that although the client resolves the function on a timeout,\n * and will try to cancel the request on the server, the server might not be\n * able to cancel the request if it's already running.\n *\n * Note: currently, the timeout is not enforced and the default is `undefined`.\n * This behavior might change in the future.\n */\n timeout?: number;\n\n /**\n * The URL to send a webhook notification to when the request is completed.\n * @see WebHookResponse\n */\n webhookUrl?: string;\n\n /**\n * The priority of the request. It defaults to `normal`.\n * @see QueuePriority\n */\n priority?: QueuePriority;\n} & (\n | {\n mode?: \"polling\";\n /**\n * The interval (in milliseconds) at which to poll for updates.\n * If not provided, a default value of `500` will be used.\n *\n * This value is ignored if `mode` is set to `streaming`.\n */\n pollInterval?: number;\n }\n | {\n mode: \"streaming\";\n\n /**\n * The connection mode to use for streaming updates. It defaults to `server`.\n * Set to `client` if your server proxy doesn't support streaming.\n */\n connectionMode?: StreamingConnectionMode;\n }\n);\n\n/**\n * Options for submitting a request to the queue.\n */\nexport type SubmitOptions<Input> = RunOptions<Input> & {\n /**\n * The URL to send a webhook notification to when the request is completed.\n * @see WebHookResponse\n */\n webhookUrl?: string;\n\n /**\n * The priority of the request. It defaults to `normal`.\n * @see QueuePriority\n */\n priority?: QueuePriority;\n};\n\ntype BaseQueueOptions = {\n /**\n * The unique identifier for the enqueued request.\n */\n requestId: string;\n\n /**\n * The signal to abort the request.\n */\n abortSignal?: AbortSignal;\n};\n\nexport type QueueStatusOptions = BaseQueueOptions & {\n /**\n * If `true`, the response will include the logs for the request.\n * Defaults to `false`.\n */\n logs?: boolean;\n};\n\nexport type QueueStatusStreamOptions = QueueStatusOptions & {\n /**\n * The connection mode to use for streaming updates. It defaults to `server`.\n * Set to `client` if your server proxy doesn't support streaming.\n */\n connectionMode?: StreamingConnectionMode;\n};\n\n/**\n * Represents a request queue with methods for submitting requests,\n * checking their status, retrieving results, and subscribing to updates.\n */\nexport interface QueueClient {\n /**\n * Submits a request to the queue.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run.\n * @returns A promise that resolves to the result of enqueuing the request.\n */\n submit<Id extends EndpointType>(\n endpointId: Id,\n options: SubmitOptions<InputType<Id>>,\n ): Promise<InQueueQueueStatus>;\n\n /**\n * Retrieves the status of a specific request in the queue.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run.\n * @returns A promise that resolves to the status of the request.\n */\n status(endpointId: string, options: QueueStatusOptions): Promise<QueueStatus>;\n\n /**\n * Subscribes to updates for a specific request in the queue using HTTP streaming events.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run and how updates are received.\n * @returns The streaming object that can be used to listen for updates.\n */\n streamStatus(\n endpointId: string,\n options: QueueStatusStreamOptions,\n ): Promise<FalStream<unknown, QueueStatus>>;\n\n /**\n * Subscribes to updates for a specific request in the queue using polling or streaming.\n * See `options.mode` for more details.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run and how updates are received.\n * @returns A promise that resolves to the final status of the request.\n */\n subscribeToStatus(\n endpointId: string,\n options: QueueStatusSubscriptionOptions,\n ): Promise<CompletedQueueStatus>;\n\n /**\n * Retrieves the result of a specific request from the queue.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run.\n * @returns A promise that resolves to the result of the request.\n */\n result<Id extends EndpointType>(\n endpointId: Id,\n options: BaseQueueOptions,\n ): Promise<Result<OutputType<Id>>>;\n\n /**\n * Cancels a request in the queue.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request\n * is run and how updates are received.\n * @returns A promise that resolves once the request is cancelled.\n * @throws {Error} If the request cannot be cancelled.\n */\n cancel(endpointId: string, options: BaseQueueOptions): Promise<void>;\n}\n\ntype QueueClientDependencies = {\n config: RequiredConfig;\n storage: StorageClient;\n};\n\nexport const createQueueClient = ({\n config,\n storage,\n}: QueueClientDependencies): QueueClient => {\n const ref: QueueClient = {\n async submit<Input>(\n endpointId: string,\n options: SubmitOptions<Input>,\n ): Promise<InQueueQueueStatus> {\n const { webhookUrl, priority, ...runOptions } = options;\n const input = options.input\n ? await storage.transformInput(options.input)\n : undefined;\n return dispatchRequest<Input, InQueueQueueStatus>({\n method: options.method,\n targetUrl: buildUrl(endpointId, {\n ...runOptions,\n subdomain: \"queue\",\n query: webhookUrl ? { fal_webhook: webhookUrl } : undefined,\n }),\n headers: {\n \"x-fal-queue-priority\": priority ?? \"normal\",\n },\n input: input as Input,\n config,\n options: {\n signal: options.abortSignal,\n },\n });\n },\n async status(\n endpointId: string,\n { requestId, logs = false, abortSignal }: QueueStatusOptions,\n ): Promise<QueueStatus> {\n const appId = parseEndpointId(endpointId);\n const prefix = appId.namespace ? `${appId.namespace}/` : \"\";\n return dispatchRequest<unknown, QueueStatus>({\n method: \"get\",\n targetUrl: buildUrl(`${prefix}${appId.owner}/${appId.alias}`, {\n subdomain: \"queue\",\n query: { logs: logs ? \"1\" : \"0\" },\n path: `/requests/${requestId}/status`,\n }),\n config,\n options: {\n signal: abortSignal,\n },\n });\n },\n\n async streamStatus(\n endpointId: string,\n { requestId, logs = false, connectionMode }: QueueStatusStreamOptions,\n ): Promise<FalStream<unknown, QueueStatus>> {\n const appId = parseEndpointId(endpointId);\n const prefix = appId.namespace ? `${appId.namespace}/` : \"\";\n\n const queryParams = {\n logs: logs ? \"1\" : \"0\",\n };\n\n const url = buildUrl(`${prefix}${appId.owner}/${appId.alias}`, {\n subdomain: \"queue\",\n path: `/requests/${requestId}/status/stream`,\n query: queryParams,\n });\n\n return new FalStream<unknown, QueueStatus>(endpointId, config, {\n url,\n method: \"get\",\n connectionMode,\n queryParams,\n });\n },\n\n async subscribeToStatus(\n endpointId,\n options,\n ): Promise<CompletedQueueStatus> {\n const requestId = options.requestId;\n const timeout = options.timeout;\n let timeoutId: TimeoutId = undefined;\n\n const handleCancelError = () => {\n // Ignore errors as the client will follow through with the timeout\n // regardless of the server response. In case cancelation fails, we\n // still want to reject the promise and consider the client call canceled.\n };\n if (options.mode === \"streaming\") {\n const status = await ref.streamStatus(endpointId, {\n requestId,\n logs: options.logs,\n connectionMode:\n \"connectionMode\" in options\n ? (options.connectionMode as StreamingConnectionMode)\n : undefined,\n });\n const logs: RequestLog[] = [];\n if (timeout) {\n timeoutId = setTimeout(() => {\n status.abort();\n ref.cancel(endpointId, { requestId }).catch(handleCancelError);\n // TODO this error cannot bubble up to the user since it's thrown in\n // a closure in the global scope due to setTimeout behavior.\n // User will get a platform error instead. We should find a way to\n // make this behavior aligned with polling.\n throw new Error(\n `Client timed out waiting for the request to complete after ${timeout}ms`,\n );\n }, timeout);\n }\n status.on(\"data\", (data: QueueStatus) => {\n if (options.onQueueUpdate) {\n // accumulate logs to match previous polling behavior\n if (\n \"logs\" in data &&\n Array.isArray(data.logs) &&\n data.logs.length > 0\n ) {\n logs.push(...data.logs);\n }\n options.onQueueUpdate(\"logs\" in data ? { ...data, logs } : data);\n }\n });\n const doneStatus = await status.done();\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n return doneStatus as CompletedQueueStatus;\n }\n // default to polling until status streaming is stable and faster\n return new Promise<CompletedQueueStatus>((resolve, reject) => {\n let pollingTimeoutId: TimeoutId;\n // type resolution isn't great in this case, so check for its presence\n // and and type so the typechecker behaves as expected\n const pollInterval =\n \"pollInterval\" in options && typeof options.pollInterval === \"number\"\n ? (options.pollInterval ?? DEFAULT_POLL_INTERVAL)\n : DEFAULT_POLL_INTERVAL;\n\n const clearScheduledTasks = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n if (pollingTimeoutId) {\n clearTimeout(pollingTimeoutId);\n }\n };\n if (timeout) {\n timeoutId = setTimeout(() => {\n clearScheduledTasks();\n ref.cancel(endpointId, { requestId }).catch(handleCancelError);\n reject(\n new Error(\n `Client timed out waiting for the request to complete after ${timeout}ms`,\n ),\n );\n }, timeout);\n }\n const poll = async () => {\n try {\n const requestStatus = await ref.status(endpointId, {\n requestId,\n logs: options.logs ?? false,\n abortSignal: options.abortSignal,\n });\n if (options.onQueueUpdate) {\n options.onQueueUpdate(requestStatus);\n }\n if (requestStatus.status === \"COMPLETED\") {\n clearScheduledTasks();\n resolve(requestStatus);\n return;\n }\n pollingTimeoutId = setTimeout(poll, pollInterval);\n } catch (error) {\n clearScheduledTasks();\n reject(error);\n }\n };\n poll().catch(reject);\n });\n },\n\n async result<Output>(\n endpointId: string,\n { requestId, abortSignal }: BaseQueueOptions,\n ): Promise<Result<Output>> {\n const appId = parseEndpointId(endpointId);\n const prefix = appId.namespace ? `${appId.namespace}/` : \"\";\n return dispatchRequest<unknown, Result<Output>>({\n method: \"get\",\n targetUrl: buildUrl(`${prefix}${appId.owner}/${appId.alias}`, {\n subdomain: \"queue\",\n path: `/requests/${requestId}`,\n }),\n config: {\n ...config,\n responseHandler: resultResponseHandler,\n },\n options: {\n signal: abortSignal,\n },\n });\n },\n\n async cancel(\n endpointId: string,\n { requestId, abortSignal }: BaseQueueOptions,\n ): Promise<void> {\n const appId = parseEndpointId(endpointId);\n const prefix = appId.namespace ? `${appId.namespace}/` : \"\";\n await dispatchRequest<unknown, void>({\n method: \"put\",\n targetUrl: buildUrl(`${prefix}${appId.owner}/${appId.alias}`, {\n subdomain: \"queue\",\n path: `/requests/${requestId}/cancel`,\n }),\n config,\n options: {\n signal: abortSignal,\n },\n });\n },\n };\n return ref;\n};\n", "export function utf8Count(str: string): number {\n const strLength = str.length;\n\n let byteLength = 0;\n let pos = 0;\n while (pos < strLength) {\n let value = str.charCodeAt(pos++);\n\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n byteLength++;\n continue;\n } else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n byteLength += 2;\n } else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n const extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n byteLength += 3;\n } else {\n // 4-byte\n byteLength += 4;\n }\n }\n }\n return byteLength;\n}\n\nexport function utf8EncodeJs(str: string, output: Uint8Array, outputOffset: number): void {\n const strLength = str.length;\n let offset = outputOffset;\n let pos = 0;\n while (pos < strLength) {\n let value = str.charCodeAt(pos++);\n\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n output[offset++] = value;\n continue;\n } else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n output[offset++] = ((value >> 6) & 0x1f) | 0xc0;\n } else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n const extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n output[offset++] = ((value >> 12) & 0x0f) | 0xe0;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n } else {\n // 4-byte\n output[offset++] = ((value >> 18) & 0x07) | 0xf0;\n output[offset++] = ((value >> 12) & 0x3f) | 0x80;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n }\n }\n\n output[offset++] = (value & 0x3f) | 0x80;\n }\n}\n\n// TextEncoder and TextDecoder are standardized in whatwg encoding:\n// https://encoding.spec.whatwg.org/\n// and available in all the modern browsers:\n// https://caniuse.com/textencoder\n// They are available in Node.js since v12 LTS as well:\n// https://nodejs.org/api/globals.html#textencoder\n\nconst sharedTextEncoder = new TextEncoder();\n\n// This threshold should be determined by benchmarking, which might vary in engines and input data.\n// Run `npx ts-node benchmark/encode-string.ts` for details.\nconst TEXT_ENCODER_THRESHOLD = 50;\n\nexport function utf8EncodeTE(str: string, output: Uint8Array, outputOffset: number): void {\n sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));\n}\n\nexport function utf8Encode(str: string, output: Uint8Array, outputOffset: number): void {\n if (str.length > TEXT_ENCODER_THRESHOLD) {\n utf8EncodeTE(str, output, outputOffset);\n } else {\n utf8EncodeJs(str, output, outputOffset);\n }\n}\n\nconst CHUNK_SIZE = 0x1_000;\n\nexport function utf8DecodeJs(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n let offset = inputOffset;\n const end = offset + byteLength;\n\n const units: Array<number> = [];\n let result = \"\";\n while (offset < end) {\n const byte1 = bytes[offset++]!;\n if ((byte1 & 0x80) === 0) {\n // 1 byte\n units.push(byte1);\n } else if ((byte1 & 0xe0) === 0xc0) {\n // 2 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n units.push(((byte1 & 0x1f) << 6) | byte2);\n } else if ((byte1 & 0xf0) === 0xe0) {\n // 3 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n const byte3 = bytes[offset++]! & 0x3f;\n units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);\n } else if ((byte1 & 0xf8) === 0xf0) {\n // 4 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n const byte3 = bytes[offset++]! & 0x3f;\n const byte4 = bytes[offset++]! & 0x3f;\n let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;\n if (unit > 0xffff) {\n unit -= 0x10000;\n units.push(((unit >>> 10) & 0x3ff) | 0xd800);\n unit = 0xdc00 | (unit & 0x3ff);\n }\n units.push(unit);\n } else {\n units.push(byte1);\n }\n\n if (units.length >= CHUNK_SIZE) {\n result += String.fromCharCode(...units);\n units.length = 0;\n }\n }\n\n if (units.length > 0) {\n result += String.fromCharCode(...units);\n }\n\n return result;\n}\n\nconst sharedTextDecoder = new TextDecoder();\n\n// This threshold should be determined by benchmarking, which might vary in engines and input data.\n// Run `npx ts-node benchmark/decode-string.ts` for details.\nconst TEXT_DECODER_THRESHOLD = 200;\n\nexport function utf8DecodeTD(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n const stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);\n return sharedTextDecoder.decode(stringBytes);\n}\n\nexport function utf8Decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n if (byteLength > TEXT_DECODER_THRESHOLD) {\n return utf8DecodeTD(bytes, inputOffset, byteLength);\n } else {\n return utf8DecodeJs(bytes, inputOffset, byteLength);\n }\n}\n", "/**\n * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.\n */\nexport class ExtData {\n readonly type: number;\n readonly data: Uint8Array | ((pos: number) => Uint8Array);\n\n constructor(type: number, data: Uint8Array | ((pos: number) => Uint8Array)) {\n this.type = type;\n this.data = data;\n }\n}\n", "export class DecodeError extends Error {\n constructor(message: string) {\n super(message);\n\n // fix the prototype chain in a cross-platform way\n const proto: typeof DecodeError.prototype = Object.create(DecodeError.prototype);\n Object.setPrototypeOf(this, proto);\n\n Object.defineProperty(this, \"name\", {\n configurable: true,\n enumerable: false,\n value: DecodeError.name,\n });\n }\n}\n", "// Integer Utility\n\nexport const UINT32_MAX = 0xffff_ffff;\n\n// DataView extension to handle int64 / uint64,\n// where the actual range is 53-bits integer (a.k.a. safe integer)\n\nexport function setUint64(view: DataView, offset: number, value: number): void {\n const high = value / 0x1_0000_0000;\n const low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\n\nexport function setInt64(view: DataView, offset: number, value: number): void {\n const high = Math.floor(value / 0x1_0000_0000);\n const low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\n\nexport function getInt64(view: DataView, offset: number): number {\n const high = view.getInt32(offset);\n const low = view.getUint32(offset + 4);\n return high * 0x1_0000_0000 + low;\n}\n\nexport function getUint64(view: DataView, offset: number): number {\n const high = view.getUint32(offset);\n const low = view.getUint32(offset + 4);\n return high * 0x1_0000_0000 + low;\n}\n", "// https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type\nimport { DecodeError } from \"./DecodeError.ts\";\nimport { getInt64, setInt64 } from \"./utils/int.ts\";\n\nexport const EXT_TIMESTAMP = -1;\n\nexport type TimeSpec = {\n sec: number;\n nsec: number;\n};\n\nconst TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int\nconst TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int\n\nexport function encodeTimeSpecToTimestamp({ sec, nsec }: TimeSpec): Uint8Array {\n if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {\n // Here sec >= 0 && nsec >= 0\n if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {\n // timestamp 32 = { sec32 (unsigned) }\n const rv = new Uint8Array(4);\n const view = new DataView(rv.buffer);\n view.setUint32(0, sec);\n return rv;\n } else {\n // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }\n const secHigh = sec / 0x100000000;\n const secLow = sec & 0xffffffff;\n const rv = new Uint8Array(8);\n const view = new DataView(rv.buffer);\n // nsec30 | secHigh2\n view.setUint32(0, (nsec << 2) | (secHigh & 0x3));\n // secLow32\n view.setUint32(4, secLow);\n return rv;\n }\n } else {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n const rv = new Uint8Array(12);\n const view = new DataView(rv.buffer);\n view.setUint32(0, nsec);\n setInt64(view, 4, sec);\n return rv;\n }\n}\n\nexport function encodeDateToTimeSpec(date: Date): TimeSpec {\n const msec = date.getTime();\n const sec = Math.floor(msec / 1e3);\n const nsec = (msec - sec * 1e3) * 1e6;\n\n // Normalizes { sec, nsec } to ensure nsec is unsigned.\n const nsecInSec = Math.floor(nsec / 1e9);\n return {\n sec: sec + nsecInSec,\n nsec: nsec - nsecInSec * 1e9,\n };\n}\n\nexport function encodeTimestampExtension(object: unknown): Uint8Array | null {\n if (object instanceof Date) {\n const timeSpec = encodeDateToTimeSpec(object);\n return encodeTimeSpecToTimestamp(timeSpec);\n } else {\n return null;\n }\n}\n\nexport function decodeTimestampToTimeSpec(data: Uint8Array): TimeSpec {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n // data may be 32, 64, or 96 bits\n switch (data.byteLength) {\n case 4: {\n // timestamp 32 = { sec32 }\n const sec = view.getUint32(0);\n const nsec = 0;\n return { sec, nsec };\n }\n case 8: {\n // timestamp 64 = { nsec30, sec34 }\n const nsec30AndSecHigh2 = view.getUint32(0);\n const secLow32 = view.getUint32(4);\n const sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;\n const nsec = nsec30AndSecHigh2 >>> 2;\n return { sec, nsec };\n }\n case 12: {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n\n const sec = getInt64(view, 4);\n const nsec = view.getUint32(0);\n return { sec, nsec };\n }\n default:\n throw new DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);\n }\n}\n\nexport function decodeTimestampExtension(data: Uint8Array): Date {\n const timeSpec = decodeTimestampToTimeSpec(data);\n return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);\n}\n\nexport const timestampExtension = {\n type: EXT_TIMESTAMP,\n encode: encodeTimestampExtension,\n decode: decodeTimestampExtension,\n};\n", "// ExtensionCodec to handle MessagePack extensions\n\nimport { ExtData } from \"./ExtData.ts\";\nimport { timestampExtension } from \"./timestamp.ts\";\n\nexport type ExtensionDecoderType<ContextType> = (\n data: Uint8Array,\n extensionType: number,\n context: ContextType,\n) => unknown;\n\nexport type ExtensionEncoderType<ContextType> = (\n input: unknown,\n context: ContextType,\n) => Uint8Array | ((dataPos: number) => Uint8Array) | null;\n\n// immutable interface to ExtensionCodec\nexport type ExtensionCodecType<ContextType> = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __brand?: ContextType;\n tryToEncode(object: unknown, context: ContextType): ExtData | null;\n decode(data: Uint8Array, extType: number, context: ContextType): unknown;\n};\n\nexport class ExtensionCodec<ContextType = undefined> implements ExtensionCodecType<ContextType> {\n public static readonly defaultCodec: ExtensionCodecType<undefined> = new ExtensionCodec();\n\n // ensures ExtensionCodecType<X> matches ExtensionCodec<X>\n // this will make type errors a lot more clear\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __brand?: ContextType;\n\n // built-in extensions\n private readonly builtInEncoders: Array<ExtensionEncoderType<ContextType> | undefined | null> = [];\n private readonly builtInDecoders: Array<ExtensionDecoderType<ContextType> | undefined | null> = [];\n\n // custom extensions\n private readonly encoders: Array<ExtensionEncoderType<ContextType> | undefined | null> = [];\n private readonly decoders: Array<ExtensionDecoderType<ContextType> | undefined | null> = [];\n\n public constructor() {\n this.register(timestampExtension);\n }\n\n public register({\n type,\n encode,\n decode,\n }: {\n type: number;\n encode: ExtensionEncoderType<ContextType>;\n decode: ExtensionDecoderType<ContextType>;\n }): void {\n if (type >= 0) {\n // custom extensions\n this.encoders[type] = encode;\n this.decoders[type] = decode;\n } else {\n // built-in extensions\n const index = -1 - type;\n this.builtInEncoders[index] = encode;\n this.builtInDecoders[index] = decode;\n }\n }\n\n public tryToEncode(object: unknown, context: ContextType): ExtData | null {\n // built-in extensions\n for (let i = 0; i < this.builtInEncoders.length; i++) {\n const encodeExt = this.builtInEncoders[i];\n if (encodeExt != null) {\n const data = encodeExt(object, context);\n if (data != null) {\n const type = -1 - i;\n return new ExtData(type, data);\n }\n }\n }\n\n // custom extensions\n for (let i = 0; i < this.encoders.length; i++) {\n const encodeExt = this.encoders[i];\n if (encodeExt != null) {\n const data = encodeExt(object, context);\n if (data != null) {\n const type = i;\n return new ExtData(type, data);\n }\n }\n }\n\n if (object instanceof ExtData) {\n // to keep ExtData as is\n return object;\n }\n return null;\n }\n\n public decode(data: Uint8Array, type: number, context: ContextType): unknown {\n const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];\n if (decodeExt) {\n return decodeExt(data, type, context);\n } else {\n // decode() does not fail, returns ExtData instead.\n return new ExtData(type, data);\n }\n }\n}\n", "function isArrayBufferLike(buffer: unknown): buffer is ArrayBufferLike {\n return (\n buffer instanceof ArrayBuffer || (typeof SharedArrayBuffer !== \"undefined\" && buffer instanceof SharedArrayBuffer)\n );\n}\n\nexport function ensureUint8Array(\n buffer: ArrayLike<number> | Uint8Array<ArrayBufferLike> | ArrayBufferView | ArrayBufferLike,\n): Uint8Array<ArrayBufferLike> {\n if (buffer instanceof Uint8Array) {\n return buffer;\n } else if (ArrayBuffer.isView(buffer)) {\n return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n } else if (isArrayBufferLike(buffer)) {\n return new Uint8Array(buffer);\n } else {\n // ArrayLike<number>\n return Uint8Array.from(buffer);\n }\n}\n", "import { utf8Count, utf8Encode } from \"./utils/utf8.ts\";\nimport { ExtensionCodec, ExtensionCodecType } from \"./ExtensionCodec.ts\";\nimport { setInt64, setUint64 } from \"./utils/int.ts\";\nimport { ensureUint8Array } from \"./utils/typedArrays.ts\";\nimport type { ExtData } from \"./ExtData.ts\";\nimport type { ContextOf } from \"./context.ts\";\n\nexport const DEFAULT_MAX_DEPTH = 100;\nexport const DEFAULT_INITIAL_BUFFER_SIZE = 2048;\n\nexport type EncoderOptions<ContextType = undefined> = Partial<\n Readonly<{\n extensionCodec: ExtensionCodecType<ContextType>;\n\n /**\n * Encodes bigint as Int64 or Uint64 if it's set to true.\n * {@link forceIntegerToFloat} does not affect bigint.\n * Depends on ES2020's {@link DataView#setBigInt64} and\n * {@link DataView#setBigUint64}.\n *\n * Defaults to false.\n */\n useBigInt64: boolean;\n\n /**\n * The maximum depth in nested objects and arrays.\n *\n * Defaults to 100.\n */\n maxDepth: number;\n\n /**\n * The initial size of the internal buffer.\n *\n * Defaults to 2048.\n */\n initialBufferSize: number;\n\n /**\n * If `true`, the keys of an object is sorted. In other words, the encoded\n * binary is canonical and thus comparable to another encoded binary.\n *\n * Defaults to `false`. If enabled, it spends more time in encoding objects.\n */\n sortKeys: boolean;\n /**\n * If `true`, non-integer numbers are encoded in float32, not in float64 (the default).\n *\n * Only use it if precisions don't matter.\n *\n * Defaults to `false`.\n */\n forceFloat32: boolean;\n\n /**\n * If `true`, an object property with `undefined` value are ignored.\n * e.g. `{ foo: undefined }` will be encoded as `{}`, as `JSON.stringify()` does.\n *\n * Defaults to `false`. If enabled, it spends more time in encoding objects.\n */\n ignoreUndefined: boolean;\n\n /**\n * If `true`, integer numbers are encoded as floating point numbers,\n * with the `forceFloat32` option taken into account.\n *\n * Defaults to `false`.\n */\n forceIntegerToFloat: boolean;\n }>\n> &\n ContextOf<ContextType>;\n\nexport class Encoder<ContextType = undefined> {\n private readonly extensionCodec: ExtensionCodecType<ContextType>;\n private readonly context: ContextType;\n private readonly useBigInt64: boolean;\n private readonly maxDepth: number;\n private readonly initialBufferSize: number;\n private readonly sortKeys: boolean;\n private readonly forceFloat32: boolean;\n private readonly ignoreUndefined: boolean;\n private readonly forceIntegerToFloat: boolean;\n\n private pos: number;\n private view: DataView;\n private bytes: Uint8Array;\n\n private entered = false;\n\n public constructor(options?: EncoderOptions<ContextType>) {\n this.extensionCodec = options?.extensionCodec ?? (ExtensionCodec.defaultCodec as ExtensionCodecType<ContextType>);\n this.context = (options as { context: ContextType } | undefined)?.context as ContextType; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined\n\n this.useBigInt64 = options?.useBigInt64 ?? false;\n this.maxDepth = options?.maxDepth ?? DEFAULT_MAX_DEPTH;\n this.initialBufferSize = options?.initialBufferSize ?? DEFAULT_INITIAL_BUFFER_SIZE;\n this.sortKeys = options?.sortKeys ?? false;\n this.forceFloat32 = options?.forceFloat32 ?? false;\n this.ignoreUndefined = options?.ignoreUndefined ?? false;\n this.forceIntegerToFloat = options?.forceIntegerToFloat ?? false;\n\n this.pos = 0;\n this.view = new DataView(new ArrayBuffer(this.initialBufferSize));\n this.bytes = new Uint8Array(this.view.buffer);\n }\n\n private clone() {\n // Because of slightly special argument `context`,\n // type assertion is needed.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return new Encoder<ContextType>({\n extensionCodec: this.extensionCodec,\n context: this.context,\n useBigInt64: this.useBigInt64,\n maxDepth: this.maxDepth,\n initialBufferSize: this.initialBufferSize,\n sortKeys: this.sortKeys,\n forceFloat32: this.forceFloat32,\n ignoreUndefined: this.ignoreUndefined,\n forceIntegerToFloat: this.forceIntegerToFloat,\n } as any);\n }\n\n private reinitializeState() {\n this.pos = 0;\n }\n\n /**\n * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.\n *\n * @returns Encodes the object and returns a shared reference the encoder's internal buffer.\n */\n public encodeSharedRef(object: unknown): Uint8Array {\n if (this.entered) {\n const instance = this.clone();\n return instance.encodeSharedRef(object);\n }\n\n try {\n this.entered = true;\n\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.subarray(0, this.pos);\n } finally {\n this.entered = false;\n }\n }\n\n /**\n * @returns Encodes the object and returns a copy of the encoder's internal buffer.\n */\n public encode(object: unknown): Uint8Array {\n if (this.entered) {\n const instance = this.clone();\n return instance.encode(object);\n }\n\n try {\n this.entered = true;\n\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.slice(0, this.pos);\n } finally {\n this.entered = false;\n }\n }\n\n private doEncode(object: unknown, depth: number): void {\n if (depth > this.maxDepth) {\n throw new Error(`Too deep objects in depth ${depth}`);\n }\n\n if (object == null) {\n this.encodeNil();\n } else if (typeof object === \"boolean\") {\n this.encodeBoolean(object);\n } else if (typeof object === \"number\") {\n if (!this.forceIntegerToFloat) {\n this.encodeNumber(object);\n } else {\n this.encodeNumberAsFloat(object);\n }\n } else if (typeof object === \"string\") {\n this.encodeString(object);\n } else if (this.useBigInt64 && typeof object === \"bigint\") {\n this.encodeBigInt64(object);\n } else {\n this.encodeObject(object, depth);\n }\n }\n\n private ensureBufferSizeToWrite(sizeToWrite: number) {\n const requiredSize = this.pos + sizeToWrite;\n\n if (this.view.byteLength < requiredSize) {\n this.resizeBuffer(requiredSize * 2);\n }\n }\n\n private resizeBuffer(newSize: number) {\n const newBuffer = new ArrayBuffer(newSize);\n const newBytes = new Uint8Array(newBuffer);\n const newView = new DataView(newBuffer);\n\n newBytes.set(this.bytes);\n\n this.view = newView;\n this.bytes = newBytes;\n }\n\n private encodeNil() {\n this.writeU8(0xc0);\n }\n\n private encodeBoolean(object: boolean) {\n if (object === false) {\n this.writeU8(0xc2);\n } else {\n this.writeU8(0xc3);\n }\n }\n\n private encodeNumber(object: number): void {\n if (!this.forceIntegerToFloat && Number.isSafeInteger(object)) {\n if (object >= 0) {\n if (object < 0x80) {\n // positive fixint\n this.writeU8(object);\n } else if (object < 0x100) {\n // uint 8\n this.writeU8(0xcc);\n this.writeU8(object);\n } else if (object < 0x10000) {\n // uint 16\n this.writeU8(0xcd);\n this.writeU16(object);\n } else if (object < 0x100000000) {\n // uint 32\n this.writeU8(0xce);\n this.writeU32(object);\n } else if (!this.useBigInt64) {\n // uint 64\n this.writeU8(0xcf);\n this.writeU64(object);\n } else {\n this.encodeNumberAsFloat(object);\n }\n } else {\n if (object >= -0x20) {\n // negative fixint\n this.writeU8(0xe0 | (object + 0x20));\n } else if (object >= -0x80) {\n // int 8\n this.writeU8(0xd0);\n this.writeI8(object);\n } else if (object >= -0x8000) {\n // int 16\n this.writeU8(0xd1);\n this.writeI16(object);\n } else if (object >= -0x80000000) {\n // int 32\n this.writeU8(0xd2);\n this.writeI32(object);\n } else if (!this.useBigInt64) {\n // int 64\n this.writeU8(0xd3);\n this.writeI64(object);\n } else {\n this.encodeNumberAsFloat(object);\n }\n }\n } else {\n this.encodeNumberAsFloat(object);\n }\n }\n\n private encodeNumberAsFloat(object: number): void {\n if (this.forceFloat32) {\n // float 32\n this.writeU8(0xca);\n this.writeF32(object);\n } else {\n // float 64\n this.writeU8(0xcb);\n this.writeF64(object);\n }\n }\n\n private encodeBigInt64(object: bigint): void {\n if (object >= BigInt(0)) {\n // uint 64\n this.writeU8(0xcf);\n this.writeBigUint64(object);\n } else {\n // int 64\n this.writeU8(0xd3);\n this.writeBigInt64(object);\n }\n }\n\n private writeStringHeader(byteLength: number) {\n if (byteLength < 32) {\n // fixstr\n this.writeU8(0xa0 + byteLength);\n } else if (byteLength < 0x100) {\n // str 8\n this.writeU8(0xd9);\n this.writeU8(byteLength);\n } else if (byteLength < 0x10000) {\n // str 16\n this.writeU8(0xda);\n this.writeU16(byteLength);\n } else if (byteLength < 0x100000000) {\n // str 32\n this.writeU8(0xdb);\n this.writeU32(byteLength);\n } else {\n throw new Error(`Too long string: ${byteLength} bytes in UTF-8`);\n }\n }\n\n private encodeString(object: string) {\n const maxHeaderSize = 1 + 4;\n\n const byteLength = utf8Count(object);\n this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n this.writeStringHeader(byteLength);\n utf8Encode(object, this.bytes, this.pos);\n this.pos += byteLength;\n }\n\n private encodeObject(object: unknown, depth: number) {\n // try to encode objects with custom codec first of non-primitives\n const ext = this.extensionCodec.tryToEncode(object, this.context);\n if (ext != null) {\n this.encodeExtension(ext);\n } else if (Array.isArray(object)) {\n this.encodeArray(object, depth);\n } else if (ArrayBuffer.isView(object)) {\n this.encodeBinary(object);\n } else if (typeof object === \"object\") {\n this.encodeMap(object as Record<string, unknown>, depth);\n } else {\n // symbol, function and other special object come here unless extensionCodec handles them.\n throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`);\n }\n }\n\n private encodeBinary(object: ArrayBufferView) {\n const size = object.byteLength;\n if (size < 0x100) {\n // bin 8\n this.writeU8(0xc4);\n this.writeU8(size);\n } else if (size < 0x10000) {\n // bin 16\n this.writeU8(0xc5);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // bin 32\n this.writeU8(0xc6);\n this.writeU32(size);\n } else {\n throw new Error(`Too large binary: ${size}`);\n }\n const bytes = ensureUint8Array(object);\n this.writeU8a(bytes);\n }\n\n private encodeArray(object: Array<unknown>, depth: number) {\n const size = object.length;\n if (size < 16) {\n // fixarray\n this.writeU8(0x90 + size);\n } else if (size < 0x10000) {\n // array 16\n this.writeU8(0xdc);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // array 32\n this.writeU8(0xdd);\n this.writeU32(size);\n } else {\n throw new Error(`Too large array: ${size}`);\n }\n for (const item of object) {\n this.doEncode(item, depth + 1);\n }\n }\n\n private countWithoutUndefined(object: Record<string, unknown>, keys: ReadonlyArray<string>): number {\n let count = 0;\n\n for (const key of keys) {\n if (object[key] !== undefined) {\n count++;\n }\n }\n\n return count;\n }\n\n private encodeMap(object: Record<string, unknown>, depth: number) {\n const keys = Object.keys(object);\n if (this.sortKeys) {\n keys.sort();\n }\n\n const size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;\n\n if (size < 16) {\n // fixmap\n this.writeU8(0x80 + size);\n } else if (size < 0x10000) {\n // map 16\n this.writeU8(0xde);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // map 32\n this.writeU8(0xdf);\n this.writeU32(size);\n } else {\n throw new Error(`Too large map object: ${size}`);\n }\n\n for (const key of keys) {\n const value = object[key];\n\n if (!(this.ignoreUndefined && value === undefined)) {\n this.encodeString(key);\n this.doEncode(value, depth + 1);\n }\n }\n }\n\n private encodeExtension(ext: ExtData) {\n if (typeof ext.data === \"function\") {\n const data = ext.data(this.pos + 6);\n const size = data.length;\n\n if (size >= 0x100000000) {\n throw new Error(`Too large extension object: ${size}`);\n }\n\n this.writeU8(0xc9);\n this.writeU32(size);\n this.writeI8(ext.type);\n this.writeU8a(data);\n return;\n }\n\n const size = ext.data.length;\n if (size === 1) {\n // fixext 1\n this.writeU8(0xd4);\n } else if (size === 2) {\n // fixext 2\n this.writeU8(0xd5);\n } else if (size === 4) {\n // fixext 4\n this.writeU8(0xd6);\n } else if (size === 8) {\n // fixext 8\n this.writeU8(0xd7);\n } else if (size === 16) {\n // fixext 16\n this.writeU8(0xd8);\n } else if (size < 0x100) {\n // ext 8\n this.writeU8(0xc7);\n this.writeU8(size);\n } else if (size < 0x10000) {\n // ext 16\n this.writeU8(0xc8);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // ext 32\n this.writeU8(0xc9);\n this.writeU32(size);\n } else {\n throw new Error(`Too large extension object: ${size}`);\n }\n this.writeI8(ext.type);\n this.writeU8a(ext.data);\n }\n\n private writeU8(value: number) {\n this.ensureBufferSizeToWrite(1);\n\n this.view.setUint8(this.pos, value);\n this.pos++;\n }\n\n private writeU8a(values: ArrayLike<number>) {\n const size = values.length;\n this.ensureBufferSizeToWrite(size);\n\n this.bytes.set(values, this.pos);\n this.pos += size;\n }\n\n private writeI8(value: number) {\n this.ensureBufferSizeToWrite(1);\n\n this.view.setInt8(this.pos, value);\n this.pos++;\n }\n\n private writeU16(value: number) {\n this.ensureBufferSizeToWrite(2);\n\n this.view.setUint16(this.pos, value);\n this.pos += 2;\n }\n\n private writeI16(value: number) {\n this.ensureBufferSizeToWrite(2);\n\n this.view.setInt16(this.pos, value);\n this.pos += 2;\n }\n\n private writeU32(value: number) {\n this.ensureBufferSizeToWrite(4);\n\n this.view.setUint32(this.pos, value);\n this.pos += 4;\n }\n\n private writeI32(value: number) {\n this.ensureBufferSizeToWrite(4);\n\n this.view.setInt32(this.pos, value);\n this.pos += 4;\n }\n\n private writeF32(value: number) {\n this.ensureBufferSizeToWrite(4);\n\n this.view.setFloat32(this.pos, value);\n this.pos += 4;\n }\n\n private writeF64(value: number) {\n this.ensureBufferSizeToWrite(8);\n\n this.view.setFloat64(this.pos, value);\n this.pos += 8;\n }\n\n private writeU64(value: number) {\n this.ensureBufferSizeToWrite(8);\n\n setUint64(this.view, this.pos, value);\n this.pos += 8;\n }\n\n private writeI64(value: number) {\n this.ensureBufferSizeToWrite(8);\n\n setInt64(this.view, this.pos, value);\n this.pos += 8;\n }\n\n private writeBigUint64(value: bigint) {\n this.ensureBufferSizeToWrite(8);\n\n this.view.setBigUint64(this.pos, value);\n this.pos += 8;\n }\n\n private writeBigInt64(value: bigint) {\n this.ensureBufferSizeToWrite(8);\n\n this.view.setBigInt64(this.pos, value);\n this.pos += 8;\n }\n}\n", "import { Encoder } from \"./Encoder.ts\";\nimport type { EncoderOptions } from \"./Encoder.ts\";\nimport type { SplitUndefined } from \"./context.ts\";\n\n/**\n * It encodes `value` in the MessagePack format and\n * returns a byte buffer.\n *\n * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.\n */\nexport function encode<ContextType = undefined>(\n value: unknown,\n options?: EncoderOptions<SplitUndefined<ContextType>>,\n): Uint8Array {\n const encoder = new Encoder(options);\n return encoder.encodeSharedRef(value);\n}\n", "export function prettyByte(byte: number): string {\n return `${byte < 0 ? \"-\" : \"\"}0x${Math.abs(byte).toString(16).padStart(2, \"0\")}`;\n}\n", "import { utf8DecodeJs } from \"./utils/utf8.ts\";\n\nconst DEFAULT_MAX_KEY_LENGTH = 16;\nconst DEFAULT_MAX_LENGTH_PER_KEY = 16;\n\nexport interface KeyDecoder {\n canBeCached(byteLength: number): boolean;\n decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string;\n}\ninterface KeyCacheRecord {\n readonly bytes: Uint8Array;\n readonly str: string;\n}\n\nexport class CachedKeyDecoder implements KeyDecoder {\n hit = 0;\n miss = 0;\n private readonly caches: Array<Array<KeyCacheRecord>>;\n private readonly maxKeyLength: number;\n private readonly maxLengthPerKey: number;\n\n constructor(maxKeyLength = DEFAULT_MAX_KEY_LENGTH, maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY) {\n this.maxKeyLength = maxKeyLength;\n this.maxLengthPerKey = maxLengthPerKey;\n\n // avoid `new Array(N)`, which makes a sparse array,\n // because a sparse array is typically slower than a non-sparse array.\n this.caches = [];\n for (let i = 0; i < this.maxKeyLength; i++) {\n this.caches.push([]);\n }\n }\n\n public canBeCached(byteLength: number): boolean {\n return byteLength > 0 && byteLength <= this.maxKeyLength;\n }\n\n private find(bytes: Uint8Array, inputOffset: number, byteLength: number): string | null {\n const records = this.caches[byteLength - 1]!;\n\n FIND_CHUNK: for (const record of records) {\n const recordBytes = record.bytes;\n\n for (let j = 0; j < byteLength; j++) {\n if (recordBytes[j] !== bytes[inputOffset + j]) {\n continue FIND_CHUNK;\n }\n }\n return record.str;\n }\n return null;\n }\n\n private store(bytes: Uint8Array, value: string) {\n const records = this.caches[bytes.length - 1]!;\n const record: KeyCacheRecord = { bytes, str: value };\n\n if (records.length >= this.maxLengthPerKey) {\n // `records` are full!\n // Set `record` to an arbitrary position.\n records[(Math.random() * records.length) | 0] = record;\n } else {\n records.push(record);\n }\n }\n\n public decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n const cachedValue = this.find(bytes, inputOffset, byteLength);\n if (cachedValue != null) {\n this.hit++;\n return cachedValue;\n }\n this.miss++;\n\n const str = utf8DecodeJs(bytes, inputOffset, byteLength);\n // Ensure to copy a slice of bytes because the bytes may be a NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.\n const slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);\n this.store(slicedCopyOfBytes, str);\n return str;\n }\n}\n", "import { prettyByte } from \"./utils/prettyByte.ts\";\nimport { ExtensionCodec, ExtensionCodecType } from \"./ExtensionCodec.ts\";\nimport { getInt64, getUint64, UINT32_MAX } from \"./utils/int.ts\";\nimport { utf8Decode } from \"./utils/utf8.ts\";\nimport { ensureUint8Array } from \"./utils/typedArrays.ts\";\nimport { CachedKeyDecoder, KeyDecoder } from \"./CachedKeyDecoder.ts\";\nimport { DecodeError } from \"./DecodeError.ts\";\nimport type { ContextOf } from \"./context.ts\";\n\nexport type DecoderOptions<ContextType = undefined> = Readonly<\n Partial<{\n extensionCodec: ExtensionCodecType<ContextType>;\n\n /**\n * Decodes Int64 and Uint64 as bigint if it's set to true.\n * Depends on ES2020's {@link DataView#getBigInt64} and\n * {@link DataView#getBigUint64}.\n *\n * Defaults to false.\n */\n useBigInt64: boolean;\n\n /**\n * By default, string values will be decoded as UTF-8 strings. However, if this option is true,\n * string values will be returned as Uint8Arrays without additional decoding.\n *\n * This is useful if the strings may contain invalid UTF-8 sequences.\n *\n * Note that this option only applies to string values, not map keys. Additionally, when\n * enabled, raw string length is limited by the maxBinLength option.\n */\n rawStrings: boolean;\n\n /**\n * Maximum string length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxStrLength: number;\n /**\n * Maximum binary length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxBinLength: number;\n /**\n * Maximum array length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxArrayLength: number;\n /**\n * Maximum map length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxMapLength: number;\n /**\n * Maximum extension length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxExtLength: number;\n\n /**\n * An object key decoder. Defaults to the shared instance of {@link CachedKeyDecoder}.\n * `null` is a special value to disable the use of the key decoder at all.\n */\n keyDecoder: KeyDecoder | null;\n\n /**\n * A function to convert decoded map key to a valid JS key type.\n * \n * Defaults to a function that throws an error if the key is not a string or a number.\n */\n mapKeyConverter: (key: unknown) => MapKeyType;\n }>\n> &\n ContextOf<ContextType>;\n\nconst STATE_ARRAY = \"array\";\nconst STATE_MAP_KEY = \"map_key\";\nconst STATE_MAP_VALUE = \"map_value\";\n\ntype MapKeyType = string | number;\n\nconst mapKeyConverter = (key: unknown): MapKeyType => {\n if (typeof key === \"string\" || typeof key === \"number\") {\n return key;\n }\n throw new DecodeError(\"The type of key must be string or number but \" + typeof key);\n};\n\ntype StackMapState = {\n type: typeof STATE_MAP_KEY | typeof STATE_MAP_VALUE;\n size: number;\n key: MapKeyType | null;\n readCount: number;\n map: Record<string, unknown>;\n};\n\ntype StackArrayState = {\n type: typeof STATE_ARRAY;\n size: number;\n array: Array<unknown>;\n position: number;\n};\n\nclass StackPool {\n private readonly stack: Array<StackState> = [];\n private stackHeadPosition = -1;\n\n public get length(): number {\n return this.stackHeadPosition + 1;\n }\n\n public top(): StackState | undefined {\n return this.stack[this.stackHeadPosition];\n }\n\n public pushArrayState(size: number) {\n const state = this.getUninitializedStateFromPool() as StackArrayState;\n\n state.type = STATE_ARRAY;\n state.position = 0;\n state.size = size;\n state.array = new Array(size);\n }\n\n public pushMapState(size: number) {\n const state = this.getUninitializedStateFromPool() as StackMapState;\n\n state.type = STATE_MAP_KEY;\n state.readCount = 0;\n state.size = size;\n state.map = {};\n }\n\n private getUninitializedStateFromPool() {\n this.stackHeadPosition++;\n\n if (this.stackHeadPosition === this.stack.length) {\n const partialState: Partial<StackState> = {\n type: undefined,\n size: 0,\n array: undefined,\n position: 0,\n readCount: 0,\n map: undefined,\n key: null,\n };\n\n this.stack.push(partialState as StackState);\n }\n\n return this.stack[this.stackHeadPosition];\n }\n\n public release(state: StackState): void {\n const topStackState = this.stack[this.stackHeadPosition];\n\n if (topStackState !== state) {\n throw new Error(\"Invalid stack state. Released state is not on top of the stack.\");\n }\n\n if (state.type === STATE_ARRAY) {\n const partialState = state as Partial<StackArrayState>;\n partialState.size = 0;\n partialState.array = undefined;\n partialState.position = 0;\n partialState.type = undefined;\n }\n\n if (state.type === STATE_MAP_KEY || state.type === STATE_MAP_VALUE) {\n const partialState = state as Partial<StackMapState>;\n partialState.size = 0;\n partialState.map = undefined;\n partialState.readCount = 0;\n partialState.type = undefined;\n }\n\n this.stackHeadPosition--;\n }\n\n public reset(): void {\n this.stack.length = 0;\n this.stackHeadPosition = -1;\n }\n}\n\ntype StackState = StackArrayState | StackMapState;\n\nconst HEAD_BYTE_REQUIRED = -1;\n\nconst EMPTY_VIEW = new DataView<ArrayBufferLike>(new ArrayBuffer(0));\nconst EMPTY_BYTES = new Uint8Array<ArrayBufferLike>(EMPTY_VIEW.buffer);\n\ntry {\n // IE11: The spec says it should throw RangeError,\n // IE11: but in IE11 it throws TypeError.\n EMPTY_VIEW.getInt8(0);\n} catch (e) {\n if (!(e instanceof RangeError)) {\n throw new Error(\n \"This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access\",\n );\n }\n}\n\nconst MORE_DATA = new RangeError(\"Insufficient data\");\n\nconst sharedCachedKeyDecoder = new CachedKeyDecoder();\n\nexport class Decoder<ContextType = undefined> {\n private readonly extensionCodec: ExtensionCodecType<ContextType>;\n private readonly context: ContextType;\n private readonly useBigInt64: boolean;\n private readonly rawStrings: boolean;\n private readonly maxStrLength: number;\n private readonly maxBinLength: number;\n private readonly maxArrayLength: number;\n private readonly maxMapLength: number;\n private readonly maxExtLength: number;\n private readonly keyDecoder: KeyDecoder | null;\n private readonly mapKeyConverter: (key: unknown) => MapKeyType;\n\n private totalPos = 0;\n private pos = 0;\n\n private view = EMPTY_VIEW;\n private bytes = EMPTY_BYTES;\n private headByte = HEAD_BYTE_REQUIRED;\n private readonly stack = new StackPool();\n\n private entered = false;\n\n public constructor(options?: DecoderOptions<ContextType>) {\n this.extensionCodec = options?.extensionCodec ?? (ExtensionCodec.defaultCodec as ExtensionCodecType<ContextType>);\n this.context = (options as { context: ContextType } | undefined)?.context as ContextType; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined\n\n this.useBigInt64 = options?.useBigInt64 ?? false;\n this.rawStrings = options?.rawStrings ?? false;\n this.maxStrLength = options?.maxStrLength ?? UINT32_MAX;\n this.maxBinLength = options?.maxBinLength ?? UINT32_MAX;\n this.maxArrayLength = options?.maxArrayLength ?? UINT32_MAX;\n this.maxMapLength = options?.maxMapLength ?? UINT32_MAX;\n this.maxExtLength = options?.maxExtLength ?? UINT32_MAX;\n this.keyDecoder = options?.keyDecoder !== undefined ? options.keyDecoder : sharedCachedKeyDecoder;\n this.mapKeyConverter = options?.mapKeyConverter ?? mapKeyConverter;\n }\n\n private clone(): Decoder<ContextType> {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return new Decoder({\n extensionCodec: this.extensionCodec,\n context: this.context,\n useBigInt64: this.useBigInt64,\n rawStrings: this.rawStrings,\n maxStrLength: this.maxStrLength,\n maxBinLength: this.maxBinLength,\n maxArrayLength: this.maxArrayLength,\n maxMapLength: this.maxMapLength,\n maxExtLength: this.maxExtLength,\n keyDecoder: this.keyDecoder,\n } as any);\n }\n\n private reinitializeState() {\n this.totalPos = 0;\n this.headByte = HEAD_BYTE_REQUIRED;\n this.stack.reset();\n\n // view, bytes, and pos will be re-initialized in setBuffer()\n }\n\n private setBuffer(buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike): void {\n const bytes = ensureUint8Array(buffer);\n this.bytes = bytes;\n this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n this.pos = 0;\n }\n\n private appendBuffer(buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike): void {\n if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {\n this.setBuffer(buffer);\n } else {\n const remainingData = this.bytes.subarray(this.pos);\n const newData = ensureUint8Array(buffer);\n\n // concat remainingData + newData\n const newBuffer = new Uint8Array(remainingData.length + newData.length);\n newBuffer.set(remainingData);\n newBuffer.set(newData, remainingData.length);\n this.setBuffer(newBuffer);\n }\n }\n\n private hasRemaining(size: number) {\n return this.view.byteLength - this.pos >= size;\n }\n\n private createExtraByteError(posToShow: number): Error {\n const { view, pos } = this;\n return new RangeError(`Extra ${view.byteLength - pos} of ${view.byteLength} byte(s) found at buffer[${posToShow}]`);\n }\n\n /**\n * @throws {@link DecodeError}\n * @throws {@link RangeError}\n */\n public decode(buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike): unknown {\n if (this.entered) {\n const instance = this.clone();\n return instance.decode(buffer);\n }\n\n try {\n this.entered = true;\n\n this.reinitializeState();\n this.setBuffer(buffer);\n\n const object = this.doDecodeSync();\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.pos);\n }\n return object;\n } finally {\n this.entered = false;\n }\n }\n\n public *decodeMulti(buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike): Generator<unknown, void, unknown> {\n if (this.entered) {\n const instance = this.clone();\n yield* instance.decodeMulti(buffer);\n return;\n }\n\n try {\n this.entered = true;\n\n this.reinitializeState();\n this.setBuffer(buffer);\n\n while (this.hasRemaining(1)) {\n yield this.doDecodeSync();\n }\n } finally {\n this.entered = false;\n }\n }\n\n public async decodeAsync(stream: AsyncIterable<ArrayLike<number> | ArrayBufferView | ArrayBufferLike>): Promise<unknown> {\n if (this.entered) {\n const instance = this.clone();\n return instance.decodeAsync(stream);\n }\n\n try {\n this.entered = true;\n\n let decoded = false;\n let object: unknown;\n for await (const buffer of stream) {\n if (decoded) {\n this.entered = false;\n throw this.createExtraByteError(this.totalPos);\n }\n\n this.appendBuffer(buffer);\n\n try {\n object = this.doDecodeSync();\n decoded = true;\n } catch (e) {\n if (!(e instanceof RangeError)) {\n throw e; // rethrow\n }\n // fallthrough\n }\n this.totalPos += this.pos;\n }\n\n if (decoded) {\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.totalPos);\n }\n return object;\n }\n\n const { headByte, pos, totalPos } = this;\n throw new RangeError(\n `Insufficient data in parsing ${prettyByte(headByte)} at ${totalPos} (${pos} in the current buffer)`,\n );\n } finally {\n this.entered = false;\n }\n }\n\n public decodeArrayStream(\n stream: AsyncIterable<ArrayLike<number> | ArrayBufferView | ArrayBufferLike>,\n ): AsyncGenerator<unknown, void, unknown> {\n return this.decodeMultiAsync(stream, true);\n }\n\n public decodeStream(stream: AsyncIterable<ArrayLike<number> | ArrayBufferView | ArrayBufferLike>): AsyncGenerator<unknown, void, unknown> {\n return this.decodeMultiAsync(stream, false);\n }\n\n private async *decodeMultiAsync(stream: AsyncIterable<ArrayLike<number> | ArrayBufferView | ArrayBufferLike>, isArray: boolean): AsyncGenerator<unknown, void, unknown> {\n if (this.entered) {\n const instance = this.clone();\n yield* instance.decodeMultiAsync(stream, isArray);\n return;\n }\n\n try {\n this.entered = true;\n\n let isArrayHeaderRequired = isArray;\n let arrayItemsLeft = -1;\n\n for await (const buffer of stream) {\n if (isArray && arrayItemsLeft === 0) {\n throw this.createExtraByteError(this.totalPos);\n }\n\n this.appendBuffer(buffer);\n\n if (isArrayHeaderRequired) {\n arrayItemsLeft = this.readArraySize();\n isArrayHeaderRequired = false;\n this.complete();\n }\n\n try {\n while (true) {\n yield this.doDecodeSync();\n if (--arrayItemsLeft === 0) {\n break;\n }\n }\n } catch (e) {\n if (!(e instanceof RangeError)) {\n throw e; // rethrow\n }\n // fallthrough\n }\n this.totalPos += this.pos;\n }\n } finally {\n this.entered = false;\n }\n }\n\n private doDecodeSync(): unknown {\n DECODE: while (true) {\n const headByte = this.readHeadByte();\n let object: unknown;\n\n if (headByte >= 0xe0) {\n // negative fixint (111x xxxx) 0xe0 - 0xff\n object = headByte - 0x100;\n } else if (headByte < 0xc0) {\n if (headByte < 0x80) {\n // positive fixint (0xxx xxxx) 0x00 - 0x7f\n object = headByte;\n } else if (headByte < 0x90) {\n // fixmap (1000 xxxx) 0x80 - 0x8f\n const size = headByte - 0x80;\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte < 0xa0) {\n // fixarray (1001 xxxx) 0x90 - 0x9f\n const size = headByte - 0x90;\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else {\n // fixstr (101x xxxx) 0xa0 - 0xbf\n const byteLength = headByte - 0xa0;\n object = this.decodeString(byteLength, 0);\n }\n } else if (headByte === 0xc0) {\n // nil\n object = null;\n } else if (headByte === 0xc2) {\n // false\n object = false;\n } else if (headByte === 0xc3) {\n // true\n object = true;\n } else if (headByte === 0xca) {\n // float 32\n object = this.readF32();\n } else if (headByte === 0xcb) {\n // float 64\n object = this.readF64();\n } else if (headByte === 0xcc) {\n // uint 8\n object = this.readU8();\n } else if (headByte === 0xcd) {\n // uint 16\n object = this.readU16();\n } else if (headByte === 0xce) {\n // uint 32\n object = this.readU32();\n } else if (headByte === 0xcf) {\n // uint 64\n if (this.useBigInt64) {\n object = this.readU64AsBigInt();\n } else {\n object = this.readU64();\n }\n } else if (headByte === 0xd0) {\n // int 8\n object = this.readI8();\n } else if (headByte === 0xd1) {\n // int 16\n object = this.readI16();\n } else if (headByte === 0xd2) {\n // int 32\n object = this.readI32();\n } else if (headByte === 0xd3) {\n // int 64\n if (this.useBigInt64) {\n object = this.readI64AsBigInt();\n } else {\n object = this.readI64();\n }\n } else if (headByte === 0xd9) {\n // str 8\n const byteLength = this.lookU8();\n object = this.decodeString(byteLength, 1);\n } else if (headByte === 0xda) {\n // str 16\n const byteLength = this.lookU16();\n object = this.decodeString(byteLength, 2);\n } else if (headByte === 0xdb) {\n // str 32\n const byteLength = this.lookU32();\n object = this.decodeString(byteLength, 4);\n } else if (headByte === 0xdc) {\n // array 16\n const size = this.readU16();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else if (headByte === 0xdd) {\n // array 32\n const size = this.readU32();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else if (headByte === 0xde) {\n // map 16\n const size = this.readU16();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte === 0xdf) {\n // map 32\n const size = this.readU32();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte === 0xc4) {\n // bin 8\n const size = this.lookU8();\n object = this.decodeBinary(size, 1);\n } else if (headByte === 0xc5) {\n // bin 16\n const size = this.lookU16();\n object = this.decodeBinary(size, 2);\n } else if (headByte === 0xc6) {\n // bin 32\n const size = this.lookU32();\n object = this.decodeBinary(size, 4);\n } else if (headByte === 0xd4) {\n // fixext 1\n object = this.decodeExtension(1, 0);\n } else if (headByte === 0xd5) {\n // fixext 2\n object = this.decodeExtension(2, 0);\n } else if (headByte === 0xd6) {\n // fixext 4\n object = this.decodeExtension(4, 0);\n } else if (headByte === 0xd7) {\n // fixext 8\n object = this.decodeExtension(8, 0);\n } else if (headByte === 0xd8) {\n // fixext 16\n object = this.decodeExtension(16, 0);\n } else if (headByte === 0xc7) {\n // ext 8\n const size = this.lookU8();\n object = this.decodeExtension(size, 1);\n } else if (headByte === 0xc8) {\n // ext 16\n const size = this.lookU16();\n object = this.decodeExtension(size, 2);\n } else if (headByte === 0xc9) {\n // ext 32\n const size = this.lookU32();\n object = this.decodeExtension(size, 4);\n } else {\n throw new DecodeError(`Unrecognized type byte: ${prettyByte(headByte)}`);\n }\n\n this.complete();\n\n const stack = this.stack;\n while (stack.length > 0) {\n // arrays and maps\n const state = stack.top()!;\n if (state.type === STATE_ARRAY) {\n state.array[state.position] = object;\n state.position++;\n if (state.position === state.size) {\n object = state.array;\n stack.release(state);\n } else {\n continue DECODE;\n }\n } else if (state.type === STATE_MAP_KEY) {\n if (object === \"__proto__\") {\n throw new DecodeError(\"The key __proto__ is not allowed\");\n }\n\n state.key = this.mapKeyConverter(object);\n state.type = STATE_MAP_VALUE;\n continue DECODE;\n } else {\n // it must be `state.type === State.MAP_VALUE` here\n\n state.map[state.key!] = object;\n state.readCount++;\n\n if (state.readCount === state.size) {\n object = state.map;\n stack.release(state);\n } else {\n state.key = null;\n state.type = STATE_MAP_KEY;\n continue DECODE;\n }\n }\n }\n\n return object;\n }\n }\n\n private readHeadByte(): number {\n if (this.headByte === HEAD_BYTE_REQUIRED) {\n this.headByte = this.readU8();\n // console.log(\"headByte\", prettyByte(this.headByte));\n }\n\n return this.headByte;\n }\n\n private complete(): void {\n this.headByte = HEAD_BYTE_REQUIRED;\n }\n\n private readArraySize(): number {\n const headByte = this.readHeadByte();\n\n switch (headByte) {\n case 0xdc:\n return this.readU16();\n case 0xdd:\n return this.readU32();\n default: {\n if (headByte < 0xa0) {\n return headByte - 0x90;\n } else {\n throw new DecodeError(`Unrecognized array type byte: ${prettyByte(headByte)}`);\n }\n }\n }\n }\n\n private pushMapState(size: number) {\n if (size > this.maxMapLength) {\n throw new DecodeError(`Max length exceeded: map length (${size}) > maxMapLengthLength (${this.maxMapLength})`);\n }\n\n this.stack.pushMapState(size);\n }\n\n private pushArrayState(size: number) {\n if (size > this.maxArrayLength) {\n throw new DecodeError(`Max length exceeded: array length (${size}) > maxArrayLength (${this.maxArrayLength})`);\n }\n\n this.stack.pushArrayState(size);\n }\n\n private decodeString(byteLength: number, headerOffset: number): string | Uint8Array {\n if (!this.rawStrings || this.stateIsMapKey()) {\n return this.decodeUtf8String(byteLength, headerOffset);\n }\n return this.decodeBinary(byteLength, headerOffset);\n }\n\n /**\n * @throws {@link RangeError}\n */\n private decodeUtf8String(byteLength: number, headerOffset: number): string {\n if (byteLength > this.maxStrLength) {\n throw new DecodeError(\n `Max length exceeded: UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`,\n );\n }\n\n if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {\n throw MORE_DATA;\n }\n\n const offset = this.pos + headerOffset;\n let object: string;\n if (this.stateIsMapKey() && this.keyDecoder?.canBeCached(byteLength)) {\n object = this.keyDecoder.decode(this.bytes, offset, byteLength);\n } else {\n object = utf8Decode(this.bytes, offset, byteLength);\n }\n this.pos += headerOffset + byteLength;\n return object;\n }\n\n private stateIsMapKey(): boolean {\n if (this.stack.length > 0) {\n const state = this.stack.top()!;\n return state.type === STATE_MAP_KEY;\n }\n return false;\n }\n\n /**\n * @throws {@link RangeError}\n */\n private decodeBinary(byteLength: number, headOffset: number): Uint8Array {\n if (byteLength > this.maxBinLength) {\n throw new DecodeError(`Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`);\n }\n\n if (!this.hasRemaining(byteLength + headOffset)) {\n throw MORE_DATA;\n }\n\n const offset = this.pos + headOffset;\n const object = this.bytes.subarray(offset, offset + byteLength);\n this.pos += headOffset + byteLength;\n return object;\n }\n\n private decodeExtension(size: number, headOffset: number): unknown {\n if (size > this.maxExtLength) {\n throw new DecodeError(`Max length exceeded: ext length (${size}) > maxExtLength (${this.maxExtLength})`);\n }\n\n const extType = this.view.getInt8(this.pos + headOffset);\n const data = this.decodeBinary(size, headOffset + 1 /* extType */);\n return this.extensionCodec.decode(data, extType, this.context);\n }\n\n private lookU8() {\n return this.view.getUint8(this.pos);\n }\n\n private lookU16() {\n return this.view.getUint16(this.pos);\n }\n\n private lookU32() {\n return this.view.getUint32(this.pos);\n }\n\n private readU8(): number {\n const value = this.view.getUint8(this.pos);\n this.pos++;\n return value;\n }\n\n private readI8(): number {\n const value = this.view.getInt8(this.pos);\n this.pos++;\n return value;\n }\n\n private readU16(): number {\n const value = this.view.getUint16(this.pos);\n this.pos += 2;\n return value;\n }\n\n private readI16(): number {\n const value = this.view.getInt16(this.pos);\n this.pos += 2;\n return value;\n }\n\n private readU32(): number {\n const value = this.view.getUint32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readI32(): number {\n const value = this.view.getInt32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readU64(): number {\n const value = getUint64(this.view, this.pos);\n this.pos += 8;\n return value;\n }\n\n private readI64(): number {\n const value = getInt64(this.view, this.pos);\n this.pos += 8;\n return value;\n }\n\n private readU64AsBigInt(): bigint {\n const value = this.view.getBigUint64(this.pos);\n this.pos += 8;\n return value;\n }\n\n private readI64AsBigInt(): bigint {\n const value = this.view.getBigInt64(this.pos);\n this.pos += 8;\n return value;\n }\n\n private readF32() {\n const value = this.view.getFloat32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readF64() {\n const value = this.view.getFloat64(this.pos);\n this.pos += 8;\n return value;\n }\n}\n", "import { Decoder } from \"./Decoder.ts\";\nimport type { DecoderOptions } from \"./Decoder.ts\";\nimport type { SplitUndefined } from \"./context.ts\";\n\n/**\n * It decodes a single MessagePack object in a buffer.\n *\n * This is a synchronous decoding function.\n * See other variants for asynchronous decoding: {@link decodeAsync}, {@link decodeStream}, or {@link decodeArrayStream}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decode<ContextType = undefined>(\n buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): unknown {\n const decoder = new Decoder(options);\n return decoder.decode(buffer);\n}\n\n/**\n * It decodes multiple MessagePack objects in a buffer.\n * This is corresponding to {@link decodeMultiStream}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMulti<ContextType = undefined>(\n buffer: ArrayLike<number> | BufferSource,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): Generator<unknown, void, unknown> {\n const decoder = new Decoder(options);\n return decoder.decodeMulti(buffer);\n}\n", "// utility for whatwg streams\n\n// The living standard of whatwg streams says\n// ReadableStream is also AsyncIterable, but\n// as of June 2019, no browser implements it.\n// See https://streams.spec.whatwg.org/ for details\nexport type ReadableStreamLike<T> = AsyncIterable<T> | ReadableStream<T>;\n\nexport function isAsyncIterable<T>(object: ReadableStreamLike<T>): object is AsyncIterable<T> {\n return (object as any)[Symbol.asyncIterator] != null;\n}\n\nexport async function* asyncIterableFromStream<T>(stream: ReadableStream<T>): AsyncIterable<T> {\n const reader = stream.getReader();\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nexport function ensureAsyncIterable<T>(streamLike: ReadableStreamLike<T>): AsyncIterable<T> {\n if (isAsyncIterable(streamLike)) {\n return streamLike;\n } else {\n return asyncIterableFromStream(streamLike);\n }\n}\n", "import { Decoder } from \"./Decoder.ts\";\nimport { ensureAsyncIterable } from \"./utils/stream.ts\";\nimport type { DecoderOptions } from \"./Decoder.ts\";\nimport type { ReadableStreamLike } from \"./utils/stream.ts\";\nimport type { SplitUndefined } from \"./context.ts\";\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport async function decodeAsync<ContextType = undefined>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): Promise<unknown> {\n const stream = ensureAsyncIterable(streamLike);\n const decoder = new Decoder(options);\n return decoder.decodeAsync(stream);\n}\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeArrayStream<ContextType>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): AsyncGenerator<unknown, void, unknown> {\n const stream = ensureAsyncIterable(streamLike);\n const decoder = new Decoder(options);\n return decoder.decodeArrayStream(stream);\n}\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMultiStream<ContextType>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): AsyncGenerator<unknown, void, unknown> {\n const stream = ensureAsyncIterable(streamLike);\n const decoder = new Decoder(options);\n return decoder.decodeStream(stream);\n}\n", "// Main Functions:\n\nimport { encode } from \"./encode.ts\";\nexport { encode };\n\nimport { decode, decodeMulti } from \"./decode.ts\";\nexport { decode, decodeMulti };\n\nimport { decodeAsync, decodeArrayStream, decodeMultiStream } from \"./decodeAsync.ts\";\nexport { decodeAsync, decodeArrayStream, decodeMultiStream };\n\nimport { Decoder } from \"./Decoder.ts\";\nexport { Decoder };\nimport type { DecoderOptions } from \"./Decoder.ts\";\nexport type { DecoderOptions };\nimport { DecodeError } from \"./DecodeError.ts\";\nexport { DecodeError };\n\nimport { Encoder } from \"./Encoder.ts\";\nexport { Encoder };\nimport type { EncoderOptions } from \"./Encoder.ts\";\nexport type { EncoderOptions };\n\n// Utilities for Extension Types:\n\nimport { ExtensionCodec } from \"./ExtensionCodec.ts\";\nexport { ExtensionCodec };\nimport type { ExtensionCodecType, ExtensionDecoderType, ExtensionEncoderType } from \"./ExtensionCodec.ts\";\nexport type { ExtensionCodecType, ExtensionDecoderType, ExtensionEncoderType };\nimport { ExtData } from \"./ExtData.ts\";\nexport { ExtData };\n\nimport {\n EXT_TIMESTAMP,\n encodeDateToTimeSpec,\n encodeTimeSpecToTimestamp,\n decodeTimestampToTimeSpec,\n encodeTimestampExtension,\n decodeTimestampExtension,\n} from \"./timestamp.ts\";\nexport {\n EXT_TIMESTAMP,\n encodeDateToTimeSpec,\n encodeTimeSpecToTimestamp,\n decodeTimestampToTimeSpec,\n encodeTimestampExtension,\n decodeTimestampExtension,\n};\n", "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction valueEnumerable(value) {\n return { enumerable: true, value };\n}\n\nfunction valueEnumerableWritable(value) {\n return { enumerable: true, writable: true, value };\n}\n\nlet d = {};\nlet truthy = () => true;\nlet empty = () => ({});\nlet identity = a => a;\nlet callBoth = (par, fn, self, args) => par.apply(self, args) && fn.apply(self, args);\nlet callForward = (par, fn, self, [a, b]) => fn.call(self, par.call(self, a, b), b);\nlet create = (a, b) => Object.freeze(Object.create(a, b));\n\nfunction stack(fns, def, caller) {\n return fns.reduce((par, fn) => {\n return function(...args) {\n return caller(par, fn, this, args);\n };\n }, def);\n}\n\nfunction fnType(fn) {\n return create(this, { fn: valueEnumerable(fn) });\n}\n\nlet reduceType = {};\nlet reduce = fnType.bind(reduceType);\nlet action = fn => reduce((ctx, ev) => !!~fn(ctx, ev) && ctx);\n\nlet guardType = {};\nlet guard = fnType.bind(guardType);\n\nfunction filter(Type, arr) {\n return arr.filter(value => Type.isPrototypeOf(value));\n}\n\nfunction makeTransition(from, to, ...args) {\n let guards = stack(filter(guardType, args).map(t => t.fn), truthy, callBoth);\n let reducers = stack(filter(reduceType, args).map(t => t.fn), identity, callForward);\n return create(this, {\n from: valueEnumerable(from),\n to: valueEnumerable(to),\n guards: valueEnumerable(guards),\n reducers: valueEnumerable(reducers)\n });\n}\n\nlet transitionType = {};\nlet immediateType = {};\nlet transition = makeTransition.bind(transitionType);\nlet immediate = makeTransition.bind(immediateType, null);\n\nfunction enterImmediate(machine, service, event) {\n return transitionTo(service, machine, event, this.immediates) || machine;\n}\n\nfunction transitionsToMap(transitions) {\n let m = new Map();\n for(let t of transitions) {\n if(!m.has(t.from)) m.set(t.from, []);\n m.get(t.from).push(t);\n }\n return m;\n}\n\nlet stateType = { enter: identity };\nfunction state(...args) {\n let transitions = filter(transitionType, args);\n let immediates = filter(immediateType, args);\n let desc = {\n final: valueEnumerable(args.length === 0),\n transitions: valueEnumerable(transitionsToMap(transitions))\n };\n if(immediates.length) {\n desc.immediates = valueEnumerable(immediates);\n desc.enter = valueEnumerable(enterImmediate);\n }\n return create(stateType, desc);\n}\n\nlet invokeFnType = {\n enter(machine2, service, event) {\n let rn = this.fn.call(service, service.context, event);\n if(machine.isPrototypeOf(rn))\n return create(invokeMachineType, {\n machine: valueEnumerable(rn),\n transitions: valueEnumerable(this.transitions)\n }).enter(machine2, service, event)\n rn.then(data => service.send({ type: 'done', data }))\n .catch(error => service.send({ type: 'error', error }));\n return machine2;\n }\n};\nlet invokeMachineType = {\n enter(machine, service, event) {\n service.child = interpret(this.machine, s => {\n service.onChange(s);\n if(service.child == s && s.machine.state.value.final) {\n delete service.child;\n service.send({ type: 'done', data: s.context });\n }\n }, service.context, event);\n if(service.child.machine.state.value.final) {\n let data = service.child.context;\n delete service.child;\n return transitionTo(service, machine, { type: 'done', data }, this.transitions.get('done'));\n }\n return machine;\n }\n};\nfunction invoke(fn, ...transitions) {\n let t = valueEnumerable(transitionsToMap(transitions));\n return machine.isPrototypeOf(fn) ?\n create(invokeMachineType, {\n machine: valueEnumerable(fn),\n transitions: t\n }) :\n create(invokeFnType, {\n fn: valueEnumerable(fn),\n transitions: t\n });\n}\n\nlet machine = {\n get state() {\n return {\n name: this.current,\n value: this.states[this.current]\n };\n }\n};\n\nfunction createMachine(current, states, contextFn = empty) {\n if(typeof current !== 'string') {\n contextFn = states || empty;\n states = current;\n current = Object.keys(states)[0];\n }\n if(d._create) d._create(current, states);\n return create(machine, {\n context: valueEnumerable(contextFn),\n current: valueEnumerable(current),\n states: valueEnumerable(states)\n });\n}\n\nfunction transitionTo(service, machine, fromEvent, candidates) {\n let { context } = service;\n for(let { to, guards, reducers } of candidates) { \n if(guards(context, fromEvent)) {\n service.context = reducers.call(service, context, fromEvent);\n\n let original = machine.original || machine;\n let newMachine = create(original, {\n current: valueEnumerable(to),\n original: { value: original }\n });\n\n if (d._onEnter) d._onEnter(machine, to, service.context, context, fromEvent);\n let state = newMachine.state.value;\n return state.enter(newMachine, service, fromEvent);\n }\n }\n}\n\nfunction send(service, event) {\n let eventName = event.type || event;\n let { machine } = service;\n let { value: state, name: currentStateName } = machine.state;\n \n if(state.transitions.has(eventName)) {\n return transitionTo(service, machine, event, state.transitions.get(eventName)) || machine;\n } else {\n if(d._send) d._send(eventName, currentStateName);\n }\n return machine;\n}\n\nlet service = {\n send(event) {\n this.machine = send(this, event);\n \n // TODO detect change\n this.onChange(this);\n }\n};\n\nfunction interpret(machine, onChange, initialContext, event) {\n let s = Object.create(service, {\n machine: valueEnumerableWritable(machine),\n context: valueEnumerableWritable(machine.context(initialContext, event)),\n onChange: valueEnumerable(onChange)\n });\n s.send = s.send.bind(s);\n s.machine = s.machine.state.value.enter(s.machine, s, event);\n return s;\n}\n\nexports.action = action;\nexports.createMachine = createMachine;\nexports.d = d;\nexports.guard = guard;\nexports.immediate = immediate;\nexports.interpret = interpret;\nexports.invoke = invoke;\nexports.reduce = reduce;\nexports.state = state;\nexports.transition = transition;\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { decode, encode } from \"@msgpack/msgpack\";\nimport {\n ContextFunction,\n InterpretOnChangeFunction,\n Service,\n createMachine,\n guard,\n immediate,\n interpret,\n reduce,\n state,\n transition,\n} from \"robot3\";\nimport { TOKEN_EXPIRATION_SECONDS, getTemporaryAuthToken } from \"./auth\";\nimport { RequiredConfig } from \"./config\";\nimport { ApiError } from \"./response\";\nimport { isBrowser } from \"./runtime\";\nimport { ensureEndpointIdFormat, isReact, throttle } from \"./utils\";\n\n// Define the context\ninterface Context {\n token?: string;\n enqueuedMessage?: any;\n websocket?: WebSocket;\n error?: Error;\n}\n\nconst initialState: ContextFunction<Context> = () => ({\n enqueuedMessage: undefined,\n});\n\ntype SendEvent = { type: \"send\"; message: any };\ntype AuthenticatedEvent = { type: \"authenticated\"; token: string };\ntype InitiateAuthEvent = { type: \"initiateAuth\" };\ntype UnauthorizedEvent = { type: \"unauthorized\"; error: Error };\ntype ConnectedEvent = { type: \"connected\"; websocket: WebSocket };\ntype ConnectionClosedEvent = {\n type: \"connectionClosed\";\n code: number;\n reason: string;\n};\n\ntype Event =\n | SendEvent\n | AuthenticatedEvent\n | InitiateAuthEvent\n | UnauthorizedEvent\n | ConnectedEvent\n | ConnectionClosedEvent;\n\nfunction hasToken(context: Context): boolean {\n return context.token !== undefined;\n}\n\nfunction noToken(context: Context): boolean {\n return !hasToken(context);\n}\n\nfunction enqueueMessage(context: Context, event: SendEvent): Context {\n return {\n ...context,\n enqueuedMessage: event.message,\n };\n}\n\nfunction closeConnection(context: Context): Context {\n if (context.websocket && context.websocket.readyState === WebSocket.OPEN) {\n context.websocket.close();\n }\n return {\n ...context,\n websocket: undefined,\n };\n}\n\nfunction sendMessage(context: Context, event: SendEvent): Context {\n if (context.websocket && context.websocket.readyState === WebSocket.OPEN) {\n if (event.message instanceof Uint8Array) {\n context.websocket.send(event.message);\n } else {\n context.websocket.send(encode(event.message));\n }\n\n return {\n ...context,\n enqueuedMessage: undefined,\n };\n }\n return {\n ...context,\n enqueuedMessage: event.message,\n };\n}\n\nfunction expireToken(context: Context): Context {\n return {\n ...context,\n token: undefined,\n };\n}\n\nfunction setToken(context: Context, event: AuthenticatedEvent): Context {\n return {\n ...context,\n token: event.token,\n };\n}\n\nfunction connectionEstablished(\n context: Context,\n event: ConnectedEvent,\n): Context {\n return {\n ...context,\n websocket: event.websocket,\n };\n}\n\n// State machine\nconst connectionStateMachine = createMachine(\n \"idle\",\n {\n idle: state(\n transition(\"send\", \"connecting\", reduce(enqueueMessage)),\n transition(\"expireToken\", \"idle\", reduce(expireToken)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n connecting: state(\n transition(\"connecting\", \"connecting\"),\n transition(\"connected\", \"active\", reduce(connectionEstablished)),\n transition(\"connectionClosed\", \"idle\", reduce(closeConnection)),\n transition(\"send\", \"connecting\", reduce(enqueueMessage)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n immediate(\"authRequired\", guard(noToken)),\n ),\n authRequired: state(\n transition(\"initiateAuth\", \"authInProgress\"),\n transition(\"send\", \"authRequired\", reduce(enqueueMessage)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n authInProgress: state(\n transition(\"authenticated\", \"connecting\", reduce(setToken)),\n transition(\n \"unauthorized\",\n \"idle\",\n reduce(expireToken),\n reduce(closeConnection),\n ),\n transition(\"send\", \"authInProgress\", reduce(enqueueMessage)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n active: state(\n transition(\"send\", \"active\", reduce(sendMessage)),\n transition(\"unauthorized\", \"idle\", reduce(expireToken)),\n transition(\"connectionClosed\", \"idle\", reduce(closeConnection)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n failed: state(\n transition(\"send\", \"failed\"),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n },\n initialState,\n);\n\ntype WithRequestId = {\n request_id: string;\n};\n\n/**\n * A connection object that allows you to `send` request payloads to a\n * realtime endpoint.\n */\nexport interface RealtimeConnection<Input> {\n send(input: Input & Partial<WithRequestId>): void;\n\n close(): void;\n}\n\n/**\n * Options for connecting to the realtime endpoint.\n */\nexport interface RealtimeConnectionHandler<Output> {\n /**\n * The connection key. This is used to reuse the same connection\n * across multiple calls to `connect`. This is particularly useful in\n * contexts where the connection is established as part of a component\n * lifecycle (e.g. React) and the component is re-rendered multiple times.\n */\n connectionKey?: string;\n\n /**\n * If `true`, the connection will only be established on the client side.\n * This is useful for frameworks that reuse code for both server-side\n * rendering and client-side rendering (e.g. Next.js).\n *\n * This is set to `true` by default when running on React in the server.\n * Otherwise, it is set to `false`.\n *\n * Note that more SSR frameworks might be automatically detected\n * in the future. In the meantime, you can set this to `true` when needed.\n */\n clientOnly?: boolean;\n\n /**\n * The throtle duration in milliseconds. This is used to throtle the\n * calls to the `send` function. Realtime apps usually react to user\n * input, which can be very frequent (e.g. fast typing or mouse/drag movements).\n *\n * The default value is `128` milliseconds.\n */\n throttleInterval?: number;\n\n /**\n * Configures the maximum amount of frames to store in memory before starting to drop\n * old ones for in favor of the newer ones. It must be between `1` and `60`.\n *\n * The recommended is `2`. The default is `undefined` so it can be determined\n * by the app (normally is set to the recommended setting).\n */\n maxBuffering?: number;\n\n /**\n * Callback function that is called when a result is received.\n * @param result - The result of the request.\n */\n onResult(result: Output & WithRequestId): void;\n\n /**\n * Callback function that is called when an error occurs.\n * @param error - The error that occurred.\n */\n onError?(error: ApiError<any>): void;\n}\n\nexport interface RealtimeClient {\n /**\n * Connect to the realtime endpoint. The default implementation uses\n * WebSockets to connect to fal function endpoints that support WSS.\n *\n * @param app the app alias or identifier.\n * @param handler the connection handler.\n */\n connect<Input = any, Output = any>(\n app: string,\n handler: RealtimeConnectionHandler<Output>,\n ): RealtimeConnection<Input>;\n}\n\ntype RealtimeUrlParams = {\n token: string;\n maxBuffering?: number;\n};\n\nfunction buildRealtimeUrl(\n app: string,\n { token, maxBuffering }: RealtimeUrlParams,\n): string {\n if (maxBuffering !== undefined && (maxBuffering < 1 || maxBuffering > 60)) {\n throw new Error(\"The `maxBuffering` must be between 1 and 60 (inclusive)\");\n }\n const queryParams = new URLSearchParams({\n fal_jwt_token: token,\n });\n if (maxBuffering !== undefined) {\n queryParams.set(\"max_buffering\", maxBuffering.toFixed(0));\n }\n const appId = ensureEndpointIdFormat(app);\n return `wss://fal.run/${appId}/realtime?${queryParams.toString()}`;\n}\n\nconst DEFAULT_THROTTLE_INTERVAL = 128;\n\nfunction isUnauthorizedError(message: any): boolean {\n // TODO we need better protocol definition with error codes\n return message[\"status\"] === \"error\" && message[\"error\"] === \"Unauthorized\";\n}\n\n/**\n * See https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1\n */\nconst WebSocketErrorCodes = {\n NORMAL_CLOSURE: 1000,\n GOING_AWAY: 1001,\n};\n\ntype ConnectionStateMachine = Service<typeof connectionStateMachine> & {\n throttledSend: (\n event: Event,\n payload?: any,\n ) => void | Promise<void> | undefined;\n};\n\ntype ConnectionOnChange = InterpretOnChangeFunction<\n typeof connectionStateMachine\n>;\n\ntype RealtimeConnectionCallback = Pick<\n RealtimeConnectionHandler<any>,\n \"onResult\" | \"onError\"\n>;\n\nconst connectionCache = new Map<string, ConnectionStateMachine>();\nconst connectionCallbacks = new Map<string, RealtimeConnectionCallback>();\nfunction reuseInterpreter(\n key: string,\n throttleInterval: number,\n onChange: ConnectionOnChange,\n) {\n if (!connectionCache.has(key)) {\n const machine = interpret(connectionStateMachine, onChange);\n connectionCache.set(key, {\n ...machine,\n throttledSend:\n throttleInterval > 0\n ? throttle(machine.send, throttleInterval, true)\n : machine.send,\n });\n }\n return connectionCache.get(key) as ConnectionStateMachine;\n}\n\nconst noop = () => {\n /* No-op */\n};\n\n/**\n * A no-op connection that does not send any message.\n * Useful on the frameworks that reuse code for both ssr and csr (e.g. Next)\n * so the call when doing ssr has no side-effects.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst NoOpConnection: RealtimeConnection<any> = {\n send: noop,\n close: noop,\n};\n\nfunction isSuccessfulResult(data: any): boolean {\n return (\n data.status !== \"error\" &&\n data.type !== \"x-fal-message\" &&\n !isFalErrorResult(data)\n );\n}\n\ntype FalErrorResult = {\n type: \"x-fal-error\";\n error: string;\n reason: string;\n};\n\nfunction isFalErrorResult(data: any): data is FalErrorResult {\n return data.type === \"x-fal-error\";\n}\n\ntype RealtimeClientDependencies = {\n config: RequiredConfig;\n};\n\nexport function createRealtimeClient({\n config,\n}: RealtimeClientDependencies): RealtimeClient {\n return {\n connect<Input, Output>(\n app: string,\n handler: RealtimeConnectionHandler<Output>,\n ): RealtimeConnection<Input> {\n const {\n // if running on React in the server, set clientOnly to true by default\n clientOnly = isReact() && !isBrowser(),\n connectionKey = crypto.randomUUID(),\n maxBuffering,\n throttleInterval = DEFAULT_THROTTLE_INTERVAL,\n } = handler;\n if (clientOnly && !isBrowser()) {\n return NoOpConnection;\n }\n\n let previousState: string | undefined;\n\n // Although the state machine is cached so we don't open multiple connections,\n // we still need to update the callbacks so we can call the correct references\n // when the state machine is reused. This is needed because the callbacks\n // are passed as part of the handler object, which can be different across\n // different calls to `connect`.\n connectionCallbacks.set(connectionKey, {\n onError: handler.onError,\n onResult: handler.onResult,\n });\n const getCallbacks = () =>\n connectionCallbacks.get(connectionKey) as RealtimeConnectionCallback;\n const stateMachine = reuseInterpreter(\n connectionKey,\n throttleInterval,\n ({ context, machine, send }) => {\n const { enqueuedMessage, token } = context;\n if (machine.current === \"active\" && enqueuedMessage) {\n send({ type: \"send\", message: enqueuedMessage });\n }\n if (\n machine.current === \"authRequired\" &&\n token === undefined &&\n previousState !== machine.current\n ) {\n send({ type: \"initiateAuth\" });\n getTemporaryAuthToken(app, config)\n .then((token) => {\n send({ type: \"authenticated\", token });\n const tokenExpirationTimeout = Math.round(\n TOKEN_EXPIRATION_SECONDS * 0.9 * 1000,\n );\n setTimeout(() => {\n send({ type: \"expireToken\" });\n }, tokenExpirationTimeout);\n })\n .catch((error) => {\n send({ type: \"unauthorized\", error });\n });\n }\n if (\n machine.current === \"connecting\" &&\n previousState !== machine.current &&\n token !== undefined\n ) {\n const ws = new WebSocket(\n buildRealtimeUrl(app, { token, maxBuffering }),\n );\n ws.onopen = () => {\n send({ type: \"connected\", websocket: ws });\n };\n ws.onclose = (event) => {\n if (event.code !== WebSocketErrorCodes.NORMAL_CLOSURE) {\n const { onError = noop } = getCallbacks();\n onError(\n new ApiError({\n message: `Error closing the connection: ${event.reason}`,\n status: event.code,\n }),\n );\n }\n send({ type: \"connectionClosed\", code: event.code });\n };\n ws.onerror = (event) => {\n // TODO specify error protocol for identified errors\n const { onError = noop } = getCallbacks();\n onError(new ApiError({ message: \"Unknown error\", status: 500 }));\n };\n ws.onmessage = (event) => {\n const { onResult } = getCallbacks();\n\n // Handle binary messages as msgpack messages\n if (event.data instanceof ArrayBuffer) {\n const result = decode(new Uint8Array(event.data));\n onResult(result);\n return;\n }\n if (event.data instanceof Uint8Array) {\n const result = decode(event.data);\n onResult(result);\n return;\n }\n if (event.data instanceof Blob) {\n event.data.arrayBuffer().then((buffer) => {\n const result = decode(new Uint8Array(buffer));\n onResult(result);\n });\n return;\n }\n\n // Otherwise handle strings as plain JSON messages\n const data = JSON.parse(event.data);\n\n // Drop messages that are not related to the actual result.\n // In the future, we might want to handle other types of messages.\n // TODO: specify the fal ws protocol format\n if (isUnauthorizedError(data)) {\n send({\n type: \"unauthorized\",\n error: new Error(\"Unauthorized\"),\n });\n return;\n }\n if (isSuccessfulResult(data)) {\n onResult(data);\n return;\n }\n if (isFalErrorResult(data)) {\n if (data.error === \"TIMEOUT\") {\n // Timeout error messages just indicate that the connection hasn't\n // received an incoming message for a while. We don't need to\n // handle them as errors.\n return;\n }\n const { onError = noop } = getCallbacks();\n onError(\n new ApiError({\n message: `${data.error}: ${data.reason}`,\n // TODO better error status code\n status: 400,\n body: data,\n }),\n );\n return;\n }\n };\n }\n previousState = machine.current;\n },\n );\n\n const send = (input: Input & Partial<WithRequestId>) => {\n // Use throttled send to avoid sending too many messages\n stateMachine.throttledSend({\n type: \"send\",\n message: input,\n });\n };\n\n const close = () => {\n stateMachine.send({ type: \"close\" });\n };\n\n return {\n send,\n close,\n };\n },\n };\n}\n", "import { getRestApiUrl, RequiredConfig } from \"./config\";\nimport { dispatchRequest } from \"./request\";\nimport { isPlainObject } from \"./utils\";\n/**\n * File support for the client. This interface establishes the contract for\n * uploading files to the server and transforming the input to replace file\n * objects with URLs.\n */\nexport interface StorageClient {\n /**\n * Upload a file to the server. Returns the URL of the uploaded file.\n * @param file the file to upload\n * @param options optional parameters, such as custom file name\n * @returns the URL of the uploaded file\n */\n upload: (file: Blob) => Promise<string>;\n\n /**\n * Transform the input to replace file objects with URLs. This is used\n * to transform the input before sending it to the server and ensures\n * that the server receives URLs instead of file objects.\n *\n * @param input the input to transform.\n * @returns the transformed input.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n transformInput: (input: Record<string, any>) => Promise<Record<string, any>>;\n}\n\ntype InitiateUploadResult = {\n file_url: string;\n upload_url: string;\n};\n\ntype InitiateUploadData = {\n file_name: string;\n content_type: string | null;\n};\n\n/**\n * Get the file extension from the content type. This is used to generate\n * a file name if the file name is not provided.\n *\n * @param contentType the content type of the file.\n * @returns the file extension or `bin` if the content type is not recognized.\n */\nfunction getExtensionFromContentType(contentType: string): string {\n const [_, fileType] = contentType.split(\"/\");\n return fileType.split(/[-;]/)[0] ?? \"bin\";\n}\n\n/**\n * Initiate the upload of a file to the server. This returns the URL to upload\n * the file to and the URL of the file once it is uploaded.\n */\nasync function initiateUpload(\n file: Blob,\n config: RequiredConfig,\n contentType: string,\n): Promise<InitiateUploadResult> {\n const filename =\n file.name || `${Date.now()}.${getExtensionFromContentType(contentType)}`;\n\n return await dispatchRequest<InitiateUploadData, InitiateUploadResult>({\n method: \"POST\",\n // NOTE: We want to test V3 without making it the default at the API level\n targetUrl: `${getRestApiUrl()}/storage/upload/initiate?storage_type=fal-cdn-v3`,\n input: {\n content_type: contentType,\n file_name: filename,\n },\n config,\n });\n}\n\n/**\n * Initiate the multipart upload of a file to the server. This returns the URL to upload\n * the file to and the URL of the file once it is uploaded.\n */\nasync function initiateMultipartUpload(\n file: Blob,\n config: RequiredConfig,\n contentType: string,\n): Promise<InitiateUploadResult> {\n const filename =\n file.name || `${Date.now()}.${getExtensionFromContentType(contentType)}`;\n\n return await dispatchRequest<InitiateUploadData, InitiateUploadResult>({\n method: \"POST\",\n targetUrl: `${getRestApiUrl()}/storage/upload/initiate-multipart?storage_type=fal-cdn-v3`,\n input: {\n content_type: contentType,\n file_name: filename,\n },\n config,\n });\n}\n\ntype MultipartObject = {\n partNumber: number;\n etag: string;\n};\n\nasync function partUploadRetries(\n uploadUrl: string,\n chunk: Blob,\n config: RequiredConfig,\n tries = 3,\n): Promise<MultipartObject> {\n if (tries === 0) {\n throw new Error(\"Part upload failed, retries exhausted\");\n }\n\n const { fetch, responseHandler } = config;\n\n try {\n const response = await fetch(uploadUrl, {\n method: \"PUT\",\n body: chunk,\n });\n\n return (await responseHandler(response)) as MultipartObject;\n } catch (error) {\n return await partUploadRetries(uploadUrl, chunk, config, tries - 1);\n }\n}\n\nasync function multipartUpload(\n file: Blob,\n config: RequiredConfig,\n): Promise<string> {\n const { fetch, responseHandler } = config;\n const contentType = file.type || \"application/octet-stream\";\n const { upload_url: uploadUrl, file_url: url } =\n await initiateMultipartUpload(file, config, contentType);\n\n // Break the file into 10MB chunks\n const chunkSize = 10 * 1024 * 1024;\n const chunks = Math.ceil(file.size / chunkSize);\n\n const parsedUrl = new URL(uploadUrl);\n\n const responses: MultipartObject[] = [];\n\n for (let i = 0; i < chunks; i++) {\n const start = i * chunkSize;\n const end = Math.min(start + chunkSize, file.size);\n\n const chunk = file.slice(start, end);\n\n const partNumber = i + 1;\n // {uploadUrl}/{part_number}?uploadUrlParams=...\n const partUploadUrl = `${parsedUrl.origin}${parsedUrl.pathname}/${partNumber}${parsedUrl.search}`;\n\n responses.push(await partUploadRetries(partUploadUrl, chunk, config));\n }\n\n // Complete the upload\n const completeUrl = `${parsedUrl.origin}${parsedUrl.pathname}/complete${parsedUrl.search}`;\n const response = await fetch(completeUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n parts: responses.map((mpart) => ({\n partNumber: mpart.partNumber,\n etag: mpart.etag,\n })),\n }),\n });\n await responseHandler(response);\n\n return url;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype KeyValuePair = [string, any];\n\ntype StorageClientDependencies = {\n config: RequiredConfig;\n};\n\nexport function createStorageClient({\n config,\n}: StorageClientDependencies): StorageClient {\n const ref: StorageClient = {\n upload: async (file: Blob) => {\n // Check for 90+ MB file size to do multipart upload\n if (file.size > 90 * 1024 * 1024) {\n return await multipartUpload(file, config);\n }\n\n const contentType = file.type || \"application/octet-stream\";\n\n const { fetch, responseHandler } = config;\n const { upload_url: uploadUrl, file_url: url } = await initiateUpload(\n file,\n config,\n contentType,\n );\n const response = await fetch(uploadUrl, {\n method: \"PUT\",\n body: file,\n headers: {\n \"Content-Type\": file.type || \"application/octet-stream\",\n },\n });\n await responseHandler(response);\n return url;\n },\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n transformInput: async (input: any): Promise<any> => {\n if (Array.isArray(input)) {\n return Promise.all(input.map((item) => ref.transformInput(item)));\n } else if (input instanceof Blob) {\n return await ref.upload(input);\n } else if (isPlainObject(input)) {\n const inputObject = input as Record<string, any>;\n const promises = Object.entries(inputObject).map(\n async ([key, value]): Promise<KeyValuePair> => {\n return [key, await ref.transformInput(value)];\n },\n );\n const results = await Promise.all(promises);\n return Object.fromEntries(results);\n }\n // Return the input as is if it's neither an object nor a file/blob/data URI\n return input;\n },\n };\n return ref;\n}\n", "import { Config, createConfig } from \"./config\";\nimport { createQueueClient, QueueClient, QueueSubscribeOptions } from \"./queue\";\nimport { createRealtimeClient, RealtimeClient } from \"./realtime\";\nimport { buildUrl, dispatchRequest } from \"./request\";\nimport { resultResponseHandler } from \"./response\";\nimport { createStorageClient, StorageClient } from \"./storage\";\nimport { createStreamingClient, StreamingClient } from \"./streaming\";\nimport { EndpointType, InputType, OutputType } from \"./types/client\";\nimport { Result, RunOptions } from \"./types/common\";\n\n/**\n * The main client type, it provides access to simple API model usage,\n * as well as access to the `queue` and `storage` APIs.\n *\n * @see createFalClient\n */\nexport interface FalClient {\n /**\n * The queue client to interact with the queue API.\n */\n readonly queue: QueueClient;\n\n /**\n * The realtime client to interact with the realtime API\n * and receive updates in real-time.\n * @see #RealtimeClient\n * @see #RealtimeClient.connect\n */\n readonly realtime: RealtimeClient;\n\n /**\n * The storage client to interact with the storage API.\n */\n readonly storage: StorageClient;\n\n /**\n * The streaming client to interact with the streaming API.\n * @see #stream\n */\n readonly streaming: StreamingClient;\n\n /**\n * Runs a fal endpoint identified by its `endpointId`.\n *\n * @param endpointId The endpoint id, e.g. `fal-ai/fast-sdxl`.\n * @param options The request options, including the input payload.\n * @returns A promise that resolves to the result of the request once it's completed.\n *\n * @note\n * We **do not recommend** this use for most use cases as it will block the client\n * until the response is received. Moreover, if the connection is closed before\n * the response is received, the request will be lost. Instead, we recommend\n * using the `subscribe` method for most use cases.\n */\n run<Id extends EndpointType>(\n endpointId: Id,\n options: RunOptions<InputType<Id>>,\n ): Promise<Result<OutputType<Id>>>;\n\n /**\n * Subscribes to updates for a specific request in the queue.\n *\n * @param endpointId - The ID of the API endpoint.\n * @param options - Options to configure how the request is run and how updates are received.\n * @returns A promise that resolves to the result of the request once it's completed.\n */\n subscribe<Id extends EndpointType>(\n endpointId: Id,\n options: RunOptions<InputType<Id>> & QueueSubscribeOptions,\n ): Promise<Result<OutputType<Id>>>;\n\n /**\n * Calls a fal app that supports streaming and provides a streaming-capable\n * object as a result, that can be used to get partial results through either\n * `AsyncIterator` or through an event listener.\n *\n * @param endpointId the endpoint id, e.g. `fal-ai/llavav15-13b`.\n * @param options the request options, including the input payload.\n * @returns the `FalStream` instance.\n */\n stream: StreamingClient[\"stream\"];\n}\n\n/**\n * Creates a new reference of the `FalClient`.\n * @param userConfig Optional configuration to override the default settings.\n * @returns a new instance of the `FalClient`.\n */\nexport function createFalClient(userConfig: Config = {}): FalClient {\n const config = createConfig(userConfig);\n const storage = createStorageClient({ config });\n const queue = createQueueClient({ config, storage });\n const streaming = createStreamingClient({ config, storage });\n const realtime = createRealtimeClient({ config });\n return {\n queue,\n realtime,\n storage,\n streaming,\n stream: streaming.stream,\n async run<Id extends EndpointType>(\n endpointId: Id,\n options: RunOptions<InputType<Id>> = {},\n ): Promise<Result<OutputType<Id>>> {\n const input = options.input\n ? await storage.transformInput(options.input)\n : undefined;\n return dispatchRequest<InputType<Id>, Result<OutputType<Id>>>({\n method: options.method,\n targetUrl: buildUrl(endpointId, options),\n input: input as InputType<Id>,\n config: {\n ...config,\n responseHandler: resultResponseHandler,\n },\n options: {\n signal: options.abortSignal,\n },\n });\n },\n subscribe: async (endpointId, options) => {\n const { request_id: requestId } = await queue.submit(endpointId, options);\n if (options.onEnqueue) {\n options.onEnqueue(requestId);\n }\n await queue.subscribeToStatus(endpointId, { requestId, ...options });\n return queue.result(endpointId, { requestId });\n },\n };\n}\n", "/**\n * Represents an API result, containing the data,\n * the request ID and any other relevant information.\n */\nexport type Result<T> = {\n data: T;\n requestId: string;\n};\n\n/**\n * The function input and other configuration when running\n * the function, such as the HTTP method to use.\n */\nexport type RunOptions<Input> = {\n /**\n * The function input. It will be submitted either as query params\n * or the body payload, depending on the `method`.\n */\n readonly input?: Input;\n\n /**\n * The HTTP method, defaults to `post`;\n */\n readonly method?: \"get\" | \"post\" | \"put\" | \"delete\" | string;\n\n /**\n * The abort signal to cancel the request.\n */\n readonly abortSignal?: AbortSignal;\n};\n\nexport type UrlOptions = {\n /**\n * If `true`, the function will use the queue to run the function\n * asynchronously and return the result in a separate call. This\n * influences how the URL is built.\n */\n readonly subdomain?: string;\n\n /**\n * The query parameters to include in the URL.\n */\n readonly query?: Record<string, string>;\n\n /**\n * The path to append to the function URL.\n */\n path?: string;\n};\n\nexport type RequestLog = {\n message: string;\n level: \"STDERR\" | \"STDOUT\" | \"ERROR\" | \"INFO\" | \"WARN\" | \"DEBUG\";\n source: \"USER\";\n timestamp: string; // Using string to represent date-time format, but you could also use 'Date' type if you're going to construct Date objects.\n};\n\nexport type Metrics = {\n inference_time: number | null;\n};\n\ninterface BaseQueueStatus {\n status: \"IN_QUEUE\" | \"IN_PROGRESS\" | \"COMPLETED\";\n request_id: string;\n}\n\nexport interface InQueueQueueStatus extends BaseQueueStatus {\n status: \"IN_QUEUE\";\n queue_position: number;\n response_url: string;\n}\n\nexport interface InProgressQueueStatus extends BaseQueueStatus {\n status: \"IN_PROGRESS\";\n response_url: string;\n logs: RequestLog[];\n}\n\nexport interface CompletedQueueStatus extends BaseQueueStatus {\n status: \"COMPLETED\";\n response_url: string;\n logs: RequestLog[];\n metrics?: Metrics;\n}\n\nexport type QueueStatus =\n | InProgressQueueStatus\n | CompletedQueueStatus\n | InQueueQueueStatus;\n\nexport function isQueueStatus(obj: any): obj is QueueStatus {\n return obj && obj.status && obj.response_url;\n}\n\nexport function isCompletedQueueStatus(obj: any): obj is CompletedQueueStatus {\n return isQueueStatus(obj) && obj.status === \"COMPLETED\";\n}\n\nexport type ValidationErrorInfo = {\n msg: string;\n loc: Array<string | number>;\n type: string;\n};\n\n/**\n * Represents the response from a WebHook request.\n * This is a union type that varies based on the `status` property.\n *\n * @template Payload - The type of the payload in the response. It defaults to `any`,\n * allowing for flexibility in specifying the structure of the payload.\n */\nexport type WebHookResponse<Payload = any> =\n | {\n /** Indicates a successful response. */\n status: \"OK\";\n /** The payload of the response, structure determined by the Payload type. */\n payload: Payload;\n /** Error is never present in a successful response. */\n error: never;\n /** The unique identifier for the request. */\n request_id: string;\n }\n | {\n /** Indicates an unsuccessful response. */\n status: \"ERROR\";\n /** The payload of the response, structure determined by the Payload type. */\n payload: Payload;\n /** Description of the error that occurred. */\n error: string;\n /** The unique identifier for the request. */\n request_id: string;\n };\n", "import { createFalClient, type FalClient } from \"./client\";\nimport { Config } from \"./config\";\nimport { StreamOptions } from \"./streaming\";\nimport { EndpointType, InputType } from \"./types/client\";\nimport { RunOptions } from \"./types/common\";\n\nexport { createFalClient, type FalClient } from \"./client\";\nexport { withMiddleware, withProxy } from \"./middleware\";\nexport type { RequestMiddleware } from \"./middleware\";\nexport type { QueueClient } from \"./queue\";\nexport type { RealtimeClient } from \"./realtime\";\nexport { ApiError, ValidationError } from \"./response\";\nexport type { ResponseHandler } from \"./response\";\nexport type { StorageClient } from \"./storage\";\nexport type { FalStream, StreamingClient } from \"./streaming\";\nexport * from \"./types/common\";\nexport type {\n QueueStatus,\n ValidationErrorInfo,\n WebHookResponse,\n} from \"./types/common\";\nexport { parseEndpointId } from \"./utils\";\n\ntype SingletonFalClient = {\n config(config: Config): void;\n} & FalClient;\n\n/**\n * Creates a singleton instance of the client. This is useful as a compatibility\n * layer for existing code that uses the clients version prior to 1.0.0.\n */\nexport const fal: SingletonFalClient = (function createSingletonFalClient() {\n let currentInstance: FalClient = createFalClient();\n return {\n config(config: Config) {\n currentInstance = createFalClient(config);\n },\n get queue() {\n return currentInstance.queue;\n },\n get realtime() {\n return currentInstance.realtime;\n },\n get storage() {\n return currentInstance.storage;\n },\n get streaming() {\n return currentInstance.streaming;\n },\n run<Id extends EndpointType>(id: Id, options: RunOptions<InputType<Id>>) {\n return currentInstance.run<Id>(id, options);\n },\n subscribe<Id extends EndpointType>(\n endpointId: Id,\n options: RunOptions<InputType<Id>>,\n ) {\n return currentInstance.subscribe<Id>(endpointId, options);\n },\n stream<Id extends EndpointType>(\n endpointId: Id,\n options: StreamOptions<InputType<Id>>,\n ) {\n return currentInstance.stream<Id>(endpointId, options);\n },\n } satisfies SingletonFalClient;\n})();\n", "export default `\n<svg>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratioFree\"\n >\n <path d=\"M7 6C6.44772 6 6 6.44772 6 7V9.22222H4V7C4 5.34315 5.34315 4 7 4H9.22222V6H7Z\" fill=\"currentColor\"/>\n <path d=\"M17 6H14.7778V4H17C18.6569 4 20 5.34315 20 7V9.22222H18V7C18 6.44772 17.5523 6 17 6Z\" fill=\"currentColor\"/>\n <path d=\"M6 14.7778V17C6 17.5523 6.44772 18 7 18H9.22222V20H7C5.34315 20 4 18.6569 4 17V14.7778H6Z\" fill=\"currentColor\"/>\n <path d=\"M18 17V14.7778H20V17C20 18.6569 18.6569 20 17 20H14.7778V18H17C17.5523 18 18 17.5523 18 17Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio4by3\"\n >\n <path d=\"M6.5 13H8V15H10V16.5H6.5V13Z\" fill=\"currentColor\"/>\n <path d=\"M14 9V7.5H17.5V11H16V9H14Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M6 4C4.34315 4 3 5.34315 3 7V17C3 18.6569 4.34315 20 6 20H18C19.6569 20 21 18.6569 21 17V7C21 5.34315 19.6569 4 18 4H6ZM5 7C5 6.44772 5.44772 6 6 6H18C18.5523 6 19 6.44772 19 7V17C19 17.5523 18.5523 18 18 18H6C5.44772 18 5 17.5523 5 17V7Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio16by9\"\n >\n <path d=\"M4.5 13H6V15H8V16.5H4.5V13Z\" fill=\"currentColor\"/>\n <path d=\"M16 9V7.5H19.5V11H18V9H16Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M4 4C2.34315 4 1 5.34315 1 7V17C1 18.6569 2.34315 20 4 20H20C21.6569 20 23 18.6569 23 17V7C23 5.34315 21.6569 4 20 4H4ZM3 7C3 6.44772 3.44772 6 4 6H20C20.5523 6 21 6.44772 21 7V17C21 17.5523 20.5523 18 20 18H4C3.44772 18 3 17.5523 3 17V7Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio9by16\"\n >\n <path d=\"M7.5 16H9V18H11V19.5H7.5V16Z\" fill=\"currentColor\"/>\n <path d=\"M13 6V4.5H16.5V8H15V6H13Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M4 20C4 21.6569 5.34315 23 7 23H17C18.6569 23 20 21.6569 20 20V4C20 2.34315 18.6569 1 17 1H7C5.34315 1 4 2.34315 4 4V20ZM7 21C6.44772 21 6 20.5523 6 20V4C6 3.44772 6.44772 3 7 3H17C17.5523 3 18 3.44772 18 4V20C18 20.5523 17.5523 21 17 21H7Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio3by4\"\n >\n <path d=\"M11 17.5V16H9V14H7.5V17.5H11Z\" fill=\"currentColor\"/>\n <path d=\"M15 10H16.5V6.5H13V8H15V10Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M20 18C20 19.6569 18.6569 21 17 21H7C5.34315 21 4 19.6569 4 18V6C4 4.34315 5.34315 3 7 3H17C18.6569 3 20 4.34315 20 6V18ZM17 19C17.5523 19 18 18.5523 18 18V6C18 5.44772 17.5523 5 17 5H7C6.44771 5 6 5.44771 6 6V18C6 18.5523 6.44772 19 7 19H17Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio1by1\"\n >\n <path d=\"M17.4142 8.00009L16 6.58587L14.2929 8.29298L15.7071 9.70719L17.4142 8.00009Z\" fill=\"currentColor\"/>\n <path d=\"M13.0404 12.3739L15.0404 10.3739L13.6262 8.95965L11.6262 10.9596L13.0404 12.3739Z\" fill=\"currentColor\"/>\n <path d=\"M10.3737 15.0405L12.3737 13.0405L10.9595 11.6263L8.95953 13.6263L10.3737 15.0405Z\" fill=\"currentColor\"/>\n <path d=\"M9.70708 15.7072L8.29286 14.293L6.58576 16.0001L7.99997 17.4143L9.70708 15.7072Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M7 4C5.34315 4 4 5.34315 4 7V17C4 18.6569 5.34315 20 7 20H17C18.6569 20 20 18.6569 20 17V7C20 5.34315 18.6569 4 17 4H7ZM6 7C6 6.44772 6.44772 6 7 6H17C17.5523 6 18 6.44772 18 7V17C18 17.5523 17.5523 18 17 18H7C6.44772 18 6 17.5523 6 17V7Z\" fill=\"currentColor\"/>\n </symbol>\n</svg>\n`;\n", "import type {\n AssetDefinition,\n AssetQueryData,\n AssetResult,\n AssetSource,\n AssetsQueryResult\n} from '@cesdk/engine';\n\n/**\n * Simplified value type for select inputs that can be converted to asset definitions\n */\nexport type SelectValue = {\n id: string;\n label: string;\n thumbUri?: string;\n};\n\n/**\n * A custom AssetSource implementation that manages assets from an array\n * and provides additional functionality like to mark assets as active or changing\n * labels.\n */\nexport class CustomAssetSource implements AssetSource {\n /** The unique id of the asset source */\n id: string;\n\n /** Array of assets to be served by this source */\n private assets: AssetDefinition[];\n\n /** Set of IDs for active assets */\n private activeAssetIds: Set<string>;\n\n /**\n * Creates a new instance of CustomAssetSource\n *\n * @param id - The unique identifier for this asset source\n * @param assets - Array of asset definitions or SelectValue objects to include in this source\n */\n constructor(id: string, assets: (AssetDefinition | SelectValue)[] = []) {\n this.id = id;\n this.assets = assets.map((asset) => {\n // Check if the asset is a SelectValue by looking for the label property as a string\n if (\n typeof (asset as SelectValue).label === 'string' &&\n !(\n (asset as AssetDefinition).label &&\n typeof (asset as AssetDefinition).label === 'object'\n )\n ) {\n const selectValue = asset as SelectValue;\n // Convert SelectValue to AssetDefinition\n return {\n id: selectValue.id,\n label: { en: selectValue.label },\n meta: selectValue.thumbUri\n ? { thumbUri: selectValue.thumbUri }\n : undefined\n } as AssetDefinition;\n }\n return asset as AssetDefinition;\n });\n this.activeAssetIds = new Set<string>();\n }\n\n /**\n * Find assets based on the provided query data\n * Supports pagination, searching, filtering, and active-first sorting\n *\n * @param queryData - Query parameters to filter and sort assets\n * @returns Promise with the query results\n */\n async findAssets(\n queryData: AssetQueryData\n ): Promise<AssetsQueryResult | undefined> {\n const {\n page,\n perPage,\n locale = 'en',\n sortActiveFirst,\n query,\n tags,\n groups,\n excludeGroups,\n sortingOrder,\n sortKey\n } = queryData;\n\n // Start with all assets\n let filteredAssets = [...this.assets];\n\n // Filter by groups if provided\n if (groups && groups.length > 0) {\n filteredAssets = filteredAssets.filter(\n (asset) =>\n asset.groups && groups.some((group) => asset.groups?.includes(group))\n );\n }\n\n // Filter out excluded groups if provided\n if (excludeGroups && excludeGroups.length > 0) {\n filteredAssets = filteredAssets.filter(\n (asset) =>\n !asset.groups ||\n !excludeGroups.some((group) => asset.groups?.includes(group))\n );\n }\n\n // Filter by query (search in label and tags)\n if (query) {\n const lowerQuery = query.toLowerCase();\n filteredAssets = filteredAssets.filter((asset) => {\n const label = asset.label?.[locale]?.toLowerCase();\n const assetTags = asset.tags?.[locale] || [];\n\n return (\n (label && label.includes(lowerQuery)) ||\n assetTags.some((tag) => tag.toLowerCase().includes(lowerQuery))\n );\n });\n }\n\n // Filter by exact tags if provided\n if (tags && tags.length > 0) {\n const tagArray = Array.isArray(tags) ? tags : [tags];\n filteredAssets = filteredAssets.filter((asset) => {\n const assetTags = asset.tags?.[locale] || [];\n return tagArray.some((tag) => assetTags.includes(tag));\n });\n }\n\n // Sort by active first if requested\n if (sortActiveFirst) {\n filteredAssets.sort((a, b) => {\n const aActive = this.activeAssetIds.has(a.id);\n const bActive = this.activeAssetIds.has(b.id);\n\n if (aActive && !bActive) return -1;\n if (!aActive && bActive) return 1;\n return 0;\n });\n }\n\n // Sort by sortKey if provided\n if (sortKey && sortKey !== 'id') {\n filteredAssets.sort((a, b) => {\n // Sort by metadata field\n const aValue = a.meta?.[sortKey];\n const bValue = b.meta?.[sortKey];\n\n if (aValue === undefined) return 1;\n if (bValue === undefined) return -1;\n\n if (typeof aValue === 'string' && typeof bValue === 'string') {\n return sortingOrder === 'Descending'\n ? bValue.localeCompare(aValue)\n : aValue.localeCompare(bValue);\n }\n\n if (typeof aValue === 'number' && typeof bValue === 'number') {\n return sortingOrder === 'Descending'\n ? bValue - aValue\n : aValue - bValue;\n }\n\n return 0;\n });\n } else if (sortKey === 'id') {\n // Sort by id\n filteredAssets.sort((a, b) => {\n return sortingOrder === 'Descending'\n ? b.id.localeCompare(a.id)\n : a.id.localeCompare(b.id);\n });\n }\n\n // Calculate pagination\n const total = filteredAssets.length;\n const startIndex = page * perPage;\n const endIndex = startIndex + perPage;\n const paginatedAssets = filteredAssets.slice(startIndex, endIndex);\n\n // Transform AssetDefinition objects to AssetResult objects\n const resultAssets: AssetResult[] = paginatedAssets.map((asset) => {\n return {\n id: asset.id,\n groups: asset.groups,\n meta: asset.meta,\n payload: asset.payload,\n locale,\n label: asset.label?.[locale],\n tags: asset.tags?.[locale],\n active: this.activeAssetIds.has(asset.id)\n };\n });\n\n // Calculate next page if there are more assets\n const nextPage = endIndex < total ? page + 1 : undefined;\n\n return {\n assets: resultAssets,\n currentPage: page,\n nextPage,\n total\n };\n }\n\n updateLabel(assetId: string, label: string, locale: string): void {\n this.assets.forEach((asset) => {\n if (asset.id === assetId) {\n asset.label = asset.label || {};\n asset.label[locale] = label;\n }\n });\n }\n\n /**\n * Get the asset select value by its ID\n *\n * @param assetId - The ID of the asset to retrieve\n * @returns The SelectValue object for the asset or undefined if not found\n */\n getAssetSelectValue(assetId: string): SelectValue | undefined {\n const asset = this.assets.find(({ id }) => id === assetId);\n if (asset) {\n return {\n id: asset.id,\n label: asset.label?.en || '',\n thumbUri: asset.meta?.thumbUri\n };\n }\n return undefined;\n }\n\n /**\n * Get an asset by its ID\n */\n getAsset(id: string): AssetDefinition | undefined {\n return this.assets.find((asset) => asset.id === id);\n }\n\n /**\n * Set an asset as active by its ID\n *\n * @param assetId - The ID of the asset to mark as active\n */\n setAssetActive(assetId: string): void {\n this.activeAssetIds.add(assetId);\n }\n\n /**\n * Get all active asset IDs\n *\n * @returns Array of active asset IDs\n */\n getActiveAssetIds(): string[] {\n return Array.from(this.activeAssetIds);\n }\n\n /**\n * Set multiple assets as active by their IDs\n *\n * @param assetIds - Array of asset IDs to mark as active\n */\n setAssetsActive(assetIds: string[]): void {\n assetIds.forEach((id) => this.activeAssetIds.add(id));\n }\n\n /**\n * Set an asset as inactive by its ID\n *\n * @param assetId - The ID of the asset to mark as inactive\n */\n setAssetInactive(assetId: string): void {\n this.activeAssetIds.delete(assetId);\n }\n\n /**\n * Clear all active assets\n */\n clearActiveAssets(): void {\n this.activeAssetIds.clear();\n }\n\n /**\n * Check if an asset is marked as active\n *\n * @param assetId - The ID of the asset to check\n * @returns True if the asset is active, false otherwise\n */\n isAssetActive(assetId: string): boolean {\n return this.activeAssetIds.has(assetId);\n }\n\n /**\n * Add an asset to this source\n *\n * @param asset - The asset definition to add\n */\n addAsset(asset: AssetDefinition): void {\n // Check if asset with this ID already exists\n const existingIndex = this.assets.findIndex((a) => a.id === asset.id);\n if (existingIndex >= 0) {\n // Replace existing asset\n this.assets[existingIndex] = asset;\n } else {\n // Add new asset\n this.assets.push(asset);\n }\n }\n\n /**\n * Remove an asset from this source\n *\n * @param assetId - The ID of the asset to remove\n */\n removeAsset(assetId: string): void {\n const index = this.assets.findIndex((asset) => asset.id === assetId);\n if (index !== -1) {\n this.assets.splice(index, 1);\n this.activeAssetIds.delete(assetId);\n }\n }\n\n /**\n * Get all available groups from the assets\n *\n * @returns Array of unique group names\n */\n async getGroups(): Promise<string[]> {\n const groups = new Set<string>();\n this.assets.forEach((asset) => {\n if (asset.groups) {\n asset.groups.forEach((group) => groups.add(group));\n }\n });\n return Array.from(groups);\n }\n\n /**\n * Returns the supported MIME types for this asset source\n *\n * @returns Array of supported MIME types\n */\n getSupportedMimeTypes(): string[] {\n return [\n 'image/jpeg',\n 'image/png',\n 'image/svg+xml',\n 'image/webp',\n 'video/mp4',\n 'audio/mpeg'\n ];\n }\n}\n\n/**\n * Helper function to create a CustomAssetSource instance\n *\n * @param id - The unique identifier for this asset source\n * @param assets - Array of asset definitions or SelectValue objects to include in this source\n * @returns A new CustomAssetSource instance\n */\nexport function createCustomAssetSource(\n id: string,\n assets: (AssetDefinition | SelectValue)[] = []\n): CustomAssetSource {\n return new CustomAssetSource(id, assets);\n}\n\nexport default CustomAssetSource;\n", "/* eslint-disable no-console */\nimport {\n CreativeEngine,\n type AssetDefinition,\n type AssetQueryData,\n type AssetResult,\n type AssetSource,\n type AssetsQueryResult\n} from '@cesdk/cesdk-js';\n\ntype BlobEntry = {\n id: string;\n blob: Blob;\n};\n\n// Asset definition with meta containing insertedAt timestamp\ntype AssetEntryWithMeta = AssetDefinition;\n\n/**\n * IndexedDBAssetSource implements the AssetSource interface using IndexedDB as the storage backend.\n */\nexport class IndexedDBAssetSource implements AssetSource {\n /** The unique id of the API */\n public readonly id: string;\n\n public readonly engine: CreativeEngine;\n\n private readonly dbName: string;\n\n private readonly dbVersion: number;\n\n private readonly assetStoreName: string = 'assets';\n\n private readonly blobStoreName: string = 'blobs';\n\n private db: IDBDatabase | null = null;\n\n /**\n * Creates a new IndexedDBAssetSource\n *\n * @param id - The unique identifier for this asset source\n * @param {Object} [options] - Optional configuration options.\n * @param {string} [options.dbName] - The name of the database.\n * @param {number} [options.dbVersion] - The version number of the database.\n */\n constructor(\n id: string,\n engine: CreativeEngine,\n options?: {\n dbName?: string;\n dbVersion?: number;\n }\n ) {\n this.id = id;\n this.engine = engine;\n this.dbName = options?.dbName ?? `ly.img.assetSource/${id}`;\n this.dbVersion = options?.dbVersion ?? 1;\n }\n\n /**\n * Initialize the database connection and create object stores if needed\n */\n public async initialize(): Promise<void> {\n if (this.db) {\n return;\n }\n\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(this.dbName, this.dbVersion);\n\n request.onerror = (event) => {\n reject(\n new Error(\n `Failed to open IndexedDB: ${(event.target as IDBRequest).error}`\n )\n );\n };\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n\n // Create asset store if it doesn't exist\n if (!db.objectStoreNames.contains(this.assetStoreName)) {\n db.createObjectStore(this.assetStoreName, {\n keyPath: 'id'\n });\n }\n // Create blob store if it doesn't exist\n if (!db.objectStoreNames.contains(this.blobStoreName)) {\n db.createObjectStore(this.blobStoreName, {\n keyPath: 'id'\n });\n }\n };\n\n request.onsuccess = (event) => {\n this.db = (event.target as IDBOpenDBRequest).result;\n resolve();\n };\n });\n }\n\n /**\n * Close the database connection\n */\n public close(): void {\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n }\n\n /**\n * Find all assets for the given type and the provided query data.\n *\n * @param queryData - The query parameters for filtering assets\n * @param insertionSortOrder - Optional parameter to sort by insertion time: 'asc' for oldest first, 'desc' for newest first (default)\n * @returns A promise that resolves to the query results or undefined if there was an error\n */\n public async findAssets(\n queryData: AssetQueryData\n ): Promise<AssetsQueryResult | undefined> {\n await this.initialize();\n\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n try {\n // Get all assets from the store with specified insertion order\n const assetDefinitions = await this.getAllAssets('asc');\n\n let assetResults = assetDefinitions.reduce((acc, assetDefinition) => {\n const locale = queryData.locale ?? 'en';\n let label = '';\n let tags: string[] = [];\n\n // Handle localized label if available\n if (\n assetDefinition.label != null &&\n typeof assetDefinition.label === 'object' &&\n assetDefinition.label[locale]\n ) {\n label = assetDefinition.label[locale];\n }\n\n // Handle localized tags if available\n if (\n assetDefinition.tags != null &&\n typeof assetDefinition.tags === 'object' &&\n assetDefinition.tags[locale]\n ) {\n tags = assetDefinition.tags[locale];\n }\n\n const result: AssetResult = {\n ...assetDefinition,\n label,\n tags\n };\n\n if (this.filterAsset(result, queryData)) {\n acc.push(result);\n }\n\n return acc;\n }, [] as AssetResult[]);\n\n assetResults = await this.restoreBlobUrls(assetResults);\n\n // Apply sorting\n assetResults = this.sortAssets(assetResults, queryData);\n\n // Apply pagination\n const { page, perPage } = queryData;\n const startIndex = page * perPage;\n const endIndex = startIndex + perPage;\n const paginatedAssets = assetResults.slice(startIndex, endIndex);\n\n // Determine if there's a next page\n const nextPage = endIndex < assetResults.length ? page + 1 : undefined;\n\n const result = {\n assets: paginatedAssets,\n currentPage: page,\n nextPage,\n total: assetResults.length\n };\n\n return result;\n } catch (error) {\n console.error('Error finding assets:', error);\n return undefined;\n }\n }\n\n public async getGroups(): Promise<string[]> {\n await this.initialize();\n\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.assetStoreName, 'readonly');\n const store = transaction.objectStore(this.assetStoreName);\n const request = store.getAll();\n\n request.onsuccess = () => {\n const allGroups = new Set<string>();\n\n // Extract all groups from all assets\n (request.result as AssetResult[]).forEach((asset) => {\n if (asset.groups && Array.isArray(asset.groups)) {\n asset.groups.forEach((group) => allGroups.add(group));\n }\n });\n\n const uniqueGroups = [...allGroups];\n resolve(uniqueGroups);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get groups: ${request.error}`));\n };\n });\n }\n\n /**\n * Adds the given asset to this source. Part of the AssetSource interface.\n *\n * @param asset - The asset definition to add\n */\n public addAsset(asset: AssetDefinition): void {\n this.initialize()\n .then(async () => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.assetStoreName,\n 'readwrite'\n );\n const assetStore = transaction.objectStore(this.assetStoreName);\n\n const blobsToStore = new Set<string>();\n processBlobUrls(asset, (value) => {\n blobsToStore.add(value);\n });\n\n setTimeout(() => {\n this.storeBlobUrls([...blobsToStore]);\n });\n\n // Ensure asset has meta object with insertedAt timestamp\n const assetWithMeta: AssetEntryWithMeta = {\n ...asset,\n meta: {\n ...asset.meta,\n insertedAt: asset.meta?.insertedAt || Date.now()\n }\n };\n\n // Store the asset in the database\n assetStore.put(assetWithMeta);\n\n transaction.onerror = () => {\n console.error(`Failed to add asset: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n /**\n * Removes the given asset from this source. Part of the AssetSource interface.\n *\n * @param assetId - The ID of the asset to remove\n */\n public async removeAsset(assetId: string): Promise<void> {\n const asset = await this.getAsset(assetId);\n\n return this.initialize()\n .then(() => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.assetStoreName,\n 'readwrite'\n );\n const store = transaction.objectStore(this.assetStoreName);\n store.delete(assetId);\n\n transaction.oncomplete = () => {\n processBlobUrls(asset, (value) => {\n this.removeBlob(value);\n });\n this.engine.asset.assetSourceContentsChanged(this.id);\n };\n\n transaction.onerror = () => {\n console.error(`Failed to remove asset: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n /**\n * Removes the given asset from this source. Part of the AssetSource interface.\n *\n * @param assetId - The ID of the asset to remove\n */\n public async removeBlob(blobId: string): Promise<void> {\n return this.initialize()\n .then(() => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.blobStoreName,\n 'readwrite'\n );\n const store = transaction.objectStore(this.blobStoreName);\n store.delete(blobId);\n\n transaction.onerror = () => {\n console.error(`Failed to remove blob: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n /**\n * Get all assets from the database sorted by insertion order (newest to oldest)\n *\n * @param sortOrder - Optional parameter to specify sort order: 'asc' for oldest first, 'desc' for newest first (default)\n * @returns A promise that resolves to an array of all assets\n */\n private async getAllAssets(\n sortOrder: 'asc' | 'desc' = 'desc'\n ): Promise<AssetDefinition[]> {\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.assetStoreName, 'readonly');\n const store = transaction.objectStore(this.assetStoreName);\n const request = store.getAll();\n\n request.onsuccess = () => {\n const assets = request.result as AssetEntryWithMeta[];\n\n // Sort by insertion timestamp\n assets.sort((a, b) => {\n // Default to current time if insertedAt is missing (for backward compatibility)\n // First check in meta.insertedAt, then fallback to legacy _insertedAt for backward compatibility\n const timeA =\n a.meta?.insertedAt || (a as any)._insertedAt || Date.now();\n const timeB =\n b.meta?.insertedAt || (b as any)._insertedAt || Date.now();\n\n // Sort based on requested order\n return sortOrder === 'asc'\n ? timeA - timeB // oldest first\n : timeB - timeA; // newest first (default)\n });\n\n resolve(assets);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get assets: ${request.error}`));\n };\n });\n }\n\n // Retrieve a blob by ID\n async getAsset(id: string): Promise<AssetResult | undefined> {\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.assetStoreName, 'readonly');\n const store = transaction.objectStore(this.assetStoreName);\n const request = store.get(id);\n\n request.onsuccess = () => {\n resolve(request.result as AssetResult);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get blob: ${request.error}`));\n };\n });\n }\n\n // Retrieve a blob by ID\n async getBlob(id: string): Promise<BlobEntry | undefined> {\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.blobStoreName, 'readonly');\n const store = transaction.objectStore(this.blobStoreName);\n const request = store.get(id);\n\n request.onsuccess = () => {\n resolve(request.result as BlobEntry);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get blob: ${request.error}`));\n };\n });\n }\n\n async createBlobUrlFromStore(blobUrl: string): Promise<string> {\n const blobEntry = await this.getBlob(blobUrl);\n if (blobEntry != null) {\n return URL.createObjectURL(blobEntry.blob);\n }\n return blobUrl;\n }\n\n async storeBlobUrls(urls: string[]): Promise<void> {\n const blobsToStore: { [key: string]: Blob } = {};\n await Promise.all(\n urls.map(async (blobUrl) => {\n const blobResponse = await fetch(blobUrl);\n const blob = await blobResponse.blob();\n blobsToStore[blobUrl] = blob;\n })\n );\n\n return this.initialize()\n .then(async () => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.blobStoreName,\n 'readwrite'\n );\n const blobStore = transaction.objectStore(this.blobStoreName);\n\n // Store the asset in the database\n Object.entries(blobsToStore).forEach(([key, blob]) => {\n const asset: BlobEntry = { id: key, blob };\n blobStore.put(asset);\n });\n\n transaction.onerror = () => {\n console.error(`Failed to add blobs: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n async restoreBlobUrls(assets: AssetResult[]): Promise<AssetResult[]> {\n const blobReplaced: { [key: string]: string } = {};\n const blobUrls: Set<string> = new Set();\n processBlobUrls(assets, (value) => {\n blobUrls.add(value);\n });\n\n await Promise.all(\n [...blobUrls].map(async (value) => {\n const newUrl = await this.createBlobUrlFromStore(value);\n blobReplaced[value] = newUrl;\n })\n );\n\n return processBlobUrls(assets, (value) => {\n return blobReplaced[value] ?? value;\n });\n }\n\n /**\n * Returns if the given asset should be filtered based on query data\n *\n * @param asset - The asset to filter\n * @param queryData - The query parameters to filter by\n * @returns true if the asset should be included, false otherwise\n */\n private filterAsset(asset: AssetResult, queryData: AssetQueryData): boolean {\n const { query, tags, groups, excludeGroups } = queryData;\n\n // Filter by query string (search on label and tags)\n if (query && query.trim() !== '') {\n const lowerQuery = query.trim().toLowerCase().split(' ');\n\n const lowerLabel = asset.label?.toLowerCase() ?? '';\n const lowerTags = asset.tags?.map((tag) => tag.toLowerCase()) ?? [];\n\n const matchLabelOrTag = lowerQuery.every((word) => {\n return (\n lowerLabel.includes(word) ||\n lowerTags.some((tag) => tag.includes(word))\n );\n });\n\n if (!matchLabelOrTag) {\n return false;\n }\n }\n\n // Filter by exact tags if provided by the query\n if (tags) {\n const tagList = Array.isArray(tags) ? tags : [tags];\n if (\n tagList.length > 0 &&\n (!asset.tags || !tagList.every((tag) => asset.tags?.includes(tag)))\n ) {\n return false;\n }\n }\n\n // Filter by groups\n if (groups && groups.length > 0) {\n if (\n !asset.groups ||\n !groups.some((group) => asset.groups?.includes(group))\n ) {\n return false;\n }\n }\n\n // Filter by excluded groups\n if (excludeGroups && excludeGroups.length > 0) {\n if (\n asset.groups &&\n asset.groups.some((group) => excludeGroups.includes(group))\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Sort assets based on query data\n *\n * @param assets - The assets to sort\n * @param queryData - The query parameters with sorting information\n * @returns The sorted assets\n */\n private sortAssets(\n assets: AssetResult[],\n queryData: AssetQueryData\n ): AssetResult[] {\n const { sortingOrder, sortKey, sortActiveFirst } = queryData;\n\n // Clone the array to avoid modifying the original\n const sortedAssets = [...assets];\n\n // If no sorting order specified or set to 'None', return the current order\n if (!sortingOrder || sortingOrder === 'None') {\n return sortedAssets;\n }\n\n // Sort by the specified key\n if (sortKey) {\n sortedAssets.sort((a, b) => {\n let valueA;\n let valueB;\n\n if (sortKey === 'id') {\n valueA = a.id;\n valueB = b.id;\n } else {\n // Handle metadata sorting (assuming metadata is stored in a 'metadata' field)\n valueA = a.meta?.[sortKey] ?? null;\n valueB = b.meta?.[sortKey] ?? null;\n }\n\n // Handle null/undefined values\n if (valueA === null || valueA === undefined)\n return sortingOrder === 'Ascending' ? -1 : 1;\n if (valueB === null || valueB === undefined)\n return sortingOrder === 'Ascending' ? 1 : -1;\n\n // Compare values based on sorting order\n if (typeof valueA === 'string' && typeof valueB === 'string') {\n return sortingOrder === 'Ascending'\n ? valueA.localeCompare(valueB)\n : valueB.localeCompare(valueA);\n } else {\n return sortingOrder === 'Ascending'\n ? valueA < valueB\n ? -1\n : valueA > valueB\n ? 1\n : 0\n : valueA > valueB\n ? -1\n : valueA < valueB\n ? 1\n : 0;\n }\n });\n } else if (sortingOrder === 'Descending') {\n // If no sort key is specified, and sorting order set\n // to Descending, just reverse original order\n sortedAssets.reverse();\n }\n\n // Sort by active first if requested\n if (sortActiveFirst) {\n sortedAssets.sort((a, b) => {\n if (a.active && !b.active) return -1;\n if (!a.active && b.active) return 1;\n return 0;\n });\n }\n\n return sortedAssets;\n }\n}\n\n/**\n * Goes through an object and calls a callback for every string value that starts with 'blob:'\n * The callback can return a string to replace the original value\n * @param obj The object to traverse\n * @param callback Function to call when a blob URL is found, can return a replacement value\n * @param path Current path in the object (used for recursion)\n * @returns The modified object (or the original if no replacements were made)\n */\nfunction processBlobUrls<T>(\n obj: T,\n callback: (value: string, path: string) => string | void,\n path: string = ''\n): T {\n // Return the object as is if it's null or not an object\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n for (let index = 0; index < obj.length; index++) {\n const currentPath = path ? `${path}[${index}]` : `[${index}]`;\n\n if (typeof obj[index] === 'string' && obj[index].startsWith('blob:')) {\n const replacement = callback(obj[index], currentPath);\n if (typeof replacement === 'string') {\n obj[index] = replacement;\n }\n } else {\n obj[index] = processBlobUrls(obj[index], callback, currentPath);\n }\n }\n return obj;\n }\n\n // Handle regular objects\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key];\n const currentPath = path ? `${path}.${key}` : key;\n\n if (typeof value === 'string' && value.startsWith('blob:')) {\n const replacement = callback(value, currentPath);\n if (typeof replacement === 'string') {\n // @ts-ignore\n obj[key] = replacement;\n }\n } else {\n obj[key] = processBlobUrls(value, callback, currentPath);\n }\n }\n }\n\n return obj;\n}\n\nexport default IndexedDBAssetSource;\n", "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport type {\n AssetDefinition,\n AssetQueryData,\n AssetResult,\n AssetSource,\n AssetsQueryResult\n} from '@cesdk/cesdk-js';\nimport CreativeEditorSDK from '@cesdk/cesdk-js';\n\n/**\n * AggregatedAssetSource implements the AssetSource interface by aggregating\n * multiple asset sources via the cesdk API and combining their results.\n *\n * This asset source is read-only - it does not support adding or removing assets.\n */\nexport class AggregatedAssetSource implements AssetSource {\n /** The unique id of the asset source */\n public readonly id: string;\n\n /** The Creative Editor SDK instance */\n private cesdk: CreativeEditorSDK;\n\n /** The IDs of asset sources to aggregate */\n private assetSourceIds: string[];\n\n /**\n * Creates a new AggregatedAssetSource\n *\n * @param id - The unique identifier for this asset source\n * @param cesdk - The Creative Editor SDK instance\n * @param assetSourceIds - The IDs of asset sources to aggregate\n */\n constructor(id: string, cesdk: CreativeEditorSDK, assetSourceIds: string[]) {\n this.id = id;\n this.cesdk = cesdk;\n this.assetSourceIds = assetSourceIds;\n }\n\n /**\n * Find assets across all aggregated sources based on the provided query data\n * Results are sorted by the insertedAt timestamp in meta field\n *\n * @param queryData - Query parameters to filter and sort assets\n * @returns Promise with the query results\n */\n async findAssets(\n queryData: AssetQueryData\n ): Promise<AssetsQueryResult | undefined> {\n try {\n // Query all asset sources via cesdk\n const queryPromises = this.assetSourceIds.map((sourceId) =>\n this.cesdk.engine.asset.findAssets(sourceId, {\n ...queryData,\n // Increase page size to get all assets from each source\n // We'll handle pagination after merging\n perPage: 9999,\n page: 0\n })\n );\n\n // Wait for all queries to complete\n const results = await Promise.all(queryPromises);\n\n // Combine all assets from all sources\n let allAssets: AssetResult[] = [];\n results.forEach((result) => {\n if (result?.assets) {\n allAssets = allAssets.concat(result.assets);\n }\n });\n\n // Sort by insertedAt timestamp\n allAssets.sort((a, b) => {\n const timeA = (a.meta?.insertedAt as number) || 0;\n const timeB = (b.meta?.insertedAt as number) || 0;\n\n // Sort newest first (descending)\n return timeB - timeA;\n });\n\n // Apply pagination after merging\n const { page, perPage } = queryData;\n const startIndex = page * perPage;\n const endIndex = startIndex + perPage;\n const paginatedAssets = allAssets.slice(startIndex, endIndex);\n\n // Calculate if there is a next page\n const nextPage = endIndex < allAssets.length ? page + 1 : undefined;\n\n return {\n assets: paginatedAssets,\n currentPage: page,\n nextPage,\n total: allAssets.length\n };\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Error finding assets:', error);\n return undefined;\n }\n }\n\n /**\n * Retrieves all groups from all aggregated asset sources using cesdk\n * @returns Promise with an array of unique group names\n */\n async getGroups(): Promise<string[]> {\n const groupPromises = this.assetSourceIds.map((sourceId) =>\n this.cesdk.engine.asset.getGroups(sourceId)\n );\n\n const groupArrays = await Promise.all(groupPromises);\n\n // Combine and deduplicate groups\n const uniqueGroups = new Set<string>();\n groupArrays.forEach((groups) => {\n groups.forEach((group) => uniqueGroups.add(group));\n });\n\n return Array.from(uniqueGroups);\n }\n\n /**\n * This operation is not supported in AggregatedAssetSource\n * @throws Error - This method is not supported\n */\n addAsset(_asset: AssetDefinition): void {\n throw new Error('AggregatedAssetSource does not support adding assets');\n }\n\n /**\n * This operation is not supported in AggregatedAssetSource\n * @throws Error - This method is not supported\n */\n removeAsset(_assetId: string): void {\n throw new Error('AggregatedAssetSource does not support removing assets');\n }\n}\n\n/**\n * Helper function to create an AggregatedAssetSource instance\n *\n * @param id - The unique identifier for this asset source\n * @param cesdk - The Creative Editor SDK instance\n * @param assetSourceIds - The IDs of asset sources to aggregate\n * @returns A new AggregatedAssetSource instance\n */\nexport function createAggregatedAssetSource(\n id: string,\n cesdk: CreativeEditorSDK,\n assetSourceIds: string[]\n): AggregatedAssetSource {\n return new AggregatedAssetSource(id, cesdk, assetSourceIds);\n}\n\nexport default AggregatedAssetSource;\n", "import { type CreativeEngine } from '@cesdk/cesdk-js';\n\nclass Metadata<V> {\n engine: CreativeEngine;\n\n key: string;\n\n constructor(engine: CreativeEngine, key: string) {\n this.engine = engine;\n this.key = key;\n }\n\n hasData(blockId: number): boolean {\n return (\n this.engine.block.isValid(blockId) &&\n this.engine.block.hasMetadata(blockId, this.key)\n );\n }\n\n get(blockId: number): V | undefined {\n if (this.hasData(blockId)) {\n return JSON.parse(this.engine.block.getMetadata(blockId, this.key));\n }\n return undefined;\n }\n\n set(blockId: number, value: V) {\n this.engine.block.setMetadata(blockId, this.key, JSON.stringify(value));\n }\n\n clear(blockId: number) {\n if (this.engine.block.hasMetadata(blockId, this.key)) {\n this.engine.block.removeMetadata(blockId, this.key);\n }\n }\n}\n\nexport default Metadata;\n", "/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nexport default root;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n", "import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n", "import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\n", "/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n", "/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n", "/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nexport default isFunction;\n", "import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n", "import coreJsData from './_coreJsData.js';\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nexport default isMasked;\n", "/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n", "import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nexport default baseIsNative;\n", "/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n", "import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nexport default getNative;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n", "/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n", "import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nexport default isArrayLike;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n", "/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nexport default baseIsArguments;\n", "import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nexport default isArguments;\n", "/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n", "import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n", "import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nexport default baseIsTypedArray;\n", "/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nexport default nodeUtil;\n", "import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nexport default isTypedArray;\n", "import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default arrayLikeKeys;\n", "/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n", "import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n", "import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeys;\n", "import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nexport default keys;\n", "import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n", "import nativeCreate from './_nativeCreate.js';\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nexport default hashClear;\n", "/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nexport default hashGet;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nexport default hashHas;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nexport default hashSet;\n", "import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nexport default Hash;\n", "/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n", "import eq from './eq.js';\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nexport default assocIndexOf;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nexport default listCacheDelete;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nexport default listCacheGet;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nexport default listCacheHas;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nexport default listCacheSet;\n", "import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nexport default ListCache;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n", "import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nexport default mapCacheClear;\n", "/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n", "import isKeyable from './_isKeyable.js';\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nexport default getMapData;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default mapCacheDelete;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nexport default mapCacheGet;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nexport default mapCacheHas;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nexport default mapCacheSet;\n", "import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nexport default MapCache;\n", "/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n", "import ListCache from './_ListCache.js';\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nexport default stackClear;\n", "/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n", "/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n", "/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n", "import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nexport default stackSet;\n", "import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nexport default Stack;\n", "/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n", "/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n", "import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nexport default getSymbols;\n", "import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nexport default baseGetAllKeys;\n", "import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nexport default getAllKeys;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n", "import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nexport default getTag;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\n", "/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n", "/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n", "import MapCache from './_MapCache.js';\nimport setCacheAdd from './_setCacheAdd.js';\nimport setCacheHas from './_setCacheHas.js';\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nexport default SetCache;\n", "/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n", "/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n", "import SetCache from './_SetCache.js';\nimport arraySome from './_arraySome.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nexport default equalArrays;\n", "/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n", "/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n", "import Symbol from './_Symbol.js';\nimport Uint8Array from './_Uint8Array.js';\nimport eq from './eq.js';\nimport equalArrays from './_equalArrays.js';\nimport mapToArray from './_mapToArray.js';\nimport setToArray from './_setToArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nexport default equalByTag;\n", "import getAllKeys from './_getAllKeys.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nexport default equalObjects;\n", "import Stack from './_Stack.js';\nimport equalArrays from './_equalArrays.js';\nimport equalByTag from './_equalByTag.js';\nimport equalObjects from './_equalObjects.js';\nimport getTag from './_getTag.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nexport default baseIsEqualDeep;\n", "import baseIsEqualDeep from './_baseIsEqualDeep.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nexport default baseIsEqual;\n", "import baseIsEqual from './_baseIsEqual.js';\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\nexport default isEqual;\n", "import { isEqual } from 'lodash-es';\n\nimport Metadata from './Metadata';\nimport {\n PluginStatusError,\n PluginStatusMetadata,\n PluginStatusProcessed,\n PluginStatusProcessing\n} from './types';\n\nclass ImageProcessingMetadata extends Metadata<PluginStatusMetadata> {\n get(blockId: number): PluginStatusMetadata {\n return super.get(blockId) ?? { status: 'IDLE' };\n }\n\n /**\n * Detect if the block has been duplicated with processed or processing\n * fill processing. In that case the processing state is still\n * valid, but blockId and fillId have changed.\n */\n isDuplicate(blockId: number): boolean {\n if (!this.engine.block.isValid(blockId)) return false;\n\n const metadata = this.get(blockId);\n\n if (\n metadata.status === 'IDLE' ||\n metadata.status === 'PENDING' ||\n metadata.status === 'ERROR'\n )\n return false;\n\n if (!this.engine.block.hasFill(blockId)) return false;\n const fillId = this.engine.block.getFill(blockId);\n\n // It cannot be a duplicate if the blockId or fillId are the same\n if (metadata.blockId === blockId || metadata.fillId === fillId)\n return false;\n\n return true;\n }\n\n /**\n * Fixes the metadata if the block has been duplicated, i.e. the blockId and\n * fillId will be updated to the current block/fill.\n *\n * Please note: Call this method only on duplicates (see isDuplicate).\n */\n fixDuplicate(blockId: number) {\n const fillId = this.engine.block.getFill(blockId);\n const metadata = this.get(blockId);\n if (\n metadata.status === 'IDLE' ||\n metadata.status === 'PENDING' ||\n metadata.status === 'ERROR'\n )\n return;\n this.set(blockId, {\n ...metadata,\n blockId,\n fillId\n });\n\n // If it is currently processing the best we can do is to just recover\n // the initial image data, since no processing will update this block and\n // it will be stuck in the processing state.\n if (metadata.status === 'PROCESSING') {\n this.recoverInitialImageData(blockId);\n this.clear(blockId);\n }\n }\n\n /**\n * Check if the image has a consisten metadata state. A inconsistent state is\n * caused by outside changes of the fill data.\n *\n * @returns true if the metadata is consistent, false otherwise\n */\n isConsistent(blockId: number): boolean {\n // In case the block was removed, we just abort and mark it\n // as reset by returning true\n if (!this.engine.block.isValid(blockId)) return false;\n const metadata = this.get(blockId);\n if (metadata.status === 'IDLE' || metadata.status === 'PENDING')\n return true;\n\n if (!this.engine.block.hasFill(blockId)) return false;\n const fillId = this.engine.block.getFill(blockId);\n if (fillId == null) return false;\n\n if (blockId !== metadata.blockId || fillId !== metadata.fillId)\n return false;\n\n const sourceSet = this.engine.block.getSourceSet(\n fillId,\n 'fill/image/sourceSet'\n );\n const imageFileURI = this.engine.block.getString(\n fillId,\n 'fill/image/imageFileURI'\n );\n\n if (\n sourceSet.length === 0 &&\n !imageFileURI &&\n metadata.status === 'PROCESSING'\n ) {\n // While we process it is OK to have no image file URI and no source set\n // (which we cleared to show the spinning loader)\n return true;\n }\n\n // Source sets have precedence over imageFileURI so if we have a source set,\n // we only need to check if it has changed to something else.\n if (sourceSet?.length > 0) {\n const initialSourceSet = metadata.initialSourceSet;\n // If we have already processed the image, we need to check if the source set\n // we need to check against both source sets, the removed and the initial\n if (metadata.status !== 'PROCESSED') {\n if (!isEqual(sourceSet, initialSourceSet)) {\n return false;\n }\n }\n } else {\n if (metadata.status !== 'PROCESSED') {\n if (imageFileURI !== metadata.initialImageFileURI) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Recover the initial values to avoid the loading spinner and have the same\n * state as before the fill processing was started.\n */\n recoverInitialImageData(blockId: number) {\n const blockApi = this.engine.block;\n if (!blockApi.hasFill(blockId)) return; // Nothing to recover (no fill anymore)\n\n const metadata = this.get(blockId);\n\n if (metadata.status === 'PENDING' || metadata.status === 'IDLE') {\n return;\n }\n\n const initialSourceSet = metadata.initialSourceSet;\n const initialImageFileURI = metadata.initialImageFileURI;\n const initialPreviewFileURI = metadata.initialPreviewFileURI;\n\n const fillId = this.getValidFill(blockId, metadata);\n if (fillId == null) return;\n\n if (initialImageFileURI) {\n this.engine.block.setString(\n fillId,\n 'fill/image/imageFileURI',\n initialImageFileURI\n );\n }\n if (initialPreviewFileURI) {\n this.engine.block.setString(\n fillId,\n 'fill/image/previewFileURI',\n initialPreviewFileURI\n );\n }\n if (initialSourceSet.length > 0) {\n this.engine.block.setSourceSet(\n fillId,\n 'fill/image/sourceSet',\n initialSourceSet\n );\n }\n }\n\n /**\n * Returns the fill id of the block if it has a valid fill that was used for\n * fill processing. Returns undefined otherwise.\n */\n private getValidFill(\n blockId: number,\n metadata: PluginStatusProcessing | PluginStatusError | PluginStatusProcessed\n ): number | undefined {\n if (\n !this.engine.block.isValid(blockId) ||\n !this.engine.block.hasFill(blockId) ||\n blockId !== metadata.blockId\n ) {\n return undefined;\n }\n const fillId = this.engine.block.getFill(blockId);\n if (fillId !== metadata.fillId) {\n return undefined;\n }\n\n return fillId;\n }\n}\n\nexport default ImageProcessingMetadata;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { FillProcessingMetadata } from '..';\nimport {\n PluginStatusProcessed,\n PluginStatusProcessing\n} from '../metadata/types';\n\ninterface FillProcessor<T> {\n processFill(metadataState: PluginStatusProcessing): Promise<T>;\n\n commitProcessing(\n data: T,\n metadataState: PluginStatusProcessed\n ): number | void;\n}\n\nasync function fillProcessing<T>(\n blockId: number,\n cesdk: CreativeEditorSDK,\n metadata: FillProcessingMetadata,\n processor: FillProcessor<T>\n) {\n const blockApi = cesdk.engine.block;\n if (!blockApi.hasFill(blockId))\n throw new Error('Block does not support fill');\n\n const fillId = blockApi.getFill(blockId);\n\n // Get the current image URI and source set as initial values.\n const initialSourceSet = blockApi.getSourceSet(\n fillId,\n 'fill/image/sourceSet'\n );\n const initialImageFileURI = blockApi.getString(\n fillId,\n 'fill/image/imageFileURI'\n );\n const initialPreviewFileURI = blockApi.getString(\n fillId,\n 'fill/image/previewFileURI'\n );\n try {\n cesdk.engine.block.setState(fillId, {\n type: 'Pending',\n progress: 0\n });\n\n const status: PluginStatusProcessing = {\n ...metadata.get(blockId),\n version: PLUGIN_VERSION,\n initialSourceSet,\n initialImageFileURI,\n initialPreviewFileURI,\n blockId,\n fillId,\n status: 'PROCESSING'\n };\n\n metadata.set(blockId, status);\n\n const processedData = await processor.processFill(status);\n // Check for externally changed state while we were applying the mask and\n // do not proceed if the state was reset.\n if (\n metadata.get(blockId).status !== 'PROCESSING' ||\n !metadata.isConsistent(blockId)\n )\n return;\n\n // Check for externally changed state while we were uploading and\n // do not proceed if the state was reset.\n if (\n metadata.get(blockId).status !== 'PROCESSING' ||\n !metadata.isConsistent(blockId)\n )\n return;\n\n if (processedData == null) return;\n\n const metadataStateProcessed: PluginStatusProcessed = {\n version: PLUGIN_VERSION,\n initialSourceSet,\n initialImageFileURI,\n initialPreviewFileURI,\n blockId,\n fillId,\n status: 'PROCESSED'\n };\n\n const blockIdOrVoid = processor.commitProcessing(\n processedData,\n metadataStateProcessed\n );\n\n // If a new block was created, we do not update the metadata.\n if (blockIdOrVoid == null || blockIdOrVoid === blockId) {\n metadata.set(blockId, metadataStateProcessed);\n }\n\n // Finally, create an undo step\n cesdk.engine.editor.addUndoStep();\n } catch (error) {\n if (cesdk.engine.block.isValid(blockId)) {\n metadata.set(blockId, {\n version: PLUGIN_VERSION,\n initialSourceSet,\n initialImageFileURI,\n initialPreviewFileURI,\n blockId,\n fillId,\n status: 'ERROR'\n });\n\n metadata.recoverInitialImageData(blockId);\n }\n\n if (\n error != null &&\n typeof error === 'object' &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n const message =\n error.message === 'signal timed out'\n ? 'Processing canceled due to timeout'\n : error.message;\n cesdk.ui.showNotification({\n type: 'error',\n message\n });\n }\n\n // eslint-disable-next-line no-console\n console.log(error);\n } finally {\n if (cesdk.engine.block.isValid(fillId)) {\n cesdk.engine.block.setState(fillId, { type: 'Ready' });\n }\n }\n}\n\nexport default fillProcessing;\n", "export function getFeatureId(pluginId: string): string {\n return `${pluginId}.fillProcessing.feature`;\n}\n\nexport function getCanvasMenuComponentIds(pluginId: string): string[] {\n return [`${pluginId}.canvasMenu`, `${pluginId}.fillProcessing.canvasMenu`];\n}\n\nexport function getDockComponentIds(pluginId: string): string[] {\n return [`${pluginId}.dock`, `${pluginId}.fillProcessing.dock`];\n}\n\nexport function getInspectorBarComponentIds(pluginId: string): string[] {\n return [\n `${pluginId}.inspectorBar`,\n `${pluginId}.fillProcessing.inspectorBar`\n ];\n}\n\nexport function getNavigationBarComponentIds(pluginId: string): string[] {\n return [\n `${pluginId}.navigationBar`,\n `${pluginId}.fillProcessing.navigationBar`\n ];\n}\n\nexport function getCanvasBarComponentIds(pluginId: string): string[] {\n return [`${pluginId}.canvasBar`, `${pluginId}.fillProcessing.canvasBar`];\n}\n\nexport function getI18nCanvasMenuLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.canvasMenu.button.label`;\n}\n\nexport function getI18nDockLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.dock.button.label`;\n}\n\nexport function getI18nInspectorBarLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.inspectorBar.button.label`;\n}\n\nexport function getI18nNavigationBarLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.navigationBar.button.label`;\n}\n\nexport function getI18nCanvasBarLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.canvasBar.button.label`;\n}\n", "import type CreativeEditorSDK from '@cesdk/cesdk-js';\n\nimport { FillProcessingMetadata } from '..';\nimport { getFeatureId } from './constants';\n\nexport default function handleFillProcessing(\n cesdk: CreativeEditorSDK,\n {\n pluginId,\n process\n }: {\n pluginId: string;\n icon?: string;\n process: (blockId: number, metadata: FillProcessingMetadata) => void;\n }\n): {\n featureId: string;\n} {\n const featureId = getFeatureId(pluginId);\n\n const metadata = new FillProcessingMetadata(cesdk.engine, pluginId);\n\n enableFeatures(cesdk, metadata, featureId);\n\n cesdk.engine.event.subscribe([], async (events) => {\n events.forEach((e) => {\n const id = e.block;\n if (!cesdk.engine.block.isValid(id) || !metadata.hasData(id)) {\n return;\n }\n\n if (e.type === 'Created') {\n if (metadata.isDuplicate(id)) {\n metadata.fixDuplicate(id);\n }\n } else if (e.type === 'Updated') {\n switch (metadata.get(id).status) {\n case 'PENDING': {\n if (\n cesdk.feature.isEnabled(featureId, {\n engine: cesdk.engine\n }) &&\n cesdk.engine.block.isAllowedByScope(id, 'fill/change') &&\n cesdk.engine.block.getState(id).type !== 'Pending'\n ) {\n process(id, metadata);\n }\n break;\n }\n\n case 'PROCESSING':\n case 'PROCESSED': {\n if (!metadata.isConsistent(id)) {\n metadata.clear(id);\n }\n break;\n }\n\n default: {\n // We do not care about other states\n }\n }\n }\n });\n });\n\n return { featureId };\n}\n\n/**\n * Defines the feature that determines in which context (on which block)\n * fill processing is allowed/enabled.\n */\nfunction enableFeatures(\n cesdk: CreativeEditorSDK,\n metadata: FillProcessingMetadata,\n featureId: string\n) {\n cesdk.feature.enable(featureId, ({ engine }) => {\n const selectedIds = engine.block.findAllSelected();\n if (selectedIds.length !== 1) {\n return false;\n }\n const [selectedId] = selectedIds;\n\n if (!cesdk.engine.block.isVisible(selectedId)) return false;\n\n if (cesdk.engine.block.hasFill(selectedId)) {\n const kind = cesdk.engine.block.getKind(selectedId);\n if (kind === 'sticker') return false;\n\n const fillId = cesdk.engine.block.getFill(selectedId);\n const fillType = cesdk.engine.block.getType(fillId);\n\n if (fillType !== '//ly.img.ubq/fill/image') {\n return false;\n }\n\n const fileUri = engine.block.getString(fillId, 'fill/image/imageFileURI');\n const sourceSet = engine.block.getSourceSet(\n fillId,\n 'fill/image/sourceSet'\n );\n\n if (sourceSet.length > 0 || fileUri !== '') return true;\n\n // If we are in a processing state we do not have a imageFileURI or\n // source set set (to show the loading spinner), but the feature is still\n // enabled.\n return metadata.get(selectedId).status === 'PROCESSING';\n }\n\n return false;\n });\n}\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { FillProcessingMetadata } from '..';\nimport {\n getCanvasBarComponentIds,\n getCanvasMenuComponentIds,\n getDockComponentIds,\n getFeatureId,\n getI18nCanvasBarLabel,\n getI18nCanvasMenuLabel,\n getI18nDockLabel,\n getI18nInspectorBarLabel,\n getI18nNavigationBarLabel,\n getInspectorBarComponentIds,\n getNavigationBarComponentIds\n} from './constants';\n\nexport type Location =\n | 'inspectorBar'\n | 'navigationBar'\n | 'canvasBarTop'\n | 'canvasBarBottom'\n | 'canvasMenu'\n | 'dock';\n\n/**\n * Registers the components that can be used to process the fill of\n * a block.\n */\nexport default function registerFillProcessingComponents(\n cesdk: CreativeEditorSDK,\n options: {\n pluginId: string;\n icon?: string;\n locations?: Location | Location[];\n }\n): {\n canvasMenuComponentId: string;\n dockComponentId: string;\n\n translationsKeys: {\n inspectorBarLabel: string;\n navigationBarLabel: string;\n canvasBarLabel: string;\n canvasMenuLabel: string;\n dockLabel: string;\n };\n} {\n const { pluginId, locations } = options;\n const metadata = new FillProcessingMetadata(cesdk.engine, pluginId);\n\n const canvasMenuLabel = getI18nCanvasMenuLabel(pluginId);\n const canvasMenuComponentIds = getCanvasMenuComponentIds(pluginId);\n const canvasMenuComponentId = canvasMenuComponentIds[0];\n\n const dockLabel = getI18nDockLabel(pluginId);\n const dockComponentIds = getDockComponentIds(pluginId);\n const dockComponentId = dockComponentIds[0];\n\n const inspectorBarLabel = getI18nInspectorBarLabel(pluginId);\n const inspectorBarComponentIds = getInspectorBarComponentIds(pluginId);\n const inspectorBarComponentId = inspectorBarComponentIds[0];\n\n const navigationBarLabel = getI18nNavigationBarLabel(pluginId);\n const navigationBarComponentIds = getNavigationBarComponentIds(pluginId);\n const navigationBarComponentId = navigationBarComponentIds[0];\n\n const canvasBarLabel = getI18nCanvasBarLabel(pluginId);\n const canvasBarComponentIds = getCanvasBarComponentIds(pluginId);\n const canvasBarComponentId = canvasBarComponentIds[0];\n\n const featureId = getFeatureId(pluginId);\n\n if (locations?.includes('inspectorBar')) {\n cesdk.ui.setInspectorBarOrder([\n inspectorBarComponentId,\n ...cesdk.ui.getInspectorBarOrder()\n ]);\n }\n\n if (locations?.includes('navigationBar')) {\n cesdk.ui.setNavigationBarOrder([\n navigationBarComponentId,\n ...cesdk.ui.getNavigationBarOrder()\n ]);\n }\n\n if (locations?.includes('canvasBarTop')) {\n cesdk.ui.setCanvasBarOrder(\n [canvasBarComponentId, ...cesdk.ui.getCanvasBarOrder('top')],\n 'top'\n );\n }\n\n if (locations?.includes('canvasBarBottom')) {\n cesdk.ui.setCanvasBarOrder(\n [canvasBarComponentId, ...cesdk.ui.getCanvasBarOrder('bottom')],\n 'bottom'\n );\n }\n\n if (locations?.includes('canvasMenu')) {\n cesdk.ui.setCanvasMenuOrder([\n canvasMenuComponentId,\n ...cesdk.ui.getCanvasMenuOrder()\n ]);\n }\n\n if (locations?.includes('dock')) {\n cesdk.ui.setDockOrder([...cesdk.ui.getDockOrder(), dockComponentId]);\n }\n\n cesdk.ui.registerComponent(\n dockComponentIds,\n ({ builder: { Button }, engine }) => {\n const [id] = engine.block.findAllSelected();\n\n let isDisabled = false;\n let isLoading = false;\n let loadingProgress: number | undefined;\n\n if (id == null) {\n isDisabled = true;\n }\n\n if (\n !isDisabled &&\n !cesdk.feature.isEnabled(featureId, {\n engine\n })\n ) {\n isDisabled = true;\n }\n\n if (\n !isDisabled &&\n !cesdk.engine.block.isAllowedByScope(id, 'fill/change')\n ) {\n isDisabled = true;\n }\n\n if (!isDisabled && engine.block.getState(id)?.type === 'Pending') {\n isDisabled = true;\n }\n\n if (!isDisabled) {\n const currentMetadata = metadata.get(id);\n\n isLoading = currentMetadata.status === 'PROCESSING';\n isDisabled =\n currentMetadata.status === 'PENDING' ||\n currentMetadata.status === 'PROCESSING';\n\n if (\n currentMetadata.status === 'PROCESSING' &&\n currentMetadata.progress\n ) {\n const { current, total } = currentMetadata.progress;\n loadingProgress = (current / total) * 100;\n }\n }\n\n const buttonId = `${dockComponentId}.button`;\n Button(buttonId, {\n label: dockLabel,\n icon: options.icon,\n isLoading,\n isDisabled,\n loadingProgress,\n onClick: () => {\n const currentMetadata = metadata.get(id);\n\n if (\n currentMetadata.status === 'IDLE' ||\n currentMetadata.status === 'ERROR' ||\n currentMetadata.status === 'PROCESSED'\n ) {\n metadata.set(id, {\n status: 'PENDING'\n });\n }\n }\n });\n }\n );\n\n const buttonComponents: {\n componentIds: string[];\n label: string;\n variant: 'plain' | 'regular';\n }[] = [\n {\n componentIds: inspectorBarComponentIds,\n variant: 'plain',\n label: inspectorBarLabel\n },\n {\n componentIds: navigationBarComponentIds,\n variant: 'regular',\n label: navigationBarLabel\n },\n {\n componentIds: canvasBarComponentIds,\n variant: 'regular',\n label: canvasBarLabel\n },\n {\n componentIds: canvasMenuComponentIds,\n variant: 'plain',\n label: canvasMenuLabel\n }\n ];\n\n buttonComponents.forEach(({ componentIds, label, variant }) => {\n const componentId = componentIds[0];\n cesdk.ui.registerComponent(\n componentIds,\n ({ builder: { Button }, engine }) => {\n if (\n !cesdk.feature.isEnabled(featureId, {\n engine\n })\n ) {\n return;\n }\n\n const [id] = engine.block.findAllSelected();\n\n if (!cesdk.engine.block.isAllowedByScope(id, 'fill/change')) return;\n\n const currentMetadata = metadata.get(id);\n\n const isLoading = currentMetadata.status === 'PROCESSING';\n const isDisabled =\n currentMetadata.status === 'PENDING' ||\n currentMetadata.status === 'PROCESSING' ||\n engine.block.getState(id)?.type === 'Pending';\n\n let loadingProgress: number | undefined;\n if (isLoading && currentMetadata.progress) {\n const { current, total } = currentMetadata.progress;\n loadingProgress = (current / total) * 100;\n }\n\n const buttonId = `${componentId}.button`;\n Button(buttonId, {\n icon: options.icon,\n label,\n variant,\n isLoading,\n isDisabled,\n loadingProgress,\n onClick: () => {\n if (\n currentMetadata.status === 'IDLE' ||\n currentMetadata.status === 'ERROR' ||\n currentMetadata.status === 'PROCESSED'\n ) {\n metadata.set(id, {\n status: 'PENDING'\n });\n }\n }\n });\n }\n );\n });\n\n return {\n canvasMenuComponentId,\n dockComponentId,\n translationsKeys: {\n inspectorBarLabel,\n navigationBarLabel,\n canvasBarLabel,\n canvasMenuLabel,\n dockLabel\n }\n };\n}\n", "import { type RGBAColor } from '@cesdk/cesdk-js';\n\nconst HEX_COLOR_PATTERN = new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/, 'i');\nconst HEX_SINGLE_CHAR_COMPONENTS_PATTERN = new RegExp(/[A-Fa-f0-9]{1}/, 'g');\nconst HEX_DOUBLE_CHAR_COMPONENTS_PATTERN = new RegExp(/[A-Fa-f0-9]{2}/, 'g');\n\n/** @public */\nexport const rgbaToHex = (rgba: RGBAColor, includeAlpha = false): string => {\n const { r, g, b, a } = rgba;\n const rByte = Math.round(255 * r);\n const gByte = Math.round(255 * g);\n const bByte = Math.round(255 * b);\n const aByte = Math.round(255 * a);\n const byteToHex = (byte: number) => {\n return byte.toString(16).padStart(2, '0');\n };\n return `#${byteToHex(rByte)}${byteToHex(gByte)}${byteToHex(bByte)}${\n includeAlpha ? byteToHex(aByte) : ''\n }`;\n};\n\n/** @public */\nexport const hexToRgba = (hexString: string): RGBAColor => {\n const rgbaHexToColor = (\n r: string,\n g: string,\n b: string,\n a: string | undefined,\n max: number\n ) => {\n return {\n r: parseInt(r, 16) / max,\n g: parseInt(g, 16) / max,\n b: parseInt(b, 16) / max,\n a: a === undefined ? 1 : parseInt(a, 16) / max\n };\n };\n\n if (hexString.startsWith('#')) {\n if (hexString.length === 4 || hexString.length === 5) {\n const hexMatch = hexString.match(HEX_SINGLE_CHAR_COMPONENTS_PATTERN);\n if (hexMatch) {\n const [r, g, b, a] = hexMatch;\n return rgbaHexToColor(r, g, b, a, 15);\n }\n }\n if (hexString.length === 7 || hexString.length === 8) {\n const hexMatch = hexString.match(HEX_DOUBLE_CHAR_COMPONENTS_PATTERN);\n if (hexMatch) {\n const [r, g, b, a] = hexMatch;\n return rgbaHexToColor(r, g, b, a, 255);\n }\n }\n }\n\n throw new Error(\n 'Invalid hex string! Allowed RGB formats are \"#FFF\" and \"#FFFFFF\". Allowed RGBA formats are \"#FFFF\" and \"#FFFFFFFF'\n );\n};\n\n/** @public */\nexport const isValidHexColor = (hexString: string): boolean => {\n return HEX_COLOR_PATTERN.test(hexString);\n};\n", "import type CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { CreativeEngine } from '@cesdk/cesdk-js';\n\n/**\n * Uploads a blob with the help of CE.SDK\n */\nexport async function uploadBlob(\n blob: Blob,\n initialUri: string,\n cesdk: CreativeEditorSDK\n) {\n const pathname = new URL(initialUri).pathname;\n const parts = pathname.split('/');\n const extension = mimeTypeToExtension(blob.type);\n const filename = parts[parts.length - 1]?.split('.')?.[0] ?? 'asset';\n const filenameWithExtension = `${filename}.${extension}`;\n\n const uploadedAssets = await cesdk.unstable_upload(\n new File([blob], filenameWithExtension, { type: blob.type }),\n () => {\n // TODO Delegate process to UI component\n }\n );\n\n const url = uploadedAssets.meta?.uri;\n if (url == null) {\n throw new Error('Could not upload processed fill');\n }\n return url;\n}\n\n/**\n * Returns the file extension for a given mime type.\n */\nexport function mimeTypeToExtension(mimeType: string): string {\n const extensions: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'image/svg+xml': 'svg'\n };\n return extensions[mimeType] ?? 'png';\n}\n\nexport async function fetchImageBlob(uri: string): Promise<Blob> {\n return fetch(uri).then((response) => response.blob());\n}\n\n/**\n * Converts a buffer URI to a object url.\n */\nexport async function bufferURIToObjectURL(\n uri: string,\n engine: CreativeEngine\n): Promise<string> {\n if (uri.startsWith('buffer:')) {\n const mimeType = await engine.editor.getMimeType(uri);\n const length = engine.editor.getBufferLength(uri);\n const data = engine.editor.getBufferData(uri, 0, length);\n const blob = new Blob([data], { type: mimeType });\n return URL.createObjectURL(blob);\n } else {\n return uri;\n }\n}\n", "function uuid4() {\n /* eslint-disable no-bitwise */\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n /* eslint-enable no-bitwise */\n });\n}\n\nexport default uuid4;\n", "import { bufferURIToObjectURL } from './upload';\nimport { type CreativeEngine } from '@cesdk/cesdk-js';\n\n/**\n * Get the dimensions of an image from its URL\n *\n * @param url - The URL of the image\n * @returns A promise that resolves to an object containing the width and height of the image\n */\nexport async function getImageDimensionsFromURL(\n url: string,\n engine: CreativeEngine\n): Promise<{ width: number; height: number }> {\n const resolvedUrl = await bufferURIToObjectURL(url, engine);\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => {\n resolve({ width: img.width, height: img.height });\n };\n img.onerror = reject;\n img.src = resolvedUrl;\n });\n}\n\n/**\n * Get the URI of an image from a block ID, either the first source of a source set or\n * the image file URI. Will handle buffer URIs and convert them to object URLs.\n */\nexport async function getImageUri(\n blockId: number,\n engine: CreativeEngine,\n options?: { throwErrorIfSvg?: boolean }\n): Promise<string> {\n let uri;\n const fillBlock = engine.block.getFill(blockId);\n const sourceSet = engine.block.getSourceSet(\n fillBlock,\n 'fill/image/sourceSet'\n );\n const [source] = sourceSet;\n if (source == null) {\n uri = engine.block.getString(fillBlock, 'fill/image/imageFileURI');\n if (uri == null) throw new Error('No image source/uri found');\n } else {\n uri = source.uri;\n }\n\n // Check if the image is SVG (not supported)\n if (options?.throwErrorIfSvg) {\n const mimeType = await engine.editor.getMimeType(uri);\n if (mimeType === 'image/svg+xml') {\n throw new Error('SVG images are not supported');\n }\n }\n\n return bufferURIToObjectURL(uri, engine);\n}\n", "/**\n * Checks if a value is defined (not undefined).\n *\n * Helpful to filter out undefined values from an array or collection\n * while keeping the type information intact.\n *\n * ```\n * array.filter(isDefined)\n * ```\n */\nfunction isDefined<T>(value: T | undefined): value is T {\n return value !== undefined;\n}\n\nexport default isDefined;\n", "import formatsIconSprite from './icons/formats';\n\nconst Icons = {\n Formats: formatsIconSprite\n};\n\nexport { Icons };\n\nexport { CustomAssetSource } from './assetSources/CustomAssetSource';\n\nexport { IndexedDBAssetSource } from './assetSources/IndexedDBAssetSource';\n\nexport { AggregatedAssetSource } from './assetSources/AggregatedAssetSource';\n\nexport { default as Metadata } from './metadata/Metadata';\n\nexport { default as FillProcessingMetadata } from './metadata/FillProcessingMetadata';\n\nexport { default as fillProcessing } from './processing/fillProcessing';\n\nexport { default as initializeFillProcessing } from './processing/initializeFillProcessing';\n\nexport { default as registerFillProcessingComponents } from './processing/registerFillProcessingComponents';\n\nexport { type Optional } from './types/Optional';\n\nexport {\n type Location,\n type UserInterfaceConfiguration\n} from './types/UserInterfaceConfiguration';\n\nexport { hexToRgba, isValidHexColor, rgbaToHex } from './utils/colors';\n\nexport {\n uploadBlob,\n fetchImageBlob,\n bufferURIToObjectURL,\n mimeTypeToExtension\n} from './utils/upload';\n\nexport { default as uuid } from './utils/uuid';\n\nexport { getImageDimensionsFromURL, getImageUri } from './utils/images';\n\nexport { default as isDefined } from './utils/isDefined';\n", "import CreativeEditorSDK, { AssetResult } from '@cesdk/cesdk-js';\nimport { RenderCustomProperty } from '../generation/provider';\n\n/**\n * Provides render function for a image url property that allows\n * to select an image from the library with a MediaPreview\n *\n * By default this expects the property key to be `image_url`. This can be changed in the options.\n */\nfunction renderImageUrlProperty(\n provderId: string,\n options: {\n cesdk: CreativeEditorSDK;\n propertyKey?: string;\n defaultUrl?: string;\n }\n): RenderCustomProperty {\n const { cesdk } = options;\n const propertyKey = options.propertyKey ?? 'image_url';\n const panelIdForImageSelection = getImageSelectionPanelId(provderId);\n\n cesdk.i18n.setTranslations({\n en: {\n [`panel.${panelIdForImageSelection}`]: 'Select Image To Change'\n }\n });\n\n createPanels(provderId, cesdk);\n\n const customProperties: RenderCustomProperty = {\n [propertyKey]: (context, property) => {\n const {\n builder,\n experimental: { global },\n payload\n } = context;\n const defaultUrl = payload?.url ?? options.defaultUrl;\n const stateValue = global<string>(\n `${provderId}.${property.id}`,\n defaultUrl\n );\n\n builder.MediaPreview(property.id, {\n preview: {\n type: 'image',\n uri: stateValue.value\n },\n action: {\n label: 'Select Image',\n onClick: () => {\n if (cesdk == null) return;\n\n cesdk.ui.openPanel(panelIdForImageSelection, {\n payload: {\n onSelect: (assetResult: AssetResult) => {\n if (assetResult.meta?.uri != null) {\n stateValue.setValue(assetResult.meta?.uri);\n }\n }\n }\n });\n }\n }\n });\n\n return () => {\n return {\n id: property.id,\n type: 'string',\n value: stateValue.value\n };\n };\n }\n };\n\n return customProperties;\n}\n\nfunction createPanels(providerId: string, cesdk?: CreativeEditorSDK) {\n if (cesdk == null) return;\n\n cesdk.ui.registerPanel<{\n onSelect: (assetResult: AssetResult) => void;\n }>(getImageSelectionPanelId(providerId), ({ builder, payload }) => {\n builder.Library(`${providerId}.library.image`, {\n entries: ['ly.img.image'],\n onSelect: async (asset) => {\n const uri = asset?.meta?.uri;\n if (uri == null) return;\n\n const mimeType = await cesdk.engine.editor.getMimeType(uri);\n if (mimeType === 'image/svg+xml') {\n cesdk.ui.showNotification({\n type: 'warning',\n message:\n 'SVG images are not supported. Please choose a different image.'\n });\n } else if (mimeType.startsWith('image/')) {\n payload?.onSelect(asset);\n cesdk?.ui.closePanel(getImageSelectionPanelId(providerId));\n } else {\n cesdk.ui.showNotification({\n type: 'warning',\n message: `Only images are supported. Found '${mimeType}'. Please choose a different image.`\n });\n }\n }\n });\n });\n}\n\nfunction getImageSelectionPanelId(providerId: string) {\n return `ly.img.ai/${providerId}.imageSelection`;\n}\n\nexport default renderImageUrlProperty;\n", "import { type OpenAPIV3 } from 'openapi-types';\n\n/**\n * Resolves a JSON reference path within a document\n * @param document The OpenAPI document\n * @param refPath The reference path (e.g. \"#/components/schemas/MySchema\")\n * @returns The resolved object from the document\n */\nexport function resolveReference(\n document: OpenAPIV3.Document,\n refPath: string\n): unknown {\n // Only handle internal references\n if (!refPath.startsWith('#/')) {\n throw new Error(`External references are not supported: ${refPath}`);\n }\n\n // Remove the leading #/\n const path = refPath.substring(2).split('/');\n let current: any = document;\n\n // Navigate through the path\n for (const segment of path) {\n if (current === undefined || current === null) {\n throw new Error(`Invalid reference path: ${refPath}`);\n }\n current = current[segment];\n }\n\n if (current === undefined) {\n throw new Error(`Reference not found: ${refPath}`);\n }\n\n return current;\n}\n\n/**\n * Recursively dereferences all $ref properties in an object\n * @param document The original document for resolving references\n * @param obj The object to dereference\n * @param visited Set of visited objects to prevent circular references\n * @returns The dereferenced object\n */\nfunction dereferenceObject(\n document: OpenAPIV3.Document,\n obj: any,\n visited = new Set<any>()\n): any {\n // Handle null or undefined\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n // If we've seen this object before, return it to avoid circular references\n if (visited.has(obj)) {\n return obj;\n }\n\n // Add the current object to the visited set\n visited.add(obj);\n\n // Handle $ref\n if (obj.$ref && typeof obj.$ref === 'string') {\n // Get the referenced object\n const referenced = resolveReference(document, obj.$ref);\n // Dereference the referenced object\n const dereferenced = dereferenceObject(document, referenced, visited);\n\n // Merge other properties from the original object\n const result = { ...dereferenced };\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key) && key !== '$ref') {\n result[key] = dereferenceObject(document, obj[key], visited);\n }\n }\n return result;\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return obj.map((item) => dereferenceObject(document, item, visited));\n }\n\n // Handle objects\n if (typeof obj === 'object') {\n const result: any = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = dereferenceObject(document, obj[key], visited);\n }\n }\n return result;\n }\n\n // Return primitives as is\n return obj;\n}\n\n/**\n * Dereferences all $ref properties in an OpenAPI document\n * @param document The OpenAPI document to dereference\n * @returns A new document with all references resolved\n */\nexport default function dereferenceDocument(\n document: OpenAPIV3.Document\n): OpenAPIV3.Document {\n return dereferenceObject(document, { ...document }) as OpenAPIV3.Document;\n}\n", "import { OpenAPIV3 } from 'openapi-types';\n\n/**\n * Checks if an unknown object is an OpenAPI schema (first level only)\n *\n * @param obj - The object to check (potentially undefined)\n * @param debug - If true, log the reason when validation fails\n * @returns A boolean indicating whether the object is an OpenAPI schema\n */\nexport function isOpenAPISchema(\n obj: unknown,\n debug: boolean = false\n): obj is OpenAPIV3.SchemaObject {\n // Helper function to log debug messages and return false\n const fail = (reason: string): false => {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(`OpenAPI Schema validation failed: ${reason}`);\n }\n return false;\n };\n\n // Check if obj is an object and not null\n if (typeof obj !== 'object' || obj === null) {\n return fail(\n `Input is ${obj === null ? 'null' : typeof obj}, not an object`\n );\n }\n\n const schema = obj as Record<string, any>;\n\n // Basic property validation - most schemas have at least one of these properties\n const hasSchemaTypeProperties =\n typeof schema.type === 'string' ||\n Array.isArray(schema.enum) ||\n typeof schema.properties === 'object' ||\n typeof schema.items === 'object' ||\n typeof schema.allOf === 'object' ||\n typeof schema.anyOf === 'object' ||\n typeof schema.oneOf === 'object' ||\n typeof schema.not === 'object';\n\n if (!hasSchemaTypeProperties) {\n return fail(\n 'Missing required schema-defining properties (type, enum, properties, items, allOf, anyOf, oneOf, not)'\n );\n }\n\n // If it has a type, validate it's one of the allowed OpenAPI schema types\n if (schema.type !== undefined) {\n const validTypes = [\n 'string',\n 'number',\n 'integer',\n 'boolean',\n 'array',\n 'object',\n 'null'\n ];\n\n // Type can be a string or an array of strings\n if (typeof schema.type === 'string') {\n if (!validTypes.includes(schema.type)) {\n return fail(\n `Invalid type: ${schema.type}. Must be one of ${validTypes.join(\n ', '\n )}`\n );\n }\n } else if (Array.isArray(schema.type)) {\n for (const type of schema.type) {\n if (typeof type !== 'string' || !validTypes.includes(type)) {\n return fail(\n `Array of types contains invalid value: ${type}. Must be one of ${validTypes.join(\n ', '\n )}`\n );\n }\n }\n } else {\n return fail(\n `Type must be a string or array of strings, got ${typeof schema.type}`\n );\n }\n }\n\n // If it has items (for array type), validate that items is an object (without recursion)\n if (schema.items !== undefined) {\n if (typeof schema.items !== 'object' || schema.items === null) {\n return fail(\n `Items must be an object, got ${\n schema.items === null ? 'null' : typeof schema.items\n }`\n );\n }\n }\n\n // If it has properties (for object type), validate that properties is an object (without recursion)\n if (schema.properties !== undefined) {\n if (typeof schema.properties !== 'object' || schema.properties === null) {\n return fail(\n `Properties must be an object, got ${\n schema.properties === null ? 'null' : typeof schema.properties\n }`\n );\n }\n }\n\n // Check if advanced schema constructs are valid (without recursion)\n const schemaArrays = ['allOf', 'anyOf', 'oneOf'];\n for (const arrayType of schemaArrays) {\n if (schema[arrayType] !== undefined) {\n if (!Array.isArray(schema[arrayType])) {\n return fail(\n `${arrayType} must be an array, got ${typeof schema[arrayType]}`\n );\n }\n\n // Just check that each item is an object (without recursion)\n for (let i = 0; i < schema[arrayType].length; i++) {\n const subSchema = schema[arrayType][i];\n if (typeof subSchema !== 'object' || subSchema === null) {\n return fail(\n `Item ${i} in ${arrayType} must be an object, got ${\n subSchema === null ? 'null' : typeof subSchema\n }`\n );\n }\n }\n }\n }\n\n // Check if 'not' is an object\n if (schema.not !== undefined) {\n if (typeof schema.not !== 'object' || schema.not === null) {\n return fail(\n `'not' must be an object, got ${\n schema.not === null ? 'null' : typeof schema.not\n }`\n );\n }\n }\n\n // If we have additionalProperties, make sure it's a boolean or an object\n if (schema.additionalProperties !== undefined) {\n if (\n typeof schema.additionalProperties !== 'boolean' &&\n (typeof schema.additionalProperties !== 'object' ||\n schema.additionalProperties === null)\n ) {\n return fail(\n `additionalProperties must be a boolean or an object, got ${\n schema.additionalProperties === null\n ? 'null'\n : typeof schema.additionalProperties\n }`\n );\n }\n }\n\n // Check basic format if present (for string type)\n if (schema.format !== undefined && typeof schema.format !== 'string') {\n return fail(`format must be a string, got ${typeof schema.format}`);\n }\n\n // Check number constraints\n const numberConstraints = [\n 'minimum',\n 'maximum',\n 'exclusiveMinimum',\n 'exclusiveMaximum',\n 'multipleOf'\n ];\n for (const constraint of numberConstraints) {\n if (\n schema[constraint] !== undefined &&\n typeof schema[constraint] !== 'number'\n ) {\n return fail(\n `${constraint} must be a number, got ${typeof schema[constraint]}`\n );\n }\n }\n\n // Check string constraints\n if (\n schema.minLength !== undefined &&\n (typeof schema.minLength !== 'number' || schema.minLength < 0)\n ) {\n return fail(\n `minLength must be a non-negative number, got ${\n typeof schema.minLength === 'number'\n ? schema.minLength\n : typeof schema.minLength\n }`\n );\n }\n if (\n schema.maxLength !== undefined &&\n (typeof schema.maxLength !== 'number' || schema.maxLength < 0)\n ) {\n return fail(\n `maxLength must be a non-negative number, got ${\n typeof schema.maxLength === 'number'\n ? schema.maxLength\n : typeof schema.maxLength\n }`\n );\n }\n if (schema.pattern !== undefined && typeof schema.pattern !== 'string') {\n return fail(`pattern must be a string, got ${typeof schema.pattern}`);\n }\n\n // Check array constraints\n if (\n schema.minItems !== undefined &&\n (typeof schema.minItems !== 'number' || schema.minItems < 0)\n ) {\n return fail(\n `minItems must be a non-negative number, got ${\n typeof schema.minItems === 'number'\n ? schema.minItems\n : typeof schema.minItems\n }`\n );\n }\n if (\n schema.maxItems !== undefined &&\n (typeof schema.maxItems !== 'number' || schema.maxItems < 0)\n ) {\n return fail(\n `maxItems must be a non-negative number, got ${\n typeof schema.maxItems === 'number'\n ? schema.maxItems\n : typeof schema.maxItems\n }`\n );\n }\n if (\n schema.uniqueItems !== undefined &&\n typeof schema.uniqueItems !== 'boolean'\n ) {\n return fail(\n `uniqueItems must be a boolean, got ${typeof schema.uniqueItems}`\n );\n }\n\n // Check object constraints\n if (\n schema.minProperties !== undefined &&\n (typeof schema.minProperties !== 'number' || schema.minProperties < 0)\n ) {\n return fail(\n `minProperties must be a non-negative number, got ${\n typeof schema.minProperties === 'number'\n ? schema.minProperties\n : typeof schema.minProperties\n }`\n );\n }\n if (\n schema.maxProperties !== undefined &&\n (typeof schema.maxProperties !== 'number' || schema.maxProperties < 0)\n ) {\n return fail(\n `maxProperties must be a non-negative number, got ${\n typeof schema.maxProperties === 'number'\n ? schema.maxProperties\n : typeof schema.maxProperties\n }`\n );\n }\n if (schema.required !== undefined) {\n if (!Array.isArray(schema.required)) {\n return fail(`required must be an array, got ${typeof schema.required}`);\n }\n for (let i = 0; i < schema.required.length; i++) {\n const prop = schema.required[i];\n if (typeof prop !== 'string') {\n return fail(\n `Item ${i} in required array must be a string, got ${typeof prop}`\n );\n }\n }\n }\n\n // It has passed all the first-level checks\n return true;\n}\n", "import { OpenAPIV3 } from 'openapi-types';\nimport { OutputKind, PanelInputSchema } from '../provider';\nimport { Property } from './types';\n\nfunction getProperties<K extends OutputKind, I>(\n inputSchema: OpenAPIV3.SchemaObject,\n panelInput: PanelInputSchema<K, I>\n): Property[] {\n if (inputSchema.properties == null) {\n throw new Error('Input schema must have properties');\n }\n\n const properties: Property[] = [];\n\n const orderedProperties = getOrderedProperties(inputSchema, panelInput);\n if (orderedProperties != null) {\n return orderedProperties;\n } else {\n Object.entries(inputSchema.properties).forEach((property) => {\n const id = property[0];\n const schema = property[1] as OpenAPIV3.SchemaObject;\n properties.push({ id, schema });\n });\n }\n\n return properties;\n}\n\nfunction getOrderedProperties<K extends OutputKind, I>(\n inputSchema: OpenAPIV3.SchemaObject,\n panelInput: PanelInputSchema<K, I>\n): Property[] | undefined {\n if (panelInput.orderExtensionKeyword == null) {\n return undefined;\n }\n const properties: Property[] = [];\n\n if (\n typeof panelInput.orderExtensionKeyword !== 'string' &&\n !Array.isArray(panelInput.orderExtensionKeyword)\n ) {\n throw new Error(\n 'orderExtensionKeyword must be a string or an array of strings'\n );\n }\n\n const orderExtensionKeywords =\n typeof panelInput.orderExtensionKeyword === 'string'\n ? [panelInput.orderExtensionKeyword]\n : panelInput.orderExtensionKeyword;\n\n const orderExtensionKeyword = orderExtensionKeywords.find(\n (extensionKeyword) => {\n return extensionKeyword in inputSchema;\n }\n );\n\n if (orderExtensionKeyword == null) {\n return undefined;\n }\n const order =\n // @ts-ignore\n inputSchema[orderExtensionKeyword] as string[];\n\n if (order == null || Array.isArray(order) === false) {\n throw new Error(\n `Extension keyword ${orderExtensionKeyword} must be an array of strings`\n );\n }\n\n [...new Set(order)].forEach((orderKey) => {\n const property = inputSchema.properties?.[orderKey];\n if (property != null) {\n properties.push({\n id: orderKey,\n schema: property as OpenAPIV3.SchemaObject\n });\n }\n });\n\n if (properties.length === 0) {\n throw new Error(\n `Could not find any properties with order extension keyword(s) ${orderExtensionKeywords.join(\n ', '\n )}`\n );\n }\n return properties;\n}\n\nexport default getProperties;\n", "import CreativeEditorSDK, { AssetResult } from '@cesdk/cesdk-js';\nimport { GenerationResult, Output } from './generation/provider';\n\nexport const AI_PANEL_ID_PREFIX = 'ly.img.ai';\n\nconst TEMP_ASSET_SOURCE_ID = 'ly.img.ai/temp';\n\n/**\n * Adding asset to the scene.\n *\n * NOTE: Will use a temporary asset source so that\n * our asset source middleware trigger. This is necessary since there is\n * a lot of extra logic in the video middlewares regarding trim, position etc.\n *\n * These will only trigger via an asset source, not by calling\n * `defaultApplyAsset` directly.\n */\nexport async function addAssetToScene(\n cesdk: CreativeEditorSDK,\n assetResult: AssetResult\n) {\n if (!cesdk.engine.asset.findAllSources().includes(TEMP_ASSET_SOURCE_ID)) {\n cesdk.engine.asset.addLocalSource(TEMP_ASSET_SOURCE_ID);\n }\n\n return cesdk.engine.asset.apply(TEMP_ASSET_SOURCE_ID, assetResult);\n}\n\n/**\n * Returns a consistent panel ID for a provider ID\n */\nexport function getPanelId(providerId: string): string {\n return `${AI_PANEL_ID_PREFIX}/${providerId}`;\n}\n\nexport default getPanelId;\n/**\n * Extracts a readable error message from an unknown error\n *\n * @param error The error caught in a try/catch block\n * @param fallbackMessage Optional fallback message if error is not an Error object\n * @returns A string representation of the error\n */\nexport function extractErrorMessage(\n error: unknown,\n fallbackMessage = 'We encountered an unknown error while generating the asset. Please try again.'\n): string {\n if (error === null) {\n return fallbackMessage;\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n if (typeof error === 'object') {\n // Try to get message property if it exists\n const errorObj = error as Record<string, unknown>;\n if ('message' in errorObj && typeof errorObj.message === 'string') {\n return errorObj.message;\n }\n if ('cause' in errorObj && typeof errorObj.cause === 'string') {\n return errorObj.cause;\n }\n\n /*\n * Elevenlabs for instance uses the following structure for errors:\n * {\n * \"detail\": {\n * \"status\": \"error_code\",\n * \"message\": \"Explanation of the rate limit issue.\"\n * }\n * }\n */\n if (\n 'detail' in errorObj &&\n typeof errorObj.detail === 'object' &&\n errorObj.detail !== null &&\n 'message' in errorObj.detail &&\n typeof errorObj.detail.message === 'string'\n ) {\n return errorObj.detail.message;\n }\n\n /*\n * Used by e.g. Anthropic\n */\n if (\n 'error' in errorObj &&\n typeof errorObj.error === 'object' &&\n errorObj.error !== null &&\n 'message' in errorObj.error &&\n typeof errorObj.error.message === 'string'\n ) {\n return errorObj.error.message;\n }\n\n return fallbackMessage;\n }\n\n if (typeof error === 'string') {\n return error;\n }\n\n // For any other type, convert to string\n return String(error) || fallbackMessage;\n}\n\n/**\n * Generates a random UUID v4\n */\nexport function uuid4() {\n /* eslint-disable no-bitwise */\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n /* eslint-enable no-bitwise */\n });\n}\n\n/**\n * Gets the duration of a video from a URL\n * @param url - The URL of the video\n * @returns A promise that resolves to the duration of the video in seconds\n */\nexport function getDurationForVideo(url: string): Promise<number> {\n return new Promise((resolve, reject) => {\n try {\n const video = document.createElement('video');\n video.style.display = 'none';\n\n // Set up event handlers\n video.addEventListener('loadedmetadata', () => {\n if (video.duration === Infinity) {\n // Some videos might initially report Infinity\n video.currentTime = 1e101;\n // Wait for currentTime to update\n setTimeout(() => {\n video.currentTime = 0;\n resolve(video.duration);\n document.body.removeChild(video);\n }, 50);\n } else {\n resolve(video.duration);\n document.body.removeChild(video);\n }\n });\n\n video.addEventListener('error', () => {\n document.body.removeChild(video);\n reject(new Error(`Failed to load video from ${url}`));\n });\n\n // Set source and begin loading\n video.src = url;\n document.body.appendChild(video);\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n * Gets a thumbnail image from a video URL\n * @param url - The URL of the video\n * @param seekTime - Time in seconds to capture the thumbnail (default: 0)\n * @param format - Image format for the thumbnail (default: 'image/jpeg')\n * @param quality - Image quality between 0 and 1 (default: 0.8)\n * @returns A promise that resolves to the thumbnail data URL\n */\nexport function getThumbnailForVideo(\n url: string,\n seekTime = 0,\n format = 'image/jpeg',\n quality = 0.8\n): Promise<string> {\n return new Promise((resolve, reject) => {\n try {\n const video = document.createElement('video');\n // Set crossOrigin to anonymous to prevent tainted canvas issues\n video.crossOrigin = 'anonymous';\n video.style.display = 'none';\n\n // Set up event handlers\n video.addEventListener('loadedmetadata', () => {\n // Seek to the specified time\n video.currentTime = Math.min(seekTime, video.duration);\n\n video.addEventListener(\n 'seeked',\n () => {\n // Create a canvas to draw the video frame\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n\n // Draw the video frame to the canvas\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n document.body.removeChild(video);\n reject(new Error('Failed to create canvas context'));\n return;\n }\n\n ctx.drawImage(video, 0, 0, canvas.width, canvas.height);\n\n try {\n // Convert canvas to data URL\n const dataURL = canvas.toDataURL(format, quality);\n // Clean up\n document.body.removeChild(video);\n resolve(dataURL);\n } catch (e) {\n document.body.removeChild(video);\n reject(\n new Error(\n `Failed to create thumbnail: ${\n e instanceof Error ? e.message : String(e)\n }`\n )\n );\n }\n },\n { once: true }\n );\n });\n\n video.addEventListener('error', () => {\n document.body.removeChild(video);\n reject(new Error(`Failed to load video from ${url}`));\n });\n\n // Set source and begin loading\n video.src = url;\n document.body.appendChild(video);\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n * Converts an ID string to a human-readable label\n * @param id - The ID string to convert\n * @returns A human-readable label derived from the ID\n *\n * Examples:\n * - snake_case_id \u2192 Snake Case Id\n * - kebab-case-id \u2192 Kebab Case Id\n * - camelCaseId \u2192 Camel Case Id\n * - PascalCaseId \u2192 Pascal Case Id\n */\nexport function getLabelFromId(id: string): string {\n if (!id) return '';\n\n // Handle snake_case, kebab-case, camelCase, and PascalCase\n return (\n id\n // Replace underscores and hyphens with spaces (for snake_case and kebab-case)\n .replace(/[_-]/g, ' ')\n // Add spaces before uppercase letters (for camelCase and PascalCase)\n .replace(/([A-Z])/g, ' $1')\n // Trim any extra spaces and ensure first letter is capitalized\n .trim()\n .split(' ')\n .filter((word) => word.length > 0) // Remove empty strings from multiple spaces\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n .join(' ')\n );\n}\n\n/**\n * Type guard to check if a value is an AsyncGenerator rather than a Promise\n *\n * @param value - Value of type Promise<O> | AsyncGenerator<O, C>\n * @returns Boolean indicating if the value is an AsyncGenerator\n */\nexport function isAsyncGenerator<O extends Output, C>(\n value: GenerationResult<O, C>\n): value is AsyncGenerator<O, C> {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'next' in value &&\n 'return' in value &&\n 'throw' in value &&\n typeof value.next === 'function' &&\n typeof value.return === 'function' &&\n typeof value.throw === 'function' &&\n Symbol.asyncIterator in value &&\n typeof value[Symbol.asyncIterator] === 'function'\n );\n}\n\nexport function isAbortError(error: unknown): error is Error {\n return error instanceof Error && error.name === 'AbortError';\n}\n", "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { BuilderRenderFunctionContext } from '@cesdk/cesdk-js';\nimport {\n EnumValue,\n ExtensionImglyBuilder,\n GetPropertyInput,\n Property,\n PropertyInput\n} from './types';\nimport Provider, { Output, OutputKind, PanelInputSchema } from '../provider';\nimport { InitProviderConfiguration, UIOptions } from '../types';\nimport { OpenAPIV3 } from 'openapi-types';\nimport getProperties from './getProperties';\nimport { getLabelFromId } from '../../utils';\n\nfunction renderProperty<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n property: Property,\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): GetPropertyInput | undefined {\n const type = property.schema.type;\n\n if (\n panelInput.renderCustomProperty != null &&\n panelInput.renderCustomProperty[property.id] != null\n ) {\n return panelInput.renderCustomProperty[property.id](context, property);\n }\n\n switch (type) {\n case 'string': {\n if (property.schema.enum != null) {\n return renderEnumProperty(\n context,\n property,\n provider,\n panelInput,\n options,\n config\n );\n } else {\n return renderStringProperty(\n context,\n property,\n provider,\n panelInput,\n options,\n config\n );\n }\n }\n\n case 'boolean': {\n return renderBooleanProperty(\n context,\n property,\n provider,\n panelInput,\n options,\n config\n );\n }\n\n case 'number':\n case 'integer': {\n return renderIntegerProperty(\n context,\n property,\n provider,\n panelInput,\n options,\n config\n );\n }\n\n case 'object': {\n return renderObjectProperty(\n context,\n property,\n provider,\n panelInput,\n options,\n config\n );\n }\n\n case 'array': {\n // not supported yet\n break;\n }\n\n case undefined: {\n if (\n property.schema.anyOf != null &&\n Array.isArray(property.schema.anyOf)\n ) {\n return renderAnyOfProperty(\n context,\n property,\n provider,\n panelInput,\n options,\n config\n );\n }\n break;\n }\n\n default: {\n // eslint-disable-next-line no-console\n console.error(`Unsupported property type: ${type}`);\n }\n }\n}\n\nfunction renderObjectProperty<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n property: Property,\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): GetPropertyInput {\n const properties = getProperties(property.schema ?? {}, panelInput);\n\n const childInputs = properties.reduce((acc, childProperty) => {\n const getInput = renderProperty(\n context,\n childProperty,\n provider,\n panelInput,\n options,\n config\n );\n if (getInput != null) {\n acc[childProperty.id] = getInput();\n }\n return acc;\n }, {} as Record<string, PropertyInput>);\n\n return () => ({\n id: property.id,\n type: 'object',\n value: childInputs\n });\n}\n\nfunction renderStringProperty<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n property: Property,\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): GetPropertyInput {\n const {\n builder,\n experimental: { global }\n } = context;\n const { id: propertyId } = property;\n\n const id = `${provider.id}.${propertyId}`;\n const inputLabel = property.schema.title ?? id;\n\n const propertyState = global(id, property.schema.default ?? '');\n\n const extension = getImglyExtensionBuilder(property.schema);\n const builderComponent =\n extension?.component != null && extension?.component === 'TextArea'\n ? 'TextArea'\n : 'TextInput';\n\n builder[builderComponent](id, {\n inputLabel,\n placeholder: options.i18n?.prompt,\n ...propertyState\n });\n\n return () => ({\n id: property.id,\n type: 'string',\n value: propertyState.value\n });\n}\n\nfunction renderEnumProperty<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n property: Property,\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): GetPropertyInput {\n const {\n builder,\n experimental: { global }\n } = context;\n const { id: propertyId } = property;\n\n const id = `${provider.id}.${propertyId}`;\n const inputLabel = property.schema.title ?? id;\n\n const labels: Record<string, string> =\n property.schema.enum != null &&\n 'x-imgly-enum-labels' in property.schema.enum &&\n typeof property.schema.enum['x-imgly-enum-labels'] === 'object'\n ? (property.schema.enum['x-imgly-enum-labels'] as Record<string, string>)\n : 'x-imgly-enum-labels' in property.schema &&\n typeof property.schema['x-imgly-enum-labels'] === 'object'\n ? (property.schema['x-imgly-enum-labels'] as Record<string, string>)\n : {};\n\n const icons: Record<string, string> =\n 'x-imgly-enum-icons' in property.schema &&\n typeof property.schema['x-imgly-enum-icons'] === 'object'\n ? (property.schema['x-imgly-enum-icons'] as Record<string, string>)\n : {};\n\n const values: EnumValue[] = (property.schema.enum ?? []).map((valueId) => ({\n id: valueId,\n label: labels[valueId] ?? getLabelFromId(valueId),\n icon: icons[valueId]\n }));\n const defaultValue =\n property.schema.default != null\n ? values.find((v) => v.id === property.schema.default) ?? values[0]\n : values[0];\n\n const propertyState = global<EnumValue>(id, defaultValue);\n\n builder.Select(id, {\n inputLabel,\n values,\n ...propertyState\n });\n\n return () => ({\n id: property.id,\n type: 'string',\n value: propertyState.value.id\n });\n}\n\nfunction renderBooleanProperty<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n property: Property,\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): GetPropertyInput {\n const {\n builder,\n experimental: { global }\n } = context;\n const { id: propertyId } = property;\n\n const id = `${provider.id}.${propertyId}`;\n const inputLabel = property.schema.title ?? id;\n\n const defaultValue = !!property.schema.default;\n const propertyState = global<boolean>(id, defaultValue);\n\n builder.Checkbox(id, {\n inputLabel,\n ...propertyState\n });\n\n return () => ({\n id: property.id,\n type: 'boolean',\n value: propertyState.value\n });\n}\n\nfunction renderIntegerProperty<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n property: Property,\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): GetPropertyInput {\n const {\n builder,\n experimental: { global }\n } = context;\n const { id: propertyId } = property;\n\n const id = `${provider.id}.${propertyId}`;\n const inputLabel = property.schema.title ?? id;\n\n const minValue = property.schema.minimum;\n const maxValue = property.schema.maximum;\n\n let defaultValue = property.schema.default;\n if (defaultValue == null) {\n if (minValue != null) {\n defaultValue = minValue;\n } else if (maxValue != null) {\n defaultValue = maxValue;\n } else {\n defaultValue = 0;\n }\n }\n\n const propertyState = global<number>(id, defaultValue);\n\n if (minValue != null && maxValue != null) {\n let step = property.schema.type === 'number' ? 0.1 : 1;\n if (\n 'x-imgly-step' in property.schema &&\n typeof property.schema['x-imgly-step'] === 'number'\n ) {\n step = property.schema['x-imgly-step'];\n }\n\n builder.Slider(id, {\n inputLabel,\n min: minValue,\n max: maxValue,\n step,\n ...propertyState\n });\n } else {\n builder.NumberInput(id, {\n inputLabel,\n min: minValue,\n max: maxValue,\n ...propertyState\n });\n }\n\n return () => ({\n id: property.id,\n type: 'integer',\n value: propertyState.value\n });\n}\n\nfunction renderAnyOfProperty<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n property: Property,\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): GetPropertyInput | undefined {\n const {\n builder,\n experimental: { global }\n } = context;\n const { id: propertyId } = property;\n\n const id = `${provider.id}.${propertyId}`;\n const inputLabel = property.schema.title ?? id;\n\n const anyOf = (property.schema.anyOf ?? []) as OpenAPIV3.SchemaObject[];\n\n const values: EnumValue[] = [];\n\n const conditionalRender: Record<string, () => GetPropertyInput> = {};\n const conditionalInputs: Record<string, () => PropertyInput> = {};\n\n anyOf.forEach((anySchema, index) => {\n const label = anySchema.title ?? 'common.custom';\n const schemaId = `${provider.id}.${propertyId}.anyOf[${index}]`;\n\n const labels: Record<string, string> =\n 'x-imgly-enum-labels' in property.schema &&\n typeof property.schema['x-imgly-enum-labels'] === 'object'\n ? (property.schema['x-imgly-enum-labels'] as Record<string, string>)\n : {};\n\n const icons: Record<string, string> =\n 'x-imgly-enum-icons' in property.schema &&\n typeof property.schema['x-imgly-enum-icons'] === 'object'\n ? (property.schema['x-imgly-enum-icons'] as Record<string, string>)\n : {};\n\n if (anySchema.type === 'string') {\n if (anySchema.enum != null) {\n anySchema.enum.forEach((valueId) => {\n values.push({\n id: valueId,\n label: labels[valueId] ?? getLabelFromId(valueId),\n icon: icons[valueId]\n });\n });\n } else {\n conditionalRender[schemaId] = () => {\n return renderStringProperty(\n context,\n { id: schemaId, schema: { ...anySchema, title: label } },\n provider,\n panelInput,\n options,\n config\n );\n };\n\n values.push({\n id: schemaId,\n label: labels[label] ?? label,\n icon: icons[label]\n });\n }\n } else if (anySchema.type === 'boolean') {\n conditionalRender[schemaId] = () => {\n return renderBooleanProperty(\n context,\n { id: schemaId, schema: { ...anySchema, title: label } },\n provider,\n panelInput,\n options,\n config\n );\n };\n\n values.push({\n id: schemaId,\n label: labels[label] ?? label,\n icon: icons[label]\n });\n } else if (anySchema.type === 'integer') {\n conditionalRender[schemaId] = () => {\n return renderIntegerProperty(\n context,\n { id: schemaId, schema: { ...anySchema, title: label } },\n provider,\n panelInput,\n options,\n config\n );\n };\n\n values.push({\n id: schemaId,\n label: labels[label] ?? label,\n icon: icons[label]\n });\n } else if (anySchema.type === 'array') {\n // not supported yet\n } else if (anySchema.type === 'object') {\n conditionalRender[schemaId] = () => {\n return renderObjectProperty(\n context,\n { id: schemaId, schema: { ...anySchema, title: label } },\n provider,\n panelInput,\n options,\n config\n );\n };\n\n values.push({\n id: schemaId,\n label: labels[label] ?? label,\n icon: icons[label]\n });\n }\n });\n\n const defaultValue =\n property.schema.default != null\n ? values.find((value) => value.id === property.schema.default) ??\n values[0]\n : values[0];\n\n const propertyState = global<EnumValue>(id, defaultValue);\n\n builder.Select(id, {\n inputLabel,\n values,\n ...propertyState\n });\n\n if (propertyState.value.id in conditionalRender) {\n const inputs = conditionalRender[propertyState.value.id]();\n conditionalInputs[propertyState.value.id] = inputs;\n }\n\n return () => {\n const conditionalInput = conditionalInputs[propertyState.value.id];\n\n if (conditionalInput != null) {\n return {\n ...conditionalInput(),\n id: property.id\n };\n }\n\n return {\n id: property.id,\n type: 'string',\n value: propertyState.value.id\n };\n };\n}\n\nfunction getImglyExtensionBuilder(\n schema: OpenAPIV3.SchemaObject\n): ExtensionImglyBuilder | undefined {\n if ('x-imgly-builder' in schema) {\n const extension = schema['x-imgly-builder'] as ExtensionImglyBuilder;\n return extension;\n }\n\n return undefined;\n}\n\nexport default renderProperty;\n", "const previewUri =\n 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4R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Q4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==';\n\nexport default previewUri;\n", "import { type AssetResult } from '@cesdk/cesdk-js';\nimport { type OutputKind, GetBlockInputResult, InputByKind } from './provider';\nimport previewUri from './previewUri';\n\nfunction getAssetResultForPlaceholder<K extends OutputKind>(\n id: string,\n kind: K,\n blockInput: GetBlockInputResult<K>\n): AssetResult {\n switch (kind) {\n case 'image': {\n return getImageAssetResultForPlaceholder(\n id,\n blockInput[kind] as InputByKind['image']\n );\n }\n case 'video': {\n return getVideoAssetResultForPlaceholder(\n id,\n blockInput[kind] as InputByKind['video']\n );\n }\n\n default: {\n throw new Error(\n `Unsupported output kind for creating placeholder block: ${kind}`\n );\n }\n }\n}\n\nfunction getImageAssetResultForPlaceholder(\n id: string,\n input: InputByKind['image']\n): AssetResult {\n const width = input.width;\n const height = input.height;\n return {\n id,\n meta: {\n previewUri,\n fillType: '//ly.img.ubq/fill/image',\n kind: 'image',\n\n width,\n height\n }\n };\n}\n\nfunction getVideoAssetResultForPlaceholder(\n id: string,\n input: InputByKind['video']\n): AssetResult {\n const width = input.width;\n const height = input.height;\n return {\n id,\n label: input.label,\n meta: {\n previewUri,\n mimeType: 'video/mp4',\n kind: 'video',\n fillType: '//ly.img.ubq/fill/video',\n\n duration: input.duration.toString(),\n\n width,\n height\n }\n };\n}\n\nexport default getAssetResultForPlaceholder;\n", "import { type AssetResult } from '@cesdk/cesdk-js';\nimport {\n type OutputKind,\n AudioOutput,\n GetBlockInputResult,\n ImageOutput,\n InputByKind,\n Output,\n VideoOutput\n} from './provider';\nimport { getThumbnailForVideo } from '../utils';\n\nasync function getAssetResultForGenerated<K extends OutputKind>(\n id: string,\n kind: K,\n blockInputs: GetBlockInputResult<K>,\n output: Output\n): Promise<AssetResult> {\n switch (kind) {\n case 'image': {\n if (output.kind !== 'image') {\n throw new Error(\n `Output kind does not match the expected type: ${output.kind} (expected: image)`\n );\n }\n\n return getImageAssetResultForGenerated(\n id,\n blockInputs[kind] as InputByKind['image'],\n output\n );\n }\n\n case 'video': {\n if (output.kind !== 'video') {\n throw new Error(\n `Output kind does not match the expected type: ${output.kind} (expected: video)`\n );\n }\n\n return getVideoAssetResultForGenerated(\n id,\n blockInputs[kind] as InputByKind['video'],\n output\n );\n }\n\n case 'audio': {\n if (output.kind !== 'audio') {\n throw new Error(\n `Output kind does not match the expected type: ${output.kind} (expected: audio)`\n );\n }\n\n return getAudioAssetResultForGenerated(\n id,\n blockInputs[kind] as InputByKind['audio'],\n output\n );\n }\n\n default: {\n throw new Error(\n `Unsupported output kind for creating placeholder block: ${kind}`\n );\n }\n }\n}\n\nfunction getImageAssetResultForGenerated(\n id: string,\n input: InputByKind['image'],\n output: ImageOutput\n): AssetResult {\n const width = input.width;\n const height = input.height;\n return {\n id,\n label: input.label,\n meta: {\n uri: output.url,\n thumbUri: output.url,\n fillType: '//ly.img.ubq/fill/image',\n kind: 'image',\n\n width,\n height\n },\n payload: {\n sourceSet: [\n {\n uri: output.url,\n width,\n height\n }\n ]\n }\n };\n}\n\nasync function getVideoAssetResultForGenerated(\n id: string,\n input: InputByKind['video'],\n output: VideoOutput\n): Promise<AssetResult> {\n const width = input.width;\n const height = input.height;\n\n const thumbUri = await getThumbnailForVideo(output.url, 0);\n\n return {\n id,\n label: input.label,\n meta: {\n uri: output.url,\n thumbUri,\n\n mimeType: 'video/mp4',\n kind: 'video',\n fillType: '//ly.img.ubq/fill/video',\n\n duration: input.duration.toString(),\n\n width,\n height\n }\n };\n}\n\nfunction getAudioAssetResultForGenerated(\n id: string,\n input: InputByKind['audio'],\n output: AudioOutput\n): AssetResult {\n return {\n id,\n label: input.label,\n meta: {\n uri: output.url,\n thumbUri: output.thumbnailUrl,\n blockType: '//ly.img.ubq/audio',\n mimeType: 'audio/x-m4a',\n duration: output.duration.toString()\n }\n };\n}\n\nexport default getAssetResultForGenerated;\n", "import { GenerationOptions, GenerationResult, Output } from '../provider';\n\n/**\n * Result of the generation with a dispose function to clean up\n */\nexport interface DisposableGenerationResult<O extends Output> {\n /**\n * The actual generation result\n */\n result: GenerationResult<O>;\n\n /**\n * Function to dispose/clean up resources created during generation\n * This should be called when the generation is cancelled or completely\n * finished including the confirmation of the generation if applicable.\n */\n dispose: () => Promise<void>;\n}\n\n/**\n * Define the type for middleware functions\n */\nexport type Middleware<I, O extends Output> = (\n input: I,\n options: GenerationOptions & {\n /**\n * The block ids the generation is applied on\n * If this value is undefined, the selected blocks will be used.\n * Setting this value to null will explicitly tell every\n * middleware that no block shall be used.\n */\n blockIds?: number[] | null;\n\n /**\n * Adds a disposer function to this genereation which is called\n * when the generation is cancelled or completely finished\n * including the confirmation of the generation if applicable.\n */\n addDisposer: (dispose: () => Promise<void>) => void;\n },\n next: (input: I, options: GenerationOptions) => Promise<GenerationResult<O>>\n) => Promise<GenerationResult<O>>;\n\nexport function composeMiddlewares<I, O extends Output>(\n middlewares: (Middleware<I, O> | false | undefined | null)[]\n) {\n // Filter out false, undefined, and null middlewares\n const validMiddlewares = middlewares.filter(\n (middleware): middleware is Middleware<I, O> => !!middleware\n );\n // Start with the base handler\n return (\n baseHandler: (\n input: I,\n options: GenerationOptions\n ) => Promise<GenerationResult<O>>\n ) => {\n // We need to build a chain where each step is a function with the signature:\n // (input, options) => Promise<Result>\n\n // The composed function that will be returned\n return async (\n input: I,\n options: GenerationOptions\n ): Promise<DisposableGenerationResult<O>> => {\n // Store disposer functions that will be called when dispose() is called\n const disposers: Array<() => Promise<void>> = [];\n\n // Function to add a disposer\n const addDisposer = (dispose: () => Promise<void>) => {\n disposers.push(dispose);\n };\n\n // Define a function to process each middleware in sequence\n const runMiddleware = async (\n index: number,\n currentInput: I,\n currentOptions: GenerationOptions\n ): Promise<GenerationResult<O>> => {\n // If we've processed all middlewares, call the base handler\n if (index >= validMiddlewares.length) {\n return baseHandler(currentInput, currentOptions);\n }\n\n // Get the current middleware\n const currentMiddleware = validMiddlewares[index];\n\n // Create a next function for this middleware that calls the next middleware in line\n const next = async (\n nextInput: I,\n nextOptions: GenerationOptions\n ): Promise<GenerationResult<O>> => {\n return runMiddleware(index + 1, nextInput, nextOptions);\n };\n\n // Enhanced options with addDisposer\n const enhancedOptions = {\n ...currentOptions,\n addDisposer\n };\n\n // Call the current middleware with the input, enhanced options, and next function\n return currentMiddleware(currentInput, enhancedOptions, next);\n };\n\n // Create enhanced options with addDisposer for base handler as well\n const enhancedOptions = {\n ...options,\n addDisposer\n };\n\n // Run the middleware chain\n const result = await runMiddleware(0, input, enhancedOptions);\n\n // Create the dispose function that will call all collected disposers in reverse order\n const dispose = async (): Promise<void> => {\n // Execute disposers in reverse order (last added, first disposed)\n /* eslint-disable no-await-in-loop */\n for (let i = disposers.length - 1; i >= 0; i--) {\n try {\n await disposers[i]();\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Error in disposer:', error);\n }\n }\n // Clear the disposers array after all are executed\n disposers.length = 0;\n };\n\n // Return both the result and the dispose function\n return {\n result,\n dispose\n };\n };\n };\n}\n", "/* eslint-disable no-console */\nimport { GenerationResult, Output } from '../provider';\nimport { Middleware } from './middleware';\n\nfunction loggingMiddleware<I, O extends Output>() {\n const middleware: Middleware<I, O> = async (input, options, next) => {\n console.group('[GENERATION]');\n console.log(`Generating with input:`, JSON.stringify(input, null, 2));\n let result: GenerationResult<O> | undefined;\n const start = Date.now();\n try {\n result = await next(input, options);\n return result;\n } finally {\n if (result != null) {\n console.log(`Generation took ${Date.now() - start}ms`);\n console.log(`Generation result:`, JSON.stringify(result, null, 2));\n }\n console.groupEnd();\n }\n };\n\n return middleware;\n}\n\nexport default loggingMiddleware;\n", "export default `\n<svg>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratioFree\"\n >\n <path d=\"M7 6C6.44772 6 6 6.44772 6 7V9.22222H4V7C4 5.34315 5.34315 4 7 4H9.22222V6H7Z\" fill=\"currentColor\"/>\n <path d=\"M17 6H14.7778V4H17C18.6569 4 20 5.34315 20 7V9.22222H18V7C18 6.44772 17.5523 6 17 6Z\" fill=\"currentColor\"/>\n <path d=\"M6 14.7778V17C6 17.5523 6.44772 18 7 18H9.22222V20H7C5.34315 20 4 18.6569 4 17V14.7778H6Z\" fill=\"currentColor\"/>\n <path d=\"M18 17V14.7778H20V17C20 18.6569 18.6569 20 17 20H14.7778V18H17C17.5523 18 18 17.5523 18 17Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio4by3\"\n >\n <path d=\"M6.5 13H8V15H10V16.5H6.5V13Z\" fill=\"currentColor\"/>\n <path d=\"M14 9V7.5H17.5V11H16V9H14Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M6 4C4.34315 4 3 5.34315 3 7V17C3 18.6569 4.34315 20 6 20H18C19.6569 20 21 18.6569 21 17V7C21 5.34315 19.6569 4 18 4H6ZM5 7C5 6.44772 5.44772 6 6 6H18C18.5523 6 19 6.44772 19 7V17C19 17.5523 18.5523 18 18 18H6C5.44772 18 5 17.5523 5 17V7Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio16by9\"\n >\n <path d=\"M4.5 13H6V15H8V16.5H4.5V13Z\" fill=\"currentColor\"/>\n <path d=\"M16 9V7.5H19.5V11H18V9H16Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M4 4C2.34315 4 1 5.34315 1 7V17C1 18.6569 2.34315 20 4 20H20C21.6569 20 23 18.6569 23 17V7C23 5.34315 21.6569 4 20 4H4ZM3 7C3 6.44772 3.44772 6 4 6H20C20.5523 6 21 6.44772 21 7V17C21 17.5523 20.5523 18 20 18H4C3.44772 18 3 17.5523 3 17V7Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio9by16\"\n >\n <path d=\"M7.5 16H9V18H11V19.5H7.5V16Z\" fill=\"currentColor\"/>\n <path d=\"M13 6V4.5H16.5V8H15V6H13Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M4 20C4 21.6569 5.34315 23 7 23H17C18.6569 23 20 21.6569 20 20V4C20 2.34315 18.6569 1 17 1H7C5.34315 1 4 2.34315 4 4V20ZM7 21C6.44772 21 6 20.5523 6 20V4C6 3.44772 6.44772 3 7 3H17C17.5523 3 18 3.44772 18 4V20C18 20.5523 17.5523 21 17 21H7Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio3by4\"\n >\n <path d=\"M11 17.5V16H9V14H7.5V17.5H11Z\" fill=\"currentColor\"/>\n <path d=\"M15 10H16.5V6.5H13V8H15V10Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M20 18C20 19.6569 18.6569 21 17 21H7C5.34315 21 4 19.6569 4 18V6C4 4.34315 5.34315 3 7 3H17C18.6569 3 20 4.34315 20 6V18ZM17 19C17.5523 19 18 18.5523 18 18V6C18 5.44772 17.5523 5 17 5H7C6.44771 5 6 5.44771 6 6V18C6 18.5523 6.44772 19 7 19H17Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/plugin/formats/ratio1by1\"\n >\n <path d=\"M17.4142 8.00009L16 6.58587L14.2929 8.29298L15.7071 9.70719L17.4142 8.00009Z\" fill=\"currentColor\"/>\n <path d=\"M13.0404 12.3739L15.0404 10.3739L13.6262 8.95965L11.6262 10.9596L13.0404 12.3739Z\" fill=\"currentColor\"/>\n <path d=\"M10.3737 15.0405L12.3737 13.0405L10.9595 11.6263L8.95953 13.6263L10.3737 15.0405Z\" fill=\"currentColor\"/>\n <path d=\"M9.70708 15.7072L8.29286 14.293L6.58576 16.0001L7.99997 17.4143L9.70708 15.7072Z\" fill=\"currentColor\"/>\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M7 4C5.34315 4 4 5.34315 4 7V17C4 18.6569 5.34315 20 7 20H17C18.6569 20 20 18.6569 20 17V7C20 5.34315 18.6569 4 17 4H7ZM6 7C6 6.44772 6.44772 6 7 6H17C17.5523 6 18 6.44772 18 7V17C18 17.5523 17.5523 18 17 18H7C6.44772 18 6 17.5523 6 17V7Z\" fill=\"currentColor\"/>\n </symbol>\n</svg>\n`;\n", "import type {\n AssetDefinition,\n AssetQueryData,\n AssetResult,\n AssetSource,\n AssetsQueryResult\n} from '@cesdk/engine';\n\n/**\n * Simplified value type for select inputs that can be converted to asset definitions\n */\nexport type SelectValue = {\n id: string;\n label: string;\n thumbUri?: string;\n};\n\n/**\n * A custom AssetSource implementation that manages assets from an array\n * and provides additional functionality like to mark assets as active or changing\n * labels.\n */\nexport class CustomAssetSource implements AssetSource {\n /** The unique id of the asset source */\n id: string;\n\n /** Array of assets to be served by this source */\n private assets: AssetDefinition[];\n\n /** Set of IDs for active assets */\n private activeAssetIds: Set<string>;\n\n /**\n * Creates a new instance of CustomAssetSource\n *\n * @param id - The unique identifier for this asset source\n * @param assets - Array of asset definitions or SelectValue objects to include in this source\n */\n constructor(id: string, assets: (AssetDefinition | SelectValue)[] = []) {\n this.id = id;\n this.assets = assets.map((asset) => {\n // Check if the asset is a SelectValue by looking for the label property as a string\n if (\n typeof (asset as SelectValue).label === 'string' &&\n !(\n (asset as AssetDefinition).label &&\n typeof (asset as AssetDefinition).label === 'object'\n )\n ) {\n const selectValue = asset as SelectValue;\n // Convert SelectValue to AssetDefinition\n return {\n id: selectValue.id,\n label: { en: selectValue.label },\n meta: selectValue.thumbUri\n ? { thumbUri: selectValue.thumbUri }\n : undefined\n } as AssetDefinition;\n }\n return asset as AssetDefinition;\n });\n this.activeAssetIds = new Set<string>();\n }\n\n /**\n * Find assets based on the provided query data\n * Supports pagination, searching, filtering, and active-first sorting\n *\n * @param queryData - Query parameters to filter and sort assets\n * @returns Promise with the query results\n */\n async findAssets(\n queryData: AssetQueryData\n ): Promise<AssetsQueryResult | undefined> {\n const {\n page,\n perPage,\n locale = 'en',\n sortActiveFirst,\n query,\n tags,\n groups,\n excludeGroups,\n sortingOrder,\n sortKey\n } = queryData;\n\n // Start with all assets\n let filteredAssets = [...this.assets];\n\n // Filter by groups if provided\n if (groups && groups.length > 0) {\n filteredAssets = filteredAssets.filter(\n (asset) =>\n asset.groups && groups.some((group) => asset.groups?.includes(group))\n );\n }\n\n // Filter out excluded groups if provided\n if (excludeGroups && excludeGroups.length > 0) {\n filteredAssets = filteredAssets.filter(\n (asset) =>\n !asset.groups ||\n !excludeGroups.some((group) => asset.groups?.includes(group))\n );\n }\n\n // Filter by query (search in label and tags)\n if (query) {\n const lowerQuery = query.toLowerCase();\n filteredAssets = filteredAssets.filter((asset) => {\n const label = asset.label?.[locale]?.toLowerCase();\n const assetTags = asset.tags?.[locale] || [];\n\n return (\n (label && label.includes(lowerQuery)) ||\n assetTags.some((tag) => tag.toLowerCase().includes(lowerQuery))\n );\n });\n }\n\n // Filter by exact tags if provided\n if (tags && tags.length > 0) {\n const tagArray = Array.isArray(tags) ? tags : [tags];\n filteredAssets = filteredAssets.filter((asset) => {\n const assetTags = asset.tags?.[locale] || [];\n return tagArray.some((tag) => assetTags.includes(tag));\n });\n }\n\n // Sort by active first if requested\n if (sortActiveFirst) {\n filteredAssets.sort((a, b) => {\n const aActive = this.activeAssetIds.has(a.id);\n const bActive = this.activeAssetIds.has(b.id);\n\n if (aActive && !bActive) return -1;\n if (!aActive && bActive) return 1;\n return 0;\n });\n }\n\n // Sort by sortKey if provided\n if (sortKey && sortKey !== 'id') {\n filteredAssets.sort((a, b) => {\n // Sort by metadata field\n const aValue = a.meta?.[sortKey];\n const bValue = b.meta?.[sortKey];\n\n if (aValue === undefined) return 1;\n if (bValue === undefined) return -1;\n\n if (typeof aValue === 'string' && typeof bValue === 'string') {\n return sortingOrder === 'Descending'\n ? bValue.localeCompare(aValue)\n : aValue.localeCompare(bValue);\n }\n\n if (typeof aValue === 'number' && typeof bValue === 'number') {\n return sortingOrder === 'Descending'\n ? bValue - aValue\n : aValue - bValue;\n }\n\n return 0;\n });\n } else if (sortKey === 'id') {\n // Sort by id\n filteredAssets.sort((a, b) => {\n return sortingOrder === 'Descending'\n ? b.id.localeCompare(a.id)\n : a.id.localeCompare(b.id);\n });\n }\n\n // Calculate pagination\n const total = filteredAssets.length;\n const startIndex = page * perPage;\n const endIndex = startIndex + perPage;\n const paginatedAssets = filteredAssets.slice(startIndex, endIndex);\n\n // Transform AssetDefinition objects to AssetResult objects\n const resultAssets: AssetResult[] = paginatedAssets.map((asset) => {\n return {\n id: asset.id,\n groups: asset.groups,\n meta: asset.meta,\n payload: asset.payload,\n locale,\n label: asset.label?.[locale],\n tags: asset.tags?.[locale],\n active: this.activeAssetIds.has(asset.id)\n };\n });\n\n // Calculate next page if there are more assets\n const nextPage = endIndex < total ? page + 1 : undefined;\n\n return {\n assets: resultAssets,\n currentPage: page,\n nextPage,\n total\n };\n }\n\n updateLabel(assetId: string, label: string, locale: string): void {\n this.assets.forEach((asset) => {\n if (asset.id === assetId) {\n asset.label = asset.label || {};\n asset.label[locale] = label;\n }\n });\n }\n\n /**\n * Get the asset select value by its ID\n *\n * @param assetId - The ID of the asset to retrieve\n * @returns The SelectValue object for the asset or undefined if not found\n */\n getAssetSelectValue(assetId: string): SelectValue | undefined {\n const asset = this.assets.find(({ id }) => id === assetId);\n if (asset) {\n return {\n id: asset.id,\n label: asset.label?.en || '',\n thumbUri: asset.meta?.thumbUri\n };\n }\n return undefined;\n }\n\n /**\n * Get an asset by its ID\n */\n getAsset(id: string): AssetDefinition | undefined {\n return this.assets.find((asset) => asset.id === id);\n }\n\n /**\n * Set an asset as active by its ID\n *\n * @param assetId - The ID of the asset to mark as active\n */\n setAssetActive(assetId: string): void {\n this.activeAssetIds.add(assetId);\n }\n\n /**\n * Get all active asset IDs\n *\n * @returns Array of active asset IDs\n */\n getActiveAssetIds(): string[] {\n return Array.from(this.activeAssetIds);\n }\n\n /**\n * Set multiple assets as active by their IDs\n *\n * @param assetIds - Array of asset IDs to mark as active\n */\n setAssetsActive(assetIds: string[]): void {\n assetIds.forEach((id) => this.activeAssetIds.add(id));\n }\n\n /**\n * Set an asset as inactive by its ID\n *\n * @param assetId - The ID of the asset to mark as inactive\n */\n setAssetInactive(assetId: string): void {\n this.activeAssetIds.delete(assetId);\n }\n\n /**\n * Clear all active assets\n */\n clearActiveAssets(): void {\n this.activeAssetIds.clear();\n }\n\n /**\n * Check if an asset is marked as active\n *\n * @param assetId - The ID of the asset to check\n * @returns True if the asset is active, false otherwise\n */\n isAssetActive(assetId: string): boolean {\n return this.activeAssetIds.has(assetId);\n }\n\n /**\n * Add an asset to this source\n *\n * @param asset - The asset definition to add\n */\n addAsset(asset: AssetDefinition): void {\n // Check if asset with this ID already exists\n const existingIndex = this.assets.findIndex((a) => a.id === asset.id);\n if (existingIndex >= 0) {\n // Replace existing asset\n this.assets[existingIndex] = asset;\n } else {\n // Add new asset\n this.assets.push(asset);\n }\n }\n\n /**\n * Remove an asset from this source\n *\n * @param assetId - The ID of the asset to remove\n */\n removeAsset(assetId: string): void {\n const index = this.assets.findIndex((asset) => asset.id === assetId);\n if (index !== -1) {\n this.assets.splice(index, 1);\n this.activeAssetIds.delete(assetId);\n }\n }\n\n /**\n * Get all available groups from the assets\n *\n * @returns Array of unique group names\n */\n async getGroups(): Promise<string[]> {\n const groups = new Set<string>();\n this.assets.forEach((asset) => {\n if (asset.groups) {\n asset.groups.forEach((group) => groups.add(group));\n }\n });\n return Array.from(groups);\n }\n\n /**\n * Returns the supported MIME types for this asset source\n *\n * @returns Array of supported MIME types\n */\n getSupportedMimeTypes(): string[] {\n return [\n 'image/jpeg',\n 'image/png',\n 'image/svg+xml',\n 'image/webp',\n 'video/mp4',\n 'audio/mpeg'\n ];\n }\n}\n\n/**\n * Helper function to create a CustomAssetSource instance\n *\n * @param id - The unique identifier for this asset source\n * @param assets - Array of asset definitions or SelectValue objects to include in this source\n * @returns A new CustomAssetSource instance\n */\nexport function createCustomAssetSource(\n id: string,\n assets: (AssetDefinition | SelectValue)[] = []\n): CustomAssetSource {\n return new CustomAssetSource(id, assets);\n}\n\nexport default CustomAssetSource;\n", "/* eslint-disable no-console */\nimport {\n CreativeEngine,\n type AssetDefinition,\n type AssetQueryData,\n type AssetResult,\n type AssetSource,\n type AssetsQueryResult\n} from '@cesdk/cesdk-js';\n\ntype BlobEntry = {\n id: string;\n blob: Blob;\n};\n\n// Asset definition with meta containing insertedAt timestamp\ntype AssetEntryWithMeta = AssetDefinition;\n\n/**\n * IndexedDBAssetSource implements the AssetSource interface using IndexedDB as the storage backend.\n */\nexport class IndexedDBAssetSource implements AssetSource {\n /** The unique id of the API */\n public readonly id: string;\n\n public readonly engine: CreativeEngine;\n\n private readonly dbName: string;\n\n private readonly dbVersion: number;\n\n private readonly assetStoreName: string = 'assets';\n\n private readonly blobStoreName: string = 'blobs';\n\n private db: IDBDatabase | null = null;\n\n /**\n * Creates a new IndexedDBAssetSource\n *\n * @param id - The unique identifier for this asset source\n * @param {Object} [options] - Optional configuration options.\n * @param {string} [options.dbName] - The name of the database.\n * @param {number} [options.dbVersion] - The version number of the database.\n */\n constructor(\n id: string,\n engine: CreativeEngine,\n options?: {\n dbName?: string;\n dbVersion?: number;\n }\n ) {\n this.id = id;\n this.engine = engine;\n this.dbName = options?.dbName ?? `ly.img.assetSource/${id}`;\n this.dbVersion = options?.dbVersion ?? 1;\n }\n\n /**\n * Initialize the database connection and create object stores if needed\n */\n public async initialize(): Promise<void> {\n if (this.db) {\n return;\n }\n\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(this.dbName, this.dbVersion);\n\n request.onerror = (event) => {\n reject(\n new Error(\n `Failed to open IndexedDB: ${(event.target as IDBRequest).error}`\n )\n );\n };\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n\n // Create asset store if it doesn't exist\n if (!db.objectStoreNames.contains(this.assetStoreName)) {\n db.createObjectStore(this.assetStoreName, {\n keyPath: 'id'\n });\n }\n // Create blob store if it doesn't exist\n if (!db.objectStoreNames.contains(this.blobStoreName)) {\n db.createObjectStore(this.blobStoreName, {\n keyPath: 'id'\n });\n }\n };\n\n request.onsuccess = (event) => {\n this.db = (event.target as IDBOpenDBRequest).result;\n resolve();\n };\n });\n }\n\n /**\n * Close the database connection\n */\n public close(): void {\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n }\n\n /**\n * Find all assets for the given type and the provided query data.\n *\n * @param queryData - The query parameters for filtering assets\n * @param insertionSortOrder - Optional parameter to sort by insertion time: 'asc' for oldest first, 'desc' for newest first (default)\n * @returns A promise that resolves to the query results or undefined if there was an error\n */\n public async findAssets(\n queryData: AssetQueryData\n ): Promise<AssetsQueryResult | undefined> {\n await this.initialize();\n\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n try {\n // Get all assets from the store with specified insertion order\n const assetDefinitions = await this.getAllAssets('asc');\n\n let assetResults = assetDefinitions.reduce((acc, assetDefinition) => {\n const locale = queryData.locale ?? 'en';\n let label = '';\n let tags: string[] = [];\n\n // Handle localized label if available\n if (\n assetDefinition.label != null &&\n typeof assetDefinition.label === 'object' &&\n assetDefinition.label[locale]\n ) {\n label = assetDefinition.label[locale];\n }\n\n // Handle localized tags if available\n if (\n assetDefinition.tags != null &&\n typeof assetDefinition.tags === 'object' &&\n assetDefinition.tags[locale]\n ) {\n tags = assetDefinition.tags[locale];\n }\n\n const result: AssetResult = {\n ...assetDefinition,\n label,\n tags\n };\n\n if (this.filterAsset(result, queryData)) {\n acc.push(result);\n }\n\n return acc;\n }, [] as AssetResult[]);\n\n assetResults = await this.restoreBlobUrls(assetResults);\n\n // Apply sorting\n assetResults = this.sortAssets(assetResults, queryData);\n\n // Apply pagination\n const { page, perPage } = queryData;\n const startIndex = page * perPage;\n const endIndex = startIndex + perPage;\n const paginatedAssets = assetResults.slice(startIndex, endIndex);\n\n // Determine if there's a next page\n const nextPage = endIndex < assetResults.length ? page + 1 : undefined;\n\n const result = {\n assets: paginatedAssets,\n currentPage: page,\n nextPage,\n total: assetResults.length\n };\n\n return result;\n } catch (error) {\n console.error('Error finding assets:', error);\n return undefined;\n }\n }\n\n public async getGroups(): Promise<string[]> {\n await this.initialize();\n\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.assetStoreName, 'readonly');\n const store = transaction.objectStore(this.assetStoreName);\n const request = store.getAll();\n\n request.onsuccess = () => {\n const allGroups = new Set<string>();\n\n // Extract all groups from all assets\n (request.result as AssetResult[]).forEach((asset) => {\n if (asset.groups && Array.isArray(asset.groups)) {\n asset.groups.forEach((group) => allGroups.add(group));\n }\n });\n\n const uniqueGroups = [...allGroups];\n resolve(uniqueGroups);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get groups: ${request.error}`));\n };\n });\n }\n\n /**\n * Adds the given asset to this source. Part of the AssetSource interface.\n *\n * @param asset - The asset definition to add\n */\n public addAsset(asset: AssetDefinition): void {\n this.initialize()\n .then(async () => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.assetStoreName,\n 'readwrite'\n );\n const assetStore = transaction.objectStore(this.assetStoreName);\n\n const blobsToStore = new Set<string>();\n processBlobUrls(asset, (value) => {\n blobsToStore.add(value);\n });\n\n setTimeout(() => {\n this.storeBlobUrls([...blobsToStore]);\n });\n\n // Ensure asset has meta object with insertedAt timestamp\n const assetWithMeta: AssetEntryWithMeta = {\n ...asset,\n meta: {\n ...asset.meta,\n insertedAt: asset.meta?.insertedAt || Date.now()\n }\n };\n\n // Store the asset in the database\n assetStore.put(assetWithMeta);\n\n transaction.onerror = () => {\n console.error(`Failed to add asset: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n /**\n * Removes the given asset from this source. Part of the AssetSource interface.\n *\n * @param assetId - The ID of the asset to remove\n */\n public async removeAsset(assetId: string): Promise<void> {\n const asset = await this.getAsset(assetId);\n\n return this.initialize()\n .then(() => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.assetStoreName,\n 'readwrite'\n );\n const store = transaction.objectStore(this.assetStoreName);\n store.delete(assetId);\n\n transaction.oncomplete = () => {\n processBlobUrls(asset, (value) => {\n this.removeBlob(value);\n });\n this.engine.asset.assetSourceContentsChanged(this.id);\n };\n\n transaction.onerror = () => {\n console.error(`Failed to remove asset: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n /**\n * Removes the given asset from this source. Part of the AssetSource interface.\n *\n * @param assetId - The ID of the asset to remove\n */\n public async removeBlob(blobId: string): Promise<void> {\n return this.initialize()\n .then(() => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.blobStoreName,\n 'readwrite'\n );\n const store = transaction.objectStore(this.blobStoreName);\n store.delete(blobId);\n\n transaction.onerror = () => {\n console.error(`Failed to remove blob: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n /**\n * Get all assets from the database sorted by insertion order (newest to oldest)\n *\n * @param sortOrder - Optional parameter to specify sort order: 'asc' for oldest first, 'desc' for newest first (default)\n * @returns A promise that resolves to an array of all assets\n */\n private async getAllAssets(\n sortOrder: 'asc' | 'desc' = 'desc'\n ): Promise<AssetDefinition[]> {\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.assetStoreName, 'readonly');\n const store = transaction.objectStore(this.assetStoreName);\n const request = store.getAll();\n\n request.onsuccess = () => {\n const assets = request.result as AssetEntryWithMeta[];\n\n // Sort by insertion timestamp\n assets.sort((a, b) => {\n // Default to current time if insertedAt is missing (for backward compatibility)\n // First check in meta.insertedAt, then fallback to legacy _insertedAt for backward compatibility\n const timeA =\n a.meta?.insertedAt || (a as any)._insertedAt || Date.now();\n const timeB =\n b.meta?.insertedAt || (b as any)._insertedAt || Date.now();\n\n // Sort based on requested order\n return sortOrder === 'asc'\n ? timeA - timeB // oldest first\n : timeB - timeA; // newest first (default)\n });\n\n resolve(assets);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get assets: ${request.error}`));\n };\n });\n }\n\n // Retrieve a blob by ID\n async getAsset(id: string): Promise<AssetResult | undefined> {\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.assetStoreName, 'readonly');\n const store = transaction.objectStore(this.assetStoreName);\n const request = store.get(id);\n\n request.onsuccess = () => {\n resolve(request.result as AssetResult);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get blob: ${request.error}`));\n };\n });\n }\n\n // Retrieve a blob by ID\n async getBlob(id: string): Promise<BlobEntry | undefined> {\n return new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.blobStoreName, 'readonly');\n const store = transaction.objectStore(this.blobStoreName);\n const request = store.get(id);\n\n request.onsuccess = () => {\n resolve(request.result as BlobEntry);\n };\n\n request.onerror = () => {\n reject(new Error(`Failed to get blob: ${request.error}`));\n };\n });\n }\n\n async createBlobUrlFromStore(blobUrl: string): Promise<string> {\n const blobEntry = await this.getBlob(blobUrl);\n if (blobEntry != null) {\n return URL.createObjectURL(blobEntry.blob);\n }\n return blobUrl;\n }\n\n async storeBlobUrls(urls: string[]): Promise<void> {\n const blobsToStore: { [key: string]: Blob } = {};\n await Promise.all(\n urls.map(async (blobUrl) => {\n const blobResponse = await fetch(blobUrl);\n const blob = await blobResponse.blob();\n blobsToStore[blobUrl] = blob;\n })\n );\n\n return this.initialize()\n .then(async () => {\n if (!this.db) {\n throw new Error('Database not initialized');\n }\n\n const transaction = this.db.transaction(\n this.blobStoreName,\n 'readwrite'\n );\n const blobStore = transaction.objectStore(this.blobStoreName);\n\n // Store the asset in the database\n Object.entries(blobsToStore).forEach(([key, blob]) => {\n const asset: BlobEntry = { id: key, blob };\n blobStore.put(asset);\n });\n\n transaction.onerror = () => {\n console.error(`Failed to add blobs: ${transaction.error}`);\n };\n })\n .catch((error) => {\n console.error('Error initializing database:', error);\n });\n }\n\n async restoreBlobUrls(assets: AssetResult[]): Promise<AssetResult[]> {\n const blobReplaced: { [key: string]: string } = {};\n const blobUrls: Set<string> = new Set();\n processBlobUrls(assets, (value) => {\n blobUrls.add(value);\n });\n\n await Promise.all(\n [...blobUrls].map(async (value) => {\n const newUrl = await this.createBlobUrlFromStore(value);\n blobReplaced[value] = newUrl;\n })\n );\n\n return processBlobUrls(assets, (value) => {\n return blobReplaced[value] ?? value;\n });\n }\n\n /**\n * Returns if the given asset should be filtered based on query data\n *\n * @param asset - The asset to filter\n * @param queryData - The query parameters to filter by\n * @returns true if the asset should be included, false otherwise\n */\n private filterAsset(asset: AssetResult, queryData: AssetQueryData): boolean {\n const { query, tags, groups, excludeGroups } = queryData;\n\n // Filter by query string (search on label and tags)\n if (query && query.trim() !== '') {\n const lowerQuery = query.trim().toLowerCase().split(' ');\n\n const lowerLabel = asset.label?.toLowerCase() ?? '';\n const lowerTags = asset.tags?.map((tag) => tag.toLowerCase()) ?? [];\n\n const matchLabelOrTag = lowerQuery.every((word) => {\n return (\n lowerLabel.includes(word) ||\n lowerTags.some((tag) => tag.includes(word))\n );\n });\n\n if (!matchLabelOrTag) {\n return false;\n }\n }\n\n // Filter by exact tags if provided by the query\n if (tags) {\n const tagList = Array.isArray(tags) ? tags : [tags];\n if (\n tagList.length > 0 &&\n (!asset.tags || !tagList.every((tag) => asset.tags?.includes(tag)))\n ) {\n return false;\n }\n }\n\n // Filter by groups\n if (groups && groups.length > 0) {\n if (\n !asset.groups ||\n !groups.some((group) => asset.groups?.includes(group))\n ) {\n return false;\n }\n }\n\n // Filter by excluded groups\n if (excludeGroups && excludeGroups.length > 0) {\n if (\n asset.groups &&\n asset.groups.some((group) => excludeGroups.includes(group))\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Sort assets based on query data\n *\n * @param assets - The assets to sort\n * @param queryData - The query parameters with sorting information\n * @returns The sorted assets\n */\n private sortAssets(\n assets: AssetResult[],\n queryData: AssetQueryData\n ): AssetResult[] {\n const { sortingOrder, sortKey, sortActiveFirst } = queryData;\n\n // Clone the array to avoid modifying the original\n const sortedAssets = [...assets];\n\n // If no sorting order specified or set to 'None', return the current order\n if (!sortingOrder || sortingOrder === 'None') {\n return sortedAssets;\n }\n\n // Sort by the specified key\n if (sortKey) {\n sortedAssets.sort((a, b) => {\n let valueA;\n let valueB;\n\n if (sortKey === 'id') {\n valueA = a.id;\n valueB = b.id;\n } else {\n // Handle metadata sorting (assuming metadata is stored in a 'metadata' field)\n valueA = a.meta?.[sortKey] ?? null;\n valueB = b.meta?.[sortKey] ?? null;\n }\n\n // Handle null/undefined values\n if (valueA === null || valueA === undefined)\n return sortingOrder === 'Ascending' ? -1 : 1;\n if (valueB === null || valueB === undefined)\n return sortingOrder === 'Ascending' ? 1 : -1;\n\n // Compare values based on sorting order\n if (typeof valueA === 'string' && typeof valueB === 'string') {\n return sortingOrder === 'Ascending'\n ? valueA.localeCompare(valueB)\n : valueB.localeCompare(valueA);\n } else {\n return sortingOrder === 'Ascending'\n ? valueA < valueB\n ? -1\n : valueA > valueB\n ? 1\n : 0\n : valueA > valueB\n ? -1\n : valueA < valueB\n ? 1\n : 0;\n }\n });\n } else if (sortingOrder === 'Descending') {\n // If no sort key is specified, and sorting order set\n // to Descending, just reverse original order\n sortedAssets.reverse();\n }\n\n // Sort by active first if requested\n if (sortActiveFirst) {\n sortedAssets.sort((a, b) => {\n if (a.active && !b.active) return -1;\n if (!a.active && b.active) return 1;\n return 0;\n });\n }\n\n return sortedAssets;\n }\n}\n\n/**\n * Goes through an object and calls a callback for every string value that starts with 'blob:'\n * The callback can return a string to replace the original value\n * @param obj The object to traverse\n * @param callback Function to call when a blob URL is found, can return a replacement value\n * @param path Current path in the object (used for recursion)\n * @returns The modified object (or the original if no replacements were made)\n */\nfunction processBlobUrls<T>(\n obj: T,\n callback: (value: string, path: string) => string | void,\n path: string = ''\n): T {\n // Return the object as is if it's null or not an object\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n for (let index = 0; index < obj.length; index++) {\n const currentPath = path ? `${path}[${index}]` : `[${index}]`;\n\n if (typeof obj[index] === 'string' && obj[index].startsWith('blob:')) {\n const replacement = callback(obj[index], currentPath);\n if (typeof replacement === 'string') {\n obj[index] = replacement;\n }\n } else {\n obj[index] = processBlobUrls(obj[index], callback, currentPath);\n }\n }\n return obj;\n }\n\n // Handle regular objects\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key];\n const currentPath = path ? `${path}.${key}` : key;\n\n if (typeof value === 'string' && value.startsWith('blob:')) {\n const replacement = callback(value, currentPath);\n if (typeof replacement === 'string') {\n // @ts-ignore\n obj[key] = replacement;\n }\n } else {\n obj[key] = processBlobUrls(value, callback, currentPath);\n }\n }\n }\n\n return obj;\n}\n\nexport default IndexedDBAssetSource;\n", "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport type {\n AssetDefinition,\n AssetQueryData,\n AssetResult,\n AssetSource,\n AssetsQueryResult\n} from '@cesdk/cesdk-js';\nimport CreativeEditorSDK from '@cesdk/cesdk-js';\n\n/**\n * AggregatedAssetSource implements the AssetSource interface by aggregating\n * multiple asset sources via the cesdk API and combining their results.\n *\n * This asset source is read-only - it does not support adding or removing assets.\n */\nexport class AggregatedAssetSource implements AssetSource {\n /** The unique id of the asset source */\n public readonly id: string;\n\n /** The Creative Editor SDK instance */\n private cesdk: CreativeEditorSDK;\n\n /** The IDs of asset sources to aggregate */\n private assetSourceIds: string[];\n\n /**\n * Creates a new AggregatedAssetSource\n *\n * @param id - The unique identifier for this asset source\n * @param cesdk - The Creative Editor SDK instance\n * @param assetSourceIds - The IDs of asset sources to aggregate\n */\n constructor(id: string, cesdk: CreativeEditorSDK, assetSourceIds: string[]) {\n this.id = id;\n this.cesdk = cesdk;\n this.assetSourceIds = assetSourceIds;\n }\n\n /**\n * Find assets across all aggregated sources based on the provided query data\n * Results are sorted by the insertedAt timestamp in meta field\n *\n * @param queryData - Query parameters to filter and sort assets\n * @returns Promise with the query results\n */\n async findAssets(\n queryData: AssetQueryData\n ): Promise<AssetsQueryResult | undefined> {\n try {\n // Query all asset sources via cesdk\n const queryPromises = this.assetSourceIds.map((sourceId) =>\n this.cesdk.engine.asset.findAssets(sourceId, {\n ...queryData,\n // Increase page size to get all assets from each source\n // We'll handle pagination after merging\n perPage: 9999,\n page: 0\n })\n );\n\n // Wait for all queries to complete\n const results = await Promise.all(queryPromises);\n\n // Combine all assets from all sources\n let allAssets: AssetResult[] = [];\n results.forEach((result) => {\n if (result?.assets) {\n allAssets = allAssets.concat(result.assets);\n }\n });\n\n // Sort by insertedAt timestamp\n allAssets.sort((a, b) => {\n const timeA = (a.meta?.insertedAt as number) || 0;\n const timeB = (b.meta?.insertedAt as number) || 0;\n\n // Sort newest first (descending)\n return timeB - timeA;\n });\n\n // Apply pagination after merging\n const { page, perPage } = queryData;\n const startIndex = page * perPage;\n const endIndex = startIndex + perPage;\n const paginatedAssets = allAssets.slice(startIndex, endIndex);\n\n // Calculate if there is a next page\n const nextPage = endIndex < allAssets.length ? page + 1 : undefined;\n\n return {\n assets: paginatedAssets,\n currentPage: page,\n nextPage,\n total: allAssets.length\n };\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Error finding assets:', error);\n return undefined;\n }\n }\n\n /**\n * Retrieves all groups from all aggregated asset sources using cesdk\n * @returns Promise with an array of unique group names\n */\n async getGroups(): Promise<string[]> {\n const groupPromises = this.assetSourceIds.map((sourceId) =>\n this.cesdk.engine.asset.getGroups(sourceId)\n );\n\n const groupArrays = await Promise.all(groupPromises);\n\n // Combine and deduplicate groups\n const uniqueGroups = new Set<string>();\n groupArrays.forEach((groups) => {\n groups.forEach((group) => uniqueGroups.add(group));\n });\n\n return Array.from(uniqueGroups);\n }\n\n /**\n * This operation is not supported in AggregatedAssetSource\n * @throws Error - This method is not supported\n */\n addAsset(_asset: AssetDefinition): void {\n throw new Error('AggregatedAssetSource does not support adding assets');\n }\n\n /**\n * This operation is not supported in AggregatedAssetSource\n * @throws Error - This method is not supported\n */\n removeAsset(_assetId: string): void {\n throw new Error('AggregatedAssetSource does not support removing assets');\n }\n}\n\n/**\n * Helper function to create an AggregatedAssetSource instance\n *\n * @param id - The unique identifier for this asset source\n * @param cesdk - The Creative Editor SDK instance\n * @param assetSourceIds - The IDs of asset sources to aggregate\n * @returns A new AggregatedAssetSource instance\n */\nexport function createAggregatedAssetSource(\n id: string,\n cesdk: CreativeEditorSDK,\n assetSourceIds: string[]\n): AggregatedAssetSource {\n return new AggregatedAssetSource(id, cesdk, assetSourceIds);\n}\n\nexport default AggregatedAssetSource;\n", "import { type CreativeEngine } from '@cesdk/cesdk-js';\n\nclass Metadata<V> {\n engine: CreativeEngine;\n\n key: string;\n\n constructor(engine: CreativeEngine, key: string) {\n this.engine = engine;\n this.key = key;\n }\n\n hasData(blockId: number): boolean {\n return (\n this.engine.block.isValid(blockId) &&\n this.engine.block.hasMetadata(blockId, this.key)\n );\n }\n\n get(blockId: number): V | undefined {\n if (this.hasData(blockId)) {\n return JSON.parse(this.engine.block.getMetadata(blockId, this.key));\n }\n return undefined;\n }\n\n set(blockId: number, value: V) {\n this.engine.block.setMetadata(blockId, this.key, JSON.stringify(value));\n }\n\n clear(blockId: number) {\n if (this.engine.block.hasMetadata(blockId, this.key)) {\n this.engine.block.removeMetadata(blockId, this.key);\n }\n }\n}\n\nexport default Metadata;\n", "/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nexport default root;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n", "import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n", "import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\n", "/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n", "/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n", "/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nexport default isFunction;\n", "import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n", "import coreJsData from './_coreJsData.js';\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nexport default isMasked;\n", "/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n", "import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nexport default baseIsNative;\n", "/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n", "import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nexport default getNative;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n", "/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n", "import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nexport default isArrayLike;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n", "/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nexport default baseIsArguments;\n", "import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nexport default isArguments;\n", "/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n", "import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n", "import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nexport default baseIsTypedArray;\n", "/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nexport default nodeUtil;\n", "import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nexport default isTypedArray;\n", "import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default arrayLikeKeys;\n", "/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n", "import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n", "import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeys;\n", "import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nexport default keys;\n", "import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n", "import nativeCreate from './_nativeCreate.js';\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nexport default hashClear;\n", "/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nexport default hashGet;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nexport default hashHas;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nexport default hashSet;\n", "import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nexport default Hash;\n", "/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n", "import eq from './eq.js';\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nexport default assocIndexOf;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nexport default listCacheDelete;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nexport default listCacheGet;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nexport default listCacheHas;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nexport default listCacheSet;\n", "import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nexport default ListCache;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n", "import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nexport default mapCacheClear;\n", "/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n", "import isKeyable from './_isKeyable.js';\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nexport default getMapData;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default mapCacheDelete;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nexport default mapCacheGet;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nexport default mapCacheHas;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nexport default mapCacheSet;\n", "import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nexport default MapCache;\n", "/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n", "import ListCache from './_ListCache.js';\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nexport default stackClear;\n", "/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n", "/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n", "/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n", "import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nexport default stackSet;\n", "import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nexport default Stack;\n", "/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n", "/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n", "import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nexport default getSymbols;\n", "import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nexport default baseGetAllKeys;\n", "import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nexport default getAllKeys;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n", "import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nexport default getTag;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\n", "/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n", "/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n", "import MapCache from './_MapCache.js';\nimport setCacheAdd from './_setCacheAdd.js';\nimport setCacheHas from './_setCacheHas.js';\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nexport default SetCache;\n", "/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n", "/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n", "import SetCache from './_SetCache.js';\nimport arraySome from './_arraySome.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nexport default equalArrays;\n", "/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n", "/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n", "import Symbol from './_Symbol.js';\nimport Uint8Array from './_Uint8Array.js';\nimport eq from './eq.js';\nimport equalArrays from './_equalArrays.js';\nimport mapToArray from './_mapToArray.js';\nimport setToArray from './_setToArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nexport default equalByTag;\n", "import getAllKeys from './_getAllKeys.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nexport default equalObjects;\n", "import Stack from './_Stack.js';\nimport equalArrays from './_equalArrays.js';\nimport equalByTag from './_equalByTag.js';\nimport equalObjects from './_equalObjects.js';\nimport getTag from './_getTag.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nexport default baseIsEqualDeep;\n", "import baseIsEqualDeep from './_baseIsEqualDeep.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nexport default baseIsEqual;\n", "import baseIsEqual from './_baseIsEqual.js';\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\nexport default isEqual;\n", "import { isEqual } from 'lodash-es';\n\nimport Metadata from './Metadata';\nimport {\n PluginStatusError,\n PluginStatusMetadata,\n PluginStatusProcessed,\n PluginStatusProcessing\n} from './types';\n\nclass ImageProcessingMetadata extends Metadata<PluginStatusMetadata> {\n get(blockId: number): PluginStatusMetadata {\n return super.get(blockId) ?? { status: 'IDLE' };\n }\n\n /**\n * Detect if the block has been duplicated with processed or processing\n * fill processing. In that case the processing state is still\n * valid, but blockId and fillId have changed.\n */\n isDuplicate(blockId: number): boolean {\n if (!this.engine.block.isValid(blockId)) return false;\n\n const metadata = this.get(blockId);\n\n if (\n metadata.status === 'IDLE' ||\n metadata.status === 'PENDING' ||\n metadata.status === 'ERROR'\n )\n return false;\n\n if (!this.engine.block.hasFill(blockId)) return false;\n const fillId = this.engine.block.getFill(blockId);\n\n // It cannot be a duplicate if the blockId or fillId are the same\n if (metadata.blockId === blockId || metadata.fillId === fillId)\n return false;\n\n return true;\n }\n\n /**\n * Fixes the metadata if the block has been duplicated, i.e. the blockId and\n * fillId will be updated to the current block/fill.\n *\n * Please note: Call this method only on duplicates (see isDuplicate).\n */\n fixDuplicate(blockId: number) {\n const fillId = this.engine.block.getFill(blockId);\n const metadata = this.get(blockId);\n if (\n metadata.status === 'IDLE' ||\n metadata.status === 'PENDING' ||\n metadata.status === 'ERROR'\n )\n return;\n this.set(blockId, {\n ...metadata,\n blockId,\n fillId\n });\n\n // If it is currently processing the best we can do is to just recover\n // the initial image data, since no processing will update this block and\n // it will be stuck in the processing state.\n if (metadata.status === 'PROCESSING') {\n this.recoverInitialImageData(blockId);\n this.clear(blockId);\n }\n }\n\n /**\n * Check if the image has a consisten metadata state. A inconsistent state is\n * caused by outside changes of the fill data.\n *\n * @returns true if the metadata is consistent, false otherwise\n */\n isConsistent(blockId: number): boolean {\n // In case the block was removed, we just abort and mark it\n // as reset by returning true\n if (!this.engine.block.isValid(blockId)) return false;\n const metadata = this.get(blockId);\n if (metadata.status === 'IDLE' || metadata.status === 'PENDING')\n return true;\n\n if (!this.engine.block.hasFill(blockId)) return false;\n const fillId = this.engine.block.getFill(blockId);\n if (fillId == null) return false;\n\n if (blockId !== metadata.blockId || fillId !== metadata.fillId)\n return false;\n\n const sourceSet = this.engine.block.getSourceSet(\n fillId,\n 'fill/image/sourceSet'\n );\n const imageFileURI = this.engine.block.getString(\n fillId,\n 'fill/image/imageFileURI'\n );\n\n if (\n sourceSet.length === 0 &&\n !imageFileURI &&\n metadata.status === 'PROCESSING'\n ) {\n // While we process it is OK to have no image file URI and no source set\n // (which we cleared to show the spinning loader)\n return true;\n }\n\n // Source sets have precedence over imageFileURI so if we have a source set,\n // we only need to check if it has changed to something else.\n if (sourceSet?.length > 0) {\n const initialSourceSet = metadata.initialSourceSet;\n // If we have already processed the image, we need to check if the source set\n // we need to check against both source sets, the removed and the initial\n if (metadata.status !== 'PROCESSED') {\n if (!isEqual(sourceSet, initialSourceSet)) {\n return false;\n }\n }\n } else {\n if (metadata.status !== 'PROCESSED') {\n if (imageFileURI !== metadata.initialImageFileURI) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Recover the initial values to avoid the loading spinner and have the same\n * state as before the fill processing was started.\n */\n recoverInitialImageData(blockId: number) {\n const blockApi = this.engine.block;\n if (!blockApi.hasFill(blockId)) return; // Nothing to recover (no fill anymore)\n\n const metadata = this.get(blockId);\n\n if (metadata.status === 'PENDING' || metadata.status === 'IDLE') {\n return;\n }\n\n const initialSourceSet = metadata.initialSourceSet;\n const initialImageFileURI = metadata.initialImageFileURI;\n const initialPreviewFileURI = metadata.initialPreviewFileURI;\n\n const fillId = this.getValidFill(blockId, metadata);\n if (fillId == null) return;\n\n if (initialImageFileURI) {\n this.engine.block.setString(\n fillId,\n 'fill/image/imageFileURI',\n initialImageFileURI\n );\n }\n if (initialPreviewFileURI) {\n this.engine.block.setString(\n fillId,\n 'fill/image/previewFileURI',\n initialPreviewFileURI\n );\n }\n if (initialSourceSet.length > 0) {\n this.engine.block.setSourceSet(\n fillId,\n 'fill/image/sourceSet',\n initialSourceSet\n );\n }\n }\n\n /**\n * Returns the fill id of the block if it has a valid fill that was used for\n * fill processing. Returns undefined otherwise.\n */\n private getValidFill(\n blockId: number,\n metadata: PluginStatusProcessing | PluginStatusError | PluginStatusProcessed\n ): number | undefined {\n if (\n !this.engine.block.isValid(blockId) ||\n !this.engine.block.hasFill(blockId) ||\n blockId !== metadata.blockId\n ) {\n return undefined;\n }\n const fillId = this.engine.block.getFill(blockId);\n if (fillId !== metadata.fillId) {\n return undefined;\n }\n\n return fillId;\n }\n}\n\nexport default ImageProcessingMetadata;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { FillProcessingMetadata } from '..';\nimport {\n PluginStatusProcessed,\n PluginStatusProcessing\n} from '../metadata/types';\n\ninterface FillProcessor<T> {\n processFill(metadataState: PluginStatusProcessing): Promise<T>;\n\n commitProcessing(\n data: T,\n metadataState: PluginStatusProcessed\n ): number | void;\n}\n\nasync function fillProcessing<T>(\n blockId: number,\n cesdk: CreativeEditorSDK,\n metadata: FillProcessingMetadata,\n processor: FillProcessor<T>\n) {\n const blockApi = cesdk.engine.block;\n if (!blockApi.hasFill(blockId))\n throw new Error('Block does not support fill');\n\n const fillId = blockApi.getFill(blockId);\n\n // Get the current image URI and source set as initial values.\n const initialSourceSet = blockApi.getSourceSet(\n fillId,\n 'fill/image/sourceSet'\n );\n const initialImageFileURI = blockApi.getString(\n fillId,\n 'fill/image/imageFileURI'\n );\n const initialPreviewFileURI = blockApi.getString(\n fillId,\n 'fill/image/previewFileURI'\n );\n try {\n cesdk.engine.block.setState(fillId, {\n type: 'Pending',\n progress: 0\n });\n\n const status: PluginStatusProcessing = {\n ...metadata.get(blockId),\n version: PLUGIN_VERSION,\n initialSourceSet,\n initialImageFileURI,\n initialPreviewFileURI,\n blockId,\n fillId,\n status: 'PROCESSING'\n };\n\n metadata.set(blockId, status);\n\n const processedData = await processor.processFill(status);\n // Check for externally changed state while we were applying the mask and\n // do not proceed if the state was reset.\n if (\n metadata.get(blockId).status !== 'PROCESSING' ||\n !metadata.isConsistent(blockId)\n )\n return;\n\n // Check for externally changed state while we were uploading and\n // do not proceed if the state was reset.\n if (\n metadata.get(blockId).status !== 'PROCESSING' ||\n !metadata.isConsistent(blockId)\n )\n return;\n\n if (processedData == null) return;\n\n const metadataStateProcessed: PluginStatusProcessed = {\n version: PLUGIN_VERSION,\n initialSourceSet,\n initialImageFileURI,\n initialPreviewFileURI,\n blockId,\n fillId,\n status: 'PROCESSED'\n };\n\n const blockIdOrVoid = processor.commitProcessing(\n processedData,\n metadataStateProcessed\n );\n\n // If a new block was created, we do not update the metadata.\n if (blockIdOrVoid == null || blockIdOrVoid === blockId) {\n metadata.set(blockId, metadataStateProcessed);\n }\n\n // Finally, create an undo step\n cesdk.engine.editor.addUndoStep();\n } catch (error) {\n if (cesdk.engine.block.isValid(blockId)) {\n metadata.set(blockId, {\n version: PLUGIN_VERSION,\n initialSourceSet,\n initialImageFileURI,\n initialPreviewFileURI,\n blockId,\n fillId,\n status: 'ERROR'\n });\n\n metadata.recoverInitialImageData(blockId);\n }\n\n if (\n error != null &&\n typeof error === 'object' &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n const message =\n error.message === 'signal timed out'\n ? 'Processing canceled due to timeout'\n : error.message;\n cesdk.ui.showNotification({\n type: 'error',\n message\n });\n }\n\n // eslint-disable-next-line no-console\n console.log(error);\n } finally {\n if (cesdk.engine.block.isValid(fillId)) {\n cesdk.engine.block.setState(fillId, { type: 'Ready' });\n }\n }\n}\n\nexport default fillProcessing;\n", "export function getFeatureId(pluginId: string): string {\n return `${pluginId}.fillProcessing.feature`;\n}\n\nexport function getCanvasMenuComponentIds(pluginId: string): string[] {\n return [`${pluginId}.canvasMenu`, `${pluginId}.fillProcessing.canvasMenu`];\n}\n\nexport function getDockComponentIds(pluginId: string): string[] {\n return [`${pluginId}.dock`, `${pluginId}.fillProcessing.dock`];\n}\n\nexport function getInspectorBarComponentIds(pluginId: string): string[] {\n return [\n `${pluginId}.inspectorBar`,\n `${pluginId}.fillProcessing.inspectorBar`\n ];\n}\n\nexport function getNavigationBarComponentIds(pluginId: string): string[] {\n return [\n `${pluginId}.navigationBar`,\n `${pluginId}.fillProcessing.navigationBar`\n ];\n}\n\nexport function getCanvasBarComponentIds(pluginId: string): string[] {\n return [`${pluginId}.canvasBar`, `${pluginId}.fillProcessing.canvasBar`];\n}\n\nexport function getI18nCanvasMenuLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.canvasMenu.button.label`;\n}\n\nexport function getI18nDockLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.dock.button.label`;\n}\n\nexport function getI18nInspectorBarLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.inspectorBar.button.label`;\n}\n\nexport function getI18nNavigationBarLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.navigationBar.button.label`;\n}\n\nexport function getI18nCanvasBarLabel(pluginId: string): string {\n return `plugin.${pluginId}.fillProcessing.canvasBar.button.label`;\n}\n", "import type CreativeEditorSDK from '@cesdk/cesdk-js';\n\nimport { FillProcessingMetadata } from '..';\nimport { getFeatureId } from './constants';\n\nexport default function handleFillProcessing(\n cesdk: CreativeEditorSDK,\n {\n pluginId,\n process\n }: {\n pluginId: string;\n icon?: string;\n process: (blockId: number, metadata: FillProcessingMetadata) => void;\n }\n): {\n featureId: string;\n} {\n const featureId = getFeatureId(pluginId);\n\n const metadata = new FillProcessingMetadata(cesdk.engine, pluginId);\n\n enableFeatures(cesdk, metadata, featureId);\n\n cesdk.engine.event.subscribe([], async (events) => {\n events.forEach((e) => {\n const id = e.block;\n if (!cesdk.engine.block.isValid(id) || !metadata.hasData(id)) {\n return;\n }\n\n if (e.type === 'Created') {\n if (metadata.isDuplicate(id)) {\n metadata.fixDuplicate(id);\n }\n } else if (e.type === 'Updated') {\n switch (metadata.get(id).status) {\n case 'PENDING': {\n if (\n cesdk.feature.isEnabled(featureId, {\n engine: cesdk.engine\n }) &&\n cesdk.engine.block.isAllowedByScope(id, 'fill/change') &&\n cesdk.engine.block.getState(id).type !== 'Pending'\n ) {\n process(id, metadata);\n }\n break;\n }\n\n case 'PROCESSING':\n case 'PROCESSED': {\n if (!metadata.isConsistent(id)) {\n metadata.clear(id);\n }\n break;\n }\n\n default: {\n // We do not care about other states\n }\n }\n }\n });\n });\n\n return { featureId };\n}\n\n/**\n * Defines the feature that determines in which context (on which block)\n * fill processing is allowed/enabled.\n */\nfunction enableFeatures(\n cesdk: CreativeEditorSDK,\n metadata: FillProcessingMetadata,\n featureId: string\n) {\n cesdk.feature.enable(featureId, ({ engine }) => {\n const selectedIds = engine.block.findAllSelected();\n if (selectedIds.length !== 1) {\n return false;\n }\n const [selectedId] = selectedIds;\n\n if (!cesdk.engine.block.isVisible(selectedId)) return false;\n\n if (cesdk.engine.block.hasFill(selectedId)) {\n const kind = cesdk.engine.block.getKind(selectedId);\n if (kind === 'sticker') return false;\n\n const fillId = cesdk.engine.block.getFill(selectedId);\n const fillType = cesdk.engine.block.getType(fillId);\n\n if (fillType !== '//ly.img.ubq/fill/image') {\n return false;\n }\n\n const fileUri = engine.block.getString(fillId, 'fill/image/imageFileURI');\n const sourceSet = engine.block.getSourceSet(\n fillId,\n 'fill/image/sourceSet'\n );\n\n if (sourceSet.length > 0 || fileUri !== '') return true;\n\n // If we are in a processing state we do not have a imageFileURI or\n // source set set (to show the loading spinner), but the feature is still\n // enabled.\n return metadata.get(selectedId).status === 'PROCESSING';\n }\n\n return false;\n });\n}\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { FillProcessingMetadata } from '..';\nimport {\n getCanvasBarComponentIds,\n getCanvasMenuComponentIds,\n getDockComponentIds,\n getFeatureId,\n getI18nCanvasBarLabel,\n getI18nCanvasMenuLabel,\n getI18nDockLabel,\n getI18nInspectorBarLabel,\n getI18nNavigationBarLabel,\n getInspectorBarComponentIds,\n getNavigationBarComponentIds\n} from './constants';\n\nexport type Location =\n | 'inspectorBar'\n | 'navigationBar'\n | 'canvasBarTop'\n | 'canvasBarBottom'\n | 'canvasMenu'\n | 'dock';\n\n/**\n * Registers the components that can be used to process the fill of\n * a block.\n */\nexport default function registerFillProcessingComponents(\n cesdk: CreativeEditorSDK,\n options: {\n pluginId: string;\n icon?: string;\n locations?: Location | Location[];\n }\n): {\n canvasMenuComponentId: string;\n dockComponentId: string;\n\n translationsKeys: {\n inspectorBarLabel: string;\n navigationBarLabel: string;\n canvasBarLabel: string;\n canvasMenuLabel: string;\n dockLabel: string;\n };\n} {\n const { pluginId, locations } = options;\n const metadata = new FillProcessingMetadata(cesdk.engine, pluginId);\n\n const canvasMenuLabel = getI18nCanvasMenuLabel(pluginId);\n const canvasMenuComponentIds = getCanvasMenuComponentIds(pluginId);\n const canvasMenuComponentId = canvasMenuComponentIds[0];\n\n const dockLabel = getI18nDockLabel(pluginId);\n const dockComponentIds = getDockComponentIds(pluginId);\n const dockComponentId = dockComponentIds[0];\n\n const inspectorBarLabel = getI18nInspectorBarLabel(pluginId);\n const inspectorBarComponentIds = getInspectorBarComponentIds(pluginId);\n const inspectorBarComponentId = inspectorBarComponentIds[0];\n\n const navigationBarLabel = getI18nNavigationBarLabel(pluginId);\n const navigationBarComponentIds = getNavigationBarComponentIds(pluginId);\n const navigationBarComponentId = navigationBarComponentIds[0];\n\n const canvasBarLabel = getI18nCanvasBarLabel(pluginId);\n const canvasBarComponentIds = getCanvasBarComponentIds(pluginId);\n const canvasBarComponentId = canvasBarComponentIds[0];\n\n const featureId = getFeatureId(pluginId);\n\n if (locations?.includes('inspectorBar')) {\n cesdk.ui.setInspectorBarOrder([\n inspectorBarComponentId,\n ...cesdk.ui.getInspectorBarOrder()\n ]);\n }\n\n if (locations?.includes('navigationBar')) {\n cesdk.ui.setNavigationBarOrder([\n navigationBarComponentId,\n ...cesdk.ui.getNavigationBarOrder()\n ]);\n }\n\n if (locations?.includes('canvasBarTop')) {\n cesdk.ui.setCanvasBarOrder(\n [canvasBarComponentId, ...cesdk.ui.getCanvasBarOrder('top')],\n 'top'\n );\n }\n\n if (locations?.includes('canvasBarBottom')) {\n cesdk.ui.setCanvasBarOrder(\n [canvasBarComponentId, ...cesdk.ui.getCanvasBarOrder('bottom')],\n 'bottom'\n );\n }\n\n if (locations?.includes('canvasMenu')) {\n cesdk.ui.setCanvasMenuOrder([\n canvasMenuComponentId,\n ...cesdk.ui.getCanvasMenuOrder()\n ]);\n }\n\n if (locations?.includes('dock')) {\n cesdk.ui.setDockOrder([...cesdk.ui.getDockOrder(), dockComponentId]);\n }\n\n cesdk.ui.registerComponent(\n dockComponentIds,\n ({ builder: { Button }, engine }) => {\n const [id] = engine.block.findAllSelected();\n\n let isDisabled = false;\n let isLoading = false;\n let loadingProgress: number | undefined;\n\n if (id == null) {\n isDisabled = true;\n }\n\n if (\n !isDisabled &&\n !cesdk.feature.isEnabled(featureId, {\n engine\n })\n ) {\n isDisabled = true;\n }\n\n if (\n !isDisabled &&\n !cesdk.engine.block.isAllowedByScope(id, 'fill/change')\n ) {\n isDisabled = true;\n }\n\n if (!isDisabled && engine.block.getState(id)?.type === 'Pending') {\n isDisabled = true;\n }\n\n if (!isDisabled) {\n const currentMetadata = metadata.get(id);\n\n isLoading = currentMetadata.status === 'PROCESSING';\n isDisabled =\n currentMetadata.status === 'PENDING' ||\n currentMetadata.status === 'PROCESSING';\n\n if (\n currentMetadata.status === 'PROCESSING' &&\n currentMetadata.progress\n ) {\n const { current, total } = currentMetadata.progress;\n loadingProgress = (current / total) * 100;\n }\n }\n\n const buttonId = `${dockComponentId}.button`;\n Button(buttonId, {\n label: dockLabel,\n icon: options.icon,\n isLoading,\n isDisabled,\n loadingProgress,\n onClick: () => {\n const currentMetadata = metadata.get(id);\n\n if (\n currentMetadata.status === 'IDLE' ||\n currentMetadata.status === 'ERROR' ||\n currentMetadata.status === 'PROCESSED'\n ) {\n metadata.set(id, {\n status: 'PENDING'\n });\n }\n }\n });\n }\n );\n\n const buttonComponents: {\n componentIds: string[];\n label: string;\n variant: 'plain' | 'regular';\n }[] = [\n {\n componentIds: inspectorBarComponentIds,\n variant: 'plain',\n label: inspectorBarLabel\n },\n {\n componentIds: navigationBarComponentIds,\n variant: 'regular',\n label: navigationBarLabel\n },\n {\n componentIds: canvasBarComponentIds,\n variant: 'regular',\n label: canvasBarLabel\n },\n {\n componentIds: canvasMenuComponentIds,\n variant: 'plain',\n label: canvasMenuLabel\n }\n ];\n\n buttonComponents.forEach(({ componentIds, label, variant }) => {\n const componentId = componentIds[0];\n cesdk.ui.registerComponent(\n componentIds,\n ({ builder: { Button }, engine }) => {\n if (\n !cesdk.feature.isEnabled(featureId, {\n engine\n })\n ) {\n return;\n }\n\n const [id] = engine.block.findAllSelected();\n\n if (!cesdk.engine.block.isAllowedByScope(id, 'fill/change')) return;\n\n const currentMetadata = metadata.get(id);\n\n const isLoading = currentMetadata.status === 'PROCESSING';\n const isDisabled =\n currentMetadata.status === 'PENDING' ||\n currentMetadata.status === 'PROCESSING' ||\n engine.block.getState(id)?.type === 'Pending';\n\n let loadingProgress: number | undefined;\n if (isLoading && currentMetadata.progress) {\n const { current, total } = currentMetadata.progress;\n loadingProgress = (current / total) * 100;\n }\n\n const buttonId = `${componentId}.button`;\n Button(buttonId, {\n icon: options.icon,\n label,\n variant,\n isLoading,\n isDisabled,\n loadingProgress,\n onClick: () => {\n if (\n currentMetadata.status === 'IDLE' ||\n currentMetadata.status === 'ERROR' ||\n currentMetadata.status === 'PROCESSED'\n ) {\n metadata.set(id, {\n status: 'PENDING'\n });\n }\n }\n });\n }\n );\n });\n\n return {\n canvasMenuComponentId,\n dockComponentId,\n translationsKeys: {\n inspectorBarLabel,\n navigationBarLabel,\n canvasBarLabel,\n canvasMenuLabel,\n dockLabel\n }\n };\n}\n", "import { type RGBAColor } from '@cesdk/cesdk-js';\n\nconst HEX_COLOR_PATTERN = new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/, 'i');\nconst HEX_SINGLE_CHAR_COMPONENTS_PATTERN = new RegExp(/[A-Fa-f0-9]{1}/, 'g');\nconst HEX_DOUBLE_CHAR_COMPONENTS_PATTERN = new RegExp(/[A-Fa-f0-9]{2}/, 'g');\n\n/** @public */\nexport const rgbaToHex = (rgba: RGBAColor, includeAlpha = false): string => {\n const { r, g, b, a } = rgba;\n const rByte = Math.round(255 * r);\n const gByte = Math.round(255 * g);\n const bByte = Math.round(255 * b);\n const aByte = Math.round(255 * a);\n const byteToHex = (byte: number) => {\n return byte.toString(16).padStart(2, '0');\n };\n return `#${byteToHex(rByte)}${byteToHex(gByte)}${byteToHex(bByte)}${\n includeAlpha ? byteToHex(aByte) : ''\n }`;\n};\n\n/** @public */\nexport const hexToRgba = (hexString: string): RGBAColor => {\n const rgbaHexToColor = (\n r: string,\n g: string,\n b: string,\n a: string | undefined,\n max: number\n ) => {\n return {\n r: parseInt(r, 16) / max,\n g: parseInt(g, 16) / max,\n b: parseInt(b, 16) / max,\n a: a === undefined ? 1 : parseInt(a, 16) / max\n };\n };\n\n if (hexString.startsWith('#')) {\n if (hexString.length === 4 || hexString.length === 5) {\n const hexMatch = hexString.match(HEX_SINGLE_CHAR_COMPONENTS_PATTERN);\n if (hexMatch) {\n const [r, g, b, a] = hexMatch;\n return rgbaHexToColor(r, g, b, a, 15);\n }\n }\n if (hexString.length === 7 || hexString.length === 8) {\n const hexMatch = hexString.match(HEX_DOUBLE_CHAR_COMPONENTS_PATTERN);\n if (hexMatch) {\n const [r, g, b, a] = hexMatch;\n return rgbaHexToColor(r, g, b, a, 255);\n }\n }\n }\n\n throw new Error(\n 'Invalid hex string! Allowed RGB formats are \"#FFF\" and \"#FFFFFF\". Allowed RGBA formats are \"#FFFF\" and \"#FFFFFFFF'\n );\n};\n\n/** @public */\nexport const isValidHexColor = (hexString: string): boolean => {\n return HEX_COLOR_PATTERN.test(hexString);\n};\n", "import type CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { CreativeEngine } from '@cesdk/cesdk-js';\n\n/**\n * Uploads a blob with the help of CE.SDK\n */\nexport async function uploadBlob(\n blob: Blob,\n initialUri: string,\n cesdk: CreativeEditorSDK\n) {\n const pathname = new URL(initialUri).pathname;\n const parts = pathname.split('/');\n const extension = mimeTypeToExtension(blob.type);\n const filename = parts[parts.length - 1]?.split('.')?.[0] ?? 'asset';\n const filenameWithExtension = `${filename}.${extension}`;\n\n const uploadedAssets = await cesdk.unstable_upload(\n new File([blob], filenameWithExtension, { type: blob.type }),\n () => {\n // TODO Delegate process to UI component\n }\n );\n\n const url = uploadedAssets.meta?.uri;\n if (url == null) {\n throw new Error('Could not upload processed fill');\n }\n return url;\n}\n\n/**\n * Returns the file extension for a given mime type.\n */\nexport function mimeTypeToExtension(mimeType: string): string {\n const extensions: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'image/svg+xml': 'svg'\n };\n return extensions[mimeType] ?? 'png';\n}\n\nexport async function fetchImageBlob(uri: string): Promise<Blob> {\n return fetch(uri).then((response) => response.blob());\n}\n\n/**\n * Converts a buffer URI to a object url.\n */\nexport async function bufferURIToObjectURL(\n uri: string,\n engine: CreativeEngine\n): Promise<string> {\n if (uri.startsWith('buffer:')) {\n const mimeType = await engine.editor.getMimeType(uri);\n const length = engine.editor.getBufferLength(uri);\n const data = engine.editor.getBufferData(uri, 0, length);\n const blob = new Blob([data], { type: mimeType });\n return URL.createObjectURL(blob);\n } else {\n return uri;\n }\n}\n", "function uuid4() {\n /* eslint-disable no-bitwise */\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n /* eslint-enable no-bitwise */\n });\n}\n\nexport default uuid4;\n", "import { bufferURIToObjectURL } from './upload';\nimport { type CreativeEngine } from '@cesdk/cesdk-js';\n\n/**\n * Get the dimensions of an image from its URL\n *\n * @param url - The URL of the image\n * @returns A promise that resolves to an object containing the width and height of the image\n */\nexport async function getImageDimensionsFromURL(\n url: string,\n engine: CreativeEngine\n): Promise<{ width: number; height: number }> {\n const resolvedUrl = await bufferURIToObjectURL(url, engine);\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => {\n resolve({ width: img.width, height: img.height });\n };\n img.onerror = reject;\n img.src = resolvedUrl;\n });\n}\n\n/**\n * Get the URI of an image from a block ID, either the first source of a source set or\n * the image file URI. Will handle buffer URIs and convert them to object URLs.\n */\nexport async function getImageUri(\n blockId: number,\n engine: CreativeEngine,\n options?: { throwErrorIfSvg?: boolean }\n): Promise<string> {\n let uri;\n const fillBlock = engine.block.getFill(blockId);\n const sourceSet = engine.block.getSourceSet(\n fillBlock,\n 'fill/image/sourceSet'\n );\n const [source] = sourceSet;\n if (source == null) {\n uri = engine.block.getString(fillBlock, 'fill/image/imageFileURI');\n if (uri == null) throw new Error('No image source/uri found');\n } else {\n uri = source.uri;\n }\n\n // Check if the image is SVG (not supported)\n if (options?.throwErrorIfSvg) {\n const mimeType = await engine.editor.getMimeType(uri);\n if (mimeType === 'image/svg+xml') {\n throw new Error('SVG images are not supported');\n }\n }\n\n return bufferURIToObjectURL(uri, engine);\n}\n", "/**\n * Checks if a value is defined (not undefined).\n *\n * Helpful to filter out undefined values from an array or collection\n * while keeping the type information intact.\n *\n * ```\n * array.filter(isDefined)\n * ```\n */\nfunction isDefined<T>(value: T | undefined): value is T {\n return value !== undefined;\n}\n\nexport default isDefined;\n", "import formatsIconSprite from './icons/formats';\n\nconst Icons = {\n Formats: formatsIconSprite\n};\n\nexport { Icons };\n\nexport { CustomAssetSource } from './assetSources/CustomAssetSource';\n\nexport { IndexedDBAssetSource } from './assetSources/IndexedDBAssetSource';\n\nexport { AggregatedAssetSource } from './assetSources/AggregatedAssetSource';\n\nexport { default as Metadata } from './metadata/Metadata';\n\nexport { default as FillProcessingMetadata } from './metadata/FillProcessingMetadata';\n\nexport { default as fillProcessing } from './processing/fillProcessing';\n\nexport { default as initializeFillProcessing } from './processing/initializeFillProcessing';\n\nexport { default as registerFillProcessingComponents } from './processing/registerFillProcessingComponents';\n\nexport { type Optional } from './types/Optional';\n\nexport {\n type Location,\n type UserInterfaceConfiguration\n} from './types/UserInterfaceConfiguration';\n\nexport { hexToRgba, isValidHexColor, rgbaToHex } from './utils/colors';\n\nexport {\n uploadBlob,\n fetchImageBlob,\n bufferURIToObjectURL,\n mimeTypeToExtension\n} from './utils/upload';\n\nexport { default as uuid } from './utils/uuid';\n\nexport { getImageDimensionsFromURL, getImageUri } from './utils/images';\n\nexport { default as isDefined } from './utils/isDefined';\n", "/* eslint-disable no-console */\nimport { getImageDimensionsFromURL, getImageUri } from '@imgly/plugin-utils';\nimport {\n type Output,\n type OutputKind,\n type GetBlockInputResult,\n VideoOutput,\n ImageOutput,\n GenerationOptions\n} from '../provider';\nimport { Middleware } from './middleware';\n\ninterface DryRunOptions<K extends OutputKind> {\n kind: K;\n\n // Is only defined with generation from a panel where we create a complete new block\n blockInputs?: GetBlockInputResult<K>;\n\n // Is only defined with quick action generation on a given block(s).\n blockIds?: number[];\n}\n\nfunction dryRunMiddleware<I, K extends OutputKind, O extends Output>(\n options: DryRunOptions<K>\n) {\n const middleware: Middleware<I, O> = async (\n generationInput,\n generationOptions\n ) => {\n console.log(\n `[DRY RUN]: Requesting dummy AI generation for kind '${options.kind}' with inputs: `,\n JSON.stringify(generationInput, undefined, 2)\n );\n await wait(2000);\n const output = await getDryRunOutput(\n generationInput,\n options,\n generationOptions\n );\n return output as O;\n };\n\n return middleware;\n}\n\nasync function getDryRunOutput<K extends OutputKind, I>(\n generationInput: I,\n options: DryRunOptions<K>,\n generationOptions: GenerationOptions\n): Promise<Output> {\n switch (options.kind) {\n case 'image': {\n return getImageDryRunOutput(\n generationInput,\n options as DryRunOptions<'image'>,\n generationOptions\n );\n }\n case 'video': {\n return getVideoDryRunOutput(\n generationInput,\n options as DryRunOptions<'video'>,\n generationOptions\n );\n }\n\n default: {\n throw new Error(\n `Unsupported output kind for creating dry run output: ${options.kind}`\n );\n }\n }\n}\n\nasync function getImageDryRunOutput<I>(\n generationInput: I,\n options: DryRunOptions<'image'>,\n { engine }: GenerationOptions\n): Promise<ImageOutput> {\n let width;\n let height;\n\n const prompt: string =\n generationInput != null &&\n typeof generationInput === 'object' &&\n 'prompt' in generationInput &&\n typeof generationInput.prompt === 'string'\n ? generationInput.prompt\n : 'AI Generated Image';\n\n // If prompt includes something that looks like a dimension\n // e.g. 512x512, 1024x768, etc. than we will use this as the\n // output image size for testing purposes.\n const promptDimension = prompt.match(/(\\d+)x(\\d+)/);\n if (promptDimension != null) {\n width = parseInt(promptDimension[1], 10);\n height = parseInt(promptDimension[2], 10);\n } else {\n if (options.blockInputs != null) {\n width = options.blockInputs.image.width;\n height = options.blockInputs.image.height;\n }\n if (\n options.blockIds != null &&\n Array.isArray(options.blockIds) &&\n options.blockIds.length > 0\n ) {\n const [blockId] = options.blockIds;\n const url = await getImageUri(blockId, engine);\n const dimension = await getImageDimensionsFromURL(url, engine);\n width = dimension.width;\n height = dimension.height;\n } else {\n width = 512;\n height = 512;\n }\n }\n\n const url = `https://placehold.co/${width}x${height}/000000/FFF?text=${prompt\n .replace(' ', '+')\n .replace('\\n', '+')}`;\n\n return {\n kind: 'image',\n url\n };\n}\n\nasync function getVideoDryRunOutput<I>(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _generationInput: I,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _options: DryRunOptions<'video'>,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _generationOptions: GenerationOptions\n): Promise<VideoOutput> {\n return Promise.resolve({\n kind: 'video',\n url: 'https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4'\n });\n}\n\nasync function wait(ms: number) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nexport default dryRunMiddleware;\n", "/* eslint-disable no-console */\nimport type { AssetDefinition, AssetResult } from '@cesdk/cesdk-js';\nimport {\n addAssetToScene,\n isAbortError,\n isAsyncGenerator,\n uuid4\n} from '../utils';\nimport type Provider from './provider';\nimport {\n type GetInput,\n type GetBlockInput,\n OutputKind,\n type Output\n} from './provider';\nimport { InitProviderConfiguration, UIOptions } from './types';\nimport CreativeEditorSDK from '@cesdk/cesdk-js';\nimport getAssetResultForPlaceholder from './getAssetResultForPlaceholder';\nimport getAssetResultForGenerated from './getAssetResultForGenerated';\nimport { composeMiddlewares } from './middleware/middleware';\nimport loggingMiddleware from './middleware/loggingMiddleware';\nimport dryRunMiddleware from './middleware/dryRunMiddleware';\n\ntype Result<O> = { status: 'success'; output: O } | { status: 'aborted' };\n\n/**\n * Generate content using the provider with the given input\n */\nasync function generate<K extends OutputKind, I, O extends Output>(\n kind: K,\n getInput: GetInput<I>,\n getBlockInput: GetBlockInput<K, I>,\n provider: Provider<K, I, O>,\n options: UIOptions & {\n createPlaceholderBlock?: boolean;\n },\n config: InitProviderConfiguration,\n abortSignal: AbortSignal\n): Promise<Result<O>> {\n const { cesdk, createPlaceholderBlock, historyAssetSourceId } = options;\n\n let placeholderBlock: number | undefined;\n\n try {\n if (config.debug) console.group(`Starting Generation for '${kind}'`);\n\n const inputs = getInput();\n const blockInputs = await getBlockInput(inputs.input);\n const assetId = uuid4();\n let assetResult: AssetResult;\n\n // Create a placeholder block\n if (createPlaceholderBlock) {\n assetResult = getAssetResultForPlaceholder(assetId, kind, blockInputs);\n\n if (config.debug)\n console.log(\n 'Adding as asset to scene:',\n JSON.stringify(assetResult, undefined, 2)\n );\n\n placeholderBlock = await addAssetToScene(cesdk, assetResult);\n // This is a workaround. The middleware in the video timeline\n // is calling APIs that will render the block in an error\n // state if it does not have an URI set. It's difficult to\n // recover from that. A bug report has been created for this.\n // As a workaround: Duplicating the block will remove the error state\n // but you will still see an error in the web console.\n // TODO: Remove this workaround when the bug is fixed.\n if (placeholderBlock != null && provider.kind === 'video') {\n const positionX = cesdk.engine.block.getPositionX(placeholderBlock);\n const positionY = cesdk.engine.block.getPositionY(placeholderBlock);\n const duplicated = cesdk.engine.block.duplicate(placeholderBlock);\n cesdk.engine.block.setPositionX(duplicated, positionX);\n cesdk.engine.block.setPositionY(duplicated, positionY);\n cesdk.engine.block.destroy(placeholderBlock);\n placeholderBlock = duplicated;\n }\n // placeholderBlock = await options.engine.asset.defaultApplyAsset(\n // assetResult\n // );\n\n if (checkAbortSignal(cesdk, abortSignal, placeholderBlock))\n return { status: 'aborted' };\n\n if (placeholderBlock == null)\n throw new Error('Could not create placeholder block');\n\n cesdk.engine.block.setState(placeholderBlock, {\n type: 'Pending',\n progress: 0\n });\n }\n\n // Trigger the generation\n const composedMiddlewares = composeMiddlewares<I, O>([\n ...(provider.output.middleware ?? []),\n config.debug ? loggingMiddleware() : undefined,\n config.dryRun\n ? dryRunMiddleware({ kind: provider.kind, blockInputs })\n : undefined\n ]);\n\n const { result: output } = await composedMiddlewares(\n provider.output.generate\n )(inputs.input, {\n abortSignal,\n engine: options.engine,\n cesdk\n });\n\n if (isAsyncGenerator(output)) {\n throw new Error('Streaming generation is not supported yet from a panel');\n }\n\n if (checkAbortSignal(cesdk, abortSignal, placeholderBlock))\n return { status: 'aborted' };\n\n if (output == null) throw new Error('Generation failed');\n\n if (config.debug)\n console.log('Generated output:', JSON.stringify(output, undefined, 2));\n\n let generatedAssetResult: AssetResult | undefined;\n if (\n placeholderBlock != null &&\n cesdk.engine.block.isValid(placeholderBlock)\n ) {\n generatedAssetResult = await getAssetResultForGenerated(\n assetId,\n kind,\n blockInputs,\n output\n );\n if (config.debug)\n console.log(\n 'Updating asset in scene:',\n JSON.stringify(generatedAssetResult, undefined, 2)\n );\n\n await cesdk.engine.asset.defaultApplyAssetToBlock(\n generatedAssetResult,\n placeholderBlock\n );\n }\n\n if (checkAbortSignal(cesdk, abortSignal, placeholderBlock))\n return { status: 'aborted' };\n\n if (historyAssetSourceId != null) {\n if (generatedAssetResult == null) {\n generatedAssetResult = await getAssetResultForGenerated(\n assetId,\n kind,\n blockInputs,\n output\n );\n if (checkAbortSignal(cesdk, abortSignal, placeholderBlock))\n return { status: 'aborted' };\n }\n const assetDefinition: AssetDefinition = {\n ...generatedAssetResult,\n id: `${Date.now()}-${generatedAssetResult.id}`,\n label:\n generatedAssetResult.label != null\n ? {\n en: generatedAssetResult.label\n }\n : {},\n tags: {}\n };\n\n cesdk.engine.asset.addAssetToSource(\n historyAssetSourceId,\n assetDefinition\n );\n }\n\n if (\n placeholderBlock != null &&\n cesdk.engine.block.isValid(placeholderBlock)\n ) {\n cesdk.engine.block.setState(placeholderBlock, {\n type: 'Ready'\n });\n }\n return { status: 'success', output };\n } catch (error) {\n if (\n placeholderBlock != null &&\n cesdk.engine.block.isValid(placeholderBlock)\n ) {\n if (isAbortError(error)) {\n cesdk.engine.block.destroy(placeholderBlock);\n } else {\n cesdk.engine.block.setState(placeholderBlock, {\n type: 'Error',\n error: 'Unknown'\n });\n }\n }\n throw error;\n } finally {\n if (config.debug) console.groupEnd();\n }\n}\n\n/**\n * Check the given abort signal and destroy the placeholder block if it is aborted.\n * @returns `true` if the signal is aborted, `false` otherwise.\n */\nfunction checkAbortSignal(\n cesdk: CreativeEditorSDK,\n abortSignal: AbortSignal,\n placeholderBlock?: number\n) {\n if (abortSignal.aborted) {\n if (\n placeholderBlock != null &&\n cesdk.engine.block.isValid(placeholderBlock)\n ) {\n cesdk.engine.block.destroy(placeholderBlock);\n }\n return true;\n }\n return false;\n}\n\nexport default generate;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport Provider, { GetInput, Output, OutputKind } from './provider';\nimport { InitProviderConfiguration } from './types';\nimport { extractErrorMessage } from '../utils';\n\nfunction handleGenerationError<K extends OutputKind, I, O extends Output>(\n error: unknown,\n options: {\n cesdk: CreativeEditorSDK;\n provider: Provider<K, I, O>;\n getInput?: GetInput<I>;\n },\n config: InitProviderConfiguration\n) {\n const { cesdk, provider, getInput } = options;\n\n if (config.onError != null && typeof config.onError === 'function') {\n config.onError(error);\n } else {\n // eslint-disable-next-line no-console\n console.error('Generation failed:', error);\n const shown = showErrorNotification(\n cesdk,\n provider.output.notification,\n () => ({\n input: getInput?.().input,\n error\n })\n );\n if (!shown) {\n cesdk.ui.showNotification({\n type: 'error',\n message: extractErrorMessage(error)\n });\n }\n }\n}\n\nfunction showErrorNotification<I, O extends Output>(\n cesdk: CreativeEditorSDK,\n notifications: Provider<any, I, O>['output']['notification'],\n createContext: () => { input?: I; error: unknown }\n): boolean {\n const errorNotification = notifications?.error;\n if (errorNotification == null) return false;\n\n const showOnSuccess =\n typeof errorNotification.show === 'function'\n ? errorNotification.show(createContext())\n : errorNotification.show;\n\n if (!showOnSuccess) return false;\n\n const message =\n typeof errorNotification.message === 'function'\n ? errorNotification.message(createContext())\n : errorNotification.message ?? 'common.ai-generation.failed';\n\n const action =\n errorNotification.action != null\n ? {\n label:\n typeof errorNotification.action.label === 'function'\n ? errorNotification.action.label(createContext())\n : errorNotification.action.label,\n onClick: () => {\n errorNotification?.action?.onClick(createContext());\n }\n }\n : undefined;\n\n cesdk.ui.showNotification({\n type: 'error',\n message,\n action\n });\n return true;\n}\n\nexport default handleGenerationError;\n", "import CreativeEditorSDK, {\n type BuilderRenderFunctionContext\n} from '@cesdk/cesdk-js';\nimport type Provider from './provider';\nimport {\n type GetInput,\n type OutputKind,\n type Output,\n type GetBlockInput\n} from './provider';\nimport { InitProviderConfiguration, UIOptions } from './types';\nimport generate from './generate';\nimport { isAbortError } from '../utils';\nimport handleGenerationError from './handleGenerationError';\n\nexport function isGeneratingStateKey(providerId: string): string {\n return `${providerId}.generating`;\n}\n\nexport function abortGenerationStateKey(providerId: string): string {\n return `${providerId}.abort`;\n}\n\n/**\n * Renders the generation UI components and sets up event handlers\n */\nfunction renderGenerationComponents<K extends OutputKind, I, O extends Output>(\n context: BuilderRenderFunctionContext<any>,\n provider: Provider<K, I, O>,\n getInput: GetInput<I>,\n getBlockInput: GetBlockInput<K, I>,\n options: UIOptions & {\n createPlaceholderBlock?: boolean;\n includeHistoryLibrary?: boolean;\n requiredInputs?: string[];\n },\n config: InitProviderConfiguration\n): void {\n const { builder, experimental } = context;\n const { cesdk, includeHistoryLibrary = true } = options;\n const {\n id: providerId,\n output: { abortable }\n } = provider;\n const abortState = experimental.global<() => void>(\n abortGenerationStateKey(providerId),\n () => {}\n );\n const generatingState = experimental.global<boolean>(\n isGeneratingStateKey(providerId),\n false\n );\n\n let abortController: AbortController | undefined;\n const canAbortNow = generatingState.value && abortable;\n const abort = () => {\n if (canAbortNow) {\n abortState.value();\n generatingState.setValue(false);\n abortState.setValue(() => {});\n }\n };\n\n let isDisabled: boolean | undefined;\n if (options.requiredInputs != null && options.requiredInputs.length > 0) {\n const inputs = getInput();\n isDisabled = options.requiredInputs.every((input) => {\n // @ts-ignore\n const hasInput = !inputs.input[input];\n return hasInput;\n });\n }\n\n const confirmCancelDialogId = experimental.global<string | undefined>(\n `${providerId}.confirmationDialogId`,\n undefined\n );\n\n builder.Section(`${providerId}.generate.section`, {\n children: () => {\n builder.Button(`${providerId}.generate`, {\n label: [\n 'common.ai-generation.generate',\n `panel.${providerId}.generate`\n ],\n isLoading: generatingState.value,\n color: 'accent',\n isDisabled,\n suffix: canAbortNow\n ? {\n icon: '@imgly/Cross',\n color: 'danger',\n tooltip: [`panel.${providerId}.abort`, 'common.cancel'],\n onClick: () => {\n const confirmationDialogId = cesdk.ui.showDialog({\n type: 'warning',\n content: 'panel.ly.img.ai.generation.confirmCancel.content',\n cancel: {\n label: 'common.close',\n onClick: ({ id }) => {\n cesdk.ui.closeDialog(id);\n confirmCancelDialogId.setValue(undefined);\n }\n },\n actions: {\n label: 'panel.ly.img.ai.generation.confirmCancel.confirm',\n color: 'danger',\n onClick: ({ id }) => {\n abort();\n cesdk.ui.closeDialog(id);\n confirmCancelDialogId.setValue(undefined);\n }\n }\n });\n confirmCancelDialogId.setValue(confirmationDialogId);\n }\n }\n : undefined,\n onClick: async () => {\n abortController = new AbortController();\n const abortSignal = abortController.signal;\n\n const triggerGeneration = async () => {\n try {\n generatingState.setValue(true);\n abortState.setValue(() => {\n if (config.debug)\n // eslint-disable-next-line no-console\n console.log('Aborting generation');\n abortController?.abort();\n });\n\n const result = await generate(\n provider.kind,\n getInput,\n getBlockInput,\n provider,\n options,\n config,\n abortSignal\n );\n\n if (result.status === 'aborted') {\n return;\n }\n\n const notification = provider.output.notification;\n showSuccessNotification(cesdk, notification, () => ({\n input: getInput().input,\n output: result.output\n }));\n } catch (error) {\n // Do not treat abort errors as errors\n if (isAbortError(error)) {\n return;\n }\n\n handleGenerationError(\n error,\n {\n cesdk,\n provider,\n getInput\n },\n config\n );\n } finally {\n abortController = undefined;\n generatingState.setValue(false);\n abortState.setValue(() => {});\n\n if (confirmCancelDialogId.value != null) {\n cesdk.ui.closeDialog(confirmCancelDialogId.value);\n confirmCancelDialogId.setValue(undefined);\n }\n }\n };\n\n if (config.middleware != null) {\n await config.middleware(triggerGeneration, {\n provider,\n abort\n });\n } else {\n await triggerGeneration();\n }\n }\n });\n if (provider.output.generationHintText != null) {\n builder.Text(`${providerId}.generation-hint`, {\n align: 'center',\n content: provider.output.generationHintText\n });\n }\n }\n });\n\n if (includeHistoryLibrary && options.historyAssetLibraryEntryId != null) {\n builder.Library(`${providerId}.history.library`, {\n entries: [options.historyAssetLibraryEntryId]\n });\n }\n}\n\nfunction showSuccessNotification<I, O extends Output>(\n cesdk: CreativeEditorSDK,\n notifications: Provider<any, I, O>['output']['notification'],\n createContext: () => { input: I; output: O }\n): boolean {\n const successNotification = notifications?.success;\n if (successNotification == null) return false;\n\n const showOnSuccess =\n typeof successNotification.show === 'function'\n ? successNotification.show(createContext())\n : successNotification.show;\n\n if (!showOnSuccess) return false;\n\n const message =\n typeof successNotification.message === 'function'\n ? successNotification.message(createContext())\n : successNotification.message ?? 'common.ai-generation.success';\n\n const action =\n successNotification.action != null\n ? {\n label:\n typeof successNotification.action.label === 'function'\n ? successNotification.action.label(createContext())\n : successNotification.action.label,\n onClick: () => {\n successNotification?.action?.onClick(createContext());\n }\n }\n : undefined;\n\n cesdk.ui.showNotification({\n type: 'success',\n message,\n action,\n duration: successNotification.duration\n });\n return true;\n}\n\nexport default renderGenerationComponents;\n", "import { OpenAPIV3 } from 'openapi-types';\nimport dereferenceDocument, {\n resolveReference\n} from './openapi/dereferenceDocument';\nimport {\n type OutputKind,\n type Output,\n type PanelInputSchema\n} from './provider';\nimport type Provider from './provider';\nimport { InitProviderConfiguration, UIOptions } from './types';\nimport { isOpenAPISchema } from './openapi/isOpenAPISchema';\nimport { GetPropertyInput, PropertyInput } from './openapi/types';\nimport renderProperty from './openapi/renderProperty';\nimport renderGenerationComponents from './renderGenerationComponents';\nimport getProperties from './openapi/getProperties';\nimport { BuilderRenderFunction } from '@cesdk/cesdk-js';\nimport { getPanelId } from '../utils';\n\n/**\n * Registers a schema-based panel input for a provider\n */\nasync function registerPanelInputSchema<\n K extends OutputKind,\n I,\n O extends Output\n>(\n provider: Provider<K, I, O>,\n panelInput: PanelInputSchema<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): Promise<BuilderRenderFunction<any>> {\n const { cesdk } = options;\n const { id: providerId } = provider;\n\n if (config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n `Registering schema-based panel input for provider ${providerId}`\n );\n }\n\n const schemaDocument = dereferenceDocument(panelInput.document);\n const resolvedInputReference = resolveReference(\n schemaDocument,\n panelInput.inputReference\n );\n\n if (!isOpenAPISchema(resolvedInputReference, config.debug)) {\n throw new Error(\n `Input reference '${panelInput.inputReference}' does not resolve to a valid OpenAPI schema`\n );\n }\n\n const inputSchema: OpenAPIV3.SchemaObject = resolvedInputReference;\n const properties = getProperties(inputSchema, panelInput);\n\n const builderRenderFunction: BuilderRenderFunction<any> = (context) => {\n const { builder } = context;\n\n const getInputs: GetPropertyInput[] = [];\n builder.Section(`${providerId}.schema.section`, {\n children: () => {\n properties.forEach((property) => {\n const getInput = renderProperty(\n context,\n property,\n provider,\n panelInput,\n options,\n config\n );\n if (getInput != null) {\n if (Array.isArray(getInput)) {\n getInputs.push(...getInput);\n } else {\n getInputs.push(getInput);\n }\n }\n });\n }\n });\n\n const inputs = getInputs.map((getInput) => {\n const input = getInput();\n return input;\n });\n\n const resolveInput = (input: PropertyInput) => {\n if (input.type === 'object') {\n return Object.entries(input.value).reduce((acc, [key, value]) => {\n acc[key] = resolveInput(value);\n\n return acc;\n }, {} as Record<string, any>);\n }\n\n return input.value;\n };\n const input = inputs.reduce((acc, propertyInput) => {\n acc[propertyInput.id] = resolveInput(propertyInput);\n return acc;\n }, {} as Record<string, any>) as I;\n\n renderGenerationComponents(\n context,\n provider,\n () => {\n return { input };\n },\n () => {\n return panelInput.getBlockInput(input);\n },\n {\n ...options,\n requiredInputs: inputSchema.required,\n createPlaceholderBlock: panelInput.userFlow === 'placeholder'\n },\n config\n );\n };\n\n cesdk.ui.registerPanel(getPanelId(providerId), builderRenderFunction);\n return builderRenderFunction;\n}\n\nexport default registerPanelInputSchema;\n", "import { BuilderRenderFunction } from '@cesdk/cesdk-js';\nimport type Provider from './provider';\nimport { OutputKind, PanelInputCustom, type Output } from './provider';\nimport renderGenerationComponents, {\n isGeneratingStateKey\n} from './renderGenerationComponents';\nimport { InitProviderConfiguration, UIOptions } from './types';\nimport { getPanelId } from '../utils';\n\nasync function registerPanelInputCustom<\n K extends OutputKind,\n I,\n O extends Output\n>(\n provider: Provider<K, I, O>,\n panelInput: PanelInputCustom<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): Promise<BuilderRenderFunction<any>> {\n const { cesdk } = options;\n const { id: providerId } = provider;\n\n const render = panelInput.render;\n\n const builderRenderFunction: BuilderRenderFunction<any> = (context) => {\n const { state } = context;\n\n const isGenerating = state(isGeneratingStateKey(providerId), {\n isGenerating: false,\n abort: () => {}\n }).value.isGenerating;\n\n const { getInput, getBlockInput } = render(context, {\n cesdk,\n isGenerating\n });\n renderGenerationComponents(\n context,\n provider,\n getInput,\n getBlockInput,\n {\n ...options,\n includeHistoryLibrary: panelInput.includeHistoryLibrary ?? true,\n createPlaceholderBlock: panelInput.userFlow === 'placeholder'\n },\n config\n );\n\n return getInput;\n };\n\n cesdk.ui.registerPanel(getPanelId(providerId), builderRenderFunction);\n\n return builderRenderFunction;\n}\n\nexport default registerPanelInputCustom;\n", "export const PLUGIN_ICON_SET_ID = '@imgly/plugin-ai-generation';\n\nexport const ICON_SPRITE = `\n<svg>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/Sparkle\"\n >\n <path d=\"M5.35545 2.06745C5.24149 1.72556 4.7579 1.72556 4.64394 2.06745L4.05898 3.82232C4.02166 3.93429 3.9338 4.02215 3.82184 4.05948L2.06694 4.64459C1.72506 4.75858 1.72509 5.24217 2.06699 5.3561L3.82179 5.9409C3.93378 5.97822 4.02166 6.06609 4.05899 6.17808L4.64394 7.93291C4.7579 8.2748 5.24149 8.2748 5.35545 7.93291L5.9404 6.17806C5.97773 6.06608 6.06559 5.97821 6.17757 5.94089L7.93242 5.35594C8.27431 5.24198 8.27431 4.75839 7.93242 4.64442L6.17757 4.05947C6.06559 4.02215 5.97773 3.93428 5.9404 3.8223L5.35545 2.06745Z\" fill=\"currentColor\"/>\n<path d=\"M17.9632 3.23614C17.8026 2.80788 17.1968 2.80788 17.0362 3.23614L16.0787 5.78951C16.0285 5.92337 15.9229 6.02899 15.789 6.07918L13.2356 7.0367C12.8074 7.19729 12.8074 7.80307 13.2356 7.96366L15.789 8.92118C15.9229 8.97138 16.0285 9.077 16.0787 9.21085L17.0362 11.7642C17.1968 12.1925 17.8026 12.1925 17.9632 11.7642L18.9207 9.21086C18.9709 9.077 19.0765 8.97138 19.2104 8.92118L21.7637 7.96366C22.192 7.80307 22.192 7.1973 21.7637 7.0367L19.2104 6.07918C19.0765 6.02899 18.9709 5.92337 18.9207 5.78951L17.9632 3.23614Z\" fill=\"currentColor\"/>\n<path d=\"M9.30058 7.82012C9.54712 7.1791 10.454 7.1791 10.7006 7.82012L12.3809 12.189C12.4571 12.3871 12.6136 12.5436 12.8117 12.6198L17.1806 14.3001C17.8216 14.5466 17.8216 15.4536 17.1806 15.7001L12.8117 17.3804C12.6136 17.4566 12.4571 17.6131 12.3809 17.8112L10.7006 22.1801C10.454 22.8211 9.54712 22.8211 9.30058 22.1801L7.62024 17.8112C7.54406 17.6131 7.38754 17.4566 7.18947 17.3804L2.82061 15.7001C2.17959 15.4536 2.17959 14.5466 2.82061 14.3001L7.18947 12.6198C7.38754 12.5436 7.54406 12.3871 7.62024 12.189L9.30058 7.82012Z\" fill=\"currentColor\"/>\n\n </symbol>\n\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"${PLUGIN_ICON_SET_ID}/image\"\n >\n <path d=\"M3 16.5V18C3 19.6569 4.34315 21 6 21H18C19.6569 21 21 19.6569 21 18V6C21 4.34315 19.6569 3 18 3L17.999 5C18.5513 5 19 5.44772 19 6V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V16.5H3Z\" fill=\"currentColor\"/>\n<path d=\"M13.0982 0.884877C12.9734 0.568323 12.5254 0.568322 12.4005 0.884876L11.7485 2.53819C11.7104 2.63483 11.6339 2.71134 11.5372 2.74945L9.8839 3.40151C9.56735 3.52636 9.56734 3.97436 9.8839 4.09921L11.5372 4.75126C11.6339 4.78938 11.7104 4.86588 11.7485 4.96253L12.4005 6.61584C12.5254 6.93239 12.9734 6.9324 13.0982 6.61584L13.7503 4.96253C13.7884 4.86588 13.8649 4.78938 13.9616 4.75126L15.6149 4.09921C15.9314 3.97436 15.9314 3.52636 15.6149 3.40151L13.9616 2.74945C13.8649 2.71134 13.7884 2.63483 13.7503 2.53819L13.0982 0.884877Z\" fill=\"currentColor\"/>\n<path d=\"M6.40053 5.38488C6.52538 5.06832 6.97338 5.06832 7.09823 5.38488L8.17455 8.11392C8.21267 8.21057 8.28917 8.28707 8.38582 8.32519L11.1149 9.40151C11.4314 9.52636 11.4314 9.97436 11.1149 10.0992L8.38582 11.1755C8.28917 11.2136 8.21267 11.2901 8.17455 11.3868L7.09823 14.1158C6.97338 14.4324 6.52538 14.4324 6.40053 14.1158L5.32421 11.3868C5.2861 11.2901 5.20959 11.2136 5.11295 11.1755L2.3839 10.0992C2.06735 9.97436 2.06735 9.52636 2.3839 9.40151L5.11295 8.32519C5.20959 8.28707 5.2861 8.21057 5.32421 8.11392L6.40053 5.38488Z\" fill=\"currentColor\"/>\n<path d=\"M18.9994 16.5008V18.0004C18.9994 18.5526 18.5517 19.0004 17.9994 19.0004H9.33302L14.3753 11.4369C14.6722 10.9916 15.3266 10.9916 15.6234 11.4369L18.9994 16.5008Z\" fill=\"currentColor\"/>\n\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"${PLUGIN_ICON_SET_ID}/video\"\n >\n<path d=\"M6 3C4.34315 3 3 4.34315 3 6V18C3 19.6569 4.34315 21 6 21H18C19.6569 21 21 19.6569 21 18V16.5H19V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V6C5 5.44772 5.44772 5 6 5V3Z\" fill=\"currentColor\"/>\n<path d=\"M10.9025 0.8839C11.0273 0.567345 11.4753 0.567346 11.6002 0.883901L12.2522 2.53721C12.2904 2.63386 12.3669 2.71036 12.4635 2.74848L14.1168 3.40053C14.4334 3.52538 14.4334 3.97338 14.1168 4.09823L12.4635 4.75029C12.3669 4.7884 12.2904 4.86491 12.2522 4.96155L11.6002 6.61486C11.4753 6.93142 11.0273 6.93142 10.9025 6.61486L10.2504 4.96155C10.2123 4.86491 10.1358 4.7884 10.0392 4.75029L8.38585 4.09823C8.0693 3.97338 8.0693 3.52538 8.38585 3.40053L10.0392 2.74848C10.1358 2.71036 10.2123 2.63386 10.2504 2.53721L10.9025 0.8839Z\" fill=\"currentColor\"/>\n<path d=\"M18.9019 3.3845C19.0267 3.06795 19.4747 3.06795 19.5996 3.3845L20.6759 6.11355C20.714 6.2102 20.7905 6.2867 20.8872 6.32482L23.6162 7.40114C23.9328 7.52598 23.9328 7.97399 23.6162 8.09883L20.8872 9.17515C20.7905 9.21327 20.714 9.28977 20.6759 9.38642L19.5996 12.1155C19.4747 12.432 19.0267 12.432 18.9019 12.1155L17.8255 9.38642C17.7874 9.28977 17.7109 9.21327 17.6143 9.17515L14.8852 8.09883C14.5687 7.97399 14.5687 7.52598 14.8852 7.40114L17.6143 6.32482C17.7109 6.2867 17.7874 6.2102 17.8255 6.11355L18.9019 3.3845Z\" fill=\"currentColor\"/>\n<path d=\"M14.9994 13.2862C15.5089 12.8859 15.5089 12.1141 14.9995 11.7137L10.618 8.27047C9.96188 7.75485 9.00011 8.22225 9.00011 9.05673L9.00011 15.9429C9.00011 16.7773 9.96185 17.2448 10.618 16.7292L14.9994 13.2862Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"${PLUGIN_ICON_SET_ID}/audio\"\n >\n <path d=\"M6 3.80273C4.2066 4.84016 3 6.77919 3 9.00004V12.8153C3 15.931 5.39501 18.4873 8.44444 18.7436V20.9645C8.44444 22.2198 9.89427 22.9198 10.8773 22.1392L15.1265 18.7647H15.5C17.8285 18.7647 19.8472 17.4384 20.8417 15.5H18.4187C17.6889 16.2784 16.6512 16.7647 15.5 16.7647H14.9522C14.6134 16.7647 14.2846 16.8794 14.0193 17.0901L10.4444 19.929V18.2597C10.4444 17.4341 9.77513 16.7647 8.9495 16.7647C7.80494 16.7647 6.77409 16.2779 6.05276 15.5H6V15.4419C5.37798 14.7439 5 13.8237 5 12.8153V9.00004C5 7.98559 5.37764 7.05935 6 6.35422V3.80273Z\" fill=\"currentColor\"/>\n<path d=\"M11.6002 1.8839C11.4753 1.56735 11.0273 1.56735 10.9025 1.8839L10.2504 3.53721C10.2123 3.63386 10.1358 3.71036 10.0392 3.74848L8.38585 4.40053C8.0693 4.52538 8.0693 4.97338 8.38585 5.09823L10.0392 5.75029C10.1358 5.7884 10.2123 5.86491 10.2504 5.96155L10.9025 7.61486C11.0273 7.93142 11.4753 7.93142 11.6002 7.61486L12.2522 5.96155C12.2904 5.86491 12.3669 5.7884 12.4635 5.75029L14.1168 5.09823C14.4334 4.97338 14.4334 4.52538 14.1168 4.40053L12.4635 3.74848C12.3669 3.71036 12.2904 3.63386 12.2522 3.53721L11.6002 1.8839Z\" fill=\"currentColor\"/>\n<path d=\"M19.5996 4.3845C19.4747 4.06795 19.0267 4.06795 18.9019 4.3845L17.8255 7.11355C17.7874 7.2102 17.7109 7.2867 17.6143 7.32482L14.8852 8.40114C14.5687 8.52598 14.5687 8.97399 14.8852 9.09883L17.6143 10.1752C17.7109 10.2133 17.7874 10.2898 17.8255 10.3864L18.9019 13.1155C19.0267 13.432 19.4747 13.432 19.5996 13.1155L20.6759 10.3864C20.714 10.2898 20.7905 10.2133 20.8872 10.1752L23.6162 9.09883C23.9328 8.97399 23.9328 8.52598 23.6162 8.40114L20.8872 7.32482C20.7905 7.2867 20.714 7.2102 20.6759 7.11355L19.5996 4.3845Z\" fill=\"currentColor\"/>\n </symbol>\n <symbol\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n id=\"@imgly/MixingPlate\"\n >\n <path d=\"M9.75 9C10.5784 9 11.25 8.32843 11.25 7.5C11.25 6.67157 10.5784 6 9.75 6C8.92157 6 8.25 6.67157 8.25 7.5C8.25 8.32843 8.92157 9 9.75 9Z\" fill=\"currentColor\"/>\n<path d=\"M7 13C7.82843 13 8.5 12.3284 8.5 11.5C8.5 10.6716 7.82843 10 7 10C6.17157 10 5.5 10.6716 5.5 11.5C5.5 12.3284 6.17157 13 7 13Z\" fill=\"currentColor\"/>\n<path d=\"M15.75 7.5C15.75 8.32843 15.0784 9 14.25 9C13.4216 9 12.75 8.32843 12.75 7.5C12.75 6.67157 13.4216 6 14.25 6C15.0784 6 15.75 6.67157 15.75 7.5Z\" fill=\"currentColor\"/>\n<path d=\"M17 13C17.8284 13 18.5 12.3284 18.5 11.5C18.5 10.6716 17.8284 10 17 10C16.1716 10 15.5 10.6716 15.5 11.5C15.5 12.3284 16.1716 13 17 13Z\" fill=\"currentColor\"/>\n<path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M8.26309 2.77709C10.6681 1.77921 13.4829 1.7322 15.9209 2.64297C18.1572 3.47923 20.0876 5.09285 21.1766 7.28598C22.3395 9.62772 22.4889 13.1077 20.3864 15.2982C19.2693 16.4621 17.7657 16.9982 16.0026 16.9997C15.7897 16.9997 15.5555 16.9864 15.3497 16.9745C15.309 16.9722 15.2694 16.9699 15.2313 16.9679C14.9817 16.9542 14.761 16.9455 14.5569 16.9539C14.124 16.9718 13.9598 17.0612 13.89 17.1324C13.718 17.3081 13.6946 17.6672 13.8854 17.8895C14.2899 18.3608 14.5016 18.9277 14.5016 19.5497C14.5016 20.2206 14.3086 20.9011 13.7542 21.3896C13.2471 21.837 12.6082 21.9997 11.9635 21.9997C10.6049 21.9997 9.31155 21.7367 8.0934 21.2067C6.89058 20.6831 5.84501 19.9687 4.94363 19.0666C4.04281 18.1651 3.31836 17.107 2.79369 15.8978C1.72761 13.4409 1.72662 10.5261 2.81247 8.07034C3.88024 5.65548 5.84206 3.78161 8.26309 2.77709ZM15.2207 4.51639C13.2556 3.78239 10.9651 3.82132 9.02956 4.62439C7.06888 5.43791 5.49559 6.94785 4.64163 8.87914C3.78373 10.8194 3.78253 13.1522 4.62841 15.1017C5.05312 16.0805 5.63511 16.9291 6.35838 17.6529C7.08102 18.3761 7.91671 18.9484 8.89123 19.3728C9.8492 19.7895 10.87 19.9997 11.9635 19.9997C12.2815 19.9997 12.394 19.9225 12.431 19.8899L12.4319 19.8891C12.4367 19.8849 12.4487 19.8743 12.4631 19.8359C12.4799 19.7911 12.5016 19.7024 12.5016 19.5497C12.5016 19.4091 12.4633 19.3034 12.3677 19.192C11.5353 18.222 11.5272 16.6868 12.4611 15.7331C13.0741 15.1071 13.8844 14.98 14.4745 14.9556C14.7819 14.943 15.085 14.9568 15.3409 14.9709C15.3906 14.9736 15.4379 14.9763 15.4832 14.9788C15.6876 14.9904 15.8508 14.9997 16.0009 14.9997C17.3405 14.9986 18.2792 14.6054 18.9435 13.9133C20.2633 12.5382 20.3186 10.055 19.3853 8.1755C18.5436 6.48051 17.0293 5.19281 15.2207 4.51639Z\" fill=\"currentColor\"/>\n\n </symbol>\n</svg>\n`;\n\nexport default ICON_SPRITE;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { QuickActionId, QuickActionMenu } from './types';\nimport { Output, QuickAction } from '../provider';\n\nconst QUICK_ACTION_ORDER_KEY_PREFIX = 'ly.img.ai.quickAction.order';\n\nconst QUICK_ACTION_REGISTRY_PREFIX = 'ly.img.ai.quickAction.actions';\n\n/**\n * Returns an object representing the quick action menu. Can be called and\n * retrieved multiple times.\n *\n * It's backed up by the global state.\n */\nfunction getQuickActionMenu(cesdk: CreativeEditorSDK, id: string) {\n const quickActionMenu: QuickActionMenu = {\n id,\n setQuickActionMenuOrder: (quickActionIds: string[]) => {\n cesdk.ui.experimental.setGlobalStateValue<QuickActionId[]>(\n `${QUICK_ACTION_ORDER_KEY_PREFIX}.${id}`,\n quickActionIds\n );\n },\n getQuickActionMenuOrder: () => {\n return cesdk.ui.experimental.getGlobalStateValue<QuickActionId[]>(\n `${QUICK_ACTION_ORDER_KEY_PREFIX}.${id}`,\n []\n );\n },\n registerQuickAction: <I, O extends Output>(\n quickAction: QuickAction<I, O>\n ) => {\n if (\n !cesdk.ui.experimental.hasGlobalStateValue(\n `${QUICK_ACTION_REGISTRY_PREFIX}.${id}`\n )\n ) {\n cesdk.ui.experimental.setGlobalStateValue<{\n [key: string]: QuickAction<I, O>;\n }>(`${QUICK_ACTION_REGISTRY_PREFIX}.${id}`, {\n [quickAction.id]: quickAction\n });\n } else {\n const entries = cesdk.ui.experimental.getGlobalStateValue(\n `${QUICK_ACTION_REGISTRY_PREFIX}.${id}`,\n {}\n );\n cesdk.ui.experimental.setGlobalStateValue(\n `${QUICK_ACTION_REGISTRY_PREFIX}.${id}`,\n {\n ...entries,\n [quickAction.id]: quickAction\n }\n );\n }\n },\n\n getQuickAction: <I, O extends Output>(quickActionId: string) => {\n const entries = cesdk.ui.experimental.getGlobalStateValue<{\n [key: string]: QuickAction<I, O>;\n }>(`${QUICK_ACTION_REGISTRY_PREFIX}.${id}`, {});\n\n return entries[quickActionId];\n }\n };\n return quickActionMenu;\n}\n\nexport default getQuickActionMenu;\n", "import { Output, QuickAction } from '../provider';\n\nexport const INFERENCE_AI_EDIT_MODE = 'ly.img.ai.inference.editMode';\n\nexport const INFERENCE_AI_METADATA_KEY = 'ly.img.ai.inference.metadata';\n\nexport const INFERENCE_CONFIRMATION_COMPONENT_ID =\n 'ly.img.ai.inference.confirmation.canvasMenu';\n\nexport function getFeatureIdForQuickAction(options: {\n quickActionId: string;\n quickActionMenuId: string;\n}) {\n return `ly.img.ai.quickAction.${options.quickActionMenuId}.${options.quickActionId}`;\n}\n\n/**\n * Removes all two following `ly.img.separator` entries from the quick\n * actions array or if it is first or last in the array.\n */\nexport function removeDuplicatedSeparators<I, O extends Output>(\n quickActions: (QuickAction<I, O> | 'ly.img.separator')[]\n): (QuickAction<I, O> | 'ly.img.separator')[] {\n if (quickActions.length === 0) {\n return [];\n }\n\n // Create a new array for the result\n const result = [...quickActions];\n\n // Remove separators at the beginning\n while (result.length > 0 && result[0] === 'ly.img.separator') {\n result.shift();\n }\n\n // Remove separators at the end\n while (\n result.length > 0 &&\n result[result.length - 1] === 'ly.img.separator'\n ) {\n result.pop();\n }\n\n // Remove consecutive separators\n return result.reduce<(QuickAction<I, O> | 'ly.img.separator')[]>(\n (acc, current) => {\n // Skip if current is a separator and previous was also a separator\n if (\n current === 'ly.img.separator' &&\n acc.length > 0 &&\n acc[acc.length - 1] === 'ly.img.separator'\n ) {\n return acc;\n }\n\n acc.push(current);\n return acc;\n },\n []\n );\n}\n", "import { Middleware } from './middleware';\nimport { Output } from '../provider';\n\n/**\n * Highlights the blocks while the middleware is running.\n *\n * - Sets the blocks to always on top\n * - Disables clipping of the parent of the blocks so it is visible\n */\nfunction highlightBlocksMiddleware<I, O extends Output>({\n alwaysOnTop = true,\n disableClipping = true\n}: {\n /**\n * Until disposed, should the block be always on top to be visible?\n *\n * @default true\n */\n alwaysOnTop?: boolean;\n\n /**\n * If true, the clipping of the parent of the affected blocks will be\n * temporarily disabled until unlocked.\n *\n * @default true\n */\n disableClipping?: boolean;\n}): Middleware<I, O> {\n const middleware: Middleware<I, O> = async (input, options, next) => {\n const wasAlwaysOnTop: Record<number, boolean> = {};\n const parentClipping: Record<number, boolean> = {};\n\n const blockIds =\n alwaysOnTop || disableClipping\n ? options.blockIds ?? options.engine.block.findAllSelected()\n : [];\n\n blockIds.forEach((blockId) => {\n if (options.engine.block.isValid(blockId))\n if (alwaysOnTop) {\n wasAlwaysOnTop[blockId] = options.engine.block.isAlwaysOnTop(blockId);\n options.engine.block.setAlwaysOnTop(blockId, true);\n }\n if (disableClipping) {\n const parent = options.engine.block.getParent(blockId);\n if (\n parent != null &&\n options.engine.block.getType(parent) !== '//ly.img.ubq/scene'\n ) {\n parentClipping[parent] = options.engine.block.isClipped(parent);\n options.engine.block.setClipped(parent, false);\n }\n }\n });\n\n options.addDisposer(async () => {\n blockIds.forEach((blockId) => {\n if (options.engine.block.isValid(blockId))\n if (alwaysOnTop) {\n options.engine.block.setAlwaysOnTop(\n blockId,\n wasAlwaysOnTop[blockId]\n );\n }\n if (disableClipping) {\n const parent = options.engine.block.getParent(blockId);\n if (\n parent != null &&\n options.engine.block.getType(parent) !== '//ly.img.ubq/scene'\n ) {\n if (parentClipping[parent] != null) {\n options.engine.block.setClipped(parent, parentClipping[parent]);\n }\n }\n }\n });\n });\n const result = await next(input, options);\n\n return result;\n };\n\n return middleware;\n}\n\nexport default highlightBlocksMiddleware;\n", "import { Middleware } from './middleware';\nimport { Output } from '../provider';\n\n/**\n * Sets the blocks to a pending state while the middleware is running.\n */\nfunction pendingMiddleware<I, O extends Output>({\n pending = true\n}: {\n /**\n * Should the blocks be set to a pending state?\n *\n * @default true\n */\n pending?: boolean;\n}): Middleware<I, O> {\n const middleware: Middleware<I, O> = async (input, options, next) => {\n const blockIds = pending\n ? options.blockIds ?? options.engine.block.findAllSelected()\n : [];\n\n try {\n blockIds.forEach((blockId) => {\n if (options.engine.block.isValid(blockId))\n options.engine.block.setState(blockId, {\n type: 'Pending',\n progress: 0\n });\n });\n const result = await next(input, options);\n\n return result;\n } finally {\n blockIds.forEach((blockId) => {\n if (options.engine.block.isValid(blockId))\n options.engine.block.setState(blockId, { type: 'Ready' });\n });\n }\n };\n\n return middleware;\n}\n\nexport default pendingMiddleware;\n", "import { Middleware } from './middleware';\nimport { Output } from '../provider';\nimport { CreativeEngine } from '@cesdk/cesdk-js';\nimport { isAbortError } from '../../utils';\n\n/**\n * Highlights the blocks while the middleware is running.\n */\nfunction lockMiddleware<I, O extends Output>({\n editMode,\n automaticallyUnlock = false\n}: {\n /**\n * The edit mode to lock the selection to.\n */\n editMode: string;\n\n /**\n * Should the selection be automatically unlocked after the function completes?\n * Otherwise the returned unlock function must be called manually.\n *\n * @default false\n */\n automaticallyUnlock?: boolean;\n}): Middleware<I, O> {\n const middleware: Middleware<I, O> = async (input, options, next) => {\n const blockIds = options.blockIds ?? options.engine.block.findAllSelected();\n\n let unlock: () => void = () => {};\n if (!automaticallyUnlock) {\n options.addDisposer(async () => {\n if (unlock != null) {\n unlock();\n }\n });\n }\n try {\n unlock = lockSelectionInEditMode(options.engine, blockIds, editMode);\n const result = await next(input, options);\n return result;\n } catch (error) {\n if (isAbortError(error)) {\n unlock();\n }\n throw error;\n } finally {\n if (automaticallyUnlock) {\n unlock();\n }\n }\n };\n\n return middleware;\n}\n\n/**\n * Locks the selection to the given block ids with the given edit mode.\n *\n * @returns A function to unlock the selection. Will set the edit mode back to what it was before the lock.\n */\nfunction lockSelectionInEditMode(\n engine: CreativeEngine,\n blockIdsToLockOn: number[],\n editModeToLock: string\n) {\n const globalScopeBeforeLock = engine.editor.getGlobalScope('editor/select');\n const editModeBeforeLock = engine.editor.getEditMode();\n selectOnlyBlockIds();\n engine.editor.setGlobalScope('editor/select', 'Deny');\n engine.editor.setEditMode(editModeToLock);\n const lockedHistory = engine.editor.createHistory();\n const historyBeforeLock = engine.editor.getActiveHistory();\n engine.editor.setActiveHistory(lockedHistory);\n\n function selectOnlyBlockIds() {\n engine.block.findAllSelected().forEach((currentlySelectedBlockId) => {\n if (!blockIdsToLockOn.includes(currentlySelectedBlockId)) {\n engine.block.setSelected(currentlySelectedBlockId, false);\n }\n });\n\n blockIdsToLockOn.forEach((blockId) => {\n engine.block.setSelected(blockId, true);\n });\n }\n\n const stateChangeDisposer = engine.editor.onStateChanged(() => {\n const editMode = engine.editor.getEditMode();\n if (editMode !== editModeToLock) {\n engine.editor.setEditMode(editModeToLock);\n }\n });\n\n const selectionDisposer = engine.block.onSelectionChanged(selectOnlyBlockIds);\n\n const dispose = () => {\n if (globalScopeBeforeLock != null) {\n engine.editor.setGlobalScope('editor/select', globalScopeBeforeLock);\n }\n\n engine.editor.setEditMode(editModeBeforeLock);\n engine.editor.setActiveHistory(historyBeforeLock);\n engine.editor.destroyHistory(lockedHistory);\n\n selectionDisposer();\n stateChangeDisposer();\n };\n\n return dispose;\n}\n\nexport default lockMiddleware;\n", "import type CreativeEditorSDK from '@cesdk/cesdk-js';\nimport {\n GenerationResult,\n ImageOutput,\n TextOutput,\n type Output,\n type OutputKind\n} from '../provider';\nimport { ApplyCallbacks } from './types';\nimport {\n getImageDimensionsFromURL,\n mimeTypeToExtension\n} from '@imgly/plugin-utils';\nimport { isAsyncGenerator } from '../../utils';\n\ntype ConsumeGeneratedResultOptions = {\n kind: OutputKind;\n blockIds: number[];\n cesdk: CreativeEditorSDK;\n abortSignal: AbortSignal;\n};\n\ntype ReturnValue<O extends Output> = {\n consumedGenerationResult: O;\n applyCallbacks: ApplyCallbacks;\n};\n\n/**\n * This method is used in the quick action menu to handle the result of the generation\n * and providing methods for the comparision of the result.\n *\n * Different output kinds require different handling. E.g. the text generation\n * is streamed to the text block, while the image generation is applied to the fill\n * block with a source set and the same crop applied.\n */\nfunction consumeGeneratedResult<O extends Output>(\n result: GenerationResult<O>,\n options: ConsumeGeneratedResultOptions\n): Promise<ReturnValue<O>> {\n switch (options.kind) {\n case 'text':\n return getApplyCallbacksForText(result, options);\n case 'image':\n return getApplyCallbacksForImage(result, options);\n case 'video':\n return getApplyCallbacksForVideo(result, options);\n case 'audio':\n return getApplyCallbacksForAudio(result, options);\n default:\n throw new Error(\n `Unsupported output kind for quick actions: ${options.kind}`\n );\n }\n}\n\nasync function getApplyCallbacksForText<O extends Output>(\n generationResult: GenerationResult<O>,\n options: ConsumeGeneratedResultOptions\n): Promise<ReturnValue<O>> {\n const { cesdk, blockIds, abortSignal } = options;\n\n const beforeTexts = blockIds.map((blockId) => {\n return cesdk.engine.block.getString(blockId, 'text/text');\n });\n\n let output: O | undefined;\n if (isAsyncGenerator(generationResult)) {\n let inferredText = '';\n for await (const chunk of generationResult) {\n if (abortSignal.aborted) {\n break;\n }\n if (typeof chunk === 'string') {\n inferredText = chunk;\n } else if (chunk.kind === 'text') {\n inferredText = chunk.text;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-loop-func\n blockIds.forEach((blockId) => {\n cesdk.engine.block.setString(blockId, 'text/text', inferredText);\n });\n\n const textOutput: TextOutput = {\n kind: 'text',\n text: inferredText\n };\n output = textOutput as O;\n }\n } else {\n output = generationResult;\n }\n\n if (output == null || output.kind !== 'text') {\n throw new Error('Output kind from generation is not text');\n }\n\n const onAfter = () => {\n options.blockIds.forEach((blockId) => {\n options.cesdk.engine.block.setString(blockId, 'text/text', output.text);\n });\n };\n const onBefore = () => {\n options.blockIds.forEach((blockId, i) => {\n options.cesdk.engine.block.setString(\n blockId,\n 'text/text',\n beforeTexts[i]\n );\n });\n };\n const onCancel = onBefore;\n const onApply = () => {\n onAfter();\n options.cesdk.engine.editor.addUndoStep();\n };\n\n return {\n consumedGenerationResult: output,\n applyCallbacks: {\n onBefore,\n onAfter,\n onCancel,\n onApply\n }\n };\n}\n\nasync function getApplyCallbacksForImage<O extends Output>(\n generationResult: GenerationResult<O>,\n options: ConsumeGeneratedResultOptions\n): Promise<ReturnValue<O>> {\n const { cesdk, blockIds, abortSignal } = options;\n if (blockIds.length !== 1) {\n throw new Error('Only one block is supported for image generation');\n }\n\n const [block] = blockIds;\n const fillBlock = cesdk.engine.block.getFill(block);\n const sourceSetBefore = cesdk.engine.block.getSourceSet(\n fillBlock,\n 'fill/image/sourceSet'\n );\n const [sourceBefore] = sourceSetBefore;\n let uriBefore: string | undefined;\n if (sourceBefore == null) {\n uriBefore = cesdk.engine.block.getString(\n fillBlock,\n 'fill/image/imageFileURI'\n );\n }\n\n const mimeType = await cesdk.engine.editor.getMimeType(\n sourceBefore?.uri ?? uriBefore\n );\n const originalDimension = await getImageDimensionsFromURL(\n sourceBefore?.uri ?? uriBefore,\n options.cesdk.engine\n );\n const originalAspectRatio =\n originalDimension.width / originalDimension.height;\n abortSignal.throwIfAborted();\n\n if (mimeType === 'image/svg+xml') {\n throw new Error('SVG images are not supported');\n }\n\n const cropScaleX = cesdk.engine.block.getCropScaleX(block);\n const cropScaleY = cesdk.engine.block.getCropScaleY(block);\n const cropTranslationX = cesdk.engine.block.getCropTranslationX(block);\n const cropTranslationY = cesdk.engine.block.getCropTranslationY(block);\n const cropRotation = cesdk.engine.block.getCropRotation(block);\n\n const applyCrop = () => {\n cesdk.engine.block.setCropScaleX(block, cropScaleX);\n cesdk.engine.block.setCropScaleY(block, cropScaleY);\n cesdk.engine.block.setCropTranslationX(block, cropTranslationX);\n cesdk.engine.block.setCropTranslationY(block, cropTranslationY);\n cesdk.engine.block.setCropRotation(block, cropRotation);\n };\n\n if (isAsyncGenerator(generationResult)) {\n throw new Error('Streaming generation is not supported yet from a panel');\n }\n\n if (\n generationResult.kind !== 'image' ||\n typeof generationResult.url !== 'string'\n ) {\n throw new Error('Output kind from generation is not an image');\n }\n\n const url = (generationResult as ImageOutput).url;\n const generatedMimeType = await cesdk.engine.editor.getMimeType(url);\n\n const uri = await reuploadImage(cesdk, url, generatedMimeType);\n const generatedDimension = await getImageDimensionsFromURL(\n uri,\n options.cesdk.engine\n );\n const generatedAspectRatio =\n generatedDimension.width / generatedDimension.height;\n\n const differentAspectRatio =\n Math.abs(originalAspectRatio - generatedAspectRatio) > 0.001;\n\n const sourceSetAfter = sourceBefore\n ? [\n {\n uri,\n width: generatedDimension.width,\n height: generatedDimension.height\n }\n ]\n : undefined;\n const uriAfter = uri;\n\n if (sourceSetAfter == null) {\n cesdk.engine.block.setString(\n fillBlock,\n 'fill/image/imageFileURI',\n uriAfter\n );\n } else {\n cesdk.engine.block.setString(fillBlock, 'fill/image/imageFileURI', '');\n cesdk.engine.block.setSourceSet(\n fillBlock,\n 'fill/image/sourceSet',\n sourceSetAfter\n );\n }\n if (differentAspectRatio) {\n cesdk.engine.block.setContentFillMode(block, 'Cover');\n } else {\n applyCrop();\n }\n\n const onBefore = () => {\n if (sourceSetBefore == null || sourceSetBefore.length === 0) {\n if (uriBefore == null) {\n throw new Error('No image URI found');\n }\n cesdk.engine.block.setString(\n fillBlock,\n 'fill/image/imageFileURI',\n uriBefore\n );\n } else {\n cesdk.engine.block.setSourceSet(\n fillBlock,\n 'fill/image/sourceSet',\n sourceSetBefore\n );\n }\n applyCrop();\n };\n const onAfter = () => {\n if (sourceSetAfter == null) {\n if (uriAfter == null) {\n throw new Error('No image URI found');\n }\n cesdk.engine.block.setString(\n fillBlock,\n 'fill/image/imageFileURI',\n uriAfter\n );\n } else {\n cesdk.engine.block.setSourceSet(\n fillBlock,\n 'fill/image/sourceSet',\n sourceSetAfter\n );\n }\n if (differentAspectRatio) {\n cesdk.engine.block.setContentFillMode(block, 'Cover');\n } else {\n applyCrop();\n }\n };\n const onCancel = () => {\n onBefore();\n };\n const onApply = () => {\n onAfter();\n options.cesdk.engine.editor.addUndoStep();\n };\n\n return {\n consumedGenerationResult: generationResult,\n applyCallbacks: {\n onBefore,\n onAfter,\n onCancel,\n onApply\n }\n };\n}\n\nasync function getApplyCallbacksForVideo<O extends Output>(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _result: GenerationResult<O>,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _options: ConsumeGeneratedResultOptions\n): Promise<ReturnValue<O>> {\n throw new Error('Function not implemented.');\n}\n\nasync function getApplyCallbacksForAudio<O extends Output>(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _result: GenerationResult<O>,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _options: ConsumeGeneratedResultOptions\n): Promise<ReturnValue<O>> {\n throw new Error('Function not implemented.');\n}\n\nasync function reuploadImage(\n cesdk: CreativeEditorSDK,\n url: string,\n mimeType: string\n): Promise<string> {\n const response = await fetch(url);\n const blob = await response.blob();\n const file = new File([blob], `image.${mimeTypeToExtension(mimeType)}`, {\n type: mimeType\n });\n const assetDefinition = await cesdk.unstable_upload(file, () => {});\n const uploadedUri = assetDefinition?.meta?.uri;\n if (uploadedUri != null) return uploadedUri;\n // eslint-disable-next-line no-console\n console.warn('Failed to upload image:', assetDefinition);\n return url;\n}\n\nexport default consumeGeneratedResult;\n", "import { Middleware } from './middleware';\nimport { Output } from '../provider';\nimport { CreativeEngine } from '@cesdk/cesdk-js';\nimport { isAbortError } from '../../utils';\n\n/**\n * For a given edit mode and block ids, this middleware will\n * ensure that as long as these blocks are selected, the edit mode is\n * set to the given edit mode and cannot be changed.\n *\n * The use-case is to show only the generation canvas menu during\n * the generation process.\n */\nfunction editModeMiddleware<I, O extends Output>({\n editMode,\n automaticallyUnlock = false,\n showNotification = true\n}: {\n /**\n * The edit mode to lock the selection to.\n */\n editMode: string;\n\n /**\n * Should the selection be automatically unlocked after the function completes?\n * Otherwise the returned unlock function must be called manually.\n *\n * @default false\n */\n automaticallyUnlock?: boolean;\n\n /**\n * Should the blocks be set when the generation is done\n *\n * @default true\n */\n showNotification?: boolean;\n}): Middleware<I, O> {\n const middleware: Middleware<I, O> = async (input, options, next) => {\n const blockIds = options.blockIds ?? options.engine.block.findAllSelected();\n\n let unlock: () => void = () => {};\n if (!automaticallyUnlock) {\n options.addDisposer(async () => {\n if (unlock != null) {\n unlock();\n }\n });\n }\n try {\n unlock = bindSelectionToEditMode(options.engine, blockIds, editMode);\n const result = await next(input, options);\n\n if (showNotification) {\n const currentlySelectedBlockIds =\n options.engine.block.findAllSelected();\n const blockIdsAreSelected = blockIds.some((blockId) => {\n return currentlySelectedBlockIds.includes(blockId);\n });\n\n if (!blockIdsAreSelected) {\n options.cesdk?.ui.showNotification({\n type: 'success',\n message: 'AI generation complete',\n action: {\n label: 'Select',\n onClick: () => {\n blockIds.forEach((blockId) => {\n options.engine.block.select(blockId);\n });\n }\n }\n });\n }\n }\n return result;\n } catch (error) {\n if (isAbortError(error)) {\n unlock();\n }\n throw error;\n } finally {\n if (automaticallyUnlock) {\n unlock();\n }\n }\n };\n\n return middleware;\n}\n\n/**\n * Locks the selection to the given block ids with the given edit mode.\n *\n * @returns A function to unlock the selection. Will set the edit mode back to what it was before the lock.\n */\nfunction bindSelectionToEditMode(\n engine: CreativeEngine,\n blockIdsToBind: number[],\n editModeToBindTo: string\n) {\n function isBoundBlockSelected() {\n const currentlySelectedBlockIds = engine.block.findAllSelected();\n return blockIdsToBind.some((blockId) => {\n return currentlySelectedBlockIds.includes(blockId);\n });\n }\n\n const stateChangeDisposer = engine.editor.onStateChanged(() => {\n const editMode = engine.editor.getEditMode();\n if (editMode !== editModeToBindTo && isBoundBlockSelected()) {\n engine.editor.setEditMode(editModeToBindTo);\n }\n });\n\n const selectionDisposer = engine.block.onSelectionChanged(() => {\n if (isBoundBlockSelected()) {\n engine.editor.setEditMode(editModeToBindTo);\n } else {\n engine.editor.setEditMode('Transform');\n }\n });\n\n if (isBoundBlockSelected()) {\n engine.editor.setEditMode(editModeToBindTo);\n }\n\n const dispose = () => {\n selectionDisposer();\n stateChangeDisposer();\n\n engine.editor.setEditMode('Transform');\n };\n\n return dispose;\n}\n\nexport default editModeMiddleware;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { InferenceMetadata, QuickActionMenu, ApplyCallbacks } from './types';\nimport { INFERENCE_AI_EDIT_MODE, INFERENCE_AI_METADATA_KEY } from './utils';\nimport { Metadata } from '@imgly/plugin-utils';\nimport Provider, {\n GenerationOptions,\n Output,\n OutputKind,\n QuickAction\n} from '../provider';\nimport { composeMiddlewares } from '../middleware/middleware';\nimport loggingMiddleware from '../middleware/loggingMiddleware';\nimport highlightBlocksMiddleware from '../middleware/highlightBlocksMiddleware';\nimport pendingMiddleware from '../middleware/pendingMiddleware';\nimport lockMiddleware from '../middleware/lockMiddleware';\nimport consumeGeneratedResult from './consumeGeneratedResult';\nimport editModeMiddleware from '../middleware/editModeMiddleware';\nimport { InitProviderConfiguration } from '../types';\nimport dryRunMiddleware from '../middleware/dryRunMiddleware';\n\nasync function generate<K extends OutputKind, I, O extends Output>(\n options: {\n input: I;\n blockIds: number[];\n cesdk: CreativeEditorSDK;\n quickAction: QuickAction<I, O>;\n quickActionMenu: QuickActionMenu;\n provider: Provider<K, I, O>;\n abortSignal: AbortSignal;\n confirmationComponentId: string;\n },\n config: InitProviderConfiguration\n): Promise<{\n dispose: () => void;\n returnValue: O;\n applyCallbacks?: ApplyCallbacks;\n}> {\n const {\n cesdk,\n input,\n blockIds,\n provider,\n quickAction,\n confirmationComponentId,\n abortSignal\n } = options;\n if (quickAction.confirmation) {\n cesdk.ui.setCanvasMenuOrder([confirmationComponentId], {\n editMode: INFERENCE_AI_EDIT_MODE\n });\n }\n\n const metadata = new Metadata<InferenceMetadata>(\n cesdk.engine,\n INFERENCE_AI_METADATA_KEY\n );\n blockIds.forEach((blockId) => {\n metadata.set(blockId, {\n status: 'processing',\n quickActionId: quickAction.id\n });\n });\n\n const generationOptions: GenerationOptions = {\n cesdk,\n engine: cesdk.engine,\n abortSignal\n };\n\n const composedMiddlewares = composeMiddlewares<I, O>([\n ...(provider.output.middleware ?? []),\n config.debug ? loggingMiddleware() : undefined,\n pendingMiddleware({}),\n ...(quickAction.confirmation\n ? [\n quickAction.lockDuringConfirmation\n ? lockMiddleware<I, O>({\n editMode: INFERENCE_AI_EDIT_MODE\n })\n : editModeMiddleware<I, O>({\n editMode: INFERENCE_AI_EDIT_MODE\n }),\n quickAction.confirmation && highlightBlocksMiddleware<I, O>({})\n ]\n : []),\n config.dryRun\n ? dryRunMiddleware({ kind: provider.kind, blockIds })\n : undefined\n ]);\n\n const { result: generationResult, dispose: generationDispose } =\n await composedMiddlewares(provider.output.generate)(\n input,\n generationOptions\n );\n\n const { consumedGenerationResult, applyCallbacks } =\n await consumeGeneratedResult(generationResult, {\n abortSignal,\n kind: provider.kind,\n blockIds,\n cesdk\n });\n\n if (quickAction.confirmation) {\n blockIds.forEach((blockId) => {\n metadata.set(blockId, {\n status: 'confirmation',\n quickActionId: quickAction.id\n });\n });\n } else {\n applyCallbacks.onApply();\n blockIds.forEach((blockId) => {\n metadata.clear(blockId);\n });\n }\n\n const dispose = () => {\n generationDispose();\n blockIds.forEach((blockId) => {\n metadata.clear(blockId);\n });\n };\n\n abortSignal.addEventListener('abort', dispose);\n\n return {\n dispose,\n returnValue: consumedGenerationResult,\n applyCallbacks\n };\n}\n\nexport default generate;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { InferenceMetadata, QuickActionMenu, ApplyCallbacks } from './types';\nimport {\n getFeatureIdForQuickAction,\n INFERENCE_AI_METADATA_KEY,\n removeDuplicatedSeparators\n} from './utils';\nimport { Metadata } from '@imgly/plugin-utils';\nimport Provider, { Output, OutputKind } from '../provider';\nimport { isAbortError } from '../../utils';\nimport { InitProviderConfiguration } from '../types';\nimport handleGenerationError from '../handleGenerationError';\nimport generate from './generate';\n\nfunction registerQuickActionMenuComponent<\n K extends OutputKind,\n I,\n O extends Output\n>(\n options: {\n cesdk: CreativeEditorSDK;\n quickActionMenu: QuickActionMenu;\n provider: Provider<K, I, O>;\n },\n config: InitProviderConfiguration\n) {\n const { cesdk, quickActionMenu, provider } = options;\n\n const prefix = `ly.img.ai.${quickActionMenu.id}`;\n const confirmationPrefix = `${prefix}.confirmation`;\n cesdk.setTranslations({\n en: {\n [`${confirmationPrefix}.apply`]: 'Apply',\n [`${confirmationPrefix}.before`]: 'Before',\n [`${confirmationPrefix}.after`]: 'After',\n [`${prefix}.cancel`]: 'Cancel',\n [`${prefix}.processing`]: 'Generating...'\n }\n });\n const confirmationComponentId = `${confirmationPrefix}.canvasnMenu`;\n\n const shared: {\n unlock: () => void;\n abort: () => void;\n applyCallbacks: ApplyCallbacks | undefined;\n } = {\n unlock: () => {},\n abort: () => {},\n applyCallbacks: undefined\n };\n\n const createAbortSignal = () => {\n const controller = new AbortController();\n const signal = controller.signal;\n shared.abort = () => {\n controller.abort();\n };\n return signal;\n };\n\n cesdk.ui.registerComponent(\n confirmationComponentId,\n ({ builder, engine, state }) => {\n const blockIds = engine.block.findAllSelected();\n if (blockIds.length === 0) return null;\n\n const md = new Metadata<InferenceMetadata>(\n cesdk.engine,\n INFERENCE_AI_METADATA_KEY\n );\n\n // All blocks must have the same metadata\n const metadata = md.get(blockIds[0]);\n if (metadata == null) return null;\n\n const clearMetadata = () => {\n blockIds.forEach((blockId) => {\n md.clear(blockId);\n });\n };\n\n switch (metadata.status) {\n case 'processing': {\n builder.Button(`${prefix}.spinner`, {\n label: [\n `ly.img.ai.inference.${metadata.quickActionId}.processing`,\n `${prefix}.cancel`\n ],\n isLoading: true\n });\n builder.Separator(`${prefix}.separator`);\n builder.Button(`${prefix}.cancel`, {\n icon: '@imgly/Cross',\n tooltip: `${prefix}.cancel`,\n onClick: () => {\n shared.abort();\n clearMetadata();\n }\n });\n\n break;\n }\n\n case 'confirmation': {\n const comparingState = state<'before' | 'after'>(\n `${confirmationPrefix}.comparing`,\n 'after'\n );\n\n const onCancel = shared.applyCallbacks?.onCancel;\n if (onCancel != null) {\n builder.Button(`${confirmationPrefix}.cancel`, {\n icon: '@imgly/Cross',\n tooltip: `${prefix}.cancel`,\n onClick: () => {\n shared.unlock();\n onCancel();\n clearMetadata();\n }\n });\n }\n\n const onBefore = shared.applyCallbacks?.onBefore;\n const onAfter = shared.applyCallbacks?.onAfter;\n\n if (onBefore != null && onAfter != null) {\n builder.ButtonGroup(`${confirmationPrefix}.compare`, {\n children: () => {\n builder.Button(`${confirmationPrefix}.compare.before`, {\n label: `${confirmationPrefix}.before`,\n variant: 'regular',\n isActive: comparingState.value === 'before',\n onClick: () => {\n onBefore();\n comparingState.setValue('before');\n }\n });\n builder.Button(`${confirmationPrefix}.compare.after`, {\n label: `${confirmationPrefix}.after`,\n variant: 'regular',\n isActive: comparingState.value === 'after',\n onClick: () => {\n onAfter();\n comparingState.setValue('after');\n }\n });\n }\n });\n }\n\n const onApply = shared.applyCallbacks?.onApply;\n if (onApply != null) {\n builder.Button(`${confirmationPrefix}.apply`, {\n icon: '@imgly/Checkmark',\n tooltip: `${confirmationPrefix}.apply`,\n color: 'accent',\n isDisabled: comparingState.value !== 'after',\n onClick: () => {\n shared.unlock();\n clearMetadata();\n\n // Activating the old history happens in the next update lop.\n // @ts-ignore\n cesdk.engine.editor._update();\n\n onApply();\n }\n });\n }\n\n break;\n }\n\n default: {\n // noop\n }\n }\n }\n );\n\n const canvasMenuComponentId = `${prefix}.canvasMenu`;\n cesdk.ui.registerComponent(canvasMenuComponentId, (context) => {\n const blockIds = context.engine.block.findAllSelected();\n const isEveryBlockInReadyState = blockIds.every((blockId) => {\n return context.engine.block.getState(blockId).type === 'Ready';\n });\n\n let quickActions = quickActionMenu\n .getQuickActionMenuOrder()\n .map((quickActionId) => {\n if (quickActionId === 'ly.img.separator') return quickActionId;\n const quickAction = quickActionMenu.getQuickAction<I, O>(quickActionId);\n if (quickAction == null) return null;\n\n const isEnabled = cesdk.feature.isEnabled(\n getFeatureIdForQuickAction({\n quickActionId,\n quickActionMenuId: quickActionMenu.id\n }),\n {\n engine: context.engine\n }\n );\n if (!isEnabled) return null;\n\n const scopes = quickAction.scopes;\n if (scopes != null && scopes.length > 0) {\n const isAllowedByScopes = blockIds.every((blockId) => {\n return scopes.every((scope) => {\n return context.engine.block.isAllowedByScope(blockId, scope);\n });\n });\n if (!isAllowedByScopes) return null;\n }\n return quickAction;\n })\n .filter((entry) => entry != null);\n\n quickActions = removeDuplicatedSeparators(quickActions);\n\n if (\n quickActions.length === 0 ||\n quickActions.every((entry) => entry === 'ly.img.separator')\n ) {\n return null;\n }\n\n const { builder, experimental, state } = context;\n const toggleExpandedState = state<string | undefined>(\n `${prefix}.toggleExpandedState`,\n undefined\n );\n\n experimental.builder.Popover(`${prefix}.popover`, {\n icon: '@imgly/Sparkle',\n variant: 'plain',\n isDisabled: !isEveryBlockInReadyState,\n trailingIcon: null,\n children: ({ close }) => {\n builder.Section(`${prefix}.popover.section`, {\n children: () => {\n if (toggleExpandedState.value != null) {\n const expandStateForQuickActionId = toggleExpandedState.value;\n const quickAction = quickActionMenu.getQuickAction<I, O>(\n expandStateForQuickActionId\n );\n\n if (quickAction != null && quickAction.renderExpanded != null) {\n quickAction.renderExpanded(context, {\n blockIds,\n closeMenu: close,\n toggleExpand: () => {\n toggleExpandedState.setValue(undefined);\n },\n handleGenerationError: (error) => {\n handleGenerationError(\n error,\n {\n cesdk,\n provider\n },\n config\n );\n },\n generate: async (input, generateOptions) => {\n try {\n const { returnValue, applyCallbacks, dispose } =\n await generate(\n {\n input,\n quickAction,\n quickActionMenu,\n provider,\n cesdk,\n abortSignal: createAbortSignal(),\n blockIds: generateOptions?.blockIds ?? blockIds,\n confirmationComponentId\n },\n config\n );\n\n shared.unlock = dispose;\n shared.applyCallbacks = applyCallbacks;\n\n return returnValue;\n } catch (error) {\n if (!isAbortError(error)) {\n handleGenerationError(\n error,\n {\n cesdk,\n provider\n },\n config\n );\n }\n throw error;\n }\n }\n });\n\n return;\n }\n }\n\n experimental.builder.Menu(`${prefix}.menu`, {\n children: () => {\n quickActions.forEach((quickAction) => {\n if (quickAction === 'ly.img.separator') {\n builder.Separator(\n `${prefix}.separator.${Math.random().toString()}`\n );\n } else {\n quickAction.render(context, {\n blockIds,\n closeMenu: close,\n handleGenerationError: (error) => {\n handleGenerationError(\n error,\n {\n cesdk,\n provider\n },\n config\n );\n },\n toggleExpand: () => {\n toggleExpandedState.setValue(quickAction.id);\n },\n generate: async (input, generateOptions) => {\n try {\n const { returnValue, applyCallbacks, dispose } =\n await generate(\n {\n input,\n quickAction,\n quickActionMenu,\n provider,\n cesdk,\n abortSignal: createAbortSignal(),\n blockIds: generateOptions?.blockIds ?? blockIds,\n confirmationComponentId\n },\n config\n );\n\n shared.unlock = dispose;\n shared.applyCallbacks = applyCallbacks;\n return returnValue;\n } catch (error) {\n if (!isAbortError(error)) {\n handleGenerationError(\n error,\n {\n cesdk,\n provider\n },\n config\n );\n }\n throw error;\n }\n }\n });\n }\n });\n }\n });\n }\n });\n }\n });\n });\n\n return { canvasMenuComponentId };\n}\n\nexport default registerQuickActionMenuComponent;\n", "import type Provider from './provider';\nimport {\n OutputKind,\n PanelInput,\n QuickActionsInput,\n type Output\n} from './provider';\nimport registerPanelInputSchema from './registerPanelInputSchema';\nimport registerPanelInputCustom from './registerPanelInputCustom';\nimport { InitProviderConfiguration, Options, UIOptions } from './types';\nimport { BuilderRenderFunction, type CreativeEngine } from '@cesdk/cesdk-js';\nimport { IndexedDBAssetSource } from '@imgly/plugin-utils';\nimport icons from '../icons';\nimport getQuickActionMenu from './quickAction/getQuickActionMenu';\nimport { getFeatureIdForQuickAction } from './quickAction/utils';\nimport registerQuickActionMenuComponent from './quickAction/registerQuickActionMenuComponent';\nimport { QuickActionMenu } from './quickAction/types';\n\ntype RenderBuilderFunctions = {\n panel?: BuilderRenderFunction<any>;\n};\n\n/**\n * Initialize the provider. Based on the given options and configuration\n * it will register panels and components that is used to render\n * the provider in the UI.\n *\n * @param provider The provider to initialize.\n * @param options The options to use for the provider.\n * @param config The configuration to use for the provider.\n */\nasync function initProvider<K extends OutputKind, I, O extends Output>(\n provider: Provider<K, I, O>,\n options: Options,\n config: InitProviderConfiguration\n): Promise<{\n renderBuilderFunctions?: RenderBuilderFunctions;\n}> {\n await provider.initialize?.(options);\n const historyAssetSourceId = await initHistory(\n options.engine,\n provider.id,\n provider.output.history ?? '@imgly/local'\n );\n\n if (options.cesdk == null) {\n return {};\n }\n\n const historyAssetLibraryEntryId = historyAssetSourceId\n ? `${provider.id}.history.entry`\n : undefined;\n const uiOptions: UIOptions = {\n ...options,\n cesdk: options.cesdk,\n historyAssetSourceId,\n historyAssetLibraryEntryId,\n i18n: {\n prompt: 'common.ai-generation.prompt.placeholder'\n }\n };\n\n if (historyAssetLibraryEntryId != null && historyAssetSourceId != null) {\n options.cesdk.ui.addAssetLibraryEntry({\n id: historyAssetLibraryEntryId,\n sourceIds: [historyAssetSourceId],\n sortBy: {\n sortKey: 'insertedAt',\n sortingOrder: 'Descending'\n },\n canRemove: true,\n gridItemHeight: 'square',\n gridBackgroundType: 'cover'\n });\n }\n\n options.cesdk.i18n.setTranslations({\n en: {\n 'common.ai-generation.success': 'Generation Successful',\n 'common.ai-generation.failed': 'Generation Failed',\n 'common.ai-generation.generate': 'Generate',\n 'common.ai-generation.prompt.placeholder':\n 'Describe what you want to create...',\n [`panel.${provider.id}`]: getName(provider)\n }\n });\n\n // Avoid adding the icon set multiple times for different providers\n const globalStateIconSetAddedId = `@imgly/plugin-ai-generation.iconSetAdded`;\n if (\n !options.cesdk.ui.experimental.hasGlobalStateValue(\n globalStateIconSetAddedId\n )\n ) {\n options.cesdk.ui.addIconSet('@imgly/plugin-ai-generation', icons);\n options.cesdk.ui.experimental.setGlobalStateValue(\n globalStateIconSetAddedId,\n true\n );\n }\n\n const renderBuilderFunctions = await initInputs(provider, uiOptions, config);\n\n return {\n renderBuilderFunctions\n };\n}\n\nfunction getName(provider: Provider<any, any, any>): string {\n if (provider.name != null) return provider.name;\n switch (provider.kind) {\n case 'image':\n return 'Generate Image';\n case 'video':\n return 'Generate Video';\n case 'audio':\n return 'Generate Audio';\n default:\n return 'Generate Asset';\n }\n}\n\n/**\n * Initialize the history for the provider.\n */\nasync function initHistory(\n engine: CreativeEngine,\n providerId: string,\n history: undefined | false | '@imgly/local' | '@imgly/indexedDB' | string\n): Promise<string | undefined> {\n if (history == null || history === false) return undefined;\n\n if (history === '@imgly/local') {\n const historyId = `${providerId}.history`;\n engine.asset.addLocalSource(historyId);\n return historyId;\n }\n\n if (history === '@imgly/indexedDB') {\n const historyId = `${providerId}.history`;\n engine.asset.addSource(new IndexedDBAssetSource(historyId, engine));\n return historyId;\n }\n\n return history;\n}\n\nasync function initInputs<K extends OutputKind, I, O extends Output>(\n provider: Provider<K, I, O>,\n options: UIOptions,\n config: InitProviderConfiguration\n): Promise<{\n panel?: BuilderRenderFunction<any>;\n}> {\n const result: {\n panel?: BuilderRenderFunction<any>;\n } = {\n panel: undefined\n };\n\n if (provider.input?.panel != null) {\n result.panel = await initPanel(\n provider,\n provider.input.panel,\n options,\n config\n );\n }\n if (provider.input?.quickActions != null) {\n if (config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n `Initializing quick actions for provider '${provider.kind}' (${provider.id})`\n );\n }\n initQuickActions(provider, provider.input.quickActions, options, config);\n }\n\n return result;\n}\n\nasync function initPanel<K extends OutputKind, I, O extends Output>(\n provider: Provider<K, I, O>,\n panelInput: PanelInput<K, I>,\n options: UIOptions,\n config: InitProviderConfiguration\n): Promise<BuilderRenderFunction<any> | undefined> {\n switch (panelInput.type) {\n case 'custom': {\n return registerPanelInputCustom(provider, panelInput, options, config);\n }\n\n case 'schema': {\n return registerPanelInputSchema(provider, panelInput, options, config);\n }\n\n default: {\n if (config.debug) {\n // eslint-disable-next-line no-console\n console.warn(\n // @ts-ignore\n `Invalid panel input type '${panelInput.type}' - skipping`\n );\n }\n }\n }\n}\n\nasync function initQuickActions<K extends OutputKind, I, O extends Output>(\n provider: Provider<K, I, O>,\n quickActionsInput: QuickActionsInput<I, O>,\n options: UIOptions,\n config: InitProviderConfiguration\n) {\n const { cesdk } = options;\n\n const quickActionMenus: { [kind: string]: QuickActionMenu } = {};\n\n quickActionsInput.actions.forEach((quickAction) => {\n const quickActionMenuId = quickAction.kind ?? provider.kind;\n if (quickActionMenus[quickActionMenuId] == null) {\n quickActionMenus[quickActionMenuId] = getQuickActionMenu(\n cesdk,\n quickActionMenuId\n );\n }\n const quickActionMenu = quickActionMenus[quickActionMenuId];\n\n const enable = quickAction.enable ?? true;\n cesdk.feature.enable(\n getFeatureIdForQuickAction({\n quickActionId: quickAction.id,\n quickActionMenuId\n }),\n enable\n );\n quickActionMenu.registerQuickAction(quickAction);\n if (config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n `Registered quick action: '${quickAction.id}' (v${quickAction.version}) to menu '${quickActionMenuId}'`\n );\n }\n });\n\n Object.values(quickActionMenus).forEach((quickActionMenu) => {\n const { canvasMenuComponentId } = registerQuickActionMenuComponent(\n {\n cesdk,\n quickActionMenu,\n provider\n },\n config\n );\n if (config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n `Registered quick action menu component: ${canvasMenuComponentId}`\n );\n }\n });\n}\n\nexport default initProvider;\n", "import { isAsyncGenerator } from '../../utils';\nimport { GenerationResult, Output } from '../provider';\nimport { Middleware } from './middleware';\n\n/**\n * Middleware to upload the output of a generation process.\n *\n * Sometimes it is not possible to use the result of a provider or\n * not even allowed to use it directly. This middleware allows you to upload\n * the result of a generation process to a server or a cloud storage.\n *\n * @param upload The function to upload the output. It should return a promise\n */\nfunction uploadMiddleware<I, O extends Output>(\n upload: (output: O) => Promise<O>\n) {\n const middleware: Middleware<I, O> = async (input, options, next) => {\n const result: GenerationResult<O> | undefined = await next(input, options);\n if (isAsyncGenerator(result)) {\n // No reupload needed, just return the async generator\n return result;\n }\n\n const uploaded = await upload(result);\n return uploaded;\n };\n\n return middleware;\n}\n\nexport default uploadMiddleware;\n", "import { GenerationOptions, Output } from '../provider';\nimport { Middleware } from './middleware';\n\nexport interface RateLimitOptions<I> {\n /**\n * Maximum number of requests allowed in the time window\n */\n maxRequests: number;\n\n /**\n * Time window in milliseconds\n */\n timeWindowMs: number;\n\n /**\n * Optional key function or string to create different rate limits for different inputs\n * - If not provided, all requests share the same 'global' rate limit\n * - If a string is provided, that string is used as a static key\n * - If a function is provided, it generates a key based on input and options\n */\n keyFn?: string | ((input: I, options: GenerationOptions) => string);\n\n /**\n * Callback function that is called when rate limit is exceeded\n * Return value determines if the operation should be rejected (throw error) or allowed\n * If true is returned, the operation will proceed despite exceeding the rate limit\n * If false or undefined is returned, the operation will be rejected with a default error\n */\n onRateLimitExceeded?: (\n input: I,\n options: GenerationOptions,\n rateLimitInfo: {\n key: string;\n currentCount: number;\n maxRequests: number;\n timeWindowMs: number;\n remainingTimeMs: number;\n }\n ) => boolean | Promise<boolean> | void;\n\n /**\n * Optional database name for the IndexedDB store\n * If not provided, a default name will be used\n */\n dbName?: string;\n\n /**\n * Disable the rate limit middleware\n */\n disable?: boolean | (() => boolean);\n}\n\n// Store for tracking requests per key\ninterface RequestTracker {\n timestamps: number[];\n lastCleanup: number;\n}\n\n// In-memory fallback store for rate limits for environments without IndexedDB\n// Export for testing purposes\n// This is now a Map of middleware instances to their respective stores\n// The key can be either a symbol (for unique instances with prefix) or a string (for shared instances without prefix)\nexport const inMemoryStores: Map<\n symbol | string,\n Record<string, RequestTracker>\n> = new Map();\n\n/**\n * IndexedDB store for rate limiting\n */\nclass RateLimitStore {\n private db: IDBDatabase | null = null;\n\n private readonly dbName: string;\n\n private readonly storeName: string;\n\n private readonly dbVersion: number = 1;\n\n private isInitializing: boolean = false;\n\n private initPromise: Promise<void> | null = null;\n\n private readonly instanceId: symbol | string;\n\n constructor(\n instanceId: symbol | string,\n dbName?: string,\n storeName?: string\n ) {\n this.instanceId = instanceId;\n this.dbName = dbName ?? 'ly.img.ai.rateLimit';\n this.storeName = storeName ?? 'rateLimits';\n }\n\n /**\n * Initialize the database connection\n */\n async initialize(): Promise<void> {\n if (this.db) {\n return;\n }\n\n if (this.isInitializing) {\n return this.initPromise!;\n }\n\n this.isInitializing = true;\n this.initPromise = new Promise<void>((resolve, reject) => {\n try {\n const request = indexedDB.open(this.dbName, this.dbVersion);\n\n request.onerror = (event) => {\n this.isInitializing = false;\n\n // eslint-disable-next-line no-console\n console.error('Failed to open IndexedDB for rate limiting:', event);\n reject(new Error('Failed to open IndexedDB for rate limiting'));\n };\n\n request.onupgradeneeded = (event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n if (!db.objectStoreNames.contains(this.storeName)) {\n db.createObjectStore(this.storeName, { keyPath: 'id' });\n }\n };\n\n request.onsuccess = (event) => {\n this.db = (event.target as IDBOpenDBRequest).result;\n this.isInitializing = false;\n resolve();\n };\n } catch (error) {\n this.isInitializing = false;\n // eslint-disable-next-line no-console\n console.error('Error initializing IndexedDB:', error);\n reject(error);\n }\n });\n\n return this.initPromise;\n }\n\n /**\n * Get a request tracker by key\n */\n async getTracker(key: string): Promise<RequestTracker | null> {\n try {\n await this.initialize();\n\n // Create a combined key that includes the instance ID to ensure isolation\n const instanceIdStr =\n typeof this.instanceId === 'symbol'\n ? this.instanceId.description || ''\n : this.instanceId;\n const combinedKey = `${instanceIdStr}_${key}`;\n\n return await new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.storeName, 'readonly');\n const store = transaction.objectStore(this.storeName);\n const request = store.get(combinedKey);\n\n request.onsuccess = () => {\n if (request.result) {\n resolve(request.result.data);\n } else {\n resolve(null);\n }\n };\n\n request.onerror = () => {\n // eslint-disable-next-line no-console\n console.error(\n `Failed to get tracker for key ${combinedKey}:`,\n request.error\n );\n reject(request.error);\n };\n });\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Error getting tracker from IndexedDB:', error);\n return Promise.reject(error);\n }\n }\n\n /**\n * Save a request tracker by key\n */\n async saveTracker(key: string, tracker: RequestTracker): Promise<void> {\n try {\n await this.initialize();\n\n // Create a combined key that includes the instance ID to ensure isolation\n const instanceIdStr =\n typeof this.instanceId === 'symbol'\n ? this.instanceId.description || ''\n : this.instanceId;\n const combinedKey = `${instanceIdStr}_${key}`;\n\n return await new Promise((resolve, reject) => {\n const transaction = this.db!.transaction(this.storeName, 'readwrite');\n const store = transaction.objectStore(this.storeName);\n store.put({ id: combinedKey, data: tracker });\n\n transaction.oncomplete = () => {\n resolve();\n };\n\n transaction.onerror = () => {\n // eslint-disable-next-line no-console\n console.error(\n `Failed to save tracker for key ${combinedKey}:`,\n transaction.error\n );\n reject(transaction.error);\n };\n });\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Error saving tracker to IndexedDB:', error);\n return Promise.reject(error);\n }\n }\n\n /**\n * Check if IndexedDB is available\n */\n static isAvailable(): boolean {\n return typeof indexedDB !== 'undefined';\n }\n\n /**\n * Close the database connection\n */\n close(): void {\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n }\n}\n\n/**\n * Middleware that implements rate limiting for AI generation requests\n * Uses IndexedDB for storage when available, with in-memory fallback\n * Each middleware instance has its own isolated set of rate limits\n */\nfunction rateLimitMiddleware<I, O extends Output>(\n middlewareOptions: RateLimitOptions<I>\n) {\n const {\n maxRequests,\n timeWindowMs,\n keyFn = () => 'global',\n onRateLimitExceeded,\n dbName\n } = middlewareOptions;\n\n // Create an identifier for this middleware instance based on its configuration\n // This ensures persistence across page reloads and sharing between identical configurations\n const configStr = `rate-limit-middleware-${maxRequests}-${timeWindowMs}`;\n\n // Use a string key for the configuration so identical configurations share the same limits\n const instanceId = configStr;\n\n // Create the store with the instance ID\n const useIndexedDB = RateLimitStore.isAvailable();\n const store = useIndexedDB ? new RateLimitStore(instanceId, dbName) : null;\n\n // Initialize this middleware's in-memory store\n if (!inMemoryStores.has(instanceId)) {\n inMemoryStores.set(instanceId, {});\n }\n // Get this middleware's in-memory store\n const inMemoryStore = inMemoryStores.get(instanceId)!;\n\n const middleware: Middleware<I, O> = async (input, options, next) => {\n if (\n typeof middlewareOptions.disable === 'function'\n ? middlewareOptions.disable()\n : middlewareOptions.disable\n ) {\n return next(input, options);\n }\n // Get rate limit key based on input using the provided keyFn\n // If keyFn is a string, use it directly; otherwise call the function\n const key = typeof keyFn === 'string' ? keyFn : keyFn(input, options);\n const now = Date.now();\n\n let tracker: RequestTracker;\n\n // Get tracker from IndexedDB or create a new one\n if (useIndexedDB && store) {\n try {\n const storedTracker = await store.getTracker(key);\n if (storedTracker) {\n tracker = storedTracker;\n } else {\n tracker = {\n timestamps: [],\n lastCleanup: now\n };\n }\n } catch (error) {\n // Fallback to in-memory store if IndexedDB fails\n // eslint-disable-next-line no-console\n console.error(\n 'IndexedDB access failed, using in-memory fallback:',\n error\n );\n if (!inMemoryStore[key]) {\n inMemoryStore[key] = {\n timestamps: [],\n lastCleanup: now\n };\n }\n tracker = inMemoryStore[key];\n }\n } else {\n // Use in-memory store if IndexedDB is not available\n if (!inMemoryStore[key]) {\n inMemoryStore[key] = {\n timestamps: [],\n lastCleanup: now\n };\n }\n tracker = inMemoryStore[key];\n }\n\n // Clean up old timestamps that are outside the time window\n if (now - tracker.lastCleanup > timeWindowMs) {\n tracker.timestamps = tracker.timestamps.filter(\n (timestamp) => now - timestamp < timeWindowMs\n );\n tracker.lastCleanup = now;\n }\n\n // Check if rate limit is exceeded\n if (tracker.timestamps.length >= maxRequests) {\n // Calculate the time until the oldest request expires\n const oldestTimestamp = Math.min(...tracker.timestamps);\n const remainingTimeMs = Math.max(\n 0,\n timeWindowMs - (now - oldestTimestamp)\n );\n\n // Call the rate limit exceeded callback if provided\n if (onRateLimitExceeded) {\n const rateLimitInfo = {\n key, // This is the baseKey from keyFn\n currentCount: tracker.timestamps.length,\n maxRequests,\n timeWindowMs,\n remainingTimeMs\n };\n\n // If callback returns true, allow the request to proceed\n const shouldProceed = await onRateLimitExceeded(\n input,\n options,\n rateLimitInfo\n );\n if (!shouldProceed) {\n // The callback should indicate the error, so we throw\n // an abort error instead of a generic error to indicate\n // the generation was aborted and we do not show any further\n // error notification.\n throw new DOMException(\n 'Operation aborted: Rate limit exceeded',\n 'AbortError'\n );\n }\n } else {\n // Default behavior: throw an error\n throw new Error('Rate limit exceeded. Please try again later.');\n }\n }\n\n // Add current timestamp to the tracker\n tracker.timestamps.push(now);\n\n // Save the updated tracker\n if (useIndexedDB && store) {\n try {\n await store.saveTracker(key, tracker);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to save tracker to IndexedDB:', error);\n // In case of IndexedDB failure, update the in-memory store as fallback\n inMemoryStore[key] = tracker;\n }\n } else {\n inMemoryStore[key] = tracker;\n }\n\n // Continue with the next middleware\n return next(input, options);\n };\n\n return middleware;\n}\n\nexport default rateLimitMiddleware;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\n\n/**\n * Registers a dock component for AI generation that opens\n * the AI generation panel and closes any other AI panels.\n */\nfunction registerDockComponent(options: {\n cesdk: CreativeEditorSDK;\n panelId: string;\n}) {\n const { cesdk, panelId } = options;\n if (panelId.startsWith('ly.img.ai/')) {\n // eslint-disable-next-line no-console\n console.warn(\n `Dock components for AI generation should open a panel with an id starting with \"ly.img.ai/\" \u2013 \"${panelId}\" was provided.`\n );\n }\n\n const dockComponentId = `${panelId}.dock`;\n cesdk.ui.registerComponent(dockComponentId, ({ builder }) => {\n const isOpen = cesdk.ui.isPanelOpen(panelId);\n\n builder.Button(`${panelId}.dock.button`, {\n label: `${panelId}.dock.label`,\n isSelected: isOpen,\n icon: '@imgly/Sparkle',\n onClick: () => {\n cesdk.ui.findAllPanels().forEach((panel) => {\n if (panel.startsWith('ly.img.ai/')) {\n cesdk.ui.closePanel(panel);\n }\n if (!isOpen && panel === '//ly.img.panel/assetLibrary') {\n cesdk.ui.closePanel(panel);\n }\n });\n\n if (!isOpen) {\n cesdk.ui.openPanel(panelId);\n } else {\n cesdk.ui.closePanel(panelId);\n }\n }\n });\n });\n}\n\nexport default registerDockComponent;\n", "import { ButtonOptions, TextAreaOptions } from '@cesdk/cesdk-js';\nimport { Output, QuickAction, QuickActionContext } from '../../provider';\n\n/**\n * Quick action base for quick actions that require a prompt.\n * Will render a text area for the prompt.\n */\nfunction QuickActionBasePrompt<I, O extends Output>(options: {\n buttonOptions?: ButtonOptions;\n textAreaOptions?: TextAreaOptions;\n quickAction: Omit<QuickAction<I, O>, 'render' | 'renderExpanded'>;\n onApply: (prompt: string, context: QuickActionContext<I, O>) => Promise<O>;\n}): QuickAction<I, O> {\n const id = options.quickAction.id;\n return {\n confirmation: true,\n lockDuringConfirmation: false,\n ...options.quickAction,\n render: ({ builder }, { toggleExpand }) => {\n builder.Button(`${id}.button`, {\n label: `ly.img.ai.quickAction.${id}`,\n icon: '@imgly/Sparkle',\n labelAlignment: 'left',\n variant: 'plain',\n ...options.buttonOptions,\n onClick: toggleExpand\n });\n },\n renderExpanded: ({ builder, state, experimental }, context) => {\n const promptState = state(`${id}.prompt`, '');\n\n builder.TextArea(`${id}.textarea`, {\n inputLabel: `ly.img.ai.quickAction.${id}.prompt.inputLabel`,\n placeholder: `ly.img.ai.quickAction.${id}.prompt.placeholder`,\n ...options.textAreaOptions,\n ...promptState\n });\n\n builder.Separator(`${id}.separator`);\n\n experimental.builder.ButtonRow(`${id}.footer`, {\n justifyContent: 'space-between',\n children: () => {\n builder.Button(`${id}.footer.cancel`, {\n label: 'common.back',\n icon: '@imgly/ChevronLeft',\n onClick: context.toggleExpand\n });\n\n builder.Button(`${id}.footer.apply`, {\n label: `ly.img.ai.quickAction.${id}.apply`,\n icon: '@imgly/MagicWand',\n color: 'accent',\n isDisabled: promptState.value.length === 0,\n onClick: async () => {\n try {\n const prompt = promptState.value;\n if (!prompt) return;\n\n options.onApply(prompt, context);\n context.toggleExpand();\n context.closeMenu();\n } catch (error) {\n context.handleGenerationError(error);\n }\n }\n });\n }\n });\n }\n };\n}\n\nexport default QuickActionBasePrompt;\n", "import { ButtonOptions } from '@cesdk/cesdk-js';\nimport { Output, QuickAction, QuickActionContext } from '../../provider';\n\n/**\n * Quick action base for quick actions to open a panel.\n */\nfunction QuickActionBaseButton<I, O extends Output>(options: {\n buttonOptions?: ButtonOptions;\n quickAction: Omit<QuickAction<I, O>, 'render' | 'renderExpanded'>;\n\n onClick: (context: QuickActionContext<I, O>) => Promise<void>;\n}): QuickAction<I, O> {\n const id = options.quickAction.id;\n return {\n confirmation: true,\n lockDuringConfirmation: false,\n ...options.quickAction,\n render: ({ builder }, context) => {\n builder.Button(`${id}.button`, {\n label: `ly.img.ai.quickAction.${id}`,\n icon: '@imgly/Sparkle',\n labelAlignment: 'left',\n variant: 'plain',\n ...options.buttonOptions,\n onClick: async () => {\n try {\n options.onClick(context);\n context.closeMenu();\n } catch (error) {\n context.handleGenerationError(error);\n }\n }\n });\n }\n };\n}\n\nexport default QuickActionBaseButton;\n", "import CreativeEditorSDK, { ButtonOptions } from '@cesdk/cesdk-js';\nimport { Output, QuickAction, QuickActionContext } from '../../provider';\nimport { getImageUri } from '@imgly/plugin-utils';\n\ninterface QuickActionBaseSelectItem {\n id: string;\n label: string;\n icon?: string;\n prompt: string;\n}\n\n/**\n * Quick action base for quick actions that require a selection of items.\n */\nfunction QuickActionBaseSelect<I, O extends Output>(options: {\n cesdk: CreativeEditorSDK;\n items: QuickActionBaseSelectItem[];\n buttonOptions?: ButtonOptions;\n quickAction: Omit<QuickAction<I, O>, 'render' | 'renderExpanded'>;\n mapInput?: (input: {\n item: QuickActionBaseSelectItem;\n uri: string;\n blockId: number;\n }) => I;\n onApply?: (\n options: { item: QuickActionBaseSelectItem; uri: string; blockId: number },\n context: QuickActionContext<I, O>\n ) => Promise<O>;\n}): QuickAction<I, O> {\n const id = options.quickAction.id;\n\n if (options.mapInput == null && options.onApply == null) {\n throw new Error(\n `QuickAction '${id}': Either mapInput or onApply must be provided to QuickActionChangeImage`\n );\n }\n\n if (options.mapInput != null && options.onApply != null) {\n throw new Error(\n `QuickAction '${id}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`\n );\n }\n\n return {\n ...options.quickAction,\n render: ({ builder, experimental }, context) => {\n experimental.builder.Popover(`${id}.popover`, {\n label: `ly.img.ai.quickAction.${id}`,\n icon: '@imgly/Appearance',\n labelAlignment: 'left',\n variant: 'plain',\n trailingIcon: '@imgly/ChevronRight',\n placement: 'right',\n ...options.buttonOptions,\n children: () => {\n builder.Section(`${id}.popover.section`, {\n children: () => {\n experimental.builder.Menu(`${id}.popover.menu`, {\n children: () => {\n options.items.forEach((item) => {\n builder.Button(`${id}.popover.menu.${item.id}`, {\n label: item.label,\n labelAlignment: 'left',\n variant: 'plain',\n icon: item.icon,\n onClick: async () => {\n const { generate, closeMenu, handleGenerationError } =\n context;\n try {\n closeMenu();\n const [blockId] =\n options.cesdk.engine.block.findAllSelected();\n const uri = await getImageUri(\n blockId,\n options.cesdk.engine,\n {\n throwErrorIfSvg: true\n }\n );\n\n if (options.mapInput) {\n const input = options.mapInput({\n item,\n uri,\n blockId\n });\n return await generate(input);\n } else if (options.onApply) {\n return await options.onApply(\n {\n item,\n uri,\n blockId\n },\n context\n );\n } else {\n throw new Error(\n 'Please provide either mapInput or onApply'\n );\n }\n } catch (error) {\n handleGenerationError(error);\n }\n }\n });\n });\n }\n });\n }\n });\n }\n });\n }\n };\n}\n\nexport default QuickActionBaseSelect;\n", "import CreativeEditorSDK, { AssetResult, ButtonOptions } from '@cesdk/cesdk-js';\nimport { Output, QuickAction, QuickActionContext } from '../../provider';\nimport { getImageUri } from '@imgly/plugin-utils';\n\n/**\n * Quick action base for quick actions that require a selection of items\n * from a library.\n */\nfunction QuickActionBaseLibrary<I, O extends Output>(options: {\n cesdk: CreativeEditorSDK;\n entries: string[];\n buttonOptions?: ButtonOptions;\n quickAction: Omit<QuickAction<I, O>, 'render' | 'renderExpanded'>;\n mapInput?: (input: {\n assetResult: AssetResult;\n uri: string;\n blockId: number;\n }) => I;\n onApply?: (\n options: { assetResult: AssetResult; uri: string; blockId: number },\n context: QuickActionContext<I, O>\n ) => Promise<O>;\n}): QuickAction<I, O> {\n const id = options.quickAction.id;\n\n if (options.mapInput == null && options.onApply == null) {\n throw new Error(\n `QuickAction '${id}': Either mapInput or onApply must be provided to QuickActionChangeImage`\n );\n }\n\n if (options.mapInput != null && options.onApply != null) {\n throw new Error(\n `QuickAction '${id}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`\n );\n }\n\n return {\n ...options.quickAction,\n render: ({ builder, experimental }, context) => {\n experimental.builder.Popover(`${id}.popover`, {\n label: `ly.img.ai.quickAction.${id}`,\n icon: '@imgly/Appearance',\n labelAlignment: 'left',\n variant: 'plain',\n trailingIcon: '@imgly/ChevronRight',\n placement: 'right',\n ...options.buttonOptions,\n children: () => {\n builder.Library(`${id}.popover.library`, {\n entries: options.entries,\n onSelect: async (assetResult) => {\n const { generate, closeMenu, handleGenerationError } = context;\n try {\n closeMenu();\n const [blockId] = options.cesdk.engine.block.findAllSelected();\n const uri = await getImageUri(blockId, options.cesdk.engine, {\n throwErrorIfSvg: true\n });\n\n if (options.mapInput) {\n const input = options.mapInput({\n assetResult,\n uri,\n blockId\n });\n await generate(input);\n } else if (options.onApply) {\n await options.onApply(\n {\n assetResult,\n uri,\n blockId\n },\n context\n );\n } else {\n throw new Error('Please provide either mapInput or onApply');\n }\n } catch (error) {\n handleGenerationError(error);\n }\n }\n });\n }\n });\n }\n };\n}\n\nexport default QuickActionBaseLibrary;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { ImageOutput, QuickAction, QuickActionContext } from '../../provider';\nimport QuickActionBasePrompt from './QuickActionBasePrompt';\nimport { getImageUri } from '@imgly/plugin-utils';\n\nfunction QuickActionEditTextStyle<I, O extends ImageOutput>(options: {\n id?: string;\n cesdk: CreativeEditorSDK;\n mapInput?: (input: {\n prompt: string;\n uri: string;\n duplicatedBlockId: number;\n }) => I;\n onApply?: (\n options: { prompt: string; uri: string; duplicatedBlockId: number },\n context: QuickActionContext<I, O>\n ) => Promise<O>;\n}): QuickAction<I, O> {\n const id = options.id ?? 'changeToImage';\n\n if (options.mapInput == null && options.onApply == null) {\n throw new Error(\n `QuickAction '${id}': Either mapInput or onApply must be provided to QuickActionChangeImage`\n );\n }\n\n if (options.mapInput != null && options.onApply != null) {\n throw new Error(\n `QuickAction '${id}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`\n );\n }\n\n options.cesdk.i18n.setTranslations({\n en: {\n [`ly.img.ai.quickAction.${id}.apply`]: 'Change',\n [`ly.img.ai.quickAction.${id}`]: 'Change Text Style...',\n [`ly.img.ai.quickAction.${id}.prompt.inputLabel`]: 'Change Text Style...',\n [`ly.img.ai.quickAction.${id}.prompt.placeholder`]:\n 'e.g. add a 3d texture with wires...'\n }\n });\n\n return QuickActionBasePrompt<I, O>({\n buttonOptions: {\n icon: '@imgly/plugin-ai-generation/image'\n },\n quickAction: {\n kind: 'text',\n id,\n version: '1',\n confirmation: false,\n // scopes: ['fill/change'],\n enable: ({ engine }) => {\n const blockIds = engine.block.findAllSelected();\n if (blockIds == null || blockIds.length !== 1) return false;\n const [blockId] = blockIds;\n return engine.block.getType(blockId) === '//ly.img.ubq/text';\n }\n },\n onApply: async (prompt, context) => {\n const [blockId] = options.cesdk.engine.block.findAllSelected();\n const parentBlockId = options.cesdk.engine.block.getParent(blockId);\n if (parentBlockId == null) {\n throw new Error('Parent block not found');\n }\n\n const rasterized = await options.cesdk.engine.block.export(blockId);\n const rasterizedUri = URL.createObjectURL(rasterized);\n\n const width = options.cesdk.engine.block.getFrameWidth(blockId);\n const height = options.cesdk.engine.block.getFrameHeight(blockId);\n const positionX = options.cesdk.engine.block.getPositionX(blockId);\n const positionY = options.cesdk.engine.block.getPositionY(blockId);\n\n const shape = options.cesdk.engine.block.createShape('rect');\n const rasterizedBlock = options.cesdk.engine.block.create('graphic');\n options.cesdk.engine.block.setShape(rasterizedBlock, shape);\n options.cesdk.engine.block.appendChild(parentBlockId, rasterizedBlock);\n options.cesdk.engine.block.setWidth(rasterizedBlock, width);\n options.cesdk.engine.block.setHeight(rasterizedBlock, height);\n options.cesdk.engine.block.setPositionX(rasterizedBlock, positionX);\n options.cesdk.engine.block.setPositionY(rasterizedBlock, positionY);\n const fillBlock = options.cesdk.engine.block.createFill('image');\n\n options.cesdk.engine.block.setString(\n fillBlock,\n 'fill/image/imageFileURI',\n rasterizedUri\n );\n\n options.cesdk.engine.block.setFill(rasterizedBlock, fillBlock);\n\n options.cesdk.engine.block.destroy(blockId);\n options.cesdk.engine.block.setSelected(rasterizedBlock, true);\n\n const uri = await getImageUri(rasterizedBlock, options.cesdk.engine, {\n throwErrorIfSvg: true\n });\n\n if (options.mapInput) {\n const input = options.mapInput({\n prompt,\n uri,\n duplicatedBlockId: rasterizedBlock\n });\n return context.generate(input);\n } else if (options.onApply) {\n return options.onApply(\n {\n prompt,\n uri,\n duplicatedBlockId: rasterizedBlock\n },\n context\n );\n } else {\n throw new Error('Please provide either mapInput or onApply');\n }\n }\n });\n}\n\nexport default QuickActionEditTextStyle;\n", "import type CreativeEngine from '@cesdk/engine';\n\n/**\n * Enable function for a single image fill block selected.\n */\nfunction enableImageFill() {\n return ({ engine }: { engine: CreativeEngine }) => {\n const blockIds = engine.block.findAllSelected();\n if (blockIds == null || blockIds.length !== 1) return false;\n\n const [blockId] = blockIds;\n\n if (!engine.block.supportsFill(blockId)) return false;\n\n if (\n !['//ly.img.ubq/graphic', '//ly.img.ubq/page'].includes(\n engine.block.getType(blockId)\n )\n ) {\n return false;\n }\n\n const fillBlock = engine.block.getFill(blockId);\n return engine.block.getType(fillBlock) === '//ly.img.ubq/fill/image';\n };\n}\n\nexport default enableImageFill;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { ImageOutput, QuickAction, QuickActionContext } from '../../provider';\nimport QuickActionBasePrompt from './QuickActionBasePrompt';\nimport enableImageFill from './enableImageFill';\nimport { getImageUri } from '@imgly/plugin-utils';\n\nfunction QuickActionChangeImage<I, O extends ImageOutput>(options: {\n id?: string;\n cesdk: CreativeEditorSDK;\n mapInput?: (input: { prompt: string; uri: string; blockId: number }) => I;\n onApply?: (\n options: { prompt: string; uri: string; blockId: number },\n context: QuickActionContext<I, O>\n ) => Promise<O>;\n}): QuickAction<I, O> {\n const id = options.id ?? 'changeImage';\n\n if (options.mapInput == null && options.onApply == null) {\n throw new Error(\n `QuickAction '${id}': Either mapInput or onApply must be provided to QuickActionChangeImage`\n );\n }\n\n if (options.mapInput != null && options.onApply != null) {\n throw new Error(\n `QuickAction '${id}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`\n );\n }\n\n options.cesdk.i18n.setTranslations({\n en: {\n [`ly.img.ai.quickAction.${id}.apply`]: 'Change',\n [`ly.img.ai.quickAction.${id}`]: 'Edit Image...',\n [`ly.img.ai.quickAction.${id}.prompt.inputLabel`]: 'Change image...',\n [`ly.img.ai.quickAction.${id}.prompt.placeholder`]:\n 'Describe what you want to change...'\n }\n });\n\n return QuickActionBasePrompt<I, O>({\n buttonOptions: {\n icon: '@imgly/plugin-ai-generation/image'\n },\n quickAction: {\n id,\n version: '1',\n confirmation: true,\n lockDuringConfirmation: false,\n scopes: ['fill/change'],\n enable: enableImageFill()\n },\n onApply: async (prompt, context) => {\n const [blockId] = options.cesdk.engine.block.findAllSelected();\n const uri = await getImageUri(blockId, options.cesdk.engine, {\n throwErrorIfSvg: true\n });\n\n if (options.mapInput) {\n const input = options.mapInput({ prompt, uri, blockId });\n return context.generate(input);\n } else if (options.onApply) {\n return options.onApply(\n {\n prompt,\n uri,\n blockId\n },\n context\n );\n } else {\n throw new Error('Please provide either mapInput or onApply');\n }\n }\n });\n}\n\nexport default QuickActionChangeImage;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { ImageOutput, QuickAction, QuickActionContext } from '../../provider';\nimport QuickActionBasePrompt from './QuickActionBasePrompt';\nimport enableImageFill from './enableImageFill';\nimport { getImageUri } from '@imgly/plugin-utils';\n\nfunction QuickActionImageVariant<I, O extends ImageOutput>(options: {\n id?: string;\n mapInput?: (input: {\n prompt: string;\n uri: string;\n duplicatedBlockId: number;\n }) => I;\n onApply?: (\n options: { prompt: string; uri: string; duplicatedBlockId: number },\n context: QuickActionContext<I, O>\n ) => Promise<O>;\n cesdk: CreativeEditorSDK;\n}): QuickAction<I, O> {\n const id = options.id ?? 'createVariant';\n\n if (options.mapInput == null && options.onApply == null) {\n throw new Error(\n `QuickAction '${id}': Either mapInput or onApply must be provided to QuickActionChangeImage`\n );\n }\n\n if (options.mapInput != null && options.onApply != null) {\n throw new Error(\n `QuickAction '${id}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`\n );\n }\n\n options.cesdk.i18n.setTranslations({\n en: {\n [`ly.img.ai.quickAction.${id}.apply`]: 'Create',\n [`ly.img.ai.quickAction.${id}`]: 'Create Variant...',\n [`ly.img.ai.quickAction.${id}.prompt.inputLabel`]:\n 'Describe Your Variant...',\n [`ly.img.ai.quickAction.${id}.prompt.placeholder`]:\n 'e.g., same character with arms raised'\n }\n });\n\n return QuickActionBasePrompt<I, O>({\n buttonOptions: {\n icon: '@imgly/ImageVariation'\n },\n quickAction: {\n id,\n version: '1',\n confirmation: false,\n lockDuringConfirmation: false,\n scopes: ['lifecycle/duplicate', 'fill/change'],\n enable: (context) => {\n if (!enableImageFill()(context)) return false;\n\n const [blockId] = context.engine.block.findAllSelected();\n if (\n !options.cesdk.feature.isEnabled('ly.img.duplicate', {\n engine: context.engine\n })\n ) {\n return false;\n }\n if (\n !context.engine.block.isAllowedByScope(blockId, 'lifecycle/duplicate')\n ) {\n return false;\n }\n\n return true;\n }\n },\n onApply: async (prompt, context) => {\n const engine = options.cesdk.engine;\n const [blockId] = engine.block.findAllSelected();\n const type = engine.block.getType(blockId);\n\n // Duplicate the selected block\n const duplicated = engine.block.duplicate(blockId);\n if (type === '//ly.img.ubq/page') {\n engine.block.getChildren(duplicated).forEach((childId) => {\n engine.block.destroy(childId);\n });\n }\n engine.block.setSelected(blockId, false);\n engine.block.setSelected(duplicated, true);\n\n const parent = engine.block.getParent(duplicated);\n if (parent == null) throw new Error('Parent not found');\n\n const isBackgroundClip =\n parent != null &&\n engine.block.getType(parent) === '//ly.img.ubq/track' &&\n engine.block.isPageDurationSource(parent);\n\n // Offset the duplicated block unless it is a background track\n if (!isBackgroundClip && type !== '//ly.img.ubq/page') {\n const offsetFactor = 1.0;\n const parentWidth = engine.block.getWidth(parent);\n const parentHeight = engine.block.getHeight(parent);\n const offset =\n 0.02 * Math.min(parentWidth, parentHeight) * offsetFactor;\n\n engine.block.setPositionX(\n duplicated,\n engine.block.getPositionX(duplicated) + offset\n );\n engine.block.setPositionY(\n duplicated,\n engine.block.getPositionY(duplicated) + offset\n );\n }\n\n // Get the source of the duplicated block\n const uri = await getImageUri(duplicated, options.cesdk.engine, {\n throwErrorIfSvg: true\n });\n\n if (options.mapInput) {\n const input = options.mapInput({\n prompt,\n uri,\n duplicatedBlockId: duplicated\n });\n return context.generate(input);\n } else if (options.onApply) {\n return options.onApply(\n {\n prompt,\n uri,\n duplicatedBlockId: duplicated\n },\n context\n );\n } else {\n throw new Error('Please provide either mapInput or onApply');\n }\n }\n });\n}\n\nexport default QuickActionImageVariant;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { ImageOutput, QuickAction, QuickActionContext } from '../../provider';\nimport QuickActionBasePrompt from './QuickActionBasePrompt';\nimport { getImageUri } from '@imgly/plugin-utils';\n\nfunction QuickActionCombineImages<I, O extends ImageOutput>(options: {\n id?: string;\n mapInput?: (input: {\n prompt: string;\n uris: string[];\n duplicatedBlockId: number;\n }) => I;\n onApply?: (\n options: { prompt: string; uris: string[]; duplicatedBlockId: number },\n context: QuickActionContext<I, O>\n ) => Promise<O>;\n cesdk: CreativeEditorSDK;\n}): QuickAction<I, O> {\n const id = options.id ?? 'combineImages';\n\n if (options.mapInput == null && options.onApply == null) {\n throw new Error(\n `QuickAction '${id}': Either mapInput or onApply must be provided to QuickActionChangeImage`\n );\n }\n\n if (options.mapInput != null && options.onApply != null) {\n throw new Error(\n `QuickAction '${id}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`\n );\n }\n\n options.cesdk.i18n.setTranslations({\n en: {\n [`ly.img.ai.quickAction.${id}.apply`]: 'Combine',\n [`ly.img.ai.quickAction.${id}`]: 'Combine Images...',\n [`ly.img.ai.quickAction.${id}.prompt.inputLabel`]:\n 'Image Combination Instructions',\n [`ly.img.ai.quickAction.${id}.prompt.placeholder`]:\n 'e.g., add character to the left of the mountain scene'\n }\n });\n\n return QuickActionBasePrompt<I, O>({\n buttonOptions: {\n icon: '@imgly/ImageVariation'\n },\n quickAction: {\n id,\n version: '1',\n confirmation: false,\n lockDuringConfirmation: false,\n scopes: ['lifecycle/duplicate', 'fill/change'],\n enable: (context) => {\n const blockIds = context.engine.block.findAllSelected();\n\n if (blockIds == null || blockIds.length < 2) return false;\n\n return blockIds.every((blockId) => {\n if (\n context.engine.block.getType(blockId) !== '//ly.img.ubq/graphic' &&\n !context.engine.block.supportsFill(blockId)\n ) {\n return false;\n }\n\n const fillBlock = context.engine.block.getFill(blockId);\n if (\n context.engine.block.getType(fillBlock) !==\n '//ly.img.ubq/fill/image'\n ) {\n return false;\n }\n\n if (\n !options.cesdk.feature.isEnabled('ly.img.duplicate', {\n engine: context.engine\n })\n ) {\n return false;\n }\n if (\n !context.engine.block.isAllowedByScope(\n blockId,\n 'lifecycle/duplicate'\n )\n ) {\n return false;\n }\n\n const parent = context.engine.block.getParent(blockId);\n const isBackgroundClip =\n parent != null &&\n context.engine.block.getType(parent) === '//ly.img.ubq/track' &&\n context.engine.block.isPageDurationSource(parent);\n\n if (isBackgroundClip) {\n return false;\n }\n\n const blockType = context.engine.block.getType(blockId);\n if (blockType === '//ly.img.ubq/page') return false;\n return true;\n });\n }\n },\n onApply: async (prompt, context) => {\n const engine = options.cesdk.engine;\n const blockIds = engine.block.findAllSelected();\n\n // Duplicate the selected block\n const duplicated = engine.block.duplicate(blockIds[0]);\n blockIds.forEach((blockId) => {\n engine.block.setSelected(blockId, false);\n });\n engine.block.setSelected(duplicated, true);\n\n // Offset the duplicated block\n const parent = engine.block.getParent(duplicated);\n if (parent == null) throw new Error('Parent not found');\n\n const offsetFactor = 1.0;\n const parentWidth = engine.block.getWidth(parent);\n const parentHeight = engine.block.getHeight(parent);\n const offset = 0.02 * Math.min(parentWidth, parentHeight) * offsetFactor;\n\n engine.block.setPositionX(\n duplicated,\n engine.block.getPositionX(duplicated) + offset\n );\n engine.block.setPositionY(\n duplicated,\n engine.block.getPositionY(duplicated) + offset\n );\n\n const uris = await Promise.all(\n blockIds.map((blockId) =>\n getImageUri(blockId, options.cesdk.engine, {\n throwErrorIfSvg: true\n })\n )\n );\n\n if (options.mapInput) {\n const input = options.mapInput({\n prompt,\n uris,\n duplicatedBlockId: duplicated\n });\n return context.generate(input);\n } else if (options.onApply) {\n return options.onApply(\n {\n prompt,\n uris,\n duplicatedBlockId: duplicated\n },\n context\n );\n } else {\n throw new Error('Please provide either mapInput or onApply');\n }\n }\n });\n}\n\nexport default QuickActionCombineImages;\n", "import CreativeEditorSDK from '@cesdk/cesdk-js';\nimport { ImageOutput, QuickAction, QuickActionContext } from '../../provider';\nimport { getImageUri } from '@imgly/plugin-utils';\nimport QuickActionBasePrompt from './QuickActionBasePrompt';\nimport enableImageFill from './enableImageFill';\n\nfunction QuickActionChangeImage<I, O extends ImageOutput>(options: {\n id?: string;\n mapInput?: (input: { prompt: string; uri: string; blockId: number }) => I;\n onApply?: (\n options: { prompt: string; uri: string; blockId: number },\n context: QuickActionContext<I, O>\n ) => Promise<O>;\n cesdk: CreativeEditorSDK;\n}): QuickAction<I, O> {\n const id = options.id ?? 'swapBackground';\n\n if (options.mapInput == null && options.onApply == null) {\n throw new Error(\n `QuickAction '${id}': Either mapInput or onApply must be provided to QuickActionChangeImage`\n );\n }\n\n if (options.mapInput != null && options.onApply != null) {\n throw new Error(\n `QuickAction '${id}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`\n );\n }\n\n options.cesdk.i18n.setTranslations({\n en: {\n [`ly.img.ai.quickAction.${id}.apply`]: 'Change',\n [`ly.img.ai.quickAction.${id}`]: 'Change Background...',\n [`ly.img.ai.quickAction.${id}.prompt.inputLabel`]: 'Change background...',\n [`ly.img.ai.quickAction.${id}.prompt.placeholder`]:\n 'Describe the background you want...'\n }\n });\n\n return QuickActionBasePrompt<I, O>({\n buttonOptions: {\n icon: '@imgly/plugin-ai-generation/image'\n },\n quickAction: {\n id,\n version: '1',\n confirmation: true,\n lockDuringConfirmation: false,\n scopes: ['fill/change'],\n enable: enableImageFill()\n },\n onApply: async (userPrompt, context) => {\n const [blockId] = options.cesdk.engine.block.findAllSelected();\n const uri = await getImageUri(blockId, options.cesdk.engine, {\n throwErrorIfSvg: true\n });\n\n const prompt = `Swap the background to ${userPrompt}`;\n if (options.mapInput) {\n const input = options.mapInput({ prompt, uri, blockId });\n return context.generate(input);\n } else if (options.onApply) {\n return options.onApply(\n {\n prompt,\n uri,\n blockId\n },\n context\n );\n } else {\n throw new Error('Please provide either mapInput or onApply');\n }\n }\n });\n}\n\nexport default QuickActionChangeImage;\n", "import renderImageUrlProperty from './common/renderImageUrlProperty';\n\nconst CommonProperties = {\n ImageUrl: renderImageUrlProperty\n};\n\nexport { CommonProperties };\n\nexport {\n type default as Provider,\n type ImageOutput,\n type VideoOutput,\n type TextOutput,\n type AudioOutput,\n type Output,\n type OutputKind,\n type PanelInputSchema,\n type RenderCustomProperty,\n type GetBlockInput,\n type GetBlockInputResult,\n type GetInput,\n type QuickAction,\n type QuickActionsInput\n} from './generation/provider';\nexport {\n type GetPropertyInput,\n type Property\n} from './generation/openapi/types';\nexport { default as initProvider } from './generation/initProvider';\nexport { type GenerationMiddleware } from './generation/types';\n\n// Export middleware\nexport {\n composeMiddlewares,\n type Middleware\n} from './generation/middleware/middleware';\nexport { default as loggingMiddleware } from './generation/middleware/loggingMiddleware';\nexport { default as uploadMiddleware } from './generation/middleware/uploadMiddleware';\nexport {\n default as rateLimitMiddleware,\n type RateLimitOptions\n} from './generation/middleware/rateLimitMiddleware';\n\nexport {\n getPanelId,\n getDurationForVideo,\n getThumbnailForVideo,\n getLabelFromId\n} from './utils';\n\nexport { default as registerDockComponent } from './registerDockComponent';\n\nexport { default as getQuickActionMenu } from './generation/quickAction/getQuickActionMenu';\nexport { default as registerQuickActionMenuComponent } from './generation/quickAction/registerQuickActionMenuComponent';\n\nexport { default as QuickActionBasePrompt } from './generation/quickAction/common/QuickActionBasePrompt';\nexport { default as QuickActionBaseButton } from './generation/quickAction/common/QuickActionBaseButton';\nexport { default as QuickActionBaseSelect } from './generation/quickAction/common/QuickActionBaseSelect';\nexport { default as QuickActionBaseLibrary } from './generation/quickAction/common/QuickActionBaseLibrary';\n\nexport { default as QuickActionEditTextStyle } from './generation/quickAction/common/QuickActionEditTextStyle';\nexport { default as QuickActionChangeImage } from './generation/quickAction/common/QuickActionChangeImage';\nexport { default as QuickActionImageVariant } from './generation/quickAction/common/QuickActionImageVariant';\nexport { default as QuickActionCombineImages } from './generation/quickAction/common/QuickActionCombineImages';\nexport { default as QuickActionSwapImageBackground } from './generation/quickAction/common/QuickActionSwapImageBackground';\n\nexport { default as enableQuickActionForImageFill } from './generation/quickAction/common/enableImageFill';\n\nexport {\n isGeneratingStateKey,\n abortGenerationStateKey\n} from './generation/renderGenerationComponents';\n", "{\n \"openapi\": \"3.0.0\",\n \"info\": {\n \"title\": \"Fal Queue API\",\n \"version\": \"1.0.0\",\n \"description\": \"The Fal Queue API.\"\n },\n \"components\": {\n \"securitySchemes\": {\n \"apiKeyAuth\": {\n \"type\": \"apiKey\",\n \"in\": \"header\",\n \"name\": \"Authorization\",\n \"description\": \"Fal Key\"\n }\n },\n \"schemas\": {\n \"QueueStatus\": {\n \"type\": \"object\",\n \"properties\": {\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\"IN_QUEUE\", \"IN_PROGRESS\", \"COMPLETED\"]\n },\n \"request_id\": { \"type\": \"string\", \"description\": \"The request id.\" },\n \"response_url\": {\n \"type\": \"string\",\n \"description\": \"The response url.\"\n },\n \"status_url\": { \"type\": \"string\", \"description\": \"The status url.\" },\n \"cancel_url\": { \"type\": \"string\", \"description\": \"The cancel url.\" },\n \"logs\": {\n \"type\": \"object\",\n \"description\": \"The logs.\",\n \"additionalProperties\": true\n },\n \"metrics\": {\n \"type\": \"object\",\n \"description\": \"The metrics.\",\n \"additionalProperties\": true\n },\n \"queue_position\": {\n \"type\": \"integer\",\n \"description\": \"The queue position.\"\n }\n },\n \"required\": [\"status\", \"request_id\"]\n },\n \"RecraftV3Input\": {\n \"title\": \"TextToImageInput\",\n \"type\": \"object\",\n \"properties\": {\n \"prompt\": {\n \"title\": \"Prompt\",\n \"type\": \"string\",\n \"x-imgly-builder\": {\n \"component\": \"TextArea\"\n }\n },\n \"image_size\": {\n \"anyOf\": [\n {\n \"enum\": [\n \"square_hd\",\n \"square\",\n \"portrait_4_3\",\n \"portrait_16_9\",\n \"landscape_4_3\",\n \"landscape_16_9\"\n ],\n \"type\": \"string\"\n },\n { \"$ref\": \"#/components/schemas/ImageSize\" }\n ],\n \"title\": \"Format\",\n \"default\": \"square_hd\",\n \"x-imgly-enum-labels\": {\n \"ImageSize\": \"Custom\",\n \"square_hd\": \"Square HD\",\n \"square\": \"Square\",\n \"portrait_4_3\": \"Portrait 4:3\",\n \"portrait_16_9\": \"Portrait 16:9\",\n \"landscape_4_3\": \"Landscape 4:3\",\n \"landscape_16_9\": \"Landscape 16:9\"\n },\n \"x-imgly-enum-icons\": {\n \"square\": \"@imgly/plugin/formats/ratio1by1\",\n \"square_hd\": \"@imgly/plugin/formats/ratio1by1\",\n \"portrait_4_3\": \"@imgly/plugin/formats/ratio3by4\",\n \"portrait_16_9\": \"@imgly/plugin/formats/ratio9by16\",\n \"landscape_4_3\": \"@imgly/plugin/formats/ratio4by3\",\n \"landscape_16_9\": \"@imgly/plugin/formats/ratio16by9\",\n \"ImageSize\": \"@imgly/plugin/formats/ratioFree\"\n }\n },\n \"style\": {\n \"enum\": [\n \"any\",\n \"realistic_image\",\n \"digital_illustration\",\n \"vector_illustration\",\n \"realistic_image/b_and_w\",\n \"realistic_image/hard_flash\",\n \"realistic_image/hdr\",\n \"realistic_image/natural_light\",\n \"realistic_image/studio_portrait\",\n \"realistic_image/enterprise\",\n \"realistic_image/motion_blur\",\n \"realistic_image/evening_light\",\n \"realistic_image/faded_nostalgia\",\n \"realistic_image/forest_life\",\n \"realistic_image/mystic_naturalism\",\n \"realistic_image/natural_tones\",\n \"realistic_image/organic_calm\",\n \"realistic_image/real_life_glow\",\n \"realistic_image/retro_realism\",\n \"realistic_image/retro_snapshot\",\n \"realistic_image/urban_drama\",\n \"realistic_image/village_realism\",\n \"realistic_image/warm_folk\",\n \"digital_illustration/pixel_art\",\n \"digital_illustration/hand_drawn\",\n \"digital_illustration/grain\",\n \"digital_illustration/infantile_sketch\",\n \"digital_illustration/2d_art_poster\",\n \"digital_illustration/handmade_3d\",\n \"digital_illustration/hand_drawn_outline\",\n \"digital_illustration/engraving_color\",\n \"digital_illustration/2d_art_poster_2\",\n \"digital_illustration/antiquarian\",\n \"digital_illustration/bold_fantasy\",\n \"digital_illustration/child_book\",\n \"digital_illustration/child_books\",\n \"digital_illustration/cover\",\n \"digital_illustration/crosshatch\",\n \"digital_illustration/digital_engraving\",\n \"digital_illustration/expressionism\",\n \"digital_illustration/freehand_details\",\n \"digital_illustration/grain_20\",\n \"digital_illustration/graphic_intensity\",\n \"digital_illustration/hard_comics\",\n \"digital_illustration/long_shadow\",\n \"digital_illustration/modern_folk\",\n \"digital_illustration/multicolor\",\n \"digital_illustration/neon_calm\",\n \"digital_illustration/noir\",\n \"digital_illustration/nostalgic_pastel\",\n \"digital_illustration/outline_details\",\n \"digital_illustration/pastel_gradient\",\n \"digital_illustration/pastel_sketch\",\n \"digital_illustration/pop_art\",\n \"digital_illustration/pop_renaissance\",\n \"digital_illustration/street_art\",\n \"digital_illustration/tablet_sketch\",\n \"digital_illustration/urban_glow\",\n \"digital_illustration/urban_sketching\",\n \"digital_illustration/vanilla_dreams\",\n \"digital_illustration/young_adult_book\",\n \"digital_illustration/young_adult_book_2\",\n \"vector_illustration/bold_stroke\",\n \"vector_illustration/chemistry\",\n \"vector_illustration/colored_stencil\",\n \"vector_illustration/contour_pop_art\",\n \"vector_illustration/cosmics\",\n \"vector_illustration/cutout\",\n \"vector_illustration/depressive\",\n \"vector_illustration/editorial\",\n \"vector_illustration/emotional_flat\",\n \"vector_illustration/infographical\",\n \"vector_illustration/marker_outline\",\n \"vector_illustration/mosaic\",\n \"vector_illustration/naivector\",\n \"vector_illustration/roundish_flat\",\n \"vector_illustration/segmented_colors\",\n \"vector_illustration/sharp_contrast\",\n \"vector_illustration/thin\",\n \"vector_illustration/vector_photo\",\n \"vector_illustration/vivid_shapes\",\n \"vector_illustration/engraving\",\n \"vector_illustration/line_art\",\n \"vector_illustration/line_circuit\",\n \"vector_illustration/linocut\"\n ],\n \"title\": \"Style\",\n \"type\": \"string\",\n \"description\": \"The style of the generated images. Vector images cost 2X as much.\",\n \"default\": \"realistic_image\"\n },\n \"colors\": {\n \"title\": \"Colors\",\n \"type\": \"array\",\n \"description\": \"An array of preferable colors\",\n \"items\": { \"$ref\": \"#/components/schemas/RGBColor\" },\n \"default\": []\n }\n },\n \"x-fal-order-properties\": [\"prompt\", \"style\", \"image_size\"],\n \"required\": [\"prompt\"]\n },\n \"RecraftV3Output\": {\n \"title\": \"TextToImageOutput\",\n \"type\": \"object\",\n \"properties\": {\n \"images\": {\n \"title\": \"Images\",\n \"type\": \"array\",\n \"items\": { \"$ref\": \"#/components/schemas/File\" }\n }\n },\n \"x-fal-order-properties\": [\"images\"],\n \"required\": [\"images\"]\n },\n \"ImageSize\": {\n \"title\": \"ImageSize\",\n \"type\": \"object\",\n \"properties\": {\n \"height\": {\n \"maximum\": 14142,\n \"type\": \"integer\",\n \"title\": \"Height\",\n \"description\": \"The height of the generated image.\",\n \"exclusiveMinimum\": 0,\n \"default\": 512\n },\n \"width\": {\n \"maximum\": 14142,\n \"type\": \"integer\",\n \"title\": \"Width\",\n \"description\": \"The width of the generated image.\",\n \"exclusiveMinimum\": 0,\n \"default\": 512\n }\n },\n \"x-fal-order-properties\": [\"width\", \"height\"]\n },\n \"RGBColor\": {\n \"title\": \"RGBColor\",\n \"type\": \"object\",\n \"properties\": {\n \"r\": {\n \"minimum\": 0,\n \"maximum\": 255,\n \"type\": \"integer\",\n \"title\": \"R\",\n \"description\": \"Red color value\",\n \"default\": 0\n },\n \"b\": {\n \"minimum\": 0,\n \"maximum\": 255,\n \"type\": \"integer\",\n \"title\": \"B\",\n \"description\": \"Blue color value\",\n \"default\": 0\n },\n \"g\": {\n \"minimum\": 0,\n \"maximum\": 255,\n \"type\": \"integer\",\n \"title\": \"G\",\n \"description\": \"Green color value\",\n \"default\": 0\n }\n },\n \"x-fal-order-properties\": [\"r\", \"g\", \"b\"]\n },\n \"File\": {\n \"title\": \"File\",\n \"type\": \"object\",\n \"properties\": {\n \"file_size\": {\n \"title\": \"File Size\",\n \"type\": \"integer\",\n \"description\": \"The size of the file in bytes.\"\n },\n \"file_name\": {\n \"title\": \"File Name\",\n \"type\": \"string\",\n \"description\": \"The name of the file. It will be auto-generated if not provided.\"\n },\n \"content_type\": {\n \"title\": \"Content Type\",\n \"type\": \"string\",\n \"description\": \"The mime type of the file.\"\n },\n \"url\": {\n \"title\": \"Url\",\n \"type\": \"string\",\n \"description\": \"The URL where the file can be downloaded from.\"\n },\n \"file_data\": {\n \"format\": \"binary\",\n \"title\": \"File Data\",\n \"type\": \"string\",\n \"description\": \"File data\"\n }\n },\n \"x-fal-order-properties\": [\n \"url\",\n \"content_type\",\n \"file_name\",\n \"file_size\",\n \"file_data\"\n ],\n \"required\": [\"url\"]\n }\n }\n },\n \"paths\": {\n \"/fal-ai/recraft-v3/requests/{request_id}/status\": {\n \"get\": {\n \"parameters\": [\n {\n \"name\": \"request_id\",\n \"in\": \"path\",\n \"required\": true,\n \"schema\": { \"type\": \"string\", \"description\": \"Request ID\" }\n },\n {\n \"name\": \"logs\",\n \"in\": \"query\",\n \"required\": false,\n \"schema\": {\n \"type\": \"number\",\n \"description\": \"Whether to include logs (`1`) in the response or not (`0`).\"\n }\n }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"The request status.\",\n \"content\": {\n \"application/json\": {\n \"schema\": { \"$ref\": \"#/components/schemas/QueueStatus\" }\n }\n }\n }\n }\n }\n },\n \"/fal-ai/recraft-v3/requests/{request_id}/cancel\": {\n \"put\": {\n \"parameters\": [\n {\n \"name\": \"request_id\",\n \"in\": \"path\",\n \"required\": true,\n \"schema\": { \"type\": \"string\", \"description\": \"Request ID\" }\n }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"The request was cancelled.\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"success\": {\n \"type\": \"boolean\",\n \"description\": \"Whether the request was cancelled successfully.\"\n }\n }\n }\n }\n }\n }\n }\n }\n },\n \"/fal-ai/recraft-v3\": {\n \"post\": {\n \"requestBody\": {\n \"required\": true,\n \"content\": {\n \"application/json\": {\n \"schema\": { \"$ref\": \"#/components/schemas/RecraftV3Input\" }\n }\n }\n },\n \"responses\": {\n \"200\": {\n \"description\": \"The request status.\",\n \"content\": {\n \"application/json\": {\n \"schema\": { \"$ref\": \"#/components/schemas/QueueStatus\" }\n }\n }\n }\n }\n }\n },\n \"/fal-ai/recraft-v3/requests/{request_id}\": {\n \"get\": {\n \"parameters\": [\n {\n \"name\": \"request_id\",\n \"in\": \"path\",\n \"required\": true,\n \"schema\": { \"type\": \"string\", \"description\": \"Request ID\" }\n }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"Result of the request.\",\n \"content\": {\n \"application/json\": {\n \"schema\": { \"$ref\": \"#/components/schemas/RecraftV3Output\" }\n }\n }\n }\n }\n }\n }\n },\n \"servers\": [{ \"url\": \"https://queue.fal.run\" }],\n \"security\": [{ \"apiKeyAuth\": [] }]\n}\n", "import { RecraftV3Input } from '@fal-ai/client/endpoints';\n\nconst ImageSizeEnumToSize: Record<string, { width: number; height: number }> = {\n square_hd: { width: 1024, height: 1024 },\n square: { width: 512, height: 512 },\n portrait_4_3: { width: 1024, height: 1365 },\n portrait_16_9: { width: 1024, height: 1820 },\n landscape_4_3: { width: 1365, height: 1024 },\n landscape_16_9: { width: 1820, height: 1024 }\n};\n\nexport function getImageDimensions(id: string): {\n width: number;\n height: number;\n} {\n return ImageSizeEnumToSize[id];\n}\n\nexport type StyleId = Extract<RecraftV3Input['style'], string>;\n\n// prettier-ignore\nexport const STYLES_IMAGE: { id: StyleId; label: string }[] = [\n // { id: 'any', label: 'Any' },\n { id: 'realistic_image', label: 'Realistic Image' },\n { id: 'digital_illustration', label: 'Digital Illustration' },\n { id: 'realistic_image/b_and_w', label: 'Black & White' },\n { id: 'realistic_image/hard_flash', label: 'Hard Flash' },\n { id: 'realistic_image/hdr', label: 'HDR' },\n { id: 'realistic_image/natural_light', label: 'Natural Light' },\n { id: 'realistic_image/studio_portrait', label: 'Studio Portrait' },\n { id: 'realistic_image/enterprise', label: 'Enterprise' },\n { id: 'realistic_image/motion_blur', label: 'Motion Blur' },\n { id: 'realistic_image/evening_light', label: 'Evening Light' },\n { id: 'realistic_image/faded_nostalgia', label: 'Faded Nostalgia' },\n { id: 'realistic_image/forest_life', label: 'Forest Life' },\n { id: 'realistic_image/mystic_naturalism', label: 'Mystic Naturalism' },\n { id: 'realistic_image/natural_tones', label: 'Natural Tones' },\n { id: 'realistic_image/organic_calm', label: 'Organic Calm' },\n { id: 'realistic_image/real_life_glow', label: 'Real Life Glow' },\n { id: 'realistic_image/retro_realism', label: 'Retro Realism' },\n { id: 'realistic_image/retro_snapshot', label: 'Retro Snapshot' },\n { id: 'realistic_image/urban_drama', label: 'Urban Drama' },\n { id: 'realistic_image/village_realism', label: 'Village Realism' },\n { id: 'realistic_image/warm_folk', label: 'Warm Folk' },\n { id: 'digital_illustration/pixel_art', label: 'Pixel Art' },\n { id: 'digital_illustration/hand_drawn', label: 'Hand Drawn' },\n { id: 'digital_illustration/grain', label: 'Grain' },\n { id: 'digital_illustration/infantile_sketch', label: 'Infantile Sketch' },\n { id: 'digital_illustration/2d_art_poster', label: '2D Art Poster' },\n { id: 'digital_illustration/handmade_3d', label: 'Handmade 3D' },\n { id: 'digital_illustration/hand_drawn_outline', label: 'Hand Drawn Outline' },\n { id: 'digital_illustration/engraving_color', label: 'Engraving Color' },\n { id: 'digital_illustration/2d_art_poster_2', label: '2D Art Poster 2' },\n { id: 'digital_illustration/antiquarian', label: 'Antiquarian' },\n { id: 'digital_illustration/bold_fantasy', label: 'Bold Fantasy' },\n { id: 'digital_illustration/child_book', label: 'Child Book' },\n { id: 'digital_illustration/child_books', label: 'Child Books' },\n { id: 'digital_illustration/cover', label: 'Cover' },\n { id: 'digital_illustration/crosshatch', label: 'Crosshatch' },\n { id: 'digital_illustration/digital_engraving', label: 'Digital Engraving' },\n { id: 'digital_illustration/expressionism', label: 'Expressionism' },\n { id: 'digital_illustration/freehand_details', label: 'Freehand Details' },\n { id: 'digital_illustration/grain_20', label: 'Grain 20' },\n { id: 'digital_illustration/graphic_intensity', label: 'Graphic Intensity' },\n { id: 'digital_illustration/hard_comics', label: 'Hard Comics' },\n { id: 'digital_illustration/long_shadow', label: 'Long Shadow' },\n { id: 'digital_illustration/modern_folk', label: 'Modern Folk' },\n { id: 'digital_illustration/multicolor', label: 'Multicolor' },\n { id: 'digital_illustration/neon_calm', label: 'Neon Calm' },\n { id: 'digital_illustration/noir', label: 'Noir' },\n { id: 'digital_illustration/nostalgic_pastel', label: 'Nostalgic Pastel' },\n { id: 'digital_illustration/outline_details', label: 'Outline Details' },\n { id: 'digital_illustration/pastel_gradient', label: 'Pastel Gradient' },\n { id: 'digital_illustration/pastel_sketch', label: 'Pastel Sketch' },\n { id: 'digital_illustration/pop_art', label: 'Pop Art' },\n { id: 'digital_illustration/pop_renaissance', label: 'Pop Renaissance' },\n { id: 'digital_illustration/street_art', label: 'Street Art' },\n { id: 'digital_illustration/tablet_sketch', label: 'Tablet Sketch' },\n { id: 'digital_illustration/urban_glow', label: 'Urban Glow' },\n { id: 'digital_illustration/urban_sketching', label: 'Urban Sketching' },\n { id: 'digital_illustration/vanilla_dreams', label: 'Vanilla Dreams' },\n { id: 'digital_illustration/young_adult_book', label: 'Young Adult Book' },\n { id: 'digital_illustration/young_adult_book_2', label: 'Young Adult Book 2' },\n];\n\nexport const STYLE_IMAGE_DEFAULT = STYLES_IMAGE[0];\n\n// prettier-ignore\nexport const STYLES_VECTOR: { id: StyleId; label: string }[] = [\n { id: 'vector_illustration', label: 'Vector Illustration' },\n { id: 'vector_illustration/bold_stroke', label: 'Bold Stroke' },\n { id: 'vector_illustration/chemistry', label: 'Chemistry' },\n { id: 'vector_illustration/colored_stencil', label: 'Colored Stencil' },\n { id: 'vector_illustration/contour_pop_art', label: 'Contour Pop Art' },\n { id: 'vector_illustration/cosmics', label: 'Cosmics' },\n { id: 'vector_illustration/cutout', label: 'Cutout' },\n { id: 'vector_illustration/depressive', label: 'Depressive' },\n { id: 'vector_illustration/editorial', label: 'Editorial' },\n { id: 'vector_illustration/emotional_flat', label: 'Emotional Flat' },\n { id: 'vector_illustration/infographical', label: 'Infographical' },\n { id: 'vector_illustration/marker_outline', label: 'Marker Outline' },\n { id: 'vector_illustration/mosaic', label: 'Mosaic' },\n { id: 'vector_illustration/naivector', label: 'Naive Vector' },\n { id: 'vector_illustration/roundish_flat', label: 'Roundish Flat' },\n { id: 'vector_illustration/segmented_colors', label: 'Segmented Colors' },\n { id: 'vector_illustration/sharp_contrast', label: 'Sharp Contrast' },\n { id: 'vector_illustration/thin', label: 'Thin' },\n { id: 'vector_illustration/vector_photo', label: 'Vector Photo' },\n { id: 'vector_illustration/vivid_shapes', label: 'Vivid Shapes' },\n { id: 'vector_illustration/engraving', label: 'Engraving' },\n { id: 'vector_illustration/line_art', label: 'Line Art' },\n { id: 'vector_illustration/line_circuit', label: 'Line Circuit' },\n { id: 'vector_illustration/linocut', label: 'Linocut' },\n];\n\nexport const STYLE_VECTOR_DEFAULT = STYLES_VECTOR[0];\n\n// prettier-ignore\nconst STYLE_THUMBNAILS: (baseURL: string) => ({ [key in StyleId]?: string }) = (baseURL) => ({\n'realistic_image': `${baseURL}/realistic_image.webp`,\n'digital_illustration': `${baseURL}/digital_illustration.webp`,\n'realistic_image/b_and_w': `${baseURL}/realistic_image_black_&_white.webp`,\n'realistic_image/hard_flash': `${baseURL}/realistic_image_hard_flash.webp`,\n'realistic_image/hdr': `${baseURL}/realistic_image_hdr.webp`,\n'realistic_image/natural_light': `${baseURL}/realistic_image_natural_light.webp`,\n'realistic_image/studio_portrait': `${baseURL}/realistic_image_studio_portrait.webp`,\n'realistic_image/enterprise': `${baseURL}/realistic_image_enterprise.webp`,\n'realistic_image/motion_blur': `${baseURL}/realistic_image_motion_blur.webp`,\n'digital_illustration/pixel_art': `${baseURL}/digital_illustration_pixel_art.webp`,\n'digital_illustration/hand_drawn': `${baseURL}/digital_illustration_hand_drawn.webp`,\n'digital_illustration/grain': `${baseURL}/digital_illustration_grain.webp`,\n'digital_illustration/infantile_sketch': `${baseURL}/digital_illustration_infantile_sketch.webp`,\n'digital_illustration/2d_art_poster': `${baseURL}/digital_illustration_2d_art_poster.webp`,\n'digital_illustration/handmade_3d': `${baseURL}/digital_illustration_handmade_3d.webp`,\n'digital_illustration/hand_drawn_outline': `${baseURL}/digital_illustration_handdrawn_outline.webp`,\n'digital_illustration/engraving_color': `${baseURL}/digital_illustration_engraving_color.webp`,\n'digital_illustration/2d_art_poster_2': `${baseURL}/digital_illustration_2d_artposter_2.webp`,\n'vector_illustration': `${baseURL}/vector_illustration.svg`,\n'vector_illustration/bold_stroke': `${baseURL}/vector_illustration_bold_stroke.svg`,\n'vector_illustration/chemistry': `${baseURL}/vector_illustration_chemistry.svg`,\n'vector_illustration/colored_stencil': `${baseURL}/vector_illustration_colored_stencil.svg`,\n'vector_illustration/contour_pop_art': `${baseURL}/vector_illustration_contour_pop_art.svg`,\n'vector_illustration/cosmics': `${baseURL}/vector_illustration_cosmics.svg`,\n'vector_illustration/cutout': `${baseURL}/vector_illustration_cutout.svg`,\n'vector_illustration/depressive': `${baseURL}/vector_illustration_depressive.svg`,\n'vector_illustration/editorial': `${baseURL}/vector_illustration_editorial.svg`,\n'vector_illustration/emotional_flat': `${baseURL}/vector_illustration_emotional_flat.svg`,\n'vector_illustration/infographical': `${baseURL}/vector_illustration_infographical.svg`,\n'vector_illustration/marker_outline': `${baseURL}/vector_illustration_marker_outline.svg`,\n'vector_illustration/mosaic': `${baseURL}/vector_illustration_mosaic.svg`,\n'vector_illustration/naivector': `${baseURL}/vector_illustration_naivector.svg`,\n'vector_illustration/roundish_flat': `${baseURL}/vector_illustration_roundish_flat.svg`,\n'vector_illustration/segmented_colors': `${baseURL}/vector_illustration_segmented_colors.svg`,\n'vector_illustration/sharp_contrast': `${baseURL}/vector_illustration_sharp_contrast.svg`,\n'vector_illustration/thin': `${baseURL}/vector_illustration_thin.svg`,\n'vector_illustration/vector_photo': `${baseURL}/vector_illustration_vector_photo.svg`,\n'vector_illustration/vivid_shapes': `${baseURL}/vector_illustration_vivid_shapes.svg`,\n'vector_illustration/engraving': `${baseURL}/vector_illustration_engraving.svg`,\n'vector_illustration/line_art': `${baseURL}/vector_illustration_line_art.svg`,\n'vector_illustration/line_circuit': `${baseURL}/vector_illustration_line_circuit.svg`,\n'vector_illustration/linocut': `${baseURL}/vector_illustration_linocut.svg`,\n'realistic_image/evening_light': `${baseURL}/realistic_image_evening_light.webp`,\n'realistic_image/faded_nostalgia': `${baseURL}/realistic_image_faded_nostalgia.webp`,\n'realistic_image/forest_life': `${baseURL}/realistic_image_forest_life.webp`,\n'realistic_image/mystic_naturalism': `${baseURL}/realistic_image_mystic_naturalism.webp`,\n'realistic_image/natural_tones': `${baseURL}/realistic_image_natural_tones.webp`,\n'realistic_image/organic_calm': `${baseURL}/realistic_image_organic_calm.webp`,\n'realistic_image/real_life_glow': `${baseURL}/realistic_image_real_life_glow.webp`,\n'realistic_image/retro_realism': `${baseURL}/realistic_image_retro_realism.webp`,\n'realistic_image/retro_snapshot': `${baseURL}/realistic_image_retro_snapshot.webp`,\n'realistic_image/urban_drama': `${baseURL}/realistic_image_urban_drama.webp`,\n'realistic_image/village_realism': `${baseURL}/realistic_image_village_realism.webp`,\n'realistic_image/warm_folk': `${baseURL}/realistic_image_warm_folk.webp`,\n'digital_illustration/antiquarian': `${baseURL}/digital_illustration_antiquarian.webp`,\n'digital_illustration/bold_fantasy': `${baseURL}/digital_illustration_bold_fantasy.webp`,\n'digital_illustration/child_book': `${baseURL}/digital_illustration_child_book.webp`,\n'digital_illustration/child_books': `${baseURL}/digital_illustration_child_books.webp`,\n'digital_illustration/cover': `${baseURL}/digital_illustration_cover.webp`,\n'digital_illustration/crosshatch': `${baseURL}/digital_illustration_crosshatch.webp`,\n'digital_illustration/digital_engraving': `${baseURL}/digital_illustration_digital_engraving.webp`,\n'digital_illustration/expressionism': `${baseURL}/digital_illustration_expressionism.webp`,\n'digital_illustration/freehand_details': `${baseURL}/digital_illustration_freehand_details.webp`,\n'digital_illustration/grain_20': `${baseURL}/digital_illustration_grain_20.webp`,\n'digital_illustration/graphic_intensity': `${baseURL}/digital_illustration_graphic_intensity.webp`,\n'digital_illustration/hard_comics': `${baseURL}/digital_illustration_hard_comics.webp`,\n'digital_illustration/long_shadow': `${baseURL}/digital_illustration_long_shadow.webp`,\n'digital_illustration/modern_folk': `${baseURL}/digital_illustration_modern_folk.webp`,\n'digital_illustration/multicolor': `${baseURL}/digital_illustration_multicolor.webp`,\n'digital_illustration/neon_calm': `${baseURL}/digital_illustration_neon_calm.webp`,\n'digital_illustration/noir': `${baseURL}/digital_illustration_noir.webp`,\n'digital_illustration/nostalgic_pastel': `${baseURL}/digital_illustration_nostalgic_pastel.webp`,\n'digital_illustration/outline_details': `${baseURL}/digital_illustration_outline_details.webp`,\n'digital_illustration/pastel_gradient': `${baseURL}/digital_illustration_pastel_gradient.webp`,\n'digital_illustration/pastel_sketch': `${baseURL}/digital_illustration_pastel_sketch.webp`,\n'digital_illustration/pop_art': `${baseURL}/digital_illustration_pop_art.webp`,\n'digital_illustration/pop_renaissance': `${baseURL}/digital_illustration_pop_renaissance.webp`,\n'digital_illustration/street_art': `${baseURL}/digital_illustration_street_art.webp`,\n'digital_illustration/tablet_sketch': `${baseURL}/digital_illustration_tablet_sketch.webp`,\n'digital_illustration/urban_glow': `${baseURL}/digital_illustration_urban_glow.webp`,\n'digital_illustration/urban_sketching': `${baseURL}/digital_illustration_urban_sketching.webp`,\n'digital_illustration/vanilla_dreams': `${baseURL}/digital_illustration_vanilla_dreams.webp`,\n'digital_illustration/young_adult_book': `${baseURL}/digital_illustration_young_adult_book.webp`,\n'digital_illustration/young_adult_book_2': `${baseURL}/digital_illustration_young_adult_book_2.webp`,\n})\n\nexport function getStyleThumbnail(\n id: StyleId,\n baseURL: string\n): string | undefined {\n return STYLE_THUMBNAILS(`${baseURL}thumbnails/`)[id];\n}\n", "import { type OpenAPIV3 } from 'openapi-types';\nimport CreativeEditorSDK, { CreativeEngine } from '@cesdk/cesdk-js';\nimport {\n ImageOutput,\n RenderCustomProperty,\n GetBlockInput,\n CommonProperties,\n Provider,\n QuickAction,\n loggingMiddleware,\n Middleware\n} from '@imgly/plugin-ai-generation-web';\nimport { fal } from '@fal-ai/client';\nimport { isCustomImageSize, uploadImageInputToFalIfNeeded } from './utils';\nimport { getImageDimensions } from './RecraftV3.constants';\n\ntype ImageProviderConfiguration = {\n proxyUrl: string;\n debug?: boolean;\n};\n\n/**\n * Creates a base provider from schema. This should work out of the box\n * but may be rough around the edges and should/can be further customized.\n */\nfunction createImageProvider<I extends Record<string, any>>(\n options: {\n modelKey: string;\n name?: string;\n schema: OpenAPIV3.Document;\n inputReference: string;\n useFlow?: 'placeholder' | 'generation-only';\n initialize?: (context: {\n cesdk?: CreativeEditorSDK;\n engine: CreativeEngine;\n }) => void;\n\n renderCustomProperty?: RenderCustomProperty;\n\n quickActions?: QuickAction<I, ImageOutput>[];\n getBlockInput?: GetBlockInput<'image', I>;\n getImageSize?: (input: I) => { width: number; height: number };\n\n middleware?: Middleware<I, ImageOutput>[];\n\n cesdk?: CreativeEditorSDK;\n },\n config: ImageProviderConfiguration\n): Provider<'image', I, { kind: 'image'; url: string }> {\n const middleware = options.middleware ?? [];\n if (config.debug) {\n middleware.unshift(loggingMiddleware<I, ImageOutput>());\n }\n\n const provider: Provider<'image', I, ImageOutput> = {\n id: options.modelKey,\n kind: 'image',\n name: options.name,\n initialize: async (context) => {\n fal.config({\n proxyUrl: config.proxyUrl\n });\n\n options.initialize?.(context);\n },\n input: {\n quickActions: {\n actions: options.quickActions ?? []\n },\n panel: {\n type: 'schema',\n document: options.schema,\n inputReference: options.inputReference,\n includeHistoryLibrary: true,\n orderExtensionKeyword: 'x-fal-order-properties',\n renderCustomProperty: {\n ...(options.cesdk != null\n ? CommonProperties.ImageUrl(options.modelKey, {\n cesdk: options.cesdk\n })\n : {}),\n ...options.renderCustomProperty\n },\n getBlockInput: (input) => {\n if (options.getBlockInput != null)\n return options.getBlockInput(input);\n if (options.getImageSize != null) {\n const { width, height } = options.getImageSize(input);\n return Promise.resolve({\n image: {\n width,\n height\n }\n });\n }\n if (input.image_size != null && isCustomImageSize(input.image_size)) {\n return Promise.resolve({\n image: {\n width: input.image_size.width ?? 512,\n height: input.image_size.height ?? 512\n }\n });\n }\n\n if (\n input.image_size != null &&\n typeof input.image_size === 'string'\n ) {\n const imageDimension = getImageDimensions(input.image_size);\n return Promise.resolve({\n image: imageDimension\n });\n }\n\n throw new Error('getBlockInput or getImageSize must be provided');\n },\n userFlow: options.useFlow ?? 'placeholder'\n }\n },\n output: {\n abortable: true,\n middleware,\n history: '@imgly/indexedDB',\n generate: async (\n input: I,\n { abortSignal }: { abortSignal?: AbortSignal }\n ) => {\n const image_url = await uploadImageInputToFalIfNeeded(\n input.image_url,\n options.cesdk\n );\n\n const response = await fal.subscribe(options.modelKey, {\n abortSignal,\n input: image_url != null ? { ...input, image_url } : input,\n logs: true\n });\n\n const images = response?.data?.images;\n if (images != null && Array.isArray(images)) {\n const image = images[0];\n const url: string = image?.url;\n if (url != null)\n return {\n kind: 'image',\n url\n };\n } else {\n const image = response?.data?.image;\n if (image != null) {\n const url = image?.url;\n if (url != null)\n return {\n kind: 'image',\n url\n };\n }\n }\n\n // eslint-disable-next-line no-console\n console.error(\n 'Cannot extract generated image from response:',\n response\n );\n throw new Error('Cannot find generated image');\n }\n }\n };\n\n if (config.debug)\n // eslint-disable-next-line no-console\n console.log('Created Provider:', provider);\n\n return provider;\n}\n\nexport default createImageProvider;\n", "import { fal } from '@fal-ai/client';\nimport { mimeTypeToExtension } from '@imgly/plugin-utils';\nimport CreativeEditorSDK from '@cesdk/cesdk-js';\n\ntype CustomImageSize = {\n width: number;\n height: number;\n};\n\nexport function isCustomImageSize(\n imageSize: any\n): imageSize is CustomImageSize {\n return (\n imageSize != null &&\n typeof imageSize !== 'string' &&\n 'width' in imageSize &&\n 'height' in imageSize\n );\n}\n\nexport async function uploadImageInputToFalIfNeeded(\n imageUrl?: string,\n cesdk?: CreativeEditorSDK\n): Promise<string | undefined> {\n if (imageUrl == null) return undefined;\n if (imageUrl.startsWith('blob:')) {\n const mimeType =\n cesdk != null\n ? await cesdk.engine.editor.getMimeType(imageUrl)\n : 'image/png';\n const imageUrlResponse = await fetch(imageUrl);\n const imageUrlBlob = await imageUrlResponse.blob();\n const imageUrlFile = new File(\n [imageUrlBlob],\n `image.${mimeTypeToExtension(mimeType)}`,\n {\n type: mimeType\n }\n );\n return fal.storage.upload(imageUrlFile);\n }\n if (cesdk != null && imageUrl.startsWith('buffer:')) {\n const mimeType = await cesdk.engine.editor.getMimeType(imageUrl);\n const length = cesdk.engine.editor.getBufferLength(imageUrl);\n const data = cesdk.engine.editor.getBufferData(imageUrl, 0, length);\n const imageUrlFile = new File(\n [data],\n `image.${mimeTypeToExtension(mimeType)}`,\n {\n type: mimeType\n }\n );\n return fal.storage.upload(imageUrlFile);\n }\n\n return imageUrl;\n}\n", "import { Icons, CustomAssetSource } from '@imgly/plugin-utils';\nimport {\n Middleware,\n type Provider,\n getPanelId\n} from '@imgly/plugin-ai-generation-web';\nimport { type RecraftV3Input } from '@fal-ai/client/endpoints';\nimport RecraftV3Schema from './RecraftV3.json';\nimport CreativeEditorSDK, { AssetResult } from '@cesdk/cesdk-js';\nimport {\n STYLES_IMAGE,\n STYLES_VECTOR,\n getImageDimensions,\n getStyleThumbnail\n} from './RecraftV3.constants';\nimport createImageProvider from './createImageProvider';\nimport { isCustomImageSize } from './utils';\n\ntype RecraftV3Output = {\n kind: 'image';\n url: string;\n};\n\nexport type StyleId = Extract<RecraftV3Input['style'], string>;\n\ntype GenerationType = 'image' | 'vector';\n\ntype StyleSelectionPayload = {\n onSelect: (asset: AssetResult) => Promise<void>;\n generationType: GenerationType;\n};\n\ntype ProviderConfiguration = {\n proxyUrl: string;\n debug?: boolean;\n middleware?: Middleware<RecraftV3Input, RecraftV3Output>[];\n\n /**\n * Base URL used for the UI assets used in the plugin.\n *\n * By default, we load the assets from the IMG.LY CDN You can copy the assets.\n * from the `/assets` folder to your own server and set the base URL to your server.\n */\n baseURL?: string;\n};\n\nlet imageStyleAssetSource: CustomAssetSource;\nlet vectorStyleAssetSource: CustomAssetSource;\n\nexport function RecraftV3(\n config: ProviderConfiguration\n): (context: {\n cesdk: CreativeEditorSDK;\n}) => Promise<Provider<'image', RecraftV3Input, RecraftV3Output>> {\n return async ({ cesdk }: { cesdk: CreativeEditorSDK }) => {\n return getProvider(cesdk, config);\n };\n}\n\nfunction getProvider(\n cesdk: CreativeEditorSDK,\n config: ProviderConfiguration\n): Provider<'image', RecraftV3Input, RecraftV3Output> {\n const modelKey = 'fal-ai/recraft-v3';\n const styleImageAssetSourceId = `${modelKey}/styles/image`;\n const styleVectorAssetSourceId = `${modelKey}/styles/vector`;\n const baseURL =\n config.baseURL ??\n 'https://cdn.img.ly/assets/plugins/plugin-ai-image-generation-web/v1/recraft-v3/';\n\n cesdk.ui.addIconSet('@imgly/plugin/formats', Icons.Formats);\n\n imageStyleAssetSource = new CustomAssetSource(\n styleImageAssetSourceId,\n STYLES_IMAGE.map(({ id, label }) => ({\n id,\n label,\n thumbUri: getStyleThumbnail(id, baseURL)\n }))\n );\n vectorStyleAssetSource = new CustomAssetSource(\n styleVectorAssetSourceId,\n STYLES_VECTOR.map(({ id, label }) => ({\n id,\n label,\n thumbUri: getStyleThumbnail(id, baseURL)\n }))\n );\n\n imageStyleAssetSource.setAssetActive('realistic_image');\n vectorStyleAssetSource.setAssetActive('vector_illustration');\n\n cesdk.engine.asset.addSource(imageStyleAssetSource);\n cesdk.engine.asset.addSource(vectorStyleAssetSource);\n\n cesdk.ui.addAssetLibraryEntry({\n id: styleImageAssetSourceId,\n sourceIds: [styleImageAssetSourceId],\n gridItemHeight: 'square',\n gridBackgroundType: 'cover',\n cardLabel: ({ label }) => label,\n cardLabelPosition: () => 'below'\n });\n\n cesdk.ui.addAssetLibraryEntry({\n id: styleVectorAssetSourceId,\n sourceIds: [styleVectorAssetSourceId],\n gridItemHeight: 'square',\n gridBackgroundType: 'cover',\n cardLabel: ({ label }) => label,\n cardLabelPosition: () => 'below'\n });\n\n cesdk.ui.registerPanel<StyleSelectionPayload>(\n `${getPanelId(modelKey)}.styleSelection`,\n ({ builder, payload }) => {\n if (payload == null) return null;\n\n const entries =\n payload.generationType === 'image'\n ? [styleImageAssetSourceId]\n : [styleVectorAssetSourceId];\n\n builder.Library(`${modelKey}.library.style`, {\n entries,\n onSelect: async (asset) => {\n payload.onSelect(asset);\n }\n });\n }\n );\n\n cesdk.i18n.setTranslations({\n en: {\n [`panel.${getPanelId('fal-ai/recraft-v3')}.styleSelection`]:\n 'Style Selection',\n [`${modelKey}.style`]: 'Style',\n [`${modelKey}.style.type`]: 'Type',\n [`${modelKey}.style.type.image`]: 'Image',\n [`${modelKey}.style.type.vector`]: 'Vector'\n }\n });\n\n return createImageProvider(\n {\n modelKey,\n // @ts-ignore\n schema: RecraftV3Schema,\n inputReference: '#/components/schemas/RecraftV3Input',\n middleware: config.middleware ?? [],\n userFlow: 'placeholder',\n renderCustomProperty: {\n style: ({ builder, state }, property) => {\n const typeState = state<GenerationType>('type', 'image');\n\n const styleImageState = state<{\n id: RecraftV3Input['style'];\n label: string;\n }>('style/image', {\n id: 'realistic_image',\n label: 'Realistic Image'\n });\n const styleVectorState = state<{\n id: RecraftV3Input['style'];\n label: string;\n }>('style/vector', {\n id: 'vector_illustration',\n label: 'Vector Illustration'\n });\n\n const styleState =\n typeState.value === 'image' ? styleImageState : styleVectorState;\n\n builder.ButtonGroup(`${property.id}.type`, {\n inputLabel: `${modelKey}.${property.id}.type`,\n children: () => {\n builder.Button(`${property.id}.type.image`, {\n label: `${modelKey}.${property.id}.type.image`,\n isActive: typeState.value === 'image',\n onClick: () => typeState.setValue('image')\n });\n builder.Button(`${property.id}.type.vector`, {\n label: `${modelKey}.${property.id}.type.vector`,\n isActive: typeState.value === 'vector',\n onClick: () => typeState.setValue('vector')\n });\n }\n });\n\n // Show the style library for the selected type.\n builder.Button(`${property.id}`, {\n inputLabel: `${modelKey}.${property.id}`,\n icon: '@imgly/Appearance',\n trailingIcon: '@imgly/ChevronRight',\n label: styleState.value.label,\n labelAlignment: 'left',\n onClick: () => {\n const payload: StyleSelectionPayload = {\n generationType: typeState.value,\n onSelect: async (asset) => {\n if (asset.id === 'back') {\n return;\n }\n\n const newValue: { id: StyleId; label: string } = {\n id: asset.id as StyleId,\n label: asset.label ?? asset.id\n };\n\n if (typeState.value === 'image') {\n imageStyleAssetSource.clearActiveAssets();\n imageStyleAssetSource.setAssetActive(asset.id);\n styleImageState.setValue(newValue);\n } else if (typeState.value === 'vector') {\n vectorStyleAssetSource.clearActiveAssets();\n vectorStyleAssetSource.setAssetActive(asset.id);\n styleVectorState.setValue(newValue);\n }\n\n cesdk.ui.closePanel(`${getPanelId(modelKey)}.styleSelection`);\n }\n };\n\n cesdk.ui.openPanel(`${getPanelId(modelKey)}.styleSelection`, {\n payload\n });\n }\n });\n\n return () => {\n return {\n id: property.id,\n type: 'string',\n value: styleState.value.id ?? 'realistic_image'\n };\n };\n }\n },\n getBlockInput: (input) => {\n if (isCustomImageSize(input.image_size)) {\n return Promise.resolve({\n image: {\n width: input.image_size.width ?? 512,\n height: input.image_size.height ?? 512\n }\n });\n }\n\n const imageDimension = getImageDimensions(\n (input.image_size as string) ?? 'square_hd'\n );\n\n return Promise.resolve({\n image: imageDimension\n });\n }\n },\n config\n );\n}\n\nexport default getProvider;\n", "{\n \"openapi\": \"3.0.0\",\n \"info\": {\n \"title\": \"Fal Queue API\",\n \"version\": \"1.0.0\",\n \"description\": \"The Fal Queue API.\"\n },\n \"components\": {\n \"securitySchemes\": {\n \"apiKeyAuth\": {\n \"type\": \"apiKey\",\n \"in\": \"header\",\n \"name\": \"Authorization\",\n \"description\": \"Fal Key\"\n }\n },\n \"schemas\": {\n \"QueueStatus\": {\n \"type\": \"object\",\n \"properties\": {\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\"IN_QUEUE\", \"IN_PROGRESS\", \"COMPLETED\"]\n },\n \"request_id\": { \"type\": \"string\", \"description\": \"The request id.\" },\n \"response_url\": {\n \"type\": \"string\",\n \"description\": \"The response url.\"\n },\n \"status_url\": { \"type\": \"string\", \"description\": \"The status url.\" },\n \"cancel_url\": { \"type\": \"string\", \"description\": \"The cancel url.\" },\n \"logs\": {\n \"type\": \"object\",\n \"description\": \"The logs.\",\n \"additionalProperties\": true\n },\n \"metrics\": {\n \"type\": \"object\",\n \"description\": \"The metrics.\",\n \"additionalProperties\": true\n },\n \"queue_position\": {\n \"type\": \"integer\",\n \"description\": \"The queue position.\"\n }\n },\n \"required\": [\"status\", \"request_id\"]\n },\n \"GeminiFlashEditInput\": {\n \"title\": \"GeminiImageRequest\",\n \"type\": \"object\",\n \"properties\": {\n \"prompt\": {\n \"maxLength\": 5000,\n \"type\": \"string\",\n \"title\": \"Prompt\",\n \"minLength\": 3,\n \"description\": \"The prompt for image generation or editing\",\n \"x-imgly-builder\": { \"component\": \"TextArea\" }\n },\n \"image_url\": {\n \"title\": \"Image Url\",\n \"type\": \"string\",\n \"description\": \"Optional URL of an input image for editing. If not provided, generates a new image.\"\n }\n },\n \"x-fal-order-properties\": [\"image_url\", \"prompt\"],\n \"required\": [\"prompt\", \"image_url\"]\n },\n \"GeminiFlashEditOutput\": {\n \"title\": \"GeminiImageOutput\",\n \"type\": \"object\",\n \"properties\": {\n \"description\": {\n \"title\": \"Description\",\n \"type\": \"string\",\n \"description\": \"Text description or response from Gemini\"\n },\n \"image\": {\n \"description\": \"The generated or edited image\",\n \"$ref\": \"#/components/schemas/Image\"\n }\n },\n \"x-fal-order-properties\": [\"image\", \"description\"],\n \"required\": [\"image\", \"description\"]\n },\n \"Image\": {\n \"title\": \"Image\",\n \"type\": \"object\",\n \"properties\": {\n \"file_size\": {\n \"anyOf\": [{ \"type\": \"integer\" }, { \"type\": \"null\" }],\n \"title\": \"File Size\",\n \"description\": \"The size of the file in bytes.\"\n },\n \"height\": {\n \"anyOf\": [{ \"type\": \"integer\" }, { \"type\": \"null\" }],\n \"title\": \"Height\",\n \"description\": \"The height of the image in pixels.\"\n },\n \"file_name\": {\n \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }],\n \"title\": \"File Name\",\n \"description\": \"The name of the file. It will be auto-generated if not provided.\"\n },\n \"content_type\": {\n \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }],\n \"title\": \"Content Type\",\n \"description\": \"The mime type of the file.\"\n },\n \"url\": {\n \"title\": \"Url\",\n \"type\": \"string\",\n \"description\": \"The URL where the file can be downloaded from.\"\n },\n \"width\": {\n \"anyOf\": [{ \"type\": \"integer\" }, { \"type\": \"null\" }],\n \"title\": \"Width\",\n \"description\": \"The width of the image in pixels.\"\n }\n },\n \"description\": \"Represents an image file.\",\n \"x-fal-order-properties\": [\n \"url\",\n \"content_type\",\n \"file_name\",\n \"file_size\",\n \"width\",\n \"height\"\n ],\n \"required\": [\"url\"]\n }\n }\n },\n \"paths\": {\n \"/fal-ai/gemini-flash-edit/requests/{request_id}/status\": {\n \"get\": {\n \"parameters\": [\n {\n \"name\": \"request_id\",\n \"in\": \"path\",\n \"required\": true,\n \"schema\": { \"type\": \"string\", \"description\": \"Request ID\" }\n },\n {\n \"name\": \"logs\",\n \"in\": \"query\",\n \"required\": false,\n \"schema\": {\n \"type\": \"number\",\n \"description\": \"Whether to include logs (`1`) in the response or not (`0`).\"\n }\n }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"The request status.\",\n \"content\": {\n \"application/json\": {\n \"schema\": { \"$ref\": \"#/components/schemas/QueueStatus\" }\n }\n }\n }\n }\n }\n },\n \"/fal-ai/gemini-flash-edit/requests/{request_id}/cancel\": {\n \"put\": {\n \"parameters\": [\n {\n \"name\": \"request_id\",\n \"in\": \"path\",\n \"required\": true,\n \"schema\": { \"type\": \"string\", \"description\": \"Request ID\" }\n }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"The request was cancelled.\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"success\": {\n \"type\": \"boolean\",\n \"description\": \"Whether the request was cancelled successfully.\"\n }\n }\n }\n }\n }\n }\n }\n }\n },\n \"/fal-ai/gemini-flash-edit\": {\n \"post\": {\n \"requestBody\": {\n \"required\": true,\n \"content\": {\n \"application/json\": {\n \"schema\": { \"$ref\": \"#/components/schemas/GeminiFlashEditInput\" }\n }\n }\n },\n \"responses\": {\n \"200\": {\n \"description\": \"The request status.\",\n \"content\": {\n \"application/json\": {\n \"schema\": { \"$ref\": \"#/components/schemas/QueueStatus\" }\n }\n }\n }\n }\n }\n },\n \"/fal-ai/gemini-flash-edit/requests/{request_id}\": {\n \"get\": {\n \"parameters\": [\n {\n \"name\": \"request_id\",\n \"in\": \"path\",\n \"required\": true,\n \"schema\": { \"type\": \"string\", \"description\": \"Request ID\" }\n }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"Result of the request.\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"$ref\": \"#/components/schemas/GeminiFlashEditOutput\"\n }\n }\n }\n }\n }\n }\n }\n },\n \"servers\": [{ \"url\": \"https://queue.fal.run\" }],\n \"security\": [{ \"apiKeyAuth\": [] }]\n}\n", "import {\n getQuickActionMenu,\n ImageOutput,\n Middleware,\n QuickAction,\n QuickActionBaseSelect,\n QuickActionSwapImageBackground,\n QuickActionChangeImage,\n QuickActionImageVariant,\n enableQuickActionForImageFill,\n type Provider\n} from '@imgly/plugin-ai-generation-web';\nimport schema from './GeminiFlashEdit.json';\nimport { getImageDimensionsFromURL } from '@imgly/plugin-utils';\nimport CreativeEditorSDK from '@cesdk/cesdk-js';\nimport createImageProvider from './createImageProvider';\n\ntype GeminiFlashEditInput = {\n prompt: string;\n image_url: string;\n};\n\ntype ProviderConfiguration = {\n proxyUrl: string;\n debug?: boolean;\n middleware?: Middleware<GeminiFlashEditInput, ImageOutput>[];\n};\n\nexport function GeminiFlashEdit(\n config: ProviderConfiguration\n): (context: {\n cesdk: CreativeEditorSDK;\n}) => Promise<Provider<'image', GeminiFlashEditInput, ImageOutput>> {\n return async ({ cesdk }: { cesdk: CreativeEditorSDK }) => {\n return getProvider(cesdk, config);\n };\n}\n\nfunction getProvider(\n cesdk: CreativeEditorSDK,\n config: ProviderConfiguration\n): Provider<'image', GeminiFlashEditInput, ImageOutput> {\n const modelKey = 'fal-ai/gemini-flash-edit';\n\n const quickActions = createGeminiFlashEditQuickActions(cesdk);\n const quickActionMenu = getQuickActionMenu(cesdk, 'image');\n\n quickActionMenu.setQuickActionMenuOrder([\n ...quickActionMenu.getQuickActionMenuOrder(),\n 'ly.img.separator',\n 'styleTransfer',\n 'artists',\n 'ly.img.separator',\n 'changeImage',\n 'createVariant'\n ]);\n\n return createImageProvider(\n {\n modelKey,\n name: 'Change Image',\n // @ts-ignore\n schema,\n inputReference: '#/components/schemas/GeminiFlashEditInput',\n cesdk,\n quickActions,\n middleware: config.middleware,\n getBlockInput: async (input) => {\n const { width, height } = await getImageDimensionsFromURL(\n input.image_url,\n cesdk.engine\n );\n return Promise.resolve({\n image: {\n width,\n height\n }\n });\n }\n },\n config\n );\n}\n\nfunction createGeminiFlashEditQuickActions(\n cesdk: CreativeEditorSDK\n): QuickAction<GeminiFlashEditInput, ImageOutput>[] {\n cesdk.i18n.setTranslations({\n en: {\n 'ly.img.ai.quickAction.styleTransfer': 'Change Art Style',\n 'ly.img.ai.quickAction.artists': 'Painted By'\n }\n });\n\n return [\n QuickActionSwapImageBackground<GeminiFlashEditInput, ImageOutput>({\n mapInput: (input) => ({ ...input, image_url: input.uri }),\n cesdk\n }),\n QuickActionChangeImage<GeminiFlashEditInput, ImageOutput>({\n mapInput: (input) => ({ ...input, image_url: input.uri }),\n cesdk\n }),\n QuickActionImageVariant<GeminiFlashEditInput, ImageOutput>({\n onApply: async ({ prompt, uri, duplicatedBlockId }, context) => {\n // Generate a variant for the duplicated block\n return context.generate(\n {\n prompt,\n image_url: uri\n },\n {\n blockIds: [duplicatedBlockId]\n }\n );\n },\n cesdk\n }),\n\n QuickActionBaseSelect<GeminiFlashEditInput, ImageOutput>({\n quickAction: {\n id: 'styleTransfer',\n version: '1',\n enable: enableQuickActionForImageFill(),\n scopes: ['fill/change'],\n confirmation: true,\n lockDuringConfirmation: false\n },\n mapInput: (input) => ({\n prompt: input.item.prompt,\n image_url: input.uri,\n blockId: input.blockId\n }),\n items: [\n {\n id: 'water',\n label: 'Watercolor Painting',\n prompt: 'Convert to watercolor painting.'\n },\n {\n id: 'oil',\n label: 'Oil Painting',\n prompt: 'Render in oil painting style.'\n },\n {\n id: 'charcoal',\n label: 'Charcoal Sketch',\n prompt: 'Transform into a charcoal sketch.'\n },\n {\n id: 'pencil',\n label: 'Pencil Drawing',\n prompt: 'Apply pencil drawing effect.'\n },\n {\n id: 'pastel',\n label: 'Pastel Artwork',\n prompt: 'Make it look like a pastel artwork.'\n },\n {\n id: 'ink',\n label: 'Ink Wash',\n prompt: 'Turn into a classic ink wash painting.'\n },\n {\n id: 'stained-glass',\n label: 'Stained Glass Window',\n prompt: 'Stylize as a stained glass window.'\n },\n {\n id: 'japanse',\n label: 'Japanese Woodblock Print',\n prompt: 'Repaint as a traditional Japanese woodblock print.'\n }\n ],\n cesdk\n }),\n\n QuickActionBaseSelect<GeminiFlashEditInput, ImageOutput>({\n quickAction: {\n id: 'artists',\n version: '1',\n enable: enableQuickActionForImageFill(),\n scopes: ['fill/change'],\n confirmation: true,\n lockDuringConfirmation: false\n },\n mapInput: (input) => ({\n prompt: input.item.prompt,\n image_url: input.uri,\n blockId: input.blockId\n }),\n items: [\n {\n id: 'van-gogh',\n label: 'Van Gogh',\n prompt:\n 'Render this image in the style of Vincent van Gogh, using expressive brushstrokes and swirling motion.'\n },\n {\n id: 'monet',\n label: 'Monet',\n prompt:\n 'Transform this image into the soft, impressionistic style of Claude Monet with natural light and delicate color blending.'\n },\n {\n id: 'picasso',\n label: 'Picasso',\n prompt:\n 'Apply a Pablo Picasso cubist style with abstract geometry and fragmented shapes.'\n },\n {\n id: 'dali',\n label: 'Dal\u00ED',\n prompt:\n \"Make this image resemble Salvador Dal\u00ED's surrealist style, with dreamlike distortion and soft shadows.\"\n },\n {\n id: 'matisse',\n label: 'Matisse',\n prompt:\n \"Stylize the image using Henri Matisse's bold colors and simplified, flowing shapes.\"\n },\n {\n id: 'warhol',\n label: 'Warhol',\n prompt:\n \"Convert this image into Andy Warhol's pop art style with flat colors, repetition, and bold outlines.\"\n },\n {\n id: 'michelangelo',\n label: 'Michelangelo',\n prompt:\n 'Render the image in the classical Renaissance style of Michelangelo, with dramatic anatomy and fresco-like detail.'\n },\n {\n id: 'da-vinci',\n label: 'Da Vinci',\n prompt:\n 'Make this image look like a Leonardo da Vinci painting, using soft transitions, balanced composition, and natural tones.'\n },\n {\n id: 'rembrandt',\n label: 'Rembrandt',\n prompt:\n \"Apply Rembrandt's style with rich contrast, warm tones, and dramatic use of light and shadow.\"\n },\n {\n id: 'mon-drain',\n label: 'Mondrian',\n prompt:\n \"Transform the image into Piet Mondrian's abstract geometric style with grids and primary colors.\"\n },\n {\n id: 'khalo',\n label: 'Frida Kahlo',\n prompt:\n 'Stylize this image in the expressive, symbolic style of Frida Kahlo with vivid colors and surreal framing.'\n },\n {\n id: 'hokusai',\n label: 'Hokusai',\n prompt:\n 'Render the image in the style of Hokusai, using bold outlines, flat color, and traditional Japanese woodblock aesthetics.'\n }\n ],\n cesdk\n })\n ];\n}\n\nexport default getProvider;\n", "import { RecraftV3 } from './RecraftV3';\nimport { GeminiFlashEdit } from './GeminiFlashEdit';\n\nconst FalAi = {\n RecraftV3,\n GeminiFlashEdit\n};\n\nexport default FalAi;\n"],
5
+ "mappings": "o8BAyBAA,EAAA,eAAAC,GAqBAD,EAAA,UAAAE,GArBA,SAAgBD,MACXE,EAAgC,CAEnC,IAAMC,EAAaC,GACjB,OAAOA,GAAe,WAExB,OAAcC,GAAyBC,GAAA,KAAA,OAAA,OAAA,WAAA,CACrC,IAAIC,EAAa,OAAA,OAAA,CAAA,EAAQF,CAAM,EAC/B,QAAWD,KAAcF,EAAY,OAAOC,CAAS,EACnDI,EAAgB,MAAMH,EAAWG,CAAa,EAEhD,OAAOA,CACT,CAAC,CACH,CAMaR,EAAA,kBAAoB,mBAEjC,SAAgBE,GAAUI,EAA0B,CAClD,IAAMG,EAAeC,GACnB,QAAQ,QAAQA,CAAa,EAE/B,OAAI,OAAO,OAAW,IACbD,EAGDC,GACNA,EAAc,SAAWV,EAAA,qBAAqBU,EAC1CD,EAAYC,CAAa,EACzB,QAAQ,QAAO,OAAA,OAAA,OAAA,OAAA,CAAA,EACVA,CAAa,EAAA,CAChB,IAAKJ,EAAO,UACZ,QAAO,OAAA,OAAA,OAAA,OAAA,CAAA,EACDI,EAAc,SAAW,CAAA,CAAG,EAAA,CAChC,CAACV,EAAA,iBAAiB,EAAGU,EAAc,GAAG,CAAA,CAAA,CAAA,CAAA,CAGlD,ubCJAC,EAAA,uBAAAC,GA8BAD,EAAA,sBAAAE,GAtFA,IAAMC,GAAoB,mBAabC,GAAb,cAAoC,KAAK,CAGvC,YAAY,CAAE,QAAAC,EAAS,OAAAC,EAAQ,KAAAC,CAAI,EAAgB,CACjD,MAAMF,CAAO,EACb,KAAK,KAAO,WACZ,KAAK,OAASC,EACd,KAAK,KAAOC,CACd,GARFP,EAAA,SAAAI,GAeA,IAAaI,G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A,sBACA,gCACA,kCACA,6BACA,8BACA,gCACA,kCACA,8BACA,oCACA,gCACA,+BACA,iCACA,gCACA,iCACA,8BACA,kCACA,4BACA,iCACA,kCACA,6BACA,wCACA,qCACA,mCACA,0CACA,uCACA,uCACA,mCACA,oCACA,kCACA,mCACA,6BACA,kCACA,yCACA,qCACA,wCACA,gCACA,yCACA,mCACA,mCACA,mCACA,kCACA,iCACA,4BACA,wCACA,uCACA,uCACA,qCACA,+BACA,uCACA,kCACA,qCACA,kCACA,uCACA,sCACA,wCACA,0CACA,kCACA,gCACA,sCACA,sCACA,8BACA,6BACA,iCACA,gCACA,qCACA,oCACA,qCACA,6BACA,gCACA,oCACA,uCACA,qCACA,2BACA,mCACA,mCACA,gCACA,+BACA,mCACA,6BACF,EACA,MAAS,QACT,KAAQ,SACR,YAAe,oEACf,QAAW,iBACb,EACA,OAAU,CACR,MAAS,SACT,KAAQ,QACR,YAAe,gCACf,MAAS,CAAE,KAAQ,+BAAgC,EACnD,QAAW,CAAC,CACd,CACF,EACA,yBAA0B,CAAC,SAAU,QAAS,YAAY,EAC1D,SAAY,CAAC,QAAQ,CACvB,EACA,gBAAmB,CACjB,MAAS,oBACT,KAAQ,SACR,WAAc,CACZ,OAAU,CACR,MAAS,SACT,KAAQ,QACR,MAAS,CAAE,KAAQ,2BAA4B,CACjD,CACF,EACA,yBAA0B,CAAC,QAAQ,EACnC,SAAY,CAAC,QAAQ,CACvB,EACA,UAAa,CACX,MAAS,YACT,KAAQ,SACR,WAAc,CACZ,OAAU,CACR,QAAW,MACX,KAAQ,UACR,MAAS,SACT,YAAe,qCACf,iBAAoB,EACpB,QAAW,GACb,EACA,MAAS,CACP,QAAW,MACX,KAAQ,UACR,MAAS,QACT,YAAe,oCACf,iBAAoB,EACpB,QAAW,GACb,CACF,EACA,yBAA0B,CAAC,QAAS,QAAQ,CAC9C,EACA,SAAY,CACV,MAAS,WACT,KAAQ,SACR,WAAc,CACZ,EAAK,CACH,QAAW,EACX,QAAW,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,mCACV,EACA,CACE,GAAI,SACJ,MAAO,iBACP,OAAQ,8BACV,EACA,CACE,GAAI,SACJ,MAAO,iBACP,OAAQ,qCACV,EACA,CACE,GAAI,MACJ,MAAO,WACP,OAAQ,wCACV,EACA,CACE,GAAI,gBACJ,MAAO,uBACP,OAAQ,oCACV,EACA,CACE,GAAI,UACJ,MAAO,2BACP,OAAQ,oDACV,CACF,EACA,MAAAT,CACF,CAAC,EAEDoB,GAAyD,CACvD,YAAa,CACX,GAAI,UACJ,QAAS,IACT,OAAQC,GAA8B,EACtC,OAAQ,CAAC,aAAa,EACtB,aAAc,GACd,uBAAwB,EAC1B,EACA,SAAWZ,IAAW,CACpB,OAAQA,EAAM,KAAK,OACnB,UAAWA,EAAM,IACjB,QAASA,EAAM,OACjB,GACA,MAAO,CACL,CACE,GAAI,WACJ,MAAO,WACP,OACE,wGACJ,EACA,CACE,GAAI,QACJ,MAAO,QACP,OACE,2HACJ,EACA,CACE,GAAI,UACJ,MAAO,UACP,OACE,kFACJ,EACA,CACE,GAAI,OACJ,MAAO,UACP,OACE,2GACJ,EACA,CACE,GAAI,UACJ,MAAO,UACP,OACE,qFACJ,EACA,CACE,GAAI,SACJ,MAAO,SACP,OACE,sGACJ,EACA,CACE,GAAI,eACJ,MAAO,eACP,OACE,oHACJ,EACA,CACE,GAAI,WACJ,MAAO,WACP,OACE,0HACJ,EACA,CACE,GAAI,YACJ,MAAO,YACP,OACE,+FACJ,EACA,CACE,GAAI,YACJ,MAAO,WACP,OACE,kGACJ,EACA,CACE,GAAI,QACJ,MAAO,cACP,OACE,4GACJ,EACA,CACE,GAAI,UACJ,MAAO,UACP,OACE,2HACJ,CACF,EACA,MAAAT,CACF,CAAC,CACH,CACF,CC1QA,IAAMsB,GAAQ,CACZ,UAAAC,GACA,gBAAAC,EACF,EAEOC,GAAQH",
6
+ "names": ["exports", "withMiddleware", "withProxy", "middlewares", "isDefined", "middleware", "config", "__awaiter", "currentConfig", "passthrough", "requestConfig", "exports", "defaultResponseHandler", "resultResponseHandler", "REQUEST_ID_HEADER", "ApiError", "message", "status", "body", "ValidationError", "args", "field", "error", "response", "statusText", "contentType", "_a", "ErrorType", "require_package", "__commonJSMin", "exports", "module", "exports", "isBrowser", "getUserAgent", "memoizedUserAgent", "packageInfo", "exports", "resolveDefaultFetch", "createConfig", "getRestApiUrl", "middleware_1", "response_1", "runtime_1", "hasEnvVariables", "credentialsFromEnv", "DEFAULT_CONFIG", "request", "config", "configuration", "_a", "resolveCredentials", "suppressLocalCredentialsWarning", "credentials", "exports", "ensureEndpointIdFormat", "parseEndpointId", "isValidUrl", "throttle", "isReact", "isPlainObject", "id", "appOwner", "appId", "ENDPOINT_NAMESPACES", "parts", "url", "host", "func", "limit", "leading", "lastFunc", "lastRan", "args", "isRunningInReact", "stack", "value", "exports", "dispatchRequest", "buildUrl", "runtime_1", "utils_1", "isCloudflareWorkers", "params", "targetUrl", "input", "config", "options", "credentialsValue", "requestMiddleware", "responseHandler", "fetch", "userAgent", "credentials", "method", "url", "headers", "_b", "_a", "authHeader", "requestHeaders", "customResponseHandler", "requestInit", "__rest", "response", "_c", "id", "path", "queryParams", "appId", "createParser", "onParse", "isFirstChunk", "buffer", "startingPosition", "startingFieldLength", "eventId", "eventName", "data", "reset", "feed", "chunk", "hasBom", "slice", "BOM", "length", "position", "discardTrailingNewline", "lineLength", "fieldLength", "character", "index", "parseEventStreamLine", "lineBuffer", "type", "id", "event", "noValue", "field", "step", "valueLength", "value", "toString", "concat", "includes", "retry", "parseInt", "Number", "isNaN", "every", "charCode", "charCodeAt", "exports", "getTemporaryAuthToken", "config_1", "request_1", "utils_1", "app", "config", "appId", "token", "exports", "createStreamingClient", "eventsource_parser_1", "auth_1", "request_1", "response_1", "CONTENT_TYPE_EVENT_STREAM", "EVENT_STREAM_TIMEOUT", "FalStream", "endpointId", "config", "options", "__awaiter", "input", "method", "connectionMode", "token", "fetch", "parsedUrl", "response", "_a", "_b", "error", "body", "reader", "emitRawChunk", "done", "value", "decoder", "parser", "event", "data", "parsedData", "e", "timeout", "readPartialResponse", "apiError", "type", "listener", "listeners", "reason", "resolve", "reject", "running", "stopAsyncIterator", "__await", "storage", "request_1", "response_1", "streaming_1", "utils_1", "DEFAULT_POLL_INTERVAL", "createQueueClient", "config", "storage", "ref", "endpointId", "options", "webhookUrl", "priority", "runOptions", "__rest", "input", "endpointId_1", "_a", "requestId", "logs", "abortSignal", "appId", "prefix", "connectionMode", "queryParams", "url", "timeout", "timeoutId", "handleCancelError", "status", "data", "doneStatus", "resolve", "reject", "pollingTimeoutId", "pollInterval", "clearScheduledTasks", "poll", "__awaiter", "requestStatus", "error", "exports", "exports", "utf8Count", "utf8EncodeJs", "utf8EncodeTE", "utf8Encode", "utf8DecodeJs", "utf8DecodeTD", "utf8Decode", "str", "strLength", "byteLength", "pos", "value", "extra", "output", "outputOffset", "offset", "sharedTextEncoder", "TEXT_ENCODER_THRESHOLD", "CHUNK_SIZE", "bytes", "inputOffset", "end", "units", "result", "byte1", "byte2", "byte3", "byte4", "unit", "sharedTextDecoder", "TEXT_DECODER_THRESHOLD", "stringBytes", "ExtData", "type", "data", "exports", "DecodeError", "_DecodeError", "message", "proto", "exports", "exports", "setUint64", "setInt64", "getInt64", "getUint64", "view", "offset", "value", "high", "low", "exports", "encodeTimeSpecToTimestamp", "encodeDateToTimeSpec", "encodeTimestampExtension", "decodeTimestampToTimeSpec", "decodeTimestampExtension", "DecodeError_ts_1", "int_ts_1", "TIMESTAMP32_MAX_SEC", "TIMESTAMP64_MAX_SEC", "sec", "nsec", "rv", "secHigh", "secLow", "view", "date", "msec", "nsecInSec", "object", "timeSpec", "data", "nsec30AndSecHigh2", "secLow32", "ExtData_ts_1", "timestamp_ts_1", "ExtensionCodec", "type", "encode", "decode", "index", "object", "context", "i", "encodeExt", "data", "decodeExt", "exports", "exports", "ensureUint8Array", "isArrayBufferLike", "buffer", "utf8_ts_1", "ExtensionCodec_ts_1", "int_ts_1", "typedArrays_ts_1", "exports", "Encoder", "_Encoder", "options", "object", "depth", "sizeToWrite", "requiredSize", "newSize", "newBuffer", "newBytes", "newView", "byteLength", "ext", "size", "bytes", "item", "keys", "count", "key", "value", "data", "values", "exports", "encode", "Encoder_ts_1", "value", "options", "exports", "prettyByte", "byte", "utf8_ts_1", "DEFAULT_MAX_KEY_LENGTH", "DEFAULT_MAX_LENGTH_PER_KEY", "CachedKeyDecoder", "maxKeyLength", "maxLengthPerKey", "i", "byteLength", "bytes", "inputOffset", "records", "FIND_CHUNK", "record", "recordBytes", "j", "value", "cachedValue", "str", "slicedCopyOfBytes", "exports", "prettyByte_ts_1", "ExtensionCodec_ts_1", "int_ts_1", "utf8_ts_1", "typedArrays_ts_1", "CachedKeyDecoder_ts_1", "DecodeError_ts_1", "STATE_ARRAY", "STATE_MAP_KEY", "STATE_MAP_VALUE", "mapKeyConverter", "key", "StackPool", "size", "state", "partialState", "HEAD_BYTE_REQUIRED", "EMPTY_VIEW", "EMPTY_BYTES", "MORE_DATA", "sharedCachedKeyDecoder", "Decoder", "_Decoder", "options", "buffer", "bytes", "remainingData", "newData", "newBuffer", "posToShow", "view", "pos", "object", "stream", "decoded", "e", "headByte", "totalPos", "isArray", "isArrayHeaderRequired", "arrayItemsLeft", "DECODE", "byteLength", "stack", "headerOffset", "offset", "headOffset", "extType", "data", "value", "exports", "exports", "decode", "decodeMulti", "Decoder_ts_1", "buffer", "options", "exports", "isAsyncIterable", "asyncIterableFromStream", "ensureAsyncIterable", "object", "stream", "reader", "done", "value", "streamLike", "exports", "decodeAsync", "decodeArrayStream", "decodeMultiStream", "Decoder_ts_1", "stream_ts_1", "streamLike", "options", "stream", "encode_ts_1", "exports", "decode_ts_1", "decodeAsync_ts_1", "Decoder_ts_1", "DecodeError_ts_1", "Encoder_ts_1", "ExtensionCodec_ts_1", "ExtData_ts_1", "timestamp_ts_1", "require_machine", "__commonJSMin", "exports", "valueEnumerable", "value", "valueEnumerableWritable", "d", "truthy", "empty", "identity", "a", "callBoth", "par", "fn", "self", "args", "callForward", "b", "create", "stack", "fns", "def", "caller", "fnType", "reduceType", "reduce", "action", "ctx", "ev", "guardType", "guard", "filter", "Type", "arr", "makeTransition", "from", "to", "guards", "t", "reducers", "transitionType", "immediateType", "transition", "immediate", "enterImmediate", "machine", "service", "event", "transitionTo", "transitionsToMap", "transitions", "m", "stateType", "state", "immediates", "desc", "invokeFnType", "machine2", "rn", "invokeMachineType", "data", "error", "interpret", "s", "invoke", "createMachine", "current", "states", "contextFn", "fromEvent", "candidates", "context", "original", "newMachine", "send", "eventName", "currentStateName", "onChange", "initialContext", "exports", "createRealtimeClient", "msgpack_1", "robot3_1", "auth_1", "response_1", "runtime_1", "utils_1", "initialState", "hasToken", "context", "noToken", "enqueueMessage", "event", "closeConnection", "sendMessage", "expireToken", "setToken", "connectionEstablished", "connectionStateMachine", "buildRealtimeUrl", "app", "token", "maxBuffering", "queryParams", "DEFAULT_THROTTLE_INTERVAL", "isUnauthorizedError", "message", "WebSocketErrorCodes", "connectionCache", "connectionCallbacks", "reuseInterpreter", "key", "throttleInterval", "onChange", "machine", "noop", "NoOpConnection", "isSuccessfulResult", "data", "isFalErrorResult", "config", "handler", "clientOnly", "connectionKey", "previousState", "getCallbacks", "stateMachine", "send", "enqueuedMessage", "tokenExpirationTimeout", "error", "ws", "onError", "onResult", "result", "buffer", "input", "exports", "createStorageClient", "config_1", "request_1", "utils_1", "getExtensionFromContentType", "contentType", "_", "fileType", "_a", "initiateUpload", "file", "config", "filename", "initiateMultipartUpload", "partUploadRetries", "uploadUrl_1", "chunk_1", "config_2", "uploadUrl", "chunk", "tries", "fetch", "responseHandler", "response", "multipartUpload", "url", "chunkSize", "chunks", "parsedUrl", "responses", "i", "start", "end", "partNumber", "partUploadUrl", "completeUrl", "mpart", "ref", "__awaiter", "input", "item", "promises", "key", "value", "results", "exports", "createFalClient", "config_1", "queue_1", "realtime_1", "request_1", "response_1", "storage_1", "streaming_1", "userConfig", "config", "storage", "queue", "streaming", "realtime", "endpointId_1", "endpointId", "options", "input", "__awaiter", "requestId", "exports", "isQueueStatus", "isCompletedQueueStatus", "obj", "client_1", "client_2", "exports", "middleware_1", "response_1", "__exportStar", "utils_1", "currentInstance", "config", "id", "options", "endpointId", "formats_default", "CustomAssetSource", "id", "assets", "asset", "selectValue", "queryData", "page", "perPage", "locale", "sortActiveFirst", "query", "tags", "groups", "excludeGroups", "sortingOrder", "sortKey", "filteredAssets", "group", "lowerQuery", "label", "assetTags", "tag", "tagArray", "a", "b", "aActive", "bActive", "aValue", "bValue", "total", "startIndex", "endIndex", "resultAssets", "nextPage", "assetId", "assetIds", "existingIndex", "index", "freeGlobal", "freeGlobal_default", "freeSelf", "root", "root_default", "Symbol", "Symbol_default", "objectProto", "hasOwnProperty", "nativeObjectToString", "symToStringTag", "getRawTag", "value", "isOwn", "tag", "unmasked", "result", "getRawTag_default", "objectToString", "objectToString_default", "nullTag", "undefinedTag", "baseGetTag", "baseGetTag_default", "isObjectLike", "isObjectLike_default", "isArray", "isObject", "value", "type", "isObject_default", "asyncTag", "funcTag", "genTag", "proxyTag", "isFunction", "tag", "baseGetTag_default", "isFunction_default", "coreJsData", "root_default", "coreJsData_default", "maskSrcKey", "uid", "isMasked", "func", "isMasked_default", "funcProto", "funcToString", "toSource", "toSource_default", "reRegExpChar", "reIsHostCtor", "objectProto", "hasOwnProperty", "reIsNative", "baseIsNative", "pattern", "baseIsNative_default", "getValue", "object", "key", "getValue_default", "getNative", "getNative_default", "WeakMap", "WeakMap_default", "eq", "value", "other", "eq_default", "MAX_SAFE_INTEGER", "isLength", "isLength_default", "objectProto", "argsTag", "baseIsArguments", "value", "isObjectLike_default", "baseGetTag_default", "baseIsArguments_default", "objectProto", "hasOwnProperty", "propertyIsEnumerable", "isArguments", "freeExports", "freeModule", "moduleExports", "Buffer", "root_default", "nativeIsBuffer", "argsTag", "arrayTag", "boolTag", "dateTag", "errorTag", "funcTag", "mapTag", "numberTag", "objectTag", "regexpTag", "setTag", "stringTag", "weakMapTag", "arrayBufferTag", "dataViewTag", "float32Tag", "float64Tag", "int8Tag", "int16Tag", "int32Tag", "uint8Tag", "uint8ClampedTag", "uint16Tag", "uint32Tag", "typedArrayTags", "baseIsTypedArray", "value", "isObjectLike_default", "isLength_default", "baseGetTag_default", "baseIsTypedArray_default", "baseUnary", "func", "baseUnary_default", "freeExports", "freeModule", "moduleExports", "freeProcess", "freeGlobal_default", "nodeUtil", "types", "nodeUtil_default", "nodeIsTypedArray", "isTypedArray", "objectProto", "hasOwnProperty", "overArg", "func", "transform", "arg", "overArg_default", "nativeKeys", "objectProto", "hasOwnProperty", "nativeCreate", "getNative_default", "nativeCreate_default", "hashClear", "hashClear_default", "hashDelete", "key", "result", "hashDelete_default", "HASH_UNDEFINED", "objectProto", "hasOwnProperty", "hashGet", "data", "hashGet_default", "hashHas", "hashHas_default", "hashSet", "value", "hashSet_default", "Hash", "entries", "index", "length", "entry", "Hash_default", "listCacheClear", "listCacheClear_default", "assocIndexOf", "array", "eq_default", "assocIndexOf_default", "arrayProto", "splice", "listCacheDelete", "lastIndex", "listCacheDelete_default", "listCacheGet", "listCacheGet_default", "listCacheHas", "listCacheHas_default", "listCacheSet", "listCacheSet_default", "ListCache", "ListCache_default", "Map", "root_default", "Map_default", "mapCacheClear", "mapCacheClear_default", "isKeyable", "type", "isKeyable_default", "getMapData", "map", "getMapData_default", "mapCacheDelete", "mapCacheDelete_default", "mapCacheGet", "mapCacheGet_default", "mapCacheHas", "mapCacheHas_default", "mapCacheSet", "size", "mapCacheSet_default", "MapCache", "MapCache_default", "stackClear", "ListCache_default", "stackClear_default", "stackDelete", "key", "data", "result", "stackDelete_default", "stackGet", "stackGet_default", "stackHas", "stackHas_default", "LARGE_ARRAY_SIZE", "stackSet", "value", "pairs", "Map_default", "MapCache_default", "stackSet_default", "Stack", "entries", "objectProto", "propertyIsEnumerable", "DataView", "getNative_default", "root_default", "DataView_default", "Promise", "Promise_default", "Set", "Set_default", "mapTag", "objectTag", "promiseTag", "setTag", "weakMapTag", "dataViewTag", "dataViewCtorString", "toSource_default", "mapCtorString", "Map_default", "promiseCtorString", "setCtorString", "weakMapCtorString", "WeakMap_default", "getTag", "baseGetTag_default", "value", "result", "Ctor", "ctorString", "Uint8Array", "root_default", "HASH_UNDEFINED", "setCacheAdd", "value", "setCacheAdd_default", "setCacheHas", "setCacheHas_default", "SetCache", "values", "index", "length", "MapCache_default", "symbolProto", "Symbol_default", "symbolValueOf", "objectProto", "hasOwnProperty", "objectProto", "hasOwnProperty", "HEX_COLOR_PATTERN", "HEX_SINGLE_CHAR_COMPONENTS_PATTERN", "HEX_DOUBLE_CHAR_COMPONENTS_PATTERN", "mimeTypeToExtension", "mimeType", "bufferURIToObjectURL", "uri", "engine", "mimeType", "length", "data", "blob", "getImageDimensionsFromURL", "url", "engine", "resolvedUrl", "bufferURIToObjectURL", "resolve", "reject", "img", "Icons", "formats_default", "renderImageUrlProperty", "provderId", "options", "cesdk", "propertyKey", "panelIdForImageSelection", "getImageSelectionPanelId", "createPanels", "context", "property", "builder", "global", "payload", "defaultUrl", "stateValue", "assetResult", "providerId", "asset", "uri", "mimeType", "renderImageUrlProperty_default", "AI_PANEL_ID_PREFIX", "getPanelId", "providerId", "AI_PANEL_ID_PREFIX", "loggingMiddleware", "input", "options", "next", "result", "start", "loggingMiddleware_default", "freeGlobal", "freeGlobal_default", "freeSelf", "root", "root_default", "Symbol", "Symbol_default", "objectProto", "hasOwnProperty", "nativeObjectToString", "symToStringTag", "getRawTag", "value", "isOwn", "tag", "unmasked", "result", "getRawTag_default", "objectToString", "objectToString_default", "nullTag", "undefinedTag", "baseGetTag", "baseGetTag_default", "isObjectLike", "isObjectLike_default", "isArray", "isObject", "type", "isObject_default", "asyncTag", "funcTag", "genTag", "proxyTag", "isFunction", "isFunction_default", "coreJsData", "coreJsData_default", "maskSrcKey", "uid", "isMasked", "func", "isMasked_default", "funcProto", "funcToString", "toSource", "toSource_default", "reRegExpChar", "reIsHostCtor", "reIsNative", "baseIsNative", "pattern", "baseIsNative_default", "getValue", "object", "key", "getValue_default", "getNative", "getNative_default", "WeakMap", "WeakMap_default", "eq", "other", "eq_default", "MAX_SAFE_INTEGER", "isLength", "isLength_default", "argsTag", "baseIsArguments", "baseIsArguments_default", "propertyIsEnumerable", "isArguments", "freeExports", "freeModule", "moduleExports", "Buffer", "nativeIsBuffer", "arrayTag", "boolTag", "dateTag", "errorTag", "mapTag", "numberTag", "objectTag", "regexpTag", "setTag", "stringTag", "weakMapTag", "arrayBufferTag", "dataViewTag", "float32Tag", "float64Tag", "int8Tag", "int16Tag", "int32Tag", "uint8Tag", "uint8ClampedTag", "uint16Tag", "uint32Tag", "typedArrayTags", "baseIsTypedArray", "baseIsTypedArray_default", "baseUnary", "baseUnary_default", "freeProcess", "nodeUtil", "types", "nodeUtil_default", "nodeIsTypedArray", "isTypedArray", "overArg", "transform", "arg", "overArg_default", "nativeKeys", "nativeCreate", "nativeCreate_default", "hashClear", "hashClear_default", "hashDelete", "hashDelete_default", "HASH_UNDEFINED", "hashGet", "data", "hashGet_default", "hashHas", "hashHas_default", "hashSet", "hashSet_default", "Hash", "entries", "index", "length", "entry", "Hash_default", "listCacheClear", "listCacheClear_default", "assocIndexOf", "array", "assocIndexOf_default", "arrayProto", "splice", "listCacheDelete", "lastIndex", "listCacheDelete_default", "listCacheGet", "listCacheGet_default", "listCacheHas", "listCacheHas_default", "listCacheSet", "listCacheSet_default", "ListCache", "ListCache_default", "Map", "Map_default", "mapCacheClear", "mapCacheClear_default", "isKeyable", "isKeyable_default", "getMapData", "map", "getMapData_default", "mapCacheDelete", "mapCacheDelete_default", "mapCacheGet", "mapCacheGet_default", "mapCacheHas", "mapCacheHas_default", "mapCacheSet", "size", "mapCacheSet_default", "MapCache", "MapCache_default", "stackClear", "stackClear_default", "stackDelete", "stackDelete_default", "stackGet", "stackGet_default", "stackHas", "stackHas_default", "LARGE_ARRAY_SIZE", "stackSet", "pairs", "stackSet_default", "Stack", "DataView", "DataView_default", "Promise", "Promise_default", "Set", "Set_default", "promiseTag", "dataViewCtorString", "mapCtorString", "promiseCtorString", "setCtorString", "weakMapCtorString", "getTag", "Ctor", "ctorString", "Uint8Array", "setCacheAdd", "setCacheAdd_default", "setCacheHas", "setCacheHas_default", "SetCache", "values", "symbolProto", "symbolValueOf", "HEX_COLOR_PATTERN", "HEX_SINGLE_CHAR_COMPONENTS_PATTERN", "HEX_DOUBLE_CHAR_COMPONENTS_PATTERN", "bufferURIToObjectURL", "uri", "engine", "mimeType", "length", "data", "blob", "getImageUri", "blockId", "engine", "options", "uri", "fillBlock", "sourceSet", "source", "bufferURIToObjectURL", "PLUGIN_ICON_SET_ID", "ICON_SPRITE", "QUICK_ACTION_ORDER_KEY_PREFIX", "QUICK_ACTION_REGISTRY_PREFIX", "getQuickActionMenu", "cesdk", "id", "quickActionIds", "quickAction", "entries", "quickActionId", "getQuickActionMenu_default", "QuickActionBasePrompt", "options", "id", "builder", "toggleExpand", "state", "experimental", "context", "promptState", "prompt", "error", "QuickActionBasePrompt_default", "QuickActionBaseSelect", "options", "id", "builder", "experimental", "context", "item", "generate", "closeMenu", "handleGenerationError", "blockId", "uri", "Qs", "input", "error", "QuickActionBaseSelect_default", "enableImageFill", "engine", "blockIds", "blockId", "fillBlock", "enableImageFill_default", "QuickActionChangeImage", "options", "id", "QuickActionBasePrompt_default", "prompt", "context", "uri", "Qs", "input", "QuickActionChangeImage_default", "QuickActionImageVariant", "type", "duplicated", "childId", "parent", "parentWidth", "parentHeight", "offset", "QuickActionImageVariant_default", "QuickActionChangeImage", "options", "id", "QuickActionBasePrompt_default", "enableImageFill_default", "userPrompt", "context", "blockId", "uri", "Qs", "prompt", "input", "QuickActionSwapImageBackground_default", "CommonProperties", "renderImageUrlProperty_default", "RecraftV3_default", "ImageSizeEnumToSize", "getImageDimensions", "id", "STYLES_IMAGE", "STYLE_IMAGE_DEFAULT", "STYLES_VECTOR", "STYLE_VECTOR_DEFAULT", "STYLE_THUMBNAILS", "baseURL", "getStyleThumbnail", "import_client", "import_client", "isCustomImageSize", "imageSize", "uploadImageInputToFalIfNeeded", "imageUrl", "cesdk", "mimeType", "imageUrlBlob", "imageUrlFile", "gr", "length", "data", "createImageProvider", "options", "config", "middleware", "z", "provider", "context", "Il", "input", "width", "height", "isCustomImageSize", "imageDimension", "getImageDimensions", "abortSignal", "image_url", "uploadImageInputToFalIfNeeded", "response", "images", "url", "image", "createImageProvider_default", "imageStyleAssetSource", "vectorStyleAssetSource", "RecraftV3", "config", "cesdk", "getProvider", "modelKey", "styleImageAssetSourceId", "styleVectorAssetSourceId", "baseURL", "Lu", "ye", "STYLES_IMAGE", "id", "label", "getStyleThumbnail", "STYLES_VECTOR", "_", "builder", "payload", "entries", "asset", "createImageProvider_default", "RecraftV3_default", "state", "property", "typeState", "styleImageState", "styleVectorState", "styleState", "newValue", "input", "isCustomImageSize", "imageDimension", "getImageDimensions", "GeminiFlashEdit_default", "GeminiFlashEdit", "config", "cesdk", "getProvider", "modelKey", "quickActions", "createGeminiFlashEditQuickActions", "quickActionMenu", "De", "createImageProvider_default", "GeminiFlashEdit_default", "input", "width", "height", "ks", "Xo", "zo", "Ho", "prompt", "uri", "duplicatedBlockId", "context", "Fo", "L", "FalAi", "RecraftV3", "GeminiFlashEdit", "fal_ai_default"]
7
7
  }